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