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