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