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