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