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