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