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