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