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