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