Internalize BitcodeReader. Not used outside of BitcodeReader.cpp.
[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 "llvm/ADT/STLExtras.h"
12 #include "llvm/ADT/SmallString.h"
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/ADT/Triple.h"
15 #include "llvm/Bitcode/BitstreamReader.h"
16 #include "llvm/Bitcode/LLVMBitCodes.h"
17 #include "llvm/IR/AutoUpgrade.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DebugInfoMetadata.h"
20 #include "llvm/IR/DerivedTypes.h"
21 #include "llvm/IR/DiagnosticPrinter.h"
22 #include "llvm/IR/GVMaterializer.h"
23 #include "llvm/IR/InlineAsm.h"
24 #include "llvm/IR/IntrinsicInst.h"
25 #include "llvm/IR/LLVMContext.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/IR/OperandTraits.h"
28 #include "llvm/IR/Operator.h"
29 #include "llvm/IR/ValueHandle.h"
30 #include "llvm/Support/DataStream.h"
31 #include "llvm/Support/ManagedStatic.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/MemoryBuffer.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include <deque>
36 using namespace llvm;
37
38 namespace {
39 enum {
40   SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
41 };
42
43 class BitcodeReaderValueList {
44   std::vector<WeakVH> ValuePtrs;
45
46   /// ResolveConstants - As we resolve forward-referenced constants, we add
47   /// information about them to this vector.  This allows us to resolve them in
48   /// bulk instead of resolving each reference at a time.  See the code in
49   /// ResolveConstantForwardRefs for more information about this.
50   ///
51   /// The key of this vector is the placeholder constant, the value is the slot
52   /// number that holds the resolved value.
53   typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
54   ResolveConstantsTy ResolveConstants;
55   LLVMContext &Context;
56 public:
57   BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
58   ~BitcodeReaderValueList() {
59     assert(ResolveConstants.empty() && "Constants not resolved?");
60   }
61
62   // vector compatibility methods
63   unsigned size() const { return ValuePtrs.size(); }
64   void resize(unsigned N) { ValuePtrs.resize(N); }
65   void push_back(Value *V) {
66     ValuePtrs.push_back(V);
67   }
68
69   void clear() {
70     assert(ResolveConstants.empty() && "Constants not resolved?");
71     ValuePtrs.clear();
72   }
73
74   Value *operator[](unsigned i) const {
75     assert(i < ValuePtrs.size());
76     return ValuePtrs[i];
77   }
78
79   Value *back() const { return ValuePtrs.back(); }
80     void pop_back() { ValuePtrs.pop_back(); }
81   bool empty() const { return ValuePtrs.empty(); }
82   void shrinkTo(unsigned N) {
83     assert(N <= size() && "Invalid shrinkTo request!");
84     ValuePtrs.resize(N);
85   }
86
87   Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
88   Value *getValueFwdRef(unsigned Idx, Type *Ty);
89
90   void AssignValue(Value *V, unsigned Idx);
91
92   /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
93   /// resolves any forward references.
94   void ResolveConstantForwardRefs();
95 };
96
97 class BitcodeReaderMDValueList {
98   unsigned NumFwdRefs;
99   bool AnyFwdRefs;
100   unsigned MinFwdRef;
101   unsigned MaxFwdRef;
102   std::vector<TrackingMDRef> MDValuePtrs;
103
104   LLVMContext &Context;
105 public:
106   BitcodeReaderMDValueList(LLVMContext &C)
107       : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {}
108
109   // vector compatibility methods
110   unsigned size() const       { return MDValuePtrs.size(); }
111   void resize(unsigned N)     { MDValuePtrs.resize(N); }
112   void push_back(Metadata *MD) { MDValuePtrs.emplace_back(MD); }
113   void clear()                { MDValuePtrs.clear();  }
114   Metadata *back() const      { return MDValuePtrs.back(); }
115   void pop_back()             { MDValuePtrs.pop_back(); }
116   bool empty() const          { return MDValuePtrs.empty(); }
117
118   Metadata *operator[](unsigned i) const {
119     assert(i < MDValuePtrs.size());
120     return MDValuePtrs[i];
121   }
122
123   void shrinkTo(unsigned N) {
124     assert(N <= size() && "Invalid shrinkTo request!");
125     MDValuePtrs.resize(N);
126   }
127
128   Metadata *getValueFwdRef(unsigned Idx);
129   void AssignValue(Metadata *MD, unsigned Idx);
130   void tryToResolveCycles();
131 };
132
133 class BitcodeReader : public GVMaterializer {
134   LLVMContext &Context;
135   DiagnosticHandlerFunction DiagnosticHandler;
136   Module *TheModule;
137   std::unique_ptr<MemoryBuffer> Buffer;
138   std::unique_ptr<BitstreamReader> StreamFile;
139   BitstreamCursor Stream;
140   DataStreamer *LazyStreamer;
141   uint64_t NextUnreadBit;
142   bool SeenValueSymbolTable;
143
144   std::vector<Type*> TypeList;
145   BitcodeReaderValueList ValueList;
146   BitcodeReaderMDValueList MDValueList;
147   std::vector<Comdat *> ComdatList;
148   SmallVector<Instruction *, 64> InstructionList;
149
150   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
151   std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
152   std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
153   std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
154
155   SmallVector<Instruction*, 64> InstsWithTBAATag;
156
157   /// MAttributes - The set of attributes by index.  Index zero in the
158   /// file is for null, and is thus not represented here.  As such all indices
159   /// are off by one.
160   std::vector<AttributeSet> MAttributes;
161
162   /// \brief The set of attribute groups.
163   std::map<unsigned, AttributeSet> MAttributeGroups;
164
165   /// FunctionBBs - While parsing a function body, this is a list of the basic
166   /// blocks for the function.
167   std::vector<BasicBlock*> FunctionBBs;
168
169   // When reading the module header, this list is populated with functions that
170   // have bodies later in the file.
171   std::vector<Function*> FunctionsWithBodies;
172
173   // When intrinsic functions are encountered which require upgrading they are
174   // stored here with their replacement function.
175   typedef std::vector<std::pair<Function*, Function*> > UpgradedIntrinsicMap;
176   UpgradedIntrinsicMap UpgradedIntrinsics;
177
178   // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
179   DenseMap<unsigned, unsigned> MDKindMap;
180
181   // Several operations happen after the module header has been read, but
182   // before function bodies are processed. This keeps track of whether
183   // we've done this yet.
184   bool SeenFirstFunctionBody;
185
186   /// DeferredFunctionInfo - When function bodies are initially scanned, this
187   /// map contains info about where to find deferred function body in the
188   /// stream.
189   DenseMap<Function*, uint64_t> DeferredFunctionInfo;
190
191   /// When Metadata block is initially scanned when parsing the module, we may
192   /// choose to defer parsing of the metadata. This vector contains info about
193   /// which Metadata blocks are deferred.
194   std::vector<uint64_t> DeferredMetadataInfo;
195
196   /// These are basic blocks forward-referenced by block addresses.  They are
197   /// inserted lazily into functions when they're loaded.  The basic block ID is
198   /// its index into the vector.
199   DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
200   std::deque<Function *> BasicBlockFwdRefQueue;
201
202   /// UseRelativeIDs - Indicates that we are using a new encoding for
203   /// instruction operands where most operands in the current
204   /// FUNCTION_BLOCK are encoded relative to the instruction number,
205   /// for a more compact encoding.  Some instruction operands are not
206   /// relative to the instruction ID: basic block numbers, and types.
207   /// Once the old style function blocks have been phased out, we would
208   /// not need this flag.
209   bool UseRelativeIDs;
210
211   /// True if all functions will be materialized, negating the need to process
212   /// (e.g.) blockaddress forward references.
213   bool WillMaterializeAllForwardRefs;
214
215   /// Functions that have block addresses taken.  This is usually empty.
216   SmallPtrSet<const Function *, 4> BlockAddressesTaken;
217
218   /// True if any Metadata block has been materialized.
219   bool IsMetadataMaterialized;
220
221 public:
222   std::error_code Error(BitcodeError E, const Twine &Message);
223   std::error_code Error(BitcodeError E);
224   std::error_code Error(const Twine &Message);
225
226   explicit BitcodeReader(MemoryBuffer *buffer, LLVMContext &C,
227                          DiagnosticHandlerFunction DiagnosticHandler);
228   explicit BitcodeReader(DataStreamer *streamer, LLVMContext &C,
229                          DiagnosticHandlerFunction DiagnosticHandler);
230   ~BitcodeReader() { FreeState(); }
231
232   std::error_code materializeForwardReferencedFunctions();
233
234   void FreeState();
235
236   void releaseBuffer();
237
238   bool isDematerializable(const GlobalValue *GV) const override;
239   std::error_code materialize(GlobalValue *GV) override;
240   std::error_code MaterializeModule(Module *M) override;
241   std::vector<StructType *> getIdentifiedStructTypes() const override;
242   void Dematerialize(GlobalValue *GV) override;
243
244   /// @brief Main interface to parsing a bitcode buffer.
245   /// @returns true if an error occurred.
246   std::error_code ParseBitcodeInto(Module *M,
247                                    bool ShouldLazyLoadMetadata = false);
248
249   /// @brief Cheap mechanism to just extract module triple
250   /// @returns true if an error occurred.
251   ErrorOr<std::string> parseTriple();
252
253   static uint64_t decodeSignRotatedValue(uint64_t V);
254
255   /// Materialize any deferred Metadata block.
256   std::error_code materializeMetadata() override;
257
258 private:
259   std::vector<StructType *> IdentifiedStructTypes;
260   StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
261   StructType *createIdentifiedStructType(LLVMContext &Context);
262
263   Type *getTypeByID(unsigned ID);
264   Value *getFnValueByID(unsigned ID, Type *Ty) {
265     if (Ty && Ty->isMetadataTy())
266       return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
267     return ValueList.getValueFwdRef(ID, Ty);
268   }
269   Metadata *getFnMetadataByID(unsigned ID) {
270     return MDValueList.getValueFwdRef(ID);
271   }
272   BasicBlock *getBasicBlock(unsigned ID) const {
273     if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
274     return FunctionBBs[ID];
275   }
276   AttributeSet getAttributes(unsigned i) const {
277     if (i-1 < MAttributes.size())
278       return MAttributes[i-1];
279     return AttributeSet();
280   }
281
282   /// getValueTypePair - Read a value/type pair out of the specified record from
283   /// slot 'Slot'.  Increment Slot past the number of slots used in the record.
284   /// Return true on failure.
285   bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
286                         unsigned InstNum, Value *&ResVal) {
287     if (Slot == Record.size()) return true;
288     unsigned ValNo = (unsigned)Record[Slot++];
289     // Adjust the ValNo, if it was encoded relative to the InstNum.
290     if (UseRelativeIDs)
291       ValNo = InstNum - ValNo;
292     if (ValNo < InstNum) {
293       // If this is not a forward reference, just return the value we already
294       // have.
295       ResVal = getFnValueByID(ValNo, nullptr);
296       return ResVal == nullptr;
297     } else if (Slot == Record.size()) {
298       return true;
299     }
300
301     unsigned TypeNo = (unsigned)Record[Slot++];
302     ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
303     return ResVal == nullptr;
304   }
305
306   /// popValue - Read a value out of the specified record from slot 'Slot'.
307   /// Increment Slot past the number of slots used by the value in the record.
308   /// Return true if there is an error.
309   bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
310                 unsigned InstNum, Type *Ty, Value *&ResVal) {
311     if (getValue(Record, Slot, InstNum, Ty, ResVal))
312       return true;
313     // All values currently take a single record slot.
314     ++Slot;
315     return false;
316   }
317
318   /// getValue -- Like popValue, but does not increment the Slot number.
319   bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
320                 unsigned InstNum, Type *Ty, Value *&ResVal) {
321     ResVal = getValue(Record, Slot, InstNum, Ty);
322     return ResVal == nullptr;
323   }
324
325   /// getValue -- Version of getValue that returns ResVal directly,
326   /// or 0 if there is an error.
327   Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
328                   unsigned InstNum, Type *Ty) {
329     if (Slot == Record.size()) return nullptr;
330     unsigned ValNo = (unsigned)Record[Slot];
331     // Adjust the ValNo, if it was encoded relative to the InstNum.
332     if (UseRelativeIDs)
333       ValNo = InstNum - ValNo;
334     return getFnValueByID(ValNo, Ty);
335   }
336
337   /// getValueSigned -- Like getValue, but decodes signed VBRs.
338   Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
339                         unsigned InstNum, Type *Ty) {
340     if (Slot == Record.size()) return nullptr;
341     unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
342     // Adjust the ValNo, if it was encoded relative to the InstNum.
343     if (UseRelativeIDs)
344       ValNo = InstNum - ValNo;
345     return getFnValueByID(ValNo, Ty);
346   }
347
348   /// Converts alignment exponent (i.e. power of two (or zero)) to the
349   /// corresponding alignment to use. If alignment is too large, returns
350   /// a corresponding error code.
351   std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
352   std::error_code ParseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
353   std::error_code ParseModule(bool Resume, bool ShouldLazyLoadMetadata = false);
354   std::error_code ParseAttributeBlock();
355   std::error_code ParseAttributeGroupBlock();
356   std::error_code ParseTypeTable();
357   std::error_code ParseTypeTableBody();
358
359   std::error_code ParseValueSymbolTable();
360   std::error_code ParseConstants();
361   std::error_code RememberAndSkipFunctionBody();
362   /// Save the positions of the Metadata blocks and skip parsing the blocks.
363   std::error_code rememberAndSkipMetadata();
364   std::error_code ParseFunctionBody(Function *F);
365   std::error_code GlobalCleanup();
366   std::error_code ResolveGlobalAndAliasInits();
367   std::error_code ParseMetadata();
368   std::error_code ParseMetadataAttachment();
369   ErrorOr<std::string> parseModuleTriple();
370   std::error_code ParseUseLists();
371   std::error_code InitStream();
372   std::error_code InitStreamFromBuffer();
373   std::error_code InitLazyStream();
374   std::error_code FindFunctionInStream(
375       Function *F,
376       DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
377 };
378 } // namespace
379
380 BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
381                                              DiagnosticSeverity Severity,
382                                              const Twine &Msg)
383     : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
384
385 void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
386
387 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
388                              std::error_code EC, const Twine &Message) {
389   BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
390   DiagnosticHandler(DI);
391   return EC;
392 }
393
394 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
395                              std::error_code EC) {
396   return Error(DiagnosticHandler, EC, EC.message());
397 }
398
399 std::error_code BitcodeReader::Error(BitcodeError E, const Twine &Message) {
400   return ::Error(DiagnosticHandler, make_error_code(E), Message);
401 }
402
403 std::error_code BitcodeReader::Error(const Twine &Message) {
404   return ::Error(DiagnosticHandler,
405                  make_error_code(BitcodeError::CorruptedBitcode), Message);
406 }
407
408 std::error_code BitcodeReader::Error(BitcodeError E) {
409   return ::Error(DiagnosticHandler, make_error_code(E));
410 }
411
412 static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
413                                                 LLVMContext &C) {
414   if (F)
415     return F;
416   return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
417 }
418
419 BitcodeReader::BitcodeReader(MemoryBuffer *buffer, LLVMContext &C,
420                              DiagnosticHandlerFunction DiagnosticHandler)
421     : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
422       TheModule(nullptr), Buffer(buffer), LazyStreamer(nullptr),
423       NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
424       MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
425       WillMaterializeAllForwardRefs(false), IsMetadataMaterialized(false) {}
426
427 BitcodeReader::BitcodeReader(DataStreamer *streamer, LLVMContext &C,
428                              DiagnosticHandlerFunction DiagnosticHandler)
429     : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
430       TheModule(nullptr), Buffer(nullptr), LazyStreamer(streamer),
431       NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
432       MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
433       WillMaterializeAllForwardRefs(false), IsMetadataMaterialized(false) {}
434
435 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
436   if (WillMaterializeAllForwardRefs)
437     return std::error_code();
438
439   // Prevent recursion.
440   WillMaterializeAllForwardRefs = true;
441
442   while (!BasicBlockFwdRefQueue.empty()) {
443     Function *F = BasicBlockFwdRefQueue.front();
444     BasicBlockFwdRefQueue.pop_front();
445     assert(F && "Expected valid function");
446     if (!BasicBlockFwdRefs.count(F))
447       // Already materialized.
448       continue;
449
450     // Check for a function that isn't materializable to prevent an infinite
451     // loop.  When parsing a blockaddress stored in a global variable, there
452     // isn't a trivial way to check if a function will have a body without a
453     // linear search through FunctionsWithBodies, so just check it here.
454     if (!F->isMaterializable())
455       return Error("Never resolved function from blockaddress");
456
457     // Try to materialize F.
458     if (std::error_code EC = materialize(F))
459       return EC;
460   }
461   assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
462
463   // Reset state.
464   WillMaterializeAllForwardRefs = false;
465   return std::error_code();
466 }
467
468 void BitcodeReader::FreeState() {
469   Buffer = nullptr;
470   std::vector<Type*>().swap(TypeList);
471   ValueList.clear();
472   MDValueList.clear();
473   std::vector<Comdat *>().swap(ComdatList);
474
475   std::vector<AttributeSet>().swap(MAttributes);
476   std::vector<BasicBlock*>().swap(FunctionBBs);
477   std::vector<Function*>().swap(FunctionsWithBodies);
478   DeferredFunctionInfo.clear();
479   DeferredMetadataInfo.clear();
480   MDKindMap.clear();
481
482   assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
483   BasicBlockFwdRefQueue.clear();
484 }
485
486 //===----------------------------------------------------------------------===//
487 //  Helper functions to implement forward reference resolution, etc.
488 //===----------------------------------------------------------------------===//
489
490 /// ConvertToString - Convert a string from a record into an std::string, return
491 /// true on failure.
492 template<typename StrTy>
493 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
494                             StrTy &Result) {
495   if (Idx > Record.size())
496     return true;
497
498   for (unsigned i = Idx, e = Record.size(); i != e; ++i)
499     Result += (char)Record[i];
500   return false;
501 }
502
503 static bool hasImplicitComdat(size_t Val) {
504   switch (Val) {
505   default:
506     return false;
507   case 1:  // Old WeakAnyLinkage
508   case 4:  // Old LinkOnceAnyLinkage
509   case 10: // Old WeakODRLinkage
510   case 11: // Old LinkOnceODRLinkage
511     return true;
512   }
513 }
514
515 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
516   switch (Val) {
517   default: // Map unknown/new linkages to external
518   case 0:
519     return GlobalValue::ExternalLinkage;
520   case 2:
521     return GlobalValue::AppendingLinkage;
522   case 3:
523     return GlobalValue::InternalLinkage;
524   case 5:
525     return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
526   case 6:
527     return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
528   case 7:
529     return GlobalValue::ExternalWeakLinkage;
530   case 8:
531     return GlobalValue::CommonLinkage;
532   case 9:
533     return GlobalValue::PrivateLinkage;
534   case 12:
535     return GlobalValue::AvailableExternallyLinkage;
536   case 13:
537     return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
538   case 14:
539     return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
540   case 15:
541     return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
542   case 1: // Old value with implicit comdat.
543   case 16:
544     return GlobalValue::WeakAnyLinkage;
545   case 10: // Old value with implicit comdat.
546   case 17:
547     return GlobalValue::WeakODRLinkage;
548   case 4: // Old value with implicit comdat.
549   case 18:
550     return GlobalValue::LinkOnceAnyLinkage;
551   case 11: // Old value with implicit comdat.
552   case 19:
553     return GlobalValue::LinkOnceODRLinkage;
554   }
555 }
556
557 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
558   switch (Val) {
559   default: // Map unknown visibilities to default.
560   case 0: return GlobalValue::DefaultVisibility;
561   case 1: return GlobalValue::HiddenVisibility;
562   case 2: return GlobalValue::ProtectedVisibility;
563   }
564 }
565
566 static GlobalValue::DLLStorageClassTypes
567 GetDecodedDLLStorageClass(unsigned Val) {
568   switch (Val) {
569   default: // Map unknown values to default.
570   case 0: return GlobalValue::DefaultStorageClass;
571   case 1: return GlobalValue::DLLImportStorageClass;
572   case 2: return GlobalValue::DLLExportStorageClass;
573   }
574 }
575
576 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
577   switch (Val) {
578     case 0: return GlobalVariable::NotThreadLocal;
579     default: // Map unknown non-zero value to general dynamic.
580     case 1: return GlobalVariable::GeneralDynamicTLSModel;
581     case 2: return GlobalVariable::LocalDynamicTLSModel;
582     case 3: return GlobalVariable::InitialExecTLSModel;
583     case 4: return GlobalVariable::LocalExecTLSModel;
584   }
585 }
586
587 static int GetDecodedCastOpcode(unsigned Val) {
588   switch (Val) {
589   default: return -1;
590   case bitc::CAST_TRUNC   : return Instruction::Trunc;
591   case bitc::CAST_ZEXT    : return Instruction::ZExt;
592   case bitc::CAST_SEXT    : return Instruction::SExt;
593   case bitc::CAST_FPTOUI  : return Instruction::FPToUI;
594   case bitc::CAST_FPTOSI  : return Instruction::FPToSI;
595   case bitc::CAST_UITOFP  : return Instruction::UIToFP;
596   case bitc::CAST_SITOFP  : return Instruction::SIToFP;
597   case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
598   case bitc::CAST_FPEXT   : return Instruction::FPExt;
599   case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
600   case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
601   case bitc::CAST_BITCAST : return Instruction::BitCast;
602   case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
603   }
604 }
605 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
606   switch (Val) {
607   default: return -1;
608   case bitc::BINOP_ADD:
609     return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
610   case bitc::BINOP_SUB:
611     return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
612   case bitc::BINOP_MUL:
613     return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
614   case bitc::BINOP_UDIV: return Instruction::UDiv;
615   case bitc::BINOP_SDIV:
616     return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
617   case bitc::BINOP_UREM: return Instruction::URem;
618   case bitc::BINOP_SREM:
619     return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
620   case bitc::BINOP_SHL:  return Instruction::Shl;
621   case bitc::BINOP_LSHR: return Instruction::LShr;
622   case bitc::BINOP_ASHR: return Instruction::AShr;
623   case bitc::BINOP_AND:  return Instruction::And;
624   case bitc::BINOP_OR:   return Instruction::Or;
625   case bitc::BINOP_XOR:  return Instruction::Xor;
626   }
627 }
628
629 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
630   switch (Val) {
631   default: return AtomicRMWInst::BAD_BINOP;
632   case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
633   case bitc::RMW_ADD: return AtomicRMWInst::Add;
634   case bitc::RMW_SUB: return AtomicRMWInst::Sub;
635   case bitc::RMW_AND: return AtomicRMWInst::And;
636   case bitc::RMW_NAND: return AtomicRMWInst::Nand;
637   case bitc::RMW_OR: return AtomicRMWInst::Or;
638   case bitc::RMW_XOR: return AtomicRMWInst::Xor;
639   case bitc::RMW_MAX: return AtomicRMWInst::Max;
640   case bitc::RMW_MIN: return AtomicRMWInst::Min;
641   case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
642   case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
643   }
644 }
645
646 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
647   switch (Val) {
648   case bitc::ORDERING_NOTATOMIC: return NotAtomic;
649   case bitc::ORDERING_UNORDERED: return Unordered;
650   case bitc::ORDERING_MONOTONIC: return Monotonic;
651   case bitc::ORDERING_ACQUIRE: return Acquire;
652   case bitc::ORDERING_RELEASE: return Release;
653   case bitc::ORDERING_ACQREL: return AcquireRelease;
654   default: // Map unknown orderings to sequentially-consistent.
655   case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
656   }
657 }
658
659 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
660   switch (Val) {
661   case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
662   default: // Map unknown scopes to cross-thread.
663   case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
664   }
665 }
666
667 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
668   switch (Val) {
669   default: // Map unknown selection kinds to any.
670   case bitc::COMDAT_SELECTION_KIND_ANY:
671     return Comdat::Any;
672   case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
673     return Comdat::ExactMatch;
674   case bitc::COMDAT_SELECTION_KIND_LARGEST:
675     return Comdat::Largest;
676   case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
677     return Comdat::NoDuplicates;
678   case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
679     return Comdat::SameSize;
680   }
681 }
682
683 static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
684   switch (Val) {
685   case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
686   case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
687   }
688 }
689
690 namespace llvm {
691 namespace {
692   /// @brief A class for maintaining the slot number definition
693   /// as a placeholder for the actual definition for forward constants defs.
694   class ConstantPlaceHolder : public ConstantExpr {
695     void operator=(const ConstantPlaceHolder &) = delete;
696   public:
697     // allocate space for exactly one operand
698     void *operator new(size_t s) {
699       return User::operator new(s, 1);
700     }
701     explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
702       : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
703       Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
704     }
705
706     /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
707     static bool classof(const Value *V) {
708       return isa<ConstantExpr>(V) &&
709              cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
710     }
711
712
713     /// Provide fast operand accessors
714     DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
715   };
716 }
717
718 // FIXME: can we inherit this from ConstantExpr?
719 template <>
720 struct OperandTraits<ConstantPlaceHolder> :
721   public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
722 };
723 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
724 }
725
726
727 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
728   if (Idx == size()) {
729     push_back(V);
730     return;
731   }
732
733   if (Idx >= size())
734     resize(Idx+1);
735
736   WeakVH &OldV = ValuePtrs[Idx];
737   if (!OldV) {
738     OldV = V;
739     return;
740   }
741
742   // Handle constants and non-constants (e.g. instrs) differently for
743   // efficiency.
744   if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
745     ResolveConstants.push_back(std::make_pair(PHC, Idx));
746     OldV = V;
747   } else {
748     // If there was a forward reference to this value, replace it.
749     Value *PrevVal = OldV;
750     OldV->replaceAllUsesWith(V);
751     delete PrevVal;
752   }
753 }
754
755
756 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
757                                                     Type *Ty) {
758   if (Idx >= size())
759     resize(Idx + 1);
760
761   if (Value *V = ValuePtrs[Idx]) {
762     assert(Ty == V->getType() && "Type mismatch in constant table!");
763     return cast<Constant>(V);
764   }
765
766   // Create and return a placeholder, which will later be RAUW'd.
767   Constant *C = new ConstantPlaceHolder(Ty, Context);
768   ValuePtrs[Idx] = C;
769   return C;
770 }
771
772 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
773   if (Idx >= size())
774     resize(Idx + 1);
775
776   if (Value *V = ValuePtrs[Idx]) {
777     assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!");
778     return V;
779   }
780
781   // No type specified, must be invalid reference.
782   if (!Ty) return nullptr;
783
784   // Create and return a placeholder, which will later be RAUW'd.
785   Value *V = new Argument(Ty);
786   ValuePtrs[Idx] = V;
787   return V;
788 }
789
790 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
791 /// resolves any forward references.  The idea behind this is that we sometimes
792 /// get constants (such as large arrays) which reference *many* forward ref
793 /// constants.  Replacing each of these causes a lot of thrashing when
794 /// building/reuniquing the constant.  Instead of doing this, we look at all the
795 /// uses and rewrite all the place holders at once for any constant that uses
796 /// a placeholder.
797 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
798   // Sort the values by-pointer so that they are efficient to look up with a
799   // binary search.
800   std::sort(ResolveConstants.begin(), ResolveConstants.end());
801
802   SmallVector<Constant*, 64> NewOps;
803
804   while (!ResolveConstants.empty()) {
805     Value *RealVal = operator[](ResolveConstants.back().second);
806     Constant *Placeholder = ResolveConstants.back().first;
807     ResolveConstants.pop_back();
808
809     // Loop over all users of the placeholder, updating them to reference the
810     // new value.  If they reference more than one placeholder, update them all
811     // at once.
812     while (!Placeholder->use_empty()) {
813       auto UI = Placeholder->user_begin();
814       User *U = *UI;
815
816       // If the using object isn't uniqued, just update the operands.  This
817       // handles instructions and initializers for global variables.
818       if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
819         UI.getUse().set(RealVal);
820         continue;
821       }
822
823       // Otherwise, we have a constant that uses the placeholder.  Replace that
824       // constant with a new constant that has *all* placeholder uses updated.
825       Constant *UserC = cast<Constant>(U);
826       for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
827            I != E; ++I) {
828         Value *NewOp;
829         if (!isa<ConstantPlaceHolder>(*I)) {
830           // Not a placeholder reference.
831           NewOp = *I;
832         } else if (*I == Placeholder) {
833           // Common case is that it just references this one placeholder.
834           NewOp = RealVal;
835         } else {
836           // Otherwise, look up the placeholder in ResolveConstants.
837           ResolveConstantsTy::iterator It =
838             std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
839                              std::pair<Constant*, unsigned>(cast<Constant>(*I),
840                                                             0));
841           assert(It != ResolveConstants.end() && It->first == *I);
842           NewOp = operator[](It->second);
843         }
844
845         NewOps.push_back(cast<Constant>(NewOp));
846       }
847
848       // Make the new constant.
849       Constant *NewC;
850       if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
851         NewC = ConstantArray::get(UserCA->getType(), NewOps);
852       } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
853         NewC = ConstantStruct::get(UserCS->getType(), NewOps);
854       } else if (isa<ConstantVector>(UserC)) {
855         NewC = ConstantVector::get(NewOps);
856       } else {
857         assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
858         NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
859       }
860
861       UserC->replaceAllUsesWith(NewC);
862       UserC->destroyConstant();
863       NewOps.clear();
864     }
865
866     // Update all ValueHandles, they should be the only users at this point.
867     Placeholder->replaceAllUsesWith(RealVal);
868     delete Placeholder;
869   }
870 }
871
872 void BitcodeReaderMDValueList::AssignValue(Metadata *MD, unsigned Idx) {
873   if (Idx == size()) {
874     push_back(MD);
875     return;
876   }
877
878   if (Idx >= size())
879     resize(Idx+1);
880
881   TrackingMDRef &OldMD = MDValuePtrs[Idx];
882   if (!OldMD) {
883     OldMD.reset(MD);
884     return;
885   }
886
887   // If there was a forward reference to this value, replace it.
888   TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
889   PrevMD->replaceAllUsesWith(MD);
890   --NumFwdRefs;
891 }
892
893 Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
894   if (Idx >= size())
895     resize(Idx + 1);
896
897   if (Metadata *MD = MDValuePtrs[Idx])
898     return MD;
899
900   // Track forward refs to be resolved later.
901   if (AnyFwdRefs) {
902     MinFwdRef = std::min(MinFwdRef, Idx);
903     MaxFwdRef = std::max(MaxFwdRef, Idx);
904   } else {
905     AnyFwdRefs = true;
906     MinFwdRef = MaxFwdRef = Idx;
907   }
908   ++NumFwdRefs;
909
910   // Create and return a placeholder, which will later be RAUW'd.
911   Metadata *MD = MDNode::getTemporary(Context, None).release();
912   MDValuePtrs[Idx].reset(MD);
913   return MD;
914 }
915
916 void BitcodeReaderMDValueList::tryToResolveCycles() {
917   if (!AnyFwdRefs)
918     // Nothing to do.
919     return;
920
921   if (NumFwdRefs)
922     // Still forward references... can't resolve cycles.
923     return;
924
925   // Resolve any cycles.
926   for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
927     auto &MD = MDValuePtrs[I];
928     auto *N = dyn_cast_or_null<MDNode>(MD);
929     if (!N)
930       continue;
931
932     assert(!N->isTemporary() && "Unexpected forward reference");
933     N->resolveCycles();
934   }
935
936   // Make sure we return early again until there's another forward ref.
937   AnyFwdRefs = false;
938 }
939
940 Type *BitcodeReader::getTypeByID(unsigned ID) {
941   // The type table size is always specified correctly.
942   if (ID >= TypeList.size())
943     return nullptr;
944
945   if (Type *Ty = TypeList[ID])
946     return Ty;
947
948   // If we have a forward reference, the only possible case is when it is to a
949   // named struct.  Just create a placeholder for now.
950   return TypeList[ID] = createIdentifiedStructType(Context);
951 }
952
953 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
954                                                       StringRef Name) {
955   auto *Ret = StructType::create(Context, Name);
956   IdentifiedStructTypes.push_back(Ret);
957   return Ret;
958 }
959
960 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
961   auto *Ret = StructType::create(Context);
962   IdentifiedStructTypes.push_back(Ret);
963   return Ret;
964 }
965
966
967 //===----------------------------------------------------------------------===//
968 //  Functions for parsing blocks from the bitcode file
969 //===----------------------------------------------------------------------===//
970
971
972 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
973 /// been decoded from the given integer. This function must stay in sync with
974 /// 'encodeLLVMAttributesForBitcode'.
975 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
976                                            uint64_t EncodedAttrs) {
977   // FIXME: Remove in 4.0.
978
979   // The alignment is stored as a 16-bit raw value from bits 31--16.  We shift
980   // the bits above 31 down by 11 bits.
981   unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
982   assert((!Alignment || isPowerOf2_32(Alignment)) &&
983          "Alignment must be a power of two.");
984
985   if (Alignment)
986     B.addAlignmentAttr(Alignment);
987   B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
988                 (EncodedAttrs & 0xffff));
989 }
990
991 std::error_code BitcodeReader::ParseAttributeBlock() {
992   if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
993     return Error("Invalid record");
994
995   if (!MAttributes.empty())
996     return Error("Invalid multiple blocks");
997
998   SmallVector<uint64_t, 64> Record;
999
1000   SmallVector<AttributeSet, 8> Attrs;
1001
1002   // Read all the records.
1003   while (1) {
1004     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1005
1006     switch (Entry.Kind) {
1007     case BitstreamEntry::SubBlock: // Handled for us already.
1008     case BitstreamEntry::Error:
1009       return Error("Malformed block");
1010     case BitstreamEntry::EndBlock:
1011       return std::error_code();
1012     case BitstreamEntry::Record:
1013       // The interesting case.
1014       break;
1015     }
1016
1017     // Read a record.
1018     Record.clear();
1019     switch (Stream.readRecord(Entry.ID, Record)) {
1020     default:  // Default behavior: ignore.
1021       break;
1022     case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1023       // FIXME: Remove in 4.0.
1024       if (Record.size() & 1)
1025         return Error("Invalid record");
1026
1027       for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1028         AttrBuilder B;
1029         decodeLLVMAttributesForBitcode(B, Record[i+1]);
1030         Attrs.push_back(AttributeSet::get(Context, Record[i], B));
1031       }
1032
1033       MAttributes.push_back(AttributeSet::get(Context, Attrs));
1034       Attrs.clear();
1035       break;
1036     }
1037     case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1038       for (unsigned i = 0, e = Record.size(); i != e; ++i)
1039         Attrs.push_back(MAttributeGroups[Record[i]]);
1040
1041       MAttributes.push_back(AttributeSet::get(Context, Attrs));
1042       Attrs.clear();
1043       break;
1044     }
1045     }
1046   }
1047 }
1048
1049 // Returns Attribute::None on unrecognized codes.
1050 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
1051   switch (Code) {
1052   default:
1053     return Attribute::None;
1054   case bitc::ATTR_KIND_ALIGNMENT:
1055     return Attribute::Alignment;
1056   case bitc::ATTR_KIND_ALWAYS_INLINE:
1057     return Attribute::AlwaysInline;
1058   case bitc::ATTR_KIND_BUILTIN:
1059     return Attribute::Builtin;
1060   case bitc::ATTR_KIND_BY_VAL:
1061     return Attribute::ByVal;
1062   case bitc::ATTR_KIND_IN_ALLOCA:
1063     return Attribute::InAlloca;
1064   case bitc::ATTR_KIND_COLD:
1065     return Attribute::Cold;
1066   case bitc::ATTR_KIND_INLINE_HINT:
1067     return Attribute::InlineHint;
1068   case bitc::ATTR_KIND_IN_REG:
1069     return Attribute::InReg;
1070   case bitc::ATTR_KIND_JUMP_TABLE:
1071     return Attribute::JumpTable;
1072   case bitc::ATTR_KIND_MIN_SIZE:
1073     return Attribute::MinSize;
1074   case bitc::ATTR_KIND_NAKED:
1075     return Attribute::Naked;
1076   case bitc::ATTR_KIND_NEST:
1077     return Attribute::Nest;
1078   case bitc::ATTR_KIND_NO_ALIAS:
1079     return Attribute::NoAlias;
1080   case bitc::ATTR_KIND_NO_BUILTIN:
1081     return Attribute::NoBuiltin;
1082   case bitc::ATTR_KIND_NO_CAPTURE:
1083     return Attribute::NoCapture;
1084   case bitc::ATTR_KIND_NO_DUPLICATE:
1085     return Attribute::NoDuplicate;
1086   case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1087     return Attribute::NoImplicitFloat;
1088   case bitc::ATTR_KIND_NO_INLINE:
1089     return Attribute::NoInline;
1090   case bitc::ATTR_KIND_NON_LAZY_BIND:
1091     return Attribute::NonLazyBind;
1092   case bitc::ATTR_KIND_NON_NULL:
1093     return Attribute::NonNull;
1094   case bitc::ATTR_KIND_DEREFERENCEABLE:
1095     return Attribute::Dereferenceable;
1096   case bitc::ATTR_KIND_NO_RED_ZONE:
1097     return Attribute::NoRedZone;
1098   case bitc::ATTR_KIND_NO_RETURN:
1099     return Attribute::NoReturn;
1100   case bitc::ATTR_KIND_NO_UNWIND:
1101     return Attribute::NoUnwind;
1102   case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1103     return Attribute::OptimizeForSize;
1104   case bitc::ATTR_KIND_OPTIMIZE_NONE:
1105     return Attribute::OptimizeNone;
1106   case bitc::ATTR_KIND_READ_NONE:
1107     return Attribute::ReadNone;
1108   case bitc::ATTR_KIND_READ_ONLY:
1109     return Attribute::ReadOnly;
1110   case bitc::ATTR_KIND_RETURNED:
1111     return Attribute::Returned;
1112   case bitc::ATTR_KIND_RETURNS_TWICE:
1113     return Attribute::ReturnsTwice;
1114   case bitc::ATTR_KIND_S_EXT:
1115     return Attribute::SExt;
1116   case bitc::ATTR_KIND_STACK_ALIGNMENT:
1117     return Attribute::StackAlignment;
1118   case bitc::ATTR_KIND_STACK_PROTECT:
1119     return Attribute::StackProtect;
1120   case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1121     return Attribute::StackProtectReq;
1122   case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1123     return Attribute::StackProtectStrong;
1124   case bitc::ATTR_KIND_STRUCT_RET:
1125     return Attribute::StructRet;
1126   case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1127     return Attribute::SanitizeAddress;
1128   case bitc::ATTR_KIND_SANITIZE_THREAD:
1129     return Attribute::SanitizeThread;
1130   case bitc::ATTR_KIND_SANITIZE_MEMORY:
1131     return Attribute::SanitizeMemory;
1132   case bitc::ATTR_KIND_UW_TABLE:
1133     return Attribute::UWTable;
1134   case bitc::ATTR_KIND_Z_EXT:
1135     return Attribute::ZExt;
1136   }
1137 }
1138
1139 std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1140                                                    unsigned &Alignment) {
1141   // Note: Alignment in bitcode files is incremented by 1, so that zero
1142   // can be used for default alignment.
1143   if (Exponent > Value::MaxAlignmentExponent + 1)
1144     return Error("Invalid alignment value");
1145   Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1146   return std::error_code();
1147 }
1148
1149 std::error_code BitcodeReader::ParseAttrKind(uint64_t Code,
1150                                              Attribute::AttrKind *Kind) {
1151   *Kind = GetAttrFromCode(Code);
1152   if (*Kind == Attribute::None)
1153     return Error(BitcodeError::CorruptedBitcode,
1154                  "Unknown attribute kind (" + Twine(Code) + ")");
1155   return std::error_code();
1156 }
1157
1158 std::error_code BitcodeReader::ParseAttributeGroupBlock() {
1159   if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
1160     return Error("Invalid record");
1161
1162   if (!MAttributeGroups.empty())
1163     return Error("Invalid multiple blocks");
1164
1165   SmallVector<uint64_t, 64> Record;
1166
1167   // Read all the records.
1168   while (1) {
1169     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1170
1171     switch (Entry.Kind) {
1172     case BitstreamEntry::SubBlock: // Handled for us already.
1173     case BitstreamEntry::Error:
1174       return Error("Malformed block");
1175     case BitstreamEntry::EndBlock:
1176       return std::error_code();
1177     case BitstreamEntry::Record:
1178       // The interesting case.
1179       break;
1180     }
1181
1182     // Read a record.
1183     Record.clear();
1184     switch (Stream.readRecord(Entry.ID, Record)) {
1185     default:  // Default behavior: ignore.
1186       break;
1187     case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1188       if (Record.size() < 3)
1189         return Error("Invalid record");
1190
1191       uint64_t GrpID = Record[0];
1192       uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1193
1194       AttrBuilder B;
1195       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1196         if (Record[i] == 0) {        // Enum attribute
1197           Attribute::AttrKind Kind;
1198           if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
1199             return EC;
1200
1201           B.addAttribute(Kind);
1202         } else if (Record[i] == 1) { // Integer attribute
1203           Attribute::AttrKind Kind;
1204           if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
1205             return EC;
1206           if (Kind == Attribute::Alignment)
1207             B.addAlignmentAttr(Record[++i]);
1208           else if (Kind == Attribute::StackAlignment)
1209             B.addStackAlignmentAttr(Record[++i]);
1210           else if (Kind == Attribute::Dereferenceable)
1211             B.addDereferenceableAttr(Record[++i]);
1212         } else {                     // String attribute
1213           assert((Record[i] == 3 || Record[i] == 4) &&
1214                  "Invalid attribute group entry");
1215           bool HasValue = (Record[i++] == 4);
1216           SmallString<64> KindStr;
1217           SmallString<64> ValStr;
1218
1219           while (Record[i] != 0 && i != e)
1220             KindStr += Record[i++];
1221           assert(Record[i] == 0 && "Kind string not null terminated");
1222
1223           if (HasValue) {
1224             // Has a value associated with it.
1225             ++i; // Skip the '0' that terminates the "kind" string.
1226             while (Record[i] != 0 && i != e)
1227               ValStr += Record[i++];
1228             assert(Record[i] == 0 && "Value string not null terminated");
1229           }
1230
1231           B.addAttribute(KindStr.str(), ValStr.str());
1232         }
1233       }
1234
1235       MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
1236       break;
1237     }
1238     }
1239   }
1240 }
1241
1242 std::error_code BitcodeReader::ParseTypeTable() {
1243   if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
1244     return Error("Invalid record");
1245
1246   return ParseTypeTableBody();
1247 }
1248
1249 std::error_code BitcodeReader::ParseTypeTableBody() {
1250   if (!TypeList.empty())
1251     return Error("Invalid multiple blocks");
1252
1253   SmallVector<uint64_t, 64> Record;
1254   unsigned NumRecords = 0;
1255
1256   SmallString<64> TypeName;
1257
1258   // Read all the records for this type table.
1259   while (1) {
1260     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1261
1262     switch (Entry.Kind) {
1263     case BitstreamEntry::SubBlock: // Handled for us already.
1264     case BitstreamEntry::Error:
1265       return Error("Malformed block");
1266     case BitstreamEntry::EndBlock:
1267       if (NumRecords != TypeList.size())
1268         return Error("Malformed block");
1269       return std::error_code();
1270     case BitstreamEntry::Record:
1271       // The interesting case.
1272       break;
1273     }
1274
1275     // Read a record.
1276     Record.clear();
1277     Type *ResultTy = nullptr;
1278     switch (Stream.readRecord(Entry.ID, Record)) {
1279     default:
1280       return Error("Invalid value");
1281     case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1282       // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1283       // type list.  This allows us to reserve space.
1284       if (Record.size() < 1)
1285         return Error("Invalid record");
1286       TypeList.resize(Record[0]);
1287       continue;
1288     case bitc::TYPE_CODE_VOID:      // VOID
1289       ResultTy = Type::getVoidTy(Context);
1290       break;
1291     case bitc::TYPE_CODE_HALF:     // HALF
1292       ResultTy = Type::getHalfTy(Context);
1293       break;
1294     case bitc::TYPE_CODE_FLOAT:     // FLOAT
1295       ResultTy = Type::getFloatTy(Context);
1296       break;
1297     case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
1298       ResultTy = Type::getDoubleTy(Context);
1299       break;
1300     case bitc::TYPE_CODE_X86_FP80:  // X86_FP80
1301       ResultTy = Type::getX86_FP80Ty(Context);
1302       break;
1303     case bitc::TYPE_CODE_FP128:     // FP128
1304       ResultTy = Type::getFP128Ty(Context);
1305       break;
1306     case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1307       ResultTy = Type::getPPC_FP128Ty(Context);
1308       break;
1309     case bitc::TYPE_CODE_LABEL:     // LABEL
1310       ResultTy = Type::getLabelTy(Context);
1311       break;
1312     case bitc::TYPE_CODE_METADATA:  // METADATA
1313       ResultTy = Type::getMetadataTy(Context);
1314       break;
1315     case bitc::TYPE_CODE_X86_MMX:   // X86_MMX
1316       ResultTy = Type::getX86_MMXTy(Context);
1317       break;
1318     case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1319       if (Record.size() < 1)
1320         return Error("Invalid record");
1321
1322       uint64_t NumBits = Record[0];
1323       if (NumBits < IntegerType::MIN_INT_BITS ||
1324           NumBits > IntegerType::MAX_INT_BITS)
1325         return Error("Bitwidth for integer type out of range");
1326       ResultTy = IntegerType::get(Context, NumBits);
1327       break;
1328     }
1329     case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1330                                     //          [pointee type, address space]
1331       if (Record.size() < 1)
1332         return Error("Invalid record");
1333       unsigned AddressSpace = 0;
1334       if (Record.size() == 2)
1335         AddressSpace = Record[1];
1336       ResultTy = getTypeByID(Record[0]);
1337       if (!ResultTy)
1338         return Error("Invalid type");
1339       ResultTy = PointerType::get(ResultTy, AddressSpace);
1340       break;
1341     }
1342     case bitc::TYPE_CODE_FUNCTION_OLD: {
1343       // FIXME: attrid is dead, remove it in LLVM 4.0
1344       // FUNCTION: [vararg, attrid, retty, paramty x N]
1345       if (Record.size() < 3)
1346         return Error("Invalid record");
1347       SmallVector<Type*, 8> ArgTys;
1348       for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1349         if (Type *T = getTypeByID(Record[i]))
1350           ArgTys.push_back(T);
1351         else
1352           break;
1353       }
1354
1355       ResultTy = getTypeByID(Record[2]);
1356       if (!ResultTy || ArgTys.size() < Record.size()-3)
1357         return Error("Invalid type");
1358
1359       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1360       break;
1361     }
1362     case bitc::TYPE_CODE_FUNCTION: {
1363       // FUNCTION: [vararg, retty, paramty x N]
1364       if (Record.size() < 2)
1365         return Error("Invalid record");
1366       SmallVector<Type*, 8> ArgTys;
1367       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1368         if (Type *T = getTypeByID(Record[i]))
1369           ArgTys.push_back(T);
1370         else
1371           break;
1372       }
1373
1374       ResultTy = getTypeByID(Record[1]);
1375       if (!ResultTy || ArgTys.size() < Record.size()-2)
1376         return Error("Invalid type");
1377
1378       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1379       break;
1380     }
1381     case bitc::TYPE_CODE_STRUCT_ANON: {  // STRUCT: [ispacked, eltty x N]
1382       if (Record.size() < 1)
1383         return Error("Invalid record");
1384       SmallVector<Type*, 8> EltTys;
1385       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1386         if (Type *T = getTypeByID(Record[i]))
1387           EltTys.push_back(T);
1388         else
1389           break;
1390       }
1391       if (EltTys.size() != Record.size()-1)
1392         return Error("Invalid type");
1393       ResultTy = StructType::get(Context, EltTys, Record[0]);
1394       break;
1395     }
1396     case bitc::TYPE_CODE_STRUCT_NAME:   // STRUCT_NAME: [strchr x N]
1397       if (ConvertToString(Record, 0, TypeName))
1398         return Error("Invalid record");
1399       continue;
1400
1401     case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1402       if (Record.size() < 1)
1403         return Error("Invalid record");
1404
1405       if (NumRecords >= TypeList.size())
1406         return Error("Invalid TYPE table");
1407
1408       // Check to see if this was forward referenced, if so fill in the temp.
1409       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1410       if (Res) {
1411         Res->setName(TypeName);
1412         TypeList[NumRecords] = nullptr;
1413       } else  // Otherwise, create a new struct.
1414         Res = createIdentifiedStructType(Context, TypeName);
1415       TypeName.clear();
1416
1417       SmallVector<Type*, 8> EltTys;
1418       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1419         if (Type *T = getTypeByID(Record[i]))
1420           EltTys.push_back(T);
1421         else
1422           break;
1423       }
1424       if (EltTys.size() != Record.size()-1)
1425         return Error("Invalid record");
1426       Res->setBody(EltTys, Record[0]);
1427       ResultTy = Res;
1428       break;
1429     }
1430     case bitc::TYPE_CODE_OPAQUE: {       // OPAQUE: []
1431       if (Record.size() != 1)
1432         return Error("Invalid record");
1433
1434       if (NumRecords >= TypeList.size())
1435         return Error("Invalid TYPE table");
1436
1437       // Check to see if this was forward referenced, if so fill in the temp.
1438       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1439       if (Res) {
1440         Res->setName(TypeName);
1441         TypeList[NumRecords] = nullptr;
1442       } else  // Otherwise, create a new struct with no body.
1443         Res = createIdentifiedStructType(Context, TypeName);
1444       TypeName.clear();
1445       ResultTy = Res;
1446       break;
1447     }
1448     case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
1449       if (Record.size() < 2)
1450         return Error("Invalid record");
1451       if ((ResultTy = getTypeByID(Record[1])))
1452         ResultTy = ArrayType::get(ResultTy, Record[0]);
1453       else
1454         return Error("Invalid type");
1455       break;
1456     case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty]
1457       if (Record.size() < 2)
1458         return Error("Invalid record");
1459       if ((ResultTy = getTypeByID(Record[1])))
1460         ResultTy = VectorType::get(ResultTy, Record[0]);
1461       else
1462         return Error("Invalid type");
1463       break;
1464     }
1465
1466     if (NumRecords >= TypeList.size())
1467       return Error("Invalid TYPE table");
1468     if (TypeList[NumRecords])
1469       return Error(
1470           "Invalid TYPE table: Only named structs can be forward referenced");
1471     assert(ResultTy && "Didn't read a type?");
1472     TypeList[NumRecords++] = ResultTy;
1473   }
1474 }
1475
1476 std::error_code BitcodeReader::ParseValueSymbolTable() {
1477   if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1478     return Error("Invalid record");
1479
1480   SmallVector<uint64_t, 64> Record;
1481
1482   Triple TT(TheModule->getTargetTriple());
1483
1484   // Read all the records for this value table.
1485   SmallString<128> ValueName;
1486   while (1) {
1487     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1488
1489     switch (Entry.Kind) {
1490     case BitstreamEntry::SubBlock: // Handled for us already.
1491     case BitstreamEntry::Error:
1492       return Error("Malformed block");
1493     case BitstreamEntry::EndBlock:
1494       return std::error_code();
1495     case BitstreamEntry::Record:
1496       // The interesting case.
1497       break;
1498     }
1499
1500     // Read a record.
1501     Record.clear();
1502     switch (Stream.readRecord(Entry.ID, Record)) {
1503     default:  // Default behavior: unknown type.
1504       break;
1505     case bitc::VST_CODE_ENTRY: {  // VST_ENTRY: [valueid, namechar x N]
1506       if (ConvertToString(Record, 1, ValueName))
1507         return Error("Invalid record");
1508       unsigned ValueID = Record[0];
1509       if (ValueID >= ValueList.size() || !ValueList[ValueID])
1510         return Error("Invalid record");
1511       Value *V = ValueList[ValueID];
1512
1513       V->setName(StringRef(ValueName.data(), ValueName.size()));
1514       if (auto *GO = dyn_cast<GlobalObject>(V)) {
1515         if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1516           if (TT.isOSBinFormatMachO())
1517             GO->setComdat(nullptr);
1518           else
1519             GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1520         }
1521       }
1522       ValueName.clear();
1523       break;
1524     }
1525     case bitc::VST_CODE_BBENTRY: {
1526       if (ConvertToString(Record, 1, ValueName))
1527         return Error("Invalid record");
1528       BasicBlock *BB = getBasicBlock(Record[0]);
1529       if (!BB)
1530         return Error("Invalid record");
1531
1532       BB->setName(StringRef(ValueName.data(), ValueName.size()));
1533       ValueName.clear();
1534       break;
1535     }
1536     }
1537   }
1538 }
1539
1540 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1541
1542 std::error_code BitcodeReader::ParseMetadata() {
1543   IsMetadataMaterialized = true;
1544   unsigned NextMDValueNo = MDValueList.size();
1545
1546   if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1547     return Error("Invalid record");
1548
1549   SmallVector<uint64_t, 64> Record;
1550
1551   auto getMD =
1552       [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
1553   auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1554     if (ID)
1555       return getMD(ID - 1);
1556     return nullptr;
1557   };
1558   auto getMDString = [&](unsigned ID) -> MDString *{
1559     // This requires that the ID is not really a forward reference.  In
1560     // particular, the MDString must already have been resolved.
1561     return cast_or_null<MDString>(getMDOrNull(ID));
1562   };
1563
1564 #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS)                                 \
1565   (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1566
1567   // Read all the records.
1568   while (1) {
1569     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1570
1571     switch (Entry.Kind) {
1572     case BitstreamEntry::SubBlock: // Handled for us already.
1573     case BitstreamEntry::Error:
1574       return Error("Malformed block");
1575     case BitstreamEntry::EndBlock:
1576       MDValueList.tryToResolveCycles();
1577       return std::error_code();
1578     case BitstreamEntry::Record:
1579       // The interesting case.
1580       break;
1581     }
1582
1583     // Read a record.
1584     Record.clear();
1585     unsigned Code = Stream.readRecord(Entry.ID, Record);
1586     bool IsDistinct = false;
1587     switch (Code) {
1588     default:  // Default behavior: ignore.
1589       break;
1590     case bitc::METADATA_NAME: {
1591       // Read name of the named metadata.
1592       SmallString<8> Name(Record.begin(), Record.end());
1593       Record.clear();
1594       Code = Stream.ReadCode();
1595
1596       // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1597       unsigned NextBitCode = Stream.readRecord(Code, Record);
1598       assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1599
1600       // Read named metadata elements.
1601       unsigned Size = Record.size();
1602       NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1603       for (unsigned i = 0; i != Size; ++i) {
1604         MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1605         if (!MD)
1606           return Error("Invalid record");
1607         NMD->addOperand(MD);
1608       }
1609       break;
1610     }
1611     case bitc::METADATA_OLD_FN_NODE: {
1612       // FIXME: Remove in 4.0.
1613       // This is a LocalAsMetadata record, the only type of function-local
1614       // metadata.
1615       if (Record.size() % 2 == 1)
1616         return Error("Invalid record");
1617
1618       // If this isn't a LocalAsMetadata record, we're dropping it.  This used
1619       // to be legal, but there's no upgrade path.
1620       auto dropRecord = [&] {
1621         MDValueList.AssignValue(MDNode::get(Context, None), NextMDValueNo++);
1622       };
1623       if (Record.size() != 2) {
1624         dropRecord();
1625         break;
1626       }
1627
1628       Type *Ty = getTypeByID(Record[0]);
1629       if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1630         dropRecord();
1631         break;
1632       }
1633
1634       MDValueList.AssignValue(
1635           LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1636           NextMDValueNo++);
1637       break;
1638     }
1639     case bitc::METADATA_OLD_NODE: {
1640       // FIXME: Remove in 4.0.
1641       if (Record.size() % 2 == 1)
1642         return Error("Invalid record");
1643
1644       unsigned Size = Record.size();
1645       SmallVector<Metadata *, 8> Elts;
1646       for (unsigned i = 0; i != Size; i += 2) {
1647         Type *Ty = getTypeByID(Record[i]);
1648         if (!Ty)
1649           return Error("Invalid record");
1650         if (Ty->isMetadataTy())
1651           Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1652         else if (!Ty->isVoidTy()) {
1653           auto *MD =
1654               ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1655           assert(isa<ConstantAsMetadata>(MD) &&
1656                  "Expected non-function-local metadata");
1657           Elts.push_back(MD);
1658         } else
1659           Elts.push_back(nullptr);
1660       }
1661       MDValueList.AssignValue(MDNode::get(Context, Elts), NextMDValueNo++);
1662       break;
1663     }
1664     case bitc::METADATA_VALUE: {
1665       if (Record.size() != 2)
1666         return Error("Invalid record");
1667
1668       Type *Ty = getTypeByID(Record[0]);
1669       if (Ty->isMetadataTy() || Ty->isVoidTy())
1670         return Error("Invalid record");
1671
1672       MDValueList.AssignValue(
1673           ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1674           NextMDValueNo++);
1675       break;
1676     }
1677     case bitc::METADATA_DISTINCT_NODE:
1678       IsDistinct = true;
1679       // fallthrough...
1680     case bitc::METADATA_NODE: {
1681       SmallVector<Metadata *, 8> Elts;
1682       Elts.reserve(Record.size());
1683       for (unsigned ID : Record)
1684         Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
1685       MDValueList.AssignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1686                                          : MDNode::get(Context, Elts),
1687                               NextMDValueNo++);
1688       break;
1689     }
1690     case bitc::METADATA_LOCATION: {
1691       if (Record.size() != 5)
1692         return Error("Invalid record");
1693
1694       auto get = Record[0] ? MDLocation::getDistinct : MDLocation::get;
1695       unsigned Line = Record[1];
1696       unsigned Column = Record[2];
1697       MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
1698       Metadata *InlinedAt =
1699           Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
1700       MDValueList.AssignValue(get(Context, Line, Column, Scope, InlinedAt),
1701                               NextMDValueNo++);
1702       break;
1703     }
1704     case bitc::METADATA_GENERIC_DEBUG: {
1705       if (Record.size() < 4)
1706         return Error("Invalid record");
1707
1708       unsigned Tag = Record[1];
1709       unsigned Version = Record[2];
1710
1711       if (Tag >= 1u << 16 || Version != 0)
1712         return Error("Invalid record");
1713
1714       auto *Header = getMDString(Record[3]);
1715       SmallVector<Metadata *, 8> DwarfOps;
1716       for (unsigned I = 4, E = Record.size(); I != E; ++I)
1717         DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
1718                                      : nullptr);
1719       MDValueList.AssignValue(GET_OR_DISTINCT(GenericDebugNode, Record[0],
1720                                               (Context, Tag, Header, DwarfOps)),
1721                               NextMDValueNo++);
1722       break;
1723     }
1724     case bitc::METADATA_SUBRANGE: {
1725       if (Record.size() != 3)
1726         return Error("Invalid record");
1727
1728       MDValueList.AssignValue(
1729           GET_OR_DISTINCT(MDSubrange, Record[0],
1730                           (Context, Record[1], unrotateSign(Record[2]))),
1731           NextMDValueNo++);
1732       break;
1733     }
1734     case bitc::METADATA_ENUMERATOR: {
1735       if (Record.size() != 3)
1736         return Error("Invalid record");
1737
1738       MDValueList.AssignValue(GET_OR_DISTINCT(MDEnumerator, Record[0],
1739                                               (Context, unrotateSign(Record[1]),
1740                                                getMDString(Record[2]))),
1741                               NextMDValueNo++);
1742       break;
1743     }
1744     case bitc::METADATA_BASIC_TYPE: {
1745       if (Record.size() != 6)
1746         return Error("Invalid record");
1747
1748       MDValueList.AssignValue(
1749           GET_OR_DISTINCT(MDBasicType, Record[0],
1750                           (Context, Record[1], getMDString(Record[2]),
1751                            Record[3], Record[4], Record[5])),
1752           NextMDValueNo++);
1753       break;
1754     }
1755     case bitc::METADATA_DERIVED_TYPE: {
1756       if (Record.size() != 12)
1757         return Error("Invalid record");
1758
1759       MDValueList.AssignValue(
1760           GET_OR_DISTINCT(MDDerivedType, Record[0],
1761                           (Context, Record[1], getMDString(Record[2]),
1762                            getMDOrNull(Record[3]), Record[4],
1763                            getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1764                            Record[7], Record[8], Record[9], Record[10],
1765                            getMDOrNull(Record[11]))),
1766           NextMDValueNo++);
1767       break;
1768     }
1769     case bitc::METADATA_COMPOSITE_TYPE: {
1770       if (Record.size() != 16)
1771         return Error("Invalid record");
1772
1773       MDValueList.AssignValue(
1774           GET_OR_DISTINCT(MDCompositeType, Record[0],
1775                           (Context, Record[1], getMDString(Record[2]),
1776                            getMDOrNull(Record[3]), Record[4],
1777                            getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1778                            Record[7], Record[8], Record[9], Record[10],
1779                            getMDOrNull(Record[11]), Record[12],
1780                            getMDOrNull(Record[13]), getMDOrNull(Record[14]),
1781                            getMDString(Record[15]))),
1782           NextMDValueNo++);
1783       break;
1784     }
1785     case bitc::METADATA_SUBROUTINE_TYPE: {
1786       if (Record.size() != 3)
1787         return Error("Invalid record");
1788
1789       MDValueList.AssignValue(
1790           GET_OR_DISTINCT(MDSubroutineType, Record[0],
1791                           (Context, Record[1], getMDOrNull(Record[2]))),
1792           NextMDValueNo++);
1793       break;
1794     }
1795     case bitc::METADATA_FILE: {
1796       if (Record.size() != 3)
1797         return Error("Invalid record");
1798
1799       MDValueList.AssignValue(
1800           GET_OR_DISTINCT(MDFile, Record[0], (Context, getMDString(Record[1]),
1801                                               getMDString(Record[2]))),
1802           NextMDValueNo++);
1803       break;
1804     }
1805     case bitc::METADATA_COMPILE_UNIT: {
1806       if (Record.size() != 14)
1807         return Error("Invalid record");
1808
1809       MDValueList.AssignValue(
1810           GET_OR_DISTINCT(MDCompileUnit, Record[0],
1811                           (Context, Record[1], getMDOrNull(Record[2]),
1812                            getMDString(Record[3]), Record[4],
1813                            getMDString(Record[5]), Record[6],
1814                            getMDString(Record[7]), Record[8],
1815                            getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1816                            getMDOrNull(Record[11]), getMDOrNull(Record[12]),
1817                            getMDOrNull(Record[13]))),
1818           NextMDValueNo++);
1819       break;
1820     }
1821     case bitc::METADATA_SUBPROGRAM: {
1822       if (Record.size() != 19)
1823         return Error("Invalid record");
1824
1825       MDValueList.AssignValue(
1826           GET_OR_DISTINCT(
1827               MDSubprogram, Record[0],
1828               (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1829                getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1830                getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
1831                getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
1832                Record[14], getMDOrNull(Record[15]), getMDOrNull(Record[16]),
1833                getMDOrNull(Record[17]), getMDOrNull(Record[18]))),
1834           NextMDValueNo++);
1835       break;
1836     }
1837     case bitc::METADATA_LEXICAL_BLOCK: {
1838       if (Record.size() != 5)
1839         return Error("Invalid record");
1840
1841       MDValueList.AssignValue(
1842           GET_OR_DISTINCT(MDLexicalBlock, Record[0],
1843                           (Context, getMDOrNull(Record[1]),
1844                            getMDOrNull(Record[2]), Record[3], Record[4])),
1845           NextMDValueNo++);
1846       break;
1847     }
1848     case bitc::METADATA_LEXICAL_BLOCK_FILE: {
1849       if (Record.size() != 4)
1850         return Error("Invalid record");
1851
1852       MDValueList.AssignValue(
1853           GET_OR_DISTINCT(MDLexicalBlockFile, Record[0],
1854                           (Context, getMDOrNull(Record[1]),
1855                            getMDOrNull(Record[2]), Record[3])),
1856           NextMDValueNo++);
1857       break;
1858     }
1859     case bitc::METADATA_NAMESPACE: {
1860       if (Record.size() != 5)
1861         return Error("Invalid record");
1862
1863       MDValueList.AssignValue(
1864           GET_OR_DISTINCT(MDNamespace, Record[0],
1865                           (Context, getMDOrNull(Record[1]),
1866                            getMDOrNull(Record[2]), getMDString(Record[3]),
1867                            Record[4])),
1868           NextMDValueNo++);
1869       break;
1870     }
1871     case bitc::METADATA_TEMPLATE_TYPE: {
1872       if (Record.size() != 3)
1873         return Error("Invalid record");
1874
1875       MDValueList.AssignValue(GET_OR_DISTINCT(MDTemplateTypeParameter,
1876                                               Record[0],
1877                                               (Context, getMDString(Record[1]),
1878                                                getMDOrNull(Record[2]))),
1879                               NextMDValueNo++);
1880       break;
1881     }
1882     case bitc::METADATA_TEMPLATE_VALUE: {
1883       if (Record.size() != 5)
1884         return Error("Invalid record");
1885
1886       MDValueList.AssignValue(
1887           GET_OR_DISTINCT(MDTemplateValueParameter, Record[0],
1888                           (Context, Record[1], getMDString(Record[2]),
1889                            getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
1890           NextMDValueNo++);
1891       break;
1892     }
1893     case bitc::METADATA_GLOBAL_VAR: {
1894       if (Record.size() != 11)
1895         return Error("Invalid record");
1896
1897       MDValueList.AssignValue(
1898           GET_OR_DISTINCT(MDGlobalVariable, Record[0],
1899                           (Context, getMDOrNull(Record[1]),
1900                            getMDString(Record[2]), getMDString(Record[3]),
1901                            getMDOrNull(Record[4]), Record[5],
1902                            getMDOrNull(Record[6]), Record[7], Record[8],
1903                            getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
1904           NextMDValueNo++);
1905       break;
1906     }
1907     case bitc::METADATA_LOCAL_VAR: {
1908       if (Record.size() != 10)
1909         return Error("Invalid record");
1910
1911       MDValueList.AssignValue(
1912           GET_OR_DISTINCT(MDLocalVariable, Record[0],
1913                           (Context, Record[1], getMDOrNull(Record[2]),
1914                            getMDString(Record[3]), getMDOrNull(Record[4]),
1915                            Record[5], getMDOrNull(Record[6]), Record[7],
1916                            Record[8], getMDOrNull(Record[9]))),
1917           NextMDValueNo++);
1918       break;
1919     }
1920     case bitc::METADATA_EXPRESSION: {
1921       if (Record.size() < 1)
1922         return Error("Invalid record");
1923
1924       MDValueList.AssignValue(
1925           GET_OR_DISTINCT(MDExpression, Record[0],
1926                           (Context, makeArrayRef(Record).slice(1))),
1927           NextMDValueNo++);
1928       break;
1929     }
1930     case bitc::METADATA_OBJC_PROPERTY: {
1931       if (Record.size() != 8)
1932         return Error("Invalid record");
1933
1934       MDValueList.AssignValue(
1935           GET_OR_DISTINCT(MDObjCProperty, Record[0],
1936                           (Context, getMDString(Record[1]),
1937                            getMDOrNull(Record[2]), Record[3],
1938                            getMDString(Record[4]), getMDString(Record[5]),
1939                            Record[6], getMDOrNull(Record[7]))),
1940           NextMDValueNo++);
1941       break;
1942     }
1943     case bitc::METADATA_IMPORTED_ENTITY: {
1944       if (Record.size() != 6)
1945         return Error("Invalid record");
1946
1947       MDValueList.AssignValue(
1948           GET_OR_DISTINCT(MDImportedEntity, Record[0],
1949                           (Context, Record[1], getMDOrNull(Record[2]),
1950                            getMDOrNull(Record[3]), Record[4],
1951                            getMDString(Record[5]))),
1952           NextMDValueNo++);
1953       break;
1954     }
1955     case bitc::METADATA_STRING: {
1956       std::string String(Record.begin(), Record.end());
1957       llvm::UpgradeMDStringConstant(String);
1958       Metadata *MD = MDString::get(Context, String);
1959       MDValueList.AssignValue(MD, NextMDValueNo++);
1960       break;
1961     }
1962     case bitc::METADATA_KIND: {
1963       if (Record.size() < 2)
1964         return Error("Invalid record");
1965
1966       unsigned Kind = Record[0];
1967       SmallString<8> Name(Record.begin()+1, Record.end());
1968
1969       unsigned NewKind = TheModule->getMDKindID(Name.str());
1970       if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1971         return Error("Conflicting METADATA_KIND records");
1972       break;
1973     }
1974     }
1975   }
1976 #undef GET_OR_DISTINCT
1977 }
1978
1979 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1980 /// the LSB for dense VBR encoding.
1981 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1982   if ((V & 1) == 0)
1983     return V >> 1;
1984   if (V != 1)
1985     return -(V >> 1);
1986   // There is no such thing as -0 with integers.  "-0" really means MININT.
1987   return 1ULL << 63;
1988 }
1989
1990 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1991 /// values and aliases that we can.
1992 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
1993   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1994   std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1995   std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1996   std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
1997
1998   GlobalInitWorklist.swap(GlobalInits);
1999   AliasInitWorklist.swap(AliasInits);
2000   FunctionPrefixWorklist.swap(FunctionPrefixes);
2001   FunctionPrologueWorklist.swap(FunctionPrologues);
2002
2003   while (!GlobalInitWorklist.empty()) {
2004     unsigned ValID = GlobalInitWorklist.back().second;
2005     if (ValID >= ValueList.size()) {
2006       // Not ready to resolve this yet, it requires something later in the file.
2007       GlobalInits.push_back(GlobalInitWorklist.back());
2008     } else {
2009       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2010         GlobalInitWorklist.back().first->setInitializer(C);
2011       else
2012         return Error("Expected a constant");
2013     }
2014     GlobalInitWorklist.pop_back();
2015   }
2016
2017   while (!AliasInitWorklist.empty()) {
2018     unsigned ValID = AliasInitWorklist.back().second;
2019     if (ValID >= ValueList.size()) {
2020       AliasInits.push_back(AliasInitWorklist.back());
2021     } else {
2022       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2023         AliasInitWorklist.back().first->setAliasee(C);
2024       else
2025         return Error("Expected a constant");
2026     }
2027     AliasInitWorklist.pop_back();
2028   }
2029
2030   while (!FunctionPrefixWorklist.empty()) {
2031     unsigned ValID = FunctionPrefixWorklist.back().second;
2032     if (ValID >= ValueList.size()) {
2033       FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2034     } else {
2035       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2036         FunctionPrefixWorklist.back().first->setPrefixData(C);
2037       else
2038         return Error("Expected a constant");
2039     }
2040     FunctionPrefixWorklist.pop_back();
2041   }
2042
2043   while (!FunctionPrologueWorklist.empty()) {
2044     unsigned ValID = FunctionPrologueWorklist.back().second;
2045     if (ValID >= ValueList.size()) {
2046       FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2047     } else {
2048       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2049         FunctionPrologueWorklist.back().first->setPrologueData(C);
2050       else
2051         return Error("Expected a constant");
2052     }
2053     FunctionPrologueWorklist.pop_back();
2054   }
2055
2056   return std::error_code();
2057 }
2058
2059 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2060   SmallVector<uint64_t, 8> Words(Vals.size());
2061   std::transform(Vals.begin(), Vals.end(), Words.begin(),
2062                  BitcodeReader::decodeSignRotatedValue);
2063
2064   return APInt(TypeBits, Words);
2065 }
2066
2067 std::error_code BitcodeReader::ParseConstants() {
2068   if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2069     return Error("Invalid record");
2070
2071   SmallVector<uint64_t, 64> Record;
2072
2073   // Read all the records for this value table.
2074   Type *CurTy = Type::getInt32Ty(Context);
2075   unsigned NextCstNo = ValueList.size();
2076   while (1) {
2077     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2078
2079     switch (Entry.Kind) {
2080     case BitstreamEntry::SubBlock: // Handled for us already.
2081     case BitstreamEntry::Error:
2082       return Error("Malformed block");
2083     case BitstreamEntry::EndBlock:
2084       if (NextCstNo != ValueList.size())
2085         return Error("Invalid ronstant reference");
2086
2087       // Once all the constants have been read, go through and resolve forward
2088       // references.
2089       ValueList.ResolveConstantForwardRefs();
2090       return std::error_code();
2091     case BitstreamEntry::Record:
2092       // The interesting case.
2093       break;
2094     }
2095
2096     // Read a record.
2097     Record.clear();
2098     Value *V = nullptr;
2099     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2100     switch (BitCode) {
2101     default:  // Default behavior: unknown constant
2102     case bitc::CST_CODE_UNDEF:     // UNDEF
2103       V = UndefValue::get(CurTy);
2104       break;
2105     case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
2106       if (Record.empty())
2107         return Error("Invalid record");
2108       if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2109         return Error("Invalid record");
2110       CurTy = TypeList[Record[0]];
2111       continue;  // Skip the ValueList manipulation.
2112     case bitc::CST_CODE_NULL:      // NULL
2113       V = Constant::getNullValue(CurTy);
2114       break;
2115     case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
2116       if (!CurTy->isIntegerTy() || Record.empty())
2117         return Error("Invalid record");
2118       V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2119       break;
2120     case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2121       if (!CurTy->isIntegerTy() || Record.empty())
2122         return Error("Invalid record");
2123
2124       APInt VInt = ReadWideAPInt(Record,
2125                                  cast<IntegerType>(CurTy)->getBitWidth());
2126       V = ConstantInt::get(Context, VInt);
2127
2128       break;
2129     }
2130     case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
2131       if (Record.empty())
2132         return Error("Invalid record");
2133       if (CurTy->isHalfTy())
2134         V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2135                                              APInt(16, (uint16_t)Record[0])));
2136       else if (CurTy->isFloatTy())
2137         V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2138                                              APInt(32, (uint32_t)Record[0])));
2139       else if (CurTy->isDoubleTy())
2140         V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2141                                              APInt(64, Record[0])));
2142       else if (CurTy->isX86_FP80Ty()) {
2143         // Bits are not stored the same way as a normal i80 APInt, compensate.
2144         uint64_t Rearrange[2];
2145         Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2146         Rearrange[1] = Record[0] >> 48;
2147         V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2148                                              APInt(80, Rearrange)));
2149       } else if (CurTy->isFP128Ty())
2150         V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2151                                              APInt(128, Record)));
2152       else if (CurTy->isPPC_FP128Ty())
2153         V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2154                                              APInt(128, Record)));
2155       else
2156         V = UndefValue::get(CurTy);
2157       break;
2158     }
2159
2160     case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2161       if (Record.empty())
2162         return Error("Invalid record");
2163
2164       unsigned Size = Record.size();
2165       SmallVector<Constant*, 16> Elts;
2166
2167       if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2168         for (unsigned i = 0; i != Size; ++i)
2169           Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2170                                                      STy->getElementType(i)));
2171         V = ConstantStruct::get(STy, Elts);
2172       } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2173         Type *EltTy = ATy->getElementType();
2174         for (unsigned i = 0; i != Size; ++i)
2175           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2176         V = ConstantArray::get(ATy, Elts);
2177       } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2178         Type *EltTy = VTy->getElementType();
2179         for (unsigned i = 0; i != Size; ++i)
2180           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2181         V = ConstantVector::get(Elts);
2182       } else {
2183         V = UndefValue::get(CurTy);
2184       }
2185       break;
2186     }
2187     case bitc::CST_CODE_STRING:    // STRING: [values]
2188     case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2189       if (Record.empty())
2190         return Error("Invalid record");
2191
2192       SmallString<16> Elts(Record.begin(), Record.end());
2193       V = ConstantDataArray::getString(Context, Elts,
2194                                        BitCode == bitc::CST_CODE_CSTRING);
2195       break;
2196     }
2197     case bitc::CST_CODE_DATA: {// DATA: [n x value]
2198       if (Record.empty())
2199         return Error("Invalid record");
2200
2201       Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2202       unsigned Size = Record.size();
2203
2204       if (EltTy->isIntegerTy(8)) {
2205         SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2206         if (isa<VectorType>(CurTy))
2207           V = ConstantDataVector::get(Context, Elts);
2208         else
2209           V = ConstantDataArray::get(Context, Elts);
2210       } else if (EltTy->isIntegerTy(16)) {
2211         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2212         if (isa<VectorType>(CurTy))
2213           V = ConstantDataVector::get(Context, Elts);
2214         else
2215           V = ConstantDataArray::get(Context, Elts);
2216       } else if (EltTy->isIntegerTy(32)) {
2217         SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2218         if (isa<VectorType>(CurTy))
2219           V = ConstantDataVector::get(Context, Elts);
2220         else
2221           V = ConstantDataArray::get(Context, Elts);
2222       } else if (EltTy->isIntegerTy(64)) {
2223         SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2224         if (isa<VectorType>(CurTy))
2225           V = ConstantDataVector::get(Context, Elts);
2226         else
2227           V = ConstantDataArray::get(Context, Elts);
2228       } else if (EltTy->isFloatTy()) {
2229         SmallVector<float, 16> Elts(Size);
2230         std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
2231         if (isa<VectorType>(CurTy))
2232           V = ConstantDataVector::get(Context, Elts);
2233         else
2234           V = ConstantDataArray::get(Context, Elts);
2235       } else if (EltTy->isDoubleTy()) {
2236         SmallVector<double, 16> Elts(Size);
2237         std::transform(Record.begin(), Record.end(), Elts.begin(),
2238                        BitsToDouble);
2239         if (isa<VectorType>(CurTy))
2240           V = ConstantDataVector::get(Context, Elts);
2241         else
2242           V = ConstantDataArray::get(Context, Elts);
2243       } else {
2244         return Error("Invalid type for value");
2245       }
2246       break;
2247     }
2248
2249     case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
2250       if (Record.size() < 3)
2251         return Error("Invalid record");
2252       int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
2253       if (Opc < 0) {
2254         V = UndefValue::get(CurTy);  // Unknown binop.
2255       } else {
2256         Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2257         Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2258         unsigned Flags = 0;
2259         if (Record.size() >= 4) {
2260           if (Opc == Instruction::Add ||
2261               Opc == Instruction::Sub ||
2262               Opc == Instruction::Mul ||
2263               Opc == Instruction::Shl) {
2264             if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2265               Flags |= OverflowingBinaryOperator::NoSignedWrap;
2266             if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2267               Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2268           } else if (Opc == Instruction::SDiv ||
2269                      Opc == Instruction::UDiv ||
2270                      Opc == Instruction::LShr ||
2271                      Opc == Instruction::AShr) {
2272             if (Record[3] & (1 << bitc::PEO_EXACT))
2273               Flags |= SDivOperator::IsExact;
2274           }
2275         }
2276         V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2277       }
2278       break;
2279     }
2280     case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
2281       if (Record.size() < 3)
2282         return Error("Invalid record");
2283       int Opc = GetDecodedCastOpcode(Record[0]);
2284       if (Opc < 0) {
2285         V = UndefValue::get(CurTy);  // Unknown cast.
2286       } else {
2287         Type *OpTy = getTypeByID(Record[1]);
2288         if (!OpTy)
2289           return Error("Invalid record");
2290         Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2291         V = UpgradeBitCastExpr(Opc, Op, CurTy);
2292         if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2293       }
2294       break;
2295     }
2296     case bitc::CST_CODE_CE_INBOUNDS_GEP:
2297     case bitc::CST_CODE_CE_GEP: {  // CE_GEP:        [n x operands]
2298       unsigned OpNum = 0;
2299       Type *PointeeType = nullptr;
2300       if (Record.size() % 2)
2301         PointeeType = getTypeByID(Record[OpNum++]);
2302       SmallVector<Constant*, 16> Elts;
2303       while (OpNum != Record.size()) {
2304         Type *ElTy = getTypeByID(Record[OpNum++]);
2305         if (!ElTy)
2306           return Error("Invalid record");
2307         Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2308       }
2309
2310       ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2311       V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2312                                          BitCode ==
2313                                            bitc::CST_CODE_CE_INBOUNDS_GEP);
2314       if (PointeeType &&
2315           PointeeType != cast<GEPOperator>(V)->getSourceElementType())
2316         return Error("Explicit gep operator type does not match pointee type "
2317                      "of pointer operand");
2318       break;
2319     }
2320     case bitc::CST_CODE_CE_SELECT: {  // CE_SELECT: [opval#, opval#, opval#]
2321       if (Record.size() < 3)
2322         return Error("Invalid record");
2323
2324       Type *SelectorTy = Type::getInt1Ty(Context);
2325
2326       // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
2327       // vector. Otherwise, it must be a single bit.
2328       if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2329         SelectorTy = VectorType::get(Type::getInt1Ty(Context),
2330                                      VTy->getNumElements());
2331
2332       V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2333                                                               SelectorTy),
2334                                   ValueList.getConstantFwdRef(Record[1],CurTy),
2335                                   ValueList.getConstantFwdRef(Record[2],CurTy));
2336       break;
2337     }
2338     case bitc::CST_CODE_CE_EXTRACTELT
2339         : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2340       if (Record.size() < 3)
2341         return Error("Invalid record");
2342       VectorType *OpTy =
2343         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2344       if (!OpTy)
2345         return Error("Invalid record");
2346       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2347       Constant *Op1 = nullptr;
2348       if (Record.size() == 4) {
2349         Type *IdxTy = getTypeByID(Record[2]);
2350         if (!IdxTy)
2351           return Error("Invalid record");
2352         Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2353       } else // TODO: Remove with llvm 4.0
2354         Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2355       if (!Op1)
2356         return Error("Invalid record");
2357       V = ConstantExpr::getExtractElement(Op0, Op1);
2358       break;
2359     }
2360     case bitc::CST_CODE_CE_INSERTELT
2361         : { // CE_INSERTELT: [opval, opval, opty, opval]
2362       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2363       if (Record.size() < 3 || !OpTy)
2364         return Error("Invalid record");
2365       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2366       Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2367                                                   OpTy->getElementType());
2368       Constant *Op2 = nullptr;
2369       if (Record.size() == 4) {
2370         Type *IdxTy = getTypeByID(Record[2]);
2371         if (!IdxTy)
2372           return Error("Invalid record");
2373         Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2374       } else // TODO: Remove with llvm 4.0
2375         Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2376       if (!Op2)
2377         return Error("Invalid record");
2378       V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2379       break;
2380     }
2381     case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2382       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2383       if (Record.size() < 3 || !OpTy)
2384         return Error("Invalid record");
2385       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2386       Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2387       Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2388                                                  OpTy->getNumElements());
2389       Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2390       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2391       break;
2392     }
2393     case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2394       VectorType *RTy = dyn_cast<VectorType>(CurTy);
2395       VectorType *OpTy =
2396         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2397       if (Record.size() < 4 || !RTy || !OpTy)
2398         return Error("Invalid record");
2399       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2400       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2401       Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2402                                                  RTy->getNumElements());
2403       Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2404       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2405       break;
2406     }
2407     case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
2408       if (Record.size() < 4)
2409         return Error("Invalid record");
2410       Type *OpTy = getTypeByID(Record[0]);
2411       if (!OpTy)
2412         return Error("Invalid record");
2413       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2414       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2415
2416       if (OpTy->isFPOrFPVectorTy())
2417         V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2418       else
2419         V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2420       break;
2421     }
2422     // This maintains backward compatibility, pre-asm dialect keywords.
2423     // FIXME: Remove with the 4.0 release.
2424     case bitc::CST_CODE_INLINEASM_OLD: {
2425       if (Record.size() < 2)
2426         return Error("Invalid record");
2427       std::string AsmStr, ConstrStr;
2428       bool HasSideEffects = Record[0] & 1;
2429       bool IsAlignStack = Record[0] >> 1;
2430       unsigned AsmStrSize = Record[1];
2431       if (2+AsmStrSize >= Record.size())
2432         return Error("Invalid record");
2433       unsigned ConstStrSize = Record[2+AsmStrSize];
2434       if (3+AsmStrSize+ConstStrSize > Record.size())
2435         return Error("Invalid record");
2436
2437       for (unsigned i = 0; i != AsmStrSize; ++i)
2438         AsmStr += (char)Record[2+i];
2439       for (unsigned i = 0; i != ConstStrSize; ++i)
2440         ConstrStr += (char)Record[3+AsmStrSize+i];
2441       PointerType *PTy = cast<PointerType>(CurTy);
2442       V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2443                          AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2444       break;
2445     }
2446     // This version adds support for the asm dialect keywords (e.g.,
2447     // inteldialect).
2448     case bitc::CST_CODE_INLINEASM: {
2449       if (Record.size() < 2)
2450         return Error("Invalid record");
2451       std::string AsmStr, ConstrStr;
2452       bool HasSideEffects = Record[0] & 1;
2453       bool IsAlignStack = (Record[0] >> 1) & 1;
2454       unsigned AsmDialect = Record[0] >> 2;
2455       unsigned AsmStrSize = Record[1];
2456       if (2+AsmStrSize >= Record.size())
2457         return Error("Invalid record");
2458       unsigned ConstStrSize = Record[2+AsmStrSize];
2459       if (3+AsmStrSize+ConstStrSize > Record.size())
2460         return Error("Invalid record");
2461
2462       for (unsigned i = 0; i != AsmStrSize; ++i)
2463         AsmStr += (char)Record[2+i];
2464       for (unsigned i = 0; i != ConstStrSize; ++i)
2465         ConstrStr += (char)Record[3+AsmStrSize+i];
2466       PointerType *PTy = cast<PointerType>(CurTy);
2467       V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2468                          AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2469                          InlineAsm::AsmDialect(AsmDialect));
2470       break;
2471     }
2472     case bitc::CST_CODE_BLOCKADDRESS:{
2473       if (Record.size() < 3)
2474         return Error("Invalid record");
2475       Type *FnTy = getTypeByID(Record[0]);
2476       if (!FnTy)
2477         return Error("Invalid record");
2478       Function *Fn =
2479         dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2480       if (!Fn)
2481         return Error("Invalid record");
2482
2483       // Don't let Fn get dematerialized.
2484       BlockAddressesTaken.insert(Fn);
2485
2486       // If the function is already parsed we can insert the block address right
2487       // away.
2488       BasicBlock *BB;
2489       unsigned BBID = Record[2];
2490       if (!BBID)
2491         // Invalid reference to entry block.
2492         return Error("Invalid ID");
2493       if (!Fn->empty()) {
2494         Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2495         for (size_t I = 0, E = BBID; I != E; ++I) {
2496           if (BBI == BBE)
2497             return Error("Invalid ID");
2498           ++BBI;
2499         }
2500         BB = BBI;
2501       } else {
2502         // Otherwise insert a placeholder and remember it so it can be inserted
2503         // when the function is parsed.
2504         auto &FwdBBs = BasicBlockFwdRefs[Fn];
2505         if (FwdBBs.empty())
2506           BasicBlockFwdRefQueue.push_back(Fn);
2507         if (FwdBBs.size() < BBID + 1)
2508           FwdBBs.resize(BBID + 1);
2509         if (!FwdBBs[BBID])
2510           FwdBBs[BBID] = BasicBlock::Create(Context);
2511         BB = FwdBBs[BBID];
2512       }
2513       V = BlockAddress::get(Fn, BB);
2514       break;
2515     }
2516     }
2517
2518     ValueList.AssignValue(V, NextCstNo);
2519     ++NextCstNo;
2520   }
2521 }
2522
2523 std::error_code BitcodeReader::ParseUseLists() {
2524   if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2525     return Error("Invalid record");
2526
2527   // Read all the records.
2528   SmallVector<uint64_t, 64> Record;
2529   while (1) {
2530     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2531
2532     switch (Entry.Kind) {
2533     case BitstreamEntry::SubBlock: // Handled for us already.
2534     case BitstreamEntry::Error:
2535       return Error("Malformed block");
2536     case BitstreamEntry::EndBlock:
2537       return std::error_code();
2538     case BitstreamEntry::Record:
2539       // The interesting case.
2540       break;
2541     }
2542
2543     // Read a use list record.
2544     Record.clear();
2545     bool IsBB = false;
2546     switch (Stream.readRecord(Entry.ID, Record)) {
2547     default:  // Default behavior: unknown type.
2548       break;
2549     case bitc::USELIST_CODE_BB:
2550       IsBB = true;
2551       // fallthrough
2552     case bitc::USELIST_CODE_DEFAULT: {
2553       unsigned RecordLength = Record.size();
2554       if (RecordLength < 3)
2555         // Records should have at least an ID and two indexes.
2556         return Error("Invalid record");
2557       unsigned ID = Record.back();
2558       Record.pop_back();
2559
2560       Value *V;
2561       if (IsBB) {
2562         assert(ID < FunctionBBs.size() && "Basic block not found");
2563         V = FunctionBBs[ID];
2564       } else
2565         V = ValueList[ID];
2566       unsigned NumUses = 0;
2567       SmallDenseMap<const Use *, unsigned, 16> Order;
2568       for (const Use &U : V->uses()) {
2569         if (++NumUses > Record.size())
2570           break;
2571         Order[&U] = Record[NumUses - 1];
2572       }
2573       if (Order.size() != Record.size() || NumUses > Record.size())
2574         // Mismatches can happen if the functions are being materialized lazily
2575         // (out-of-order), or a value has been upgraded.
2576         break;
2577
2578       V->sortUseList([&](const Use &L, const Use &R) {
2579         return Order.lookup(&L) < Order.lookup(&R);
2580       });
2581       break;
2582     }
2583     }
2584   }
2585 }
2586
2587 /// When we see the block for metadata, remember where it is and then skip it.
2588 /// This lets us lazily deserialize the metadata.
2589 std::error_code BitcodeReader::rememberAndSkipMetadata() {
2590   // Save the current stream state.
2591   uint64_t CurBit = Stream.GetCurrentBitNo();
2592   DeferredMetadataInfo.push_back(CurBit);
2593
2594   // Skip over the block for now.
2595   if (Stream.SkipBlock())
2596     return Error("Invalid record");
2597   return std::error_code();
2598 }
2599
2600 std::error_code BitcodeReader::materializeMetadata() {
2601   for (uint64_t BitPos : DeferredMetadataInfo) {
2602     // Move the bit stream to the saved position.
2603     Stream.JumpToBit(BitPos);
2604     if (std::error_code EC = ParseMetadata())
2605       return EC;
2606   }
2607   DeferredMetadataInfo.clear();
2608   return std::error_code();
2609 }
2610
2611 /// RememberAndSkipFunctionBody - When we see the block for a function body,
2612 /// remember where it is and then skip it.  This lets us lazily deserialize the
2613 /// functions.
2614 std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
2615   // Get the function we are talking about.
2616   if (FunctionsWithBodies.empty())
2617     return Error("Insufficient function protos");
2618
2619   Function *Fn = FunctionsWithBodies.back();
2620   FunctionsWithBodies.pop_back();
2621
2622   // Save the current stream state.
2623   uint64_t CurBit = Stream.GetCurrentBitNo();
2624   DeferredFunctionInfo[Fn] = CurBit;
2625
2626   // Skip over the function block for now.
2627   if (Stream.SkipBlock())
2628     return Error("Invalid record");
2629   return std::error_code();
2630 }
2631
2632 std::error_code BitcodeReader::GlobalCleanup() {
2633   // Patch the initializers for globals and aliases up.
2634   ResolveGlobalAndAliasInits();
2635   if (!GlobalInits.empty() || !AliasInits.empty())
2636     return Error("Malformed global initializer set");
2637
2638   // Look for intrinsic functions which need to be upgraded at some point
2639   for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
2640        FI != FE; ++FI) {
2641     Function *NewFn;
2642     if (UpgradeIntrinsicFunction(FI, NewFn))
2643       UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
2644   }
2645
2646   // Look for global variables which need to be renamed.
2647   for (Module::global_iterator
2648          GI = TheModule->global_begin(), GE = TheModule->global_end();
2649        GI != GE;) {
2650     GlobalVariable *GV = GI++;
2651     UpgradeGlobalVariable(GV);
2652   }
2653
2654   // Force deallocation of memory for these vectors to favor the client that
2655   // want lazy deserialization.
2656   std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
2657   std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
2658   return std::error_code();
2659 }
2660
2661 std::error_code BitcodeReader::ParseModule(bool Resume,
2662                                            bool ShouldLazyLoadMetadata) {
2663   if (Resume)
2664     Stream.JumpToBit(NextUnreadBit);
2665   else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2666     return Error("Invalid record");
2667
2668   SmallVector<uint64_t, 64> Record;
2669   std::vector<std::string> SectionTable;
2670   std::vector<std::string> GCTable;
2671
2672   // Read all the records for this module.
2673   while (1) {
2674     BitstreamEntry Entry = Stream.advance();
2675
2676     switch (Entry.Kind) {
2677     case BitstreamEntry::Error:
2678       return Error("Malformed block");
2679     case BitstreamEntry::EndBlock:
2680       return GlobalCleanup();
2681
2682     case BitstreamEntry::SubBlock:
2683       switch (Entry.ID) {
2684       default:  // Skip unknown content.
2685         if (Stream.SkipBlock())
2686           return Error("Invalid record");
2687         break;
2688       case bitc::BLOCKINFO_BLOCK_ID:
2689         if (Stream.ReadBlockInfoBlock())
2690           return Error("Malformed block");
2691         break;
2692       case bitc::PARAMATTR_BLOCK_ID:
2693         if (std::error_code EC = ParseAttributeBlock())
2694           return EC;
2695         break;
2696       case bitc::PARAMATTR_GROUP_BLOCK_ID:
2697         if (std::error_code EC = ParseAttributeGroupBlock())
2698           return EC;
2699         break;
2700       case bitc::TYPE_BLOCK_ID_NEW:
2701         if (std::error_code EC = ParseTypeTable())
2702           return EC;
2703         break;
2704       case bitc::VALUE_SYMTAB_BLOCK_ID:
2705         if (std::error_code EC = ParseValueSymbolTable())
2706           return EC;
2707         SeenValueSymbolTable = true;
2708         break;
2709       case bitc::CONSTANTS_BLOCK_ID:
2710         if (std::error_code EC = ParseConstants())
2711           return EC;
2712         if (std::error_code EC = ResolveGlobalAndAliasInits())
2713           return EC;
2714         break;
2715       case bitc::METADATA_BLOCK_ID:
2716         if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
2717           if (std::error_code EC = rememberAndSkipMetadata())
2718             return EC;
2719           break;
2720         }
2721         assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
2722         if (std::error_code EC = ParseMetadata())
2723           return EC;
2724         break;
2725       case bitc::FUNCTION_BLOCK_ID:
2726         // If this is the first function body we've seen, reverse the
2727         // FunctionsWithBodies list.
2728         if (!SeenFirstFunctionBody) {
2729           std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
2730           if (std::error_code EC = GlobalCleanup())
2731             return EC;
2732           SeenFirstFunctionBody = true;
2733         }
2734
2735         if (std::error_code EC = RememberAndSkipFunctionBody())
2736           return EC;
2737         // For streaming bitcode, suspend parsing when we reach the function
2738         // bodies. Subsequent materialization calls will resume it when
2739         // necessary. For streaming, the function bodies must be at the end of
2740         // the bitcode. If the bitcode file is old, the symbol table will be
2741         // at the end instead and will not have been seen yet. In this case,
2742         // just finish the parse now.
2743         if (LazyStreamer && SeenValueSymbolTable) {
2744           NextUnreadBit = Stream.GetCurrentBitNo();
2745           return std::error_code();
2746         }
2747         break;
2748       case bitc::USELIST_BLOCK_ID:
2749         if (std::error_code EC = ParseUseLists())
2750           return EC;
2751         break;
2752       }
2753       continue;
2754
2755     case BitstreamEntry::Record:
2756       // The interesting case.
2757       break;
2758     }
2759
2760
2761     // Read a record.
2762     switch (Stream.readRecord(Entry.ID, Record)) {
2763     default: break;  // Default behavior, ignore unknown content.
2764     case bitc::MODULE_CODE_VERSION: {  // VERSION: [version#]
2765       if (Record.size() < 1)
2766         return Error("Invalid record");
2767       // Only version #0 and #1 are supported so far.
2768       unsigned module_version = Record[0];
2769       switch (module_version) {
2770         default:
2771           return Error("Invalid value");
2772         case 0:
2773           UseRelativeIDs = false;
2774           break;
2775         case 1:
2776           UseRelativeIDs = true;
2777           break;
2778       }
2779       break;
2780     }
2781     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
2782       std::string S;
2783       if (ConvertToString(Record, 0, S))
2784         return Error("Invalid record");
2785       TheModule->setTargetTriple(S);
2786       break;
2787     }
2788     case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
2789       std::string S;
2790       if (ConvertToString(Record, 0, S))
2791         return Error("Invalid record");
2792       TheModule->setDataLayout(S);
2793       break;
2794     }
2795     case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
2796       std::string S;
2797       if (ConvertToString(Record, 0, S))
2798         return Error("Invalid record");
2799       TheModule->setModuleInlineAsm(S);
2800       break;
2801     }
2802     case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
2803       // FIXME: Remove in 4.0.
2804       std::string S;
2805       if (ConvertToString(Record, 0, S))
2806         return Error("Invalid record");
2807       // Ignore value.
2808       break;
2809     }
2810     case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
2811       std::string S;
2812       if (ConvertToString(Record, 0, S))
2813         return Error("Invalid record");
2814       SectionTable.push_back(S);
2815       break;
2816     }
2817     case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
2818       std::string S;
2819       if (ConvertToString(Record, 0, S))
2820         return Error("Invalid record");
2821       GCTable.push_back(S);
2822       break;
2823     }
2824     case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
2825       if (Record.size() < 2)
2826         return Error("Invalid record");
2827       Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
2828       unsigned ComdatNameSize = Record[1];
2829       std::string ComdatName;
2830       ComdatName.reserve(ComdatNameSize);
2831       for (unsigned i = 0; i != ComdatNameSize; ++i)
2832         ComdatName += (char)Record[2 + i];
2833       Comdat *C = TheModule->getOrInsertComdat(ComdatName);
2834       C->setSelectionKind(SK);
2835       ComdatList.push_back(C);
2836       break;
2837     }
2838     // GLOBALVAR: [pointer type, isconst, initid,
2839     //             linkage, alignment, section, visibility, threadlocal,
2840     //             unnamed_addr, externally_initialized, dllstorageclass,
2841     //             comdat]
2842     case bitc::MODULE_CODE_GLOBALVAR: {
2843       if (Record.size() < 6)
2844         return Error("Invalid record");
2845       Type *Ty = getTypeByID(Record[0]);
2846       if (!Ty)
2847         return Error("Invalid record");
2848       if (!Ty->isPointerTy())
2849         return Error("Invalid type for value");
2850       unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2851       Ty = cast<PointerType>(Ty)->getElementType();
2852
2853       bool isConstant = Record[1];
2854       uint64_t RawLinkage = Record[3];
2855       GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
2856       unsigned Alignment;
2857       if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
2858         return EC;
2859       std::string Section;
2860       if (Record[5]) {
2861         if (Record[5]-1 >= SectionTable.size())
2862           return Error("Invalid ID");
2863         Section = SectionTable[Record[5]-1];
2864       }
2865       GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
2866       // Local linkage must have default visibility.
2867       if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2868         // FIXME: Change to an error if non-default in 4.0.
2869         Visibility = GetDecodedVisibility(Record[6]);
2870
2871       GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
2872       if (Record.size() > 7)
2873         TLM = GetDecodedThreadLocalMode(Record[7]);
2874
2875       bool UnnamedAddr = false;
2876       if (Record.size() > 8)
2877         UnnamedAddr = Record[8];
2878
2879       bool ExternallyInitialized = false;
2880       if (Record.size() > 9)
2881         ExternallyInitialized = Record[9];
2882
2883       GlobalVariable *NewGV =
2884         new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
2885                            TLM, AddressSpace, ExternallyInitialized);
2886       NewGV->setAlignment(Alignment);
2887       if (!Section.empty())
2888         NewGV->setSection(Section);
2889       NewGV->setVisibility(Visibility);
2890       NewGV->setUnnamedAddr(UnnamedAddr);
2891
2892       if (Record.size() > 10)
2893         NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
2894       else
2895         UpgradeDLLImportExportLinkage(NewGV, RawLinkage);
2896
2897       ValueList.push_back(NewGV);
2898
2899       // Remember which value to use for the global initializer.
2900       if (unsigned InitID = Record[2])
2901         GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
2902
2903       if (Record.size() > 11) {
2904         if (unsigned ComdatID = Record[11]) {
2905           assert(ComdatID <= ComdatList.size());
2906           NewGV->setComdat(ComdatList[ComdatID - 1]);
2907         }
2908       } else if (hasImplicitComdat(RawLinkage)) {
2909         NewGV->setComdat(reinterpret_cast<Comdat *>(1));
2910       }
2911       break;
2912     }
2913     // FUNCTION:  [type, callingconv, isproto, linkage, paramattr,
2914     //             alignment, section, visibility, gc, unnamed_addr,
2915     //             prologuedata, dllstorageclass, comdat, prefixdata]
2916     case bitc::MODULE_CODE_FUNCTION: {
2917       if (Record.size() < 8)
2918         return Error("Invalid record");
2919       Type *Ty = getTypeByID(Record[0]);
2920       if (!Ty)
2921         return Error("Invalid record");
2922       if (!Ty->isPointerTy())
2923         return Error("Invalid type for value");
2924       FunctionType *FTy =
2925         dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
2926       if (!FTy)
2927         return Error("Invalid type for value");
2928
2929       Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2930                                         "", TheModule);
2931
2932       Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
2933       bool isProto = Record[2];
2934       uint64_t RawLinkage = Record[3];
2935       Func->setLinkage(getDecodedLinkage(RawLinkage));
2936       Func->setAttributes(getAttributes(Record[4]));
2937
2938       unsigned Alignment;
2939       if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
2940         return EC;
2941       Func->setAlignment(Alignment);
2942       if (Record[6]) {
2943         if (Record[6]-1 >= SectionTable.size())
2944           return Error("Invalid ID");
2945         Func->setSection(SectionTable[Record[6]-1]);
2946       }
2947       // Local linkage must have default visibility.
2948       if (!Func->hasLocalLinkage())
2949         // FIXME: Change to an error if non-default in 4.0.
2950         Func->setVisibility(GetDecodedVisibility(Record[7]));
2951       if (Record.size() > 8 && Record[8]) {
2952         if (Record[8]-1 > GCTable.size())
2953           return Error("Invalid ID");
2954         Func->setGC(GCTable[Record[8]-1].c_str());
2955       }
2956       bool UnnamedAddr = false;
2957       if (Record.size() > 9)
2958         UnnamedAddr = Record[9];
2959       Func->setUnnamedAddr(UnnamedAddr);
2960       if (Record.size() > 10 && Record[10] != 0)
2961         FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
2962
2963       if (Record.size() > 11)
2964         Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
2965       else
2966         UpgradeDLLImportExportLinkage(Func, RawLinkage);
2967
2968       if (Record.size() > 12) {
2969         if (unsigned ComdatID = Record[12]) {
2970           assert(ComdatID <= ComdatList.size());
2971           Func->setComdat(ComdatList[ComdatID - 1]);
2972         }
2973       } else if (hasImplicitComdat(RawLinkage)) {
2974         Func->setComdat(reinterpret_cast<Comdat *>(1));
2975       }
2976
2977       if (Record.size() > 13 && Record[13] != 0)
2978         FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
2979
2980       ValueList.push_back(Func);
2981
2982       // If this is a function with a body, remember the prototype we are
2983       // creating now, so that we can match up the body with them later.
2984       if (!isProto) {
2985         Func->setIsMaterializable(true);
2986         FunctionsWithBodies.push_back(Func);
2987         if (LazyStreamer)
2988           DeferredFunctionInfo[Func] = 0;
2989       }
2990       break;
2991     }
2992     // ALIAS: [alias type, aliasee val#, linkage]
2993     // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
2994     case bitc::MODULE_CODE_ALIAS: {
2995       if (Record.size() < 3)
2996         return Error("Invalid record");
2997       Type *Ty = getTypeByID(Record[0]);
2998       if (!Ty)
2999         return Error("Invalid record");
3000       auto *PTy = dyn_cast<PointerType>(Ty);
3001       if (!PTy)
3002         return Error("Invalid type for value");
3003
3004       auto *NewGA =
3005           GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
3006                               getDecodedLinkage(Record[2]), "", TheModule);
3007       // Old bitcode files didn't have visibility field.
3008       // Local linkage must have default visibility.
3009       if (Record.size() > 3 && !NewGA->hasLocalLinkage())
3010         // FIXME: Change to an error if non-default in 4.0.
3011         NewGA->setVisibility(GetDecodedVisibility(Record[3]));
3012       if (Record.size() > 4)
3013         NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
3014       else
3015         UpgradeDLLImportExportLinkage(NewGA, Record[2]);
3016       if (Record.size() > 5)
3017         NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
3018       if (Record.size() > 6)
3019         NewGA->setUnnamedAddr(Record[6]);
3020       ValueList.push_back(NewGA);
3021       AliasInits.push_back(std::make_pair(NewGA, Record[1]));
3022       break;
3023     }
3024     /// MODULE_CODE_PURGEVALS: [numvals]
3025     case bitc::MODULE_CODE_PURGEVALS:
3026       // Trim down the value list to the specified size.
3027       if (Record.size() < 1 || Record[0] > ValueList.size())
3028         return Error("Invalid record");
3029       ValueList.shrinkTo(Record[0]);
3030       break;
3031     }
3032     Record.clear();
3033   }
3034 }
3035
3036 std::error_code BitcodeReader::ParseBitcodeInto(Module *M,
3037                                                 bool ShouldLazyLoadMetadata) {
3038   TheModule = nullptr;
3039
3040   if (std::error_code EC = InitStream())
3041     return EC;
3042
3043   // Sniff for the signature.
3044   if (Stream.Read(8) != 'B' ||
3045       Stream.Read(8) != 'C' ||
3046       Stream.Read(4) != 0x0 ||
3047       Stream.Read(4) != 0xC ||
3048       Stream.Read(4) != 0xE ||
3049       Stream.Read(4) != 0xD)
3050     return Error("Invalid bitcode signature");
3051
3052   // We expect a number of well-defined blocks, though we don't necessarily
3053   // need to understand them all.
3054   while (1) {
3055     if (Stream.AtEndOfStream())
3056       return std::error_code();
3057
3058     BitstreamEntry Entry =
3059       Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
3060
3061     switch (Entry.Kind) {
3062     case BitstreamEntry::Error:
3063       return Error("Malformed block");
3064     case BitstreamEntry::EndBlock:
3065       return std::error_code();
3066
3067     case BitstreamEntry::SubBlock:
3068       switch (Entry.ID) {
3069       case bitc::BLOCKINFO_BLOCK_ID:
3070         if (Stream.ReadBlockInfoBlock())
3071           return Error("Malformed block");
3072         break;
3073       case bitc::MODULE_BLOCK_ID:
3074         // Reject multiple MODULE_BLOCK's in a single bitstream.
3075         if (TheModule)
3076           return Error("Invalid multiple blocks");
3077         TheModule = M;
3078         if (std::error_code EC = ParseModule(false, ShouldLazyLoadMetadata))
3079           return EC;
3080         if (LazyStreamer)
3081           return std::error_code();
3082         break;
3083       default:
3084         if (Stream.SkipBlock())
3085           return Error("Invalid record");
3086         break;
3087       }
3088       continue;
3089     case BitstreamEntry::Record:
3090       // There should be no records in the top-level of blocks.
3091
3092       // The ranlib in Xcode 4 will align archive members by appending newlines
3093       // to the end of them. If this file size is a multiple of 4 but not 8, we
3094       // have to read and ignore these final 4 bytes :-(
3095       if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
3096           Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
3097           Stream.AtEndOfStream())
3098         return std::error_code();
3099
3100       return Error("Invalid record");
3101     }
3102   }
3103 }
3104
3105 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
3106   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3107     return Error("Invalid record");
3108
3109   SmallVector<uint64_t, 64> Record;
3110
3111   std::string Triple;
3112   // Read all the records for this module.
3113   while (1) {
3114     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3115
3116     switch (Entry.Kind) {
3117     case BitstreamEntry::SubBlock: // Handled for us already.
3118     case BitstreamEntry::Error:
3119       return Error("Malformed block");
3120     case BitstreamEntry::EndBlock:
3121       return Triple;
3122     case BitstreamEntry::Record:
3123       // The interesting case.
3124       break;
3125     }
3126
3127     // Read a record.
3128     switch (Stream.readRecord(Entry.ID, Record)) {
3129     default: break;  // Default behavior, ignore unknown content.
3130     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
3131       std::string S;
3132       if (ConvertToString(Record, 0, S))
3133         return Error("Invalid record");
3134       Triple = S;
3135       break;
3136     }
3137     }
3138     Record.clear();
3139   }
3140   llvm_unreachable("Exit infinite loop");
3141 }
3142
3143 ErrorOr<std::string> BitcodeReader::parseTriple() {
3144   if (std::error_code EC = InitStream())
3145     return EC;
3146
3147   // Sniff for the signature.
3148   if (Stream.Read(8) != 'B' ||
3149       Stream.Read(8) != 'C' ||
3150       Stream.Read(4) != 0x0 ||
3151       Stream.Read(4) != 0xC ||
3152       Stream.Read(4) != 0xE ||
3153       Stream.Read(4) != 0xD)
3154     return Error("Invalid bitcode signature");
3155
3156   // We expect a number of well-defined blocks, though we don't necessarily
3157   // need to understand them all.
3158   while (1) {
3159     BitstreamEntry Entry = Stream.advance();
3160
3161     switch (Entry.Kind) {
3162     case BitstreamEntry::Error:
3163       return Error("Malformed block");
3164     case BitstreamEntry::EndBlock:
3165       return std::error_code();
3166
3167     case BitstreamEntry::SubBlock:
3168       if (Entry.ID == bitc::MODULE_BLOCK_ID)
3169         return parseModuleTriple();
3170
3171       // Ignore other sub-blocks.
3172       if (Stream.SkipBlock())
3173         return Error("Malformed block");
3174       continue;
3175
3176     case BitstreamEntry::Record:
3177       Stream.skipRecord(Entry.ID);
3178       continue;
3179     }
3180   }
3181 }
3182
3183 /// ParseMetadataAttachment - Parse metadata attachments.
3184 std::error_code BitcodeReader::ParseMetadataAttachment() {
3185   if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
3186     return Error("Invalid record");
3187
3188   SmallVector<uint64_t, 64> Record;
3189   while (1) {
3190     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3191
3192     switch (Entry.Kind) {
3193     case BitstreamEntry::SubBlock: // Handled for us already.
3194     case BitstreamEntry::Error:
3195       return Error("Malformed block");
3196     case BitstreamEntry::EndBlock:
3197       return std::error_code();
3198     case BitstreamEntry::Record:
3199       // The interesting case.
3200       break;
3201     }
3202
3203     // Read a metadata attachment record.
3204     Record.clear();
3205     switch (Stream.readRecord(Entry.ID, Record)) {
3206     default:  // Default behavior: ignore.
3207       break;
3208     case bitc::METADATA_ATTACHMENT: {
3209       unsigned RecordLength = Record.size();
3210       if (Record.empty() || (RecordLength - 1) % 2 == 1)
3211         return Error("Invalid record");
3212       Instruction *Inst = InstructionList[Record[0]];
3213       for (unsigned i = 1; i != RecordLength; i = i+2) {
3214         unsigned Kind = Record[i];
3215         DenseMap<unsigned, unsigned>::iterator I =
3216           MDKindMap.find(Kind);
3217         if (I == MDKindMap.end())
3218           return Error("Invalid ID");
3219         Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
3220         if (isa<LocalAsMetadata>(Node))
3221           // Drop the attachment.  This used to be legal, but there's no
3222           // upgrade path.
3223           break;
3224         Inst->setMetadata(I->second, cast<MDNode>(Node));
3225         if (I->second == LLVMContext::MD_tbaa)
3226           InstsWithTBAATag.push_back(Inst);
3227       }
3228       break;
3229     }
3230     }
3231   }
3232 }
3233
3234 /// ParseFunctionBody - Lazily parse the specified function body block.
3235 std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
3236   if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3237     return Error("Invalid record");
3238
3239   InstructionList.clear();
3240   unsigned ModuleValueListSize = ValueList.size();
3241   unsigned ModuleMDValueListSize = MDValueList.size();
3242
3243   // Add all the function arguments to the value table.
3244   for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
3245     ValueList.push_back(I);
3246
3247   unsigned NextValueNo = ValueList.size();
3248   BasicBlock *CurBB = nullptr;
3249   unsigned CurBBNo = 0;
3250
3251   DebugLoc LastLoc;
3252   auto getLastInstruction = [&]() -> Instruction * {
3253     if (CurBB && !CurBB->empty())
3254       return &CurBB->back();
3255     else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3256              !FunctionBBs[CurBBNo - 1]->empty())
3257       return &FunctionBBs[CurBBNo - 1]->back();
3258     return nullptr;
3259   };
3260
3261   // Read all the records.
3262   SmallVector<uint64_t, 64> Record;
3263   while (1) {
3264     BitstreamEntry Entry = Stream.advance();
3265
3266     switch (Entry.Kind) {
3267     case BitstreamEntry::Error:
3268       return Error("Malformed block");
3269     case BitstreamEntry::EndBlock:
3270       goto OutOfRecordLoop;
3271
3272     case BitstreamEntry::SubBlock:
3273       switch (Entry.ID) {
3274       default:  // Skip unknown content.
3275         if (Stream.SkipBlock())
3276           return Error("Invalid record");
3277         break;
3278       case bitc::CONSTANTS_BLOCK_ID:
3279         if (std::error_code EC = ParseConstants())
3280           return EC;
3281         NextValueNo = ValueList.size();
3282         break;
3283       case bitc::VALUE_SYMTAB_BLOCK_ID:
3284         if (std::error_code EC = ParseValueSymbolTable())
3285           return EC;
3286         break;
3287       case bitc::METADATA_ATTACHMENT_ID:
3288         if (std::error_code EC = ParseMetadataAttachment())
3289           return EC;
3290         break;
3291       case bitc::METADATA_BLOCK_ID:
3292         if (std::error_code EC = ParseMetadata())
3293           return EC;
3294         break;
3295       case bitc::USELIST_BLOCK_ID:
3296         if (std::error_code EC = ParseUseLists())
3297           return EC;
3298         break;
3299       }
3300       continue;
3301
3302     case BitstreamEntry::Record:
3303       // The interesting case.
3304       break;
3305     }
3306
3307     // Read a record.
3308     Record.clear();
3309     Instruction *I = nullptr;
3310     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3311     switch (BitCode) {
3312     default: // Default behavior: reject
3313       return Error("Invalid value");
3314     case bitc::FUNC_CODE_DECLAREBLOCKS: {   // DECLAREBLOCKS: [nblocks]
3315       if (Record.size() < 1 || Record[0] == 0)
3316         return Error("Invalid record");
3317       // Create all the basic blocks for the function.
3318       FunctionBBs.resize(Record[0]);
3319
3320       // See if anything took the address of blocks in this function.
3321       auto BBFRI = BasicBlockFwdRefs.find(F);
3322       if (BBFRI == BasicBlockFwdRefs.end()) {
3323         for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3324           FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3325       } else {
3326         auto &BBRefs = BBFRI->second;
3327         // Check for invalid basic block references.
3328         if (BBRefs.size() > FunctionBBs.size())
3329           return Error("Invalid ID");
3330         assert(!BBRefs.empty() && "Unexpected empty array");
3331         assert(!BBRefs.front() && "Invalid reference to entry block");
3332         for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
3333              ++I)
3334           if (I < RE && BBRefs[I]) {
3335             BBRefs[I]->insertInto(F);
3336             FunctionBBs[I] = BBRefs[I];
3337           } else {
3338             FunctionBBs[I] = BasicBlock::Create(Context, "", F);
3339           }
3340
3341         // Erase from the table.
3342         BasicBlockFwdRefs.erase(BBFRI);
3343       }
3344
3345       CurBB = FunctionBBs[0];
3346       continue;
3347     }
3348
3349     case bitc::FUNC_CODE_DEBUG_LOC_AGAIN:  // DEBUG_LOC_AGAIN
3350       // This record indicates that the last instruction is at the same
3351       // location as the previous instruction with a location.
3352       I = getLastInstruction();
3353
3354       if (!I)
3355         return Error("Invalid record");
3356       I->setDebugLoc(LastLoc);
3357       I = nullptr;
3358       continue;
3359
3360     case bitc::FUNC_CODE_DEBUG_LOC: {      // DEBUG_LOC: [line, col, scope, ia]
3361       I = getLastInstruction();
3362       if (!I || Record.size() < 4)
3363         return Error("Invalid record");
3364
3365       unsigned Line = Record[0], Col = Record[1];
3366       unsigned ScopeID = Record[2], IAID = Record[3];
3367
3368       MDNode *Scope = nullptr, *IA = nullptr;
3369       if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
3370       if (IAID)    IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
3371       LastLoc = DebugLoc::get(Line, Col, Scope, IA);
3372       I->setDebugLoc(LastLoc);
3373       I = nullptr;
3374       continue;
3375     }
3376
3377     case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
3378       unsigned OpNum = 0;
3379       Value *LHS, *RHS;
3380       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3381           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3382           OpNum+1 > Record.size())
3383         return Error("Invalid record");
3384
3385       int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
3386       if (Opc == -1)
3387         return Error("Invalid record");
3388       I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3389       InstructionList.push_back(I);
3390       if (OpNum < Record.size()) {
3391         if (Opc == Instruction::Add ||
3392             Opc == Instruction::Sub ||
3393             Opc == Instruction::Mul ||
3394             Opc == Instruction::Shl) {
3395           if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3396             cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
3397           if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3398             cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
3399         } else if (Opc == Instruction::SDiv ||
3400                    Opc == Instruction::UDiv ||
3401                    Opc == Instruction::LShr ||
3402                    Opc == Instruction::AShr) {
3403           if (Record[OpNum] & (1 << bitc::PEO_EXACT))
3404             cast<BinaryOperator>(I)->setIsExact(true);
3405         } else if (isa<FPMathOperator>(I)) {
3406           FastMathFlags FMF;
3407           if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
3408             FMF.setUnsafeAlgebra();
3409           if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
3410             FMF.setNoNaNs();
3411           if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
3412             FMF.setNoInfs();
3413           if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
3414             FMF.setNoSignedZeros();
3415           if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
3416             FMF.setAllowReciprocal();
3417           if (FMF.any())
3418             I->setFastMathFlags(FMF);
3419         }
3420
3421       }
3422       break;
3423     }
3424     case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
3425       unsigned OpNum = 0;
3426       Value *Op;
3427       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3428           OpNum+2 != Record.size())
3429         return Error("Invalid record");
3430
3431       Type *ResTy = getTypeByID(Record[OpNum]);
3432       int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
3433       if (Opc == -1 || !ResTy)
3434         return Error("Invalid record");
3435       Instruction *Temp = nullptr;
3436       if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3437         if (Temp) {
3438           InstructionList.push_back(Temp);
3439           CurBB->getInstList().push_back(Temp);
3440         }
3441       } else {
3442         I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
3443       }
3444       InstructionList.push_back(I);
3445       break;
3446     }
3447     case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
3448     case bitc::FUNC_CODE_INST_GEP_OLD:
3449     case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
3450       unsigned OpNum = 0;
3451
3452       Type *Ty;
3453       bool InBounds;
3454
3455       if (BitCode == bitc::FUNC_CODE_INST_GEP) {
3456         InBounds = Record[OpNum++];
3457         Ty = getTypeByID(Record[OpNum++]);
3458       } else {
3459         InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
3460         Ty = nullptr;
3461       }
3462
3463       Value *BasePtr;
3464       if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
3465         return Error("Invalid record");
3466
3467       if (Ty &&
3468           Ty !=
3469               cast<SequentialType>(BasePtr->getType()->getScalarType())
3470                   ->getElementType())
3471         return Error(
3472             "Explicit gep type does not match pointee type of pointer operand");
3473
3474       SmallVector<Value*, 16> GEPIdx;
3475       while (OpNum != Record.size()) {
3476         Value *Op;
3477         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3478           return Error("Invalid record");
3479         GEPIdx.push_back(Op);
3480       }
3481
3482       I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
3483
3484       InstructionList.push_back(I);
3485       if (InBounds)
3486         cast<GetElementPtrInst>(I)->setIsInBounds(true);
3487       break;
3488     }
3489
3490     case bitc::FUNC_CODE_INST_EXTRACTVAL: {
3491                                        // EXTRACTVAL: [opty, opval, n x indices]
3492       unsigned OpNum = 0;
3493       Value *Agg;
3494       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3495         return Error("Invalid record");
3496
3497       SmallVector<unsigned, 4> EXTRACTVALIdx;
3498       Type *CurTy = Agg->getType();
3499       for (unsigned RecSize = Record.size();
3500            OpNum != RecSize; ++OpNum) {
3501         bool IsArray = CurTy->isArrayTy();
3502         bool IsStruct = CurTy->isStructTy();
3503         uint64_t Index = Record[OpNum];
3504
3505         if (!IsStruct && !IsArray)
3506           return Error("EXTRACTVAL: Invalid type");
3507         if ((unsigned)Index != Index)
3508           return Error("Invalid value");
3509         if (IsStruct && Index >= CurTy->subtypes().size())
3510           return Error("EXTRACTVAL: Invalid struct index");
3511         if (IsArray && Index >= CurTy->getArrayNumElements())
3512           return Error("EXTRACTVAL: Invalid array index");
3513         EXTRACTVALIdx.push_back((unsigned)Index);
3514
3515         if (IsStruct)
3516           CurTy = CurTy->subtypes()[Index];
3517         else
3518           CurTy = CurTy->subtypes()[0];
3519       }
3520
3521       I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
3522       InstructionList.push_back(I);
3523       break;
3524     }
3525
3526     case bitc::FUNC_CODE_INST_INSERTVAL: {
3527                            // INSERTVAL: [opty, opval, opty, opval, n x indices]
3528       unsigned OpNum = 0;
3529       Value *Agg;
3530       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3531         return Error("Invalid record");
3532       Value *Val;
3533       if (getValueTypePair(Record, OpNum, NextValueNo, Val))
3534         return Error("Invalid record");
3535
3536       SmallVector<unsigned, 4> INSERTVALIdx;
3537       Type *CurTy = Agg->getType();
3538       for (unsigned RecSize = Record.size();
3539            OpNum != RecSize; ++OpNum) {
3540         bool IsArray = CurTy->isArrayTy();
3541         bool IsStruct = CurTy->isStructTy();
3542         uint64_t Index = Record[OpNum];
3543
3544         if (!IsStruct && !IsArray)
3545           return Error("INSERTVAL: Invalid type");
3546         if (!CurTy->isStructTy() && !CurTy->isArrayTy())
3547           return Error("Invalid type");
3548         if ((unsigned)Index != Index)
3549           return Error("Invalid value");
3550         if (IsStruct && Index >= CurTy->subtypes().size())
3551           return Error("INSERTVAL: Invalid struct index");
3552         if (IsArray && Index >= CurTy->getArrayNumElements())
3553           return Error("INSERTVAL: Invalid array index");
3554
3555         INSERTVALIdx.push_back((unsigned)Index);
3556         if (IsStruct)
3557           CurTy = CurTy->subtypes()[Index];
3558         else
3559           CurTy = CurTy->subtypes()[0];
3560       }
3561
3562       I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
3563       InstructionList.push_back(I);
3564       break;
3565     }
3566
3567     case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
3568       // obsolete form of select
3569       // handles select i1 ... in old bitcode
3570       unsigned OpNum = 0;
3571       Value *TrueVal, *FalseVal, *Cond;
3572       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3573           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3574           popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
3575         return Error("Invalid record");
3576
3577       I = SelectInst::Create(Cond, TrueVal, FalseVal);
3578       InstructionList.push_back(I);
3579       break;
3580     }
3581
3582     case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
3583       // new form of select
3584       // handles select i1 or select [N x i1]
3585       unsigned OpNum = 0;
3586       Value *TrueVal, *FalseVal, *Cond;
3587       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3588           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3589           getValueTypePair(Record, OpNum, NextValueNo, Cond))
3590         return Error("Invalid record");
3591
3592       // select condition can be either i1 or [N x i1]
3593       if (VectorType* vector_type =
3594           dyn_cast<VectorType>(Cond->getType())) {
3595         // expect <n x i1>
3596         if (vector_type->getElementType() != Type::getInt1Ty(Context))
3597           return Error("Invalid type for value");
3598       } else {
3599         // expect i1
3600         if (Cond->getType() != Type::getInt1Ty(Context))
3601           return Error("Invalid type for value");
3602       }
3603
3604       I = SelectInst::Create(Cond, TrueVal, FalseVal);
3605       InstructionList.push_back(I);
3606       break;
3607     }
3608
3609     case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
3610       unsigned OpNum = 0;
3611       Value *Vec, *Idx;
3612       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
3613           getValueTypePair(Record, OpNum, NextValueNo, Idx))
3614         return Error("Invalid record");
3615       I = ExtractElementInst::Create(Vec, Idx);
3616       InstructionList.push_back(I);
3617       break;
3618     }
3619
3620     case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
3621       unsigned OpNum = 0;
3622       Value *Vec, *Elt, *Idx;
3623       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
3624           popValue(Record, OpNum, NextValueNo,
3625                    cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
3626           getValueTypePair(Record, OpNum, NextValueNo, Idx))
3627         return Error("Invalid record");
3628       I = InsertElementInst::Create(Vec, Elt, Idx);
3629       InstructionList.push_back(I);
3630       break;
3631     }
3632
3633     case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
3634       unsigned OpNum = 0;
3635       Value *Vec1, *Vec2, *Mask;
3636       if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
3637           popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
3638         return Error("Invalid record");
3639
3640       if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
3641         return Error("Invalid record");
3642       I = new ShuffleVectorInst(Vec1, Vec2, Mask);
3643       InstructionList.push_back(I);
3644       break;
3645     }
3646
3647     case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
3648       // Old form of ICmp/FCmp returning bool
3649       // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
3650       // both legal on vectors but had different behaviour.
3651     case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
3652       // FCmp/ICmp returning bool or vector of bool
3653
3654       unsigned OpNum = 0;
3655       Value *LHS, *RHS;
3656       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3657           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3658           OpNum+1 != Record.size())
3659         return Error("Invalid record");
3660
3661       if (LHS->getType()->isFPOrFPVectorTy())
3662         I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
3663       else
3664         I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
3665       InstructionList.push_back(I);
3666       break;
3667     }
3668
3669     case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
3670       {
3671         unsigned Size = Record.size();
3672         if (Size == 0) {
3673           I = ReturnInst::Create(Context);
3674           InstructionList.push_back(I);
3675           break;
3676         }
3677
3678         unsigned OpNum = 0;
3679         Value *Op = nullptr;
3680         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3681           return Error("Invalid record");
3682         if (OpNum != Record.size())
3683           return Error("Invalid record");
3684
3685         I = ReturnInst::Create(Context, Op);
3686         InstructionList.push_back(I);
3687         break;
3688       }
3689     case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
3690       if (Record.size() != 1 && Record.size() != 3)
3691         return Error("Invalid record");
3692       BasicBlock *TrueDest = getBasicBlock(Record[0]);
3693       if (!TrueDest)
3694         return Error("Invalid record");
3695
3696       if (Record.size() == 1) {
3697         I = BranchInst::Create(TrueDest);
3698         InstructionList.push_back(I);
3699       }
3700       else {
3701         BasicBlock *FalseDest = getBasicBlock(Record[1]);
3702         Value *Cond = getValue(Record, 2, NextValueNo,
3703                                Type::getInt1Ty(Context));
3704         if (!FalseDest || !Cond)
3705           return Error("Invalid record");
3706         I = BranchInst::Create(TrueDest, FalseDest, Cond);
3707         InstructionList.push_back(I);
3708       }
3709       break;
3710     }
3711     case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
3712       // Check magic
3713       if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
3714         // "New" SwitchInst format with case ranges. The changes to write this
3715         // format were reverted but we still recognize bitcode that uses it.
3716         // Hopefully someday we will have support for case ranges and can use
3717         // this format again.
3718
3719         Type *OpTy = getTypeByID(Record[1]);
3720         unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
3721
3722         Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
3723         BasicBlock *Default = getBasicBlock(Record[3]);
3724         if (!OpTy || !Cond || !Default)
3725           return Error("Invalid record");
3726
3727         unsigned NumCases = Record[4];
3728
3729         SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3730         InstructionList.push_back(SI);
3731
3732         unsigned CurIdx = 5;
3733         for (unsigned i = 0; i != NumCases; ++i) {
3734           SmallVector<ConstantInt*, 1> CaseVals;
3735           unsigned NumItems = Record[CurIdx++];
3736           for (unsigned ci = 0; ci != NumItems; ++ci) {
3737             bool isSingleNumber = Record[CurIdx++];
3738
3739             APInt Low;
3740             unsigned ActiveWords = 1;
3741             if (ValueBitWidth > 64)
3742               ActiveWords = Record[CurIdx++];
3743             Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3744                                 ValueBitWidth);
3745             CurIdx += ActiveWords;
3746
3747             if (!isSingleNumber) {
3748               ActiveWords = 1;
3749               if (ValueBitWidth > 64)
3750                 ActiveWords = Record[CurIdx++];
3751               APInt High =
3752                   ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3753                                 ValueBitWidth);
3754               CurIdx += ActiveWords;
3755
3756               // FIXME: It is not clear whether values in the range should be
3757               // compared as signed or unsigned values. The partially
3758               // implemented changes that used this format in the past used
3759               // unsigned comparisons.
3760               for ( ; Low.ule(High); ++Low)
3761                 CaseVals.push_back(ConstantInt::get(Context, Low));
3762             } else
3763               CaseVals.push_back(ConstantInt::get(Context, Low));
3764           }
3765           BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
3766           for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
3767                  cve = CaseVals.end(); cvi != cve; ++cvi)
3768             SI->addCase(*cvi, DestBB);
3769         }
3770         I = SI;
3771         break;
3772       }
3773
3774       // Old SwitchInst format without case ranges.
3775
3776       if (Record.size() < 3 || (Record.size() & 1) == 0)
3777         return Error("Invalid record");
3778       Type *OpTy = getTypeByID(Record[0]);
3779       Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
3780       BasicBlock *Default = getBasicBlock(Record[2]);
3781       if (!OpTy || !Cond || !Default)
3782         return Error("Invalid record");
3783       unsigned NumCases = (Record.size()-3)/2;
3784       SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3785       InstructionList.push_back(SI);
3786       for (unsigned i = 0, e = NumCases; i != e; ++i) {
3787         ConstantInt *CaseVal =
3788           dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
3789         BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
3790         if (!CaseVal || !DestBB) {
3791           delete SI;
3792           return Error("Invalid record");
3793         }
3794         SI->addCase(CaseVal, DestBB);
3795       }
3796       I = SI;
3797       break;
3798     }
3799     case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
3800       if (Record.size() < 2)
3801         return Error("Invalid record");
3802       Type *OpTy = getTypeByID(Record[0]);
3803       Value *Address = getValue(Record, 1, NextValueNo, OpTy);
3804       if (!OpTy || !Address)
3805         return Error("Invalid record");
3806       unsigned NumDests = Record.size()-2;
3807       IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
3808       InstructionList.push_back(IBI);
3809       for (unsigned i = 0, e = NumDests; i != e; ++i) {
3810         if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
3811           IBI->addDestination(DestBB);
3812         } else {
3813           delete IBI;
3814           return Error("Invalid record");
3815         }
3816       }
3817       I = IBI;
3818       break;
3819     }
3820
3821     case bitc::FUNC_CODE_INST_INVOKE: {
3822       // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
3823       if (Record.size() < 4)
3824         return Error("Invalid record");
3825       AttributeSet PAL = getAttributes(Record[0]);
3826       unsigned CCInfo = Record[1];
3827       BasicBlock *NormalBB = getBasicBlock(Record[2]);
3828       BasicBlock *UnwindBB = getBasicBlock(Record[3]);
3829
3830       unsigned OpNum = 4;
3831       Value *Callee;
3832       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3833         return Error("Invalid record");
3834
3835       PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
3836       FunctionType *FTy = !CalleeTy ? nullptr :
3837         dyn_cast<FunctionType>(CalleeTy->getElementType());
3838
3839       // Check that the right number of fixed parameters are here.
3840       if (!FTy || !NormalBB || !UnwindBB ||
3841           Record.size() < OpNum+FTy->getNumParams())
3842         return Error("Invalid record");
3843
3844       SmallVector<Value*, 16> Ops;
3845       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3846         Ops.push_back(getValue(Record, OpNum, NextValueNo,
3847                                FTy->getParamType(i)));
3848         if (!Ops.back())
3849           return Error("Invalid record");
3850       }
3851
3852       if (!FTy->isVarArg()) {
3853         if (Record.size() != OpNum)
3854           return Error("Invalid record");
3855       } else {
3856         // Read type/value pairs for varargs params.
3857         while (OpNum != Record.size()) {
3858           Value *Op;
3859           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3860             return Error("Invalid record");
3861           Ops.push_back(Op);
3862         }
3863       }
3864
3865       I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
3866       InstructionList.push_back(I);
3867       cast<InvokeInst>(I)->setCallingConv(
3868         static_cast<CallingConv::ID>(CCInfo));
3869       cast<InvokeInst>(I)->setAttributes(PAL);
3870       break;
3871     }
3872     case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
3873       unsigned Idx = 0;
3874       Value *Val = nullptr;
3875       if (getValueTypePair(Record, Idx, NextValueNo, Val))
3876         return Error("Invalid record");
3877       I = ResumeInst::Create(Val);
3878       InstructionList.push_back(I);
3879       break;
3880     }
3881     case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
3882       I = new UnreachableInst(Context);
3883       InstructionList.push_back(I);
3884       break;
3885     case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
3886       if (Record.size() < 1 || ((Record.size()-1)&1))
3887         return Error("Invalid record");
3888       Type *Ty = getTypeByID(Record[0]);
3889       if (!Ty)
3890         return Error("Invalid record");
3891
3892       PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
3893       InstructionList.push_back(PN);
3894
3895       for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
3896         Value *V;
3897         // With the new function encoding, it is possible that operands have
3898         // negative IDs (for forward references).  Use a signed VBR
3899         // representation to keep the encoding small.
3900         if (UseRelativeIDs)
3901           V = getValueSigned(Record, 1+i, NextValueNo, Ty);
3902         else
3903           V = getValue(Record, 1+i, NextValueNo, Ty);
3904         BasicBlock *BB = getBasicBlock(Record[2+i]);
3905         if (!V || !BB)
3906           return Error("Invalid record");
3907         PN->addIncoming(V, BB);
3908       }
3909       I = PN;
3910       break;
3911     }
3912
3913     case bitc::FUNC_CODE_INST_LANDINGPAD: {
3914       // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
3915       unsigned Idx = 0;
3916       if (Record.size() < 4)
3917         return Error("Invalid record");
3918       Type *Ty = getTypeByID(Record[Idx++]);
3919       if (!Ty)
3920         return Error("Invalid record");
3921       Value *PersFn = nullptr;
3922       if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
3923         return Error("Invalid record");
3924
3925       bool IsCleanup = !!Record[Idx++];
3926       unsigned NumClauses = Record[Idx++];
3927       LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
3928       LP->setCleanup(IsCleanup);
3929       for (unsigned J = 0; J != NumClauses; ++J) {
3930         LandingPadInst::ClauseType CT =
3931           LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
3932         Value *Val;
3933
3934         if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
3935           delete LP;
3936           return Error("Invalid record");
3937         }
3938
3939         assert((CT != LandingPadInst::Catch ||
3940                 !isa<ArrayType>(Val->getType())) &&
3941                "Catch clause has a invalid type!");
3942         assert((CT != LandingPadInst::Filter ||
3943                 isa<ArrayType>(Val->getType())) &&
3944                "Filter clause has invalid type!");
3945         LP->addClause(cast<Constant>(Val));
3946       }
3947
3948       I = LP;
3949       InstructionList.push_back(I);
3950       break;
3951     }
3952
3953     case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
3954       if (Record.size() != 4)
3955         return Error("Invalid record");
3956       PointerType *Ty =
3957         dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
3958       Type *OpTy = getTypeByID(Record[1]);
3959       Value *Size = getFnValueByID(Record[2], OpTy);
3960       uint64_t AlignRecord = Record[3];
3961       const uint64_t InAllocaMask = uint64_t(1) << 5;
3962       bool InAlloca = AlignRecord & InAllocaMask;
3963       unsigned Align;
3964       if (std::error_code EC =
3965           parseAlignmentValue(AlignRecord & ~InAllocaMask, Align)) {
3966         return EC;
3967       }
3968       if (!Ty || !Size)
3969         return Error("Invalid record");
3970       AllocaInst *AI = new AllocaInst(Ty->getElementType(), Size, Align);
3971       AI->setUsedWithInAlloca(InAlloca);
3972       I = AI;
3973       InstructionList.push_back(I);
3974       break;
3975     }
3976     case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
3977       unsigned OpNum = 0;
3978       Value *Op;
3979       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3980           (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
3981         return Error("Invalid record");
3982
3983       Type *Ty = nullptr;
3984       if (OpNum + 3 == Record.size())
3985         Ty = getTypeByID(Record[OpNum++]);
3986
3987       unsigned Align;
3988       if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
3989         return EC;
3990       I = new LoadInst(Op, "", Record[OpNum+1], Align);
3991
3992       if (Ty && Ty != I->getType())
3993         return Error("Explicit load type does not match pointee type of "
3994                      "pointer operand");
3995
3996       InstructionList.push_back(I);
3997       break;
3998     }
3999     case bitc::FUNC_CODE_INST_LOADATOMIC: {
4000        // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4001       unsigned OpNum = 0;
4002       Value *Op;
4003       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4004           (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
4005         return Error("Invalid record");
4006
4007       Type *Ty = nullptr;
4008       if (OpNum + 5 == Record.size())
4009         Ty = getTypeByID(Record[OpNum++]);
4010
4011       AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
4012       if (Ordering == NotAtomic || Ordering == Release ||
4013           Ordering == AcquireRelease)
4014         return Error("Invalid record");
4015       if (Ordering != NotAtomic && Record[OpNum] == 0)
4016         return Error("Invalid record");
4017       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
4018
4019       unsigned Align;
4020       if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4021         return EC;
4022       I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
4023
4024       (void)Ty;
4025       assert((!Ty || Ty == I->getType()) &&
4026              "Explicit type doesn't match pointee type of the first operand");
4027
4028       InstructionList.push_back(I);
4029       break;
4030     }
4031     case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
4032       unsigned OpNum = 0;
4033       Value *Val, *Ptr;
4034       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4035           popValue(Record, OpNum, NextValueNo,
4036                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4037           OpNum+2 != Record.size())
4038         return Error("Invalid record");
4039       unsigned Align;
4040       if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4041         return EC;
4042       I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4043       InstructionList.push_back(I);
4044       break;
4045     }
4046     case bitc::FUNC_CODE_INST_STOREATOMIC: {
4047       // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4048       unsigned OpNum = 0;
4049       Value *Val, *Ptr;
4050       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4051           popValue(Record, OpNum, NextValueNo,
4052                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4053           OpNum+4 != Record.size())
4054         return Error("Invalid record");
4055
4056       AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
4057       if (Ordering == NotAtomic || Ordering == Acquire ||
4058           Ordering == AcquireRelease)
4059         return Error("Invalid record");
4060       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
4061       if (Ordering != NotAtomic && Record[OpNum] == 0)
4062         return Error("Invalid record");
4063
4064       unsigned Align;
4065       if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4066         return EC;
4067       I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
4068       InstructionList.push_back(I);
4069       break;
4070     }
4071     case bitc::FUNC_CODE_INST_CMPXCHG: {
4072       // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
4073       //          failureordering?, isweak?]
4074       unsigned OpNum = 0;
4075       Value *Ptr, *Cmp, *New;
4076       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4077           popValue(Record, OpNum, NextValueNo,
4078                     cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
4079           popValue(Record, OpNum, NextValueNo,
4080                     cast<PointerType>(Ptr->getType())->getElementType(), New) ||
4081           (Record.size() < OpNum + 3 || Record.size() > OpNum + 5))
4082         return Error("Invalid record");
4083       AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
4084       if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
4085         return Error("Invalid record");
4086       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
4087
4088       AtomicOrdering FailureOrdering;
4089       if (Record.size() < 7)
4090         FailureOrdering =
4091             AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4092       else
4093         FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
4094
4095       I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4096                                 SynchScope);
4097       cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
4098
4099       if (Record.size() < 8) {
4100         // Before weak cmpxchgs existed, the instruction simply returned the
4101         // value loaded from memory, so bitcode files from that era will be
4102         // expecting the first component of a modern cmpxchg.
4103         CurBB->getInstList().push_back(I);
4104         I = ExtractValueInst::Create(I, 0);
4105       } else {
4106         cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4107       }
4108
4109       InstructionList.push_back(I);
4110       break;
4111     }
4112     case bitc::FUNC_CODE_INST_ATOMICRMW: {
4113       // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
4114       unsigned OpNum = 0;
4115       Value *Ptr, *Val;
4116       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4117           popValue(Record, OpNum, NextValueNo,
4118                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4119           OpNum+4 != Record.size())
4120         return Error("Invalid record");
4121       AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
4122       if (Operation < AtomicRMWInst::FIRST_BINOP ||
4123           Operation > AtomicRMWInst::LAST_BINOP)
4124         return Error("Invalid record");
4125       AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
4126       if (Ordering == NotAtomic || Ordering == Unordered)
4127         return Error("Invalid record");
4128       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
4129       I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
4130       cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
4131       InstructionList.push_back(I);
4132       break;
4133     }
4134     case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
4135       if (2 != Record.size())
4136         return Error("Invalid record");
4137       AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
4138       if (Ordering == NotAtomic || Ordering == Unordered ||
4139           Ordering == Monotonic)
4140         return Error("Invalid record");
4141       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
4142       I = new FenceInst(Context, Ordering, SynchScope);
4143       InstructionList.push_back(I);
4144       break;
4145     }
4146     case bitc::FUNC_CODE_INST_CALL: {
4147       // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
4148       if (Record.size() < 3)
4149         return Error("Invalid record");
4150
4151       AttributeSet PAL = getAttributes(Record[0]);
4152       unsigned CCInfo = Record[1];
4153
4154       unsigned OpNum = 2;
4155       Value *Callee;
4156       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4157         return Error("Invalid record");
4158
4159       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
4160       FunctionType *FTy = nullptr;
4161       if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
4162       if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
4163         return Error("Invalid record");
4164
4165       SmallVector<Value*, 16> Args;
4166       // Read the fixed params.
4167       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4168         if (FTy->getParamType(i)->isLabelTy())
4169           Args.push_back(getBasicBlock(Record[OpNum]));
4170         else
4171           Args.push_back(getValue(Record, OpNum, NextValueNo,
4172                                   FTy->getParamType(i)));
4173         if (!Args.back())
4174           return Error("Invalid record");
4175       }
4176
4177       // Read type/value pairs for varargs params.
4178       if (!FTy->isVarArg()) {
4179         if (OpNum != Record.size())
4180           return Error("Invalid record");
4181       } else {
4182         while (OpNum != Record.size()) {
4183           Value *Op;
4184           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4185             return Error("Invalid record");
4186           Args.push_back(Op);
4187         }
4188       }
4189
4190       I = CallInst::Create(Callee, Args);
4191       InstructionList.push_back(I);
4192       cast<CallInst>(I)->setCallingConv(
4193           static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
4194       CallInst::TailCallKind TCK = CallInst::TCK_None;
4195       if (CCInfo & 1)
4196         TCK = CallInst::TCK_Tail;
4197       if (CCInfo & (1 << 14))
4198         TCK = CallInst::TCK_MustTail;
4199       cast<CallInst>(I)->setTailCallKind(TCK);
4200       cast<CallInst>(I)->setAttributes(PAL);
4201       break;
4202     }
4203     case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
4204       if (Record.size() < 3)
4205         return Error("Invalid record");
4206       Type *OpTy = getTypeByID(Record[0]);
4207       Value *Op = getValue(Record, 1, NextValueNo, OpTy);
4208       Type *ResTy = getTypeByID(Record[2]);
4209       if (!OpTy || !Op || !ResTy)
4210         return Error("Invalid record");
4211       I = new VAArgInst(Op, ResTy);
4212       InstructionList.push_back(I);
4213       break;
4214     }
4215     }
4216
4217     // Add instruction to end of current BB.  If there is no current BB, reject
4218     // this file.
4219     if (!CurBB) {
4220       delete I;
4221       return Error("Invalid instruction with no BB");
4222     }
4223     CurBB->getInstList().push_back(I);
4224
4225     // If this was a terminator instruction, move to the next block.
4226     if (isa<TerminatorInst>(I)) {
4227       ++CurBBNo;
4228       CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
4229     }
4230
4231     // Non-void values get registered in the value table for future use.
4232     if (I && !I->getType()->isVoidTy())
4233       ValueList.AssignValue(I, NextValueNo++);
4234   }
4235
4236 OutOfRecordLoop:
4237
4238   // Check the function list for unresolved values.
4239   if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
4240     if (!A->getParent()) {
4241       // We found at least one unresolved value.  Nuke them all to avoid leaks.
4242       for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
4243         if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
4244           A->replaceAllUsesWith(UndefValue::get(A->getType()));
4245           delete A;
4246         }
4247       }
4248       return Error("Never resolved value found in function");
4249     }
4250   }
4251
4252   // FIXME: Check for unresolved forward-declared metadata references
4253   // and clean up leaks.
4254
4255   // Trim the value list down to the size it was before we parsed this function.
4256   ValueList.shrinkTo(ModuleValueListSize);
4257   MDValueList.shrinkTo(ModuleMDValueListSize);
4258   std::vector<BasicBlock*>().swap(FunctionBBs);
4259   return std::error_code();
4260 }
4261
4262 /// Find the function body in the bitcode stream
4263 std::error_code BitcodeReader::FindFunctionInStream(
4264     Function *F,
4265     DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
4266   while (DeferredFunctionInfoIterator->second == 0) {
4267     if (Stream.AtEndOfStream())
4268       return Error("Could not find function in stream");
4269     // ParseModule will parse the next body in the stream and set its
4270     // position in the DeferredFunctionInfo map.
4271     if (std::error_code EC = ParseModule(true))
4272       return EC;
4273   }
4274   return std::error_code();
4275 }
4276
4277 //===----------------------------------------------------------------------===//
4278 // GVMaterializer implementation
4279 //===----------------------------------------------------------------------===//
4280
4281 void BitcodeReader::releaseBuffer() { Buffer.release(); }
4282
4283 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
4284   if (std::error_code EC = materializeMetadata())
4285     return EC;
4286
4287   Function *F = dyn_cast<Function>(GV);
4288   // If it's not a function or is already material, ignore the request.
4289   if (!F || !F->isMaterializable())
4290     return std::error_code();
4291
4292   DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
4293   assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
4294   // If its position is recorded as 0, its body is somewhere in the stream
4295   // but we haven't seen it yet.
4296   if (DFII->second == 0 && LazyStreamer)
4297     if (std::error_code EC = FindFunctionInStream(F, DFII))
4298       return EC;
4299
4300   // Move the bit stream to the saved position of the deferred function body.
4301   Stream.JumpToBit(DFII->second);
4302
4303   if (std::error_code EC = ParseFunctionBody(F))
4304     return EC;
4305   F->setIsMaterializable(false);
4306
4307   // Upgrade any old intrinsic calls in the function.
4308   for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
4309        E = UpgradedIntrinsics.end(); I != E; ++I) {
4310     if (I->first != I->second) {
4311       for (auto UI = I->first->user_begin(), UE = I->first->user_end();
4312            UI != UE;) {
4313         if (CallInst* CI = dyn_cast<CallInst>(*UI++))
4314           UpgradeIntrinsicCall(CI, I->second);
4315       }
4316     }
4317   }
4318
4319   // Bring in any functions that this function forward-referenced via
4320   // blockaddresses.
4321   return materializeForwardReferencedFunctions();
4322 }
4323
4324 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
4325   const Function *F = dyn_cast<Function>(GV);
4326   if (!F || F->isDeclaration())
4327     return false;
4328
4329   // Dematerializing F would leave dangling references that wouldn't be
4330   // reconnected on re-materialization.
4331   if (BlockAddressesTaken.count(F))
4332     return false;
4333
4334   return DeferredFunctionInfo.count(const_cast<Function*>(F));
4335 }
4336
4337 void BitcodeReader::Dematerialize(GlobalValue *GV) {
4338   Function *F = dyn_cast<Function>(GV);
4339   // If this function isn't dematerializable, this is a noop.
4340   if (!F || !isDematerializable(F))
4341     return;
4342
4343   assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
4344
4345   // Just forget the function body, we can remat it later.
4346   F->dropAllReferences();
4347   F->setIsMaterializable(true);
4348 }
4349
4350 std::error_code BitcodeReader::MaterializeModule(Module *M) {
4351   assert(M == TheModule &&
4352          "Can only Materialize the Module this BitcodeReader is attached to.");
4353
4354   if (std::error_code EC = materializeMetadata())
4355     return EC;
4356
4357   // Promise to materialize all forward references.
4358   WillMaterializeAllForwardRefs = true;
4359
4360   // Iterate over the module, deserializing any functions that are still on
4361   // disk.
4362   for (Module::iterator F = TheModule->begin(), E = TheModule->end();
4363        F != E; ++F) {
4364     if (std::error_code EC = materialize(F))
4365       return EC;
4366   }
4367   // At this point, if there are any function bodies, the current bit is
4368   // pointing to the END_BLOCK record after them. Now make sure the rest
4369   // of the bits in the module have been read.
4370   if (NextUnreadBit)
4371     ParseModule(true);
4372
4373   // Check that all block address forward references got resolved (as we
4374   // promised above).
4375   if (!BasicBlockFwdRefs.empty())
4376     return Error("Never resolved function from blockaddress");
4377
4378   // Upgrade any intrinsic calls that slipped through (should not happen!) and
4379   // delete the old functions to clean up. We can't do this unless the entire
4380   // module is materialized because there could always be another function body
4381   // with calls to the old function.
4382   for (std::vector<std::pair<Function*, Function*> >::iterator I =
4383        UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
4384     if (I->first != I->second) {
4385       for (auto UI = I->first->user_begin(), UE = I->first->user_end();
4386            UI != UE;) {
4387         if (CallInst* CI = dyn_cast<CallInst>(*UI++))
4388           UpgradeIntrinsicCall(CI, I->second);
4389       }
4390       if (!I->first->use_empty())
4391         I->first->replaceAllUsesWith(I->second);
4392       I->first->eraseFromParent();
4393     }
4394   }
4395   std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
4396
4397   for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
4398     UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
4399
4400   UpgradeDebugInfo(*M);
4401   return std::error_code();
4402 }
4403
4404 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
4405   return IdentifiedStructTypes;
4406 }
4407
4408 std::error_code BitcodeReader::InitStream() {
4409   if (LazyStreamer)
4410     return InitLazyStream();
4411   return InitStreamFromBuffer();
4412 }
4413
4414 std::error_code BitcodeReader::InitStreamFromBuffer() {
4415   const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
4416   const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
4417
4418   if (Buffer->getBufferSize() & 3)
4419     return Error("Invalid bitcode signature");
4420
4421   // If we have a wrapper header, parse it and ignore the non-bc file contents.
4422   // The magic number is 0x0B17C0DE stored in little endian.
4423   if (isBitcodeWrapper(BufPtr, BufEnd))
4424     if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
4425       return Error("Invalid bitcode wrapper header");
4426
4427   StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
4428   Stream.init(&*StreamFile);
4429
4430   return std::error_code();
4431 }
4432
4433 std::error_code BitcodeReader::InitLazyStream() {
4434   // Check and strip off the bitcode wrapper; BitstreamReader expects never to
4435   // see it.
4436   auto OwnedBytes = llvm::make_unique<StreamingMemoryObject>(LazyStreamer);
4437   StreamingMemoryObject &Bytes = *OwnedBytes;
4438   StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
4439   Stream.init(&*StreamFile);
4440
4441   unsigned char buf[16];
4442   if (Bytes.readBytes(buf, 16, 0) != 16)
4443     return Error("Invalid bitcode signature");
4444
4445   if (!isBitcode(buf, buf + 16))
4446     return Error("Invalid bitcode signature");
4447
4448   if (isBitcodeWrapper(buf, buf + 4)) {
4449     const unsigned char *bitcodeStart = buf;
4450     const unsigned char *bitcodeEnd = buf + 16;
4451     SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
4452     Bytes.dropLeadingBytes(bitcodeStart - buf);
4453     Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
4454   }
4455   return std::error_code();
4456 }
4457
4458 namespace {
4459 class BitcodeErrorCategoryType : public std::error_category {
4460   const char *name() const LLVM_NOEXCEPT override {
4461     return "llvm.bitcode";
4462   }
4463   std::string message(int IE) const override {
4464     BitcodeError E = static_cast<BitcodeError>(IE);
4465     switch (E) {
4466     case BitcodeError::InvalidBitcodeSignature:
4467       return "Invalid bitcode signature";
4468     case BitcodeError::CorruptedBitcode:
4469       return "Corrupted bitcode";
4470     }
4471     llvm_unreachable("Unknown error type!");
4472   }
4473 };
4474 }
4475
4476 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
4477
4478 const std::error_category &llvm::BitcodeErrorCategory() {
4479   return *ErrorCategory;
4480 }
4481
4482 //===----------------------------------------------------------------------===//
4483 // External interface
4484 //===----------------------------------------------------------------------===//
4485
4486 /// \brief Get a lazy one-at-time loading module from bitcode.
4487 ///
4488 /// This isn't always used in a lazy context.  In particular, it's also used by
4489 /// \a parseBitcodeFile().  If this is truly lazy, then we need to eagerly pull
4490 /// in forward-referenced functions from block address references.
4491 ///
4492 /// \param[in] WillMaterializeAll Set to \c true if the caller promises to
4493 /// materialize everything -- in particular, if this isn't truly lazy.
4494 static ErrorOr<Module *>
4495 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
4496                          LLVMContext &Context, bool WillMaterializeAll,
4497                          DiagnosticHandlerFunction DiagnosticHandler,
4498                          bool ShouldLazyLoadMetadata = false) {
4499   Module *M = new Module(Buffer->getBufferIdentifier(), Context);
4500   BitcodeReader *R =
4501       new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
4502   M->setMaterializer(R);
4503
4504   auto cleanupOnError = [&](std::error_code EC) {
4505     R->releaseBuffer(); // Never take ownership on error.
4506     delete M;  // Also deletes R.
4507     return EC;
4508   };
4509
4510   // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
4511   if (std::error_code EC = R->ParseBitcodeInto(M, ShouldLazyLoadMetadata))
4512     return cleanupOnError(EC);
4513
4514   if (!WillMaterializeAll)
4515     // Resolve forward references from blockaddresses.
4516     if (std::error_code EC = R->materializeForwardReferencedFunctions())
4517       return cleanupOnError(EC);
4518
4519   Buffer.release(); // The BitcodeReader owns it now.
4520   return M;
4521 }
4522
4523 ErrorOr<Module *>
4524 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
4525                            LLVMContext &Context,
4526                            DiagnosticHandlerFunction DiagnosticHandler,
4527                            bool ShouldLazyLoadMetadata) {
4528   return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
4529                                   DiagnosticHandler, ShouldLazyLoadMetadata);
4530 }
4531
4532 ErrorOr<std::unique_ptr<Module>>
4533 llvm::getStreamedBitcodeModule(StringRef Name, DataStreamer *Streamer,
4534                                LLVMContext &Context,
4535                                DiagnosticHandlerFunction DiagnosticHandler) {
4536   std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
4537   BitcodeReader *R = new BitcodeReader(Streamer, Context, DiagnosticHandler);
4538   M->setMaterializer(R);
4539   if (std::error_code EC = R->ParseBitcodeInto(M.get()))
4540     return EC;
4541   return std::move(M);
4542 }
4543
4544 ErrorOr<Module *>
4545 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
4546                        DiagnosticHandlerFunction DiagnosticHandler) {
4547   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
4548   ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModuleImpl(
4549       std::move(Buf), Context, true, DiagnosticHandler);
4550   if (!ModuleOrErr)
4551     return ModuleOrErr;
4552   Module *M = ModuleOrErr.get();
4553   // Read in the entire module, and destroy the BitcodeReader.
4554   if (std::error_code EC = M->materializeAllPermanently()) {
4555     delete M;
4556     return EC;
4557   }
4558
4559   // TODO: Restore the use-lists to the in-memory state when the bitcode was
4560   // written.  We must defer until the Module has been fully materialized.
4561
4562   return M;
4563 }
4564
4565 std::string
4566 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
4567                              DiagnosticHandlerFunction DiagnosticHandler) {
4568   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
4569   auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
4570                                             DiagnosticHandler);
4571   ErrorOr<std::string> Triple = R->parseTriple();
4572   if (Triple.getError())
4573     return "";
4574   return Triple.get();
4575 }