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