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