]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Bitcode/Reader/BitcodeReader.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ trunk r321545,
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / Bitcode / Reader / BitcodeReader.cpp
1 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "llvm/Bitcode/BitcodeReader.h"
11 #include "MetadataLoader.h"
12 #include "ValueList.h"
13 #include "llvm/ADT/APFloat.h"
14 #include "llvm/ADT/APInt.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/Optional.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/ADT/Twine.h"
24 #include "llvm/Bitcode/BitstreamReader.h"
25 #include "llvm/Bitcode/LLVMBitCodes.h"
26 #include "llvm/IR/Argument.h"
27 #include "llvm/IR/Attributes.h"
28 #include "llvm/IR/AutoUpgrade.h"
29 #include "llvm/IR/BasicBlock.h"
30 #include "llvm/IR/CallSite.h"
31 #include "llvm/IR/CallingConv.h"
32 #include "llvm/IR/Comdat.h"
33 #include "llvm/IR/Constant.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/DataLayout.h"
36 #include "llvm/IR/DebugInfo.h"
37 #include "llvm/IR/DebugInfoMetadata.h"
38 #include "llvm/IR/DebugLoc.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GVMaterializer.h"
42 #include "llvm/IR/GlobalAlias.h"
43 #include "llvm/IR/GlobalIFunc.h"
44 #include "llvm/IR/GlobalIndirectSymbol.h"
45 #include "llvm/IR/GlobalObject.h"
46 #include "llvm/IR/GlobalValue.h"
47 #include "llvm/IR/GlobalVariable.h"
48 #include "llvm/IR/InlineAsm.h"
49 #include "llvm/IR/InstIterator.h"
50 #include "llvm/IR/InstrTypes.h"
51 #include "llvm/IR/Instruction.h"
52 #include "llvm/IR/Instructions.h"
53 #include "llvm/IR/Intrinsics.h"
54 #include "llvm/IR/LLVMContext.h"
55 #include "llvm/IR/Metadata.h"
56 #include "llvm/IR/Module.h"
57 #include "llvm/IR/ModuleSummaryIndex.h"
58 #include "llvm/IR/Operator.h"
59 #include "llvm/IR/Type.h"
60 #include "llvm/IR/Value.h"
61 #include "llvm/IR/Verifier.h"
62 #include "llvm/Support/AtomicOrdering.h"
63 #include "llvm/Support/Casting.h"
64 #include "llvm/Support/CommandLine.h"
65 #include "llvm/Support/Compiler.h"
66 #include "llvm/Support/Debug.h"
67 #include "llvm/Support/Error.h"
68 #include "llvm/Support/ErrorHandling.h"
69 #include "llvm/Support/ErrorOr.h"
70 #include "llvm/Support/ManagedStatic.h"
71 #include "llvm/Support/MathExtras.h"
72 #include "llvm/Support/MemoryBuffer.h"
73 #include "llvm/Support/raw_ostream.h"
74 #include <algorithm>
75 #include <cassert>
76 #include <cstddef>
77 #include <cstdint>
78 #include <deque>
79 #include <map>
80 #include <memory>
81 #include <set>
82 #include <string>
83 #include <system_error>
84 #include <tuple>
85 #include <utility>
86 #include <vector>
87
88 using namespace llvm;
89
90 static cl::opt<bool> PrintSummaryGUIDs(
91     "print-summary-global-ids", cl::init(false), cl::Hidden,
92     cl::desc(
93         "Print the global id for each value when reading the module summary"));
94
95 namespace {
96
97 enum {
98   SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
99 };
100
101 } // end anonymous namespace
102
103 static Error error(const Twine &Message) {
104   return make_error<StringError>(
105       Message, make_error_code(BitcodeError::CorruptedBitcode));
106 }
107
108 /// Helper to read the header common to all bitcode files.
109 static bool hasValidBitcodeHeader(BitstreamCursor &Stream) {
110   // Sniff for the signature.
111   if (!Stream.canSkipToPos(4) ||
112       Stream.Read(8) != 'B' ||
113       Stream.Read(8) != 'C' ||
114       Stream.Read(4) != 0x0 ||
115       Stream.Read(4) != 0xC ||
116       Stream.Read(4) != 0xE ||
117       Stream.Read(4) != 0xD)
118     return false;
119   return true;
120 }
121
122 static Expected<BitstreamCursor> initStream(MemoryBufferRef Buffer) {
123   const unsigned char *BufPtr = (const unsigned char *)Buffer.getBufferStart();
124   const unsigned char *BufEnd = BufPtr + Buffer.getBufferSize();
125
126   if (Buffer.getBufferSize() & 3)
127     return error("Invalid bitcode signature");
128
129   // If we have a wrapper header, parse it and ignore the non-bc file contents.
130   // The magic number is 0x0B17C0DE stored in little endian.
131   if (isBitcodeWrapper(BufPtr, BufEnd))
132     if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
133       return error("Invalid bitcode wrapper header");
134
135   BitstreamCursor Stream(ArrayRef<uint8_t>(BufPtr, BufEnd));
136   if (!hasValidBitcodeHeader(Stream))
137     return error("Invalid bitcode signature");
138
139   return std::move(Stream);
140 }
141
142 /// Convert a string from a record into an std::string, return true on failure.
143 template <typename StrTy>
144 static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
145                             StrTy &Result) {
146   if (Idx > Record.size())
147     return true;
148
149   for (unsigned i = Idx, e = Record.size(); i != e; ++i)
150     Result += (char)Record[i];
151   return false;
152 }
153
154 // Strip all the TBAA attachment for the module.
155 static void stripTBAA(Module *M) {
156   for (auto &F : *M) {
157     if (F.isMaterializable())
158       continue;
159     for (auto &I : instructions(F))
160       I.setMetadata(LLVMContext::MD_tbaa, nullptr);
161   }
162 }
163
164 /// Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the
165 /// "epoch" encoded in the bitcode, and return the producer name if any.
166 static Expected<std::string> readIdentificationBlock(BitstreamCursor &Stream) {
167   if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
168     return error("Invalid record");
169
170   // Read all the records.
171   SmallVector<uint64_t, 64> Record;
172
173   std::string ProducerIdentification;
174
175   while (true) {
176     BitstreamEntry Entry = Stream.advance();
177
178     switch (Entry.Kind) {
179     default:
180     case BitstreamEntry::Error:
181       return error("Malformed block");
182     case BitstreamEntry::EndBlock:
183       return ProducerIdentification;
184     case BitstreamEntry::Record:
185       // The interesting case.
186       break;
187     }
188
189     // Read a record.
190     Record.clear();
191     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
192     switch (BitCode) {
193     default: // Default behavior: reject
194       return error("Invalid value");
195     case bitc::IDENTIFICATION_CODE_STRING: // IDENTIFICATION: [strchr x N]
196       convertToString(Record, 0, ProducerIdentification);
197       break;
198     case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
199       unsigned epoch = (unsigned)Record[0];
200       if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
201         return error(
202           Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
203           "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
204       }
205     }
206     }
207   }
208 }
209
210 static Expected<std::string> readIdentificationCode(BitstreamCursor &Stream) {
211   // We expect a number of well-defined blocks, though we don't necessarily
212   // need to understand them all.
213   while (true) {
214     if (Stream.AtEndOfStream())
215       return "";
216
217     BitstreamEntry Entry = Stream.advance();
218     switch (Entry.Kind) {
219     case BitstreamEntry::EndBlock:
220     case BitstreamEntry::Error:
221       return error("Malformed block");
222
223     case BitstreamEntry::SubBlock:
224       if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID)
225         return readIdentificationBlock(Stream);
226
227       // Ignore other sub-blocks.
228       if (Stream.SkipBlock())
229         return error("Malformed block");
230       continue;
231     case BitstreamEntry::Record:
232       Stream.skipRecord(Entry.ID);
233       continue;
234     }
235   }
236 }
237
238 static Expected<bool> hasObjCCategoryInModule(BitstreamCursor &Stream) {
239   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
240     return error("Invalid record");
241
242   SmallVector<uint64_t, 64> Record;
243   // Read all the records for this module.
244
245   while (true) {
246     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
247
248     switch (Entry.Kind) {
249     case BitstreamEntry::SubBlock: // Handled for us already.
250     case BitstreamEntry::Error:
251       return error("Malformed block");
252     case BitstreamEntry::EndBlock:
253       return false;
254     case BitstreamEntry::Record:
255       // The interesting case.
256       break;
257     }
258
259     // Read a record.
260     switch (Stream.readRecord(Entry.ID, Record)) {
261     default:
262       break; // Default behavior, ignore unknown content.
263     case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
264       std::string S;
265       if (convertToString(Record, 0, S))
266         return error("Invalid record");
267       // Check for the i386 and other (x86_64, ARM) conventions
268       if (S.find("__DATA,__objc_catlist") != std::string::npos ||
269           S.find("__OBJC,__category") != std::string::npos)
270         return true;
271       break;
272     }
273     }
274     Record.clear();
275   }
276   llvm_unreachable("Exit infinite loop");
277 }
278
279 static Expected<bool> hasObjCCategory(BitstreamCursor &Stream) {
280   // We expect a number of well-defined blocks, though we don't necessarily
281   // need to understand them all.
282   while (true) {
283     BitstreamEntry Entry = Stream.advance();
284
285     switch (Entry.Kind) {
286     case BitstreamEntry::Error:
287       return error("Malformed block");
288     case BitstreamEntry::EndBlock:
289       return false;
290
291     case BitstreamEntry::SubBlock:
292       if (Entry.ID == bitc::MODULE_BLOCK_ID)
293         return hasObjCCategoryInModule(Stream);
294
295       // Ignore other sub-blocks.
296       if (Stream.SkipBlock())
297         return error("Malformed block");
298       continue;
299
300     case BitstreamEntry::Record:
301       Stream.skipRecord(Entry.ID);
302       continue;
303     }
304   }
305 }
306
307 static Expected<std::string> readModuleTriple(BitstreamCursor &Stream) {
308   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
309     return error("Invalid record");
310
311   SmallVector<uint64_t, 64> Record;
312
313   std::string Triple;
314
315   // Read all the records for this module.
316   while (true) {
317     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
318
319     switch (Entry.Kind) {
320     case BitstreamEntry::SubBlock: // Handled for us already.
321     case BitstreamEntry::Error:
322       return error("Malformed block");
323     case BitstreamEntry::EndBlock:
324       return Triple;
325     case BitstreamEntry::Record:
326       // The interesting case.
327       break;
328     }
329
330     // Read a record.
331     switch (Stream.readRecord(Entry.ID, Record)) {
332     default: break;  // Default behavior, ignore unknown content.
333     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
334       std::string S;
335       if (convertToString(Record, 0, S))
336         return error("Invalid record");
337       Triple = S;
338       break;
339     }
340     }
341     Record.clear();
342   }
343   llvm_unreachable("Exit infinite loop");
344 }
345
346 static Expected<std::string> readTriple(BitstreamCursor &Stream) {
347   // We expect a number of well-defined blocks, though we don't necessarily
348   // need to understand them all.
349   while (true) {
350     BitstreamEntry Entry = Stream.advance();
351
352     switch (Entry.Kind) {
353     case BitstreamEntry::Error:
354       return error("Malformed block");
355     case BitstreamEntry::EndBlock:
356       return "";
357
358     case BitstreamEntry::SubBlock:
359       if (Entry.ID == bitc::MODULE_BLOCK_ID)
360         return readModuleTriple(Stream);
361
362       // Ignore other sub-blocks.
363       if (Stream.SkipBlock())
364         return error("Malformed block");
365       continue;
366
367     case BitstreamEntry::Record:
368       Stream.skipRecord(Entry.ID);
369       continue;
370     }
371   }
372 }
373
374 namespace {
375
376 class BitcodeReaderBase {
377 protected:
378   BitcodeReaderBase(BitstreamCursor Stream, StringRef Strtab)
379       : Stream(std::move(Stream)), Strtab(Strtab) {
380     this->Stream.setBlockInfo(&BlockInfo);
381   }
382
383   BitstreamBlockInfo BlockInfo;
384   BitstreamCursor Stream;
385   StringRef Strtab;
386
387   /// In version 2 of the bitcode we store names of global values and comdats in
388   /// a string table rather than in the VST.
389   bool UseStrtab = false;
390
391   Expected<unsigned> parseVersionRecord(ArrayRef<uint64_t> Record);
392
393   /// If this module uses a string table, pop the reference to the string table
394   /// and return the referenced string and the rest of the record. Otherwise
395   /// just return the record itself.
396   std::pair<StringRef, ArrayRef<uint64_t>>
397   readNameFromStrtab(ArrayRef<uint64_t> Record);
398
399   bool readBlockInfo();
400
401   // Contains an arbitrary and optional string identifying the bitcode producer
402   std::string ProducerIdentification;
403
404   Error error(const Twine &Message);
405 };
406
407 } // end anonymous namespace
408
409 Error BitcodeReaderBase::error(const Twine &Message) {
410   std::string FullMsg = Message.str();
411   if (!ProducerIdentification.empty())
412     FullMsg += " (Producer: '" + ProducerIdentification + "' Reader: 'LLVM " +
413                LLVM_VERSION_STRING "')";
414   return ::error(FullMsg);
415 }
416
417 Expected<unsigned>
418 BitcodeReaderBase::parseVersionRecord(ArrayRef<uint64_t> Record) {
419   if (Record.empty())
420     return error("Invalid record");
421   unsigned ModuleVersion = Record[0];
422   if (ModuleVersion > 2)
423     return error("Invalid value");
424   UseStrtab = ModuleVersion >= 2;
425   return ModuleVersion;
426 }
427
428 std::pair<StringRef, ArrayRef<uint64_t>>
429 BitcodeReaderBase::readNameFromStrtab(ArrayRef<uint64_t> Record) {
430   if (!UseStrtab)
431     return {"", Record};
432   // Invalid reference. Let the caller complain about the record being empty.
433   if (Record[0] + Record[1] > Strtab.size())
434     return {"", {}};
435   return {StringRef(Strtab.data() + Record[0], Record[1]), Record.slice(2)};
436 }
437
438 namespace {
439
440 class BitcodeReader : public BitcodeReaderBase, public GVMaterializer {
441   LLVMContext &Context;
442   Module *TheModule = nullptr;
443   // Next offset to start scanning for lazy parsing of function bodies.
444   uint64_t NextUnreadBit = 0;
445   // Last function offset found in the VST.
446   uint64_t LastFunctionBlockBit = 0;
447   bool SeenValueSymbolTable = false;
448   uint64_t VSTOffset = 0;
449
450   std::vector<std::string> SectionTable;
451   std::vector<std::string> GCTable;
452
453   std::vector<Type*> TypeList;
454   BitcodeReaderValueList ValueList;
455   Optional<MetadataLoader> MDLoader;
456   std::vector<Comdat *> ComdatList;
457   SmallVector<Instruction *, 64> InstructionList;
458
459   std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInits;
460   std::vector<std::pair<GlobalIndirectSymbol *, unsigned>> IndirectSymbolInits;
461   std::vector<std::pair<Function *, unsigned>> FunctionPrefixes;
462   std::vector<std::pair<Function *, unsigned>> FunctionPrologues;
463   std::vector<std::pair<Function *, unsigned>> FunctionPersonalityFns;
464
465   /// The set of attributes by index.  Index zero in the file is for null, and
466   /// is thus not represented here.  As such all indices are off by one.
467   std::vector<AttributeList> MAttributes;
468
469   /// The set of attribute groups.
470   std::map<unsigned, AttributeList> MAttributeGroups;
471
472   /// While parsing a function body, this is a list of the basic blocks for the
473   /// function.
474   std::vector<BasicBlock*> FunctionBBs;
475
476   // When reading the module header, this list is populated with functions that
477   // have bodies later in the file.
478   std::vector<Function*> FunctionsWithBodies;
479
480   // When intrinsic functions are encountered which require upgrading they are
481   // stored here with their replacement function.
482   using UpdatedIntrinsicMap = DenseMap<Function *, Function *>;
483   UpdatedIntrinsicMap UpgradedIntrinsics;
484   // Intrinsics which were remangled because of types rename
485   UpdatedIntrinsicMap RemangledIntrinsics;
486
487   // Several operations happen after the module header has been read, but
488   // before function bodies are processed. This keeps track of whether
489   // we've done this yet.
490   bool SeenFirstFunctionBody = false;
491
492   /// When function bodies are initially scanned, this map contains info about
493   /// where to find deferred function body in the stream.
494   DenseMap<Function*, uint64_t> DeferredFunctionInfo;
495
496   /// When Metadata block is initially scanned when parsing the module, we may
497   /// choose to defer parsing of the metadata. This vector contains info about
498   /// which Metadata blocks are deferred.
499   std::vector<uint64_t> DeferredMetadataInfo;
500
501   /// These are basic blocks forward-referenced by block addresses.  They are
502   /// inserted lazily into functions when they're loaded.  The basic block ID is
503   /// its index into the vector.
504   DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
505   std::deque<Function *> BasicBlockFwdRefQueue;
506
507   /// Indicates that we are using a new encoding for instruction operands where
508   /// most operands in the current FUNCTION_BLOCK are encoded relative to the
509   /// instruction number, for a more compact encoding.  Some instruction
510   /// operands are not relative to the instruction ID: basic block numbers, and
511   /// types. Once the old style function blocks have been phased out, we would
512   /// not need this flag.
513   bool UseRelativeIDs = false;
514
515   /// True if all functions will be materialized, negating the need to process
516   /// (e.g.) blockaddress forward references.
517   bool WillMaterializeAllForwardRefs = false;
518
519   bool StripDebugInfo = false;
520   TBAAVerifier TBAAVerifyHelper;
521
522   std::vector<std::string> BundleTags;
523   SmallVector<SyncScope::ID, 8> SSIDs;
524
525 public:
526   BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
527                 StringRef ProducerIdentification, LLVMContext &Context);
528
529   Error materializeForwardReferencedFunctions();
530
531   Error materialize(GlobalValue *GV) override;
532   Error materializeModule() override;
533   std::vector<StructType *> getIdentifiedStructTypes() const override;
534
535   /// \brief Main interface to parsing a bitcode buffer.
536   /// \returns true if an error occurred.
537   Error parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata = false,
538                          bool IsImporting = false);
539
540   static uint64_t decodeSignRotatedValue(uint64_t V);
541
542   /// Materialize any deferred Metadata block.
543   Error materializeMetadata() override;
544
545   void setStripDebugInfo() override;
546
547 private:
548   std::vector<StructType *> IdentifiedStructTypes;
549   StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
550   StructType *createIdentifiedStructType(LLVMContext &Context);
551
552   Type *getTypeByID(unsigned ID);
553
554   Value *getFnValueByID(unsigned ID, Type *Ty) {
555     if (Ty && Ty->isMetadataTy())
556       return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
557     return ValueList.getValueFwdRef(ID, Ty);
558   }
559
560   Metadata *getFnMetadataByID(unsigned ID) {
561     return MDLoader->getMetadataFwdRefOrLoad(ID);
562   }
563
564   BasicBlock *getBasicBlock(unsigned ID) const {
565     if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
566     return FunctionBBs[ID];
567   }
568
569   AttributeList getAttributes(unsigned i) const {
570     if (i-1 < MAttributes.size())
571       return MAttributes[i-1];
572     return AttributeList();
573   }
574
575   /// Read a value/type pair out of the specified record from slot 'Slot'.
576   /// Increment Slot past the number of slots used in the record. Return true on
577   /// failure.
578   bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
579                         unsigned InstNum, Value *&ResVal) {
580     if (Slot == Record.size()) return true;
581     unsigned ValNo = (unsigned)Record[Slot++];
582     // Adjust the ValNo, if it was encoded relative to the InstNum.
583     if (UseRelativeIDs)
584       ValNo = InstNum - ValNo;
585     if (ValNo < InstNum) {
586       // If this is not a forward reference, just return the value we already
587       // have.
588       ResVal = getFnValueByID(ValNo, nullptr);
589       return ResVal == nullptr;
590     }
591     if (Slot == Record.size())
592       return true;
593
594     unsigned TypeNo = (unsigned)Record[Slot++];
595     ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
596     return ResVal == nullptr;
597   }
598
599   /// Read a value out of the specified record from slot 'Slot'. Increment Slot
600   /// past the number of slots used by the value in the record. Return true if
601   /// there is an error.
602   bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
603                 unsigned InstNum, Type *Ty, Value *&ResVal) {
604     if (getValue(Record, Slot, InstNum, Ty, ResVal))
605       return true;
606     // All values currently take a single record slot.
607     ++Slot;
608     return false;
609   }
610
611   /// Like popValue, but does not increment the Slot number.
612   bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
613                 unsigned InstNum, Type *Ty, Value *&ResVal) {
614     ResVal = getValue(Record, Slot, InstNum, Ty);
615     return ResVal == nullptr;
616   }
617
618   /// Version of getValue that returns ResVal directly, or 0 if there is an
619   /// error.
620   Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
621                   unsigned InstNum, Type *Ty) {
622     if (Slot == Record.size()) return nullptr;
623     unsigned ValNo = (unsigned)Record[Slot];
624     // Adjust the ValNo, if it was encoded relative to the InstNum.
625     if (UseRelativeIDs)
626       ValNo = InstNum - ValNo;
627     return getFnValueByID(ValNo, Ty);
628   }
629
630   /// Like getValue, but decodes signed VBRs.
631   Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
632                         unsigned InstNum, Type *Ty) {
633     if (Slot == Record.size()) return nullptr;
634     unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
635     // Adjust the ValNo, if it was encoded relative to the InstNum.
636     if (UseRelativeIDs)
637       ValNo = InstNum - ValNo;
638     return getFnValueByID(ValNo, Ty);
639   }
640
641   /// Converts alignment exponent (i.e. power of two (or zero)) to the
642   /// corresponding alignment to use. If alignment is too large, returns
643   /// a corresponding error code.
644   Error parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
645   Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
646   Error parseModule(uint64_t ResumeBit, bool ShouldLazyLoadMetadata = false);
647
648   Error parseComdatRecord(ArrayRef<uint64_t> Record);
649   Error parseGlobalVarRecord(ArrayRef<uint64_t> Record);
650   Error parseFunctionRecord(ArrayRef<uint64_t> Record);
651   Error parseGlobalIndirectSymbolRecord(unsigned BitCode,
652                                         ArrayRef<uint64_t> Record);
653
654   Error parseAttributeBlock();
655   Error parseAttributeGroupBlock();
656   Error parseTypeTable();
657   Error parseTypeTableBody();
658   Error parseOperandBundleTags();
659   Error parseSyncScopeNames();
660
661   Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
662                                 unsigned NameIndex, Triple &TT);
663   void setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, Function *F,
664                                ArrayRef<uint64_t> Record);
665   Error parseValueSymbolTable(uint64_t Offset = 0);
666   Error parseGlobalValueSymbolTable();
667   Error parseConstants();
668   Error rememberAndSkipFunctionBodies();
669   Error rememberAndSkipFunctionBody();
670   /// Save the positions of the Metadata blocks and skip parsing the blocks.
671   Error rememberAndSkipMetadata();
672   Error typeCheckLoadStoreInst(Type *ValType, Type *PtrType);
673   Error parseFunctionBody(Function *F);
674   Error globalCleanup();
675   Error resolveGlobalAndIndirectSymbolInits();
676   Error parseUseLists();
677   Error findFunctionInStream(
678       Function *F,
679       DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
680
681   SyncScope::ID getDecodedSyncScopeID(unsigned Val);
682 };
683
684 /// Class to manage reading and parsing function summary index bitcode
685 /// files/sections.
686 class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase {
687   /// The module index built during parsing.
688   ModuleSummaryIndex &TheIndex;
689
690   /// Indicates whether we have encountered a global value summary section
691   /// yet during parsing.
692   bool SeenGlobalValSummary = false;
693
694   /// Indicates whether we have already parsed the VST, used for error checking.
695   bool SeenValueSymbolTable = false;
696
697   /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record.
698   /// Used to enable on-demand parsing of the VST.
699   uint64_t VSTOffset = 0;
700
701   // Map to save ValueId to ValueInfo association that was recorded in the
702   // ValueSymbolTable. It is used after the VST is parsed to convert
703   // call graph edges read from the function summary from referencing
704   // callees by their ValueId to using the ValueInfo instead, which is how
705   // they are recorded in the summary index being built.
706   // We save a GUID which refers to the same global as the ValueInfo, but
707   // ignoring the linkage, i.e. for values other than local linkage they are
708   // identical.
709   DenseMap<unsigned, std::pair<ValueInfo, GlobalValue::GUID>>
710       ValueIdToValueInfoMap;
711
712   /// Map populated during module path string table parsing, from the
713   /// module ID to a string reference owned by the index's module
714   /// path string table, used to correlate with combined index
715   /// summary records.
716   DenseMap<uint64_t, StringRef> ModuleIdMap;
717
718   /// Original source file name recorded in a bitcode record.
719   std::string SourceFileName;
720
721   /// The string identifier given to this module by the client, normally the
722   /// path to the bitcode file.
723   StringRef ModulePath;
724
725   /// For per-module summary indexes, the unique numerical identifier given to
726   /// this module by the client.
727   unsigned ModuleId;
728
729 public:
730   ModuleSummaryIndexBitcodeReader(BitstreamCursor Stream, StringRef Strtab,
731                                   ModuleSummaryIndex &TheIndex,
732                                   StringRef ModulePath, unsigned ModuleId);
733
734   Error parseModule();
735
736 private:
737   void setValueGUID(uint64_t ValueID, StringRef ValueName,
738                     GlobalValue::LinkageTypes Linkage,
739                     StringRef SourceFileName);
740   Error parseValueSymbolTable(
741       uint64_t Offset,
742       DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
743   std::vector<ValueInfo> makeRefList(ArrayRef<uint64_t> Record);
744   std::vector<FunctionSummary::EdgeTy> makeCallList(ArrayRef<uint64_t> Record,
745                                                     bool IsOldProfileFormat,
746                                                     bool HasProfile);
747   Error parseEntireSummary(unsigned ID);
748   Error parseModuleStringTable();
749
750   std::pair<ValueInfo, GlobalValue::GUID>
751   getValueInfoFromValueId(unsigned ValueId);
752
753   ModuleSummaryIndex::ModuleInfo *addThisModule();
754 };
755
756 } // end anonymous namespace
757
758 std::error_code llvm::errorToErrorCodeAndEmitErrors(LLVMContext &Ctx,
759                                                     Error Err) {
760   if (Err) {
761     std::error_code EC;
762     handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) {
763       EC = EIB.convertToErrorCode();
764       Ctx.emitError(EIB.message());
765     });
766     return EC;
767   }
768   return std::error_code();
769 }
770
771 BitcodeReader::BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
772                              StringRef ProducerIdentification,
773                              LLVMContext &Context)
774     : BitcodeReaderBase(std::move(Stream), Strtab), Context(Context),
775       ValueList(Context) {
776   this->ProducerIdentification = ProducerIdentification;
777 }
778
779 Error BitcodeReader::materializeForwardReferencedFunctions() {
780   if (WillMaterializeAllForwardRefs)
781     return Error::success();
782
783   // Prevent recursion.
784   WillMaterializeAllForwardRefs = true;
785
786   while (!BasicBlockFwdRefQueue.empty()) {
787     Function *F = BasicBlockFwdRefQueue.front();
788     BasicBlockFwdRefQueue.pop_front();
789     assert(F && "Expected valid function");
790     if (!BasicBlockFwdRefs.count(F))
791       // Already materialized.
792       continue;
793
794     // Check for a function that isn't materializable to prevent an infinite
795     // loop.  When parsing a blockaddress stored in a global variable, there
796     // isn't a trivial way to check if a function will have a body without a
797     // linear search through FunctionsWithBodies, so just check it here.
798     if (!F->isMaterializable())
799       return error("Never resolved function from blockaddress");
800
801     // Try to materialize F.
802     if (Error Err = materialize(F))
803       return Err;
804   }
805   assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
806
807   // Reset state.
808   WillMaterializeAllForwardRefs = false;
809   return Error::success();
810 }
811
812 //===----------------------------------------------------------------------===//
813 //  Helper functions to implement forward reference resolution, etc.
814 //===----------------------------------------------------------------------===//
815
816 static bool hasImplicitComdat(size_t Val) {
817   switch (Val) {
818   default:
819     return false;
820   case 1:  // Old WeakAnyLinkage
821   case 4:  // Old LinkOnceAnyLinkage
822   case 10: // Old WeakODRLinkage
823   case 11: // Old LinkOnceODRLinkage
824     return true;
825   }
826 }
827
828 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
829   switch (Val) {
830   default: // Map unknown/new linkages to external
831   case 0:
832     return GlobalValue::ExternalLinkage;
833   case 2:
834     return GlobalValue::AppendingLinkage;
835   case 3:
836     return GlobalValue::InternalLinkage;
837   case 5:
838     return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
839   case 6:
840     return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
841   case 7:
842     return GlobalValue::ExternalWeakLinkage;
843   case 8:
844     return GlobalValue::CommonLinkage;
845   case 9:
846     return GlobalValue::PrivateLinkage;
847   case 12:
848     return GlobalValue::AvailableExternallyLinkage;
849   case 13:
850     return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
851   case 14:
852     return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
853   case 15:
854     return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
855   case 1: // Old value with implicit comdat.
856   case 16:
857     return GlobalValue::WeakAnyLinkage;
858   case 10: // Old value with implicit comdat.
859   case 17:
860     return GlobalValue::WeakODRLinkage;
861   case 4: // Old value with implicit comdat.
862   case 18:
863     return GlobalValue::LinkOnceAnyLinkage;
864   case 11: // Old value with implicit comdat.
865   case 19:
866     return GlobalValue::LinkOnceODRLinkage;
867   }
868 }
869
870 static FunctionSummary::FFlags getDecodedFFlags(uint64_t RawFlags) {
871   FunctionSummary::FFlags Flags;
872   Flags.ReadNone = RawFlags & 0x1;
873   Flags.ReadOnly = (RawFlags >> 1) & 0x1;
874   Flags.NoRecurse = (RawFlags >> 2) & 0x1;
875   Flags.ReturnDoesNotAlias = (RawFlags >> 3) & 0x1;
876   return Flags;
877 }
878
879 /// Decode the flags for GlobalValue in the summary.
880 static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags,
881                                                             uint64_t Version) {
882   // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage
883   // like getDecodedLinkage() above. Any future change to the linkage enum and
884   // to getDecodedLinkage() will need to be taken into account here as above.
885   auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits
886   RawFlags = RawFlags >> 4;
887   bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3;
888   // The Live flag wasn't introduced until version 3. For dead stripping
889   // to work correctly on earlier versions, we must conservatively treat all
890   // values as live.
891   bool Live = (RawFlags & 0x2) || Version < 3;
892   bool Local = (RawFlags & 0x4);
893
894   return GlobalValueSummary::GVFlags(Linkage, NotEligibleToImport, Live, Local);
895 }
896
897 static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
898   switch (Val) {
899   default: // Map unknown visibilities to default.
900   case 0: return GlobalValue::DefaultVisibility;
901   case 1: return GlobalValue::HiddenVisibility;
902   case 2: return GlobalValue::ProtectedVisibility;
903   }
904 }
905
906 static GlobalValue::DLLStorageClassTypes
907 getDecodedDLLStorageClass(unsigned Val) {
908   switch (Val) {
909   default: // Map unknown values to default.
910   case 0: return GlobalValue::DefaultStorageClass;
911   case 1: return GlobalValue::DLLImportStorageClass;
912   case 2: return GlobalValue::DLLExportStorageClass;
913   }
914 }
915
916 static bool getDecodedDSOLocal(unsigned Val) {
917   switch(Val) {
918   default: // Map unknown values to preemptable.
919   case 0:  return false;
920   case 1:  return true;
921   }
922 }
923
924 static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
925   switch (Val) {
926     case 0: return GlobalVariable::NotThreadLocal;
927     default: // Map unknown non-zero value to general dynamic.
928     case 1: return GlobalVariable::GeneralDynamicTLSModel;
929     case 2: return GlobalVariable::LocalDynamicTLSModel;
930     case 3: return GlobalVariable::InitialExecTLSModel;
931     case 4: return GlobalVariable::LocalExecTLSModel;
932   }
933 }
934
935 static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) {
936   switch (Val) {
937     default: // Map unknown to UnnamedAddr::None.
938     case 0: return GlobalVariable::UnnamedAddr::None;
939     case 1: return GlobalVariable::UnnamedAddr::Global;
940     case 2: return GlobalVariable::UnnamedAddr::Local;
941   }
942 }
943
944 static int getDecodedCastOpcode(unsigned Val) {
945   switch (Val) {
946   default: return -1;
947   case bitc::CAST_TRUNC   : return Instruction::Trunc;
948   case bitc::CAST_ZEXT    : return Instruction::ZExt;
949   case bitc::CAST_SEXT    : return Instruction::SExt;
950   case bitc::CAST_FPTOUI  : return Instruction::FPToUI;
951   case bitc::CAST_FPTOSI  : return Instruction::FPToSI;
952   case bitc::CAST_UITOFP  : return Instruction::UIToFP;
953   case bitc::CAST_SITOFP  : return Instruction::SIToFP;
954   case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
955   case bitc::CAST_FPEXT   : return Instruction::FPExt;
956   case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
957   case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
958   case bitc::CAST_BITCAST : return Instruction::BitCast;
959   case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
960   }
961 }
962
963 static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
964   bool IsFP = Ty->isFPOrFPVectorTy();
965   // BinOps are only valid for int/fp or vector of int/fp types
966   if (!IsFP && !Ty->isIntOrIntVectorTy())
967     return -1;
968
969   switch (Val) {
970   default:
971     return -1;
972   case bitc::BINOP_ADD:
973     return IsFP ? Instruction::FAdd : Instruction::Add;
974   case bitc::BINOP_SUB:
975     return IsFP ? Instruction::FSub : Instruction::Sub;
976   case bitc::BINOP_MUL:
977     return IsFP ? Instruction::FMul : Instruction::Mul;
978   case bitc::BINOP_UDIV:
979     return IsFP ? -1 : Instruction::UDiv;
980   case bitc::BINOP_SDIV:
981     return IsFP ? Instruction::FDiv : Instruction::SDiv;
982   case bitc::BINOP_UREM:
983     return IsFP ? -1 : Instruction::URem;
984   case bitc::BINOP_SREM:
985     return IsFP ? Instruction::FRem : Instruction::SRem;
986   case bitc::BINOP_SHL:
987     return IsFP ? -1 : Instruction::Shl;
988   case bitc::BINOP_LSHR:
989     return IsFP ? -1 : Instruction::LShr;
990   case bitc::BINOP_ASHR:
991     return IsFP ? -1 : Instruction::AShr;
992   case bitc::BINOP_AND:
993     return IsFP ? -1 : Instruction::And;
994   case bitc::BINOP_OR:
995     return IsFP ? -1 : Instruction::Or;
996   case bitc::BINOP_XOR:
997     return IsFP ? -1 : Instruction::Xor;
998   }
999 }
1000
1001 static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
1002   switch (Val) {
1003   default: return AtomicRMWInst::BAD_BINOP;
1004   case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
1005   case bitc::RMW_ADD: return AtomicRMWInst::Add;
1006   case bitc::RMW_SUB: return AtomicRMWInst::Sub;
1007   case bitc::RMW_AND: return AtomicRMWInst::And;
1008   case bitc::RMW_NAND: return AtomicRMWInst::Nand;
1009   case bitc::RMW_OR: return AtomicRMWInst::Or;
1010   case bitc::RMW_XOR: return AtomicRMWInst::Xor;
1011   case bitc::RMW_MAX: return AtomicRMWInst::Max;
1012   case bitc::RMW_MIN: return AtomicRMWInst::Min;
1013   case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
1014   case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
1015   }
1016 }
1017
1018 static AtomicOrdering getDecodedOrdering(unsigned Val) {
1019   switch (Val) {
1020   case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic;
1021   case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered;
1022   case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic;
1023   case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire;
1024   case bitc::ORDERING_RELEASE: return AtomicOrdering::Release;
1025   case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease;
1026   default: // Map unknown orderings to sequentially-consistent.
1027   case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent;
1028   }
1029 }
1030
1031 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
1032   switch (Val) {
1033   default: // Map unknown selection kinds to any.
1034   case bitc::COMDAT_SELECTION_KIND_ANY:
1035     return Comdat::Any;
1036   case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
1037     return Comdat::ExactMatch;
1038   case bitc::COMDAT_SELECTION_KIND_LARGEST:
1039     return Comdat::Largest;
1040   case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
1041     return Comdat::NoDuplicates;
1042   case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
1043     return Comdat::SameSize;
1044   }
1045 }
1046
1047 static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
1048   FastMathFlags FMF;
1049   if (0 != (Val & FastMathFlags::AllowReassoc))
1050     FMF.setAllowReassoc();
1051   if (0 != (Val & FastMathFlags::NoNaNs))
1052     FMF.setNoNaNs();
1053   if (0 != (Val & FastMathFlags::NoInfs))
1054     FMF.setNoInfs();
1055   if (0 != (Val & FastMathFlags::NoSignedZeros))
1056     FMF.setNoSignedZeros();
1057   if (0 != (Val & FastMathFlags::AllowReciprocal))
1058     FMF.setAllowReciprocal();
1059   if (0 != (Val & FastMathFlags::AllowContract))
1060     FMF.setAllowContract(true);
1061   if (0 != (Val & FastMathFlags::ApproxFunc))
1062     FMF.setApproxFunc();
1063   return FMF;
1064 }
1065
1066 static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) {
1067   switch (Val) {
1068   case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
1069   case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
1070   }
1071 }
1072
1073 Type *BitcodeReader::getTypeByID(unsigned ID) {
1074   // The type table size is always specified correctly.
1075   if (ID >= TypeList.size())
1076     return nullptr;
1077
1078   if (Type *Ty = TypeList[ID])
1079     return Ty;
1080
1081   // If we have a forward reference, the only possible case is when it is to a
1082   // named struct.  Just create a placeholder for now.
1083   return TypeList[ID] = createIdentifiedStructType(Context);
1084 }
1085
1086 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1087                                                       StringRef Name) {
1088   auto *Ret = StructType::create(Context, Name);
1089   IdentifiedStructTypes.push_back(Ret);
1090   return Ret;
1091 }
1092
1093 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1094   auto *Ret = StructType::create(Context);
1095   IdentifiedStructTypes.push_back(Ret);
1096   return Ret;
1097 }
1098
1099 //===----------------------------------------------------------------------===//
1100 //  Functions for parsing blocks from the bitcode file
1101 //===----------------------------------------------------------------------===//
1102
1103 static uint64_t getRawAttributeMask(Attribute::AttrKind Val) {
1104   switch (Val) {
1105   case Attribute::EndAttrKinds:
1106     llvm_unreachable("Synthetic enumerators which should never get here");
1107
1108   case Attribute::None:            return 0;
1109   case Attribute::ZExt:            return 1 << 0;
1110   case Attribute::SExt:            return 1 << 1;
1111   case Attribute::NoReturn:        return 1 << 2;
1112   case Attribute::InReg:           return 1 << 3;
1113   case Attribute::StructRet:       return 1 << 4;
1114   case Attribute::NoUnwind:        return 1 << 5;
1115   case Attribute::NoAlias:         return 1 << 6;
1116   case Attribute::ByVal:           return 1 << 7;
1117   case Attribute::Nest:            return 1 << 8;
1118   case Attribute::ReadNone:        return 1 << 9;
1119   case Attribute::ReadOnly:        return 1 << 10;
1120   case Attribute::NoInline:        return 1 << 11;
1121   case Attribute::AlwaysInline:    return 1 << 12;
1122   case Attribute::OptimizeForSize: return 1 << 13;
1123   case Attribute::StackProtect:    return 1 << 14;
1124   case Attribute::StackProtectReq: return 1 << 15;
1125   case Attribute::Alignment:       return 31 << 16;
1126   case Attribute::NoCapture:       return 1 << 21;
1127   case Attribute::NoRedZone:       return 1 << 22;
1128   case Attribute::NoImplicitFloat: return 1 << 23;
1129   case Attribute::Naked:           return 1 << 24;
1130   case Attribute::InlineHint:      return 1 << 25;
1131   case Attribute::StackAlignment:  return 7 << 26;
1132   case Attribute::ReturnsTwice:    return 1 << 29;
1133   case Attribute::UWTable:         return 1 << 30;
1134   case Attribute::NonLazyBind:     return 1U << 31;
1135   case Attribute::SanitizeAddress: return 1ULL << 32;
1136   case Attribute::MinSize:         return 1ULL << 33;
1137   case Attribute::NoDuplicate:     return 1ULL << 34;
1138   case Attribute::StackProtectStrong: return 1ULL << 35;
1139   case Attribute::SanitizeThread:  return 1ULL << 36;
1140   case Attribute::SanitizeMemory:  return 1ULL << 37;
1141   case Attribute::NoBuiltin:       return 1ULL << 38;
1142   case Attribute::Returned:        return 1ULL << 39;
1143   case Attribute::Cold:            return 1ULL << 40;
1144   case Attribute::Builtin:         return 1ULL << 41;
1145   case Attribute::OptimizeNone:    return 1ULL << 42;
1146   case Attribute::InAlloca:        return 1ULL << 43;
1147   case Attribute::NonNull:         return 1ULL << 44;
1148   case Attribute::JumpTable:       return 1ULL << 45;
1149   case Attribute::Convergent:      return 1ULL << 46;
1150   case Attribute::SafeStack:       return 1ULL << 47;
1151   case Attribute::NoRecurse:       return 1ULL << 48;
1152   case Attribute::InaccessibleMemOnly:         return 1ULL << 49;
1153   case Attribute::InaccessibleMemOrArgMemOnly: return 1ULL << 50;
1154   case Attribute::SwiftSelf:       return 1ULL << 51;
1155   case Attribute::SwiftError:      return 1ULL << 52;
1156   case Attribute::WriteOnly:       return 1ULL << 53;
1157   case Attribute::Speculatable:    return 1ULL << 54;
1158   case Attribute::StrictFP:        return 1ULL << 55;
1159   case Attribute::SanitizeHWAddress: return 1ULL << 56;
1160   case Attribute::Dereferenceable:
1161     llvm_unreachable("dereferenceable attribute not supported in raw format");
1162     break;
1163   case Attribute::DereferenceableOrNull:
1164     llvm_unreachable("dereferenceable_or_null attribute not supported in raw "
1165                      "format");
1166     break;
1167   case Attribute::ArgMemOnly:
1168     llvm_unreachable("argmemonly attribute not supported in raw format");
1169     break;
1170   case Attribute::AllocSize:
1171     llvm_unreachable("allocsize not supported in raw format");
1172     break;
1173   }
1174   llvm_unreachable("Unsupported attribute type");
1175 }
1176
1177 static void addRawAttributeValue(AttrBuilder &B, uint64_t Val) {
1178   if (!Val) return;
1179
1180   for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
1181        I = Attribute::AttrKind(I + 1)) {
1182     if (I == Attribute::Dereferenceable ||
1183         I == Attribute::DereferenceableOrNull ||
1184         I == Attribute::ArgMemOnly ||
1185         I == Attribute::AllocSize)
1186       continue;
1187     if (uint64_t A = (Val & getRawAttributeMask(I))) {
1188       if (I == Attribute::Alignment)
1189         B.addAlignmentAttr(1ULL << ((A >> 16) - 1));
1190       else if (I == Attribute::StackAlignment)
1191         B.addStackAlignmentAttr(1ULL << ((A >> 26)-1));
1192       else
1193         B.addAttribute(I);
1194     }
1195   }
1196 }
1197
1198 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
1199 /// been decoded from the given integer. This function must stay in sync with
1200 /// 'encodeLLVMAttributesForBitcode'.
1201 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1202                                            uint64_t EncodedAttrs) {
1203   // FIXME: Remove in 4.0.
1204
1205   // The alignment is stored as a 16-bit raw value from bits 31--16.  We shift
1206   // the bits above 31 down by 11 bits.
1207   unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1208   assert((!Alignment || isPowerOf2_32(Alignment)) &&
1209          "Alignment must be a power of two.");
1210
1211   if (Alignment)
1212     B.addAlignmentAttr(Alignment);
1213   addRawAttributeValue(B, ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1214                           (EncodedAttrs & 0xffff));
1215 }
1216
1217 Error BitcodeReader::parseAttributeBlock() {
1218   if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
1219     return error("Invalid record");
1220
1221   if (!MAttributes.empty())
1222     return error("Invalid multiple blocks");
1223
1224   SmallVector<uint64_t, 64> Record;
1225
1226   SmallVector<AttributeList, 8> Attrs;
1227
1228   // Read all the records.
1229   while (true) {
1230     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1231
1232     switch (Entry.Kind) {
1233     case BitstreamEntry::SubBlock: // Handled for us already.
1234     case BitstreamEntry::Error:
1235       return error("Malformed block");
1236     case BitstreamEntry::EndBlock:
1237       return Error::success();
1238     case BitstreamEntry::Record:
1239       // The interesting case.
1240       break;
1241     }
1242
1243     // Read a record.
1244     Record.clear();
1245     switch (Stream.readRecord(Entry.ID, Record)) {
1246     default:  // Default behavior: ignore.
1247       break;
1248     case bitc::PARAMATTR_CODE_ENTRY_OLD: // ENTRY: [paramidx0, attr0, ...]
1249       // FIXME: Remove in 4.0.
1250       if (Record.size() & 1)
1251         return error("Invalid record");
1252
1253       for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1254         AttrBuilder B;
1255         decodeLLVMAttributesForBitcode(B, Record[i+1]);
1256         Attrs.push_back(AttributeList::get(Context, Record[i], B));
1257       }
1258
1259       MAttributes.push_back(AttributeList::get(Context, Attrs));
1260       Attrs.clear();
1261       break;
1262     case bitc::PARAMATTR_CODE_ENTRY: // ENTRY: [attrgrp0, attrgrp1, ...]
1263       for (unsigned i = 0, e = Record.size(); i != e; ++i)
1264         Attrs.push_back(MAttributeGroups[Record[i]]);
1265
1266       MAttributes.push_back(AttributeList::get(Context, Attrs));
1267       Attrs.clear();
1268       break;
1269     }
1270   }
1271 }
1272
1273 // Returns Attribute::None on unrecognized codes.
1274 static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
1275   switch (Code) {
1276   default:
1277     return Attribute::None;
1278   case bitc::ATTR_KIND_ALIGNMENT:
1279     return Attribute::Alignment;
1280   case bitc::ATTR_KIND_ALWAYS_INLINE:
1281     return Attribute::AlwaysInline;
1282   case bitc::ATTR_KIND_ARGMEMONLY:
1283     return Attribute::ArgMemOnly;
1284   case bitc::ATTR_KIND_BUILTIN:
1285     return Attribute::Builtin;
1286   case bitc::ATTR_KIND_BY_VAL:
1287     return Attribute::ByVal;
1288   case bitc::ATTR_KIND_IN_ALLOCA:
1289     return Attribute::InAlloca;
1290   case bitc::ATTR_KIND_COLD:
1291     return Attribute::Cold;
1292   case bitc::ATTR_KIND_CONVERGENT:
1293     return Attribute::Convergent;
1294   case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY:
1295     return Attribute::InaccessibleMemOnly;
1296   case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY:
1297     return Attribute::InaccessibleMemOrArgMemOnly;
1298   case bitc::ATTR_KIND_INLINE_HINT:
1299     return Attribute::InlineHint;
1300   case bitc::ATTR_KIND_IN_REG:
1301     return Attribute::InReg;
1302   case bitc::ATTR_KIND_JUMP_TABLE:
1303     return Attribute::JumpTable;
1304   case bitc::ATTR_KIND_MIN_SIZE:
1305     return Attribute::MinSize;
1306   case bitc::ATTR_KIND_NAKED:
1307     return Attribute::Naked;
1308   case bitc::ATTR_KIND_NEST:
1309     return Attribute::Nest;
1310   case bitc::ATTR_KIND_NO_ALIAS:
1311     return Attribute::NoAlias;
1312   case bitc::ATTR_KIND_NO_BUILTIN:
1313     return Attribute::NoBuiltin;
1314   case bitc::ATTR_KIND_NO_CAPTURE:
1315     return Attribute::NoCapture;
1316   case bitc::ATTR_KIND_NO_DUPLICATE:
1317     return Attribute::NoDuplicate;
1318   case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1319     return Attribute::NoImplicitFloat;
1320   case bitc::ATTR_KIND_NO_INLINE:
1321     return Attribute::NoInline;
1322   case bitc::ATTR_KIND_NO_RECURSE:
1323     return Attribute::NoRecurse;
1324   case bitc::ATTR_KIND_NON_LAZY_BIND:
1325     return Attribute::NonLazyBind;
1326   case bitc::ATTR_KIND_NON_NULL:
1327     return Attribute::NonNull;
1328   case bitc::ATTR_KIND_DEREFERENCEABLE:
1329     return Attribute::Dereferenceable;
1330   case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1331     return Attribute::DereferenceableOrNull;
1332   case bitc::ATTR_KIND_ALLOC_SIZE:
1333     return Attribute::AllocSize;
1334   case bitc::ATTR_KIND_NO_RED_ZONE:
1335     return Attribute::NoRedZone;
1336   case bitc::ATTR_KIND_NO_RETURN:
1337     return Attribute::NoReturn;
1338   case bitc::ATTR_KIND_NO_UNWIND:
1339     return Attribute::NoUnwind;
1340   case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1341     return Attribute::OptimizeForSize;
1342   case bitc::ATTR_KIND_OPTIMIZE_NONE:
1343     return Attribute::OptimizeNone;
1344   case bitc::ATTR_KIND_READ_NONE:
1345     return Attribute::ReadNone;
1346   case bitc::ATTR_KIND_READ_ONLY:
1347     return Attribute::ReadOnly;
1348   case bitc::ATTR_KIND_RETURNED:
1349     return Attribute::Returned;
1350   case bitc::ATTR_KIND_RETURNS_TWICE:
1351     return Attribute::ReturnsTwice;
1352   case bitc::ATTR_KIND_S_EXT:
1353     return Attribute::SExt;
1354   case bitc::ATTR_KIND_SPECULATABLE:
1355     return Attribute::Speculatable;
1356   case bitc::ATTR_KIND_STACK_ALIGNMENT:
1357     return Attribute::StackAlignment;
1358   case bitc::ATTR_KIND_STACK_PROTECT:
1359     return Attribute::StackProtect;
1360   case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1361     return Attribute::StackProtectReq;
1362   case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1363     return Attribute::StackProtectStrong;
1364   case bitc::ATTR_KIND_SAFESTACK:
1365     return Attribute::SafeStack;
1366   case bitc::ATTR_KIND_STRICT_FP:
1367     return Attribute::StrictFP;
1368   case bitc::ATTR_KIND_STRUCT_RET:
1369     return Attribute::StructRet;
1370   case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1371     return Attribute::SanitizeAddress;
1372   case bitc::ATTR_KIND_SANITIZE_HWADDRESS:
1373     return Attribute::SanitizeHWAddress;
1374   case bitc::ATTR_KIND_SANITIZE_THREAD:
1375     return Attribute::SanitizeThread;
1376   case bitc::ATTR_KIND_SANITIZE_MEMORY:
1377     return Attribute::SanitizeMemory;
1378   case bitc::ATTR_KIND_SWIFT_ERROR:
1379     return Attribute::SwiftError;
1380   case bitc::ATTR_KIND_SWIFT_SELF:
1381     return Attribute::SwiftSelf;
1382   case bitc::ATTR_KIND_UW_TABLE:
1383     return Attribute::UWTable;
1384   case bitc::ATTR_KIND_WRITEONLY:
1385     return Attribute::WriteOnly;
1386   case bitc::ATTR_KIND_Z_EXT:
1387     return Attribute::ZExt;
1388   }
1389 }
1390
1391 Error BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1392                                          unsigned &Alignment) {
1393   // Note: Alignment in bitcode files is incremented by 1, so that zero
1394   // can be used for default alignment.
1395   if (Exponent > Value::MaxAlignmentExponent + 1)
1396     return error("Invalid alignment value");
1397   Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1398   return Error::success();
1399 }
1400
1401 Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) {
1402   *Kind = getAttrFromCode(Code);
1403   if (*Kind == Attribute::None)
1404     return error("Unknown attribute kind (" + Twine(Code) + ")");
1405   return Error::success();
1406 }
1407
1408 Error BitcodeReader::parseAttributeGroupBlock() {
1409   if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
1410     return error("Invalid record");
1411
1412   if (!MAttributeGroups.empty())
1413     return error("Invalid multiple blocks");
1414
1415   SmallVector<uint64_t, 64> Record;
1416
1417   // Read all the records.
1418   while (true) {
1419     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1420
1421     switch (Entry.Kind) {
1422     case BitstreamEntry::SubBlock: // Handled for us already.
1423     case BitstreamEntry::Error:
1424       return error("Malformed block");
1425     case BitstreamEntry::EndBlock:
1426       return Error::success();
1427     case BitstreamEntry::Record:
1428       // The interesting case.
1429       break;
1430     }
1431
1432     // Read a record.
1433     Record.clear();
1434     switch (Stream.readRecord(Entry.ID, Record)) {
1435     default:  // Default behavior: ignore.
1436       break;
1437     case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1438       if (Record.size() < 3)
1439         return error("Invalid record");
1440
1441       uint64_t GrpID = Record[0];
1442       uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1443
1444       AttrBuilder B;
1445       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1446         if (Record[i] == 0) {        // Enum attribute
1447           Attribute::AttrKind Kind;
1448           if (Error Err = parseAttrKind(Record[++i], &Kind))
1449             return Err;
1450
1451           B.addAttribute(Kind);
1452         } else if (Record[i] == 1) { // Integer attribute
1453           Attribute::AttrKind Kind;
1454           if (Error Err = parseAttrKind(Record[++i], &Kind))
1455             return Err;
1456           if (Kind == Attribute::Alignment)
1457             B.addAlignmentAttr(Record[++i]);
1458           else if (Kind == Attribute::StackAlignment)
1459             B.addStackAlignmentAttr(Record[++i]);
1460           else if (Kind == Attribute::Dereferenceable)
1461             B.addDereferenceableAttr(Record[++i]);
1462           else if (Kind == Attribute::DereferenceableOrNull)
1463             B.addDereferenceableOrNullAttr(Record[++i]);
1464           else if (Kind == Attribute::AllocSize)
1465             B.addAllocSizeAttrFromRawRepr(Record[++i]);
1466         } else {                     // String attribute
1467           assert((Record[i] == 3 || Record[i] == 4) &&
1468                  "Invalid attribute group entry");
1469           bool HasValue = (Record[i++] == 4);
1470           SmallString<64> KindStr;
1471           SmallString<64> ValStr;
1472
1473           while (Record[i] != 0 && i != e)
1474             KindStr += Record[i++];
1475           assert(Record[i] == 0 && "Kind string not null terminated");
1476
1477           if (HasValue) {
1478             // Has a value associated with it.
1479             ++i; // Skip the '0' that terminates the "kind" string.
1480             while (Record[i] != 0 && i != e)
1481               ValStr += Record[i++];
1482             assert(Record[i] == 0 && "Value string not null terminated");
1483           }
1484
1485           B.addAttribute(KindStr.str(), ValStr.str());
1486         }
1487       }
1488
1489       MAttributeGroups[GrpID] = AttributeList::get(Context, Idx, B);
1490       break;
1491     }
1492     }
1493   }
1494 }
1495
1496 Error BitcodeReader::parseTypeTable() {
1497   if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
1498     return error("Invalid record");
1499
1500   return parseTypeTableBody();
1501 }
1502
1503 Error BitcodeReader::parseTypeTableBody() {
1504   if (!TypeList.empty())
1505     return error("Invalid multiple blocks");
1506
1507   SmallVector<uint64_t, 64> Record;
1508   unsigned NumRecords = 0;
1509
1510   SmallString<64> TypeName;
1511
1512   // Read all the records for this type table.
1513   while (true) {
1514     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1515
1516     switch (Entry.Kind) {
1517     case BitstreamEntry::SubBlock: // Handled for us already.
1518     case BitstreamEntry::Error:
1519       return error("Malformed block");
1520     case BitstreamEntry::EndBlock:
1521       if (NumRecords != TypeList.size())
1522         return error("Malformed block");
1523       return Error::success();
1524     case BitstreamEntry::Record:
1525       // The interesting case.
1526       break;
1527     }
1528
1529     // Read a record.
1530     Record.clear();
1531     Type *ResultTy = nullptr;
1532     switch (Stream.readRecord(Entry.ID, Record)) {
1533     default:
1534       return error("Invalid value");
1535     case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1536       // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1537       // type list.  This allows us to reserve space.
1538       if (Record.size() < 1)
1539         return error("Invalid record");
1540       TypeList.resize(Record[0]);
1541       continue;
1542     case bitc::TYPE_CODE_VOID:      // VOID
1543       ResultTy = Type::getVoidTy(Context);
1544       break;
1545     case bitc::TYPE_CODE_HALF:     // HALF
1546       ResultTy = Type::getHalfTy(Context);
1547       break;
1548     case bitc::TYPE_CODE_FLOAT:     // FLOAT
1549       ResultTy = Type::getFloatTy(Context);
1550       break;
1551     case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
1552       ResultTy = Type::getDoubleTy(Context);
1553       break;
1554     case bitc::TYPE_CODE_X86_FP80:  // X86_FP80
1555       ResultTy = Type::getX86_FP80Ty(Context);
1556       break;
1557     case bitc::TYPE_CODE_FP128:     // FP128
1558       ResultTy = Type::getFP128Ty(Context);
1559       break;
1560     case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1561       ResultTy = Type::getPPC_FP128Ty(Context);
1562       break;
1563     case bitc::TYPE_CODE_LABEL:     // LABEL
1564       ResultTy = Type::getLabelTy(Context);
1565       break;
1566     case bitc::TYPE_CODE_METADATA:  // METADATA
1567       ResultTy = Type::getMetadataTy(Context);
1568       break;
1569     case bitc::TYPE_CODE_X86_MMX:   // X86_MMX
1570       ResultTy = Type::getX86_MMXTy(Context);
1571       break;
1572     case bitc::TYPE_CODE_TOKEN:     // TOKEN
1573       ResultTy = Type::getTokenTy(Context);
1574       break;
1575     case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1576       if (Record.size() < 1)
1577         return error("Invalid record");
1578
1579       uint64_t NumBits = Record[0];
1580       if (NumBits < IntegerType::MIN_INT_BITS ||
1581           NumBits > IntegerType::MAX_INT_BITS)
1582         return error("Bitwidth for integer type out of range");
1583       ResultTy = IntegerType::get(Context, NumBits);
1584       break;
1585     }
1586     case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1587                                     //          [pointee type, address space]
1588       if (Record.size() < 1)
1589         return error("Invalid record");
1590       unsigned AddressSpace = 0;
1591       if (Record.size() == 2)
1592         AddressSpace = Record[1];
1593       ResultTy = getTypeByID(Record[0]);
1594       if (!ResultTy ||
1595           !PointerType::isValidElementType(ResultTy))
1596         return error("Invalid type");
1597       ResultTy = PointerType::get(ResultTy, AddressSpace);
1598       break;
1599     }
1600     case bitc::TYPE_CODE_FUNCTION_OLD: {
1601       // FIXME: attrid is dead, remove it in LLVM 4.0
1602       // FUNCTION: [vararg, attrid, retty, paramty x N]
1603       if (Record.size() < 3)
1604         return error("Invalid record");
1605       SmallVector<Type*, 8> ArgTys;
1606       for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1607         if (Type *T = getTypeByID(Record[i]))
1608           ArgTys.push_back(T);
1609         else
1610           break;
1611       }
1612
1613       ResultTy = getTypeByID(Record[2]);
1614       if (!ResultTy || ArgTys.size() < Record.size()-3)
1615         return error("Invalid type");
1616
1617       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1618       break;
1619     }
1620     case bitc::TYPE_CODE_FUNCTION: {
1621       // FUNCTION: [vararg, retty, paramty x N]
1622       if (Record.size() < 2)
1623         return error("Invalid record");
1624       SmallVector<Type*, 8> ArgTys;
1625       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1626         if (Type *T = getTypeByID(Record[i])) {
1627           if (!FunctionType::isValidArgumentType(T))
1628             return error("Invalid function argument type");
1629           ArgTys.push_back(T);
1630         }
1631         else
1632           break;
1633       }
1634
1635       ResultTy = getTypeByID(Record[1]);
1636       if (!ResultTy || ArgTys.size() < Record.size()-2)
1637         return error("Invalid type");
1638
1639       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1640       break;
1641     }
1642     case bitc::TYPE_CODE_STRUCT_ANON: {  // STRUCT: [ispacked, eltty x N]
1643       if (Record.size() < 1)
1644         return error("Invalid record");
1645       SmallVector<Type*, 8> EltTys;
1646       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1647         if (Type *T = getTypeByID(Record[i]))
1648           EltTys.push_back(T);
1649         else
1650           break;
1651       }
1652       if (EltTys.size() != Record.size()-1)
1653         return error("Invalid type");
1654       ResultTy = StructType::get(Context, EltTys, Record[0]);
1655       break;
1656     }
1657     case bitc::TYPE_CODE_STRUCT_NAME:   // STRUCT_NAME: [strchr x N]
1658       if (convertToString(Record, 0, TypeName))
1659         return error("Invalid record");
1660       continue;
1661
1662     case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1663       if (Record.size() < 1)
1664         return error("Invalid record");
1665
1666       if (NumRecords >= TypeList.size())
1667         return error("Invalid TYPE table");
1668
1669       // Check to see if this was forward referenced, if so fill in the temp.
1670       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1671       if (Res) {
1672         Res->setName(TypeName);
1673         TypeList[NumRecords] = nullptr;
1674       } else  // Otherwise, create a new struct.
1675         Res = createIdentifiedStructType(Context, TypeName);
1676       TypeName.clear();
1677
1678       SmallVector<Type*, 8> EltTys;
1679       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1680         if (Type *T = getTypeByID(Record[i]))
1681           EltTys.push_back(T);
1682         else
1683           break;
1684       }
1685       if (EltTys.size() != Record.size()-1)
1686         return error("Invalid record");
1687       Res->setBody(EltTys, Record[0]);
1688       ResultTy = Res;
1689       break;
1690     }
1691     case bitc::TYPE_CODE_OPAQUE: {       // OPAQUE: []
1692       if (Record.size() != 1)
1693         return error("Invalid record");
1694
1695       if (NumRecords >= TypeList.size())
1696         return error("Invalid TYPE table");
1697
1698       // Check to see if this was forward referenced, if so fill in the temp.
1699       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1700       if (Res) {
1701         Res->setName(TypeName);
1702         TypeList[NumRecords] = nullptr;
1703       } else  // Otherwise, create a new struct with no body.
1704         Res = createIdentifiedStructType(Context, TypeName);
1705       TypeName.clear();
1706       ResultTy = Res;
1707       break;
1708     }
1709     case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
1710       if (Record.size() < 2)
1711         return error("Invalid record");
1712       ResultTy = getTypeByID(Record[1]);
1713       if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
1714         return error("Invalid type");
1715       ResultTy = ArrayType::get(ResultTy, Record[0]);
1716       break;
1717     case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty]
1718       if (Record.size() < 2)
1719         return error("Invalid record");
1720       if (Record[0] == 0)
1721         return error("Invalid vector length");
1722       ResultTy = getTypeByID(Record[1]);
1723       if (!ResultTy || !StructType::isValidElementType(ResultTy))
1724         return error("Invalid type");
1725       ResultTy = VectorType::get(ResultTy, Record[0]);
1726       break;
1727     }
1728
1729     if (NumRecords >= TypeList.size())
1730       return error("Invalid TYPE table");
1731     if (TypeList[NumRecords])
1732       return error(
1733           "Invalid TYPE table: Only named structs can be forward referenced");
1734     assert(ResultTy && "Didn't read a type?");
1735     TypeList[NumRecords++] = ResultTy;
1736   }
1737 }
1738
1739 Error BitcodeReader::parseOperandBundleTags() {
1740   if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
1741     return error("Invalid record");
1742
1743   if (!BundleTags.empty())
1744     return error("Invalid multiple blocks");
1745
1746   SmallVector<uint64_t, 64> Record;
1747
1748   while (true) {
1749     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1750
1751     switch (Entry.Kind) {
1752     case BitstreamEntry::SubBlock: // Handled for us already.
1753     case BitstreamEntry::Error:
1754       return error("Malformed block");
1755     case BitstreamEntry::EndBlock:
1756       return Error::success();
1757     case BitstreamEntry::Record:
1758       // The interesting case.
1759       break;
1760     }
1761
1762     // Tags are implicitly mapped to integers by their order.
1763
1764     if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG)
1765       return error("Invalid record");
1766
1767     // OPERAND_BUNDLE_TAG: [strchr x N]
1768     BundleTags.emplace_back();
1769     if (convertToString(Record, 0, BundleTags.back()))
1770       return error("Invalid record");
1771     Record.clear();
1772   }
1773 }
1774
1775 Error BitcodeReader::parseSyncScopeNames() {
1776   if (Stream.EnterSubBlock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID))
1777     return error("Invalid record");
1778
1779   if (!SSIDs.empty())
1780     return error("Invalid multiple synchronization scope names blocks");
1781
1782   SmallVector<uint64_t, 64> Record;
1783   while (true) {
1784     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1785     switch (Entry.Kind) {
1786     case BitstreamEntry::SubBlock: // Handled for us already.
1787     case BitstreamEntry::Error:
1788       return error("Malformed block");
1789     case BitstreamEntry::EndBlock:
1790       if (SSIDs.empty())
1791         return error("Invalid empty synchronization scope names block");
1792       return Error::success();
1793     case BitstreamEntry::Record:
1794       // The interesting case.
1795       break;
1796     }
1797
1798     // Synchronization scope names are implicitly mapped to synchronization
1799     // scope IDs by their order.
1800
1801     if (Stream.readRecord(Entry.ID, Record) != bitc::SYNC_SCOPE_NAME)
1802       return error("Invalid record");
1803
1804     SmallString<16> SSN;
1805     if (convertToString(Record, 0, SSN))
1806       return error("Invalid record");
1807
1808     SSIDs.push_back(Context.getOrInsertSyncScopeID(SSN));
1809     Record.clear();
1810   }
1811 }
1812
1813 /// Associate a value with its name from the given index in the provided record.
1814 Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
1815                                              unsigned NameIndex, Triple &TT) {
1816   SmallString<128> ValueName;
1817   if (convertToString(Record, NameIndex, ValueName))
1818     return error("Invalid record");
1819   unsigned ValueID = Record[0];
1820   if (ValueID >= ValueList.size() || !ValueList[ValueID])
1821     return error("Invalid record");
1822   Value *V = ValueList[ValueID];
1823
1824   StringRef NameStr(ValueName.data(), ValueName.size());
1825   if (NameStr.find_first_of(0) != StringRef::npos)
1826     return error("Invalid value name");
1827   V->setName(NameStr);
1828   auto *GO = dyn_cast<GlobalObject>(V);
1829   if (GO) {
1830     if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1831       if (TT.supportsCOMDAT())
1832         GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1833       else
1834         GO->setComdat(nullptr);
1835     }
1836   }
1837   return V;
1838 }
1839
1840 /// Helper to note and return the current location, and jump to the given
1841 /// offset.
1842 static uint64_t jumpToValueSymbolTable(uint64_t Offset,
1843                                        BitstreamCursor &Stream) {
1844   // Save the current parsing location so we can jump back at the end
1845   // of the VST read.
1846   uint64_t CurrentBit = Stream.GetCurrentBitNo();
1847   Stream.JumpToBit(Offset * 32);
1848 #ifndef NDEBUG
1849   // Do some checking if we are in debug mode.
1850   BitstreamEntry Entry = Stream.advance();
1851   assert(Entry.Kind == BitstreamEntry::SubBlock);
1852   assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID);
1853 #else
1854   // In NDEBUG mode ignore the output so we don't get an unused variable
1855   // warning.
1856   Stream.advance();
1857 #endif
1858   return CurrentBit;
1859 }
1860
1861 void BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta,
1862                                             Function *F,
1863                                             ArrayRef<uint64_t> Record) {
1864   // Note that we subtract 1 here because the offset is relative to one word
1865   // before the start of the identification or module block, which was
1866   // historically always the start of the regular bitcode header.
1867   uint64_t FuncWordOffset = Record[1] - 1;
1868   uint64_t FuncBitOffset = FuncWordOffset * 32;
1869   DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
1870   // Set the LastFunctionBlockBit to point to the last function block.
1871   // Later when parsing is resumed after function materialization,
1872   // we can simply skip that last function block.
1873   if (FuncBitOffset > LastFunctionBlockBit)
1874     LastFunctionBlockBit = FuncBitOffset;
1875 }
1876
1877 /// Read a new-style GlobalValue symbol table.
1878 Error BitcodeReader::parseGlobalValueSymbolTable() {
1879   unsigned FuncBitcodeOffsetDelta =
1880       Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1881
1882   if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1883     return error("Invalid record");
1884
1885   SmallVector<uint64_t, 64> Record;
1886   while (true) {
1887     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1888
1889     switch (Entry.Kind) {
1890     case BitstreamEntry::SubBlock:
1891     case BitstreamEntry::Error:
1892       return error("Malformed block");
1893     case BitstreamEntry::EndBlock:
1894       return Error::success();
1895     case BitstreamEntry::Record:
1896       break;
1897     }
1898
1899     Record.clear();
1900     switch (Stream.readRecord(Entry.ID, Record)) {
1901     case bitc::VST_CODE_FNENTRY: // [valueid, offset]
1902       setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
1903                               cast<Function>(ValueList[Record[0]]), Record);
1904       break;
1905     }
1906   }
1907 }
1908
1909 /// Parse the value symbol table at either the current parsing location or
1910 /// at the given bit offset if provided.
1911 Error BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
1912   uint64_t CurrentBit;
1913   // Pass in the Offset to distinguish between calling for the module-level
1914   // VST (where we want to jump to the VST offset) and the function-level
1915   // VST (where we don't).
1916   if (Offset > 0) {
1917     CurrentBit = jumpToValueSymbolTable(Offset, Stream);
1918     // If this module uses a string table, read this as a module-level VST.
1919     if (UseStrtab) {
1920       if (Error Err = parseGlobalValueSymbolTable())
1921         return Err;
1922       Stream.JumpToBit(CurrentBit);
1923       return Error::success();
1924     }
1925     // Otherwise, the VST will be in a similar format to a function-level VST,
1926     // and will contain symbol names.
1927   }
1928
1929   // Compute the delta between the bitcode indices in the VST (the word offset
1930   // to the word-aligned ENTER_SUBBLOCK for the function block, and that
1931   // expected by the lazy reader. The reader's EnterSubBlock expects to have
1932   // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
1933   // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
1934   // just before entering the VST subblock because: 1) the EnterSubBlock
1935   // changes the AbbrevID width; 2) the VST block is nested within the same
1936   // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
1937   // AbbrevID width before calling EnterSubBlock; and 3) when we want to
1938   // jump to the FUNCTION_BLOCK using this offset later, we don't want
1939   // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
1940   unsigned FuncBitcodeOffsetDelta =
1941       Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1942
1943   if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1944     return error("Invalid record");
1945
1946   SmallVector<uint64_t, 64> Record;
1947
1948   Triple TT(TheModule->getTargetTriple());
1949
1950   // Read all the records for this value table.
1951   SmallString<128> ValueName;
1952
1953   while (true) {
1954     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1955
1956     switch (Entry.Kind) {
1957     case BitstreamEntry::SubBlock: // Handled for us already.
1958     case BitstreamEntry::Error:
1959       return error("Malformed block");
1960     case BitstreamEntry::EndBlock:
1961       if (Offset > 0)
1962         Stream.JumpToBit(CurrentBit);
1963       return Error::success();
1964     case BitstreamEntry::Record:
1965       // The interesting case.
1966       break;
1967     }
1968
1969     // Read a record.
1970     Record.clear();
1971     switch (Stream.readRecord(Entry.ID, Record)) {
1972     default:  // Default behavior: unknown type.
1973       break;
1974     case bitc::VST_CODE_ENTRY: {  // VST_CODE_ENTRY: [valueid, namechar x N]
1975       Expected<Value *> ValOrErr = recordValue(Record, 1, TT);
1976       if (Error Err = ValOrErr.takeError())
1977         return Err;
1978       ValOrErr.get();
1979       break;
1980     }
1981     case bitc::VST_CODE_FNENTRY: {
1982       // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
1983       Expected<Value *> ValOrErr = recordValue(Record, 2, TT);
1984       if (Error Err = ValOrErr.takeError())
1985         return Err;
1986       Value *V = ValOrErr.get();
1987
1988       // Ignore function offsets emitted for aliases of functions in older
1989       // versions of LLVM.
1990       if (auto *F = dyn_cast<Function>(V))
1991         setDeferredFunctionInfo(FuncBitcodeOffsetDelta, F, Record);
1992       break;
1993     }
1994     case bitc::VST_CODE_BBENTRY: {
1995       if (convertToString(Record, 1, ValueName))
1996         return error("Invalid record");
1997       BasicBlock *BB = getBasicBlock(Record[0]);
1998       if (!BB)
1999         return error("Invalid record");
2000
2001       BB->setName(StringRef(ValueName.data(), ValueName.size()));
2002       ValueName.clear();
2003       break;
2004     }
2005     }
2006   }
2007 }
2008
2009 /// Decode a signed value stored with the sign bit in the LSB for dense VBR
2010 /// encoding.
2011 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2012   if ((V & 1) == 0)
2013     return V >> 1;
2014   if (V != 1)
2015     return -(V >> 1);
2016   // There is no such thing as -0 with integers.  "-0" really means MININT.
2017   return 1ULL << 63;
2018 }
2019
2020 /// Resolve all of the initializers for global values and aliases that we can.
2021 Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
2022   std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist;
2023   std::vector<std::pair<GlobalIndirectSymbol *, unsigned>>
2024       IndirectSymbolInitWorklist;
2025   std::vector<std::pair<Function *, unsigned>> FunctionPrefixWorklist;
2026   std::vector<std::pair<Function *, unsigned>> FunctionPrologueWorklist;
2027   std::vector<std::pair<Function *, unsigned>> FunctionPersonalityFnWorklist;
2028
2029   GlobalInitWorklist.swap(GlobalInits);
2030   IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
2031   FunctionPrefixWorklist.swap(FunctionPrefixes);
2032   FunctionPrologueWorklist.swap(FunctionPrologues);
2033   FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
2034
2035   while (!GlobalInitWorklist.empty()) {
2036     unsigned ValID = GlobalInitWorklist.back().second;
2037     if (ValID >= ValueList.size()) {
2038       // Not ready to resolve this yet, it requires something later in the file.
2039       GlobalInits.push_back(GlobalInitWorklist.back());
2040     } else {
2041       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2042         GlobalInitWorklist.back().first->setInitializer(C);
2043       else
2044         return error("Expected a constant");
2045     }
2046     GlobalInitWorklist.pop_back();
2047   }
2048
2049   while (!IndirectSymbolInitWorklist.empty()) {
2050     unsigned ValID = IndirectSymbolInitWorklist.back().second;
2051     if (ValID >= ValueList.size()) {
2052       IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
2053     } else {
2054       Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2055       if (!C)
2056         return error("Expected a constant");
2057       GlobalIndirectSymbol *GIS = IndirectSymbolInitWorklist.back().first;
2058       if (isa<GlobalAlias>(GIS) && C->getType() != GIS->getType())
2059         return error("Alias and aliasee types don't match");
2060       GIS->setIndirectSymbol(C);
2061     }
2062     IndirectSymbolInitWorklist.pop_back();
2063   }
2064
2065   while (!FunctionPrefixWorklist.empty()) {
2066     unsigned ValID = FunctionPrefixWorklist.back().second;
2067     if (ValID >= ValueList.size()) {
2068       FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2069     } else {
2070       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2071         FunctionPrefixWorklist.back().first->setPrefixData(C);
2072       else
2073         return error("Expected a constant");
2074     }
2075     FunctionPrefixWorklist.pop_back();
2076   }
2077
2078   while (!FunctionPrologueWorklist.empty()) {
2079     unsigned ValID = FunctionPrologueWorklist.back().second;
2080     if (ValID >= ValueList.size()) {
2081       FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2082     } else {
2083       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2084         FunctionPrologueWorklist.back().first->setPrologueData(C);
2085       else
2086         return error("Expected a constant");
2087     }
2088     FunctionPrologueWorklist.pop_back();
2089   }
2090
2091   while (!FunctionPersonalityFnWorklist.empty()) {
2092     unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2093     if (ValID >= ValueList.size()) {
2094       FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2095     } else {
2096       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2097         FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2098       else
2099         return error("Expected a constant");
2100     }
2101     FunctionPersonalityFnWorklist.pop_back();
2102   }
2103
2104   return Error::success();
2105 }
2106
2107 static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2108   SmallVector<uint64_t, 8> Words(Vals.size());
2109   transform(Vals, Words.begin(),
2110                  BitcodeReader::decodeSignRotatedValue);
2111
2112   return APInt(TypeBits, Words);
2113 }
2114
2115 Error BitcodeReader::parseConstants() {
2116   if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2117     return error("Invalid record");
2118
2119   SmallVector<uint64_t, 64> Record;
2120
2121   // Read all the records for this value table.
2122   Type *CurTy = Type::getInt32Ty(Context);
2123   unsigned NextCstNo = ValueList.size();
2124
2125   while (true) {
2126     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2127
2128     switch (Entry.Kind) {
2129     case BitstreamEntry::SubBlock: // Handled for us already.
2130     case BitstreamEntry::Error:
2131       return error("Malformed block");
2132     case BitstreamEntry::EndBlock:
2133       if (NextCstNo != ValueList.size())
2134         return error("Invalid constant reference");
2135
2136       // Once all the constants have been read, go through and resolve forward
2137       // references.
2138       ValueList.resolveConstantForwardRefs();
2139       return Error::success();
2140     case BitstreamEntry::Record:
2141       // The interesting case.
2142       break;
2143     }
2144
2145     // Read a record.
2146     Record.clear();
2147     Type *VoidType = Type::getVoidTy(Context);
2148     Value *V = nullptr;
2149     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2150     switch (BitCode) {
2151     default:  // Default behavior: unknown constant
2152     case bitc::CST_CODE_UNDEF:     // UNDEF
2153       V = UndefValue::get(CurTy);
2154       break;
2155     case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
2156       if (Record.empty())
2157         return error("Invalid record");
2158       if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2159         return error("Invalid record");
2160       if (TypeList[Record[0]] == VoidType)
2161         return error("Invalid constant type");
2162       CurTy = TypeList[Record[0]];
2163       continue;  // Skip the ValueList manipulation.
2164     case bitc::CST_CODE_NULL:      // NULL
2165       V = Constant::getNullValue(CurTy);
2166       break;
2167     case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
2168       if (!CurTy->isIntegerTy() || Record.empty())
2169         return error("Invalid record");
2170       V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2171       break;
2172     case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2173       if (!CurTy->isIntegerTy() || Record.empty())
2174         return error("Invalid record");
2175
2176       APInt VInt =
2177           readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
2178       V = ConstantInt::get(Context, VInt);
2179
2180       break;
2181     }
2182     case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
2183       if (Record.empty())
2184         return error("Invalid record");
2185       if (CurTy->isHalfTy())
2186         V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf(),
2187                                              APInt(16, (uint16_t)Record[0])));
2188       else if (CurTy->isFloatTy())
2189         V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle(),
2190                                              APInt(32, (uint32_t)Record[0])));
2191       else if (CurTy->isDoubleTy())
2192         V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble(),
2193                                              APInt(64, Record[0])));
2194       else if (CurTy->isX86_FP80Ty()) {
2195         // Bits are not stored the same way as a normal i80 APInt, compensate.
2196         uint64_t Rearrange[2];
2197         Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2198         Rearrange[1] = Record[0] >> 48;
2199         V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended(),
2200                                              APInt(80, Rearrange)));
2201       } else if (CurTy->isFP128Ty())
2202         V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad(),
2203                                              APInt(128, Record)));
2204       else if (CurTy->isPPC_FP128Ty())
2205         V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble(),
2206                                              APInt(128, Record)));
2207       else
2208         V = UndefValue::get(CurTy);
2209       break;
2210     }
2211
2212     case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2213       if (Record.empty())
2214         return error("Invalid record");
2215
2216       unsigned Size = Record.size();
2217       SmallVector<Constant*, 16> Elts;
2218
2219       if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2220         for (unsigned i = 0; i != Size; ++i)
2221           Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2222                                                      STy->getElementType(i)));
2223         V = ConstantStruct::get(STy, Elts);
2224       } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2225         Type *EltTy = ATy->getElementType();
2226         for (unsigned i = 0; i != Size; ++i)
2227           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2228         V = ConstantArray::get(ATy, Elts);
2229       } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2230         Type *EltTy = VTy->getElementType();
2231         for (unsigned i = 0; i != Size; ++i)
2232           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2233         V = ConstantVector::get(Elts);
2234       } else {
2235         V = UndefValue::get(CurTy);
2236       }
2237       break;
2238     }
2239     case bitc::CST_CODE_STRING:    // STRING: [values]
2240     case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2241       if (Record.empty())
2242         return error("Invalid record");
2243
2244       SmallString<16> Elts(Record.begin(), Record.end());
2245       V = ConstantDataArray::getString(Context, Elts,
2246                                        BitCode == bitc::CST_CODE_CSTRING);
2247       break;
2248     }
2249     case bitc::CST_CODE_DATA: {// DATA: [n x value]
2250       if (Record.empty())
2251         return error("Invalid record");
2252
2253       Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2254       if (EltTy->isIntegerTy(8)) {
2255         SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2256         if (isa<VectorType>(CurTy))
2257           V = ConstantDataVector::get(Context, Elts);
2258         else
2259           V = ConstantDataArray::get(Context, Elts);
2260       } else if (EltTy->isIntegerTy(16)) {
2261         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2262         if (isa<VectorType>(CurTy))
2263           V = ConstantDataVector::get(Context, Elts);
2264         else
2265           V = ConstantDataArray::get(Context, Elts);
2266       } else if (EltTy->isIntegerTy(32)) {
2267         SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2268         if (isa<VectorType>(CurTy))
2269           V = ConstantDataVector::get(Context, Elts);
2270         else
2271           V = ConstantDataArray::get(Context, Elts);
2272       } else if (EltTy->isIntegerTy(64)) {
2273         SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2274         if (isa<VectorType>(CurTy))
2275           V = ConstantDataVector::get(Context, Elts);
2276         else
2277           V = ConstantDataArray::get(Context, Elts);
2278       } else if (EltTy->isHalfTy()) {
2279         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2280         if (isa<VectorType>(CurTy))
2281           V = ConstantDataVector::getFP(Context, Elts);
2282         else
2283           V = ConstantDataArray::getFP(Context, Elts);
2284       } else if (EltTy->isFloatTy()) {
2285         SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2286         if (isa<VectorType>(CurTy))
2287           V = ConstantDataVector::getFP(Context, Elts);
2288         else
2289           V = ConstantDataArray::getFP(Context, Elts);
2290       } else if (EltTy->isDoubleTy()) {
2291         SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2292         if (isa<VectorType>(CurTy))
2293           V = ConstantDataVector::getFP(Context, Elts);
2294         else
2295           V = ConstantDataArray::getFP(Context, Elts);
2296       } else {
2297         return error("Invalid type for value");
2298       }
2299       break;
2300     }
2301     case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
2302       if (Record.size() < 3)
2303         return error("Invalid record");
2304       int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
2305       if (Opc < 0) {
2306         V = UndefValue::get(CurTy);  // Unknown binop.
2307       } else {
2308         Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2309         Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2310         unsigned Flags = 0;
2311         if (Record.size() >= 4) {
2312           if (Opc == Instruction::Add ||
2313               Opc == Instruction::Sub ||
2314               Opc == Instruction::Mul ||
2315               Opc == Instruction::Shl) {
2316             if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2317               Flags |= OverflowingBinaryOperator::NoSignedWrap;
2318             if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2319               Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2320           } else if (Opc == Instruction::SDiv ||
2321                      Opc == Instruction::UDiv ||
2322                      Opc == Instruction::LShr ||
2323                      Opc == Instruction::AShr) {
2324             if (Record[3] & (1 << bitc::PEO_EXACT))
2325               Flags |= SDivOperator::IsExact;
2326           }
2327         }
2328         V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2329       }
2330       break;
2331     }
2332     case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
2333       if (Record.size() < 3)
2334         return error("Invalid record");
2335       int Opc = getDecodedCastOpcode(Record[0]);
2336       if (Opc < 0) {
2337         V = UndefValue::get(CurTy);  // Unknown cast.
2338       } else {
2339         Type *OpTy = getTypeByID(Record[1]);
2340         if (!OpTy)
2341           return error("Invalid record");
2342         Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2343         V = UpgradeBitCastExpr(Opc, Op, CurTy);
2344         if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2345       }
2346       break;
2347     }
2348     case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands]
2349     case bitc::CST_CODE_CE_GEP: // [ty, n x operands]
2350     case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX: { // [ty, flags, n x
2351                                                      // operands]
2352       unsigned OpNum = 0;
2353       Type *PointeeType = nullptr;
2354       if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX ||
2355           Record.size() % 2)
2356         PointeeType = getTypeByID(Record[OpNum++]);
2357
2358       bool InBounds = false;
2359       Optional<unsigned> InRangeIndex;
2360       if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX) {
2361         uint64_t Op = Record[OpNum++];
2362         InBounds = Op & 1;
2363         InRangeIndex = Op >> 1;
2364       } else if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
2365         InBounds = true;
2366
2367       SmallVector<Constant*, 16> Elts;
2368       while (OpNum != Record.size()) {
2369         Type *ElTy = getTypeByID(Record[OpNum++]);
2370         if (!ElTy)
2371           return error("Invalid record");
2372         Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2373       }
2374
2375       if (PointeeType &&
2376           PointeeType !=
2377               cast<PointerType>(Elts[0]->getType()->getScalarType())
2378                   ->getElementType())
2379         return error("Explicit gep operator type does not match pointee type "
2380                      "of pointer operand");
2381
2382       if (Elts.size() < 1)
2383         return error("Invalid gep with no operands");
2384
2385       ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2386       V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2387                                          InBounds, InRangeIndex);
2388       break;
2389     }
2390     case bitc::CST_CODE_CE_SELECT: {  // CE_SELECT: [opval#, opval#, opval#]
2391       if (Record.size() < 3)
2392         return error("Invalid record");
2393
2394       Type *SelectorTy = Type::getInt1Ty(Context);
2395
2396       // The selector might be an i1 or an <n x i1>
2397       // Get the type from the ValueList before getting a forward ref.
2398       if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2399         if (Value *V = ValueList[Record[0]])
2400           if (SelectorTy != V->getType())
2401             SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
2402
2403       V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2404                                                               SelectorTy),
2405                                   ValueList.getConstantFwdRef(Record[1],CurTy),
2406                                   ValueList.getConstantFwdRef(Record[2],CurTy));
2407       break;
2408     }
2409     case bitc::CST_CODE_CE_EXTRACTELT
2410         : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2411       if (Record.size() < 3)
2412         return error("Invalid record");
2413       VectorType *OpTy =
2414         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2415       if (!OpTy)
2416         return error("Invalid record");
2417       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2418       Constant *Op1 = nullptr;
2419       if (Record.size() == 4) {
2420         Type *IdxTy = getTypeByID(Record[2]);
2421         if (!IdxTy)
2422           return error("Invalid record");
2423         Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2424       } else // TODO: Remove with llvm 4.0
2425         Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2426       if (!Op1)
2427         return error("Invalid record");
2428       V = ConstantExpr::getExtractElement(Op0, Op1);
2429       break;
2430     }
2431     case bitc::CST_CODE_CE_INSERTELT
2432         : { // CE_INSERTELT: [opval, opval, opty, opval]
2433       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2434       if (Record.size() < 3 || !OpTy)
2435         return error("Invalid record");
2436       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2437       Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2438                                                   OpTy->getElementType());
2439       Constant *Op2 = nullptr;
2440       if (Record.size() == 4) {
2441         Type *IdxTy = getTypeByID(Record[2]);
2442         if (!IdxTy)
2443           return error("Invalid record");
2444         Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2445       } else // TODO: Remove with llvm 4.0
2446         Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2447       if (!Op2)
2448         return error("Invalid record");
2449       V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2450       break;
2451     }
2452     case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2453       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2454       if (Record.size() < 3 || !OpTy)
2455         return error("Invalid record");
2456       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2457       Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2458       Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2459                                                  OpTy->getNumElements());
2460       Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2461       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2462       break;
2463     }
2464     case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2465       VectorType *RTy = dyn_cast<VectorType>(CurTy);
2466       VectorType *OpTy =
2467         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2468       if (Record.size() < 4 || !RTy || !OpTy)
2469         return error("Invalid record");
2470       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2471       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2472       Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2473                                                  RTy->getNumElements());
2474       Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2475       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2476       break;
2477     }
2478     case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
2479       if (Record.size() < 4)
2480         return error("Invalid record");
2481       Type *OpTy = getTypeByID(Record[0]);
2482       if (!OpTy)
2483         return error("Invalid record");
2484       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2485       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2486
2487       if (OpTy->isFPOrFPVectorTy())
2488         V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2489       else
2490         V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2491       break;
2492     }
2493     // This maintains backward compatibility, pre-asm dialect keywords.
2494     // FIXME: Remove with the 4.0 release.
2495     case bitc::CST_CODE_INLINEASM_OLD: {
2496       if (Record.size() < 2)
2497         return error("Invalid record");
2498       std::string AsmStr, ConstrStr;
2499       bool HasSideEffects = Record[0] & 1;
2500       bool IsAlignStack = Record[0] >> 1;
2501       unsigned AsmStrSize = Record[1];
2502       if (2+AsmStrSize >= Record.size())
2503         return error("Invalid record");
2504       unsigned ConstStrSize = Record[2+AsmStrSize];
2505       if (3+AsmStrSize+ConstStrSize > Record.size())
2506         return error("Invalid record");
2507
2508       for (unsigned i = 0; i != AsmStrSize; ++i)
2509         AsmStr += (char)Record[2+i];
2510       for (unsigned i = 0; i != ConstStrSize; ++i)
2511         ConstrStr += (char)Record[3+AsmStrSize+i];
2512       PointerType *PTy = cast<PointerType>(CurTy);
2513       V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2514                          AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2515       break;
2516     }
2517     // This version adds support for the asm dialect keywords (e.g.,
2518     // inteldialect).
2519     case bitc::CST_CODE_INLINEASM: {
2520       if (Record.size() < 2)
2521         return error("Invalid record");
2522       std::string AsmStr, ConstrStr;
2523       bool HasSideEffects = Record[0] & 1;
2524       bool IsAlignStack = (Record[0] >> 1) & 1;
2525       unsigned AsmDialect = Record[0] >> 2;
2526       unsigned AsmStrSize = Record[1];
2527       if (2+AsmStrSize >= Record.size())
2528         return error("Invalid record");
2529       unsigned ConstStrSize = Record[2+AsmStrSize];
2530       if (3+AsmStrSize+ConstStrSize > Record.size())
2531         return error("Invalid record");
2532
2533       for (unsigned i = 0; i != AsmStrSize; ++i)
2534         AsmStr += (char)Record[2+i];
2535       for (unsigned i = 0; i != ConstStrSize; ++i)
2536         ConstrStr += (char)Record[3+AsmStrSize+i];
2537       PointerType *PTy = cast<PointerType>(CurTy);
2538       V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2539                          AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2540                          InlineAsm::AsmDialect(AsmDialect));
2541       break;
2542     }
2543     case bitc::CST_CODE_BLOCKADDRESS:{
2544       if (Record.size() < 3)
2545         return error("Invalid record");
2546       Type *FnTy = getTypeByID(Record[0]);
2547       if (!FnTy)
2548         return error("Invalid record");
2549       Function *Fn =
2550         dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2551       if (!Fn)
2552         return error("Invalid record");
2553
2554       // If the function is already parsed we can insert the block address right
2555       // away.
2556       BasicBlock *BB;
2557       unsigned BBID = Record[2];
2558       if (!BBID)
2559         // Invalid reference to entry block.
2560         return error("Invalid ID");
2561       if (!Fn->empty()) {
2562         Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2563         for (size_t I = 0, E = BBID; I != E; ++I) {
2564           if (BBI == BBE)
2565             return error("Invalid ID");
2566           ++BBI;
2567         }
2568         BB = &*BBI;
2569       } else {
2570         // Otherwise insert a placeholder and remember it so it can be inserted
2571         // when the function is parsed.
2572         auto &FwdBBs = BasicBlockFwdRefs[Fn];
2573         if (FwdBBs.empty())
2574           BasicBlockFwdRefQueue.push_back(Fn);
2575         if (FwdBBs.size() < BBID + 1)
2576           FwdBBs.resize(BBID + 1);
2577         if (!FwdBBs[BBID])
2578           FwdBBs[BBID] = BasicBlock::Create(Context);
2579         BB = FwdBBs[BBID];
2580       }
2581       V = BlockAddress::get(Fn, BB);
2582       break;
2583     }
2584     }
2585
2586     ValueList.assignValue(V, NextCstNo);
2587     ++NextCstNo;
2588   }
2589 }
2590
2591 Error BitcodeReader::parseUseLists() {
2592   if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2593     return error("Invalid record");
2594
2595   // Read all the records.
2596   SmallVector<uint64_t, 64> Record;
2597
2598   while (true) {
2599     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2600
2601     switch (Entry.Kind) {
2602     case BitstreamEntry::SubBlock: // Handled for us already.
2603     case BitstreamEntry::Error:
2604       return error("Malformed block");
2605     case BitstreamEntry::EndBlock:
2606       return Error::success();
2607     case BitstreamEntry::Record:
2608       // The interesting case.
2609       break;
2610     }
2611
2612     // Read a use list record.
2613     Record.clear();
2614     bool IsBB = false;
2615     switch (Stream.readRecord(Entry.ID, Record)) {
2616     default:  // Default behavior: unknown type.
2617       break;
2618     case bitc::USELIST_CODE_BB:
2619       IsBB = true;
2620       LLVM_FALLTHROUGH;
2621     case bitc::USELIST_CODE_DEFAULT: {
2622       unsigned RecordLength = Record.size();
2623       if (RecordLength < 3)
2624         // Records should have at least an ID and two indexes.
2625         return error("Invalid record");
2626       unsigned ID = Record.back();
2627       Record.pop_back();
2628
2629       Value *V;
2630       if (IsBB) {
2631         assert(ID < FunctionBBs.size() && "Basic block not found");
2632         V = FunctionBBs[ID];
2633       } else
2634         V = ValueList[ID];
2635       unsigned NumUses = 0;
2636       SmallDenseMap<const Use *, unsigned, 16> Order;
2637       for (const Use &U : V->materialized_uses()) {
2638         if (++NumUses > Record.size())
2639           break;
2640         Order[&U] = Record[NumUses - 1];
2641       }
2642       if (Order.size() != Record.size() || NumUses > Record.size())
2643         // Mismatches can happen if the functions are being materialized lazily
2644         // (out-of-order), or a value has been upgraded.
2645         break;
2646
2647       V->sortUseList([&](const Use &L, const Use &R) {
2648         return Order.lookup(&L) < Order.lookup(&R);
2649       });
2650       break;
2651     }
2652     }
2653   }
2654 }
2655
2656 /// When we see the block for metadata, remember where it is and then skip it.
2657 /// This lets us lazily deserialize the metadata.
2658 Error BitcodeReader::rememberAndSkipMetadata() {
2659   // Save the current stream state.
2660   uint64_t CurBit = Stream.GetCurrentBitNo();
2661   DeferredMetadataInfo.push_back(CurBit);
2662
2663   // Skip over the block for now.
2664   if (Stream.SkipBlock())
2665     return error("Invalid record");
2666   return Error::success();
2667 }
2668
2669 Error BitcodeReader::materializeMetadata() {
2670   for (uint64_t BitPos : DeferredMetadataInfo) {
2671     // Move the bit stream to the saved position.
2672     Stream.JumpToBit(BitPos);
2673     if (Error Err = MDLoader->parseModuleMetadata())
2674       return Err;
2675   }
2676
2677   // Upgrade "Linker Options" module flag to "llvm.linker.options" module-level
2678   // metadata.
2679   if (Metadata *Val = TheModule->getModuleFlag("Linker Options")) {
2680     NamedMDNode *LinkerOpts =
2681         TheModule->getOrInsertNamedMetadata("llvm.linker.options");
2682     for (const MDOperand &MDOptions : cast<MDNode>(Val)->operands())
2683       LinkerOpts->addOperand(cast<MDNode>(MDOptions));
2684   }
2685
2686   DeferredMetadataInfo.clear();
2687   return Error::success();
2688 }
2689
2690 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
2691
2692 /// When we see the block for a function body, remember where it is and then
2693 /// skip it.  This lets us lazily deserialize the functions.
2694 Error BitcodeReader::rememberAndSkipFunctionBody() {
2695   // Get the function we are talking about.
2696   if (FunctionsWithBodies.empty())
2697     return error("Insufficient function protos");
2698
2699   Function *Fn = FunctionsWithBodies.back();
2700   FunctionsWithBodies.pop_back();
2701
2702   // Save the current stream state.
2703   uint64_t CurBit = Stream.GetCurrentBitNo();
2704   assert(
2705       (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
2706       "Mismatch between VST and scanned function offsets");
2707   DeferredFunctionInfo[Fn] = CurBit;
2708
2709   // Skip over the function block for now.
2710   if (Stream.SkipBlock())
2711     return error("Invalid record");
2712   return Error::success();
2713 }
2714
2715 Error BitcodeReader::globalCleanup() {
2716   // Patch the initializers for globals and aliases up.
2717   if (Error Err = resolveGlobalAndIndirectSymbolInits())
2718     return Err;
2719   if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
2720     return error("Malformed global initializer set");
2721
2722   // Look for intrinsic functions which need to be upgraded at some point
2723   for (Function &F : *TheModule) {
2724     MDLoader->upgradeDebugIntrinsics(F);
2725     Function *NewFn;
2726     if (UpgradeIntrinsicFunction(&F, NewFn))
2727       UpgradedIntrinsics[&F] = NewFn;
2728     else if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F))
2729       // Some types could be renamed during loading if several modules are
2730       // loaded in the same LLVMContext (LTO scenario). In this case we should
2731       // remangle intrinsics names as well.
2732       RemangledIntrinsics[&F] = Remangled.getValue();
2733   }
2734
2735   // Look for global variables which need to be renamed.
2736   for (GlobalVariable &GV : TheModule->globals())
2737     UpgradeGlobalVariable(&GV);
2738
2739   // Force deallocation of memory for these vectors to favor the client that
2740   // want lazy deserialization.
2741   std::vector<std::pair<GlobalVariable *, unsigned>>().swap(GlobalInits);
2742   std::vector<std::pair<GlobalIndirectSymbol *, unsigned>>().swap(
2743       IndirectSymbolInits);
2744   return Error::success();
2745 }
2746
2747 /// Support for lazy parsing of function bodies. This is required if we
2748 /// either have an old bitcode file without a VST forward declaration record,
2749 /// or if we have an anonymous function being materialized, since anonymous
2750 /// functions do not have a name and are therefore not in the VST.
2751 Error BitcodeReader::rememberAndSkipFunctionBodies() {
2752   Stream.JumpToBit(NextUnreadBit);
2753
2754   if (Stream.AtEndOfStream())
2755     return error("Could not find function in stream");
2756
2757   if (!SeenFirstFunctionBody)
2758     return error("Trying to materialize functions before seeing function blocks");
2759
2760   // An old bitcode file with the symbol table at the end would have
2761   // finished the parse greedily.
2762   assert(SeenValueSymbolTable);
2763
2764   SmallVector<uint64_t, 64> Record;
2765
2766   while (true) {
2767     BitstreamEntry Entry = Stream.advance();
2768     switch (Entry.Kind) {
2769     default:
2770       return error("Expect SubBlock");
2771     case BitstreamEntry::SubBlock:
2772       switch (Entry.ID) {
2773       default:
2774         return error("Expect function block");
2775       case bitc::FUNCTION_BLOCK_ID:
2776         if (Error Err = rememberAndSkipFunctionBody())
2777           return Err;
2778         NextUnreadBit = Stream.GetCurrentBitNo();
2779         return Error::success();
2780       }
2781     }
2782   }
2783 }
2784
2785 bool BitcodeReaderBase::readBlockInfo() {
2786   Optional<BitstreamBlockInfo> NewBlockInfo = Stream.ReadBlockInfoBlock();
2787   if (!NewBlockInfo)
2788     return true;
2789   BlockInfo = std::move(*NewBlockInfo);
2790   return false;
2791 }
2792
2793 Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) {
2794   // v1: [selection_kind, name]
2795   // v2: [strtab_offset, strtab_size, selection_kind]
2796   StringRef Name;
2797   std::tie(Name, Record) = readNameFromStrtab(Record);
2798
2799   if (Record.empty())
2800     return error("Invalid record");
2801   Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
2802   std::string OldFormatName;
2803   if (!UseStrtab) {
2804     if (Record.size() < 2)
2805       return error("Invalid record");
2806     unsigned ComdatNameSize = Record[1];
2807     OldFormatName.reserve(ComdatNameSize);
2808     for (unsigned i = 0; i != ComdatNameSize; ++i)
2809       OldFormatName += (char)Record[2 + i];
2810     Name = OldFormatName;
2811   }
2812   Comdat *C = TheModule->getOrInsertComdat(Name);
2813   C->setSelectionKind(SK);
2814   ComdatList.push_back(C);
2815   return Error::success();
2816 }
2817
2818 Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) {
2819   // v1: [pointer type, isconst, initid, linkage, alignment, section,
2820   // visibility, threadlocal, unnamed_addr, externally_initialized,
2821   // dllstorageclass, comdat, attributes, preemption specifier] (name in VST)
2822   // v2: [strtab_offset, strtab_size, v1]
2823   StringRef Name;
2824   std::tie(Name, Record) = readNameFromStrtab(Record);
2825
2826   if (Record.size() < 6)
2827     return error("Invalid record");
2828   Type *Ty = getTypeByID(Record[0]);
2829   if (!Ty)
2830     return error("Invalid record");
2831   bool isConstant = Record[1] & 1;
2832   bool explicitType = Record[1] & 2;
2833   unsigned AddressSpace;
2834   if (explicitType) {
2835     AddressSpace = Record[1] >> 2;
2836   } else {
2837     if (!Ty->isPointerTy())
2838       return error("Invalid type for value");
2839     AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2840     Ty = cast<PointerType>(Ty)->getElementType();
2841   }
2842
2843   uint64_t RawLinkage = Record[3];
2844   GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
2845   unsigned Alignment;
2846   if (Error Err = parseAlignmentValue(Record[4], Alignment))
2847     return Err;
2848   std::string Section;
2849   if (Record[5]) {
2850     if (Record[5] - 1 >= SectionTable.size())
2851       return error("Invalid ID");
2852     Section = SectionTable[Record[5] - 1];
2853   }
2854   GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
2855   // Local linkage must have default visibility.
2856   if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2857     // FIXME: Change to an error if non-default in 4.0.
2858     Visibility = getDecodedVisibility(Record[6]);
2859
2860   GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
2861   if (Record.size() > 7)
2862     TLM = getDecodedThreadLocalMode(Record[7]);
2863
2864   GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
2865   if (Record.size() > 8)
2866     UnnamedAddr = getDecodedUnnamedAddrType(Record[8]);
2867
2868   bool ExternallyInitialized = false;
2869   if (Record.size() > 9)
2870     ExternallyInitialized = Record[9];
2871
2872   GlobalVariable *NewGV =
2873       new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, Name,
2874                          nullptr, TLM, AddressSpace, ExternallyInitialized);
2875   NewGV->setAlignment(Alignment);
2876   if (!Section.empty())
2877     NewGV->setSection(Section);
2878   NewGV->setVisibility(Visibility);
2879   NewGV->setUnnamedAddr(UnnamedAddr);
2880
2881   if (Record.size() > 10)
2882     NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
2883   else
2884     upgradeDLLImportExportLinkage(NewGV, RawLinkage);
2885
2886   ValueList.push_back(NewGV);
2887
2888   // Remember which value to use for the global initializer.
2889   if (unsigned InitID = Record[2])
2890     GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));
2891
2892   if (Record.size() > 11) {
2893     if (unsigned ComdatID = Record[11]) {
2894       if (ComdatID > ComdatList.size())
2895         return error("Invalid global variable comdat ID");
2896       NewGV->setComdat(ComdatList[ComdatID - 1]);
2897     }
2898   } else if (hasImplicitComdat(RawLinkage)) {
2899     NewGV->setComdat(reinterpret_cast<Comdat *>(1));
2900   }
2901
2902   if (Record.size() > 12) {
2903     auto AS = getAttributes(Record[12]).getFnAttributes();
2904     NewGV->setAttributes(AS);
2905   }
2906
2907   if (Record.size() > 13) {
2908     NewGV->setDSOLocal(getDecodedDSOLocal(Record[13]));
2909   }
2910
2911   return Error::success();
2912 }
2913
2914 Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) {
2915   // v1: [type, callingconv, isproto, linkage, paramattr, alignment, section,
2916   // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat,
2917   // prefixdata,  personalityfn, preemption specifier] (name in VST)
2918   // v2: [strtab_offset, strtab_size, v1]
2919   StringRef Name;
2920   std::tie(Name, Record) = readNameFromStrtab(Record);
2921
2922   if (Record.size() < 8)
2923     return error("Invalid record");
2924   Type *Ty = getTypeByID(Record[0]);
2925   if (!Ty)
2926     return error("Invalid record");
2927   if (auto *PTy = dyn_cast<PointerType>(Ty))
2928     Ty = PTy->getElementType();
2929   auto *FTy = dyn_cast<FunctionType>(Ty);
2930   if (!FTy)
2931     return error("Invalid type for value");
2932   auto CC = static_cast<CallingConv::ID>(Record[1]);
2933   if (CC & ~CallingConv::MaxID)
2934     return error("Invalid calling convention ID");
2935
2936   Function *Func =
2937       Function::Create(FTy, GlobalValue::ExternalLinkage, Name, TheModule);
2938
2939   Func->setCallingConv(CC);
2940   bool isProto = Record[2];
2941   uint64_t RawLinkage = Record[3];
2942   Func->setLinkage(getDecodedLinkage(RawLinkage));
2943   Func->setAttributes(getAttributes(Record[4]));
2944
2945   unsigned Alignment;
2946   if (Error Err = parseAlignmentValue(Record[5], Alignment))
2947     return Err;
2948   Func->setAlignment(Alignment);
2949   if (Record[6]) {
2950     if (Record[6] - 1 >= SectionTable.size())
2951       return error("Invalid ID");
2952     Func->setSection(SectionTable[Record[6] - 1]);
2953   }
2954   // Local linkage must have default visibility.
2955   if (!Func->hasLocalLinkage())
2956     // FIXME: Change to an error if non-default in 4.0.
2957     Func->setVisibility(getDecodedVisibility(Record[7]));
2958   if (Record.size() > 8 && Record[8]) {
2959     if (Record[8] - 1 >= GCTable.size())
2960       return error("Invalid ID");
2961     Func->setGC(GCTable[Record[8] - 1]);
2962   }
2963   GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
2964   if (Record.size() > 9)
2965     UnnamedAddr = getDecodedUnnamedAddrType(Record[9]);
2966   Func->setUnnamedAddr(UnnamedAddr);
2967   if (Record.size() > 10 && Record[10] != 0)
2968     FunctionPrologues.push_back(std::make_pair(Func, Record[10] - 1));
2969
2970   if (Record.size() > 11)
2971     Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
2972   else
2973     upgradeDLLImportExportLinkage(Func, RawLinkage);
2974
2975   if (Record.size() > 12) {
2976     if (unsigned ComdatID = Record[12]) {
2977       if (ComdatID > ComdatList.size())
2978         return error("Invalid function comdat ID");
2979       Func->setComdat(ComdatList[ComdatID - 1]);
2980     }
2981   } else if (hasImplicitComdat(RawLinkage)) {
2982     Func->setComdat(reinterpret_cast<Comdat *>(1));
2983   }
2984
2985   if (Record.size() > 13 && Record[13] != 0)
2986     FunctionPrefixes.push_back(std::make_pair(Func, Record[13] - 1));
2987
2988   if (Record.size() > 14 && Record[14] != 0)
2989     FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
2990
2991   if (Record.size() > 15) {
2992     Func->setDSOLocal(getDecodedDSOLocal(Record[15]));
2993   }
2994
2995   ValueList.push_back(Func);
2996
2997   // If this is a function with a body, remember the prototype we are
2998   // creating now, so that we can match up the body with them later.
2999   if (!isProto) {
3000     Func->setIsMaterializable(true);
3001     FunctionsWithBodies.push_back(Func);
3002     DeferredFunctionInfo[Func] = 0;
3003   }
3004   return Error::success();
3005 }
3006
3007 Error BitcodeReader::parseGlobalIndirectSymbolRecord(
3008     unsigned BitCode, ArrayRef<uint64_t> Record) {
3009   // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST)
3010   // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
3011   // dllstorageclass, threadlocal, unnamed_addr,
3012   // preemption specifier] (name in VST)
3013   // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage,
3014   // visibility, dllstorageclass, threadlocal, unnamed_addr,
3015   // preemption specifier] (name in VST)
3016   // v2: [strtab_offset, strtab_size, v1]
3017   StringRef Name;
3018   std::tie(Name, Record) = readNameFromStrtab(Record);
3019
3020   bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
3021   if (Record.size() < (3 + (unsigned)NewRecord))
3022     return error("Invalid record");
3023   unsigned OpNum = 0;
3024   Type *Ty = getTypeByID(Record[OpNum++]);
3025   if (!Ty)
3026     return error("Invalid record");
3027
3028   unsigned AddrSpace;
3029   if (!NewRecord) {
3030     auto *PTy = dyn_cast<PointerType>(Ty);
3031     if (!PTy)
3032       return error("Invalid type for value");
3033     Ty = PTy->getElementType();
3034     AddrSpace = PTy->getAddressSpace();
3035   } else {
3036     AddrSpace = Record[OpNum++];
3037   }
3038
3039   auto Val = Record[OpNum++];
3040   auto Linkage = Record[OpNum++];
3041   GlobalIndirectSymbol *NewGA;
3042   if (BitCode == bitc::MODULE_CODE_ALIAS ||
3043       BitCode == bitc::MODULE_CODE_ALIAS_OLD)
3044     NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
3045                                 TheModule);
3046   else
3047     NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
3048                                 nullptr, TheModule);
3049   // Old bitcode files didn't have visibility field.
3050   // Local linkage must have default visibility.
3051   if (OpNum != Record.size()) {
3052     auto VisInd = OpNum++;
3053     if (!NewGA->hasLocalLinkage())
3054       // FIXME: Change to an error if non-default in 4.0.
3055       NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
3056   }
3057   if (OpNum != Record.size())
3058     NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
3059   else
3060     upgradeDLLImportExportLinkage(NewGA, Linkage);
3061   if (OpNum != Record.size())
3062     NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
3063   if (OpNum != Record.size())
3064     NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++]));
3065   if (OpNum != Record.size())
3066     NewGA->setDSOLocal(getDecodedDSOLocal(Record[OpNum++]));
3067   ValueList.push_back(NewGA);
3068   IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
3069   return Error::success();
3070 }
3071
3072 Error BitcodeReader::parseModule(uint64_t ResumeBit,
3073                                  bool ShouldLazyLoadMetadata) {
3074   if (ResumeBit)
3075     Stream.JumpToBit(ResumeBit);
3076   else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3077     return error("Invalid record");
3078
3079   SmallVector<uint64_t, 64> Record;
3080
3081   // Read all the records for this module.
3082   while (true) {
3083     BitstreamEntry Entry = Stream.advance();
3084
3085     switch (Entry.Kind) {
3086     case BitstreamEntry::Error:
3087       return error("Malformed block");
3088     case BitstreamEntry::EndBlock:
3089       return globalCleanup();
3090
3091     case BitstreamEntry::SubBlock:
3092       switch (Entry.ID) {
3093       default:  // Skip unknown content.
3094         if (Stream.SkipBlock())
3095           return error("Invalid record");
3096         break;
3097       case bitc::BLOCKINFO_BLOCK_ID:
3098         if (readBlockInfo())
3099           return error("Malformed block");
3100         break;
3101       case bitc::PARAMATTR_BLOCK_ID:
3102         if (Error Err = parseAttributeBlock())
3103           return Err;
3104         break;
3105       case bitc::PARAMATTR_GROUP_BLOCK_ID:
3106         if (Error Err = parseAttributeGroupBlock())
3107           return Err;
3108         break;
3109       case bitc::TYPE_BLOCK_ID_NEW:
3110         if (Error Err = parseTypeTable())
3111           return Err;
3112         break;
3113       case bitc::VALUE_SYMTAB_BLOCK_ID:
3114         if (!SeenValueSymbolTable) {
3115           // Either this is an old form VST without function index and an
3116           // associated VST forward declaration record (which would have caused
3117           // the VST to be jumped to and parsed before it was encountered
3118           // normally in the stream), or there were no function blocks to
3119           // trigger an earlier parsing of the VST.
3120           assert(VSTOffset == 0 || FunctionsWithBodies.empty());
3121           if (Error Err = parseValueSymbolTable())
3122             return Err;
3123           SeenValueSymbolTable = true;
3124         } else {
3125           // We must have had a VST forward declaration record, which caused
3126           // the parser to jump to and parse the VST earlier.
3127           assert(VSTOffset > 0);
3128           if (Stream.SkipBlock())
3129             return error("Invalid record");
3130         }
3131         break;
3132       case bitc::CONSTANTS_BLOCK_ID:
3133         if (Error Err = parseConstants())
3134           return Err;
3135         if (Error Err = resolveGlobalAndIndirectSymbolInits())
3136           return Err;
3137         break;
3138       case bitc::METADATA_BLOCK_ID:
3139         if (ShouldLazyLoadMetadata) {
3140           if (Error Err = rememberAndSkipMetadata())
3141             return Err;
3142           break;
3143         }
3144         assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
3145         if (Error Err = MDLoader->parseModuleMetadata())
3146           return Err;
3147         break;
3148       case bitc::METADATA_KIND_BLOCK_ID:
3149         if (Error Err = MDLoader->parseMetadataKinds())
3150           return Err;
3151         break;
3152       case bitc::FUNCTION_BLOCK_ID:
3153         // If this is the first function body we've seen, reverse the
3154         // FunctionsWithBodies list.
3155         if (!SeenFirstFunctionBody) {
3156           std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
3157           if (Error Err = globalCleanup())
3158             return Err;
3159           SeenFirstFunctionBody = true;
3160         }
3161
3162         if (VSTOffset > 0) {
3163           // If we have a VST forward declaration record, make sure we
3164           // parse the VST now if we haven't already. It is needed to
3165           // set up the DeferredFunctionInfo vector for lazy reading.
3166           if (!SeenValueSymbolTable) {
3167             if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
3168               return Err;
3169             SeenValueSymbolTable = true;
3170             // Fall through so that we record the NextUnreadBit below.
3171             // This is necessary in case we have an anonymous function that
3172             // is later materialized. Since it will not have a VST entry we
3173             // need to fall back to the lazy parse to find its offset.
3174           } else {
3175             // If we have a VST forward declaration record, but have already
3176             // parsed the VST (just above, when the first function body was
3177             // encountered here), then we are resuming the parse after
3178             // materializing functions. The ResumeBit points to the
3179             // start of the last function block recorded in the
3180             // DeferredFunctionInfo map. Skip it.
3181             if (Stream.SkipBlock())
3182               return error("Invalid record");
3183             continue;
3184           }
3185         }
3186
3187         // Support older bitcode files that did not have the function
3188         // index in the VST, nor a VST forward declaration record, as
3189         // well as anonymous functions that do not have VST entries.
3190         // Build the DeferredFunctionInfo vector on the fly.
3191         if (Error Err = rememberAndSkipFunctionBody())
3192           return Err;
3193
3194         // Suspend parsing when we reach the function bodies. Subsequent
3195         // materialization calls will resume it when necessary. If the bitcode
3196         // file is old, the symbol table will be at the end instead and will not
3197         // have been seen yet. In this case, just finish the parse now.
3198         if (SeenValueSymbolTable) {
3199           NextUnreadBit = Stream.GetCurrentBitNo();
3200           // After the VST has been parsed, we need to make sure intrinsic name
3201           // are auto-upgraded.
3202           return globalCleanup();
3203         }
3204         break;
3205       case bitc::USELIST_BLOCK_ID:
3206         if (Error Err = parseUseLists())
3207           return Err;
3208         break;
3209       case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
3210         if (Error Err = parseOperandBundleTags())
3211           return Err;
3212         break;
3213       case bitc::SYNC_SCOPE_NAMES_BLOCK_ID:
3214         if (Error Err = parseSyncScopeNames())
3215           return Err;
3216         break;
3217       }
3218       continue;
3219
3220     case BitstreamEntry::Record:
3221       // The interesting case.
3222       break;
3223     }
3224
3225     // Read a record.
3226     auto BitCode = Stream.readRecord(Entry.ID, Record);
3227     switch (BitCode) {
3228     default: break;  // Default behavior, ignore unknown content.
3229     case bitc::MODULE_CODE_VERSION: {
3230       Expected<unsigned> VersionOrErr = parseVersionRecord(Record);
3231       if (!VersionOrErr)
3232         return VersionOrErr.takeError();
3233       UseRelativeIDs = *VersionOrErr >= 1;
3234       break;
3235     }
3236     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
3237       std::string S;
3238       if (convertToString(Record, 0, S))
3239         return error("Invalid record");
3240       TheModule->setTargetTriple(S);
3241       break;
3242     }
3243     case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
3244       std::string S;
3245       if (convertToString(Record, 0, S))
3246         return error("Invalid record");
3247       TheModule->setDataLayout(S);
3248       break;
3249     }
3250     case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
3251       std::string S;
3252       if (convertToString(Record, 0, S))
3253         return error("Invalid record");
3254       TheModule->setModuleInlineAsm(S);
3255       break;
3256     }
3257     case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
3258       // FIXME: Remove in 4.0.
3259       std::string S;
3260       if (convertToString(Record, 0, S))
3261         return error("Invalid record");
3262       // Ignore value.
3263       break;
3264     }
3265     case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
3266       std::string S;
3267       if (convertToString(Record, 0, S))
3268         return error("Invalid record");
3269       SectionTable.push_back(S);
3270       break;
3271     }
3272     case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
3273       std::string S;
3274       if (convertToString(Record, 0, S))
3275         return error("Invalid record");
3276       GCTable.push_back(S);
3277       break;
3278     }
3279     case bitc::MODULE_CODE_COMDAT:
3280       if (Error Err = parseComdatRecord(Record))
3281         return Err;
3282       break;
3283     case bitc::MODULE_CODE_GLOBALVAR:
3284       if (Error Err = parseGlobalVarRecord(Record))
3285         return Err;
3286       break;
3287     case bitc::MODULE_CODE_FUNCTION:
3288       if (Error Err = parseFunctionRecord(Record))
3289         return Err;
3290       break;
3291     case bitc::MODULE_CODE_IFUNC:
3292     case bitc::MODULE_CODE_ALIAS:
3293     case bitc::MODULE_CODE_ALIAS_OLD:
3294       if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
3295         return Err;
3296       break;
3297     /// MODULE_CODE_VSTOFFSET: [offset]
3298     case bitc::MODULE_CODE_VSTOFFSET:
3299       if (Record.size() < 1)
3300         return error("Invalid record");
3301       // Note that we subtract 1 here because the offset is relative to one word
3302       // before the start of the identification or module block, which was
3303       // historically always the start of the regular bitcode header.
3304       VSTOffset = Record[0] - 1;
3305       break;
3306     /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
3307     case bitc::MODULE_CODE_SOURCE_FILENAME:
3308       SmallString<128> ValueName;
3309       if (convertToString(Record, 0, ValueName))
3310         return error("Invalid record");
3311       TheModule->setSourceFileName(ValueName);
3312       break;
3313     }
3314     Record.clear();
3315   }
3316 }
3317
3318 Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata,
3319                                       bool IsImporting) {
3320   TheModule = M;
3321   MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting,
3322                             [&](unsigned ID) { return getTypeByID(ID); });
3323   return parseModule(0, ShouldLazyLoadMetadata);
3324 }
3325
3326 Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
3327   if (!isa<PointerType>(PtrType))
3328     return error("Load/Store operand is not a pointer type");
3329   Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3330
3331   if (ValType && ValType != ElemType)
3332     return error("Explicit load/store type does not match pointee "
3333                  "type of pointer operand");
3334   if (!PointerType::isLoadableOrStorableType(ElemType))
3335     return error("Cannot load/store from pointer");
3336   return Error::success();
3337 }
3338
3339 /// Lazily parse the specified function body block.
3340 Error BitcodeReader::parseFunctionBody(Function *F) {
3341   if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3342     return error("Invalid record");
3343
3344   // Unexpected unresolved metadata when parsing function.
3345   if (MDLoader->hasFwdRefs())
3346     return error("Invalid function metadata: incoming forward references");
3347
3348   InstructionList.clear();
3349   unsigned ModuleValueListSize = ValueList.size();
3350   unsigned ModuleMDLoaderSize = MDLoader->size();
3351
3352   // Add all the function arguments to the value table.
3353   for (Argument &I : F->args())
3354     ValueList.push_back(&I);
3355
3356   unsigned NextValueNo = ValueList.size();
3357   BasicBlock *CurBB = nullptr;
3358   unsigned CurBBNo = 0;
3359
3360   DebugLoc LastLoc;
3361   auto getLastInstruction = [&]() -> Instruction * {
3362     if (CurBB && !CurBB->empty())
3363       return &CurBB->back();
3364     else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3365              !FunctionBBs[CurBBNo - 1]->empty())
3366       return &FunctionBBs[CurBBNo - 1]->back();
3367     return nullptr;
3368   };
3369
3370   std::vector<OperandBundleDef> OperandBundles;
3371
3372   // Read all the records.
3373   SmallVector<uint64_t, 64> Record;
3374
3375   while (true) {
3376     BitstreamEntry Entry = Stream.advance();
3377
3378     switch (Entry.Kind) {
3379     case BitstreamEntry::Error:
3380       return error("Malformed block");
3381     case BitstreamEntry::EndBlock:
3382       goto OutOfRecordLoop;
3383
3384     case BitstreamEntry::SubBlock:
3385       switch (Entry.ID) {
3386       default:  // Skip unknown content.
3387         if (Stream.SkipBlock())
3388           return error("Invalid record");
3389         break;
3390       case bitc::CONSTANTS_BLOCK_ID:
3391         if (Error Err = parseConstants())
3392           return Err;
3393         NextValueNo = ValueList.size();
3394         break;
3395       case bitc::VALUE_SYMTAB_BLOCK_ID:
3396         if (Error Err = parseValueSymbolTable())
3397           return Err;
3398         break;
3399       case bitc::METADATA_ATTACHMENT_ID:
3400         if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList))
3401           return Err;
3402         break;
3403       case bitc::METADATA_BLOCK_ID:
3404         assert(DeferredMetadataInfo.empty() &&
3405                "Must read all module-level metadata before function-level");
3406         if (Error Err = MDLoader->parseFunctionMetadata())
3407           return Err;
3408         break;
3409       case bitc::USELIST_BLOCK_ID:
3410         if (Error Err = parseUseLists())
3411           return Err;
3412         break;
3413       }
3414       continue;
3415
3416     case BitstreamEntry::Record:
3417       // The interesting case.
3418       break;
3419     }
3420
3421     // Read a record.
3422     Record.clear();
3423     Instruction *I = nullptr;
3424     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3425     switch (BitCode) {
3426     default: // Default behavior: reject
3427       return error("Invalid value");
3428     case bitc::FUNC_CODE_DECLAREBLOCKS: {   // DECLAREBLOCKS: [nblocks]
3429       if (Record.size() < 1 || Record[0] == 0)
3430         return error("Invalid record");
3431       // Create all the basic blocks for the function.
3432       FunctionBBs.resize(Record[0]);
3433
3434       // See if anything took the address of blocks in this function.
3435       auto BBFRI = BasicBlockFwdRefs.find(F);
3436       if (BBFRI == BasicBlockFwdRefs.end()) {
3437         for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3438           FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3439       } else {
3440         auto &BBRefs = BBFRI->second;
3441         // Check for invalid basic block references.
3442         if (BBRefs.size() > FunctionBBs.size())
3443           return error("Invalid ID");
3444         assert(!BBRefs.empty() && "Unexpected empty array");
3445         assert(!BBRefs.front() && "Invalid reference to entry block");
3446         for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
3447              ++I)
3448           if (I < RE && BBRefs[I]) {
3449             BBRefs[I]->insertInto(F);
3450             FunctionBBs[I] = BBRefs[I];
3451           } else {
3452             FunctionBBs[I] = BasicBlock::Create(Context, "", F);
3453           }
3454
3455         // Erase from the table.
3456         BasicBlockFwdRefs.erase(BBFRI);
3457       }
3458
3459       CurBB = FunctionBBs[0];
3460       continue;
3461     }
3462
3463     case bitc::FUNC_CODE_DEBUG_LOC_AGAIN:  // DEBUG_LOC_AGAIN
3464       // This record indicates that the last instruction is at the same
3465       // location as the previous instruction with a location.
3466       I = getLastInstruction();
3467
3468       if (!I)
3469         return error("Invalid record");
3470       I->setDebugLoc(LastLoc);
3471       I = nullptr;
3472       continue;
3473
3474     case bitc::FUNC_CODE_DEBUG_LOC: {      // DEBUG_LOC: [line, col, scope, ia]
3475       I = getLastInstruction();
3476       if (!I || Record.size() < 4)
3477         return error("Invalid record");
3478
3479       unsigned Line = Record[0], Col = Record[1];
3480       unsigned ScopeID = Record[2], IAID = Record[3];
3481
3482       MDNode *Scope = nullptr, *IA = nullptr;
3483       if (ScopeID) {
3484         Scope = MDLoader->getMDNodeFwdRefOrNull(ScopeID - 1);
3485         if (!Scope)
3486           return error("Invalid record");
3487       }
3488       if (IAID) {
3489         IA = MDLoader->getMDNodeFwdRefOrNull(IAID - 1);
3490         if (!IA)
3491           return error("Invalid record");
3492       }
3493       LastLoc = DebugLoc::get(Line, Col, Scope, IA);
3494       I->setDebugLoc(LastLoc);
3495       I = nullptr;
3496       continue;
3497     }
3498
3499     case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
3500       unsigned OpNum = 0;
3501       Value *LHS, *RHS;
3502       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3503           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3504           OpNum+1 > Record.size())
3505         return error("Invalid record");
3506
3507       int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
3508       if (Opc == -1)
3509         return error("Invalid record");
3510       I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3511       InstructionList.push_back(I);
3512       if (OpNum < Record.size()) {
3513         if (Opc == Instruction::Add ||
3514             Opc == Instruction::Sub ||
3515             Opc == Instruction::Mul ||
3516             Opc == Instruction::Shl) {
3517           if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3518             cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
3519           if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3520             cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
3521         } else if (Opc == Instruction::SDiv ||
3522                    Opc == Instruction::UDiv ||
3523                    Opc == Instruction::LShr ||
3524                    Opc == Instruction::AShr) {
3525           if (Record[OpNum] & (1 << bitc::PEO_EXACT))
3526             cast<BinaryOperator>(I)->setIsExact(true);
3527         } else if (isa<FPMathOperator>(I)) {
3528           FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
3529           if (FMF.any())
3530             I->setFastMathFlags(FMF);
3531         }
3532
3533       }
3534       break;
3535     }
3536     case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
3537       unsigned OpNum = 0;
3538       Value *Op;
3539       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3540           OpNum+2 != Record.size())
3541         return error("Invalid record");
3542
3543       Type *ResTy = getTypeByID(Record[OpNum]);
3544       int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
3545       if (Opc == -1 || !ResTy)
3546         return error("Invalid record");
3547       Instruction *Temp = nullptr;
3548       if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3549         if (Temp) {
3550           InstructionList.push_back(Temp);
3551           CurBB->getInstList().push_back(Temp);
3552         }
3553       } else {
3554         auto CastOp = (Instruction::CastOps)Opc;
3555         if (!CastInst::castIsValid(CastOp, Op, ResTy))
3556           return error("Invalid cast");
3557         I = CastInst::Create(CastOp, Op, ResTy);
3558       }
3559       InstructionList.push_back(I);
3560       break;
3561     }
3562     case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
3563     case bitc::FUNC_CODE_INST_GEP_OLD:
3564     case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
3565       unsigned OpNum = 0;
3566
3567       Type *Ty;
3568       bool InBounds;
3569
3570       if (BitCode == bitc::FUNC_CODE_INST_GEP) {
3571         InBounds = Record[OpNum++];
3572         Ty = getTypeByID(Record[OpNum++]);
3573       } else {
3574         InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
3575         Ty = nullptr;
3576       }
3577
3578       Value *BasePtr;
3579       if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
3580         return error("Invalid record");
3581
3582       if (!Ty)
3583         Ty = cast<PointerType>(BasePtr->getType()->getScalarType())
3584                  ->getElementType();
3585       else if (Ty !=
3586                cast<PointerType>(BasePtr->getType()->getScalarType())
3587                    ->getElementType())
3588         return error(
3589             "Explicit gep type does not match pointee type of pointer operand");
3590
3591       SmallVector<Value*, 16> GEPIdx;
3592       while (OpNum != Record.size()) {
3593         Value *Op;
3594         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3595           return error("Invalid record");
3596         GEPIdx.push_back(Op);
3597       }
3598
3599       I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
3600
3601       InstructionList.push_back(I);
3602       if (InBounds)
3603         cast<GetElementPtrInst>(I)->setIsInBounds(true);
3604       break;
3605     }
3606
3607     case bitc::FUNC_CODE_INST_EXTRACTVAL: {
3608                                        // EXTRACTVAL: [opty, opval, n x indices]
3609       unsigned OpNum = 0;
3610       Value *Agg;
3611       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3612         return error("Invalid record");
3613
3614       unsigned RecSize = Record.size();
3615       if (OpNum == RecSize)
3616         return error("EXTRACTVAL: Invalid instruction with 0 indices");
3617
3618       SmallVector<unsigned, 4> EXTRACTVALIdx;
3619       Type *CurTy = Agg->getType();
3620       for (; OpNum != RecSize; ++OpNum) {
3621         bool IsArray = CurTy->isArrayTy();
3622         bool IsStruct = CurTy->isStructTy();
3623         uint64_t Index = Record[OpNum];
3624
3625         if (!IsStruct && !IsArray)
3626           return error("EXTRACTVAL: Invalid type");
3627         if ((unsigned)Index != Index)
3628           return error("Invalid value");
3629         if (IsStruct && Index >= CurTy->subtypes().size())
3630           return error("EXTRACTVAL: Invalid struct index");
3631         if (IsArray && Index >= CurTy->getArrayNumElements())
3632           return error("EXTRACTVAL: Invalid array index");
3633         EXTRACTVALIdx.push_back((unsigned)Index);
3634
3635         if (IsStruct)
3636           CurTy = CurTy->subtypes()[Index];
3637         else
3638           CurTy = CurTy->subtypes()[0];
3639       }
3640
3641       I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
3642       InstructionList.push_back(I);
3643       break;
3644     }
3645
3646     case bitc::FUNC_CODE_INST_INSERTVAL: {
3647                            // INSERTVAL: [opty, opval, opty, opval, n x indices]
3648       unsigned OpNum = 0;
3649       Value *Agg;
3650       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3651         return error("Invalid record");
3652       Value *Val;
3653       if (getValueTypePair(Record, OpNum, NextValueNo, Val))
3654         return error("Invalid record");
3655
3656       unsigned RecSize = Record.size();
3657       if (OpNum == RecSize)
3658         return error("INSERTVAL: Invalid instruction with 0 indices");
3659
3660       SmallVector<unsigned, 4> INSERTVALIdx;
3661       Type *CurTy = Agg->getType();
3662       for (; OpNum != RecSize; ++OpNum) {
3663         bool IsArray = CurTy->isArrayTy();
3664         bool IsStruct = CurTy->isStructTy();
3665         uint64_t Index = Record[OpNum];
3666
3667         if (!IsStruct && !IsArray)
3668           return error("INSERTVAL: Invalid type");
3669         if ((unsigned)Index != Index)
3670           return error("Invalid value");
3671         if (IsStruct && Index >= CurTy->subtypes().size())
3672           return error("INSERTVAL: Invalid struct index");
3673         if (IsArray && Index >= CurTy->getArrayNumElements())
3674           return error("INSERTVAL: Invalid array index");
3675
3676         INSERTVALIdx.push_back((unsigned)Index);
3677         if (IsStruct)
3678           CurTy = CurTy->subtypes()[Index];
3679         else
3680           CurTy = CurTy->subtypes()[0];
3681       }
3682
3683       if (CurTy != Val->getType())
3684         return error("Inserted value type doesn't match aggregate type");
3685
3686       I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
3687       InstructionList.push_back(I);
3688       break;
3689     }
3690
3691     case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
3692       // obsolete form of select
3693       // handles select i1 ... in old bitcode
3694       unsigned OpNum = 0;
3695       Value *TrueVal, *FalseVal, *Cond;
3696       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3697           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3698           popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
3699         return error("Invalid record");
3700
3701       I = SelectInst::Create(Cond, TrueVal, FalseVal);
3702       InstructionList.push_back(I);
3703       break;
3704     }
3705
3706     case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
3707       // new form of select
3708       // handles select i1 or select [N x i1]
3709       unsigned OpNum = 0;
3710       Value *TrueVal, *FalseVal, *Cond;
3711       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3712           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3713           getValueTypePair(Record, OpNum, NextValueNo, Cond))
3714         return error("Invalid record");
3715
3716       // select condition can be either i1 or [N x i1]
3717       if (VectorType* vector_type =
3718           dyn_cast<VectorType>(Cond->getType())) {
3719         // expect <n x i1>
3720         if (vector_type->getElementType() != Type::getInt1Ty(Context))
3721           return error("Invalid type for value");
3722       } else {
3723         // expect i1
3724         if (Cond->getType() != Type::getInt1Ty(Context))
3725           return error("Invalid type for value");
3726       }
3727
3728       I = SelectInst::Create(Cond, TrueVal, FalseVal);
3729       InstructionList.push_back(I);
3730       break;
3731     }
3732
3733     case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
3734       unsigned OpNum = 0;
3735       Value *Vec, *Idx;
3736       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
3737           getValueTypePair(Record, OpNum, NextValueNo, Idx))
3738         return error("Invalid record");
3739       if (!Vec->getType()->isVectorTy())
3740         return error("Invalid type for value");
3741       I = ExtractElementInst::Create(Vec, Idx);
3742       InstructionList.push_back(I);
3743       break;
3744     }
3745
3746     case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
3747       unsigned OpNum = 0;
3748       Value *Vec, *Elt, *Idx;
3749       if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
3750         return error("Invalid record");
3751       if (!Vec->getType()->isVectorTy())
3752         return error("Invalid type for value");
3753       if (popValue(Record, OpNum, NextValueNo,
3754                    cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
3755           getValueTypePair(Record, OpNum, NextValueNo, Idx))
3756         return error("Invalid record");
3757       I = InsertElementInst::Create(Vec, Elt, Idx);
3758       InstructionList.push_back(I);
3759       break;
3760     }
3761
3762     case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
3763       unsigned OpNum = 0;
3764       Value *Vec1, *Vec2, *Mask;
3765       if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
3766           popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
3767         return error("Invalid record");
3768
3769       if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
3770         return error("Invalid record");
3771       if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
3772         return error("Invalid type for value");
3773       I = new ShuffleVectorInst(Vec1, Vec2, Mask);
3774       InstructionList.push_back(I);
3775       break;
3776     }
3777
3778     case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
3779       // Old form of ICmp/FCmp returning bool
3780       // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
3781       // both legal on vectors but had different behaviour.
3782     case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
3783       // FCmp/ICmp returning bool or vector of bool
3784
3785       unsigned OpNum = 0;
3786       Value *LHS, *RHS;
3787       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3788           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
3789         return error("Invalid record");
3790
3791       unsigned PredVal = Record[OpNum];
3792       bool IsFP = LHS->getType()->isFPOrFPVectorTy();
3793       FastMathFlags FMF;
3794       if (IsFP && Record.size() > OpNum+1)
3795         FMF = getDecodedFastMathFlags(Record[++OpNum]);
3796
3797       if (OpNum+1 != Record.size())
3798         return error("Invalid record");
3799
3800       if (LHS->getType()->isFPOrFPVectorTy())
3801         I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
3802       else
3803         I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
3804
3805       if (FMF.any())
3806         I->setFastMathFlags(FMF);
3807       InstructionList.push_back(I);
3808       break;
3809     }
3810
3811     case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
3812       {
3813         unsigned Size = Record.size();
3814         if (Size == 0) {
3815           I = ReturnInst::Create(Context);
3816           InstructionList.push_back(I);
3817           break;
3818         }
3819
3820         unsigned OpNum = 0;
3821         Value *Op = nullptr;
3822         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3823           return error("Invalid record");
3824         if (OpNum != Record.size())
3825           return error("Invalid record");
3826
3827         I = ReturnInst::Create(Context, Op);
3828         InstructionList.push_back(I);
3829         break;
3830       }
3831     case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
3832       if (Record.size() != 1 && Record.size() != 3)
3833         return error("Invalid record");
3834       BasicBlock *TrueDest = getBasicBlock(Record[0]);
3835       if (!TrueDest)
3836         return error("Invalid record");
3837
3838       if (Record.size() == 1) {
3839         I = BranchInst::Create(TrueDest);
3840         InstructionList.push_back(I);
3841       }
3842       else {
3843         BasicBlock *FalseDest = getBasicBlock(Record[1]);
3844         Value *Cond = getValue(Record, 2, NextValueNo,
3845                                Type::getInt1Ty(Context));
3846         if (!FalseDest || !Cond)
3847           return error("Invalid record");
3848         I = BranchInst::Create(TrueDest, FalseDest, Cond);
3849         InstructionList.push_back(I);
3850       }
3851       break;
3852     }
3853     case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
3854       if (Record.size() != 1 && Record.size() != 2)
3855         return error("Invalid record");
3856       unsigned Idx = 0;
3857       Value *CleanupPad =
3858           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
3859       if (!CleanupPad)
3860         return error("Invalid record");
3861       BasicBlock *UnwindDest = nullptr;
3862       if (Record.size() == 2) {
3863         UnwindDest = getBasicBlock(Record[Idx++]);
3864         if (!UnwindDest)
3865           return error("Invalid record");
3866       }
3867
3868       I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
3869       InstructionList.push_back(I);
3870       break;
3871     }
3872     case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
3873       if (Record.size() != 2)
3874         return error("Invalid record");
3875       unsigned Idx = 0;
3876       Value *CatchPad =
3877           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
3878       if (!CatchPad)
3879         return error("Invalid record");
3880       BasicBlock *BB = getBasicBlock(Record[Idx++]);
3881       if (!BB)
3882         return error("Invalid record");
3883
3884       I = CatchReturnInst::Create(CatchPad, BB);
3885       InstructionList.push_back(I);
3886       break;
3887     }
3888     case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
3889       // We must have, at minimum, the outer scope and the number of arguments.
3890       if (Record.size() < 2)
3891         return error("Invalid record");
3892
3893       unsigned Idx = 0;
3894
3895       Value *ParentPad =
3896           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
3897
3898       unsigned NumHandlers = Record[Idx++];
3899
3900       SmallVector<BasicBlock *, 2> Handlers;
3901       for (unsigned Op = 0; Op != NumHandlers; ++Op) {
3902         BasicBlock *BB = getBasicBlock(Record[Idx++]);
3903         if (!BB)
3904           return error("Invalid record");
3905         Handlers.push_back(BB);
3906       }
3907
3908       BasicBlock *UnwindDest = nullptr;
3909       if (Idx + 1 == Record.size()) {
3910         UnwindDest = getBasicBlock(Record[Idx++]);
3911         if (!UnwindDest)
3912           return error("Invalid record");
3913       }
3914
3915       if (Record.size() != Idx)
3916         return error("Invalid record");
3917
3918       auto *CatchSwitch =
3919           CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
3920       for (BasicBlock *Handler : Handlers)
3921         CatchSwitch->addHandler(Handler);
3922       I = CatchSwitch;
3923       InstructionList.push_back(I);
3924       break;
3925     }
3926     case bitc::FUNC_CODE_INST_CATCHPAD:
3927     case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
3928       // We must have, at minimum, the outer scope and the number of arguments.
3929       if (Record.size() < 2)
3930         return error("Invalid record");
3931
3932       unsigned Idx = 0;
3933
3934       Value *ParentPad =
3935           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
3936
3937       unsigned NumArgOperands = Record[Idx++];
3938
3939       SmallVector<Value *, 2> Args;
3940       for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
3941         Value *Val;
3942         if (getValueTypePair(Record, Idx, NextValueNo, Val))
3943           return error("Invalid record");
3944         Args.push_back(Val);
3945       }
3946
3947       if (Record.size() != Idx)
3948         return error("Invalid record");
3949
3950       if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
3951         I = CleanupPadInst::Create(ParentPad, Args);
3952       else
3953         I = CatchPadInst::Create(ParentPad, Args);
3954       InstructionList.push_back(I);
3955       break;
3956     }
3957     case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
3958       // Check magic
3959       if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
3960         // "New" SwitchInst format with case ranges. The changes to write this
3961         // format were reverted but we still recognize bitcode that uses it.
3962         // Hopefully someday we will have support for case ranges and can use
3963         // this format again.
3964
3965         Type *OpTy = getTypeByID(Record[1]);
3966         unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
3967
3968         Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
3969         BasicBlock *Default = getBasicBlock(Record[3]);
3970         if (!OpTy || !Cond || !Default)
3971           return error("Invalid record");
3972
3973         unsigned NumCases = Record[4];
3974
3975         SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3976         InstructionList.push_back(SI);
3977
3978         unsigned CurIdx = 5;
3979         for (unsigned i = 0; i != NumCases; ++i) {
3980           SmallVector<ConstantInt*, 1> CaseVals;
3981           unsigned NumItems = Record[CurIdx++];
3982           for (unsigned ci = 0; ci != NumItems; ++ci) {
3983             bool isSingleNumber = Record[CurIdx++];
3984
3985             APInt Low;
3986             unsigned ActiveWords = 1;
3987             if (ValueBitWidth > 64)
3988               ActiveWords = Record[CurIdx++];
3989             Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3990                                 ValueBitWidth);
3991             CurIdx += ActiveWords;
3992
3993             if (!isSingleNumber) {
3994               ActiveWords = 1;
3995               if (ValueBitWidth > 64)
3996                 ActiveWords = Record[CurIdx++];
3997               APInt High = readWideAPInt(
3998                   makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
3999               CurIdx += ActiveWords;
4000
4001               // FIXME: It is not clear whether values in the range should be
4002               // compared as signed or unsigned values. The partially
4003               // implemented changes that used this format in the past used
4004               // unsigned comparisons.
4005               for ( ; Low.ule(High); ++Low)
4006                 CaseVals.push_back(ConstantInt::get(Context, Low));
4007             } else
4008               CaseVals.push_back(ConstantInt::get(Context, Low));
4009           }
4010           BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
4011           for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
4012                  cve = CaseVals.end(); cvi != cve; ++cvi)
4013             SI->addCase(*cvi, DestBB);
4014         }
4015         I = SI;
4016         break;
4017       }
4018
4019       // Old SwitchInst format without case ranges.
4020
4021       if (Record.size() < 3 || (Record.size() & 1) == 0)
4022         return error("Invalid record");
4023       Type *OpTy = getTypeByID(Record[0]);
4024       Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
4025       BasicBlock *Default = getBasicBlock(Record[2]);
4026       if (!OpTy || !Cond || !Default)
4027         return error("Invalid record");
4028       unsigned NumCases = (Record.size()-3)/2;
4029       SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4030       InstructionList.push_back(SI);
4031       for (unsigned i = 0, e = NumCases; i != e; ++i) {
4032         ConstantInt *CaseVal =
4033           dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4034         BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
4035         if (!CaseVal || !DestBB) {
4036           delete SI;
4037           return error("Invalid record");
4038         }
4039         SI->addCase(CaseVal, DestBB);
4040       }
4041       I = SI;
4042       break;
4043     }
4044     case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
4045       if (Record.size() < 2)
4046         return error("Invalid record");
4047       Type *OpTy = getTypeByID(Record[0]);
4048       Value *Address = getValue(Record, 1, NextValueNo, OpTy);
4049       if (!OpTy || !Address)
4050         return error("Invalid record");
4051       unsigned NumDests = Record.size()-2;
4052       IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
4053       InstructionList.push_back(IBI);
4054       for (unsigned i = 0, e = NumDests; i != e; ++i) {
4055         if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4056           IBI->addDestination(DestBB);
4057         } else {
4058           delete IBI;
4059           return error("Invalid record");
4060         }
4061       }
4062       I = IBI;
4063       break;
4064     }
4065
4066     case bitc::FUNC_CODE_INST_INVOKE: {
4067       // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
4068       if (Record.size() < 4)
4069         return error("Invalid record");
4070       unsigned OpNum = 0;
4071       AttributeList PAL = getAttributes(Record[OpNum++]);
4072       unsigned CCInfo = Record[OpNum++];
4073       BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4074       BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
4075
4076       FunctionType *FTy = nullptr;
4077       if (CCInfo >> 13 & 1 &&
4078           !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4079         return error("Explicit invoke type is not a function type");
4080
4081       Value *Callee;
4082       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4083         return error("Invalid record");
4084
4085       PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
4086       if (!CalleeTy)
4087         return error("Callee is not a pointer");
4088       if (!FTy) {
4089         FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
4090         if (!FTy)
4091           return error("Callee is not of pointer to function type");
4092       } else if (CalleeTy->getElementType() != FTy)
4093         return error("Explicit invoke type does not match pointee type of "
4094                      "callee operand");
4095       if (Record.size() < FTy->getNumParams() + OpNum)
4096         return error("Insufficient operands to call");
4097
4098       SmallVector<Value*, 16> Ops;
4099       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4100         Ops.push_back(getValue(Record, OpNum, NextValueNo,
4101                                FTy->getParamType(i)));
4102         if (!Ops.back())
4103           return error("Invalid record");
4104       }
4105
4106       if (!FTy->isVarArg()) {
4107         if (Record.size() != OpNum)
4108           return error("Invalid record");
4109       } else {
4110         // Read type/value pairs for varargs params.
4111         while (OpNum != Record.size()) {
4112           Value *Op;
4113           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4114             return error("Invalid record");
4115           Ops.push_back(Op);
4116         }
4117       }
4118
4119       I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
4120       OperandBundles.clear();
4121       InstructionList.push_back(I);
4122       cast<InvokeInst>(I)->setCallingConv(
4123           static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
4124       cast<InvokeInst>(I)->setAttributes(PAL);
4125       break;
4126     }
4127     case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4128       unsigned Idx = 0;
4129       Value *Val = nullptr;
4130       if (getValueTypePair(Record, Idx, NextValueNo, Val))
4131         return error("Invalid record");
4132       I = ResumeInst::Create(Val);
4133       InstructionList.push_back(I);
4134       break;
4135     }
4136     case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
4137       I = new UnreachableInst(Context);
4138       InstructionList.push_back(I);
4139       break;
4140     case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
4141       if (Record.size() < 1 || ((Record.size()-1)&1))
4142         return error("Invalid record");
4143       Type *Ty = getTypeByID(Record[0]);
4144       if (!Ty)
4145         return error("Invalid record");
4146
4147       PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
4148       InstructionList.push_back(PN);
4149
4150       for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
4151         Value *V;
4152         // With the new function encoding, it is possible that operands have
4153         // negative IDs (for forward references).  Use a signed VBR
4154         // representation to keep the encoding small.
4155         if (UseRelativeIDs)
4156           V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4157         else
4158           V = getValue(Record, 1+i, NextValueNo, Ty);
4159         BasicBlock *BB = getBasicBlock(Record[2+i]);
4160         if (!V || !BB)
4161           return error("Invalid record");
4162         PN->addIncoming(V, BB);
4163       }
4164       I = PN;
4165       break;
4166     }
4167
4168     case bitc::FUNC_CODE_INST_LANDINGPAD:
4169     case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
4170       // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4171       unsigned Idx = 0;
4172       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4173         if (Record.size() < 3)
4174           return error("Invalid record");
4175       } else {
4176         assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
4177         if (Record.size() < 4)
4178           return error("Invalid record");
4179       }
4180       Type *Ty = getTypeByID(Record[Idx++]);
4181       if (!Ty)
4182         return error("Invalid record");
4183       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4184         Value *PersFn = nullptr;
4185         if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4186           return error("Invalid record");
4187
4188         if (!F->hasPersonalityFn())
4189           F->setPersonalityFn(cast<Constant>(PersFn));
4190         else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4191           return error("Personality function mismatch");
4192       }
4193
4194       bool IsCleanup = !!Record[Idx++];
4195       unsigned NumClauses = Record[Idx++];
4196       LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
4197       LP->setCleanup(IsCleanup);
4198       for (unsigned J = 0; J != NumClauses; ++J) {
4199         LandingPadInst::ClauseType CT =
4200           LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4201         Value *Val;
4202
4203         if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4204           delete LP;
4205           return error("Invalid record");
4206         }
4207
4208         assert((CT != LandingPadInst::Catch ||
4209                 !isa<ArrayType>(Val->getType())) &&
4210                "Catch clause has a invalid type!");
4211         assert((CT != LandingPadInst::Filter ||
4212                 isa<ArrayType>(Val->getType())) &&
4213                "Filter clause has invalid type!");
4214         LP->addClause(cast<Constant>(Val));
4215       }
4216
4217       I = LP;
4218       InstructionList.push_back(I);
4219       break;
4220     }
4221
4222     case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4223       if (Record.size() != 4)
4224         return error("Invalid record");
4225       uint64_t AlignRecord = Record[3];
4226       const uint64_t InAllocaMask = uint64_t(1) << 5;
4227       const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
4228       const uint64_t SwiftErrorMask = uint64_t(1) << 7;
4229       const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask |
4230                                 SwiftErrorMask;
4231       bool InAlloca = AlignRecord & InAllocaMask;
4232       bool SwiftError = AlignRecord & SwiftErrorMask;
4233       Type *Ty = getTypeByID(Record[0]);
4234       if ((AlignRecord & ExplicitTypeMask) == 0) {
4235         auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4236         if (!PTy)
4237           return error("Old-style alloca with a non-pointer type");
4238         Ty = PTy->getElementType();
4239       }
4240       Type *OpTy = getTypeByID(Record[1]);
4241       Value *Size = getFnValueByID(Record[2], OpTy);
4242       unsigned Align;
4243       if (Error Err = parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4244         return Err;
4245       }
4246       if (!Ty || !Size)
4247         return error("Invalid record");
4248
4249       // FIXME: Make this an optional field.
4250       const DataLayout &DL = TheModule->getDataLayout();
4251       unsigned AS = DL.getAllocaAddrSpace();
4252
4253       AllocaInst *AI = new AllocaInst(Ty, AS, Size, Align);
4254       AI->setUsedWithInAlloca(InAlloca);
4255       AI->setSwiftError(SwiftError);
4256       I = AI;
4257       InstructionList.push_back(I);
4258       break;
4259     }
4260     case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
4261       unsigned OpNum = 0;
4262       Value *Op;
4263       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4264           (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
4265         return error("Invalid record");
4266
4267       Type *Ty = nullptr;
4268       if (OpNum + 3 == Record.size())
4269         Ty = getTypeByID(Record[OpNum++]);
4270       if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
4271         return Err;
4272       if (!Ty)
4273         Ty = cast<PointerType>(Op->getType())->getElementType();
4274
4275       unsigned Align;
4276       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4277         return Err;
4278       I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
4279
4280       InstructionList.push_back(I);
4281       break;
4282     }
4283     case bitc::FUNC_CODE_INST_LOADATOMIC: {
4284        // LOADATOMIC: [opty, op, align, vol, ordering, ssid]
4285       unsigned OpNum = 0;
4286       Value *Op;
4287       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4288           (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
4289         return error("Invalid record");
4290
4291       Type *Ty = nullptr;
4292       if (OpNum + 5 == Record.size())
4293         Ty = getTypeByID(Record[OpNum++]);
4294       if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
4295         return Err;
4296       if (!Ty)
4297         Ty = cast<PointerType>(Op->getType())->getElementType();
4298
4299       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4300       if (Ordering == AtomicOrdering::NotAtomic ||
4301           Ordering == AtomicOrdering::Release ||
4302           Ordering == AtomicOrdering::AcquireRelease)
4303         return error("Invalid record");
4304       if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
4305         return error("Invalid record");
4306       SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
4307
4308       unsigned Align;
4309       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4310         return Err;
4311       I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SSID);
4312
4313       InstructionList.push_back(I);
4314       break;
4315     }
4316     case bitc::FUNC_CODE_INST_STORE:
4317     case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
4318       unsigned OpNum = 0;
4319       Value *Val, *Ptr;
4320       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4321           (BitCode == bitc::FUNC_CODE_INST_STORE
4322                ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4323                : popValue(Record, OpNum, NextValueNo,
4324                           cast<PointerType>(Ptr->getType())->getElementType(),
4325                           Val)) ||
4326           OpNum + 2 != Record.size())
4327         return error("Invalid record");
4328
4329       if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
4330         return Err;
4331       unsigned Align;
4332       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4333         return Err;
4334       I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4335       InstructionList.push_back(I);
4336       break;
4337     }
4338     case bitc::FUNC_CODE_INST_STOREATOMIC:
4339     case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
4340       // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid]
4341       unsigned OpNum = 0;
4342       Value *Val, *Ptr;
4343       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4344           !isa<PointerType>(Ptr->getType()) ||
4345           (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4346                ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4347                : popValue(Record, OpNum, NextValueNo,
4348                           cast<PointerType>(Ptr->getType())->getElementType(),
4349                           Val)) ||
4350           OpNum + 4 != Record.size())
4351         return error("Invalid record");
4352
4353       if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
4354         return Err;
4355       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4356       if (Ordering == AtomicOrdering::NotAtomic ||
4357           Ordering == AtomicOrdering::Acquire ||
4358           Ordering == AtomicOrdering::AcquireRelease)
4359         return error("Invalid record");
4360       SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
4361       if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
4362         return error("Invalid record");
4363
4364       unsigned Align;
4365       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4366         return Err;
4367       I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SSID);
4368       InstructionList.push_back(I);
4369       break;
4370     }
4371     case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
4372     case bitc::FUNC_CODE_INST_CMPXCHG: {
4373       // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, ssid,
4374       //          failureordering?, isweak?]
4375       unsigned OpNum = 0;
4376       Value *Ptr, *Cmp, *New;
4377       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4378           (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4379                ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4380                : popValue(Record, OpNum, NextValueNo,
4381                           cast<PointerType>(Ptr->getType())->getElementType(),
4382                           Cmp)) ||
4383           popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4384           Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
4385         return error("Invalid record");
4386       AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
4387       if (SuccessOrdering == AtomicOrdering::NotAtomic ||
4388           SuccessOrdering == AtomicOrdering::Unordered)
4389         return error("Invalid record");
4390       SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
4391
4392       if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
4393         return Err;
4394       AtomicOrdering FailureOrdering;
4395       if (Record.size() < 7)
4396         FailureOrdering =
4397             AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4398       else
4399         FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
4400
4401       I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4402                                 SSID);
4403       cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
4404
4405       if (Record.size() < 8) {
4406         // Before weak cmpxchgs existed, the instruction simply returned the
4407         // value loaded from memory, so bitcode files from that era will be
4408         // expecting the first component of a modern cmpxchg.
4409         CurBB->getInstList().push_back(I);
4410         I = ExtractValueInst::Create(I, 0);
4411       } else {
4412         cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4413       }
4414
4415       InstructionList.push_back(I);
4416       break;
4417     }
4418     case bitc::FUNC_CODE_INST_ATOMICRMW: {
4419       // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, ssid]
4420       unsigned OpNum = 0;
4421       Value *Ptr, *Val;
4422       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4423           !isa<PointerType>(Ptr->getType()) ||
4424           popValue(Record, OpNum, NextValueNo,
4425                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4426           OpNum+4 != Record.size())
4427         return error("Invalid record");
4428       AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
4429       if (Operation < AtomicRMWInst::FIRST_BINOP ||
4430           Operation > AtomicRMWInst::LAST_BINOP)
4431         return error("Invalid record");
4432       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4433       if (Ordering == AtomicOrdering::NotAtomic ||
4434           Ordering == AtomicOrdering::Unordered)
4435         return error("Invalid record");
4436       SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
4437       I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SSID);
4438       cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
4439       InstructionList.push_back(I);
4440       break;
4441     }
4442     case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid]
4443       if (2 != Record.size())
4444         return error("Invalid record");
4445       AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
4446       if (Ordering == AtomicOrdering::NotAtomic ||
4447           Ordering == AtomicOrdering::Unordered ||
4448           Ordering == AtomicOrdering::Monotonic)
4449         return error("Invalid record");
4450       SyncScope::ID SSID = getDecodedSyncScopeID(Record[1]);
4451       I = new FenceInst(Context, Ordering, SSID);
4452       InstructionList.push_back(I);
4453       break;
4454     }
4455     case bitc::FUNC_CODE_INST_CALL: {
4456       // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
4457       if (Record.size() < 3)
4458         return error("Invalid record");
4459
4460       unsigned OpNum = 0;
4461       AttributeList PAL = getAttributes(Record[OpNum++]);
4462       unsigned CCInfo = Record[OpNum++];
4463
4464       FastMathFlags FMF;
4465       if ((CCInfo >> bitc::CALL_FMF) & 1) {
4466         FMF = getDecodedFastMathFlags(Record[OpNum++]);
4467         if (!FMF.any())
4468           return error("Fast math flags indicator set for call with no FMF");
4469       }
4470
4471       FunctionType *FTy = nullptr;
4472       if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 &&
4473           !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4474         return error("Explicit call type is not a function type");
4475
4476       Value *Callee;
4477       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4478         return error("Invalid record");
4479
4480       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
4481       if (!OpTy)
4482         return error("Callee is not a pointer type");
4483       if (!FTy) {
4484         FTy = dyn_cast<FunctionType>(OpTy->getElementType());
4485         if (!FTy)
4486           return error("Callee is not of pointer to function type");
4487       } else if (OpTy->getElementType() != FTy)
4488         return error("Explicit call type does not match pointee type of "
4489                      "callee operand");
4490       if (Record.size() < FTy->getNumParams() + OpNum)
4491         return error("Insufficient operands to call");
4492
4493       SmallVector<Value*, 16> Args;
4494       // Read the fixed params.
4495       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4496         if (FTy->getParamType(i)->isLabelTy())
4497           Args.push_back(getBasicBlock(Record[OpNum]));
4498         else
4499           Args.push_back(getValue(Record, OpNum, NextValueNo,
4500                                   FTy->getParamType(i)));
4501         if (!Args.back())
4502           return error("Invalid record");
4503       }
4504
4505       // Read type/value pairs for varargs params.
4506       if (!FTy->isVarArg()) {
4507         if (OpNum != Record.size())
4508           return error("Invalid record");
4509       } else {
4510         while (OpNum != Record.size()) {
4511           Value *Op;
4512           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4513             return error("Invalid record");
4514           Args.push_back(Op);
4515         }
4516       }
4517
4518       I = CallInst::Create(FTy, Callee, Args, OperandBundles);
4519       OperandBundles.clear();
4520       InstructionList.push_back(I);
4521       cast<CallInst>(I)->setCallingConv(
4522           static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
4523       CallInst::TailCallKind TCK = CallInst::TCK_None;
4524       if (CCInfo & 1 << bitc::CALL_TAIL)
4525         TCK = CallInst::TCK_Tail;
4526       if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
4527         TCK = CallInst::TCK_MustTail;
4528       if (CCInfo & (1 << bitc::CALL_NOTAIL))
4529         TCK = CallInst::TCK_NoTail;
4530       cast<CallInst>(I)->setTailCallKind(TCK);
4531       cast<CallInst>(I)->setAttributes(PAL);
4532       if (FMF.any()) {
4533         if (!isa<FPMathOperator>(I))
4534           return error("Fast-math-flags specified for call without "
4535                        "floating-point scalar or vector return type");
4536         I->setFastMathFlags(FMF);
4537       }
4538       break;
4539     }
4540     case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
4541       if (Record.size() < 3)
4542         return error("Invalid record");
4543       Type *OpTy = getTypeByID(Record[0]);
4544       Value *Op = getValue(Record, 1, NextValueNo, OpTy);
4545       Type *ResTy = getTypeByID(Record[2]);
4546       if (!OpTy || !Op || !ResTy)
4547         return error("Invalid record");
4548       I = new VAArgInst(Op, ResTy);
4549       InstructionList.push_back(I);
4550       break;
4551     }
4552
4553     case bitc::FUNC_CODE_OPERAND_BUNDLE: {
4554       // A call or an invoke can be optionally prefixed with some variable
4555       // number of operand bundle blocks.  These blocks are read into
4556       // OperandBundles and consumed at the next call or invoke instruction.
4557
4558       if (Record.size() < 1 || Record[0] >= BundleTags.size())
4559         return error("Invalid record");
4560
4561       std::vector<Value *> Inputs;
4562
4563       unsigned OpNum = 1;
4564       while (OpNum != Record.size()) {
4565         Value *Op;
4566         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4567           return error("Invalid record");
4568         Inputs.push_back(Op);
4569       }
4570
4571       OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
4572       continue;
4573     }
4574     }
4575
4576     // Add instruction to end of current BB.  If there is no current BB, reject
4577     // this file.
4578     if (!CurBB) {
4579       I->deleteValue();
4580       return error("Invalid instruction with no BB");
4581     }
4582     if (!OperandBundles.empty()) {
4583       I->deleteValue();
4584       return error("Operand bundles found with no consumer");
4585     }
4586     CurBB->getInstList().push_back(I);
4587
4588     // If this was a terminator instruction, move to the next block.
4589     if (isa<TerminatorInst>(I)) {
4590       ++CurBBNo;
4591       CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
4592     }
4593
4594     // Non-void values get registered in the value table for future use.
4595     if (I && !I->getType()->isVoidTy())
4596       ValueList.assignValue(I, NextValueNo++);
4597   }
4598
4599 OutOfRecordLoop:
4600
4601   if (!OperandBundles.empty())
4602     return error("Operand bundles found with no consumer");
4603
4604   // Check the function list for unresolved values.
4605   if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
4606     if (!A->getParent()) {
4607       // We found at least one unresolved value.  Nuke them all to avoid leaks.
4608       for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
4609         if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
4610           A->replaceAllUsesWith(UndefValue::get(A->getType()));
4611           delete A;
4612         }
4613       }
4614       return error("Never resolved value found in function");
4615     }
4616   }
4617
4618   // Unexpected unresolved metadata about to be dropped.
4619   if (MDLoader->hasFwdRefs())
4620     return error("Invalid function metadata: outgoing forward refs");
4621
4622   // Trim the value list down to the size it was before we parsed this function.
4623   ValueList.shrinkTo(ModuleValueListSize);
4624   MDLoader->shrinkTo(ModuleMDLoaderSize);
4625   std::vector<BasicBlock*>().swap(FunctionBBs);
4626   return Error::success();
4627 }
4628
4629 /// Find the function body in the bitcode stream
4630 Error BitcodeReader::findFunctionInStream(
4631     Function *F,
4632     DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
4633   while (DeferredFunctionInfoIterator->second == 0) {
4634     // This is the fallback handling for the old format bitcode that
4635     // didn't contain the function index in the VST, or when we have
4636     // an anonymous function which would not have a VST entry.
4637     // Assert that we have one of those two cases.
4638     assert(VSTOffset == 0 || !F->hasName());
4639     // Parse the next body in the stream and set its position in the
4640     // DeferredFunctionInfo map.
4641     if (Error Err = rememberAndSkipFunctionBodies())
4642       return Err;
4643   }
4644   return Error::success();
4645 }
4646
4647 SyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) {
4648   if (Val == SyncScope::SingleThread || Val == SyncScope::System)
4649     return SyncScope::ID(Val);
4650   if (Val >= SSIDs.size())
4651     return SyncScope::System; // Map unknown synchronization scopes to system.
4652   return SSIDs[Val];
4653 }
4654
4655 //===----------------------------------------------------------------------===//
4656 // GVMaterializer implementation
4657 //===----------------------------------------------------------------------===//
4658
4659 Error BitcodeReader::materialize(GlobalValue *GV) {
4660   Function *F = dyn_cast<Function>(GV);
4661   // If it's not a function or is already material, ignore the request.
4662   if (!F || !F->isMaterializable())
4663     return Error::success();
4664
4665   DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
4666   assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
4667   // If its position is recorded as 0, its body is somewhere in the stream
4668   // but we haven't seen it yet.
4669   if (DFII->second == 0)
4670     if (Error Err = findFunctionInStream(F, DFII))
4671       return Err;
4672
4673   // Materialize metadata before parsing any function bodies.
4674   if (Error Err = materializeMetadata())
4675     return Err;
4676
4677   // Move the bit stream to the saved position of the deferred function body.
4678   Stream.JumpToBit(DFII->second);
4679
4680   if (Error Err = parseFunctionBody(F))
4681     return Err;
4682   F->setIsMaterializable(false);
4683
4684   if (StripDebugInfo)
4685     stripDebugInfo(*F);
4686
4687   // Upgrade any old intrinsic calls in the function.
4688   for (auto &I : UpgradedIntrinsics) {
4689     for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
4690          UI != UE;) {
4691       User *U = *UI;
4692       ++UI;
4693       if (CallInst *CI = dyn_cast<CallInst>(U))
4694         UpgradeIntrinsicCall(CI, I.second);
4695     }
4696   }
4697
4698   // Update calls to the remangled intrinsics
4699   for (auto &I : RemangledIntrinsics)
4700     for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
4701          UI != UE;)
4702       // Don't expect any other users than call sites
4703       CallSite(*UI++).setCalledFunction(I.second);
4704
4705   // Finish fn->subprogram upgrade for materialized functions.
4706   if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F))
4707     F->setSubprogram(SP);
4708
4709   // Check if the TBAA Metadata are valid, otherwise we will need to strip them.
4710   if (!MDLoader->isStrippingTBAA()) {
4711     for (auto &I : instructions(F)) {
4712       MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa);
4713       if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA))
4714         continue;
4715       MDLoader->setStripTBAA(true);
4716       stripTBAA(F->getParent());
4717     }
4718   }
4719
4720   // Bring in any functions that this function forward-referenced via
4721   // blockaddresses.
4722   return materializeForwardReferencedFunctions();
4723 }
4724
4725 Error BitcodeReader::materializeModule() {
4726   if (Error Err = materializeMetadata())
4727     return Err;
4728
4729   // Promise to materialize all forward references.
4730   WillMaterializeAllForwardRefs = true;
4731
4732   // Iterate over the module, deserializing any functions that are still on
4733   // disk.
4734   for (Function &F : *TheModule) {
4735     if (Error Err = materialize(&F))
4736       return Err;
4737   }
4738   // At this point, if there are any function bodies, parse the rest of
4739   // the bits in the module past the last function block we have recorded
4740   // through either lazy scanning or the VST.
4741   if (LastFunctionBlockBit || NextUnreadBit)
4742     if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit
4743                                     ? LastFunctionBlockBit
4744                                     : NextUnreadBit))
4745       return Err;
4746
4747   // Check that all block address forward references got resolved (as we
4748   // promised above).
4749   if (!BasicBlockFwdRefs.empty())
4750     return error("Never resolved function from blockaddress");
4751
4752   // Upgrade any intrinsic calls that slipped through (should not happen!) and
4753   // delete the old functions to clean up. We can't do this unless the entire
4754   // module is materialized because there could always be another function body
4755   // with calls to the old function.
4756   for (auto &I : UpgradedIntrinsics) {
4757     for (auto *U : I.first->users()) {
4758       if (CallInst *CI = dyn_cast<CallInst>(U))
4759         UpgradeIntrinsicCall(CI, I.second);
4760     }
4761     if (!I.first->use_empty())
4762       I.first->replaceAllUsesWith(I.second);
4763     I.first->eraseFromParent();
4764   }
4765   UpgradedIntrinsics.clear();
4766   // Do the same for remangled intrinsics
4767   for (auto &I : RemangledIntrinsics) {
4768     I.first->replaceAllUsesWith(I.second);
4769     I.first->eraseFromParent();
4770   }
4771   RemangledIntrinsics.clear();
4772
4773   UpgradeDebugInfo(*TheModule);
4774
4775   UpgradeModuleFlags(*TheModule);
4776   return Error::success();
4777 }
4778
4779 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
4780   return IdentifiedStructTypes;
4781 }
4782
4783 ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
4784     BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex,
4785     StringRef ModulePath, unsigned ModuleId)
4786     : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex),
4787       ModulePath(ModulePath), ModuleId(ModuleId) {}
4788
4789 ModuleSummaryIndex::ModuleInfo *
4790 ModuleSummaryIndexBitcodeReader::addThisModule() {
4791   return TheIndex.addModule(ModulePath, ModuleId);
4792 }
4793
4794 std::pair<ValueInfo, GlobalValue::GUID>
4795 ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) {
4796   auto VGI = ValueIdToValueInfoMap[ValueId];
4797   assert(VGI.first);
4798   return VGI;
4799 }
4800
4801 void ModuleSummaryIndexBitcodeReader::setValueGUID(
4802     uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage,
4803     StringRef SourceFileName) {
4804   std::string GlobalId =
4805       GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
4806   auto ValueGUID = GlobalValue::getGUID(GlobalId);
4807   auto OriginalNameID = ValueGUID;
4808   if (GlobalValue::isLocalLinkage(Linkage))
4809     OriginalNameID = GlobalValue::getGUID(ValueName);
4810   if (PrintSummaryGUIDs)
4811     dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
4812            << ValueName << "\n";
4813   ValueIdToValueInfoMap[ValueID] =
4814       std::make_pair(TheIndex.getOrInsertValueInfo(ValueGUID), OriginalNameID);
4815 }
4816
4817 // Specialized value symbol table parser used when reading module index
4818 // blocks where we don't actually create global values. The parsed information
4819 // is saved in the bitcode reader for use when later parsing summaries.
4820 Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
4821     uint64_t Offset,
4822     DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
4823   // With a strtab the VST is not required to parse the summary.
4824   if (UseStrtab)
4825     return Error::success();
4826
4827   assert(Offset > 0 && "Expected non-zero VST offset");
4828   uint64_t CurrentBit = jumpToValueSymbolTable(Offset, Stream);
4829
4830   if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
4831     return error("Invalid record");
4832
4833   SmallVector<uint64_t, 64> Record;
4834
4835   // Read all the records for this value table.
4836   SmallString<128> ValueName;
4837
4838   while (true) {
4839     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4840
4841     switch (Entry.Kind) {
4842     case BitstreamEntry::SubBlock: // Handled for us already.
4843     case BitstreamEntry::Error:
4844       return error("Malformed block");
4845     case BitstreamEntry::EndBlock:
4846       // Done parsing VST, jump back to wherever we came from.
4847       Stream.JumpToBit(CurrentBit);
4848       return Error::success();
4849     case BitstreamEntry::Record:
4850       // The interesting case.
4851       break;
4852     }
4853
4854     // Read a record.
4855     Record.clear();
4856     switch (Stream.readRecord(Entry.ID, Record)) {
4857     default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
4858       break;
4859     case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
4860       if (convertToString(Record, 1, ValueName))
4861         return error("Invalid record");
4862       unsigned ValueID = Record[0];
4863       assert(!SourceFileName.empty());
4864       auto VLI = ValueIdToLinkageMap.find(ValueID);
4865       assert(VLI != ValueIdToLinkageMap.end() &&
4866              "No linkage found for VST entry?");
4867       auto Linkage = VLI->second;
4868       setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
4869       ValueName.clear();
4870       break;
4871     }
4872     case bitc::VST_CODE_FNENTRY: {
4873       // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
4874       if (convertToString(Record, 2, ValueName))
4875         return error("Invalid record");
4876       unsigned ValueID = Record[0];
4877       assert(!SourceFileName.empty());
4878       auto VLI = ValueIdToLinkageMap.find(ValueID);
4879       assert(VLI != ValueIdToLinkageMap.end() &&
4880              "No linkage found for VST entry?");
4881       auto Linkage = VLI->second;
4882       setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
4883       ValueName.clear();
4884       break;
4885     }
4886     case bitc::VST_CODE_COMBINED_ENTRY: {
4887       // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
4888       unsigned ValueID = Record[0];
4889       GlobalValue::GUID RefGUID = Record[1];
4890       // The "original name", which is the second value of the pair will be
4891       // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
4892       ValueIdToValueInfoMap[ValueID] =
4893           std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
4894       break;
4895     }
4896     }
4897   }
4898 }
4899
4900 // Parse just the blocks needed for building the index out of the module.
4901 // At the end of this routine the module Index is populated with a map
4902 // from global value id to GlobalValueSummary objects.
4903 Error ModuleSummaryIndexBitcodeReader::parseModule() {
4904   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
4905     return error("Invalid record");
4906
4907   SmallVector<uint64_t, 64> Record;
4908   DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
4909   unsigned ValueId = 0;
4910
4911   // Read the index for this module.
4912   while (true) {
4913     BitstreamEntry Entry = Stream.advance();
4914
4915     switch (Entry.Kind) {
4916     case BitstreamEntry::Error:
4917       return error("Malformed block");
4918     case BitstreamEntry::EndBlock:
4919       return Error::success();
4920
4921     case BitstreamEntry::SubBlock:
4922       switch (Entry.ID) {
4923       default: // Skip unknown content.
4924         if (Stream.SkipBlock())
4925           return error("Invalid record");
4926         break;
4927       case bitc::BLOCKINFO_BLOCK_ID:
4928         // Need to parse these to get abbrev ids (e.g. for VST)
4929         if (readBlockInfo())
4930           return error("Malformed block");
4931         break;
4932       case bitc::VALUE_SYMTAB_BLOCK_ID:
4933         // Should have been parsed earlier via VSTOffset, unless there
4934         // is no summary section.
4935         assert(((SeenValueSymbolTable && VSTOffset > 0) ||
4936                 !SeenGlobalValSummary) &&
4937                "Expected early VST parse via VSTOffset record");
4938         if (Stream.SkipBlock())
4939           return error("Invalid record");
4940         break;
4941       case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
4942       case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID:
4943         assert(!SeenValueSymbolTable &&
4944                "Already read VST when parsing summary block?");
4945         // We might not have a VST if there were no values in the
4946         // summary. An empty summary block generated when we are
4947         // performing ThinLTO compiles so we don't later invoke
4948         // the regular LTO process on them.
4949         if (VSTOffset > 0) {
4950           if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
4951             return Err;
4952           SeenValueSymbolTable = true;
4953         }
4954         SeenGlobalValSummary = true;
4955         if (Error Err = parseEntireSummary(Entry.ID))
4956           return Err;
4957         break;
4958       case bitc::MODULE_STRTAB_BLOCK_ID:
4959         if (Error Err = parseModuleStringTable())
4960           return Err;
4961         break;
4962       }
4963       continue;
4964
4965     case BitstreamEntry::Record: {
4966         Record.clear();
4967         auto BitCode = Stream.readRecord(Entry.ID, Record);
4968         switch (BitCode) {
4969         default:
4970           break; // Default behavior, ignore unknown content.
4971         case bitc::MODULE_CODE_VERSION: {
4972           if (Error Err = parseVersionRecord(Record).takeError())
4973             return Err;
4974           break;
4975         }
4976         /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
4977         case bitc::MODULE_CODE_SOURCE_FILENAME: {
4978           SmallString<128> ValueName;
4979           if (convertToString(Record, 0, ValueName))
4980             return error("Invalid record");
4981           SourceFileName = ValueName.c_str();
4982           break;
4983         }
4984         /// MODULE_CODE_HASH: [5*i32]
4985         case bitc::MODULE_CODE_HASH: {
4986           if (Record.size() != 5)
4987             return error("Invalid hash length " + Twine(Record.size()).str());
4988           auto &Hash = addThisModule()->second.second;
4989           int Pos = 0;
4990           for (auto &Val : Record) {
4991             assert(!(Val >> 32) && "Unexpected high bits set");
4992             Hash[Pos++] = Val;
4993           }
4994           break;
4995         }
4996         /// MODULE_CODE_VSTOFFSET: [offset]
4997         case bitc::MODULE_CODE_VSTOFFSET:
4998           if (Record.size() < 1)
4999             return error("Invalid record");
5000           // Note that we subtract 1 here because the offset is relative to one
5001           // word before the start of the identification or module block, which
5002           // was historically always the start of the regular bitcode header.
5003           VSTOffset = Record[0] - 1;
5004           break;
5005         // v1 GLOBALVAR: [pointer type, isconst,     initid,       linkage, ...]
5006         // v1 FUNCTION:  [type,         callingconv, isproto,      linkage, ...]
5007         // v1 ALIAS:     [alias type,   addrspace,   aliasee val#, linkage, ...]
5008         // v2: [strtab offset, strtab size, v1]
5009         case bitc::MODULE_CODE_GLOBALVAR:
5010         case bitc::MODULE_CODE_FUNCTION:
5011         case bitc::MODULE_CODE_ALIAS: {
5012           StringRef Name;
5013           ArrayRef<uint64_t> GVRecord;
5014           std::tie(Name, GVRecord) = readNameFromStrtab(Record);
5015           if (GVRecord.size() <= 3)
5016             return error("Invalid record");
5017           uint64_t RawLinkage = GVRecord[3];
5018           GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
5019           if (!UseStrtab) {
5020             ValueIdToLinkageMap[ValueId++] = Linkage;
5021             break;
5022           }
5023
5024           setValueGUID(ValueId++, Name, Linkage, SourceFileName);
5025           break;
5026         }
5027         }
5028       }
5029       continue;
5030     }
5031   }
5032 }
5033
5034 std::vector<ValueInfo>
5035 ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
5036   std::vector<ValueInfo> Ret;
5037   Ret.reserve(Record.size());
5038   for (uint64_t RefValueId : Record)
5039     Ret.push_back(getValueInfoFromValueId(RefValueId).first);
5040   return Ret;
5041 }
5042
5043 std::vector<FunctionSummary::EdgeTy> ModuleSummaryIndexBitcodeReader::makeCallList(
5044     ArrayRef<uint64_t> Record, bool IsOldProfileFormat, bool HasProfile) {
5045   std::vector<FunctionSummary::EdgeTy> Ret;
5046   Ret.reserve(Record.size());
5047   for (unsigned I = 0, E = Record.size(); I != E; ++I) {
5048     CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
5049     ValueInfo Callee = getValueInfoFromValueId(Record[I]).first;
5050     if (IsOldProfileFormat) {
5051       I += 1; // Skip old callsitecount field
5052       if (HasProfile)
5053         I += 1; // Skip old profilecount field
5054     } else if (HasProfile)
5055       Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]);
5056     Ret.push_back(FunctionSummary::EdgeTy{Callee, CalleeInfo{Hotness}});
5057   }
5058   return Ret;
5059 }
5060
5061 // Eagerly parse the entire summary block. This populates the GlobalValueSummary
5062 // objects in the index.
5063 Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) {
5064   if (Stream.EnterSubBlock(ID))
5065     return error("Invalid record");
5066   SmallVector<uint64_t, 64> Record;
5067
5068   // Parse version
5069   {
5070     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5071     if (Entry.Kind != BitstreamEntry::Record)
5072       return error("Invalid Summary Block: record for version expected");
5073     if (Stream.readRecord(Entry.ID, Record) != bitc::FS_VERSION)
5074       return error("Invalid Summary Block: version expected");
5075   }
5076   const uint64_t Version = Record[0];
5077   const bool IsOldProfileFormat = Version == 1;
5078   if (Version < 1 || Version > 4)
5079     return error("Invalid summary version " + Twine(Version) +
5080                  ", 1, 2, 3 or 4 expected");
5081   Record.clear();
5082
5083   // Keep around the last seen summary to be used when we see an optional
5084   // "OriginalName" attachement.
5085   GlobalValueSummary *LastSeenSummary = nullptr;
5086   GlobalValue::GUID LastSeenGUID = 0;
5087
5088   // We can expect to see any number of type ID information records before
5089   // each function summary records; these variables store the information
5090   // collected so far so that it can be used to create the summary object.
5091   std::vector<GlobalValue::GUID> PendingTypeTests;
5092   std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
5093       PendingTypeCheckedLoadVCalls;
5094   std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
5095       PendingTypeCheckedLoadConstVCalls;
5096
5097   while (true) {
5098     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5099
5100     switch (Entry.Kind) {
5101     case BitstreamEntry::SubBlock: // Handled for us already.
5102     case BitstreamEntry::Error:
5103       return error("Malformed block");
5104     case BitstreamEntry::EndBlock:
5105       return Error::success();
5106     case BitstreamEntry::Record:
5107       // The interesting case.
5108       break;
5109     }
5110
5111     // Read a record. The record format depends on whether this
5112     // is a per-module index or a combined index file. In the per-module
5113     // case the records contain the associated value's ID for correlation
5114     // with VST entries. In the combined index the correlation is done
5115     // via the bitcode offset of the summary records (which were saved
5116     // in the combined index VST entries). The records also contain
5117     // information used for ThinLTO renaming and importing.
5118     Record.clear();
5119     auto BitCode = Stream.readRecord(Entry.ID, Record);
5120     switch (BitCode) {
5121     default: // Default behavior: ignore.
5122       break;
5123     case bitc::FS_VALUE_GUID: { // [valueid, refguid]
5124       uint64_t ValueID = Record[0];
5125       GlobalValue::GUID RefGUID = Record[1];
5126       ValueIdToValueInfoMap[ValueID] =
5127           std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
5128       break;
5129     }
5130     // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs,
5131     //                numrefs x valueid, n x (valueid)]
5132     // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs,
5133     //                        numrefs x valueid,
5134     //                        n x (valueid, hotness)]
5135     case bitc::FS_PERMODULE:
5136     case bitc::FS_PERMODULE_PROFILE: {
5137       unsigned ValueID = Record[0];
5138       uint64_t RawFlags = Record[1];
5139       unsigned InstCount = Record[2];
5140       uint64_t RawFunFlags = 0;
5141       unsigned NumRefs = Record[3];
5142       int RefListStartIndex = 4;
5143       if (Version >= 4) {
5144         RawFunFlags = Record[3];
5145         NumRefs = Record[4];
5146         RefListStartIndex = 5;
5147       }
5148
5149       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
5150       // The module path string ref set in the summary must be owned by the
5151       // index's module string table. Since we don't have a module path
5152       // string table section in the per-module index, we create a single
5153       // module path string table entry with an empty (0) ID to take
5154       // ownership.
5155       int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
5156       assert(Record.size() >= RefListStartIndex + NumRefs &&
5157              "Record size inconsistent with number of references");
5158       std::vector<ValueInfo> Refs = makeRefList(
5159           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
5160       bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
5161       std::vector<FunctionSummary::EdgeTy> Calls = makeCallList(
5162           ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
5163           IsOldProfileFormat, HasProfile);
5164       auto FS = llvm::make_unique<FunctionSummary>(
5165           Flags, InstCount, getDecodedFFlags(RawFunFlags), std::move(Refs),
5166           std::move(Calls), std::move(PendingTypeTests),
5167           std::move(PendingTypeTestAssumeVCalls),
5168           std::move(PendingTypeCheckedLoadVCalls),
5169           std::move(PendingTypeTestAssumeConstVCalls),
5170           std::move(PendingTypeCheckedLoadConstVCalls));
5171       PendingTypeTests.clear();
5172       PendingTypeTestAssumeVCalls.clear();
5173       PendingTypeCheckedLoadVCalls.clear();
5174       PendingTypeTestAssumeConstVCalls.clear();
5175       PendingTypeCheckedLoadConstVCalls.clear();
5176       auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID);
5177       FS->setModulePath(addThisModule()->first());
5178       FS->setOriginalName(VIAndOriginalGUID.second);
5179       TheIndex.addGlobalValueSummary(VIAndOriginalGUID.first, std::move(FS));
5180       break;
5181     }
5182     // FS_ALIAS: [valueid, flags, valueid]
5183     // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
5184     // they expect all aliasee summaries to be available.
5185     case bitc::FS_ALIAS: {
5186       unsigned ValueID = Record[0];
5187       uint64_t RawFlags = Record[1];
5188       unsigned AliaseeID = Record[2];
5189       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
5190       auto AS = llvm::make_unique<AliasSummary>(Flags);
5191       // The module path string ref set in the summary must be owned by the
5192       // index's module string table. Since we don't have a module path
5193       // string table section in the per-module index, we create a single
5194       // module path string table entry with an empty (0) ID to take
5195       // ownership.
5196       AS->setModulePath(addThisModule()->first());
5197
5198       GlobalValue::GUID AliaseeGUID =
5199           getValueInfoFromValueId(AliaseeID).first.getGUID();
5200       auto AliaseeInModule =
5201           TheIndex.findSummaryInModule(AliaseeGUID, ModulePath);
5202       if (!AliaseeInModule)
5203         return error("Alias expects aliasee summary to be parsed");
5204       AS->setAliasee(AliaseeInModule);
5205       AS->setAliaseeGUID(AliaseeGUID);
5206
5207       auto GUID = getValueInfoFromValueId(ValueID);
5208       AS->setOriginalName(GUID.second);
5209       TheIndex.addGlobalValueSummary(GUID.first, std::move(AS));
5210       break;
5211     }
5212     // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, n x valueid]
5213     case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
5214       unsigned ValueID = Record[0];
5215       uint64_t RawFlags = Record[1];
5216       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
5217       std::vector<ValueInfo> Refs =
5218           makeRefList(ArrayRef<uint64_t>(Record).slice(2));
5219       auto FS = llvm::make_unique<GlobalVarSummary>(Flags, std::move(Refs));
5220       FS->setModulePath(addThisModule()->first());
5221       auto GUID = getValueInfoFromValueId(ValueID);
5222       FS->setOriginalName(GUID.second);
5223       TheIndex.addGlobalValueSummary(GUID.first, std::move(FS));
5224       break;
5225     }
5226     // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs,
5227     //               numrefs x valueid, n x (valueid)]
5228     // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs,
5229     //                       numrefs x valueid, n x (valueid, hotness)]
5230     case bitc::FS_COMBINED:
5231     case bitc::FS_COMBINED_PROFILE: {
5232       unsigned ValueID = Record[0];
5233       uint64_t ModuleId = Record[1];
5234       uint64_t RawFlags = Record[2];
5235       unsigned InstCount = Record[3];
5236       uint64_t RawFunFlags = 0;
5237       unsigned NumRefs = Record[4];
5238       int RefListStartIndex = 5;
5239
5240       if (Version >= 4) {
5241         RawFunFlags = Record[4];
5242         NumRefs = Record[5];
5243         RefListStartIndex = 6;
5244       }
5245
5246       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
5247       int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
5248       assert(Record.size() >= RefListStartIndex + NumRefs &&
5249              "Record size inconsistent with number of references");
5250       std::vector<ValueInfo> Refs = makeRefList(
5251           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
5252       bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
5253       std::vector<FunctionSummary::EdgeTy> Edges = makeCallList(
5254           ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
5255           IsOldProfileFormat, HasProfile);
5256       ValueInfo VI = getValueInfoFromValueId(ValueID).first;
5257       auto FS = llvm::make_unique<FunctionSummary>(
5258           Flags, InstCount, getDecodedFFlags(RawFunFlags), std::move(Refs),
5259           std::move(Edges), std::move(PendingTypeTests),
5260           std::move(PendingTypeTestAssumeVCalls),
5261           std::move(PendingTypeCheckedLoadVCalls),
5262           std::move(PendingTypeTestAssumeConstVCalls),
5263           std::move(PendingTypeCheckedLoadConstVCalls));
5264       PendingTypeTests.clear();
5265       PendingTypeTestAssumeVCalls.clear();
5266       PendingTypeCheckedLoadVCalls.clear();
5267       PendingTypeTestAssumeConstVCalls.clear();
5268       PendingTypeCheckedLoadConstVCalls.clear();
5269       LastSeenSummary = FS.get();
5270       LastSeenGUID = VI.getGUID();
5271       FS->setModulePath(ModuleIdMap[ModuleId]);
5272       TheIndex.addGlobalValueSummary(VI, std::move(FS));
5273       break;
5274     }
5275     // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
5276     // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
5277     // they expect all aliasee summaries to be available.
5278     case bitc::FS_COMBINED_ALIAS: {
5279       unsigned ValueID = Record[0];
5280       uint64_t ModuleId = Record[1];
5281       uint64_t RawFlags = Record[2];
5282       unsigned AliaseeValueId = Record[3];
5283       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
5284       auto AS = llvm::make_unique<AliasSummary>(Flags);
5285       LastSeenSummary = AS.get();
5286       AS->setModulePath(ModuleIdMap[ModuleId]);
5287
5288       auto AliaseeGUID =
5289           getValueInfoFromValueId(AliaseeValueId).first.getGUID();
5290       auto AliaseeInModule =
5291           TheIndex.findSummaryInModule(AliaseeGUID, AS->modulePath());
5292       AS->setAliasee(AliaseeInModule);
5293       AS->setAliaseeGUID(AliaseeGUID);
5294
5295       ValueInfo VI = getValueInfoFromValueId(ValueID).first;
5296       LastSeenGUID = VI.getGUID();
5297       TheIndex.addGlobalValueSummary(VI, std::move(AS));
5298       break;
5299     }
5300     // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
5301     case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
5302       unsigned ValueID = Record[0];
5303       uint64_t ModuleId = Record[1];
5304       uint64_t RawFlags = Record[2];
5305       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
5306       std::vector<ValueInfo> Refs =
5307           makeRefList(ArrayRef<uint64_t>(Record).slice(3));
5308       auto FS = llvm::make_unique<GlobalVarSummary>(Flags, std::move(Refs));
5309       LastSeenSummary = FS.get();
5310       FS->setModulePath(ModuleIdMap[ModuleId]);
5311       ValueInfo VI = getValueInfoFromValueId(ValueID).first;
5312       LastSeenGUID = VI.getGUID();
5313       TheIndex.addGlobalValueSummary(VI, std::move(FS));
5314       break;
5315     }
5316     // FS_COMBINED_ORIGINAL_NAME: [original_name]
5317     case bitc::FS_COMBINED_ORIGINAL_NAME: {
5318       uint64_t OriginalName = Record[0];
5319       if (!LastSeenSummary)
5320         return error("Name attachment that does not follow a combined record");
5321       LastSeenSummary->setOriginalName(OriginalName);
5322       TheIndex.addOriginalName(LastSeenGUID, OriginalName);
5323       // Reset the LastSeenSummary
5324       LastSeenSummary = nullptr;
5325       LastSeenGUID = 0;
5326       break;
5327     }
5328     case bitc::FS_TYPE_TESTS:
5329       assert(PendingTypeTests.empty());
5330       PendingTypeTests.insert(PendingTypeTests.end(), Record.begin(),
5331                               Record.end());
5332       break;
5333
5334     case bitc::FS_TYPE_TEST_ASSUME_VCALLS:
5335       assert(PendingTypeTestAssumeVCalls.empty());
5336       for (unsigned I = 0; I != Record.size(); I += 2)
5337         PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
5338       break;
5339
5340     case bitc::FS_TYPE_CHECKED_LOAD_VCALLS:
5341       assert(PendingTypeCheckedLoadVCalls.empty());
5342       for (unsigned I = 0; I != Record.size(); I += 2)
5343         PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
5344       break;
5345
5346     case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL:
5347       PendingTypeTestAssumeConstVCalls.push_back(
5348           {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
5349       break;
5350
5351     case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL:
5352       PendingTypeCheckedLoadConstVCalls.push_back(
5353           {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
5354       break;
5355
5356     case bitc::FS_CFI_FUNCTION_DEFS: {
5357       std::set<std::string> &CfiFunctionDefs = TheIndex.cfiFunctionDefs();
5358       for (unsigned I = 0; I != Record.size(); I += 2)
5359         CfiFunctionDefs.insert(
5360             {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
5361       break;
5362     }
5363     case bitc::FS_CFI_FUNCTION_DECLS: {
5364       std::set<std::string> &CfiFunctionDecls = TheIndex.cfiFunctionDecls();
5365       for (unsigned I = 0; I != Record.size(); I += 2)
5366         CfiFunctionDecls.insert(
5367             {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
5368       break;
5369     }
5370     }
5371   }
5372   llvm_unreachable("Exit infinite loop");
5373 }
5374
5375 // Parse the  module string table block into the Index.
5376 // This populates the ModulePathStringTable map in the index.
5377 Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
5378   if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
5379     return error("Invalid record");
5380
5381   SmallVector<uint64_t, 64> Record;
5382
5383   SmallString<128> ModulePath;
5384   ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr;
5385
5386   while (true) {
5387     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5388
5389     switch (Entry.Kind) {
5390     case BitstreamEntry::SubBlock: // Handled for us already.
5391     case BitstreamEntry::Error:
5392       return error("Malformed block");
5393     case BitstreamEntry::EndBlock:
5394       return Error::success();
5395     case BitstreamEntry::Record:
5396       // The interesting case.
5397       break;
5398     }
5399
5400     Record.clear();
5401     switch (Stream.readRecord(Entry.ID, Record)) {
5402     default: // Default behavior: ignore.
5403       break;
5404     case bitc::MST_CODE_ENTRY: {
5405       // MST_ENTRY: [modid, namechar x N]
5406       uint64_t ModuleId = Record[0];
5407
5408       if (convertToString(Record, 1, ModulePath))
5409         return error("Invalid record");
5410
5411       LastSeenModule = TheIndex.addModule(ModulePath, ModuleId);
5412       ModuleIdMap[ModuleId] = LastSeenModule->first();
5413
5414       ModulePath.clear();
5415       break;
5416     }
5417     /// MST_CODE_HASH: [5*i32]
5418     case bitc::MST_CODE_HASH: {
5419       if (Record.size() != 5)
5420         return error("Invalid hash length " + Twine(Record.size()).str());
5421       if (!LastSeenModule)
5422         return error("Invalid hash that does not follow a module path");
5423       int Pos = 0;
5424       for (auto &Val : Record) {
5425         assert(!(Val >> 32) && "Unexpected high bits set");
5426         LastSeenModule->second.second[Pos++] = Val;
5427       }
5428       // Reset LastSeenModule to avoid overriding the hash unexpectedly.
5429       LastSeenModule = nullptr;
5430       break;
5431     }
5432     }
5433   }
5434   llvm_unreachable("Exit infinite loop");
5435 }
5436
5437 namespace {
5438
5439 // FIXME: This class is only here to support the transition to llvm::Error. It
5440 // will be removed once this transition is complete. Clients should prefer to
5441 // deal with the Error value directly, rather than converting to error_code.
5442 class BitcodeErrorCategoryType : public std::error_category {
5443   const char *name() const noexcept override {
5444     return "llvm.bitcode";
5445   }
5446
5447   std::string message(int IE) const override {
5448     BitcodeError E = static_cast<BitcodeError>(IE);
5449     switch (E) {
5450     case BitcodeError::CorruptedBitcode:
5451       return "Corrupted bitcode";
5452     }
5453     llvm_unreachable("Unknown error type!");
5454   }
5455 };
5456
5457 } // end anonymous namespace
5458
5459 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
5460
5461 const std::error_category &llvm::BitcodeErrorCategory() {
5462   return *ErrorCategory;
5463 }
5464
5465 static Expected<StringRef> readBlobInRecord(BitstreamCursor &Stream,
5466                                             unsigned Block, unsigned RecordID) {
5467   if (Stream.EnterSubBlock(Block))
5468     return error("Invalid record");
5469
5470   StringRef Strtab;
5471   while (true) {
5472     BitstreamEntry Entry = Stream.advance();
5473     switch (Entry.Kind) {
5474     case BitstreamEntry::EndBlock:
5475       return Strtab;
5476
5477     case BitstreamEntry::Error:
5478       return error("Malformed block");
5479
5480     case BitstreamEntry::SubBlock:
5481       if (Stream.SkipBlock())
5482         return error("Malformed block");
5483       break;
5484
5485     case BitstreamEntry::Record:
5486       StringRef Blob;
5487       SmallVector<uint64_t, 1> Record;
5488       if (Stream.readRecord(Entry.ID, Record, &Blob) == RecordID)
5489         Strtab = Blob;
5490       break;
5491     }
5492   }
5493 }
5494
5495 //===----------------------------------------------------------------------===//
5496 // External interface
5497 //===----------------------------------------------------------------------===//
5498
5499 Expected<std::vector<BitcodeModule>>
5500 llvm::getBitcodeModuleList(MemoryBufferRef Buffer) {
5501   auto FOrErr = getBitcodeFileContents(Buffer);
5502   if (!FOrErr)
5503     return FOrErr.takeError();
5504   return std::move(FOrErr->Mods);
5505 }
5506
5507 Expected<BitcodeFileContents>
5508 llvm::getBitcodeFileContents(MemoryBufferRef Buffer) {
5509   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
5510   if (!StreamOrErr)
5511     return StreamOrErr.takeError();
5512   BitstreamCursor &Stream = *StreamOrErr;
5513
5514   BitcodeFileContents F;
5515   while (true) {
5516     uint64_t BCBegin = Stream.getCurrentByteNo();
5517
5518     // We may be consuming bitcode from a client that leaves garbage at the end
5519     // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to
5520     // the end that there cannot possibly be another module, stop looking.
5521     if (BCBegin + 8 >= Stream.getBitcodeBytes().size())
5522       return F;
5523
5524     BitstreamEntry Entry = Stream.advance();
5525     switch (Entry.Kind) {
5526     case BitstreamEntry::EndBlock:
5527     case BitstreamEntry::Error:
5528       return error("Malformed block");
5529
5530     case BitstreamEntry::SubBlock: {
5531       uint64_t IdentificationBit = -1ull;
5532       if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
5533         IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8;
5534         if (Stream.SkipBlock())
5535           return error("Malformed block");
5536
5537         Entry = Stream.advance();
5538         if (Entry.Kind != BitstreamEntry::SubBlock ||
5539             Entry.ID != bitc::MODULE_BLOCK_ID)
5540           return error("Malformed block");
5541       }
5542
5543       if (Entry.ID == bitc::MODULE_BLOCK_ID) {
5544         uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8;
5545         if (Stream.SkipBlock())
5546           return error("Malformed block");
5547
5548         F.Mods.push_back({Stream.getBitcodeBytes().slice(
5549                               BCBegin, Stream.getCurrentByteNo() - BCBegin),
5550                           Buffer.getBufferIdentifier(), IdentificationBit,
5551                           ModuleBit});
5552         continue;
5553       }
5554
5555       if (Entry.ID == bitc::STRTAB_BLOCK_ID) {
5556         Expected<StringRef> Strtab =
5557             readBlobInRecord(Stream, bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB);
5558         if (!Strtab)
5559           return Strtab.takeError();
5560         // This string table is used by every preceding bitcode module that does
5561         // not have its own string table. A bitcode file may have multiple
5562         // string tables if it was created by binary concatenation, for example
5563         // with "llvm-cat -b".
5564         for (auto I = F.Mods.rbegin(), E = F.Mods.rend(); I != E; ++I) {
5565           if (!I->Strtab.empty())
5566             break;
5567           I->Strtab = *Strtab;
5568         }
5569         // Similarly, the string table is used by every preceding symbol table;
5570         // normally there will be just one unless the bitcode file was created
5571         // by binary concatenation.
5572         if (!F.Symtab.empty() && F.StrtabForSymtab.empty())
5573           F.StrtabForSymtab = *Strtab;
5574         continue;
5575       }
5576
5577       if (Entry.ID == bitc::SYMTAB_BLOCK_ID) {
5578         Expected<StringRef> SymtabOrErr =
5579             readBlobInRecord(Stream, bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB);
5580         if (!SymtabOrErr)
5581           return SymtabOrErr.takeError();
5582
5583         // We can expect the bitcode file to have multiple symbol tables if it
5584         // was created by binary concatenation. In that case we silently
5585         // ignore any subsequent symbol tables, which is fine because this is a
5586         // low level function. The client is expected to notice that the number
5587         // of modules in the symbol table does not match the number of modules
5588         // in the input file and regenerate the symbol table.
5589         if (F.Symtab.empty())
5590           F.Symtab = *SymtabOrErr;
5591         continue;
5592       }
5593
5594       if (Stream.SkipBlock())
5595         return error("Malformed block");
5596       continue;
5597     }
5598     case BitstreamEntry::Record:
5599       Stream.skipRecord(Entry.ID);
5600       continue;
5601     }
5602   }
5603 }
5604
5605 /// \brief Get a lazy one-at-time loading module from bitcode.
5606 ///
5607 /// This isn't always used in a lazy context.  In particular, it's also used by
5608 /// \a parseModule().  If this is truly lazy, then we need to eagerly pull
5609 /// in forward-referenced functions from block address references.
5610 ///
5611 /// \param[in] MaterializeAll Set to \c true if we should materialize
5612 /// everything.
5613 Expected<std::unique_ptr<Module>>
5614 BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll,
5615                              bool ShouldLazyLoadMetadata, bool IsImporting) {
5616   BitstreamCursor Stream(Buffer);
5617
5618   std::string ProducerIdentification;
5619   if (IdentificationBit != -1ull) {
5620     Stream.JumpToBit(IdentificationBit);
5621     Expected<std::string> ProducerIdentificationOrErr =
5622         readIdentificationBlock(Stream);
5623     if (!ProducerIdentificationOrErr)
5624       return ProducerIdentificationOrErr.takeError();
5625
5626     ProducerIdentification = *ProducerIdentificationOrErr;
5627   }
5628
5629   Stream.JumpToBit(ModuleBit);
5630   auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
5631                               Context);
5632
5633   std::unique_ptr<Module> M =
5634       llvm::make_unique<Module>(ModuleIdentifier, Context);
5635   M->setMaterializer(R);
5636
5637   // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
5638   if (Error Err =
5639           R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata, IsImporting))
5640     return std::move(Err);
5641
5642   if (MaterializeAll) {
5643     // Read in the entire module, and destroy the BitcodeReader.
5644     if (Error Err = M->materializeAll())
5645       return std::move(Err);
5646   } else {
5647     // Resolve forward references from blockaddresses.
5648     if (Error Err = R->materializeForwardReferencedFunctions())
5649       return std::move(Err);
5650   }
5651   return std::move(M);
5652 }
5653
5654 Expected<std::unique_ptr<Module>>
5655 BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata,
5656                              bool IsImporting) {
5657   return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting);
5658 }
5659
5660 // Parse the specified bitcode buffer and merge the index into CombinedIndex.
5661 // We don't use ModuleIdentifier here because the client may need to control the
5662 // module path used in the combined summary (e.g. when reading summaries for
5663 // regular LTO modules).
5664 Error BitcodeModule::readSummary(ModuleSummaryIndex &CombinedIndex,
5665                                  StringRef ModulePath, uint64_t ModuleId) {
5666   BitstreamCursor Stream(Buffer);
5667   Stream.JumpToBit(ModuleBit);
5668
5669   ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
5670                                     ModulePath, ModuleId);
5671   return R.parseModule();
5672 }
5673
5674 // Parse the specified bitcode buffer, returning the function info index.
5675 Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() {
5676   BitstreamCursor Stream(Buffer);
5677   Stream.JumpToBit(ModuleBit);
5678
5679   auto Index = llvm::make_unique<ModuleSummaryIndex>();
5680   ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,
5681                                     ModuleIdentifier, 0);
5682
5683   if (Error Err = R.parseModule())
5684     return std::move(Err);
5685
5686   return std::move(Index);
5687 }
5688
5689 // Check if the given bitcode buffer contains a global value summary block.
5690 Expected<BitcodeLTOInfo> BitcodeModule::getLTOInfo() {
5691   BitstreamCursor Stream(Buffer);
5692   Stream.JumpToBit(ModuleBit);
5693
5694   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5695     return error("Invalid record");
5696
5697   while (true) {
5698     BitstreamEntry Entry = Stream.advance();
5699
5700     switch (Entry.Kind) {
5701     case BitstreamEntry::Error:
5702       return error("Malformed block");
5703     case BitstreamEntry::EndBlock:
5704       return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/false};
5705
5706     case BitstreamEntry::SubBlock:
5707       if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID)
5708         return BitcodeLTOInfo{/*IsThinLTO=*/true, /*HasSummary=*/true};
5709
5710       if (Entry.ID == bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID)
5711         return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/true};
5712
5713       // Ignore other sub-blocks.
5714       if (Stream.SkipBlock())
5715         return error("Malformed block");
5716       continue;
5717
5718     case BitstreamEntry::Record:
5719       Stream.skipRecord(Entry.ID);
5720       continue;
5721     }
5722   }
5723 }
5724
5725 static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) {
5726   Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer);
5727   if (!MsOrErr)
5728     return MsOrErr.takeError();
5729
5730   if (MsOrErr->size() != 1)
5731     return error("Expected a single module");
5732
5733   return (*MsOrErr)[0];
5734 }
5735
5736 Expected<std::unique_ptr<Module>>
5737 llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context,
5738                            bool ShouldLazyLoadMetadata, bool IsImporting) {
5739   Expected<BitcodeModule> BM = getSingleModule(Buffer);
5740   if (!BM)
5741     return BM.takeError();
5742
5743   return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting);
5744 }
5745
5746 Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule(
5747     std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
5748     bool ShouldLazyLoadMetadata, bool IsImporting) {
5749   auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata,
5750                                      IsImporting);
5751   if (MOrErr)
5752     (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
5753   return MOrErr;
5754 }
5755
5756 Expected<std::unique_ptr<Module>>
5757 BitcodeModule::parseModule(LLVMContext &Context) {
5758   return getModuleImpl(Context, true, false, false);
5759   // TODO: Restore the use-lists to the in-memory state when the bitcode was
5760   // written.  We must defer until the Module has been fully materialized.
5761 }
5762
5763 Expected<std::unique_ptr<Module>> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
5764                                                          LLVMContext &Context) {
5765   Expected<BitcodeModule> BM = getSingleModule(Buffer);
5766   if (!BM)
5767     return BM.takeError();
5768
5769   return BM->parseModule(Context);
5770 }
5771
5772 Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) {
5773   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
5774   if (!StreamOrErr)
5775     return StreamOrErr.takeError();
5776
5777   return readTriple(*StreamOrErr);
5778 }
5779
5780 Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) {
5781   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
5782   if (!StreamOrErr)
5783     return StreamOrErr.takeError();
5784
5785   return hasObjCCategory(*StreamOrErr);
5786 }
5787
5788 Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) {
5789   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
5790   if (!StreamOrErr)
5791     return StreamOrErr.takeError();
5792
5793   return readIdentificationCode(*StreamOrErr);
5794 }
5795
5796 Error llvm::readModuleSummaryIndex(MemoryBufferRef Buffer,
5797                                    ModuleSummaryIndex &CombinedIndex,
5798                                    uint64_t ModuleId) {
5799   Expected<BitcodeModule> BM = getSingleModule(Buffer);
5800   if (!BM)
5801     return BM.takeError();
5802
5803   return BM->readSummary(CombinedIndex, BM->getModuleIdentifier(), ModuleId);
5804 }
5805
5806 Expected<std::unique_ptr<ModuleSummaryIndex>>
5807 llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) {
5808   Expected<BitcodeModule> BM = getSingleModule(Buffer);
5809   if (!BM)
5810     return BM.takeError();
5811
5812   return BM->getSummary();
5813 }
5814
5815 Expected<BitcodeLTOInfo> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer) {
5816   Expected<BitcodeModule> BM = getSingleModule(Buffer);
5817   if (!BM)
5818     return BM.takeError();
5819
5820   return BM->getLTOInfo();
5821 }
5822
5823 Expected<std::unique_ptr<ModuleSummaryIndex>>
5824 llvm::getModuleSummaryIndexForFile(StringRef Path,
5825                                    bool IgnoreEmptyThinLTOIndexFile) {
5826   ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
5827       MemoryBuffer::getFileOrSTDIN(Path);
5828   if (!FileOrErr)
5829     return errorCodeToError(FileOrErr.getError());
5830   if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize())
5831     return nullptr;
5832   return getModuleSummaryIndex(**FileOrErr);
5833 }