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