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