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