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