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