BitcodeReader.cpp revision 1224c386981f7948f298ed9ad444c40609570f2e
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/MDNode.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>() = Context.getUndef(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 = Context.getConstantArray(UserCA->getType(), &NewOps[0],
292                                        NewOps.size());
293      } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
294        NewC = Context.getConstantStruct(&NewOps[0], NewOps.size(),
295                                         UserCS->getType()->isPacked());
296      } else if (isa<ConstantVector>(UserC)) {
297        NewC = Context.getConstantVector(&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(Context.getOpaqueType());
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 = Context.getIntegerType(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 = Context.getPointerType(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 = Context.getFunctionType(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 = Context.getStructType(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 = Context.getArrayType(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 = Context.getVectorType(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 : Context.getOpaqueType());
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(&ValueName[0], 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(&ValueName[0], ValueName.size());
695      ValueName.clear();
696      break;
697    }
698    }
699  }
700}
701
702/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
703/// the LSB for dense VBR encoding.
704static uint64_t DecodeSignRotatedValue(uint64_t V) {
705  if ((V & 1) == 0)
706    return V >> 1;
707  if (V != 1)
708    return -(V >> 1);
709  // There is no such thing as -0 with integers.  "-0" really means MININT.
710  return 1ULL << 63;
711}
712
713/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
714/// values and aliases that we can.
715bool BitcodeReader::ResolveGlobalAndAliasInits() {
716  std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
717  std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
718
719  GlobalInitWorklist.swap(GlobalInits);
720  AliasInitWorklist.swap(AliasInits);
721
722  while (!GlobalInitWorklist.empty()) {
723    unsigned ValID = GlobalInitWorklist.back().second;
724    if (ValID >= ValueList.size()) {
725      // Not ready to resolve this yet, it requires something later in the file.
726      GlobalInits.push_back(GlobalInitWorklist.back());
727    } else {
728      if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
729        GlobalInitWorklist.back().first->setInitializer(C);
730      else
731        return Error("Global variable initializer is not a constant!");
732    }
733    GlobalInitWorklist.pop_back();
734  }
735
736  while (!AliasInitWorklist.empty()) {
737    unsigned ValID = AliasInitWorklist.back().second;
738    if (ValID >= ValueList.size()) {
739      AliasInits.push_back(AliasInitWorklist.back());
740    } else {
741      if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
742        AliasInitWorklist.back().first->setAliasee(C);
743      else
744        return Error("Alias initializer is not a constant!");
745    }
746    AliasInitWorklist.pop_back();
747  }
748  return false;
749}
750
751static void SetOptimizationFlags(Value *V, uint64_t Flags) {
752  if (OverflowingBinaryOperator *OBO =
753        dyn_cast<OverflowingBinaryOperator>(V)) {
754    if (Flags & (1 << bitc::OBO_NO_SIGNED_OVERFLOW))
755      OBO->setHasNoSignedOverflow(true);
756    if (Flags & (1 << bitc::OBO_NO_UNSIGNED_OVERFLOW))
757      OBO->setHasNoUnsignedOverflow(true);
758  } else if (SDivOperator *Div = dyn_cast<SDivOperator>(V)) {
759    if (Flags & (1 << bitc::SDIV_EXACT))
760      Div->setIsExact(true);
761  }
762}
763
764bool BitcodeReader::ParseConstants() {
765  if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
766    return Error("Malformed block record");
767
768  SmallVector<uint64_t, 64> Record;
769
770  // Read all the records for this value table.
771  const Type *CurTy = Type::Int32Ty;
772  unsigned NextCstNo = ValueList.size();
773  while (1) {
774    unsigned Code = Stream.ReadCode();
775    if (Code == bitc::END_BLOCK)
776      break;
777
778    if (Code == bitc::ENTER_SUBBLOCK) {
779      // No known subblocks, always skip them.
780      Stream.ReadSubBlockID();
781      if (Stream.SkipBlock())
782        return Error("Malformed block record");
783      continue;
784    }
785
786    if (Code == bitc::DEFINE_ABBREV) {
787      Stream.ReadAbbrevRecord();
788      continue;
789    }
790
791    // Read a record.
792    Record.clear();
793    Value *V = 0;
794    unsigned BitCode = Stream.ReadRecord(Code, Record);
795    switch (BitCode) {
796    default:  // Default behavior: unknown constant
797    case bitc::CST_CODE_UNDEF:     // UNDEF
798      V = Context.getUndef(CurTy);
799      break;
800    case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
801      if (Record.empty())
802        return Error("Malformed CST_SETTYPE record");
803      if (Record[0] >= TypeList.size())
804        return Error("Invalid Type ID in CST_SETTYPE record");
805      CurTy = TypeList[Record[0]];
806      continue;  // Skip the ValueList manipulation.
807    case bitc::CST_CODE_NULL:      // NULL
808      V = Context.getNullValue(CurTy);
809      break;
810    case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
811      if (!isa<IntegerType>(CurTy) || Record.empty())
812        return Error("Invalid CST_INTEGER record");
813      V = Context.getConstantInt(CurTy, DecodeSignRotatedValue(Record[0]));
814      break;
815    case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
816      if (!isa<IntegerType>(CurTy) || Record.empty())
817        return Error("Invalid WIDE_INTEGER record");
818
819      unsigned NumWords = Record.size();
820      SmallVector<uint64_t, 8> Words;
821      Words.resize(NumWords);
822      for (unsigned i = 0; i != NumWords; ++i)
823        Words[i] = DecodeSignRotatedValue(Record[i]);
824      V = Context.getConstantInt(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
825                                 NumWords, &Words[0]));
826      break;
827    }
828    case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
829      if (Record.empty())
830        return Error("Invalid FLOAT record");
831      if (CurTy == Type::FloatTy)
832        V = Context.getConstantFP(APFloat(APInt(32, (uint32_t)Record[0])));
833      else if (CurTy == Type::DoubleTy)
834        V = Context.getConstantFP(APFloat(APInt(64, Record[0])));
835      else if (CurTy == Type::X86_FP80Ty) {
836        // Bits are not stored the same way as a normal i80 APInt, compensate.
837        uint64_t Rearrange[2];
838        Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
839        Rearrange[1] = Record[0] >> 48;
840        V = Context.getConstantFP(APFloat(APInt(80, 2, Rearrange)));
841      } else if (CurTy == Type::FP128Ty)
842        V = Context.getConstantFP(APFloat(APInt(128, 2, &Record[0]), true));
843      else if (CurTy == Type::PPC_FP128Ty)
844        V = Context.getConstantFP(APFloat(APInt(128, 2, &Record[0])));
845      else
846        V = Context.getUndef(CurTy);
847      break;
848    }
849
850    case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
851      if (Record.empty())
852        return Error("Invalid CST_AGGREGATE record");
853
854      unsigned Size = Record.size();
855      std::vector<Constant*> Elts;
856
857      if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
858        for (unsigned i = 0; i != Size; ++i)
859          Elts.push_back(ValueList.getConstantFwdRef(Record[i],
860                                                     STy->getElementType(i)));
861        V = Context.getConstantStruct(STy, Elts);
862      } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
863        const Type *EltTy = ATy->getElementType();
864        for (unsigned i = 0; i != Size; ++i)
865          Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
866        V = Context.getConstantArray(ATy, Elts);
867      } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
868        const Type *EltTy = VTy->getElementType();
869        for (unsigned i = 0; i != Size; ++i)
870          Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
871        V = Context.getConstantVector(Elts);
872      } else {
873        V = Context.getUndef(CurTy);
874      }
875      break;
876    }
877    case bitc::CST_CODE_STRING: { // STRING: [values]
878      if (Record.empty())
879        return Error("Invalid CST_AGGREGATE record");
880
881      const ArrayType *ATy = cast<ArrayType>(CurTy);
882      const Type *EltTy = ATy->getElementType();
883
884      unsigned Size = Record.size();
885      std::vector<Constant*> Elts;
886      for (unsigned i = 0; i != Size; ++i)
887        Elts.push_back(Context.getConstantInt(EltTy, Record[i]));
888      V = Context.getConstantArray(ATy, Elts);
889      break;
890    }
891    case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
892      if (Record.empty())
893        return Error("Invalid CST_AGGREGATE record");
894
895      const ArrayType *ATy = cast<ArrayType>(CurTy);
896      const Type *EltTy = ATy->getElementType();
897
898      unsigned Size = Record.size();
899      std::vector<Constant*> Elts;
900      for (unsigned i = 0; i != Size; ++i)
901        Elts.push_back(Context.getConstantInt(EltTy, Record[i]));
902      Elts.push_back(Context.getNullValue(EltTy));
903      V = Context.getConstantArray(ATy, Elts);
904      break;
905    }
906    case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
907      if (Record.size() < 3) return Error("Invalid CE_BINOP record");
908      int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
909      if (Opc < 0) {
910        V = Context.getUndef(CurTy);  // Unknown binop.
911      } else {
912        Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
913        Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
914        V = Context.getConstantExpr(Opc, LHS, RHS);
915      }
916      if (Record.size() >= 4)
917        SetOptimizationFlags(V, Record[3]);
918      break;
919    }
920    case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
921      if (Record.size() < 3) return Error("Invalid CE_CAST record");
922      int Opc = GetDecodedCastOpcode(Record[0]);
923      if (Opc < 0) {
924        V = Context.getUndef(CurTy);  // Unknown cast.
925      } else {
926        const Type *OpTy = getTypeByID(Record[1]);
927        if (!OpTy) return Error("Invalid CE_CAST record");
928        Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
929        V = Context.getConstantExprCast(Opc, Op, CurTy);
930      }
931      break;
932    }
933    case bitc::CST_CODE_CE_GEP: {  // CE_GEP:        [n x operands]
934      if (Record.size() & 1) return Error("Invalid CE_GEP record");
935      SmallVector<Constant*, 16> Elts;
936      for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
937        const Type *ElTy = getTypeByID(Record[i]);
938        if (!ElTy) return Error("Invalid CE_GEP record");
939        Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
940      }
941      V = Context.getConstantExprGetElementPtr(Elts[0], &Elts[1],
942                                               Elts.size()-1);
943      break;
944    }
945    case bitc::CST_CODE_CE_SELECT:  // CE_SELECT: [opval#, opval#, opval#]
946      if (Record.size() < 3) return Error("Invalid CE_SELECT record");
947      V = Context.getConstantExprSelect(ValueList.getConstantFwdRef(Record[0],
948                                                              Type::Int1Ty),
949                                  ValueList.getConstantFwdRef(Record[1],CurTy),
950                                  ValueList.getConstantFwdRef(Record[2],CurTy));
951      break;
952    case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
953      if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
954      const VectorType *OpTy =
955        dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
956      if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
957      Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
958      Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
959      V = Context.getConstantExprExtractElement(Op0, Op1);
960      break;
961    }
962    case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
963      const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
964      if (Record.size() < 3 || OpTy == 0)
965        return Error("Invalid CE_INSERTELT record");
966      Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
967      Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
968                                                  OpTy->getElementType());
969      Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
970      V = Context.getConstantExprInsertElement(Op0, Op1, Op2);
971      break;
972    }
973    case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
974      const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
975      if (Record.size() < 3 || OpTy == 0)
976        return Error("Invalid CE_SHUFFLEVEC record");
977      Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
978      Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
979      const Type *ShufTy = Context.getVectorType(Type::Int32Ty,
980                                                 OpTy->getNumElements());
981      Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
982      V = Context.getConstantExprShuffleVector(Op0, Op1, Op2);
983      break;
984    }
985    case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
986      const VectorType *RTy = dyn_cast<VectorType>(CurTy);
987      const VectorType *OpTy = dyn_cast<VectorType>(getTypeByID(Record[0]));
988      if (Record.size() < 4 || RTy == 0 || OpTy == 0)
989        return Error("Invalid CE_SHUFVEC_EX record");
990      Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
991      Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
992      const Type *ShufTy = Context.getVectorType(Type::Int32Ty,
993                                                 RTy->getNumElements());
994      Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
995      V = Context.getConstantExprShuffleVector(Op0, Op1, Op2);
996      break;
997    }
998    case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
999      if (Record.size() < 4) return Error("Invalid CE_CMP record");
1000      const Type *OpTy = getTypeByID(Record[0]);
1001      if (OpTy == 0) return Error("Invalid CE_CMP record");
1002      Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1003      Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1004
1005      if (OpTy->isFloatingPoint())
1006        V = Context.getConstantExprFCmp(Record[3], Op0, Op1);
1007      else
1008        V = Context.getConstantExprICmp(Record[3], Op0, Op1);
1009      break;
1010    }
1011    case bitc::CST_CODE_INLINEASM: {
1012      if (Record.size() < 2) return Error("Invalid INLINEASM record");
1013      std::string AsmStr, ConstrStr;
1014      bool HasSideEffects = Record[0];
1015      unsigned AsmStrSize = Record[1];
1016      if (2+AsmStrSize >= Record.size())
1017        return Error("Invalid INLINEASM record");
1018      unsigned ConstStrSize = Record[2+AsmStrSize];
1019      if (3+AsmStrSize+ConstStrSize > Record.size())
1020        return Error("Invalid INLINEASM record");
1021
1022      for (unsigned i = 0; i != AsmStrSize; ++i)
1023        AsmStr += (char)Record[2+i];
1024      for (unsigned i = 0; i != ConstStrSize; ++i)
1025        ConstrStr += (char)Record[3+AsmStrSize+i];
1026      const PointerType *PTy = cast<PointerType>(CurTy);
1027      V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1028                         AsmStr, ConstrStr, HasSideEffects);
1029      break;
1030    }
1031    case bitc::CST_CODE_MDSTRING: {
1032      unsigned MDStringLength = Record.size();
1033      SmallString<8> String;
1034      String.resize(MDStringLength);
1035      for (unsigned i = 0; i != MDStringLength; ++i)
1036        String[i] = Record[i];
1037      V = Context.getMDString(String.c_str(), String.c_str() + MDStringLength);
1038      break;
1039    }
1040    case bitc::CST_CODE_MDNODE: {
1041      if (Record.empty() || Record.size() % 2 == 1)
1042        return Error("Invalid CST_MDNODE record");
1043
1044      unsigned Size = Record.size();
1045      SmallVector<Value*, 8> Elts;
1046      for (unsigned i = 0; i != Size; i += 2) {
1047        const Type *Ty = getTypeByID(Record[i], false);
1048        if (Ty != Type::VoidTy)
1049          Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
1050        else
1051          Elts.push_back(NULL);
1052      }
1053      V = Context.getMDNode(&Elts[0], Elts.size());
1054      break;
1055    }
1056    }
1057
1058    ValueList.AssignValue(V, NextCstNo);
1059    ++NextCstNo;
1060  }
1061
1062  if (NextCstNo != ValueList.size())
1063    return Error("Invalid constant reference!");
1064
1065  if (Stream.ReadBlockEnd())
1066    return Error("Error at end of constants block");
1067
1068  // Once all the constants have been read, go through and resolve forward
1069  // references.
1070  ValueList.ResolveConstantForwardRefs();
1071  return false;
1072}
1073
1074/// RememberAndSkipFunctionBody - When we see the block for a function body,
1075/// remember where it is and then skip it.  This lets us lazily deserialize the
1076/// functions.
1077bool BitcodeReader::RememberAndSkipFunctionBody() {
1078  // Get the function we are talking about.
1079  if (FunctionsWithBodies.empty())
1080    return Error("Insufficient function protos");
1081
1082  Function *Fn = FunctionsWithBodies.back();
1083  FunctionsWithBodies.pop_back();
1084
1085  // Save the current stream state.
1086  uint64_t CurBit = Stream.GetCurrentBitNo();
1087  DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
1088
1089  // Set the functions linkage to GhostLinkage so we know it is lazily
1090  // deserialized.
1091  Fn->setLinkage(GlobalValue::GhostLinkage);
1092
1093  // Skip over the function block for now.
1094  if (Stream.SkipBlock())
1095    return Error("Malformed block record");
1096  return false;
1097}
1098
1099bool BitcodeReader::ParseModule(const std::string &ModuleID) {
1100  // Reject multiple MODULE_BLOCK's in a single bitstream.
1101  if (TheModule)
1102    return Error("Multiple MODULE_BLOCKs in same stream");
1103
1104  if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1105    return Error("Malformed block record");
1106
1107  // Otherwise, create the module.
1108  TheModule = new Module(ModuleID, Context);
1109
1110  SmallVector<uint64_t, 64> Record;
1111  std::vector<std::string> SectionTable;
1112  std::vector<std::string> GCTable;
1113
1114  // Read all the records for this module.
1115  while (!Stream.AtEndOfStream()) {
1116    unsigned Code = Stream.ReadCode();
1117    if (Code == bitc::END_BLOCK) {
1118      if (Stream.ReadBlockEnd())
1119        return Error("Error at end of module block");
1120
1121      // Patch the initializers for globals and aliases up.
1122      ResolveGlobalAndAliasInits();
1123      if (!GlobalInits.empty() || !AliasInits.empty())
1124        return Error("Malformed global initializer set");
1125      if (!FunctionsWithBodies.empty())
1126        return Error("Too few function bodies found");
1127
1128      // Look for intrinsic functions which need to be upgraded at some point
1129      for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1130           FI != FE; ++FI) {
1131        Function* NewFn;
1132        if (UpgradeIntrinsicFunction(FI, NewFn))
1133          UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1134      }
1135
1136      // Force deallocation of memory for these vectors to favor the client that
1137      // want lazy deserialization.
1138      std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1139      std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1140      std::vector<Function*>().swap(FunctionsWithBodies);
1141      return false;
1142    }
1143
1144    if (Code == bitc::ENTER_SUBBLOCK) {
1145      switch (Stream.ReadSubBlockID()) {
1146      default:  // Skip unknown content.
1147        if (Stream.SkipBlock())
1148          return Error("Malformed block record");
1149        break;
1150      case bitc::BLOCKINFO_BLOCK_ID:
1151        if (Stream.ReadBlockInfoBlock())
1152          return Error("Malformed BlockInfoBlock");
1153        break;
1154      case bitc::PARAMATTR_BLOCK_ID:
1155        if (ParseAttributeBlock())
1156          return true;
1157        break;
1158      case bitc::TYPE_BLOCK_ID:
1159        if (ParseTypeTable())
1160          return true;
1161        break;
1162      case bitc::TYPE_SYMTAB_BLOCK_ID:
1163        if (ParseTypeSymbolTable())
1164          return true;
1165        break;
1166      case bitc::VALUE_SYMTAB_BLOCK_ID:
1167        if (ParseValueSymbolTable())
1168          return true;
1169        break;
1170      case bitc::CONSTANTS_BLOCK_ID:
1171        if (ParseConstants() || ResolveGlobalAndAliasInits())
1172          return true;
1173        break;
1174      case bitc::FUNCTION_BLOCK_ID:
1175        // If this is the first function body we've seen, reverse the
1176        // FunctionsWithBodies list.
1177        if (!HasReversedFunctionsWithBodies) {
1178          std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1179          HasReversedFunctionsWithBodies = true;
1180        }
1181
1182        if (RememberAndSkipFunctionBody())
1183          return true;
1184        break;
1185      }
1186      continue;
1187    }
1188
1189    if (Code == bitc::DEFINE_ABBREV) {
1190      Stream.ReadAbbrevRecord();
1191      continue;
1192    }
1193
1194    // Read a record.
1195    switch (Stream.ReadRecord(Code, Record)) {
1196    default: break;  // Default behavior, ignore unknown content.
1197    case bitc::MODULE_CODE_VERSION:  // VERSION: [version#]
1198      if (Record.size() < 1)
1199        return Error("Malformed MODULE_CODE_VERSION");
1200      // Only version #0 is supported so far.
1201      if (Record[0] != 0)
1202        return Error("Unknown bitstream version!");
1203      break;
1204    case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
1205      std::string S;
1206      if (ConvertToString(Record, 0, S))
1207        return Error("Invalid MODULE_CODE_TRIPLE record");
1208      TheModule->setTargetTriple(S);
1209      break;
1210    }
1211    case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
1212      std::string S;
1213      if (ConvertToString(Record, 0, S))
1214        return Error("Invalid MODULE_CODE_DATALAYOUT record");
1215      TheModule->setDataLayout(S);
1216      break;
1217    }
1218    case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
1219      std::string S;
1220      if (ConvertToString(Record, 0, S))
1221        return Error("Invalid MODULE_CODE_ASM record");
1222      TheModule->setModuleInlineAsm(S);
1223      break;
1224    }
1225    case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
1226      std::string S;
1227      if (ConvertToString(Record, 0, S))
1228        return Error("Invalid MODULE_CODE_DEPLIB record");
1229      TheModule->addLibrary(S);
1230      break;
1231    }
1232    case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
1233      std::string S;
1234      if (ConvertToString(Record, 0, S))
1235        return Error("Invalid MODULE_CODE_SECTIONNAME record");
1236      SectionTable.push_back(S);
1237      break;
1238    }
1239    case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
1240      std::string S;
1241      if (ConvertToString(Record, 0, S))
1242        return Error("Invalid MODULE_CODE_GCNAME record");
1243      GCTable.push_back(S);
1244      break;
1245    }
1246    // GLOBALVAR: [pointer type, isconst, initid,
1247    //             linkage, alignment, section, visibility, threadlocal]
1248    case bitc::MODULE_CODE_GLOBALVAR: {
1249      if (Record.size() < 6)
1250        return Error("Invalid MODULE_CODE_GLOBALVAR record");
1251      const Type *Ty = getTypeByID(Record[0]);
1252      if (!isa<PointerType>(Ty))
1253        return Error("Global not a pointer type!");
1254      unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1255      Ty = cast<PointerType>(Ty)->getElementType();
1256
1257      bool isConstant = Record[1];
1258      GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1259      unsigned Alignment = (1 << Record[4]) >> 1;
1260      std::string Section;
1261      if (Record[5]) {
1262        if (Record[5]-1 >= SectionTable.size())
1263          return Error("Invalid section ID");
1264        Section = SectionTable[Record[5]-1];
1265      }
1266      GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1267      if (Record.size() > 6)
1268        Visibility = GetDecodedVisibility(Record[6]);
1269      bool isThreadLocal = false;
1270      if (Record.size() > 7)
1271        isThreadLocal = Record[7];
1272
1273      GlobalVariable *NewGV =
1274        new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
1275                           isThreadLocal, AddressSpace);
1276      NewGV->setAlignment(Alignment);
1277      if (!Section.empty())
1278        NewGV->setSection(Section);
1279      NewGV->setVisibility(Visibility);
1280      NewGV->setThreadLocal(isThreadLocal);
1281
1282      ValueList.push_back(NewGV);
1283
1284      // Remember which value to use for the global initializer.
1285      if (unsigned InitID = Record[2])
1286        GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1287      break;
1288    }
1289    // FUNCTION:  [type, callingconv, isproto, linkage, paramattr,
1290    //             alignment, section, visibility, gc]
1291    case bitc::MODULE_CODE_FUNCTION: {
1292      if (Record.size() < 8)
1293        return Error("Invalid MODULE_CODE_FUNCTION record");
1294      const Type *Ty = getTypeByID(Record[0]);
1295      if (!isa<PointerType>(Ty))
1296        return Error("Function not a pointer type!");
1297      const FunctionType *FTy =
1298        dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1299      if (!FTy)
1300        return Error("Function not a pointer to function type!");
1301
1302      Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1303                                        "", TheModule);
1304
1305      Func->setCallingConv(Record[1]);
1306      bool isProto = Record[2];
1307      Func->setLinkage(GetDecodedLinkage(Record[3]));
1308      Func->setAttributes(getAttributes(Record[4]));
1309
1310      Func->setAlignment((1 << Record[5]) >> 1);
1311      if (Record[6]) {
1312        if (Record[6]-1 >= SectionTable.size())
1313          return Error("Invalid section ID");
1314        Func->setSection(SectionTable[Record[6]-1]);
1315      }
1316      Func->setVisibility(GetDecodedVisibility(Record[7]));
1317      if (Record.size() > 8 && Record[8]) {
1318        if (Record[8]-1 > GCTable.size())
1319          return Error("Invalid GC ID");
1320        Func->setGC(GCTable[Record[8]-1].c_str());
1321      }
1322      ValueList.push_back(Func);
1323
1324      // If this is a function with a body, remember the prototype we are
1325      // creating now, so that we can match up the body with them later.
1326      if (!isProto)
1327        FunctionsWithBodies.push_back(Func);
1328      break;
1329    }
1330    // ALIAS: [alias type, aliasee val#, linkage]
1331    // ALIAS: [alias type, aliasee val#, linkage, visibility]
1332    case bitc::MODULE_CODE_ALIAS: {
1333      if (Record.size() < 3)
1334        return Error("Invalid MODULE_ALIAS record");
1335      const Type *Ty = getTypeByID(Record[0]);
1336      if (!isa<PointerType>(Ty))
1337        return Error("Function not a pointer type!");
1338
1339      GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1340                                           "", 0, TheModule);
1341      // Old bitcode files didn't have visibility field.
1342      if (Record.size() > 3)
1343        NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1344      ValueList.push_back(NewGA);
1345      AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1346      break;
1347    }
1348    /// MODULE_CODE_PURGEVALS: [numvals]
1349    case bitc::MODULE_CODE_PURGEVALS:
1350      // Trim down the value list to the specified size.
1351      if (Record.size() < 1 || Record[0] > ValueList.size())
1352        return Error("Invalid MODULE_PURGEVALS record");
1353      ValueList.shrinkTo(Record[0]);
1354      break;
1355    }
1356    Record.clear();
1357  }
1358
1359  return Error("Premature end of bitstream");
1360}
1361
1362bool BitcodeReader::ParseBitcode() {
1363  TheModule = 0;
1364
1365  if (Buffer->getBufferSize() & 3)
1366    return Error("Bitcode stream should be a multiple of 4 bytes in length");
1367
1368  unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
1369  unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
1370
1371  // If we have a wrapper header, parse it and ignore the non-bc file contents.
1372  // The magic number is 0x0B17C0DE stored in little endian.
1373  if (isBitcodeWrapper(BufPtr, BufEnd))
1374    if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
1375      return Error("Invalid bitcode wrapper header");
1376
1377  StreamFile.init(BufPtr, BufEnd);
1378  Stream.init(StreamFile);
1379
1380  // Sniff for the signature.
1381  if (Stream.Read(8) != 'B' ||
1382      Stream.Read(8) != 'C' ||
1383      Stream.Read(4) != 0x0 ||
1384      Stream.Read(4) != 0xC ||
1385      Stream.Read(4) != 0xE ||
1386      Stream.Read(4) != 0xD)
1387    return Error("Invalid bitcode signature");
1388
1389  // We expect a number of well-defined blocks, though we don't necessarily
1390  // need to understand them all.
1391  while (!Stream.AtEndOfStream()) {
1392    unsigned Code = Stream.ReadCode();
1393
1394    if (Code != bitc::ENTER_SUBBLOCK)
1395      return Error("Invalid record at top-level");
1396
1397    unsigned BlockID = Stream.ReadSubBlockID();
1398
1399    // We only know the MODULE subblock ID.
1400    switch (BlockID) {
1401    case bitc::BLOCKINFO_BLOCK_ID:
1402      if (Stream.ReadBlockInfoBlock())
1403        return Error("Malformed BlockInfoBlock");
1404      break;
1405    case bitc::MODULE_BLOCK_ID:
1406      if (ParseModule(Buffer->getBufferIdentifier()))
1407        return true;
1408      break;
1409    default:
1410      if (Stream.SkipBlock())
1411        return Error("Malformed block record");
1412      break;
1413    }
1414  }
1415
1416  return false;
1417}
1418
1419
1420/// ParseFunctionBody - Lazily parse the specified function body block.
1421bool BitcodeReader::ParseFunctionBody(Function *F) {
1422  if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
1423    return Error("Malformed block record");
1424
1425  unsigned ModuleValueListSize = ValueList.size();
1426
1427  // Add all the function arguments to the value table.
1428  for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1429    ValueList.push_back(I);
1430
1431  unsigned NextValueNo = ValueList.size();
1432  BasicBlock *CurBB = 0;
1433  unsigned CurBBNo = 0;
1434
1435  // Read all the records.
1436  SmallVector<uint64_t, 64> Record;
1437  while (1) {
1438    unsigned Code = Stream.ReadCode();
1439    if (Code == bitc::END_BLOCK) {
1440      if (Stream.ReadBlockEnd())
1441        return Error("Error at end of function block");
1442      break;
1443    }
1444
1445    if (Code == bitc::ENTER_SUBBLOCK) {
1446      switch (Stream.ReadSubBlockID()) {
1447      default:  // Skip unknown content.
1448        if (Stream.SkipBlock())
1449          return Error("Malformed block record");
1450        break;
1451      case bitc::CONSTANTS_BLOCK_ID:
1452        if (ParseConstants()) return true;
1453        NextValueNo = ValueList.size();
1454        break;
1455      case bitc::VALUE_SYMTAB_BLOCK_ID:
1456        if (ParseValueSymbolTable()) return true;
1457        break;
1458      }
1459      continue;
1460    }
1461
1462    if (Code == bitc::DEFINE_ABBREV) {
1463      Stream.ReadAbbrevRecord();
1464      continue;
1465    }
1466
1467    // Read a record.
1468    Record.clear();
1469    Instruction *I = 0;
1470    unsigned BitCode = Stream.ReadRecord(Code, Record);
1471    switch (BitCode) {
1472    default: // Default behavior: reject
1473      return Error("Unknown instruction");
1474    case bitc::FUNC_CODE_DECLAREBLOCKS:     // DECLAREBLOCKS: [nblocks]
1475      if (Record.size() < 1 || Record[0] == 0)
1476        return Error("Invalid DECLAREBLOCKS record");
1477      // Create all the basic blocks for the function.
1478      FunctionBBs.resize(Record[0]);
1479      for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1480        FunctionBBs[i] = BasicBlock::Create("", F);
1481      CurBB = FunctionBBs[0];
1482      continue;
1483
1484    case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
1485      unsigned OpNum = 0;
1486      Value *LHS, *RHS;
1487      if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1488          getValue(Record, OpNum, LHS->getType(), RHS) ||
1489          OpNum+1 > Record.size())
1490        return Error("Invalid BINOP record");
1491
1492      int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
1493      if (Opc == -1) return Error("Invalid BINOP record");
1494      I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
1495      if (OpNum < Record.size())
1496        SetOptimizationFlags(I, Record[3]);
1497      break;
1498    }
1499    case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
1500      unsigned OpNum = 0;
1501      Value *Op;
1502      if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1503          OpNum+2 != Record.size())
1504        return Error("Invalid CAST record");
1505
1506      const Type *ResTy = getTypeByID(Record[OpNum]);
1507      int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
1508      if (Opc == -1 || ResTy == 0)
1509        return Error("Invalid CAST record");
1510      I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
1511      break;
1512    }
1513    case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
1514      unsigned OpNum = 0;
1515      Value *BasePtr;
1516      if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
1517        return Error("Invalid GEP record");
1518
1519      SmallVector<Value*, 16> GEPIdx;
1520      while (OpNum != Record.size()) {
1521        Value *Op;
1522        if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1523          return Error("Invalid GEP record");
1524        GEPIdx.push_back(Op);
1525      }
1526
1527      I = GetElementPtrInst::Create(BasePtr, GEPIdx.begin(), GEPIdx.end());
1528      break;
1529    }
1530
1531    case bitc::FUNC_CODE_INST_EXTRACTVAL: {
1532                                       // EXTRACTVAL: [opty, opval, n x indices]
1533      unsigned OpNum = 0;
1534      Value *Agg;
1535      if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1536        return Error("Invalid EXTRACTVAL record");
1537
1538      SmallVector<unsigned, 4> EXTRACTVALIdx;
1539      for (unsigned RecSize = Record.size();
1540           OpNum != RecSize; ++OpNum) {
1541        uint64_t Index = Record[OpNum];
1542        if ((unsigned)Index != Index)
1543          return Error("Invalid EXTRACTVAL index");
1544        EXTRACTVALIdx.push_back((unsigned)Index);
1545      }
1546
1547      I = ExtractValueInst::Create(Agg,
1548                                   EXTRACTVALIdx.begin(), EXTRACTVALIdx.end());
1549      break;
1550    }
1551
1552    case bitc::FUNC_CODE_INST_INSERTVAL: {
1553                           // INSERTVAL: [opty, opval, opty, opval, n x indices]
1554      unsigned OpNum = 0;
1555      Value *Agg;
1556      if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1557        return Error("Invalid INSERTVAL record");
1558      Value *Val;
1559      if (getValueTypePair(Record, OpNum, NextValueNo, Val))
1560        return Error("Invalid INSERTVAL record");
1561
1562      SmallVector<unsigned, 4> INSERTVALIdx;
1563      for (unsigned RecSize = Record.size();
1564           OpNum != RecSize; ++OpNum) {
1565        uint64_t Index = Record[OpNum];
1566        if ((unsigned)Index != Index)
1567          return Error("Invalid INSERTVAL index");
1568        INSERTVALIdx.push_back((unsigned)Index);
1569      }
1570
1571      I = InsertValueInst::Create(Agg, Val,
1572                                  INSERTVALIdx.begin(), INSERTVALIdx.end());
1573      break;
1574    }
1575
1576    case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
1577      // obsolete form of select
1578      // handles select i1 ... in old bitcode
1579      unsigned OpNum = 0;
1580      Value *TrueVal, *FalseVal, *Cond;
1581      if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1582          getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1583          getValue(Record, OpNum, Type::Int1Ty, Cond))
1584        return Error("Invalid SELECT record");
1585
1586      I = SelectInst::Create(Cond, TrueVal, FalseVal);
1587      break;
1588    }
1589
1590    case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
1591      // new form of select
1592      // handles select i1 or select [N x i1]
1593      unsigned OpNum = 0;
1594      Value *TrueVal, *FalseVal, *Cond;
1595      if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1596          getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1597          getValueTypePair(Record, OpNum, NextValueNo, Cond))
1598        return Error("Invalid SELECT record");
1599
1600      // select condition can be either i1 or [N x i1]
1601      if (const VectorType* vector_type =
1602          dyn_cast<const VectorType>(Cond->getType())) {
1603        // expect <n x i1>
1604        if (vector_type->getElementType() != Type::Int1Ty)
1605          return Error("Invalid SELECT condition type");
1606      } else {
1607        // expect i1
1608        if (Cond->getType() != Type::Int1Ty)
1609          return Error("Invalid SELECT condition type");
1610      }
1611
1612      I = SelectInst::Create(Cond, TrueVal, FalseVal);
1613      break;
1614    }
1615
1616    case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
1617      unsigned OpNum = 0;
1618      Value *Vec, *Idx;
1619      if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1620          getValue(Record, OpNum, Type::Int32Ty, Idx))
1621        return Error("Invalid EXTRACTELT record");
1622      I = new ExtractElementInst(Vec, Idx);
1623      break;
1624    }
1625
1626    case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
1627      unsigned OpNum = 0;
1628      Value *Vec, *Elt, *Idx;
1629      if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1630          getValue(Record, OpNum,
1631                   cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
1632          getValue(Record, OpNum, Type::Int32Ty, Idx))
1633        return Error("Invalid INSERTELT record");
1634      I = InsertElementInst::Create(Vec, Elt, Idx);
1635      break;
1636    }
1637
1638    case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
1639      unsigned OpNum = 0;
1640      Value *Vec1, *Vec2, *Mask;
1641      if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
1642          getValue(Record, OpNum, Vec1->getType(), Vec2))
1643        return Error("Invalid SHUFFLEVEC record");
1644
1645      if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
1646        return Error("Invalid SHUFFLEVEC record");
1647      I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1648      break;
1649    }
1650
1651    case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
1652      // Old form of ICmp/FCmp returning bool
1653      // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
1654      // both legal on vectors but had different behaviour.
1655    case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
1656      // FCmp/ICmp returning bool or vector of bool
1657
1658      unsigned OpNum = 0;
1659      Value *LHS, *RHS;
1660      if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1661          getValue(Record, OpNum, LHS->getType(), RHS) ||
1662          OpNum+1 != Record.size())
1663        return Error("Invalid CMP record");
1664
1665      if (LHS->getType()->isFPOrFPVector())
1666        I = new FCmpInst(Context, (FCmpInst::Predicate)Record[OpNum], LHS, RHS);
1667      else
1668        I = new ICmpInst(Context, (ICmpInst::Predicate)Record[OpNum], LHS, RHS);
1669      break;
1670    }
1671
1672    case bitc::FUNC_CODE_INST_GETRESULT: { // GETRESULT: [ty, val, n]
1673      if (Record.size() != 2)
1674        return Error("Invalid GETRESULT record");
1675      unsigned OpNum = 0;
1676      Value *Op;
1677      getValueTypePair(Record, OpNum, NextValueNo, Op);
1678      unsigned Index = Record[1];
1679      I = ExtractValueInst::Create(Op, Index);
1680      break;
1681    }
1682
1683    case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
1684      {
1685        unsigned Size = Record.size();
1686        if (Size == 0) {
1687          I = ReturnInst::Create();
1688          break;
1689        }
1690
1691        unsigned OpNum = 0;
1692        SmallVector<Value *,4> Vs;
1693        do {
1694          Value *Op = NULL;
1695          if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1696            return Error("Invalid RET record");
1697          Vs.push_back(Op);
1698        } while(OpNum != Record.size());
1699
1700        const Type *ReturnType = F->getReturnType();
1701        if (Vs.size() > 1 ||
1702            (isa<StructType>(ReturnType) &&
1703             (Vs.empty() || Vs[0]->getType() != ReturnType))) {
1704          Value *RV = Context.getUndef(ReturnType);
1705          for (unsigned i = 0, e = Vs.size(); i != e; ++i) {
1706            I = InsertValueInst::Create(RV, Vs[i], i, "mrv");
1707            CurBB->getInstList().push_back(I);
1708            ValueList.AssignValue(I, NextValueNo++);
1709            RV = I;
1710          }
1711          I = ReturnInst::Create(RV);
1712          break;
1713        }
1714
1715        I = ReturnInst::Create(Vs[0]);
1716        break;
1717      }
1718    case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
1719      if (Record.size() != 1 && Record.size() != 3)
1720        return Error("Invalid BR record");
1721      BasicBlock *TrueDest = getBasicBlock(Record[0]);
1722      if (TrueDest == 0)
1723        return Error("Invalid BR record");
1724
1725      if (Record.size() == 1)
1726        I = BranchInst::Create(TrueDest);
1727      else {
1728        BasicBlock *FalseDest = getBasicBlock(Record[1]);
1729        Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
1730        if (FalseDest == 0 || Cond == 0)
1731          return Error("Invalid BR record");
1732        I = BranchInst::Create(TrueDest, FalseDest, Cond);
1733      }
1734      break;
1735    }
1736    case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
1737      if (Record.size() < 3 || (Record.size() & 1) == 0)
1738        return Error("Invalid SWITCH record");
1739      const Type *OpTy = getTypeByID(Record[0]);
1740      Value *Cond = getFnValueByID(Record[1], OpTy);
1741      BasicBlock *Default = getBasicBlock(Record[2]);
1742      if (OpTy == 0 || Cond == 0 || Default == 0)
1743        return Error("Invalid SWITCH record");
1744      unsigned NumCases = (Record.size()-3)/2;
1745      SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
1746      for (unsigned i = 0, e = NumCases; i != e; ++i) {
1747        ConstantInt *CaseVal =
1748          dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1749        BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1750        if (CaseVal == 0 || DestBB == 0) {
1751          delete SI;
1752          return Error("Invalid SWITCH record!");
1753        }
1754        SI->addCase(CaseVal, DestBB);
1755      }
1756      I = SI;
1757      break;
1758    }
1759
1760    case bitc::FUNC_CODE_INST_INVOKE: {
1761      // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
1762      if (Record.size() < 4) return Error("Invalid INVOKE record");
1763      AttrListPtr PAL = getAttributes(Record[0]);
1764      unsigned CCInfo = Record[1];
1765      BasicBlock *NormalBB = getBasicBlock(Record[2]);
1766      BasicBlock *UnwindBB = getBasicBlock(Record[3]);
1767
1768      unsigned OpNum = 4;
1769      Value *Callee;
1770      if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1771        return Error("Invalid INVOKE record");
1772
1773      const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
1774      const FunctionType *FTy = !CalleeTy ? 0 :
1775        dyn_cast<FunctionType>(CalleeTy->getElementType());
1776
1777      // Check that the right number of fixed parameters are here.
1778      if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
1779          Record.size() < OpNum+FTy->getNumParams())
1780        return Error("Invalid INVOKE record");
1781
1782      SmallVector<Value*, 16> Ops;
1783      for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1784        Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1785        if (Ops.back() == 0) return Error("Invalid INVOKE record");
1786      }
1787
1788      if (!FTy->isVarArg()) {
1789        if (Record.size() != OpNum)
1790          return Error("Invalid INVOKE record");
1791      } else {
1792        // Read type/value pairs for varargs params.
1793        while (OpNum != Record.size()) {
1794          Value *Op;
1795          if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1796            return Error("Invalid INVOKE record");
1797          Ops.push_back(Op);
1798        }
1799      }
1800
1801      I = InvokeInst::Create(Callee, NormalBB, UnwindBB,
1802                             Ops.begin(), Ops.end());
1803      cast<InvokeInst>(I)->setCallingConv(CCInfo);
1804      cast<InvokeInst>(I)->setAttributes(PAL);
1805      break;
1806    }
1807    case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1808      I = new UnwindInst();
1809      break;
1810    case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1811      I = new UnreachableInst();
1812      break;
1813    case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
1814      if (Record.size() < 1 || ((Record.size()-1)&1))
1815        return Error("Invalid PHI record");
1816      const Type *Ty = getTypeByID(Record[0]);
1817      if (!Ty) return Error("Invalid PHI record");
1818
1819      PHINode *PN = PHINode::Create(Ty);
1820      PN->reserveOperandSpace((Record.size()-1)/2);
1821
1822      for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
1823        Value *V = getFnValueByID(Record[1+i], Ty);
1824        BasicBlock *BB = getBasicBlock(Record[2+i]);
1825        if (!V || !BB) return Error("Invalid PHI record");
1826        PN->addIncoming(V, BB);
1827      }
1828      I = PN;
1829      break;
1830    }
1831
1832    case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
1833      if (Record.size() < 3)
1834        return Error("Invalid MALLOC record");
1835      const PointerType *Ty =
1836        dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1837      Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1838      unsigned Align = Record[2];
1839      if (!Ty || !Size) return Error("Invalid MALLOC record");
1840      I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1841      break;
1842    }
1843    case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
1844      unsigned OpNum = 0;
1845      Value *Op;
1846      if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1847          OpNum != Record.size())
1848        return Error("Invalid FREE record");
1849      I = new FreeInst(Op);
1850      break;
1851    }
1852    case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
1853      if (Record.size() < 3)
1854        return Error("Invalid ALLOCA record");
1855      const PointerType *Ty =
1856        dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1857      Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1858      unsigned Align = Record[2];
1859      if (!Ty || !Size) return Error("Invalid ALLOCA record");
1860      I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1861      break;
1862    }
1863    case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
1864      unsigned OpNum = 0;
1865      Value *Op;
1866      if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1867          OpNum+2 != Record.size())
1868        return Error("Invalid LOAD record");
1869
1870      I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1871      break;
1872    }
1873    case bitc::FUNC_CODE_INST_STORE2: { // STORE2:[ptrty, ptr, val, align, vol]
1874      unsigned OpNum = 0;
1875      Value *Val, *Ptr;
1876      if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
1877          getValue(Record, OpNum,
1878                    cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
1879          OpNum+2 != Record.size())
1880        return Error("Invalid STORE record");
1881
1882      I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1883      break;
1884    }
1885    case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
1886      // FIXME: Legacy form of store instruction. Should be removed in LLVM 3.0.
1887      unsigned OpNum = 0;
1888      Value *Val, *Ptr;
1889      if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
1890          getValue(Record, OpNum,
1891                   Context.getPointerTypeUnqual(Val->getType()), Ptr)||
1892          OpNum+2 != Record.size())
1893        return Error("Invalid STORE record");
1894
1895      I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1896      break;
1897    }
1898    case bitc::FUNC_CODE_INST_CALL: {
1899      // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
1900      if (Record.size() < 3)
1901        return Error("Invalid CALL record");
1902
1903      AttrListPtr PAL = getAttributes(Record[0]);
1904      unsigned CCInfo = Record[1];
1905
1906      unsigned OpNum = 2;
1907      Value *Callee;
1908      if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1909        return Error("Invalid CALL record");
1910
1911      const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
1912      const FunctionType *FTy = 0;
1913      if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
1914      if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
1915        return Error("Invalid CALL record");
1916
1917      SmallVector<Value*, 16> Args;
1918      // Read the fixed params.
1919      for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1920        if (FTy->getParamType(i)->getTypeID()==Type::LabelTyID)
1921          Args.push_back(getBasicBlock(Record[OpNum]));
1922        else
1923          Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1924        if (Args.back() == 0) return Error("Invalid CALL record");
1925      }
1926
1927      // Read type/value pairs for varargs params.
1928      if (!FTy->isVarArg()) {
1929        if (OpNum != Record.size())
1930          return Error("Invalid CALL record");
1931      } else {
1932        while (OpNum != Record.size()) {
1933          Value *Op;
1934          if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1935            return Error("Invalid CALL record");
1936          Args.push_back(Op);
1937        }
1938      }
1939
1940      I = CallInst::Create(Callee, Args.begin(), Args.end());
1941      cast<CallInst>(I)->setCallingConv(CCInfo>>1);
1942      cast<CallInst>(I)->setTailCall(CCInfo & 1);
1943      cast<CallInst>(I)->setAttributes(PAL);
1944      break;
1945    }
1946    case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
1947      if (Record.size() < 3)
1948        return Error("Invalid VAARG record");
1949      const Type *OpTy = getTypeByID(Record[0]);
1950      Value *Op = getFnValueByID(Record[1], OpTy);
1951      const Type *ResTy = getTypeByID(Record[2]);
1952      if (!OpTy || !Op || !ResTy)
1953        return Error("Invalid VAARG record");
1954      I = new VAArgInst(Op, ResTy);
1955      break;
1956    }
1957    }
1958
1959    // Add instruction to end of current BB.  If there is no current BB, reject
1960    // this file.
1961    if (CurBB == 0) {
1962      delete I;
1963      return Error("Invalid instruction with no BB");
1964    }
1965    CurBB->getInstList().push_back(I);
1966
1967    // If this was a terminator instruction, move to the next block.
1968    if (isa<TerminatorInst>(I)) {
1969      ++CurBBNo;
1970      CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
1971    }
1972
1973    // Non-void values get registered in the value table for future use.
1974    if (I && I->getType() != Type::VoidTy)
1975      ValueList.AssignValue(I, NextValueNo++);
1976  }
1977
1978  // Check the function list for unresolved values.
1979  if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
1980    if (A->getParent() == 0) {
1981      // We found at least one unresolved value.  Nuke them all to avoid leaks.
1982      for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
1983        if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
1984          A->replaceAllUsesWith(Context.getUndef(A->getType()));
1985          delete A;
1986        }
1987      }
1988      return Error("Never resolved value found in function!");
1989    }
1990  }
1991
1992  // Trim the value list down to the size it was before we parsed this function.
1993  ValueList.shrinkTo(ModuleValueListSize);
1994  std::vector<BasicBlock*>().swap(FunctionBBs);
1995
1996  return false;
1997}
1998
1999//===----------------------------------------------------------------------===//
2000// ModuleProvider implementation
2001//===----------------------------------------------------------------------===//
2002
2003
2004bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
2005  // If it already is material, ignore the request.
2006  if (!F->hasNotBeenReadFromBitcode()) return false;
2007
2008  DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
2009    DeferredFunctionInfo.find(F);
2010  assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
2011
2012  // Move the bit stream to the saved position of the deferred function body and
2013  // restore the real linkage type for the function.
2014  Stream.JumpToBit(DFII->second.first);
2015  F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
2016
2017  if (ParseFunctionBody(F)) {
2018    if (ErrInfo) *ErrInfo = ErrorString;
2019    return true;
2020  }
2021
2022  // Upgrade any old intrinsic calls in the function.
2023  for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2024       E = UpgradedIntrinsics.end(); I != E; ++I) {
2025    if (I->first != I->second) {
2026      for (Value::use_iterator UI = I->first->use_begin(),
2027           UE = I->first->use_end(); UI != UE; ) {
2028        if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2029          UpgradeIntrinsicCall(CI, I->second);
2030      }
2031    }
2032  }
2033
2034  return false;
2035}
2036
2037void BitcodeReader::dematerializeFunction(Function *F) {
2038  // If this function isn't materialized, or if it is a proto, this is a noop.
2039  if (F->hasNotBeenReadFromBitcode() || F->isDeclaration())
2040    return;
2041
2042  assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
2043
2044  // Just forget the function body, we can remat it later.
2045  F->deleteBody();
2046  F->setLinkage(GlobalValue::GhostLinkage);
2047}
2048
2049
2050Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
2051  // Iterate over the module, deserializing any functions that are still on
2052  // disk.
2053  for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2054       F != E; ++F)
2055    if (F->hasNotBeenReadFromBitcode() &&
2056        materializeFunction(F, ErrInfo))
2057      return 0;
2058
2059  // Upgrade any intrinsic calls that slipped through (should not happen!) and
2060  // delete the old functions to clean up. We can't do this unless the entire
2061  // module is materialized because there could always be another function body
2062  // with calls to the old function.
2063  for (std::vector<std::pair<Function*, Function*> >::iterator I =
2064       UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2065    if (I->first != I->second) {
2066      for (Value::use_iterator UI = I->first->use_begin(),
2067           UE = I->first->use_end(); UI != UE; ) {
2068        if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2069          UpgradeIntrinsicCall(CI, I->second);
2070      }
2071      if (!I->first->use_empty())
2072        I->first->replaceAllUsesWith(I->second);
2073      I->first->eraseFromParent();
2074    }
2075  }
2076  std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
2077
2078  return TheModule;
2079}
2080
2081
2082/// This method is provided by the parent ModuleProvde class and overriden
2083/// here. It simply releases the module from its provided and frees up our
2084/// state.
2085/// @brief Release our hold on the generated module
2086Module *BitcodeReader::releaseModule(std::string *ErrInfo) {
2087  // Since we're losing control of this Module, we must hand it back complete
2088  Module *M = ModuleProvider::releaseModule(ErrInfo);
2089  FreeState();
2090  return M;
2091}
2092
2093
2094//===----------------------------------------------------------------------===//
2095// External interface
2096//===----------------------------------------------------------------------===//
2097
2098/// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
2099///
2100ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
2101                                               LLVMContext& Context,
2102                                               std::string *ErrMsg) {
2103  BitcodeReader *R = new BitcodeReader(Buffer, Context);
2104  if (R->ParseBitcode()) {
2105    if (ErrMsg)
2106      *ErrMsg = R->getErrorString();
2107
2108    // Don't let the BitcodeReader dtor delete 'Buffer'.
2109    R->releaseMemoryBuffer();
2110    delete R;
2111    return 0;
2112  }
2113  return R;
2114}
2115
2116/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2117/// If an error occurs, return null and fill in *ErrMsg if non-null.
2118Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
2119                               std::string *ErrMsg){
2120  BitcodeReader *R;
2121  R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, Context,
2122                                                           ErrMsg));
2123  if (!R) return 0;
2124
2125  // Read in the entire module.
2126  Module *M = R->materializeModule(ErrMsg);
2127
2128  // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2129  // there was an error.
2130  R->releaseMemoryBuffer();
2131
2132  // If there was no error, tell ModuleProvider not to delete it when its dtor
2133  // is run.
2134  if (M)
2135    M = R->releaseModule(ErrMsg);
2136
2137  delete R;
2138  return M;
2139}
2140