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