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