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