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