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