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