BitcodeReader.cpp revision 3f6eb7419de437436265831fce92f62498556e08
1//===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License.  See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This header defines the BitcodeReader class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Bitcode/ReaderWriter.h"
15#include "BitcodeReader.h"
16#include "llvm/Constants.h"
17#include "llvm/DerivedTypes.h"
18#include "llvm/InlineAsm.h"
19#include "llvm/Instructions.h"
20#include "llvm/Module.h"
21#include "llvm/ParameterAttributes.h"
22#include "llvm/AutoUpgrade.h"
23#include "llvm/ADT/SmallString.h"
24#include "llvm/Support/MathExtras.h"
25#include "llvm/Support/MemoryBuffer.h"
26using namespace llvm;
27
28void BitcodeReader::FreeState() {
29  delete Buffer;
30  Buffer = 0;
31  std::vector<PATypeHolder>().swap(TypeList);
32  ValueList.clear();
33  std::vector<const ParamAttrsList*>().swap(ParamAttrs);
34  std::vector<BasicBlock*>().swap(FunctionBBs);
35  std::vector<Function*>().swap(FunctionsWithBodies);
36  DeferredFunctionInfo.clear();
37}
38
39//===----------------------------------------------------------------------===//
40//  Helper functions to implement forward reference resolution, etc.
41//===----------------------------------------------------------------------===//
42
43/// ConvertToString - Convert a string from a record into an std::string, return
44/// true on failure.
45template<typename StrTy>
46static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
47                            StrTy &Result) {
48  if (Idx > Record.size())
49    return true;
50
51  for (unsigned i = Idx, e = Record.size(); i != e; ++i)
52    Result += (char)Record[i];
53  return false;
54}
55
56static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
57  switch (Val) {
58  default: // Map unknown/new linkages to external
59  case 0: return GlobalValue::ExternalLinkage;
60  case 1: return GlobalValue::WeakLinkage;
61  case 2: return GlobalValue::AppendingLinkage;
62  case 3: return GlobalValue::InternalLinkage;
63  case 4: return GlobalValue::LinkOnceLinkage;
64  case 5: return GlobalValue::DLLImportLinkage;
65  case 6: return GlobalValue::DLLExportLinkage;
66  case 7: return GlobalValue::ExternalWeakLinkage;
67  }
68}
69
70static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
71  switch (Val) {
72  default: // Map unknown visibilities to default.
73  case 0: return GlobalValue::DefaultVisibility;
74  case 1: return GlobalValue::HiddenVisibility;
75  case 2: return GlobalValue::ProtectedVisibility;
76  }
77}
78
79static int GetDecodedCastOpcode(unsigned Val) {
80  switch (Val) {
81  default: return -1;
82  case bitc::CAST_TRUNC   : return Instruction::Trunc;
83  case bitc::CAST_ZEXT    : return Instruction::ZExt;
84  case bitc::CAST_SEXT    : return Instruction::SExt;
85  case bitc::CAST_FPTOUI  : return Instruction::FPToUI;
86  case bitc::CAST_FPTOSI  : return Instruction::FPToSI;
87  case bitc::CAST_UITOFP  : return Instruction::UIToFP;
88  case bitc::CAST_SITOFP  : return Instruction::SIToFP;
89  case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
90  case bitc::CAST_FPEXT   : return Instruction::FPExt;
91  case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
92  case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
93  case bitc::CAST_BITCAST : return Instruction::BitCast;
94  }
95}
96static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
97  switch (Val) {
98  default: return -1;
99  case bitc::BINOP_ADD:  return Instruction::Add;
100  case bitc::BINOP_SUB:  return Instruction::Sub;
101  case bitc::BINOP_MUL:  return Instruction::Mul;
102  case bitc::BINOP_UDIV: return Instruction::UDiv;
103  case bitc::BINOP_SDIV:
104    return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv;
105  case bitc::BINOP_UREM: return Instruction::URem;
106  case bitc::BINOP_SREM:
107    return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem;
108  case bitc::BINOP_SHL:  return Instruction::Shl;
109  case bitc::BINOP_LSHR: return Instruction::LShr;
110  case bitc::BINOP_ASHR: return Instruction::AShr;
111  case bitc::BINOP_AND:  return Instruction::And;
112  case bitc::BINOP_OR:   return Instruction::Or;
113  case bitc::BINOP_XOR:  return Instruction::Xor;
114  }
115}
116
117
118namespace {
119  /// @brief A class for maintaining the slot number definition
120  /// as a placeholder for the actual definition for forward constants defs.
121  class ConstantPlaceHolder : public ConstantExpr {
122    ConstantPlaceHolder();                       // DO NOT IMPLEMENT
123    void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
124  public:
125    Use Op;
126    ConstantPlaceHolder(const Type *Ty)
127      : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
128        Op(UndefValue::get(Type::Int32Ty), this) {
129    }
130  };
131}
132
133Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
134                                                    const Type *Ty) {
135  if (Idx >= size()) {
136    // Insert a bunch of null values.
137    Uses.resize(Idx+1);
138    OperandList = &Uses[0];
139    NumOperands = Idx+1;
140  }
141
142  if (Value *V = Uses[Idx]) {
143    assert(Ty == V->getType() && "Type mismatch in constant table!");
144    return cast<Constant>(V);
145  }
146
147  // Create and return a placeholder, which will later be RAUW'd.
148  Constant *C = new ConstantPlaceHolder(Ty);
149  Uses[Idx].init(C, this);
150  return C;
151}
152
153Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
154  if (Idx >= size()) {
155    // Insert a bunch of null values.
156    Uses.resize(Idx+1);
157    OperandList = &Uses[0];
158    NumOperands = Idx+1;
159  }
160
161  if (Value *V = Uses[Idx]) {
162    assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
163    return V;
164  }
165
166  // No type specified, must be invalid reference.
167  if (Ty == 0) return 0;
168
169  // Create and return a placeholder, which will later be RAUW'd.
170  Value *V = new Argument(Ty);
171  Uses[Idx].init(V, this);
172  return V;
173}
174
175
176const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
177  // If the TypeID is in range, return it.
178  if (ID < TypeList.size())
179    return TypeList[ID].get();
180  if (!isTypeTable) return 0;
181
182  // The type table allows forward references.  Push as many Opaque types as
183  // needed to get up to ID.
184  while (TypeList.size() <= ID)
185    TypeList.push_back(OpaqueType::get());
186  return TypeList.back().get();
187}
188
189//===----------------------------------------------------------------------===//
190//  Functions for parsing blocks from the bitcode file
191//===----------------------------------------------------------------------===//
192
193bool BitcodeReader::ParseParamAttrBlock() {
194  if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
195    return Error("Malformed block record");
196
197  if (!ParamAttrs.empty())
198    return Error("Multiple PARAMATTR blocks found!");
199
200  SmallVector<uint64_t, 64> Record;
201
202  ParamAttrsVector Attrs;
203
204  // Read all the records.
205  while (1) {
206    unsigned Code = Stream.ReadCode();
207    if (Code == bitc::END_BLOCK) {
208      if (Stream.ReadBlockEnd())
209        return Error("Error at end of PARAMATTR block");
210      return false;
211    }
212
213    if (Code == bitc::ENTER_SUBBLOCK) {
214      // No known subblocks, always skip them.
215      Stream.ReadSubBlockID();
216      if (Stream.SkipBlock())
217        return Error("Malformed block record");
218      continue;
219    }
220
221    if (Code == bitc::DEFINE_ABBREV) {
222      Stream.ReadAbbrevRecord();
223      continue;
224    }
225
226    // Read a record.
227    Record.clear();
228    switch (Stream.ReadRecord(Code, Record)) {
229    default:  // Default behavior: ignore.
230      break;
231    case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
232      if (Record.size() & 1)
233        return Error("Invalid ENTRY record");
234
235      ParamAttrsWithIndex PAWI;
236      for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
237        PAWI.index = Record[i];
238        PAWI.attrs = Record[i+1];
239        Attrs.push_back(PAWI);
240      }
241      ParamAttrs.push_back(ParamAttrsList::get(Attrs));
242      Attrs.clear();
243      break;
244    }
245    }
246  }
247}
248
249
250bool BitcodeReader::ParseTypeTable() {
251  if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
252    return Error("Malformed block record");
253
254  if (!TypeList.empty())
255    return Error("Multiple TYPE_BLOCKs found!");
256
257  SmallVector<uint64_t, 64> Record;
258  unsigned NumRecords = 0;
259
260  // Read all the records for this type table.
261  while (1) {
262    unsigned Code = Stream.ReadCode();
263    if (Code == bitc::END_BLOCK) {
264      if (NumRecords != TypeList.size())
265        return Error("Invalid type forward reference in TYPE_BLOCK");
266      if (Stream.ReadBlockEnd())
267        return Error("Error at end of type table block");
268      return false;
269    }
270
271    if (Code == bitc::ENTER_SUBBLOCK) {
272      // No known subblocks, always skip them.
273      Stream.ReadSubBlockID();
274      if (Stream.SkipBlock())
275        return Error("Malformed block record");
276      continue;
277    }
278
279    if (Code == bitc::DEFINE_ABBREV) {
280      Stream.ReadAbbrevRecord();
281      continue;
282    }
283
284    // Read a record.
285    Record.clear();
286    const Type *ResultTy = 0;
287    switch (Stream.ReadRecord(Code, Record)) {
288    default:  // Default behavior: unknown type.
289      ResultTy = 0;
290      break;
291    case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
292      // TYPE_CODE_NUMENTRY contains a count of the number of types in the
293      // type list.  This allows us to reserve space.
294      if (Record.size() < 1)
295        return Error("Invalid TYPE_CODE_NUMENTRY record");
296      TypeList.reserve(Record[0]);
297      continue;
298    case bitc::TYPE_CODE_VOID:      // VOID
299      ResultTy = Type::VoidTy;
300      break;
301    case bitc::TYPE_CODE_FLOAT:     // FLOAT
302      ResultTy = Type::FloatTy;
303      break;
304    case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
305      ResultTy = Type::DoubleTy;
306      break;
307    case bitc::TYPE_CODE_X86_FP80:  // X86_FP80
308      ResultTy = Type::X86_FP80Ty;
309      break;
310    case bitc::TYPE_CODE_FP128:     // FP128
311      ResultTy = Type::FP128Ty;
312      break;
313    case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
314      ResultTy = Type::PPC_FP128Ty;
315      break;
316    case bitc::TYPE_CODE_LABEL:     // LABEL
317      ResultTy = Type::LabelTy;
318      break;
319    case bitc::TYPE_CODE_OPAQUE:    // OPAQUE
320      ResultTy = 0;
321      break;
322    case bitc::TYPE_CODE_INTEGER:   // INTEGER: [width]
323      if (Record.size() < 1)
324        return Error("Invalid Integer type record");
325
326      ResultTy = IntegerType::get(Record[0]);
327      break;
328    case bitc::TYPE_CODE_POINTER:   // POINTER: [pointee type]
329      if (Record.size() < 1)
330        return Error("Invalid POINTER type record");
331      ResultTy = PointerType::get(getTypeByID(Record[0], true));
332      break;
333    case bitc::TYPE_CODE_FUNCTION: {
334      // FUNCTION: [vararg, attrid, retty, paramty x N]
335      if (Record.size() < 3)
336        return Error("Invalid FUNCTION type record");
337      std::vector<const Type*> ArgTys;
338      for (unsigned i = 3, e = Record.size(); i != e; ++i)
339        ArgTys.push_back(getTypeByID(Record[i], true));
340
341      ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
342                                   Record[0], getParamAttrs(Record[1]));
343      break;
344    }
345    case bitc::TYPE_CODE_STRUCT: {  // STRUCT: [ispacked, eltty x N]
346      if (Record.size() < 1)
347        return Error("Invalid STRUCT type record");
348      std::vector<const Type*> EltTys;
349      for (unsigned i = 1, e = Record.size(); i != e; ++i)
350        EltTys.push_back(getTypeByID(Record[i], true));
351      ResultTy = StructType::get(EltTys, Record[0]);
352      break;
353    }
354    case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
355      if (Record.size() < 2)
356        return Error("Invalid ARRAY type record");
357      ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
358      break;
359    case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty]
360      if (Record.size() < 2)
361        return Error("Invalid VECTOR type record");
362      ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
363      break;
364    }
365
366    if (NumRecords == TypeList.size()) {
367      // If this is a new type slot, just append it.
368      TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
369      ++NumRecords;
370    } else if (ResultTy == 0) {
371      // Otherwise, this was forward referenced, so an opaque type was created,
372      // but the result type is actually just an opaque.  Leave the one we
373      // created previously.
374      ++NumRecords;
375    } else {
376      // Otherwise, this was forward referenced, so an opaque type was created.
377      // Resolve the opaque type to the real type now.
378      assert(NumRecords < TypeList.size() && "Typelist imbalance");
379      const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
380
381      // Don't directly push the new type on the Tab. Instead we want to replace
382      // the opaque type we previously inserted with the new concrete value. The
383      // refinement from the abstract (opaque) type to the new type causes all
384      // uses of the abstract type to use the concrete type (NewTy). This will
385      // also cause the opaque type to be deleted.
386      const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
387
388      // This should have replaced the old opaque type with the new type in the
389      // value table... or with a preexisting type that was already in the
390      // system.  Let's just make sure it did.
391      assert(TypeList[NumRecords-1].get() != OldTy &&
392             "refineAbstractType didn't work!");
393    }
394  }
395}
396
397
398bool BitcodeReader::ParseTypeSymbolTable() {
399  if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
400    return Error("Malformed block record");
401
402  SmallVector<uint64_t, 64> Record;
403
404  // Read all the records for this type table.
405  std::string TypeName;
406  while (1) {
407    unsigned Code = Stream.ReadCode();
408    if (Code == bitc::END_BLOCK) {
409      if (Stream.ReadBlockEnd())
410        return Error("Error at end of type symbol table block");
411      return false;
412    }
413
414    if (Code == bitc::ENTER_SUBBLOCK) {
415      // No known subblocks, always skip them.
416      Stream.ReadSubBlockID();
417      if (Stream.SkipBlock())
418        return Error("Malformed block record");
419      continue;
420    }
421
422    if (Code == bitc::DEFINE_ABBREV) {
423      Stream.ReadAbbrevRecord();
424      continue;
425    }
426
427    // Read a record.
428    Record.clear();
429    switch (Stream.ReadRecord(Code, Record)) {
430    default:  // Default behavior: unknown type.
431      break;
432    case bitc::TST_CODE_ENTRY:    // TST_ENTRY: [typeid, namechar x N]
433      if (ConvertToString(Record, 1, TypeName))
434        return Error("Invalid TST_ENTRY record");
435      unsigned TypeID = Record[0];
436      if (TypeID >= TypeList.size())
437        return Error("Invalid Type ID in TST_ENTRY record");
438
439      TheModule->addTypeName(TypeName, TypeList[TypeID].get());
440      TypeName.clear();
441      break;
442    }
443  }
444}
445
446bool BitcodeReader::ParseValueSymbolTable() {
447  if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
448    return Error("Malformed block record");
449
450  SmallVector<uint64_t, 64> Record;
451
452  // Read all the records for this value table.
453  SmallString<128> ValueName;
454  while (1) {
455    unsigned Code = Stream.ReadCode();
456    if (Code == bitc::END_BLOCK) {
457      if (Stream.ReadBlockEnd())
458        return Error("Error at end of value symbol table block");
459      return false;
460    }
461    if (Code == bitc::ENTER_SUBBLOCK) {
462      // No known subblocks, always skip them.
463      Stream.ReadSubBlockID();
464      if (Stream.SkipBlock())
465        return Error("Malformed block record");
466      continue;
467    }
468
469    if (Code == bitc::DEFINE_ABBREV) {
470      Stream.ReadAbbrevRecord();
471      continue;
472    }
473
474    // Read a record.
475    Record.clear();
476    switch (Stream.ReadRecord(Code, Record)) {
477    default:  // Default behavior: unknown type.
478      break;
479    case bitc::VST_CODE_ENTRY: {  // VST_ENTRY: [valueid, namechar x N]
480      if (ConvertToString(Record, 1, ValueName))
481        return Error("Invalid TST_ENTRY record");
482      unsigned ValueID = Record[0];
483      if (ValueID >= ValueList.size())
484        return Error("Invalid Value ID in VST_ENTRY record");
485      Value *V = ValueList[ValueID];
486
487      V->setName(&ValueName[0], ValueName.size());
488      ValueName.clear();
489      break;
490    }
491    case bitc::VST_CODE_BBENTRY: {
492      if (ConvertToString(Record, 1, ValueName))
493        return Error("Invalid VST_BBENTRY record");
494      BasicBlock *BB = getBasicBlock(Record[0]);
495      if (BB == 0)
496        return Error("Invalid BB ID in VST_BBENTRY record");
497
498      BB->setName(&ValueName[0], ValueName.size());
499      ValueName.clear();
500      break;
501    }
502    }
503  }
504}
505
506/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
507/// the LSB for dense VBR encoding.
508static uint64_t DecodeSignRotatedValue(uint64_t V) {
509  if ((V & 1) == 0)
510    return V >> 1;
511  if (V != 1)
512    return -(V >> 1);
513  // There is no such thing as -0 with integers.  "-0" really means MININT.
514  return 1ULL << 63;
515}
516
517/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
518/// values and aliases that we can.
519bool BitcodeReader::ResolveGlobalAndAliasInits() {
520  std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
521  std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
522
523  GlobalInitWorklist.swap(GlobalInits);
524  AliasInitWorklist.swap(AliasInits);
525
526  while (!GlobalInitWorklist.empty()) {
527    unsigned ValID = GlobalInitWorklist.back().second;
528    if (ValID >= ValueList.size()) {
529      // Not ready to resolve this yet, it requires something later in the file.
530      GlobalInits.push_back(GlobalInitWorklist.back());
531    } else {
532      if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
533        GlobalInitWorklist.back().first->setInitializer(C);
534      else
535        return Error("Global variable initializer is not a constant!");
536    }
537    GlobalInitWorklist.pop_back();
538  }
539
540  while (!AliasInitWorklist.empty()) {
541    unsigned ValID = AliasInitWorklist.back().second;
542    if (ValID >= ValueList.size()) {
543      AliasInits.push_back(AliasInitWorklist.back());
544    } else {
545      if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
546        AliasInitWorklist.back().first->setAliasee(C);
547      else
548        return Error("Alias initializer is not a constant!");
549    }
550    AliasInitWorklist.pop_back();
551  }
552  return false;
553}
554
555
556bool BitcodeReader::ParseConstants() {
557  if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
558    return Error("Malformed block record");
559
560  SmallVector<uint64_t, 64> Record;
561
562  // Read all the records for this value table.
563  const Type *CurTy = Type::Int32Ty;
564  unsigned NextCstNo = ValueList.size();
565  while (1) {
566    unsigned Code = Stream.ReadCode();
567    if (Code == bitc::END_BLOCK) {
568      if (NextCstNo != ValueList.size())
569        return Error("Invalid constant reference!");
570
571      if (Stream.ReadBlockEnd())
572        return Error("Error at end of constants block");
573      return false;
574    }
575
576    if (Code == bitc::ENTER_SUBBLOCK) {
577      // No known subblocks, always skip them.
578      Stream.ReadSubBlockID();
579      if (Stream.SkipBlock())
580        return Error("Malformed block record");
581      continue;
582    }
583
584    if (Code == bitc::DEFINE_ABBREV) {
585      Stream.ReadAbbrevRecord();
586      continue;
587    }
588
589    // Read a record.
590    Record.clear();
591    Value *V = 0;
592    switch (Stream.ReadRecord(Code, Record)) {
593    default:  // Default behavior: unknown constant
594    case bitc::CST_CODE_UNDEF:     // UNDEF
595      V = UndefValue::get(CurTy);
596      break;
597    case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
598      if (Record.empty())
599        return Error("Malformed CST_SETTYPE record");
600      if (Record[0] >= TypeList.size())
601        return Error("Invalid Type ID in CST_SETTYPE record");
602      CurTy = TypeList[Record[0]];
603      continue;  // Skip the ValueList manipulation.
604    case bitc::CST_CODE_NULL:      // NULL
605      V = Constant::getNullValue(CurTy);
606      break;
607    case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
608      if (!isa<IntegerType>(CurTy) || Record.empty())
609        return Error("Invalid CST_INTEGER record");
610      V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
611      break;
612    case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
613      if (!isa<IntegerType>(CurTy) || Record.empty())
614        return Error("Invalid WIDE_INTEGER record");
615
616      unsigned NumWords = Record.size();
617      SmallVector<uint64_t, 8> Words;
618      Words.resize(NumWords);
619      for (unsigned i = 0; i != NumWords; ++i)
620        Words[i] = DecodeSignRotatedValue(Record[i]);
621      V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
622                                 NumWords, &Words[0]));
623      break;
624    }
625    case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
626      if (Record.empty())
627        return Error("Invalid FLOAT record");
628      if (CurTy == Type::FloatTy)
629        V = ConstantFP::get(CurTy, APFloat(APInt(32, (uint32_t)Record[0])));
630      else if (CurTy == Type::DoubleTy)
631        V = ConstantFP::get(CurTy, APFloat(APInt(64, Record[0])));
632      // FIXME: Make long double constants work.  BitsToDouble does not make it.
633      else if (CurTy == Type::X86_FP80Ty)
634        V = ConstantFP::get(CurTy, APFloat(APInt(80, 2, &Record[0])));
635      else if (CurTy == Type::FP128Ty)
636        V = ConstantFP::get(CurTy, APFloat(APInt(128, 2, &Record[0])));
637      else if (CurTy == Type::PPC_FP128Ty)
638        assert(0 && "PowerPC long double constants not handled yet.");
639      else
640        V = UndefValue::get(CurTy);
641      break;
642    }
643
644    case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
645      if (Record.empty())
646        return Error("Invalid CST_AGGREGATE record");
647
648      unsigned Size = Record.size();
649      std::vector<Constant*> Elts;
650
651      if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
652        for (unsigned i = 0; i != Size; ++i)
653          Elts.push_back(ValueList.getConstantFwdRef(Record[i],
654                                                     STy->getElementType(i)));
655        V = ConstantStruct::get(STy, Elts);
656      } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
657        const Type *EltTy = ATy->getElementType();
658        for (unsigned i = 0; i != Size; ++i)
659          Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
660        V = ConstantArray::get(ATy, Elts);
661      } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
662        const Type *EltTy = VTy->getElementType();
663        for (unsigned i = 0; i != Size; ++i)
664          Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
665        V = ConstantVector::get(Elts);
666      } else {
667        V = UndefValue::get(CurTy);
668      }
669      break;
670    }
671    case bitc::CST_CODE_STRING: { // STRING: [values]
672      if (Record.empty())
673        return Error("Invalid CST_AGGREGATE record");
674
675      const ArrayType *ATy = cast<ArrayType>(CurTy);
676      const Type *EltTy = ATy->getElementType();
677
678      unsigned Size = Record.size();
679      std::vector<Constant*> Elts;
680      for (unsigned i = 0; i != Size; ++i)
681        Elts.push_back(ConstantInt::get(EltTy, Record[i]));
682      V = ConstantArray::get(ATy, Elts);
683      break;
684    }
685    case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
686      if (Record.empty())
687        return Error("Invalid CST_AGGREGATE record");
688
689      const ArrayType *ATy = cast<ArrayType>(CurTy);
690      const Type *EltTy = ATy->getElementType();
691
692      unsigned Size = Record.size();
693      std::vector<Constant*> Elts;
694      for (unsigned i = 0; i != Size; ++i)
695        Elts.push_back(ConstantInt::get(EltTy, Record[i]));
696      Elts.push_back(Constant::getNullValue(EltTy));
697      V = ConstantArray::get(ATy, Elts);
698      break;
699    }
700    case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
701      if (Record.size() < 3) return Error("Invalid CE_BINOP record");
702      int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
703      if (Opc < 0) {
704        V = UndefValue::get(CurTy);  // Unknown binop.
705      } else {
706        Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
707        Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
708        V = ConstantExpr::get(Opc, LHS, RHS);
709      }
710      break;
711    }
712    case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
713      if (Record.size() < 3) return Error("Invalid CE_CAST record");
714      int Opc = GetDecodedCastOpcode(Record[0]);
715      if (Opc < 0) {
716        V = UndefValue::get(CurTy);  // Unknown cast.
717      } else {
718        const Type *OpTy = getTypeByID(Record[1]);
719        if (!OpTy) return Error("Invalid CE_CAST record");
720        Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
721        V = ConstantExpr::getCast(Opc, Op, CurTy);
722      }
723      break;
724    }
725    case bitc::CST_CODE_CE_GEP: {  // CE_GEP:        [n x operands]
726      if (Record.size() & 1) return Error("Invalid CE_GEP record");
727      SmallVector<Constant*, 16> Elts;
728      for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
729        const Type *ElTy = getTypeByID(Record[i]);
730        if (!ElTy) return Error("Invalid CE_GEP record");
731        Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
732      }
733      V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
734      break;
735    }
736    case bitc::CST_CODE_CE_SELECT:  // CE_SELECT: [opval#, opval#, opval#]
737      if (Record.size() < 3) return Error("Invalid CE_SELECT record");
738      V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
739                                                              Type::Int1Ty),
740                                  ValueList.getConstantFwdRef(Record[1],CurTy),
741                                  ValueList.getConstantFwdRef(Record[2],CurTy));
742      break;
743    case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
744      if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
745      const VectorType *OpTy =
746        dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
747      if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
748      Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
749      Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
750                                                  OpTy->getElementType());
751      V = ConstantExpr::getExtractElement(Op0, Op1);
752      break;
753    }
754    case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
755      const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
756      if (Record.size() < 3 || OpTy == 0)
757        return Error("Invalid CE_INSERTELT record");
758      Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
759      Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
760                                                  OpTy->getElementType());
761      Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
762      V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
763      break;
764    }
765    case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
766      const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
767      if (Record.size() < 3 || OpTy == 0)
768        return Error("Invalid CE_INSERTELT record");
769      Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
770      Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
771      const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
772      Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
773      V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
774      break;
775    }
776    case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
777      if (Record.size() < 4) return Error("Invalid CE_CMP record");
778      const Type *OpTy = getTypeByID(Record[0]);
779      if (OpTy == 0) return Error("Invalid CE_CMP record");
780      Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
781      Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
782
783      if (OpTy->isFloatingPoint())
784        V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
785      else
786        V = ConstantExpr::getICmp(Record[3], Op0, Op1);
787      break;
788    }
789    case bitc::CST_CODE_INLINEASM: {
790      if (Record.size() < 2) return Error("Invalid INLINEASM record");
791      std::string AsmStr, ConstrStr;
792      bool HasSideEffects = Record[0];
793      unsigned AsmStrSize = Record[1];
794      if (2+AsmStrSize >= Record.size())
795        return Error("Invalid INLINEASM record");
796      unsigned ConstStrSize = Record[2+AsmStrSize];
797      if (3+AsmStrSize+ConstStrSize > Record.size())
798        return Error("Invalid INLINEASM record");
799
800      for (unsigned i = 0; i != AsmStrSize; ++i)
801        AsmStr += (char)Record[2+i];
802      for (unsigned i = 0; i != ConstStrSize; ++i)
803        ConstrStr += (char)Record[3+AsmStrSize+i];
804      const PointerType *PTy = cast<PointerType>(CurTy);
805      V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
806                         AsmStr, ConstrStr, HasSideEffects);
807      break;
808    }
809    }
810
811    ValueList.AssignValue(V, NextCstNo);
812    ++NextCstNo;
813  }
814}
815
816/// RememberAndSkipFunctionBody - When we see the block for a function body,
817/// remember where it is and then skip it.  This lets us lazily deserialize the
818/// functions.
819bool BitcodeReader::RememberAndSkipFunctionBody() {
820  // Get the function we are talking about.
821  if (FunctionsWithBodies.empty())
822    return Error("Insufficient function protos");
823
824  Function *Fn = FunctionsWithBodies.back();
825  FunctionsWithBodies.pop_back();
826
827  // Save the current stream state.
828  uint64_t CurBit = Stream.GetCurrentBitNo();
829  DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
830
831  // Set the functions linkage to GhostLinkage so we know it is lazily
832  // deserialized.
833  Fn->setLinkage(GlobalValue::GhostLinkage);
834
835  // Skip over the function block for now.
836  if (Stream.SkipBlock())
837    return Error("Malformed block record");
838  return false;
839}
840
841bool BitcodeReader::ParseModule(const std::string &ModuleID) {
842  // Reject multiple MODULE_BLOCK's in a single bitstream.
843  if (TheModule)
844    return Error("Multiple MODULE_BLOCKs in same stream");
845
846  if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
847    return Error("Malformed block record");
848
849  // Otherwise, create the module.
850  TheModule = new Module(ModuleID);
851
852  SmallVector<uint64_t, 64> Record;
853  std::vector<std::string> SectionTable;
854
855  // Read all the records for this module.
856  while (!Stream.AtEndOfStream()) {
857    unsigned Code = Stream.ReadCode();
858    if (Code == bitc::END_BLOCK) {
859      if (Stream.ReadBlockEnd())
860        return Error("Error at end of module block");
861
862      // Patch the initializers for globals and aliases up.
863      ResolveGlobalAndAliasInits();
864      if (!GlobalInits.empty() || !AliasInits.empty())
865        return Error("Malformed global initializer set");
866      if (!FunctionsWithBodies.empty())
867        return Error("Too few function bodies found");
868
869      // Look for intrinsic functions which need to be upgraded at some point
870      for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
871           FI != FE; ++FI) {
872        if (Function* NewFn = UpgradeIntrinsicFunction(FI))
873          UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
874      }
875
876      // Force deallocation of memory for these vectors to favor the client that
877      // want lazy deserialization.
878      std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
879      std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
880      std::vector<Function*>().swap(FunctionsWithBodies);
881      return false;
882    }
883
884    if (Code == bitc::ENTER_SUBBLOCK) {
885      switch (Stream.ReadSubBlockID()) {
886      default:  // Skip unknown content.
887        if (Stream.SkipBlock())
888          return Error("Malformed block record");
889        break;
890      case bitc::BLOCKINFO_BLOCK_ID:
891        if (Stream.ReadBlockInfoBlock())
892          return Error("Malformed BlockInfoBlock");
893        break;
894      case bitc::PARAMATTR_BLOCK_ID:
895        if (ParseParamAttrBlock())
896          return true;
897        break;
898      case bitc::TYPE_BLOCK_ID:
899        if (ParseTypeTable())
900          return true;
901        break;
902      case bitc::TYPE_SYMTAB_BLOCK_ID:
903        if (ParseTypeSymbolTable())
904          return true;
905        break;
906      case bitc::VALUE_SYMTAB_BLOCK_ID:
907        if (ParseValueSymbolTable())
908          return true;
909        break;
910      case bitc::CONSTANTS_BLOCK_ID:
911        if (ParseConstants() || ResolveGlobalAndAliasInits())
912          return true;
913        break;
914      case bitc::FUNCTION_BLOCK_ID:
915        // If this is the first function body we've seen, reverse the
916        // FunctionsWithBodies list.
917        if (!HasReversedFunctionsWithBodies) {
918          std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
919          HasReversedFunctionsWithBodies = true;
920        }
921
922        if (RememberAndSkipFunctionBody())
923          return true;
924        break;
925      }
926      continue;
927    }
928
929    if (Code == bitc::DEFINE_ABBREV) {
930      Stream.ReadAbbrevRecord();
931      continue;
932    }
933
934    // Read a record.
935    switch (Stream.ReadRecord(Code, Record)) {
936    default: break;  // Default behavior, ignore unknown content.
937    case bitc::MODULE_CODE_VERSION:  // VERSION: [version#]
938      if (Record.size() < 1)
939        return Error("Malformed MODULE_CODE_VERSION");
940      // Only version #0 is supported so far.
941      if (Record[0] != 0)
942        return Error("Unknown bitstream version!");
943      break;
944    case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
945      std::string S;
946      if (ConvertToString(Record, 0, S))
947        return Error("Invalid MODULE_CODE_TRIPLE record");
948      TheModule->setTargetTriple(S);
949      break;
950    }
951    case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
952      std::string S;
953      if (ConvertToString(Record, 0, S))
954        return Error("Invalid MODULE_CODE_DATALAYOUT record");
955      TheModule->setDataLayout(S);
956      break;
957    }
958    case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
959      std::string S;
960      if (ConvertToString(Record, 0, S))
961        return Error("Invalid MODULE_CODE_ASM record");
962      TheModule->setModuleInlineAsm(S);
963      break;
964    }
965    case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
966      std::string S;
967      if (ConvertToString(Record, 0, S))
968        return Error("Invalid MODULE_CODE_DEPLIB record");
969      TheModule->addLibrary(S);
970      break;
971    }
972    case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
973      std::string S;
974      if (ConvertToString(Record, 0, S))
975        return Error("Invalid MODULE_CODE_SECTIONNAME record");
976      SectionTable.push_back(S);
977      break;
978    }
979    // GLOBALVAR: [type, isconst, initid,
980    //             linkage, alignment, section, visibility, threadlocal]
981    case bitc::MODULE_CODE_GLOBALVAR: {
982      if (Record.size() < 6)
983        return Error("Invalid MODULE_CODE_GLOBALVAR record");
984      const Type *Ty = getTypeByID(Record[0]);
985      if (!isa<PointerType>(Ty))
986        return Error("Global not a pointer type!");
987      Ty = cast<PointerType>(Ty)->getElementType();
988
989      bool isConstant = Record[1];
990      GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
991      unsigned Alignment = (1 << Record[4]) >> 1;
992      std::string Section;
993      if (Record[5]) {
994        if (Record[5]-1 >= SectionTable.size())
995          return Error("Invalid section ID");
996        Section = SectionTable[Record[5]-1];
997      }
998      GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
999      if (Record.size() > 6)
1000        Visibility = GetDecodedVisibility(Record[6]);
1001      bool isThreadLocal = false;
1002      if (Record.size() > 7)
1003        isThreadLocal = Record[7];
1004
1005      GlobalVariable *NewGV =
1006        new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule);
1007      NewGV->setAlignment(Alignment);
1008      if (!Section.empty())
1009        NewGV->setSection(Section);
1010      NewGV->setVisibility(Visibility);
1011      NewGV->setThreadLocal(isThreadLocal);
1012
1013      ValueList.push_back(NewGV);
1014
1015      // Remember which value to use for the global initializer.
1016      if (unsigned InitID = Record[2])
1017        GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1018      break;
1019    }
1020    // FUNCTION:  [type, callingconv, isproto, linkage, paramattr,
1021    //             alignment, section, visibility]
1022    case bitc::MODULE_CODE_FUNCTION: {
1023      if (Record.size() < 8)
1024        return Error("Invalid MODULE_CODE_FUNCTION record");
1025      const Type *Ty = getTypeByID(Record[0]);
1026      if (!isa<PointerType>(Ty))
1027        return Error("Function not a pointer type!");
1028      const FunctionType *FTy =
1029        dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1030      if (!FTy)
1031        return Error("Function not a pointer to function type!");
1032
1033      Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
1034                                    "", TheModule);
1035
1036      Func->setCallingConv(Record[1]);
1037      bool isProto = Record[2];
1038      Func->setLinkage(GetDecodedLinkage(Record[3]));
1039
1040      assert(Func->getFunctionType()->getParamAttrs() ==
1041             getParamAttrs(Record[4]));
1042
1043      Func->setAlignment((1 << Record[5]) >> 1);
1044      if (Record[6]) {
1045        if (Record[6]-1 >= SectionTable.size())
1046          return Error("Invalid section ID");
1047        Func->setSection(SectionTable[Record[6]-1]);
1048      }
1049      Func->setVisibility(GetDecodedVisibility(Record[7]));
1050
1051      ValueList.push_back(Func);
1052
1053      // If this is a function with a body, remember the prototype we are
1054      // creating now, so that we can match up the body with them later.
1055      if (!isProto)
1056        FunctionsWithBodies.push_back(Func);
1057      break;
1058    }
1059    // ALIAS: [alias type, aliasee val#, linkage]
1060    case bitc::MODULE_CODE_ALIAS: {
1061      if (Record.size() < 3)
1062        return Error("Invalid MODULE_ALIAS record");
1063      const Type *Ty = getTypeByID(Record[0]);
1064      if (!isa<PointerType>(Ty))
1065        return Error("Function not a pointer type!");
1066
1067      GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1068                                           "", 0, TheModule);
1069      ValueList.push_back(NewGA);
1070      AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1071      break;
1072    }
1073    /// MODULE_CODE_PURGEVALS: [numvals]
1074    case bitc::MODULE_CODE_PURGEVALS:
1075      // Trim down the value list to the specified size.
1076      if (Record.size() < 1 || Record[0] > ValueList.size())
1077        return Error("Invalid MODULE_PURGEVALS record");
1078      ValueList.shrinkTo(Record[0]);
1079      break;
1080    }
1081    Record.clear();
1082  }
1083
1084  return Error("Premature end of bitstream");
1085}
1086
1087
1088bool BitcodeReader::ParseBitcode() {
1089  TheModule = 0;
1090
1091  if (Buffer->getBufferSize() & 3)
1092    return Error("Bitcode stream should be a multiple of 4 bytes in length");
1093
1094  unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
1095  Stream.init(BufPtr, BufPtr+Buffer->getBufferSize());
1096
1097  // Sniff for the signature.
1098  if (Stream.Read(8) != 'B' ||
1099      Stream.Read(8) != 'C' ||
1100      Stream.Read(4) != 0x0 ||
1101      Stream.Read(4) != 0xC ||
1102      Stream.Read(4) != 0xE ||
1103      Stream.Read(4) != 0xD)
1104    return Error("Invalid bitcode signature");
1105
1106  // We expect a number of well-defined blocks, though we don't necessarily
1107  // need to understand them all.
1108  while (!Stream.AtEndOfStream()) {
1109    unsigned Code = Stream.ReadCode();
1110
1111    if (Code != bitc::ENTER_SUBBLOCK)
1112      return Error("Invalid record at top-level");
1113
1114    unsigned BlockID = Stream.ReadSubBlockID();
1115
1116    // We only know the MODULE subblock ID.
1117    switch (BlockID) {
1118    case bitc::BLOCKINFO_BLOCK_ID:
1119      if (Stream.ReadBlockInfoBlock())
1120        return Error("Malformed BlockInfoBlock");
1121      break;
1122    case bitc::MODULE_BLOCK_ID:
1123      if (ParseModule(Buffer->getBufferIdentifier()))
1124        return true;
1125      break;
1126    default:
1127      if (Stream.SkipBlock())
1128        return Error("Malformed block record");
1129      break;
1130    }
1131  }
1132
1133  return false;
1134}
1135
1136
1137/// ParseFunctionBody - Lazily parse the specified function body block.
1138bool BitcodeReader::ParseFunctionBody(Function *F) {
1139  if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
1140    return Error("Malformed block record");
1141
1142  unsigned ModuleValueListSize = ValueList.size();
1143
1144  // Add all the function arguments to the value table.
1145  for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1146    ValueList.push_back(I);
1147
1148  unsigned NextValueNo = ValueList.size();
1149  BasicBlock *CurBB = 0;
1150  unsigned CurBBNo = 0;
1151
1152  // Read all the records.
1153  SmallVector<uint64_t, 64> Record;
1154  while (1) {
1155    unsigned Code = Stream.ReadCode();
1156    if (Code == bitc::END_BLOCK) {
1157      if (Stream.ReadBlockEnd())
1158        return Error("Error at end of function block");
1159      break;
1160    }
1161
1162    if (Code == bitc::ENTER_SUBBLOCK) {
1163      switch (Stream.ReadSubBlockID()) {
1164      default:  // Skip unknown content.
1165        if (Stream.SkipBlock())
1166          return Error("Malformed block record");
1167        break;
1168      case bitc::CONSTANTS_BLOCK_ID:
1169        if (ParseConstants()) return true;
1170        NextValueNo = ValueList.size();
1171        break;
1172      case bitc::VALUE_SYMTAB_BLOCK_ID:
1173        if (ParseValueSymbolTable()) return true;
1174        break;
1175      }
1176      continue;
1177    }
1178
1179    if (Code == bitc::DEFINE_ABBREV) {
1180      Stream.ReadAbbrevRecord();
1181      continue;
1182    }
1183
1184    // Read a record.
1185    Record.clear();
1186    Instruction *I = 0;
1187    switch (Stream.ReadRecord(Code, Record)) {
1188    default: // Default behavior: reject
1189      return Error("Unknown instruction");
1190    case bitc::FUNC_CODE_DECLAREBLOCKS:     // DECLAREBLOCKS: [nblocks]
1191      if (Record.size() < 1 || Record[0] == 0)
1192        return Error("Invalid DECLAREBLOCKS record");
1193      // Create all the basic blocks for the function.
1194      FunctionBBs.resize(Record[0]);
1195      for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1196        FunctionBBs[i] = new BasicBlock("", F);
1197      CurBB = FunctionBBs[0];
1198      continue;
1199
1200    case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
1201      unsigned OpNum = 0;
1202      Value *LHS, *RHS;
1203      if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1204          getValue(Record, OpNum, LHS->getType(), RHS) ||
1205          OpNum+1 != Record.size())
1206        return Error("Invalid BINOP record");
1207
1208      int Opc = GetDecodedBinaryOpcode(Record[OpNum], LHS->getType());
1209      if (Opc == -1) return Error("Invalid BINOP record");
1210      I = BinaryOperator::create((Instruction::BinaryOps)Opc, LHS, RHS);
1211      break;
1212    }
1213    case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
1214      unsigned OpNum = 0;
1215      Value *Op;
1216      if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1217          OpNum+2 != Record.size())
1218        return Error("Invalid CAST record");
1219
1220      const Type *ResTy = getTypeByID(Record[OpNum]);
1221      int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
1222      if (Opc == -1 || ResTy == 0)
1223        return Error("Invalid CAST record");
1224      I = CastInst::create((Instruction::CastOps)Opc, Op, ResTy);
1225      break;
1226    }
1227    case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
1228      unsigned OpNum = 0;
1229      Value *BasePtr;
1230      if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
1231        return Error("Invalid GEP record");
1232
1233      SmallVector<Value*, 16> GEPIdx;
1234      while (OpNum != Record.size()) {
1235        Value *Op;
1236        if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1237          return Error("Invalid GEP record");
1238        GEPIdx.push_back(Op);
1239      }
1240
1241      I = new GetElementPtrInst(BasePtr, GEPIdx.begin(), GEPIdx.end());
1242      break;
1243    }
1244
1245    case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
1246      unsigned OpNum = 0;
1247      Value *TrueVal, *FalseVal, *Cond;
1248      if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1249          getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1250          getValue(Record, OpNum, Type::Int1Ty, Cond))
1251        return Error("Invalid SELECT record");
1252
1253      I = new SelectInst(Cond, TrueVal, FalseVal);
1254      break;
1255    }
1256
1257    case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
1258      unsigned OpNum = 0;
1259      Value *Vec, *Idx;
1260      if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1261          getValue(Record, OpNum, Type::Int32Ty, Idx))
1262        return Error("Invalid EXTRACTELT record");
1263      I = new ExtractElementInst(Vec, Idx);
1264      break;
1265    }
1266
1267    case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
1268      unsigned OpNum = 0;
1269      Value *Vec, *Elt, *Idx;
1270      if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1271          getValue(Record, OpNum,
1272                   cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
1273          getValue(Record, OpNum, Type::Int32Ty, Idx))
1274        return Error("Invalid INSERTELT record");
1275      I = new InsertElementInst(Vec, Elt, Idx);
1276      break;
1277    }
1278
1279    case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
1280      unsigned OpNum = 0;
1281      Value *Vec1, *Vec2, *Mask;
1282      if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
1283          getValue(Record, OpNum, Vec1->getType(), Vec2))
1284        return Error("Invalid SHUFFLEVEC record");
1285
1286      const Type *MaskTy =
1287        VectorType::get(Type::Int32Ty,
1288                        cast<VectorType>(Vec1->getType())->getNumElements());
1289
1290      if (getValue(Record, OpNum, MaskTy, Mask))
1291        return Error("Invalid SHUFFLEVEC record");
1292      I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1293      break;
1294    }
1295
1296    case bitc::FUNC_CODE_INST_CMP: { // CMP: [opty, opval, opval, pred]
1297      unsigned OpNum = 0;
1298      Value *LHS, *RHS;
1299      if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1300          getValue(Record, OpNum, LHS->getType(), RHS) ||
1301          OpNum+1 != Record.size())
1302        return Error("Invalid CMP record");
1303
1304      if (LHS->getType()->isFPOrFPVector())
1305        I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
1306      else
1307        I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
1308      break;
1309    }
1310
1311    case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
1312      if (Record.size() == 0) {
1313        I = new ReturnInst();
1314        break;
1315      } else {
1316        unsigned OpNum = 0;
1317        Value *Op;
1318        if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1319            OpNum != Record.size())
1320          return Error("Invalid RET record");
1321        I = new ReturnInst(Op);
1322        break;
1323      }
1324    case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
1325      if (Record.size() != 1 && Record.size() != 3)
1326        return Error("Invalid BR record");
1327      BasicBlock *TrueDest = getBasicBlock(Record[0]);
1328      if (TrueDest == 0)
1329        return Error("Invalid BR record");
1330
1331      if (Record.size() == 1)
1332        I = new BranchInst(TrueDest);
1333      else {
1334        BasicBlock *FalseDest = getBasicBlock(Record[1]);
1335        Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
1336        if (FalseDest == 0 || Cond == 0)
1337          return Error("Invalid BR record");
1338        I = new BranchInst(TrueDest, FalseDest, Cond);
1339      }
1340      break;
1341    }
1342    case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
1343      if (Record.size() < 3 || (Record.size() & 1) == 0)
1344        return Error("Invalid SWITCH record");
1345      const Type *OpTy = getTypeByID(Record[0]);
1346      Value *Cond = getFnValueByID(Record[1], OpTy);
1347      BasicBlock *Default = getBasicBlock(Record[2]);
1348      if (OpTy == 0 || Cond == 0 || Default == 0)
1349        return Error("Invalid SWITCH record");
1350      unsigned NumCases = (Record.size()-3)/2;
1351      SwitchInst *SI = new SwitchInst(Cond, Default, NumCases);
1352      for (unsigned i = 0, e = NumCases; i != e; ++i) {
1353        ConstantInt *CaseVal =
1354          dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1355        BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1356        if (CaseVal == 0 || DestBB == 0) {
1357          delete SI;
1358          return Error("Invalid SWITCH record!");
1359        }
1360        SI->addCase(CaseVal, DestBB);
1361      }
1362      I = SI;
1363      break;
1364    }
1365
1366    case bitc::FUNC_CODE_INST_INVOKE: { // INVOKE: [cc,fnty, op0,op1,op2, ...]
1367      if (Record.size() < 4) return Error("Invalid INVOKE record");
1368      unsigned CCInfo = Record[1];
1369      BasicBlock *NormalBB = getBasicBlock(Record[2]);
1370      BasicBlock *UnwindBB = getBasicBlock(Record[3]);
1371
1372      unsigned OpNum = 4;
1373      Value *Callee;
1374      if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1375        return Error("Invalid INVOKE record");
1376
1377      const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
1378      const FunctionType *FTy = !CalleeTy ? 0 :
1379        dyn_cast<FunctionType>(CalleeTy->getElementType());
1380
1381      // Check that the right number of fixed parameters are here.
1382      if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
1383          Record.size() < OpNum+FTy->getNumParams())
1384        return Error("Invalid INVOKE record");
1385
1386      assert(FTy->getParamAttrs() == getParamAttrs(Record[0]));
1387
1388      SmallVector<Value*, 16> Ops;
1389      for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1390        Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1391        if (Ops.back() == 0) return Error("Invalid INVOKE record");
1392      }
1393
1394      if (!FTy->isVarArg()) {
1395        if (Record.size() != OpNum)
1396          return Error("Invalid INVOKE record");
1397      } else {
1398        // Read type/value pairs for varargs params.
1399        while (OpNum != Record.size()) {
1400          Value *Op;
1401          if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1402            return Error("Invalid INVOKE record");
1403          Ops.push_back(Op);
1404        }
1405      }
1406
1407      I = new InvokeInst(Callee, NormalBB, UnwindBB, Ops.begin(), Ops.end());
1408      cast<InvokeInst>(I)->setCallingConv(CCInfo);
1409      break;
1410    }
1411    case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1412      I = new UnwindInst();
1413      break;
1414    case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1415      I = new UnreachableInst();
1416      break;
1417    case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
1418      if (Record.size() < 1 || ((Record.size()-1)&1))
1419        return Error("Invalid PHI record");
1420      const Type *Ty = getTypeByID(Record[0]);
1421      if (!Ty) return Error("Invalid PHI record");
1422
1423      PHINode *PN = new PHINode(Ty);
1424      PN->reserveOperandSpace(Record.size()-1);
1425
1426      for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
1427        Value *V = getFnValueByID(Record[1+i], Ty);
1428        BasicBlock *BB = getBasicBlock(Record[2+i]);
1429        if (!V || !BB) return Error("Invalid PHI record");
1430        PN->addIncoming(V, BB);
1431      }
1432      I = PN;
1433      break;
1434    }
1435
1436    case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
1437      if (Record.size() < 3)
1438        return Error("Invalid MALLOC record");
1439      const PointerType *Ty =
1440        dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1441      Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1442      unsigned Align = Record[2];
1443      if (!Ty || !Size) return Error("Invalid MALLOC record");
1444      I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1445      break;
1446    }
1447    case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
1448      unsigned OpNum = 0;
1449      Value *Op;
1450      if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1451          OpNum != Record.size())
1452        return Error("Invalid FREE record");
1453      I = new FreeInst(Op);
1454      break;
1455    }
1456    case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
1457      if (Record.size() < 3)
1458        return Error("Invalid ALLOCA record");
1459      const PointerType *Ty =
1460        dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1461      Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1462      unsigned Align = Record[2];
1463      if (!Ty || !Size) return Error("Invalid ALLOCA record");
1464      I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1465      break;
1466    }
1467    case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
1468      unsigned OpNum = 0;
1469      Value *Op;
1470      if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1471          OpNum+2 != Record.size())
1472        return Error("Invalid LOAD record");
1473
1474      I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1475      break;
1476    }
1477    case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
1478      unsigned OpNum = 0;
1479      Value *Val, *Ptr;
1480      if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
1481          getValue(Record, OpNum, PointerType::get(Val->getType()), Ptr) ||
1482          OpNum+2 != Record.size())
1483        return Error("Invalid STORE record");
1484
1485      I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1486      break;
1487    }
1488    case bitc::FUNC_CODE_INST_CALL: { // CALL: [cc, fnty, fnid, arg0, arg1...]
1489      if (Record.size() < 2)
1490        return Error("Invalid CALL record");
1491
1492      unsigned CCInfo = Record[1];
1493
1494      unsigned OpNum = 2;
1495      Value *Callee;
1496      if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1497        return Error("Invalid CALL record");
1498
1499      const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
1500      const FunctionType *FTy = 0;
1501      if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
1502      if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
1503        return Error("Invalid CALL record");
1504
1505      assert(FTy->getParamAttrs() == getParamAttrs(Record[0]));
1506
1507      SmallVector<Value*, 16> Args;
1508      // Read the fixed params.
1509      for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1510        Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1511        if (Args.back() == 0) return Error("Invalid CALL record");
1512      }
1513
1514      // Read type/value pairs for varargs params.
1515      if (!FTy->isVarArg()) {
1516        if (OpNum != Record.size())
1517          return Error("Invalid CALL record");
1518      } else {
1519        while (OpNum != Record.size()) {
1520          Value *Op;
1521          if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1522            return Error("Invalid CALL record");
1523          Args.push_back(Op);
1524        }
1525      }
1526
1527      I = new CallInst(Callee, Args.begin(), Args.end());
1528      cast<CallInst>(I)->setCallingConv(CCInfo>>1);
1529      cast<CallInst>(I)->setTailCall(CCInfo & 1);
1530      break;
1531    }
1532    case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
1533      if (Record.size() < 3)
1534        return Error("Invalid VAARG record");
1535      const Type *OpTy = getTypeByID(Record[0]);
1536      Value *Op = getFnValueByID(Record[1], OpTy);
1537      const Type *ResTy = getTypeByID(Record[2]);
1538      if (!OpTy || !Op || !ResTy)
1539        return Error("Invalid VAARG record");
1540      I = new VAArgInst(Op, ResTy);
1541      break;
1542    }
1543    }
1544
1545    // Add instruction to end of current BB.  If there is no current BB, reject
1546    // this file.
1547    if (CurBB == 0) {
1548      delete I;
1549      return Error("Invalid instruction with no BB");
1550    }
1551    CurBB->getInstList().push_back(I);
1552
1553    // If this was a terminator instruction, move to the next block.
1554    if (isa<TerminatorInst>(I)) {
1555      ++CurBBNo;
1556      CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
1557    }
1558
1559    // Non-void values get registered in the value table for future use.
1560    if (I && I->getType() != Type::VoidTy)
1561      ValueList.AssignValue(I, NextValueNo++);
1562  }
1563
1564  // Check the function list for unresolved values.
1565  if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
1566    if (A->getParent() == 0) {
1567      // We found at least one unresolved value.  Nuke them all to avoid leaks.
1568      for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
1569        if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
1570          A->replaceAllUsesWith(UndefValue::get(A->getType()));
1571          delete A;
1572        }
1573      }
1574      return Error("Never resolved value found in function!");
1575    }
1576  }
1577
1578  // Trim the value list down to the size it was before we parsed this function.
1579  ValueList.shrinkTo(ModuleValueListSize);
1580  std::vector<BasicBlock*>().swap(FunctionBBs);
1581
1582  return false;
1583}
1584
1585//===----------------------------------------------------------------------===//
1586// ModuleProvider implementation
1587//===----------------------------------------------------------------------===//
1588
1589
1590bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
1591  // If it already is material, ignore the request.
1592  if (!F->hasNotBeenReadFromBitcode()) return false;
1593
1594  DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
1595    DeferredFunctionInfo.find(F);
1596  assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
1597
1598  // Move the bit stream to the saved position of the deferred function body and
1599  // restore the real linkage type for the function.
1600  Stream.JumpToBit(DFII->second.first);
1601  F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
1602
1603  if (ParseFunctionBody(F)) {
1604    if (ErrInfo) *ErrInfo = ErrorString;
1605    return true;
1606  }
1607
1608  // Upgrade any old intrinsic calls in the function.
1609  for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
1610       E = UpgradedIntrinsics.end(); I != E; ++I) {
1611    if (I->first != I->second) {
1612      for (Value::use_iterator UI = I->first->use_begin(),
1613           UE = I->first->use_end(); UI != UE; ) {
1614        if (CallInst* CI = dyn_cast<CallInst>(*UI++))
1615          UpgradeIntrinsicCall(CI, I->second);
1616      }
1617    }
1618  }
1619
1620  return false;
1621}
1622
1623void BitcodeReader::dematerializeFunction(Function *F) {
1624  // If this function isn't materialized, or if it is a proto, this is a noop.
1625  if (F->hasNotBeenReadFromBitcode() || F->isDeclaration())
1626    return;
1627
1628  assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
1629
1630  // Just forget the function body, we can remat it later.
1631  F->deleteBody();
1632  F->setLinkage(GlobalValue::GhostLinkage);
1633}
1634
1635
1636Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
1637  for (DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator I =
1638       DeferredFunctionInfo.begin(), E = DeferredFunctionInfo.end(); I != E;
1639       ++I) {
1640    Function *F = I->first;
1641    if (F->hasNotBeenReadFromBitcode() &&
1642        materializeFunction(F, ErrInfo))
1643      return 0;
1644  }
1645
1646  // Upgrade any intrinsic calls that slipped through (should not happen!) and
1647  // delete the old functions to clean up. We can't do this unless the entire
1648  // module is materialized because there could always be another function body
1649  // with calls to the old function.
1650  for (std::vector<std::pair<Function*, Function*> >::iterator I =
1651       UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
1652    if (I->first != I->second) {
1653      for (Value::use_iterator UI = I->first->use_begin(),
1654           UE = I->first->use_end(); UI != UE; ) {
1655        if (CallInst* CI = dyn_cast<CallInst>(*UI++))
1656          UpgradeIntrinsicCall(CI, I->second);
1657      }
1658      ValueList.replaceUsesOfWith(I->first, I->second);
1659      I->first->eraseFromParent();
1660    }
1661  }
1662  std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
1663
1664  return TheModule;
1665}
1666
1667
1668/// This method is provided by the parent ModuleProvde class and overriden
1669/// here. It simply releases the module from its provided and frees up our
1670/// state.
1671/// @brief Release our hold on the generated module
1672Module *BitcodeReader::releaseModule(std::string *ErrInfo) {
1673  // Since we're losing control of this Module, we must hand it back complete
1674  Module *M = ModuleProvider::releaseModule(ErrInfo);
1675  FreeState();
1676  return M;
1677}
1678
1679
1680//===----------------------------------------------------------------------===//
1681// External interface
1682//===----------------------------------------------------------------------===//
1683
1684/// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
1685///
1686ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
1687                                               std::string *ErrMsg) {
1688  BitcodeReader *R = new BitcodeReader(Buffer);
1689  if (R->ParseBitcode()) {
1690    if (ErrMsg)
1691      *ErrMsg = R->getErrorString();
1692
1693    // Don't let the BitcodeReader dtor delete 'Buffer'.
1694    R->releaseMemoryBuffer();
1695    delete R;
1696    return 0;
1697  }
1698  return R;
1699}
1700
1701/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
1702/// If an error occurs, return null and fill in *ErrMsg if non-null.
1703Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
1704  BitcodeReader *R;
1705  R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg));
1706  if (!R) return 0;
1707
1708  // Read in the entire module.
1709  Module *M = R->materializeModule(ErrMsg);
1710
1711  // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
1712  // there was an error.
1713  R->releaseMemoryBuffer();
1714
1715  // If there was no error, tell ModuleProvider not to delete it when its dtor
1716  // is run.
1717  if (M)
1718    M = R->releaseModule(ErrMsg);
1719
1720  delete R;
1721  return M;
1722}
1723