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