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