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 *getElementTypeByID(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, 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::getElementTypeByID(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 (Attribute::isEnumAttrKind(Kind))
1632             B.addAttribute(Kind);
1633           else
1634             return error("Not an enum attribute");
1635         } else if (Record[i] == 1) { // Integer attribute
1636           Attribute::AttrKind Kind;
1637           if (Error Err = parseAttrKind(Record[++i], &Kind))
1638             return Err;
1639           if (!Attribute::isIntAttrKind(Kind))
1640             return error("Not an int attribute");
1641           if (Kind == Attribute::Alignment)
1642             B.addAlignmentAttr(Record[++i]);
1643           else if (Kind == Attribute::StackAlignment)
1644             B.addStackAlignmentAttr(Record[++i]);
1645           else if (Kind == Attribute::Dereferenceable)
1646             B.addDereferenceableAttr(Record[++i]);
1647           else if (Kind == Attribute::DereferenceableOrNull)
1648             B.addDereferenceableOrNullAttr(Record[++i]);
1649           else if (Kind == Attribute::AllocSize)
1650             B.addAllocSizeAttrFromRawRepr(Record[++i]);
1651           else if (Kind == Attribute::VScaleRange)
1652             B.addVScaleRangeAttrFromRawRepr(Record[++i]);
1653         } else if (Record[i] == 3 || Record[i] == 4) { // String attribute
1654           bool HasValue = (Record[i++] == 4);
1655           SmallString<64> KindStr;
1656           SmallString<64> ValStr;
1657 
1658           while (Record[i] != 0 && i != e)
1659             KindStr += Record[i++];
1660           assert(Record[i] == 0 && "Kind string not null terminated");
1661 
1662           if (HasValue) {
1663             // Has a value associated with it.
1664             ++i; // Skip the '0' that terminates the "kind" string.
1665             while (Record[i] != 0 && i != e)
1666               ValStr += Record[i++];
1667             assert(Record[i] == 0 && "Value string not null terminated");
1668           }
1669 
1670           B.addAttribute(KindStr.str(), ValStr.str());
1671         } else if (Record[i] == 5 || Record[i] == 6) {
1672           bool HasType = Record[i] == 6;
1673           Attribute::AttrKind Kind;
1674           if (Error Err = parseAttrKind(Record[++i], &Kind))
1675             return Err;
1676           if (!Attribute::isTypeAttrKind(Kind))
1677             return error("Not a type attribute");
1678 
1679           B.addTypeAttr(Kind, HasType ? getTypeByID(Record[++i]) : nullptr);
1680         } else {
1681           return error("Invalid attribute group entry");
1682         }
1683       }
1684 
1685       UpgradeAttributes(B);
1686       MAttributeGroups[GrpID] = AttributeList::get(Context, Idx, B);
1687       break;
1688     }
1689     }
1690   }
1691 }
1692 
1693 Error BitcodeReader::parseTypeTable() {
1694   if (Error Err = Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
1695     return Err;
1696 
1697   return parseTypeTableBody();
1698 }
1699 
1700 Error BitcodeReader::parseTypeTableBody() {
1701   if (!TypeList.empty())
1702     return error("Invalid multiple blocks");
1703 
1704   SmallVector<uint64_t, 64> Record;
1705   unsigned NumRecords = 0;
1706 
1707   SmallString<64> TypeName;
1708 
1709   // Read all the records for this type table.
1710   while (true) {
1711     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
1712     if (!MaybeEntry)
1713       return MaybeEntry.takeError();
1714     BitstreamEntry Entry = MaybeEntry.get();
1715 
1716     switch (Entry.Kind) {
1717     case BitstreamEntry::SubBlock: // Handled for us already.
1718     case BitstreamEntry::Error:
1719       return error("Malformed block");
1720     case BitstreamEntry::EndBlock:
1721       if (NumRecords != TypeList.size())
1722         return error("Malformed block");
1723       return Error::success();
1724     case BitstreamEntry::Record:
1725       // The interesting case.
1726       break;
1727     }
1728 
1729     // Read a record.
1730     Record.clear();
1731     Type *ResultTy = nullptr;
1732     Type *ElemTy = nullptr;
1733     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
1734     if (!MaybeRecord)
1735       return MaybeRecord.takeError();
1736     switch (MaybeRecord.get()) {
1737     default:
1738       return error("Invalid value");
1739     case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1740       // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1741       // type list.  This allows us to reserve space.
1742       if (Record.empty())
1743         return error("Invalid record");
1744       TypeList.resize(Record[0]);
1745       ElementTypeList.resize(Record[0]);
1746       continue;
1747     case bitc::TYPE_CODE_VOID:      // VOID
1748       ResultTy = Type::getVoidTy(Context);
1749       break;
1750     case bitc::TYPE_CODE_HALF:     // HALF
1751       ResultTy = Type::getHalfTy(Context);
1752       break;
1753     case bitc::TYPE_CODE_BFLOAT:    // BFLOAT
1754       ResultTy = Type::getBFloatTy(Context);
1755       break;
1756     case bitc::TYPE_CODE_FLOAT:     // FLOAT
1757       ResultTy = Type::getFloatTy(Context);
1758       break;
1759     case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
1760       ResultTy = Type::getDoubleTy(Context);
1761       break;
1762     case bitc::TYPE_CODE_X86_FP80:  // X86_FP80
1763       ResultTy = Type::getX86_FP80Ty(Context);
1764       break;
1765     case bitc::TYPE_CODE_FP128:     // FP128
1766       ResultTy = Type::getFP128Ty(Context);
1767       break;
1768     case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1769       ResultTy = Type::getPPC_FP128Ty(Context);
1770       break;
1771     case bitc::TYPE_CODE_LABEL:     // LABEL
1772       ResultTy = Type::getLabelTy(Context);
1773       break;
1774     case bitc::TYPE_CODE_METADATA:  // METADATA
1775       ResultTy = Type::getMetadataTy(Context);
1776       break;
1777     case bitc::TYPE_CODE_X86_MMX:   // X86_MMX
1778       ResultTy = Type::getX86_MMXTy(Context);
1779       break;
1780     case bitc::TYPE_CODE_X86_AMX:   // X86_AMX
1781       ResultTy = Type::getX86_AMXTy(Context);
1782       break;
1783     case bitc::TYPE_CODE_TOKEN:     // TOKEN
1784       ResultTy = Type::getTokenTy(Context);
1785       break;
1786     case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1787       if (Record.empty())
1788         return error("Invalid record");
1789 
1790       uint64_t NumBits = Record[0];
1791       if (NumBits < IntegerType::MIN_INT_BITS ||
1792           NumBits > IntegerType::MAX_INT_BITS)
1793         return error("Bitwidth for integer type out of range");
1794       ResultTy = IntegerType::get(Context, NumBits);
1795       break;
1796     }
1797     case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1798                                     //          [pointee type, address space]
1799       if (Record.empty())
1800         return error("Invalid record");
1801       unsigned AddressSpace = 0;
1802       if (Record.size() == 2)
1803         AddressSpace = Record[1];
1804       ResultTy = getTypeByID(Record[0]);
1805       if (!ResultTy ||
1806           !PointerType::isValidElementType(ResultTy))
1807         return error("Invalid type");
1808       ElemTy = ResultTy;
1809       ResultTy = PointerType::get(ResultTy, AddressSpace);
1810       break;
1811     }
1812     case bitc::TYPE_CODE_OPAQUE_POINTER: { // OPAQUE_POINTER: [addrspace]
1813       if (Record.size() != 1)
1814         return error("Invalid record");
1815       if (Context.supportsTypedPointers())
1816         return error(
1817             "Opaque pointers are only supported in -opaque-pointers mode");
1818       unsigned AddressSpace = Record[0];
1819       ResultTy = PointerType::get(Context, AddressSpace);
1820       break;
1821     }
1822     case bitc::TYPE_CODE_FUNCTION_OLD: {
1823       // Deprecated, but still needed to read old bitcode files.
1824       // FUNCTION: [vararg, attrid, retty, paramty x N]
1825       if (Record.size() < 3)
1826         return error("Invalid record");
1827       SmallVector<Type*, 8> ArgTys;
1828       for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1829         if (Type *T = getTypeByID(Record[i]))
1830           ArgTys.push_back(T);
1831         else
1832           break;
1833       }
1834 
1835       ResultTy = getTypeByID(Record[2]);
1836       if (!ResultTy || ArgTys.size() < Record.size()-3)
1837         return error("Invalid type");
1838 
1839       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1840       break;
1841     }
1842     case bitc::TYPE_CODE_FUNCTION: {
1843       // FUNCTION: [vararg, retty, paramty x N]
1844       if (Record.size() < 2)
1845         return error("Invalid record");
1846       SmallVector<Type*, 8> ArgTys;
1847       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1848         if (Type *T = getTypeByID(Record[i])) {
1849           if (!FunctionType::isValidArgumentType(T))
1850             return error("Invalid function argument type");
1851           ArgTys.push_back(T);
1852         }
1853         else
1854           break;
1855       }
1856 
1857       ResultTy = getTypeByID(Record[1]);
1858       if (!ResultTy || ArgTys.size() < Record.size()-2)
1859         return error("Invalid type");
1860 
1861       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1862       break;
1863     }
1864     case bitc::TYPE_CODE_STRUCT_ANON: {  // STRUCT: [ispacked, eltty x N]
1865       if (Record.empty())
1866         return error("Invalid record");
1867       SmallVector<Type*, 8> EltTys;
1868       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1869         if (Type *T = getTypeByID(Record[i]))
1870           EltTys.push_back(T);
1871         else
1872           break;
1873       }
1874       if (EltTys.size() != Record.size()-1)
1875         return error("Invalid type");
1876       ResultTy = StructType::get(Context, EltTys, Record[0]);
1877       break;
1878     }
1879     case bitc::TYPE_CODE_STRUCT_NAME:   // STRUCT_NAME: [strchr x N]
1880       if (convertToString(Record, 0, TypeName))
1881         return error("Invalid record");
1882       continue;
1883 
1884     case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1885       if (Record.empty())
1886         return error("Invalid record");
1887 
1888       if (NumRecords >= TypeList.size())
1889         return error("Invalid TYPE table");
1890 
1891       // Check to see if this was forward referenced, if so fill in the temp.
1892       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1893       if (Res) {
1894         Res->setName(TypeName);
1895         TypeList[NumRecords] = nullptr;
1896       } else  // Otherwise, create a new struct.
1897         Res = createIdentifiedStructType(Context, TypeName);
1898       TypeName.clear();
1899 
1900       SmallVector<Type*, 8> EltTys;
1901       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1902         if (Type *T = getTypeByID(Record[i]))
1903           EltTys.push_back(T);
1904         else
1905           break;
1906       }
1907       if (EltTys.size() != Record.size()-1)
1908         return error("Invalid record");
1909       Res->setBody(EltTys, Record[0]);
1910       ResultTy = Res;
1911       break;
1912     }
1913     case bitc::TYPE_CODE_OPAQUE: {       // OPAQUE: []
1914       if (Record.size() != 1)
1915         return error("Invalid record");
1916 
1917       if (NumRecords >= TypeList.size())
1918         return error("Invalid TYPE table");
1919 
1920       // Check to see if this was forward referenced, if so fill in the temp.
1921       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1922       if (Res) {
1923         Res->setName(TypeName);
1924         TypeList[NumRecords] = nullptr;
1925       } else  // Otherwise, create a new struct with no body.
1926         Res = createIdentifiedStructType(Context, TypeName);
1927       TypeName.clear();
1928       ResultTy = Res;
1929       break;
1930     }
1931     case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
1932       if (Record.size() < 2)
1933         return error("Invalid record");
1934       ResultTy = getTypeByID(Record[1]);
1935       if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
1936         return error("Invalid type");
1937       ResultTy = ArrayType::get(ResultTy, Record[0]);
1938       break;
1939     case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty] or
1940                                     //         [numelts, eltty, scalable]
1941       if (Record.size() < 2)
1942         return error("Invalid record");
1943       if (Record[0] == 0)
1944         return error("Invalid vector length");
1945       ResultTy = getTypeByID(Record[1]);
1946       if (!ResultTy || !VectorType::isValidElementType(ResultTy))
1947         return error("Invalid type");
1948       bool Scalable = Record.size() > 2 ? Record[2] : false;
1949       ResultTy = VectorType::get(ResultTy, Record[0], Scalable);
1950       break;
1951     }
1952 
1953     if (NumRecords >= TypeList.size())
1954       return error("Invalid TYPE table");
1955     if (TypeList[NumRecords])
1956       return error(
1957           "Invalid TYPE table: Only named structs can be forward referenced");
1958     assert(ResultTy && "Didn't read a type?");
1959     TypeList[NumRecords] = ResultTy;
1960     ElementTypeList[NumRecords] = ElemTy;
1961     ++NumRecords;
1962   }
1963 }
1964 
1965 Error BitcodeReader::parseOperandBundleTags() {
1966   if (Error Err = Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
1967     return Err;
1968 
1969   if (!BundleTags.empty())
1970     return error("Invalid multiple blocks");
1971 
1972   SmallVector<uint64_t, 64> Record;
1973 
1974   while (true) {
1975     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
1976     if (!MaybeEntry)
1977       return MaybeEntry.takeError();
1978     BitstreamEntry Entry = MaybeEntry.get();
1979 
1980     switch (Entry.Kind) {
1981     case BitstreamEntry::SubBlock: // Handled for us already.
1982     case BitstreamEntry::Error:
1983       return error("Malformed block");
1984     case BitstreamEntry::EndBlock:
1985       return Error::success();
1986     case BitstreamEntry::Record:
1987       // The interesting case.
1988       break;
1989     }
1990 
1991     // Tags are implicitly mapped to integers by their order.
1992 
1993     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
1994     if (!MaybeRecord)
1995       return MaybeRecord.takeError();
1996     if (MaybeRecord.get() != bitc::OPERAND_BUNDLE_TAG)
1997       return error("Invalid record");
1998 
1999     // OPERAND_BUNDLE_TAG: [strchr x N]
2000     BundleTags.emplace_back();
2001     if (convertToString(Record, 0, BundleTags.back()))
2002       return error("Invalid record");
2003     Record.clear();
2004   }
2005 }
2006 
2007 Error BitcodeReader::parseSyncScopeNames() {
2008   if (Error Err = Stream.EnterSubBlock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID))
2009     return Err;
2010 
2011   if (!SSIDs.empty())
2012     return error("Invalid multiple synchronization scope names blocks");
2013 
2014   SmallVector<uint64_t, 64> Record;
2015   while (true) {
2016     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2017     if (!MaybeEntry)
2018       return MaybeEntry.takeError();
2019     BitstreamEntry Entry = MaybeEntry.get();
2020 
2021     switch (Entry.Kind) {
2022     case BitstreamEntry::SubBlock: // Handled for us already.
2023     case BitstreamEntry::Error:
2024       return error("Malformed block");
2025     case BitstreamEntry::EndBlock:
2026       if (SSIDs.empty())
2027         return error("Invalid empty synchronization scope names block");
2028       return Error::success();
2029     case BitstreamEntry::Record:
2030       // The interesting case.
2031       break;
2032     }
2033 
2034     // Synchronization scope names are implicitly mapped to synchronization
2035     // scope IDs by their order.
2036 
2037     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2038     if (!MaybeRecord)
2039       return MaybeRecord.takeError();
2040     if (MaybeRecord.get() != bitc::SYNC_SCOPE_NAME)
2041       return error("Invalid record");
2042 
2043     SmallString<16> SSN;
2044     if (convertToString(Record, 0, SSN))
2045       return error("Invalid record");
2046 
2047     SSIDs.push_back(Context.getOrInsertSyncScopeID(SSN));
2048     Record.clear();
2049   }
2050 }
2051 
2052 /// Associate a value with its name from the given index in the provided record.
2053 Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
2054                                              unsigned NameIndex, Triple &TT) {
2055   SmallString<128> ValueName;
2056   if (convertToString(Record, NameIndex, ValueName))
2057     return error("Invalid record");
2058   unsigned ValueID = Record[0];
2059   if (ValueID >= ValueList.size() || !ValueList[ValueID])
2060     return error("Invalid record");
2061   Value *V = ValueList[ValueID];
2062 
2063   StringRef NameStr(ValueName.data(), ValueName.size());
2064   if (NameStr.find_first_of(0) != StringRef::npos)
2065     return error("Invalid value name");
2066   V->setName(NameStr);
2067   auto *GO = dyn_cast<GlobalObject>(V);
2068   if (GO && ImplicitComdatObjects.contains(GO) && TT.supportsCOMDAT())
2069     GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
2070   return V;
2071 }
2072 
2073 /// Helper to note and return the current location, and jump to the given
2074 /// offset.
2075 static Expected<uint64_t> jumpToValueSymbolTable(uint64_t Offset,
2076                                                  BitstreamCursor &Stream) {
2077   // Save the current parsing location so we can jump back at the end
2078   // of the VST read.
2079   uint64_t CurrentBit = Stream.GetCurrentBitNo();
2080   if (Error JumpFailed = Stream.JumpToBit(Offset * 32))
2081     return std::move(JumpFailed);
2082   Expected<BitstreamEntry> MaybeEntry = Stream.advance();
2083   if (!MaybeEntry)
2084     return MaybeEntry.takeError();
2085   if (MaybeEntry.get().Kind != BitstreamEntry::SubBlock ||
2086       MaybeEntry.get().ID != bitc::VALUE_SYMTAB_BLOCK_ID)
2087     return error("Expected value symbol table subblock");
2088   return CurrentBit;
2089 }
2090 
2091 void BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta,
2092                                             Function *F,
2093                                             ArrayRef<uint64_t> Record) {
2094   // Note that we subtract 1 here because the offset is relative to one word
2095   // before the start of the identification or module block, which was
2096   // historically always the start of the regular bitcode header.
2097   uint64_t FuncWordOffset = Record[1] - 1;
2098   uint64_t FuncBitOffset = FuncWordOffset * 32;
2099   DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
2100   // Set the LastFunctionBlockBit to point to the last function block.
2101   // Later when parsing is resumed after function materialization,
2102   // we can simply skip that last function block.
2103   if (FuncBitOffset > LastFunctionBlockBit)
2104     LastFunctionBlockBit = FuncBitOffset;
2105 }
2106 
2107 /// Read a new-style GlobalValue symbol table.
2108 Error BitcodeReader::parseGlobalValueSymbolTable() {
2109   unsigned FuncBitcodeOffsetDelta =
2110       Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
2111 
2112   if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
2113     return Err;
2114 
2115   SmallVector<uint64_t, 64> Record;
2116   while (true) {
2117     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2118     if (!MaybeEntry)
2119       return MaybeEntry.takeError();
2120     BitstreamEntry Entry = MaybeEntry.get();
2121 
2122     switch (Entry.Kind) {
2123     case BitstreamEntry::SubBlock:
2124     case BitstreamEntry::Error:
2125       return error("Malformed block");
2126     case BitstreamEntry::EndBlock:
2127       return Error::success();
2128     case BitstreamEntry::Record:
2129       break;
2130     }
2131 
2132     Record.clear();
2133     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2134     if (!MaybeRecord)
2135       return MaybeRecord.takeError();
2136     switch (MaybeRecord.get()) {
2137     case bitc::VST_CODE_FNENTRY: { // [valueid, offset]
2138       unsigned ValueID = Record[0];
2139       if (ValueID >= ValueList.size() || !ValueList[ValueID])
2140         return error("Invalid value reference in symbol table");
2141       setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
2142                               cast<Function>(ValueList[ValueID]), Record);
2143       break;
2144     }
2145     }
2146   }
2147 }
2148 
2149 /// Parse the value symbol table at either the current parsing location or
2150 /// at the given bit offset if provided.
2151 Error BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
2152   uint64_t CurrentBit;
2153   // Pass in the Offset to distinguish between calling for the module-level
2154   // VST (where we want to jump to the VST offset) and the function-level
2155   // VST (where we don't).
2156   if (Offset > 0) {
2157     Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream);
2158     if (!MaybeCurrentBit)
2159       return MaybeCurrentBit.takeError();
2160     CurrentBit = MaybeCurrentBit.get();
2161     // If this module uses a string table, read this as a module-level VST.
2162     if (UseStrtab) {
2163       if (Error Err = parseGlobalValueSymbolTable())
2164         return Err;
2165       if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
2166         return JumpFailed;
2167       return Error::success();
2168     }
2169     // Otherwise, the VST will be in a similar format to a function-level VST,
2170     // and will contain symbol names.
2171   }
2172 
2173   // Compute the delta between the bitcode indices in the VST (the word offset
2174   // to the word-aligned ENTER_SUBBLOCK for the function block, and that
2175   // expected by the lazy reader. The reader's EnterSubBlock expects to have
2176   // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
2177   // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
2178   // just before entering the VST subblock because: 1) the EnterSubBlock
2179   // changes the AbbrevID width; 2) the VST block is nested within the same
2180   // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
2181   // AbbrevID width before calling EnterSubBlock; and 3) when we want to
2182   // jump to the FUNCTION_BLOCK using this offset later, we don't want
2183   // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
2184   unsigned FuncBitcodeOffsetDelta =
2185       Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
2186 
2187   if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
2188     return Err;
2189 
2190   SmallVector<uint64_t, 64> Record;
2191 
2192   Triple TT(TheModule->getTargetTriple());
2193 
2194   // Read all the records for this value table.
2195   SmallString<128> ValueName;
2196 
2197   while (true) {
2198     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2199     if (!MaybeEntry)
2200       return MaybeEntry.takeError();
2201     BitstreamEntry Entry = MaybeEntry.get();
2202 
2203     switch (Entry.Kind) {
2204     case BitstreamEntry::SubBlock: // Handled for us already.
2205     case BitstreamEntry::Error:
2206       return error("Malformed block");
2207     case BitstreamEntry::EndBlock:
2208       if (Offset > 0)
2209         if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
2210           return JumpFailed;
2211       return Error::success();
2212     case BitstreamEntry::Record:
2213       // The interesting case.
2214       break;
2215     }
2216 
2217     // Read a record.
2218     Record.clear();
2219     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2220     if (!MaybeRecord)
2221       return MaybeRecord.takeError();
2222     switch (MaybeRecord.get()) {
2223     default:  // Default behavior: unknown type.
2224       break;
2225     case bitc::VST_CODE_ENTRY: {  // VST_CODE_ENTRY: [valueid, namechar x N]
2226       Expected<Value *> ValOrErr = recordValue(Record, 1, TT);
2227       if (Error Err = ValOrErr.takeError())
2228         return Err;
2229       ValOrErr.get();
2230       break;
2231     }
2232     case bitc::VST_CODE_FNENTRY: {
2233       // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
2234       Expected<Value *> ValOrErr = recordValue(Record, 2, TT);
2235       if (Error Err = ValOrErr.takeError())
2236         return Err;
2237       Value *V = ValOrErr.get();
2238 
2239       // Ignore function offsets emitted for aliases of functions in older
2240       // versions of LLVM.
2241       if (auto *F = dyn_cast<Function>(V))
2242         setDeferredFunctionInfo(FuncBitcodeOffsetDelta, F, Record);
2243       break;
2244     }
2245     case bitc::VST_CODE_BBENTRY: {
2246       if (convertToString(Record, 1, ValueName))
2247         return error("Invalid record");
2248       BasicBlock *BB = getBasicBlock(Record[0]);
2249       if (!BB)
2250         return error("Invalid record");
2251 
2252       BB->setName(StringRef(ValueName.data(), ValueName.size()));
2253       ValueName.clear();
2254       break;
2255     }
2256     }
2257   }
2258 }
2259 
2260 /// Decode a signed value stored with the sign bit in the LSB for dense VBR
2261 /// encoding.
2262 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2263   if ((V & 1) == 0)
2264     return V >> 1;
2265   if (V != 1)
2266     return -(V >> 1);
2267   // There is no such thing as -0 with integers.  "-0" really means MININT.
2268   return 1ULL << 63;
2269 }
2270 
2271 /// Resolve all of the initializers for global values and aliases that we can.
2272 Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
2273   std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist;
2274   std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInitWorklist;
2275   std::vector<FunctionOperandInfo> FunctionOperandWorklist;
2276 
2277   GlobalInitWorklist.swap(GlobalInits);
2278   IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
2279   FunctionOperandWorklist.swap(FunctionOperands);
2280 
2281   while (!GlobalInitWorklist.empty()) {
2282     unsigned ValID = GlobalInitWorklist.back().second;
2283     if (ValID >= ValueList.size()) {
2284       // Not ready to resolve this yet, it requires something later in the file.
2285       GlobalInits.push_back(GlobalInitWorklist.back());
2286     } else {
2287       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2288         GlobalInitWorklist.back().first->setInitializer(C);
2289       else
2290         return error("Expected a constant");
2291     }
2292     GlobalInitWorklist.pop_back();
2293   }
2294 
2295   while (!IndirectSymbolInitWorklist.empty()) {
2296     unsigned ValID = IndirectSymbolInitWorklist.back().second;
2297     if (ValID >= ValueList.size()) {
2298       IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
2299     } else {
2300       Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2301       if (!C)
2302         return error("Expected a constant");
2303       GlobalValue *GV = IndirectSymbolInitWorklist.back().first;
2304       if (auto *GA = dyn_cast<GlobalAlias>(GV)) {
2305         if (C->getType() != GV->getType())
2306           return error("Alias and aliasee types don't match");
2307         GA->setAliasee(C);
2308       } else if (auto *GI = dyn_cast<GlobalIFunc>(GV)) {
2309         Type *ResolverFTy =
2310             GlobalIFunc::getResolverFunctionType(GI->getValueType());
2311         // Transparently fix up the type for compatiblity with older bitcode
2312         GI->setResolver(
2313             ConstantExpr::getBitCast(C, ResolverFTy->getPointerTo()));
2314       } else {
2315         return error("Expected an alias or an ifunc");
2316       }
2317     }
2318     IndirectSymbolInitWorklist.pop_back();
2319   }
2320 
2321   while (!FunctionOperandWorklist.empty()) {
2322     FunctionOperandInfo &Info = FunctionOperandWorklist.back();
2323     if (Info.PersonalityFn) {
2324       unsigned ValID = Info.PersonalityFn - 1;
2325       if (ValID < ValueList.size()) {
2326         if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2327           Info.F->setPersonalityFn(C);
2328         else
2329           return error("Expected a constant");
2330         Info.PersonalityFn = 0;
2331       }
2332     }
2333     if (Info.Prefix) {
2334       unsigned ValID = Info.Prefix - 1;
2335       if (ValID < ValueList.size()) {
2336         if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2337           Info.F->setPrefixData(C);
2338         else
2339           return error("Expected a constant");
2340         Info.Prefix = 0;
2341       }
2342     }
2343     if (Info.Prologue) {
2344       unsigned ValID = Info.Prologue - 1;
2345       if (ValID < ValueList.size()) {
2346         if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2347           Info.F->setPrologueData(C);
2348         else
2349           return error("Expected a constant");
2350         Info.Prologue = 0;
2351       }
2352     }
2353     if (Info.PersonalityFn || Info.Prefix || Info.Prologue)
2354       FunctionOperands.push_back(Info);
2355     FunctionOperandWorklist.pop_back();
2356   }
2357 
2358   return Error::success();
2359 }
2360 
2361 APInt llvm::readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2362   SmallVector<uint64_t, 8> Words(Vals.size());
2363   transform(Vals, Words.begin(),
2364                  BitcodeReader::decodeSignRotatedValue);
2365 
2366   return APInt(TypeBits, Words);
2367 }
2368 
2369 Error BitcodeReader::parseConstants() {
2370   if (Error Err = Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2371     return Err;
2372 
2373   SmallVector<uint64_t, 64> Record;
2374 
2375   // Read all the records for this value table.
2376   Type *CurTy = Type::getInt32Ty(Context);
2377   Type *CurElemTy = nullptr;
2378   unsigned NextCstNo = ValueList.size();
2379 
2380   struct DelayedShufTy {
2381     VectorType *OpTy;
2382     VectorType *RTy;
2383     uint64_t Op0Idx;
2384     uint64_t Op1Idx;
2385     uint64_t Op2Idx;
2386     unsigned CstNo;
2387   };
2388   std::vector<DelayedShufTy> DelayedShuffles;
2389   struct DelayedSelTy {
2390     Type *OpTy;
2391     uint64_t Op0Idx;
2392     uint64_t Op1Idx;
2393     uint64_t Op2Idx;
2394     unsigned CstNo;
2395   };
2396   std::vector<DelayedSelTy> DelayedSelectors;
2397 
2398   while (true) {
2399     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2400     if (!MaybeEntry)
2401       return MaybeEntry.takeError();
2402     BitstreamEntry Entry = MaybeEntry.get();
2403 
2404     switch (Entry.Kind) {
2405     case BitstreamEntry::SubBlock: // Handled for us already.
2406     case BitstreamEntry::Error:
2407       return error("Malformed block");
2408     case BitstreamEntry::EndBlock:
2409       // Once all the constants have been read, go through and resolve forward
2410       // references.
2411       //
2412       // We have to treat shuffles specially because they don't have three
2413       // operands anymore.  We need to convert the shuffle mask into an array,
2414       // and we can't convert a forward reference.
2415       for (auto &DelayedShuffle : DelayedShuffles) {
2416         VectorType *OpTy = DelayedShuffle.OpTy;
2417         VectorType *RTy = DelayedShuffle.RTy;
2418         uint64_t Op0Idx = DelayedShuffle.Op0Idx;
2419         uint64_t Op1Idx = DelayedShuffle.Op1Idx;
2420         uint64_t Op2Idx = DelayedShuffle.Op2Idx;
2421         uint64_t CstNo = DelayedShuffle.CstNo;
2422         Constant *Op0 = ValueList.getConstantFwdRef(Op0Idx, OpTy);
2423         Constant *Op1 = ValueList.getConstantFwdRef(Op1Idx, OpTy);
2424         Type *ShufTy =
2425             VectorType::get(Type::getInt32Ty(Context), RTy->getElementCount());
2426         Constant *Op2 = ValueList.getConstantFwdRef(Op2Idx, ShufTy);
2427         if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
2428           return error("Invalid shufflevector operands");
2429         SmallVector<int, 16> Mask;
2430         ShuffleVectorInst::getShuffleMask(Op2, Mask);
2431         Value *V = ConstantExpr::getShuffleVector(Op0, Op1, Mask);
2432         ValueList.assignValue(V, CstNo);
2433       }
2434       for (auto &DelayedSelector : DelayedSelectors) {
2435         Type *OpTy = DelayedSelector.OpTy;
2436         Type *SelectorTy = Type::getInt1Ty(Context);
2437         uint64_t Op0Idx = DelayedSelector.Op0Idx;
2438         uint64_t Op1Idx = DelayedSelector.Op1Idx;
2439         uint64_t Op2Idx = DelayedSelector.Op2Idx;
2440         uint64_t CstNo = DelayedSelector.CstNo;
2441         Constant *Op1 = ValueList.getConstantFwdRef(Op1Idx, OpTy);
2442         Constant *Op2 = ValueList.getConstantFwdRef(Op2Idx, OpTy);
2443         // The selector might be an i1 or an <n x i1>
2444         // Get the type from the ValueList before getting a forward ref.
2445         if (VectorType *VTy = dyn_cast<VectorType>(OpTy)) {
2446           Value *V = ValueList[Op0Idx];
2447           assert(V);
2448           if (SelectorTy != V->getType())
2449             SelectorTy = VectorType::get(SelectorTy, VTy->getElementCount());
2450         }
2451         Constant *Op0 = ValueList.getConstantFwdRef(Op0Idx, SelectorTy);
2452         Value *V = ConstantExpr::getSelect(Op0, Op1, Op2);
2453         ValueList.assignValue(V, CstNo);
2454       }
2455 
2456       if (NextCstNo != ValueList.size())
2457         return error("Invalid constant reference");
2458 
2459       ValueList.resolveConstantForwardRefs();
2460       return Error::success();
2461     case BitstreamEntry::Record:
2462       // The interesting case.
2463       break;
2464     }
2465 
2466     // Read a record.
2467     Record.clear();
2468     Type *VoidType = Type::getVoidTy(Context);
2469     Value *V = nullptr;
2470     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
2471     if (!MaybeBitCode)
2472       return MaybeBitCode.takeError();
2473     switch (unsigned BitCode = MaybeBitCode.get()) {
2474     default:  // Default behavior: unknown constant
2475     case bitc::CST_CODE_UNDEF:     // UNDEF
2476       V = UndefValue::get(CurTy);
2477       break;
2478     case bitc::CST_CODE_POISON:    // POISON
2479       V = PoisonValue::get(CurTy);
2480       break;
2481     case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
2482       if (Record.empty())
2483         return error("Invalid record");
2484       if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2485         return error("Invalid record");
2486       if (TypeList[Record[0]] == VoidType)
2487         return error("Invalid constant type");
2488       CurTy = TypeList[Record[0]];
2489       CurElemTy = getElementTypeByID(Record[0]);
2490       continue;  // Skip the ValueList manipulation.
2491     case bitc::CST_CODE_NULL:      // NULL
2492       if (CurTy->isVoidTy() || CurTy->isFunctionTy() || CurTy->isLabelTy())
2493         return error("Invalid type for a constant null value");
2494       V = Constant::getNullValue(CurTy);
2495       break;
2496     case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
2497       if (!CurTy->isIntegerTy() || Record.empty())
2498         return error("Invalid record");
2499       V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2500       break;
2501     case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2502       if (!CurTy->isIntegerTy() || Record.empty())
2503         return error("Invalid record");
2504 
2505       APInt VInt =
2506           readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
2507       V = ConstantInt::get(Context, VInt);
2508 
2509       break;
2510     }
2511     case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
2512       if (Record.empty())
2513         return error("Invalid record");
2514       if (CurTy->isHalfTy())
2515         V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf(),
2516                                              APInt(16, (uint16_t)Record[0])));
2517       else if (CurTy->isBFloatTy())
2518         V = ConstantFP::get(Context, APFloat(APFloat::BFloat(),
2519                                              APInt(16, (uint32_t)Record[0])));
2520       else if (CurTy->isFloatTy())
2521         V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle(),
2522                                              APInt(32, (uint32_t)Record[0])));
2523       else if (CurTy->isDoubleTy())
2524         V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble(),
2525                                              APInt(64, Record[0])));
2526       else if (CurTy->isX86_FP80Ty()) {
2527         // Bits are not stored the same way as a normal i80 APInt, compensate.
2528         uint64_t Rearrange[2];
2529         Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2530         Rearrange[1] = Record[0] >> 48;
2531         V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended(),
2532                                              APInt(80, Rearrange)));
2533       } else if (CurTy->isFP128Ty())
2534         V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad(),
2535                                              APInt(128, Record)));
2536       else if (CurTy->isPPC_FP128Ty())
2537         V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble(),
2538                                              APInt(128, Record)));
2539       else
2540         V = UndefValue::get(CurTy);
2541       break;
2542     }
2543 
2544     case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2545       if (Record.empty())
2546         return error("Invalid record");
2547 
2548       unsigned Size = Record.size();
2549       SmallVector<Constant*, 16> Elts;
2550 
2551       if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2552         for (unsigned i = 0; i != Size; ++i)
2553           Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2554                                                      STy->getElementType(i)));
2555         V = ConstantStruct::get(STy, Elts);
2556       } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2557         Type *EltTy = ATy->getElementType();
2558         for (unsigned i = 0; i != Size; ++i)
2559           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2560         V = ConstantArray::get(ATy, Elts);
2561       } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2562         Type *EltTy = VTy->getElementType();
2563         for (unsigned i = 0; i != Size; ++i)
2564           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2565         V = ConstantVector::get(Elts);
2566       } else {
2567         V = UndefValue::get(CurTy);
2568       }
2569       break;
2570     }
2571     case bitc::CST_CODE_STRING:    // STRING: [values]
2572     case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2573       if (Record.empty())
2574         return error("Invalid record");
2575 
2576       SmallString<16> Elts(Record.begin(), Record.end());
2577       V = ConstantDataArray::getString(Context, Elts,
2578                                        BitCode == bitc::CST_CODE_CSTRING);
2579       break;
2580     }
2581     case bitc::CST_CODE_DATA: {// DATA: [n x value]
2582       if (Record.empty())
2583         return error("Invalid record");
2584 
2585       Type *EltTy;
2586       if (auto *Array = dyn_cast<ArrayType>(CurTy))
2587         EltTy = Array->getElementType();
2588       else
2589         EltTy = cast<VectorType>(CurTy)->getElementType();
2590       if (EltTy->isIntegerTy(8)) {
2591         SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2592         if (isa<VectorType>(CurTy))
2593           V = ConstantDataVector::get(Context, Elts);
2594         else
2595           V = ConstantDataArray::get(Context, Elts);
2596       } else if (EltTy->isIntegerTy(16)) {
2597         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2598         if (isa<VectorType>(CurTy))
2599           V = ConstantDataVector::get(Context, Elts);
2600         else
2601           V = ConstantDataArray::get(Context, Elts);
2602       } else if (EltTy->isIntegerTy(32)) {
2603         SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2604         if (isa<VectorType>(CurTy))
2605           V = ConstantDataVector::get(Context, Elts);
2606         else
2607           V = ConstantDataArray::get(Context, Elts);
2608       } else if (EltTy->isIntegerTy(64)) {
2609         SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2610         if (isa<VectorType>(CurTy))
2611           V = ConstantDataVector::get(Context, Elts);
2612         else
2613           V = ConstantDataArray::get(Context, Elts);
2614       } else if (EltTy->isHalfTy()) {
2615         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2616         if (isa<VectorType>(CurTy))
2617           V = ConstantDataVector::getFP(EltTy, Elts);
2618         else
2619           V = ConstantDataArray::getFP(EltTy, Elts);
2620       } else if (EltTy->isBFloatTy()) {
2621         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2622         if (isa<VectorType>(CurTy))
2623           V = ConstantDataVector::getFP(EltTy, Elts);
2624         else
2625           V = ConstantDataArray::getFP(EltTy, Elts);
2626       } else if (EltTy->isFloatTy()) {
2627         SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2628         if (isa<VectorType>(CurTy))
2629           V = ConstantDataVector::getFP(EltTy, Elts);
2630         else
2631           V = ConstantDataArray::getFP(EltTy, Elts);
2632       } else if (EltTy->isDoubleTy()) {
2633         SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2634         if (isa<VectorType>(CurTy))
2635           V = ConstantDataVector::getFP(EltTy, Elts);
2636         else
2637           V = ConstantDataArray::getFP(EltTy, Elts);
2638       } else {
2639         return error("Invalid type for value");
2640       }
2641       break;
2642     }
2643     case bitc::CST_CODE_CE_UNOP: {  // CE_UNOP: [opcode, opval]
2644       if (Record.size() < 2)
2645         return error("Invalid record");
2646       int Opc = getDecodedUnaryOpcode(Record[0], CurTy);
2647       if (Opc < 0) {
2648         V = UndefValue::get(CurTy);  // Unknown unop.
2649       } else {
2650         Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2651         unsigned Flags = 0;
2652         V = ConstantExpr::get(Opc, LHS, Flags);
2653       }
2654       break;
2655     }
2656     case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
2657       if (Record.size() < 3)
2658         return error("Invalid record");
2659       int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
2660       if (Opc < 0) {
2661         V = UndefValue::get(CurTy);  // Unknown binop.
2662       } else {
2663         Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2664         Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2665         unsigned Flags = 0;
2666         if (Record.size() >= 4) {
2667           if (Opc == Instruction::Add ||
2668               Opc == Instruction::Sub ||
2669               Opc == Instruction::Mul ||
2670               Opc == Instruction::Shl) {
2671             if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2672               Flags |= OverflowingBinaryOperator::NoSignedWrap;
2673             if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2674               Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2675           } else if (Opc == Instruction::SDiv ||
2676                      Opc == Instruction::UDiv ||
2677                      Opc == Instruction::LShr ||
2678                      Opc == Instruction::AShr) {
2679             if (Record[3] & (1 << bitc::PEO_EXACT))
2680               Flags |= SDivOperator::IsExact;
2681           }
2682         }
2683         V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2684       }
2685       break;
2686     }
2687     case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
2688       if (Record.size() < 3)
2689         return error("Invalid record");
2690       int Opc = getDecodedCastOpcode(Record[0]);
2691       if (Opc < 0) {
2692         V = UndefValue::get(CurTy);  // Unknown cast.
2693       } else {
2694         Type *OpTy = getTypeByID(Record[1]);
2695         if (!OpTy)
2696           return error("Invalid record");
2697         Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2698         V = UpgradeBitCastExpr(Opc, Op, CurTy);
2699         if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2700       }
2701       break;
2702     }
2703     case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands]
2704     case bitc::CST_CODE_CE_GEP: // [ty, n x operands]
2705     case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX: { // [ty, flags, n x
2706                                                      // operands]
2707       if (Record.size() < 2)
2708         return error("Constant GEP record must have at least two elements");
2709       unsigned OpNum = 0;
2710       Type *PointeeType = nullptr;
2711       if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX ||
2712           Record.size() % 2)
2713         PointeeType = getTypeByID(Record[OpNum++]);
2714 
2715       bool InBounds = false;
2716       Optional<unsigned> InRangeIndex;
2717       if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX) {
2718         uint64_t Op = Record[OpNum++];
2719         InBounds = Op & 1;
2720         InRangeIndex = Op >> 1;
2721       } else if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
2722         InBounds = true;
2723 
2724       SmallVector<Constant*, 16> Elts;
2725       Type *Elt0FullTy = nullptr;
2726       while (OpNum != Record.size()) {
2727         if (!Elt0FullTy)
2728           Elt0FullTy = getTypeByID(Record[OpNum]);
2729         Type *ElTy = getTypeByID(Record[OpNum++]);
2730         if (!ElTy)
2731           return error("Invalid record");
2732         Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2733       }
2734 
2735       if (Elts.size() < 1)
2736         return error("Invalid gep with no operands");
2737 
2738       PointerType *OrigPtrTy = cast<PointerType>(Elt0FullTy->getScalarType());
2739       if (!PointeeType)
2740         PointeeType = OrigPtrTy->getPointerElementType();
2741       else if (!OrigPtrTy->isOpaqueOrPointeeTypeMatches(PointeeType))
2742         return error("Explicit gep operator type does not match pointee type "
2743                      "of pointer operand");
2744 
2745       ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2746       V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2747                                          InBounds, InRangeIndex);
2748       break;
2749     }
2750     case bitc::CST_CODE_CE_SELECT: {  // CE_SELECT: [opval#, opval#, opval#]
2751       if (Record.size() < 3)
2752         return error("Invalid record");
2753 
2754       DelayedSelectors.push_back(
2755           {CurTy, Record[0], Record[1], Record[2], NextCstNo});
2756       (void)ValueList.getConstantFwdRef(NextCstNo, CurTy);
2757       ++NextCstNo;
2758       continue;
2759     }
2760     case bitc::CST_CODE_CE_EXTRACTELT
2761         : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2762       if (Record.size() < 3)
2763         return error("Invalid record");
2764       VectorType *OpTy =
2765         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2766       if (!OpTy)
2767         return error("Invalid record");
2768       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2769       Constant *Op1 = nullptr;
2770       if (Record.size() == 4) {
2771         Type *IdxTy = getTypeByID(Record[2]);
2772         if (!IdxTy)
2773           return error("Invalid record");
2774         Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2775       } else {
2776         // Deprecated, but still needed to read old bitcode files.
2777         Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2778       }
2779       if (!Op1)
2780         return error("Invalid record");
2781       V = ConstantExpr::getExtractElement(Op0, Op1);
2782       break;
2783     }
2784     case bitc::CST_CODE_CE_INSERTELT
2785         : { // CE_INSERTELT: [opval, opval, opty, opval]
2786       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2787       if (Record.size() < 3 || !OpTy)
2788         return error("Invalid record");
2789       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2790       Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2791                                                   OpTy->getElementType());
2792       Constant *Op2 = nullptr;
2793       if (Record.size() == 4) {
2794         Type *IdxTy = getTypeByID(Record[2]);
2795         if (!IdxTy)
2796           return error("Invalid record");
2797         Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2798       } else {
2799         // Deprecated, but still needed to read old bitcode files.
2800         Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2801       }
2802       if (!Op2)
2803         return error("Invalid record");
2804       V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2805       break;
2806     }
2807     case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2808       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2809       if (Record.size() < 3 || !OpTy)
2810         return error("Invalid record");
2811       DelayedShuffles.push_back(
2812           {OpTy, OpTy, Record[0], Record[1], Record[2], NextCstNo});
2813       ++NextCstNo;
2814       continue;
2815     }
2816     case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2817       VectorType *RTy = dyn_cast<VectorType>(CurTy);
2818       VectorType *OpTy =
2819         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2820       if (Record.size() < 4 || !RTy || !OpTy)
2821         return error("Invalid record");
2822       DelayedShuffles.push_back(
2823           {OpTy, RTy, Record[1], Record[2], Record[3], NextCstNo});
2824       ++NextCstNo;
2825       continue;
2826     }
2827     case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
2828       if (Record.size() < 4)
2829         return error("Invalid record");
2830       Type *OpTy = getTypeByID(Record[0]);
2831       if (!OpTy)
2832         return error("Invalid record");
2833       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2834       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2835 
2836       if (OpTy->isFPOrFPVectorTy())
2837         V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2838       else
2839         V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2840       break;
2841     }
2842     // This maintains backward compatibility, pre-asm dialect keywords.
2843     // Deprecated, but still needed to read old bitcode files.
2844     case bitc::CST_CODE_INLINEASM_OLD: {
2845       if (Record.size() < 2)
2846         return error("Invalid record");
2847       std::string AsmStr, ConstrStr;
2848       bool HasSideEffects = Record[0] & 1;
2849       bool IsAlignStack = Record[0] >> 1;
2850       unsigned AsmStrSize = Record[1];
2851       if (2+AsmStrSize >= Record.size())
2852         return error("Invalid record");
2853       unsigned ConstStrSize = Record[2+AsmStrSize];
2854       if (3+AsmStrSize+ConstStrSize > Record.size())
2855         return error("Invalid record");
2856 
2857       for (unsigned i = 0; i != AsmStrSize; ++i)
2858         AsmStr += (char)Record[2+i];
2859       for (unsigned i = 0; i != ConstStrSize; ++i)
2860         ConstrStr += (char)Record[3+AsmStrSize+i];
2861       UpgradeInlineAsmString(&AsmStr);
2862       if (!CurElemTy)
2863         return error("Missing element type for old-style inlineasm");
2864       V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr,
2865                          HasSideEffects, IsAlignStack);
2866       break;
2867     }
2868     // This version adds support for the asm dialect keywords (e.g.,
2869     // inteldialect).
2870     case bitc::CST_CODE_INLINEASM_OLD2: {
2871       if (Record.size() < 2)
2872         return error("Invalid record");
2873       std::string AsmStr, ConstrStr;
2874       bool HasSideEffects = Record[0] & 1;
2875       bool IsAlignStack = (Record[0] >> 1) & 1;
2876       unsigned AsmDialect = Record[0] >> 2;
2877       unsigned AsmStrSize = Record[1];
2878       if (2+AsmStrSize >= Record.size())
2879         return error("Invalid record");
2880       unsigned ConstStrSize = Record[2+AsmStrSize];
2881       if (3+AsmStrSize+ConstStrSize > Record.size())
2882         return error("Invalid record");
2883 
2884       for (unsigned i = 0; i != AsmStrSize; ++i)
2885         AsmStr += (char)Record[2+i];
2886       for (unsigned i = 0; i != ConstStrSize; ++i)
2887         ConstrStr += (char)Record[3+AsmStrSize+i];
2888       UpgradeInlineAsmString(&AsmStr);
2889       if (!CurElemTy)
2890         return error("Missing element type for old-style inlineasm");
2891       V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr,
2892                          HasSideEffects, IsAlignStack,
2893                          InlineAsm::AsmDialect(AsmDialect));
2894       break;
2895     }
2896     // This version adds support for the unwind keyword.
2897     case bitc::CST_CODE_INLINEASM_OLD3: {
2898       if (Record.size() < 2)
2899         return error("Invalid record");
2900       unsigned OpNum = 0;
2901       std::string AsmStr, ConstrStr;
2902       bool HasSideEffects = Record[OpNum] & 1;
2903       bool IsAlignStack = (Record[OpNum] >> 1) & 1;
2904       unsigned AsmDialect = (Record[OpNum] >> 2) & 1;
2905       bool CanThrow = (Record[OpNum] >> 3) & 1;
2906       ++OpNum;
2907       unsigned AsmStrSize = Record[OpNum];
2908       ++OpNum;
2909       if (OpNum + AsmStrSize >= Record.size())
2910         return error("Invalid record");
2911       unsigned ConstStrSize = Record[OpNum + AsmStrSize];
2912       if (OpNum + 1 + AsmStrSize + ConstStrSize > Record.size())
2913         return error("Invalid record");
2914 
2915       for (unsigned i = 0; i != AsmStrSize; ++i)
2916         AsmStr += (char)Record[OpNum + i];
2917       ++OpNum;
2918       for (unsigned i = 0; i != ConstStrSize; ++i)
2919         ConstrStr += (char)Record[OpNum + AsmStrSize + i];
2920       UpgradeInlineAsmString(&AsmStr);
2921       if (!CurElemTy)
2922         return error("Missing element type for old-style inlineasm");
2923       V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr,
2924                          HasSideEffects, IsAlignStack,
2925                          InlineAsm::AsmDialect(AsmDialect), CanThrow);
2926       break;
2927     }
2928     // This version adds explicit function type.
2929     case bitc::CST_CODE_INLINEASM: {
2930       if (Record.size() < 3)
2931         return error("Invalid record");
2932       unsigned OpNum = 0;
2933       auto *FnTy = dyn_cast_or_null<FunctionType>(getTypeByID(Record[OpNum]));
2934       ++OpNum;
2935       if (!FnTy)
2936         return error("Invalid record");
2937       std::string AsmStr, ConstrStr;
2938       bool HasSideEffects = Record[OpNum] & 1;
2939       bool IsAlignStack = (Record[OpNum] >> 1) & 1;
2940       unsigned AsmDialect = (Record[OpNum] >> 2) & 1;
2941       bool CanThrow = (Record[OpNum] >> 3) & 1;
2942       ++OpNum;
2943       unsigned AsmStrSize = Record[OpNum];
2944       ++OpNum;
2945       if (OpNum + AsmStrSize >= Record.size())
2946         return error("Invalid record");
2947       unsigned ConstStrSize = Record[OpNum + AsmStrSize];
2948       if (OpNum + 1 + AsmStrSize + ConstStrSize > Record.size())
2949         return error("Invalid record");
2950 
2951       for (unsigned i = 0; i != AsmStrSize; ++i)
2952         AsmStr += (char)Record[OpNum + i];
2953       ++OpNum;
2954       for (unsigned i = 0; i != ConstStrSize; ++i)
2955         ConstrStr += (char)Record[OpNum + AsmStrSize + i];
2956       UpgradeInlineAsmString(&AsmStr);
2957       V = InlineAsm::get(FnTy, AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2958                          InlineAsm::AsmDialect(AsmDialect), CanThrow);
2959       break;
2960     }
2961     case bitc::CST_CODE_BLOCKADDRESS:{
2962       if (Record.size() < 3)
2963         return error("Invalid record");
2964       Type *FnTy = getTypeByID(Record[0]);
2965       if (!FnTy)
2966         return error("Invalid record");
2967       Function *Fn =
2968         dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2969       if (!Fn)
2970         return error("Invalid record");
2971 
2972       // If the function is already parsed we can insert the block address right
2973       // away.
2974       BasicBlock *BB;
2975       unsigned BBID = Record[2];
2976       if (!BBID)
2977         // Invalid reference to entry block.
2978         return error("Invalid ID");
2979       if (!Fn->empty()) {
2980         Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2981         for (size_t I = 0, E = BBID; I != E; ++I) {
2982           if (BBI == BBE)
2983             return error("Invalid ID");
2984           ++BBI;
2985         }
2986         BB = &*BBI;
2987       } else {
2988         // Otherwise insert a placeholder and remember it so it can be inserted
2989         // when the function is parsed.
2990         auto &FwdBBs = BasicBlockFwdRefs[Fn];
2991         if (FwdBBs.empty())
2992           BasicBlockFwdRefQueue.push_back(Fn);
2993         if (FwdBBs.size() < BBID + 1)
2994           FwdBBs.resize(BBID + 1);
2995         if (!FwdBBs[BBID])
2996           FwdBBs[BBID] = BasicBlock::Create(Context);
2997         BB = FwdBBs[BBID];
2998       }
2999       V = BlockAddress::get(Fn, BB);
3000       break;
3001     }
3002     case bitc::CST_CODE_DSO_LOCAL_EQUIVALENT: {
3003       if (Record.size() < 2)
3004         return error("Invalid record");
3005       Type *GVTy = getTypeByID(Record[0]);
3006       if (!GVTy)
3007         return error("Invalid record");
3008       GlobalValue *GV = dyn_cast_or_null<GlobalValue>(
3009           ValueList.getConstantFwdRef(Record[1], GVTy));
3010       if (!GV)
3011         return error("Invalid record");
3012 
3013       V = DSOLocalEquivalent::get(GV);
3014       break;
3015     }
3016     case bitc::CST_CODE_NO_CFI_VALUE: {
3017       if (Record.size() < 2)
3018         return error("Invalid record");
3019       Type *GVTy = getTypeByID(Record[0]);
3020       if (!GVTy)
3021         return error("Invalid record");
3022       GlobalValue *GV = dyn_cast_or_null<GlobalValue>(
3023           ValueList.getConstantFwdRef(Record[1], GVTy));
3024       if (!GV)
3025         return error("Invalid record");
3026       V = NoCFIValue::get(GV);
3027       break;
3028     }
3029     }
3030 
3031     ValueList.assignValue(V, NextCstNo);
3032     ++NextCstNo;
3033   }
3034 }
3035 
3036 Error BitcodeReader::parseUseLists() {
3037   if (Error Err = Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
3038     return Err;
3039 
3040   // Read all the records.
3041   SmallVector<uint64_t, 64> Record;
3042 
3043   while (true) {
3044     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
3045     if (!MaybeEntry)
3046       return MaybeEntry.takeError();
3047     BitstreamEntry Entry = MaybeEntry.get();
3048 
3049     switch (Entry.Kind) {
3050     case BitstreamEntry::SubBlock: // Handled for us already.
3051     case BitstreamEntry::Error:
3052       return error("Malformed block");
3053     case BitstreamEntry::EndBlock:
3054       return Error::success();
3055     case BitstreamEntry::Record:
3056       // The interesting case.
3057       break;
3058     }
3059 
3060     // Read a use list record.
3061     Record.clear();
3062     bool IsBB = false;
3063     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
3064     if (!MaybeRecord)
3065       return MaybeRecord.takeError();
3066     switch (MaybeRecord.get()) {
3067     default:  // Default behavior: unknown type.
3068       break;
3069     case bitc::USELIST_CODE_BB:
3070       IsBB = true;
3071       LLVM_FALLTHROUGH;
3072     case bitc::USELIST_CODE_DEFAULT: {
3073       unsigned RecordLength = Record.size();
3074       if (RecordLength < 3)
3075         // Records should have at least an ID and two indexes.
3076         return error("Invalid record");
3077       unsigned ID = Record.pop_back_val();
3078 
3079       Value *V;
3080       if (IsBB) {
3081         assert(ID < FunctionBBs.size() && "Basic block not found");
3082         V = FunctionBBs[ID];
3083       } else
3084         V = ValueList[ID];
3085       unsigned NumUses = 0;
3086       SmallDenseMap<const Use *, unsigned, 16> Order;
3087       for (const Use &U : V->materialized_uses()) {
3088         if (++NumUses > Record.size())
3089           break;
3090         Order[&U] = Record[NumUses - 1];
3091       }
3092       if (Order.size() != Record.size() || NumUses > Record.size())
3093         // Mismatches can happen if the functions are being materialized lazily
3094         // (out-of-order), or a value has been upgraded.
3095         break;
3096 
3097       V->sortUseList([&](const Use &L, const Use &R) {
3098         return Order.lookup(&L) < Order.lookup(&R);
3099       });
3100       break;
3101     }
3102     }
3103   }
3104 }
3105 
3106 /// When we see the block for metadata, remember where it is and then skip it.
3107 /// This lets us lazily deserialize the metadata.
3108 Error BitcodeReader::rememberAndSkipMetadata() {
3109   // Save the current stream state.
3110   uint64_t CurBit = Stream.GetCurrentBitNo();
3111   DeferredMetadataInfo.push_back(CurBit);
3112 
3113   // Skip over the block for now.
3114   if (Error Err = Stream.SkipBlock())
3115     return Err;
3116   return Error::success();
3117 }
3118 
3119 Error BitcodeReader::materializeMetadata() {
3120   for (uint64_t BitPos : DeferredMetadataInfo) {
3121     // Move the bit stream to the saved position.
3122     if (Error JumpFailed = Stream.JumpToBit(BitPos))
3123       return JumpFailed;
3124     if (Error Err = MDLoader->parseModuleMetadata())
3125       return Err;
3126   }
3127 
3128   // Upgrade "Linker Options" module flag to "llvm.linker.options" module-level
3129   // metadata. Only upgrade if the new option doesn't exist to avoid upgrade
3130   // multiple times.
3131   if (!TheModule->getNamedMetadata("llvm.linker.options")) {
3132     if (Metadata *Val = TheModule->getModuleFlag("Linker Options")) {
3133       NamedMDNode *LinkerOpts =
3134           TheModule->getOrInsertNamedMetadata("llvm.linker.options");
3135       for (const MDOperand &MDOptions : cast<MDNode>(Val)->operands())
3136         LinkerOpts->addOperand(cast<MDNode>(MDOptions));
3137     }
3138   }
3139 
3140   DeferredMetadataInfo.clear();
3141   return Error::success();
3142 }
3143 
3144 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
3145 
3146 /// When we see the block for a function body, remember where it is and then
3147 /// skip it.  This lets us lazily deserialize the functions.
3148 Error BitcodeReader::rememberAndSkipFunctionBody() {
3149   // Get the function we are talking about.
3150   if (FunctionsWithBodies.empty())
3151     return error("Insufficient function protos");
3152 
3153   Function *Fn = FunctionsWithBodies.back();
3154   FunctionsWithBodies.pop_back();
3155 
3156   // Save the current stream state.
3157   uint64_t CurBit = Stream.GetCurrentBitNo();
3158   assert(
3159       (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
3160       "Mismatch between VST and scanned function offsets");
3161   DeferredFunctionInfo[Fn] = CurBit;
3162 
3163   // Skip over the function block for now.
3164   if (Error Err = Stream.SkipBlock())
3165     return Err;
3166   return Error::success();
3167 }
3168 
3169 Error BitcodeReader::globalCleanup() {
3170   // Patch the initializers for globals and aliases up.
3171   if (Error Err = resolveGlobalAndIndirectSymbolInits())
3172     return Err;
3173   if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
3174     return error("Malformed global initializer set");
3175 
3176   // Look for intrinsic functions which need to be upgraded at some point
3177   // and functions that need to have their function attributes upgraded.
3178   for (Function &F : *TheModule) {
3179     MDLoader->upgradeDebugIntrinsics(F);
3180     Function *NewFn;
3181     if (UpgradeIntrinsicFunction(&F, NewFn))
3182       UpgradedIntrinsics[&F] = NewFn;
3183     else if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F))
3184       // Some types could be renamed during loading if several modules are
3185       // loaded in the same LLVMContext (LTO scenario). In this case we should
3186       // remangle intrinsics names as well.
3187       RemangledIntrinsics[&F] = Remangled.getValue();
3188     // Look for functions that rely on old function attribute behavior.
3189     UpgradeFunctionAttributes(F);
3190   }
3191 
3192   // Look for global variables which need to be renamed.
3193   std::vector<std::pair<GlobalVariable *, GlobalVariable *>> UpgradedVariables;
3194   for (GlobalVariable &GV : TheModule->globals())
3195     if (GlobalVariable *Upgraded = UpgradeGlobalVariable(&GV))
3196       UpgradedVariables.emplace_back(&GV, Upgraded);
3197   for (auto &Pair : UpgradedVariables) {
3198     Pair.first->eraseFromParent();
3199     TheModule->getGlobalList().push_back(Pair.second);
3200   }
3201 
3202   // Force deallocation of memory for these vectors to favor the client that
3203   // want lazy deserialization.
3204   std::vector<std::pair<GlobalVariable *, unsigned>>().swap(GlobalInits);
3205   std::vector<std::pair<GlobalValue *, unsigned>>().swap(IndirectSymbolInits);
3206   return Error::success();
3207 }
3208 
3209 /// Support for lazy parsing of function bodies. This is required if we
3210 /// either have an old bitcode file without a VST forward declaration record,
3211 /// or if we have an anonymous function being materialized, since anonymous
3212 /// functions do not have a name and are therefore not in the VST.
3213 Error BitcodeReader::rememberAndSkipFunctionBodies() {
3214   if (Error JumpFailed = Stream.JumpToBit(NextUnreadBit))
3215     return JumpFailed;
3216 
3217   if (Stream.AtEndOfStream())
3218     return error("Could not find function in stream");
3219 
3220   if (!SeenFirstFunctionBody)
3221     return error("Trying to materialize functions before seeing function blocks");
3222 
3223   // An old bitcode file with the symbol table at the end would have
3224   // finished the parse greedily.
3225   assert(SeenValueSymbolTable);
3226 
3227   SmallVector<uint64_t, 64> Record;
3228 
3229   while (true) {
3230     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3231     if (!MaybeEntry)
3232       return MaybeEntry.takeError();
3233     llvm::BitstreamEntry Entry = MaybeEntry.get();
3234 
3235     switch (Entry.Kind) {
3236     default:
3237       return error("Expect SubBlock");
3238     case BitstreamEntry::SubBlock:
3239       switch (Entry.ID) {
3240       default:
3241         return error("Expect function block");
3242       case bitc::FUNCTION_BLOCK_ID:
3243         if (Error Err = rememberAndSkipFunctionBody())
3244           return Err;
3245         NextUnreadBit = Stream.GetCurrentBitNo();
3246         return Error::success();
3247       }
3248     }
3249   }
3250 }
3251 
3252 Error BitcodeReaderBase::readBlockInfo() {
3253   Expected<Optional<BitstreamBlockInfo>> MaybeNewBlockInfo =
3254       Stream.ReadBlockInfoBlock();
3255   if (!MaybeNewBlockInfo)
3256     return MaybeNewBlockInfo.takeError();
3257   Optional<BitstreamBlockInfo> NewBlockInfo =
3258       std::move(MaybeNewBlockInfo.get());
3259   if (!NewBlockInfo)
3260     return error("Malformed block");
3261   BlockInfo = std::move(*NewBlockInfo);
3262   return Error::success();
3263 }
3264 
3265 Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) {
3266   // v1: [selection_kind, name]
3267   // v2: [strtab_offset, strtab_size, selection_kind]
3268   StringRef Name;
3269   std::tie(Name, Record) = readNameFromStrtab(Record);
3270 
3271   if (Record.empty())
3272     return error("Invalid record");
3273   Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
3274   std::string OldFormatName;
3275   if (!UseStrtab) {
3276     if (Record.size() < 2)
3277       return error("Invalid record");
3278     unsigned ComdatNameSize = Record[1];
3279     if (ComdatNameSize > Record.size() - 2)
3280       return error("Comdat name size too large");
3281     OldFormatName.reserve(ComdatNameSize);
3282     for (unsigned i = 0; i != ComdatNameSize; ++i)
3283       OldFormatName += (char)Record[2 + i];
3284     Name = OldFormatName;
3285   }
3286   Comdat *C = TheModule->getOrInsertComdat(Name);
3287   C->setSelectionKind(SK);
3288   ComdatList.push_back(C);
3289   return Error::success();
3290 }
3291 
3292 static void inferDSOLocal(GlobalValue *GV) {
3293   // infer dso_local from linkage and visibility if it is not encoded.
3294   if (GV->hasLocalLinkage() ||
3295       (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage()))
3296     GV->setDSOLocal(true);
3297 }
3298 
3299 Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) {
3300   // v1: [pointer type, isconst, initid, linkage, alignment, section,
3301   // visibility, threadlocal, unnamed_addr, externally_initialized,
3302   // dllstorageclass, comdat, attributes, preemption specifier,
3303   // partition strtab offset, partition strtab size] (name in VST)
3304   // v2: [strtab_offset, strtab_size, v1]
3305   StringRef Name;
3306   std::tie(Name, Record) = readNameFromStrtab(Record);
3307 
3308   if (Record.size() < 6)
3309     return error("Invalid record");
3310   Type *Ty = getTypeByID(Record[0]);
3311   if (!Ty)
3312     return error("Invalid record");
3313   bool isConstant = Record[1] & 1;
3314   bool explicitType = Record[1] & 2;
3315   unsigned AddressSpace;
3316   if (explicitType) {
3317     AddressSpace = Record[1] >> 2;
3318   } else {
3319     if (!Ty->isPointerTy())
3320       return error("Invalid type for value");
3321     AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
3322     Ty = getElementTypeByID(Record[0]);
3323     if (!Ty)
3324       return error("Missing element type for old-style global");
3325   }
3326 
3327   uint64_t RawLinkage = Record[3];
3328   GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
3329   MaybeAlign Alignment;
3330   if (Error Err = parseAlignmentValue(Record[4], Alignment))
3331     return Err;
3332   std::string Section;
3333   if (Record[5]) {
3334     if (Record[5] - 1 >= SectionTable.size())
3335       return error("Invalid ID");
3336     Section = SectionTable[Record[5] - 1];
3337   }
3338   GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
3339   // Local linkage must have default visibility.
3340   // auto-upgrade `hidden` and `protected` for old bitcode.
3341   if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
3342     Visibility = getDecodedVisibility(Record[6]);
3343 
3344   GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
3345   if (Record.size() > 7)
3346     TLM = getDecodedThreadLocalMode(Record[7]);
3347 
3348   GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
3349   if (Record.size() > 8)
3350     UnnamedAddr = getDecodedUnnamedAddrType(Record[8]);
3351 
3352   bool ExternallyInitialized = false;
3353   if (Record.size() > 9)
3354     ExternallyInitialized = Record[9];
3355 
3356   GlobalVariable *NewGV =
3357       new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, Name,
3358                          nullptr, TLM, AddressSpace, ExternallyInitialized);
3359   NewGV->setAlignment(Alignment);
3360   if (!Section.empty())
3361     NewGV->setSection(Section);
3362   NewGV->setVisibility(Visibility);
3363   NewGV->setUnnamedAddr(UnnamedAddr);
3364 
3365   if (Record.size() > 10)
3366     NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
3367   else
3368     upgradeDLLImportExportLinkage(NewGV, RawLinkage);
3369 
3370   ValueList.push_back(NewGV);
3371 
3372   // Remember which value to use for the global initializer.
3373   if (unsigned InitID = Record[2])
3374     GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));
3375 
3376   if (Record.size() > 11) {
3377     if (unsigned ComdatID = Record[11]) {
3378       if (ComdatID > ComdatList.size())
3379         return error("Invalid global variable comdat ID");
3380       NewGV->setComdat(ComdatList[ComdatID - 1]);
3381     }
3382   } else if (hasImplicitComdat(RawLinkage)) {
3383     ImplicitComdatObjects.insert(NewGV);
3384   }
3385 
3386   if (Record.size() > 12) {
3387     auto AS = getAttributes(Record[12]).getFnAttrs();
3388     NewGV->setAttributes(AS);
3389   }
3390 
3391   if (Record.size() > 13) {
3392     NewGV->setDSOLocal(getDecodedDSOLocal(Record[13]));
3393   }
3394   inferDSOLocal(NewGV);
3395 
3396   // Check whether we have enough values to read a partition name.
3397   if (Record.size() > 15)
3398     NewGV->setPartition(StringRef(Strtab.data() + Record[14], Record[15]));
3399 
3400   return Error::success();
3401 }
3402 
3403 Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) {
3404   // v1: [type, callingconv, isproto, linkage, paramattr, alignment, section,
3405   // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat,
3406   // prefixdata,  personalityfn, preemption specifier, addrspace] (name in VST)
3407   // v2: [strtab_offset, strtab_size, v1]
3408   StringRef Name;
3409   std::tie(Name, Record) = readNameFromStrtab(Record);
3410 
3411   if (Record.size() < 8)
3412     return error("Invalid record");
3413   Type *FTy = getTypeByID(Record[0]);
3414   if (!FTy)
3415     return error("Invalid record");
3416   if (isa<PointerType>(FTy)) {
3417     FTy = getElementTypeByID(Record[0]);
3418     if (!FTy)
3419       return error("Missing element type for old-style function");
3420   }
3421 
3422   if (!isa<FunctionType>(FTy))
3423     return error("Invalid type for value");
3424   auto CC = static_cast<CallingConv::ID>(Record[1]);
3425   if (CC & ~CallingConv::MaxID)
3426     return error("Invalid calling convention ID");
3427 
3428   unsigned AddrSpace = TheModule->getDataLayout().getProgramAddressSpace();
3429   if (Record.size() > 16)
3430     AddrSpace = Record[16];
3431 
3432   Function *Func =
3433       Function::Create(cast<FunctionType>(FTy), GlobalValue::ExternalLinkage,
3434                        AddrSpace, Name, TheModule);
3435 
3436   assert(Func->getFunctionType() == FTy &&
3437          "Incorrect fully specified type provided for function");
3438   FunctionTypes[Func] = cast<FunctionType>(FTy);
3439 
3440   Func->setCallingConv(CC);
3441   bool isProto = Record[2];
3442   uint64_t RawLinkage = Record[3];
3443   Func->setLinkage(getDecodedLinkage(RawLinkage));
3444   Func->setAttributes(getAttributes(Record[4]));
3445 
3446   // Upgrade any old-style byval or sret without a type by propagating the
3447   // argument's pointee type. There should be no opaque pointers where the byval
3448   // type is implicit.
3449   for (unsigned i = 0; i != Func->arg_size(); ++i) {
3450     for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
3451                                      Attribute::InAlloca}) {
3452       if (!Func->hasParamAttribute(i, Kind))
3453         continue;
3454 
3455       if (Func->getParamAttribute(i, Kind).getValueAsType())
3456         continue;
3457 
3458       Func->removeParamAttr(i, Kind);
3459 
3460       Type *PTy = cast<FunctionType>(FTy)->getParamType(i);
3461       Type *PtrEltTy = PTy->getPointerElementType();
3462       Attribute NewAttr;
3463       switch (Kind) {
3464       case Attribute::ByVal:
3465         NewAttr = Attribute::getWithByValType(Context, PtrEltTy);
3466         break;
3467       case Attribute::StructRet:
3468         NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy);
3469         break;
3470       case Attribute::InAlloca:
3471         NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy);
3472         break;
3473       default:
3474         llvm_unreachable("not an upgraded type attribute");
3475       }
3476 
3477       Func->addParamAttr(i, NewAttr);
3478     }
3479   }
3480 
3481   MaybeAlign Alignment;
3482   if (Error Err = parseAlignmentValue(Record[5], Alignment))
3483     return Err;
3484   Func->setAlignment(Alignment);
3485   if (Record[6]) {
3486     if (Record[6] - 1 >= SectionTable.size())
3487       return error("Invalid ID");
3488     Func->setSection(SectionTable[Record[6] - 1]);
3489   }
3490   // Local linkage must have default visibility.
3491   // auto-upgrade `hidden` and `protected` for old bitcode.
3492   if (!Func->hasLocalLinkage())
3493     Func->setVisibility(getDecodedVisibility(Record[7]));
3494   if (Record.size() > 8 && Record[8]) {
3495     if (Record[8] - 1 >= GCTable.size())
3496       return error("Invalid ID");
3497     Func->setGC(GCTable[Record[8] - 1]);
3498   }
3499   GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
3500   if (Record.size() > 9)
3501     UnnamedAddr = getDecodedUnnamedAddrType(Record[9]);
3502   Func->setUnnamedAddr(UnnamedAddr);
3503 
3504   FunctionOperandInfo OperandInfo = {Func, 0, 0, 0};
3505   if (Record.size() > 10)
3506     OperandInfo.Prologue = Record[10];
3507 
3508   if (Record.size() > 11)
3509     Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
3510   else
3511     upgradeDLLImportExportLinkage(Func, RawLinkage);
3512 
3513   if (Record.size() > 12) {
3514     if (unsigned ComdatID = Record[12]) {
3515       if (ComdatID > ComdatList.size())
3516         return error("Invalid function comdat ID");
3517       Func->setComdat(ComdatList[ComdatID - 1]);
3518     }
3519   } else if (hasImplicitComdat(RawLinkage)) {
3520     ImplicitComdatObjects.insert(Func);
3521   }
3522 
3523   if (Record.size() > 13)
3524     OperandInfo.Prefix = Record[13];
3525 
3526   if (Record.size() > 14)
3527     OperandInfo.PersonalityFn = Record[14];
3528 
3529   if (Record.size() > 15) {
3530     Func->setDSOLocal(getDecodedDSOLocal(Record[15]));
3531   }
3532   inferDSOLocal(Func);
3533 
3534   // Record[16] is the address space number.
3535 
3536   // Check whether we have enough values to read a partition name. Also make
3537   // sure Strtab has enough values.
3538   if (Record.size() > 18 && Strtab.data() &&
3539       Record[17] + Record[18] <= Strtab.size()) {
3540     Func->setPartition(StringRef(Strtab.data() + Record[17], Record[18]));
3541   }
3542 
3543   ValueList.push_back(Func);
3544 
3545   if (OperandInfo.PersonalityFn || OperandInfo.Prefix || OperandInfo.Prologue)
3546     FunctionOperands.push_back(OperandInfo);
3547 
3548   // If this is a function with a body, remember the prototype we are
3549   // creating now, so that we can match up the body with them later.
3550   if (!isProto) {
3551     Func->setIsMaterializable(true);
3552     FunctionsWithBodies.push_back(Func);
3553     DeferredFunctionInfo[Func] = 0;
3554   }
3555   return Error::success();
3556 }
3557 
3558 Error BitcodeReader::parseGlobalIndirectSymbolRecord(
3559     unsigned BitCode, ArrayRef<uint64_t> Record) {
3560   // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST)
3561   // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
3562   // dllstorageclass, threadlocal, unnamed_addr,
3563   // preemption specifier] (name in VST)
3564   // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage,
3565   // visibility, dllstorageclass, threadlocal, unnamed_addr,
3566   // preemption specifier] (name in VST)
3567   // v2: [strtab_offset, strtab_size, v1]
3568   StringRef Name;
3569   std::tie(Name, Record) = readNameFromStrtab(Record);
3570 
3571   bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
3572   if (Record.size() < (3 + (unsigned)NewRecord))
3573     return error("Invalid record");
3574   unsigned OpNum = 0;
3575   unsigned TypeID = Record[OpNum++];
3576   Type *Ty = getTypeByID(TypeID);
3577   if (!Ty)
3578     return error("Invalid record");
3579 
3580   unsigned AddrSpace;
3581   if (!NewRecord) {
3582     auto *PTy = dyn_cast<PointerType>(Ty);
3583     if (!PTy)
3584       return error("Invalid type for value");
3585     AddrSpace = PTy->getAddressSpace();
3586     Ty = getElementTypeByID(TypeID);
3587     if (!Ty)
3588       return error("Missing element type for old-style indirect symbol");
3589   } else {
3590     AddrSpace = Record[OpNum++];
3591   }
3592 
3593   auto Val = Record[OpNum++];
3594   auto Linkage = Record[OpNum++];
3595   GlobalValue *NewGA;
3596   if (BitCode == bitc::MODULE_CODE_ALIAS ||
3597       BitCode == bitc::MODULE_CODE_ALIAS_OLD)
3598     NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
3599                                 TheModule);
3600   else
3601     NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
3602                                 nullptr, TheModule);
3603 
3604   // Local linkage must have default visibility.
3605   // auto-upgrade `hidden` and `protected` for old bitcode.
3606   if (OpNum != Record.size()) {
3607     auto VisInd = OpNum++;
3608     if (!NewGA->hasLocalLinkage())
3609       NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
3610   }
3611   if (BitCode == bitc::MODULE_CODE_ALIAS ||
3612       BitCode == bitc::MODULE_CODE_ALIAS_OLD) {
3613     if (OpNum != Record.size())
3614       NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
3615     else
3616       upgradeDLLImportExportLinkage(NewGA, Linkage);
3617     if (OpNum != Record.size())
3618       NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
3619     if (OpNum != Record.size())
3620       NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++]));
3621   }
3622   if (OpNum != Record.size())
3623     NewGA->setDSOLocal(getDecodedDSOLocal(Record[OpNum++]));
3624   inferDSOLocal(NewGA);
3625 
3626   // Check whether we have enough values to read a partition name.
3627   if (OpNum + 1 < Record.size()) {
3628     NewGA->setPartition(
3629         StringRef(Strtab.data() + Record[OpNum], Record[OpNum + 1]));
3630     OpNum += 2;
3631   }
3632 
3633   ValueList.push_back(NewGA);
3634   IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
3635   return Error::success();
3636 }
3637 
3638 Error BitcodeReader::parseModule(uint64_t ResumeBit,
3639                                  bool ShouldLazyLoadMetadata,
3640                                  DataLayoutCallbackTy DataLayoutCallback) {
3641   if (ResumeBit) {
3642     if (Error JumpFailed = Stream.JumpToBit(ResumeBit))
3643       return JumpFailed;
3644   } else if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3645     return Err;
3646 
3647   SmallVector<uint64_t, 64> Record;
3648 
3649   // Parts of bitcode parsing depend on the datalayout.  Make sure we
3650   // finalize the datalayout before we run any of that code.
3651   bool ResolvedDataLayout = false;
3652   auto ResolveDataLayout = [&] {
3653     if (ResolvedDataLayout)
3654       return;
3655 
3656     // datalayout and triple can't be parsed after this point.
3657     ResolvedDataLayout = true;
3658 
3659     // Upgrade data layout string.
3660     std::string DL = llvm::UpgradeDataLayoutString(
3661         TheModule->getDataLayoutStr(), TheModule->getTargetTriple());
3662     TheModule->setDataLayout(DL);
3663 
3664     if (auto LayoutOverride =
3665             DataLayoutCallback(TheModule->getTargetTriple()))
3666       TheModule->setDataLayout(*LayoutOverride);
3667   };
3668 
3669   // Read all the records for this module.
3670   while (true) {
3671     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3672     if (!MaybeEntry)
3673       return MaybeEntry.takeError();
3674     llvm::BitstreamEntry Entry = MaybeEntry.get();
3675 
3676     switch (Entry.Kind) {
3677     case BitstreamEntry::Error:
3678       return error("Malformed block");
3679     case BitstreamEntry::EndBlock:
3680       ResolveDataLayout();
3681       return globalCleanup();
3682 
3683     case BitstreamEntry::SubBlock:
3684       switch (Entry.ID) {
3685       default:  // Skip unknown content.
3686         if (Error Err = Stream.SkipBlock())
3687           return Err;
3688         break;
3689       case bitc::BLOCKINFO_BLOCK_ID:
3690         if (Error Err = readBlockInfo())
3691           return Err;
3692         break;
3693       case bitc::PARAMATTR_BLOCK_ID:
3694         if (Error Err = parseAttributeBlock())
3695           return Err;
3696         break;
3697       case bitc::PARAMATTR_GROUP_BLOCK_ID:
3698         if (Error Err = parseAttributeGroupBlock())
3699           return Err;
3700         break;
3701       case bitc::TYPE_BLOCK_ID_NEW:
3702         if (Error Err = parseTypeTable())
3703           return Err;
3704         break;
3705       case bitc::VALUE_SYMTAB_BLOCK_ID:
3706         if (!SeenValueSymbolTable) {
3707           // Either this is an old form VST without function index and an
3708           // associated VST forward declaration record (which would have caused
3709           // the VST to be jumped to and parsed before it was encountered
3710           // normally in the stream), or there were no function blocks to
3711           // trigger an earlier parsing of the VST.
3712           assert(VSTOffset == 0 || FunctionsWithBodies.empty());
3713           if (Error Err = parseValueSymbolTable())
3714             return Err;
3715           SeenValueSymbolTable = true;
3716         } else {
3717           // We must have had a VST forward declaration record, which caused
3718           // the parser to jump to and parse the VST earlier.
3719           assert(VSTOffset > 0);
3720           if (Error Err = Stream.SkipBlock())
3721             return Err;
3722         }
3723         break;
3724       case bitc::CONSTANTS_BLOCK_ID:
3725         if (Error Err = parseConstants())
3726           return Err;
3727         if (Error Err = resolveGlobalAndIndirectSymbolInits())
3728           return Err;
3729         break;
3730       case bitc::METADATA_BLOCK_ID:
3731         if (ShouldLazyLoadMetadata) {
3732           if (Error Err = rememberAndSkipMetadata())
3733             return Err;
3734           break;
3735         }
3736         assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
3737         if (Error Err = MDLoader->parseModuleMetadata())
3738           return Err;
3739         break;
3740       case bitc::METADATA_KIND_BLOCK_ID:
3741         if (Error Err = MDLoader->parseMetadataKinds())
3742           return Err;
3743         break;
3744       case bitc::FUNCTION_BLOCK_ID:
3745         ResolveDataLayout();
3746 
3747         // If this is the first function body we've seen, reverse the
3748         // FunctionsWithBodies list.
3749         if (!SeenFirstFunctionBody) {
3750           std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
3751           if (Error Err = globalCleanup())
3752             return Err;
3753           SeenFirstFunctionBody = true;
3754         }
3755 
3756         if (VSTOffset > 0) {
3757           // If we have a VST forward declaration record, make sure we
3758           // parse the VST now if we haven't already. It is needed to
3759           // set up the DeferredFunctionInfo vector for lazy reading.
3760           if (!SeenValueSymbolTable) {
3761             if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
3762               return Err;
3763             SeenValueSymbolTable = true;
3764             // Fall through so that we record the NextUnreadBit below.
3765             // This is necessary in case we have an anonymous function that
3766             // is later materialized. Since it will not have a VST entry we
3767             // need to fall back to the lazy parse to find its offset.
3768           } else {
3769             // If we have a VST forward declaration record, but have already
3770             // parsed the VST (just above, when the first function body was
3771             // encountered here), then we are resuming the parse after
3772             // materializing functions. The ResumeBit points to the
3773             // start of the last function block recorded in the
3774             // DeferredFunctionInfo map. Skip it.
3775             if (Error Err = Stream.SkipBlock())
3776               return Err;
3777             continue;
3778           }
3779         }
3780 
3781         // Support older bitcode files that did not have the function
3782         // index in the VST, nor a VST forward declaration record, as
3783         // well as anonymous functions that do not have VST entries.
3784         // Build the DeferredFunctionInfo vector on the fly.
3785         if (Error Err = rememberAndSkipFunctionBody())
3786           return Err;
3787 
3788         // Suspend parsing when we reach the function bodies. Subsequent
3789         // materialization calls will resume it when necessary. If the bitcode
3790         // file is old, the symbol table will be at the end instead and will not
3791         // have been seen yet. In this case, just finish the parse now.
3792         if (SeenValueSymbolTable) {
3793           NextUnreadBit = Stream.GetCurrentBitNo();
3794           // After the VST has been parsed, we need to make sure intrinsic name
3795           // are auto-upgraded.
3796           return globalCleanup();
3797         }
3798         break;
3799       case bitc::USELIST_BLOCK_ID:
3800         if (Error Err = parseUseLists())
3801           return Err;
3802         break;
3803       case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
3804         if (Error Err = parseOperandBundleTags())
3805           return Err;
3806         break;
3807       case bitc::SYNC_SCOPE_NAMES_BLOCK_ID:
3808         if (Error Err = parseSyncScopeNames())
3809           return Err;
3810         break;
3811       }
3812       continue;
3813 
3814     case BitstreamEntry::Record:
3815       // The interesting case.
3816       break;
3817     }
3818 
3819     // Read a record.
3820     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
3821     if (!MaybeBitCode)
3822       return MaybeBitCode.takeError();
3823     switch (unsigned BitCode = MaybeBitCode.get()) {
3824     default: break;  // Default behavior, ignore unknown content.
3825     case bitc::MODULE_CODE_VERSION: {
3826       Expected<unsigned> VersionOrErr = parseVersionRecord(Record);
3827       if (!VersionOrErr)
3828         return VersionOrErr.takeError();
3829       UseRelativeIDs = *VersionOrErr >= 1;
3830       break;
3831     }
3832     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
3833       if (ResolvedDataLayout)
3834         return error("target triple too late in module");
3835       std::string S;
3836       if (convertToString(Record, 0, S))
3837         return error("Invalid record");
3838       TheModule->setTargetTriple(S);
3839       break;
3840     }
3841     case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
3842       if (ResolvedDataLayout)
3843         return error("datalayout too late in module");
3844       std::string S;
3845       if (convertToString(Record, 0, S))
3846         return error("Invalid record");
3847       Expected<DataLayout> MaybeDL = DataLayout::parse(S);
3848       if (!MaybeDL)
3849         return MaybeDL.takeError();
3850       TheModule->setDataLayout(MaybeDL.get());
3851       break;
3852     }
3853     case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
3854       std::string S;
3855       if (convertToString(Record, 0, S))
3856         return error("Invalid record");
3857       TheModule->setModuleInlineAsm(S);
3858       break;
3859     }
3860     case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
3861       // Deprecated, but still needed to read old bitcode files.
3862       std::string S;
3863       if (convertToString(Record, 0, S))
3864         return error("Invalid record");
3865       // Ignore value.
3866       break;
3867     }
3868     case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
3869       std::string S;
3870       if (convertToString(Record, 0, S))
3871         return error("Invalid record");
3872       SectionTable.push_back(S);
3873       break;
3874     }
3875     case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
3876       std::string S;
3877       if (convertToString(Record, 0, S))
3878         return error("Invalid record");
3879       GCTable.push_back(S);
3880       break;
3881     }
3882     case bitc::MODULE_CODE_COMDAT:
3883       if (Error Err = parseComdatRecord(Record))
3884         return Err;
3885       break;
3886     // FIXME: BitcodeReader should handle {GLOBALVAR, FUNCTION, ALIAS, IFUNC}
3887     // written by ThinLinkBitcodeWriter. See
3888     // `ThinLinkBitcodeWriter::writeSimplifiedModuleInfo` for the format of each
3889     // record
3890     // (https://github.com/llvm/llvm-project/blob/b6a93967d9c11e79802b5e75cec1584d6c8aa472/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp#L4714)
3891     case bitc::MODULE_CODE_GLOBALVAR:
3892       if (Error Err = parseGlobalVarRecord(Record))
3893         return Err;
3894       break;
3895     case bitc::MODULE_CODE_FUNCTION:
3896       ResolveDataLayout();
3897       if (Error Err = parseFunctionRecord(Record))
3898         return Err;
3899       break;
3900     case bitc::MODULE_CODE_IFUNC:
3901     case bitc::MODULE_CODE_ALIAS:
3902     case bitc::MODULE_CODE_ALIAS_OLD:
3903       if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
3904         return Err;
3905       break;
3906     /// MODULE_CODE_VSTOFFSET: [offset]
3907     case bitc::MODULE_CODE_VSTOFFSET:
3908       if (Record.empty())
3909         return error("Invalid record");
3910       // Note that we subtract 1 here because the offset is relative to one word
3911       // before the start of the identification or module block, which was
3912       // historically always the start of the regular bitcode header.
3913       VSTOffset = Record[0] - 1;
3914       break;
3915     /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
3916     case bitc::MODULE_CODE_SOURCE_FILENAME:
3917       SmallString<128> ValueName;
3918       if (convertToString(Record, 0, ValueName))
3919         return error("Invalid record");
3920       TheModule->setSourceFileName(ValueName);
3921       break;
3922     }
3923     Record.clear();
3924   }
3925 }
3926 
3927 Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata,
3928                                       bool IsImporting,
3929                                       DataLayoutCallbackTy DataLayoutCallback) {
3930   TheModule = M;
3931   MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting,
3932                             [&](unsigned ID) { return getTypeByID(ID); });
3933   return parseModule(0, ShouldLazyLoadMetadata, DataLayoutCallback);
3934 }
3935 
3936 Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
3937   if (!isa<PointerType>(PtrType))
3938     return error("Load/Store operand is not a pointer type");
3939 
3940   if (!cast<PointerType>(PtrType)->isOpaqueOrPointeeTypeMatches(ValType))
3941     return error("Explicit load/store type does not match pointee "
3942                  "type of pointer operand");
3943   if (!PointerType::isLoadableOrStorableType(ValType))
3944     return error("Cannot load/store from pointer");
3945   return Error::success();
3946 }
3947 
3948 void BitcodeReader::propagateAttributeTypes(CallBase *CB,
3949                                             ArrayRef<Type *> ArgsTys) {
3950   for (unsigned i = 0; i != CB->arg_size(); ++i) {
3951     for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
3952                                      Attribute::InAlloca}) {
3953       if (!CB->paramHasAttr(i, Kind) ||
3954           CB->getParamAttr(i, Kind).getValueAsType())
3955         continue;
3956 
3957       CB->removeParamAttr(i, Kind);
3958 
3959       Type *PtrEltTy = ArgsTys[i]->getPointerElementType();
3960       Attribute NewAttr;
3961       switch (Kind) {
3962       case Attribute::ByVal:
3963         NewAttr = Attribute::getWithByValType(Context, PtrEltTy);
3964         break;
3965       case Attribute::StructRet:
3966         NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy);
3967         break;
3968       case Attribute::InAlloca:
3969         NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy);
3970         break;
3971       default:
3972         llvm_unreachable("not an upgraded type attribute");
3973       }
3974 
3975       CB->addParamAttr(i, NewAttr);
3976     }
3977   }
3978 
3979   if (CB->isInlineAsm()) {
3980     const InlineAsm *IA = cast<InlineAsm>(CB->getCalledOperand());
3981     unsigned ArgNo = 0;
3982     for (const InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
3983       if (!CI.hasArg())
3984         continue;
3985 
3986       if (CI.isIndirect && !CB->getAttributes().getParamElementType(ArgNo)) {
3987         Type *ElemTy = ArgsTys[ArgNo]->getPointerElementType();
3988         CB->addParamAttr(
3989             ArgNo, Attribute::get(Context, Attribute::ElementType, ElemTy));
3990       }
3991 
3992       ArgNo++;
3993     }
3994   }
3995 
3996   switch (CB->getIntrinsicID()) {
3997   case Intrinsic::preserve_array_access_index:
3998   case Intrinsic::preserve_struct_access_index:
3999     if (!CB->getAttributes().getParamElementType(0)) {
4000       Type *ElTy = ArgsTys[0]->getPointerElementType();
4001       Attribute NewAttr = Attribute::get(Context, Attribute::ElementType, ElTy);
4002       CB->addParamAttr(0, NewAttr);
4003     }
4004     break;
4005   default:
4006     break;
4007   }
4008 }
4009 
4010 /// Lazily parse the specified function body block.
4011 Error BitcodeReader::parseFunctionBody(Function *F) {
4012   if (Error Err = Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
4013     return Err;
4014 
4015   // Unexpected unresolved metadata when parsing function.
4016   if (MDLoader->hasFwdRefs())
4017     return error("Invalid function metadata: incoming forward references");
4018 
4019   InstructionList.clear();
4020   unsigned ModuleValueListSize = ValueList.size();
4021   unsigned ModuleMDLoaderSize = MDLoader->size();
4022 
4023   // Add all the function arguments to the value table.
4024 #ifndef NDEBUG
4025   unsigned ArgNo = 0;
4026   FunctionType *FTy = FunctionTypes[F];
4027 #endif
4028   for (Argument &I : F->args()) {
4029     assert(I.getType() == FTy->getParamType(ArgNo++) &&
4030            "Incorrect fully specified type for Function Argument");
4031     ValueList.push_back(&I);
4032   }
4033   unsigned NextValueNo = ValueList.size();
4034   BasicBlock *CurBB = nullptr;
4035   unsigned CurBBNo = 0;
4036 
4037   DebugLoc LastLoc;
4038   auto getLastInstruction = [&]() -> Instruction * {
4039     if (CurBB && !CurBB->empty())
4040       return &CurBB->back();
4041     else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
4042              !FunctionBBs[CurBBNo - 1]->empty())
4043       return &FunctionBBs[CurBBNo - 1]->back();
4044     return nullptr;
4045   };
4046 
4047   std::vector<OperandBundleDef> OperandBundles;
4048 
4049   // Read all the records.
4050   SmallVector<uint64_t, 64> Record;
4051 
4052   while (true) {
4053     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4054     if (!MaybeEntry)
4055       return MaybeEntry.takeError();
4056     llvm::BitstreamEntry Entry = MaybeEntry.get();
4057 
4058     switch (Entry.Kind) {
4059     case BitstreamEntry::Error:
4060       return error("Malformed block");
4061     case BitstreamEntry::EndBlock:
4062       goto OutOfRecordLoop;
4063 
4064     case BitstreamEntry::SubBlock:
4065       switch (Entry.ID) {
4066       default:  // Skip unknown content.
4067         if (Error Err = Stream.SkipBlock())
4068           return Err;
4069         break;
4070       case bitc::CONSTANTS_BLOCK_ID:
4071         if (Error Err = parseConstants())
4072           return Err;
4073         NextValueNo = ValueList.size();
4074         break;
4075       case bitc::VALUE_SYMTAB_BLOCK_ID:
4076         if (Error Err = parseValueSymbolTable())
4077           return Err;
4078         break;
4079       case bitc::METADATA_ATTACHMENT_ID:
4080         if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList))
4081           return Err;
4082         break;
4083       case bitc::METADATA_BLOCK_ID:
4084         assert(DeferredMetadataInfo.empty() &&
4085                "Must read all module-level metadata before function-level");
4086         if (Error Err = MDLoader->parseFunctionMetadata())
4087           return Err;
4088         break;
4089       case bitc::USELIST_BLOCK_ID:
4090         if (Error Err = parseUseLists())
4091           return Err;
4092         break;
4093       }
4094       continue;
4095 
4096     case BitstreamEntry::Record:
4097       // The interesting case.
4098       break;
4099     }
4100 
4101     // Read a record.
4102     Record.clear();
4103     Instruction *I = nullptr;
4104     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
4105     if (!MaybeBitCode)
4106       return MaybeBitCode.takeError();
4107     switch (unsigned BitCode = MaybeBitCode.get()) {
4108     default: // Default behavior: reject
4109       return error("Invalid value");
4110     case bitc::FUNC_CODE_DECLAREBLOCKS: {   // DECLAREBLOCKS: [nblocks]
4111       if (Record.empty() || Record[0] == 0)
4112         return error("Invalid record");
4113       // Create all the basic blocks for the function.
4114       FunctionBBs.resize(Record[0]);
4115 
4116       // See if anything took the address of blocks in this function.
4117       auto BBFRI = BasicBlockFwdRefs.find(F);
4118       if (BBFRI == BasicBlockFwdRefs.end()) {
4119         for (BasicBlock *&BB : FunctionBBs)
4120           BB = BasicBlock::Create(Context, "", F);
4121       } else {
4122         auto &BBRefs = BBFRI->second;
4123         // Check for invalid basic block references.
4124         if (BBRefs.size() > FunctionBBs.size())
4125           return error("Invalid ID");
4126         assert(!BBRefs.empty() && "Unexpected empty array");
4127         assert(!BBRefs.front() && "Invalid reference to entry block");
4128         for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
4129              ++I)
4130           if (I < RE && BBRefs[I]) {
4131             BBRefs[I]->insertInto(F);
4132             FunctionBBs[I] = BBRefs[I];
4133           } else {
4134             FunctionBBs[I] = BasicBlock::Create(Context, "", F);
4135           }
4136 
4137         // Erase from the table.
4138         BasicBlockFwdRefs.erase(BBFRI);
4139       }
4140 
4141       CurBB = FunctionBBs[0];
4142       continue;
4143     }
4144 
4145     case bitc::FUNC_CODE_DEBUG_LOC_AGAIN:  // DEBUG_LOC_AGAIN
4146       // This record indicates that the last instruction is at the same
4147       // location as the previous instruction with a location.
4148       I = getLastInstruction();
4149 
4150       if (!I)
4151         return error("Invalid record");
4152       I->setDebugLoc(LastLoc);
4153       I = nullptr;
4154       continue;
4155 
4156     case bitc::FUNC_CODE_DEBUG_LOC: {      // DEBUG_LOC: [line, col, scope, ia]
4157       I = getLastInstruction();
4158       if (!I || Record.size() < 4)
4159         return error("Invalid record");
4160 
4161       unsigned Line = Record[0], Col = Record[1];
4162       unsigned ScopeID = Record[2], IAID = Record[3];
4163       bool isImplicitCode = Record.size() == 5 && Record[4];
4164 
4165       MDNode *Scope = nullptr, *IA = nullptr;
4166       if (ScopeID) {
4167         Scope = dyn_cast_or_null<MDNode>(
4168             MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1));
4169         if (!Scope)
4170           return error("Invalid record");
4171       }
4172       if (IAID) {
4173         IA = dyn_cast_or_null<MDNode>(
4174             MDLoader->getMetadataFwdRefOrLoad(IAID - 1));
4175         if (!IA)
4176           return error("Invalid record");
4177       }
4178       LastLoc = DILocation::get(Scope->getContext(), Line, Col, Scope, IA,
4179                                 isImplicitCode);
4180       I->setDebugLoc(LastLoc);
4181       I = nullptr;
4182       continue;
4183     }
4184     case bitc::FUNC_CODE_INST_UNOP: {    // UNOP: [opval, ty, opcode]
4185       unsigned OpNum = 0;
4186       Value *LHS;
4187       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4188           OpNum+1 > Record.size())
4189         return error("Invalid record");
4190 
4191       int Opc = getDecodedUnaryOpcode(Record[OpNum++], LHS->getType());
4192       if (Opc == -1)
4193         return error("Invalid record");
4194       I = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS);
4195       InstructionList.push_back(I);
4196       if (OpNum < Record.size()) {
4197         if (isa<FPMathOperator>(I)) {
4198           FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
4199           if (FMF.any())
4200             I->setFastMathFlags(FMF);
4201         }
4202       }
4203       break;
4204     }
4205     case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
4206       unsigned OpNum = 0;
4207       Value *LHS, *RHS;
4208       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4209           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
4210           OpNum+1 > Record.size())
4211         return error("Invalid record");
4212 
4213       int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
4214       if (Opc == -1)
4215         return error("Invalid record");
4216       I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4217       InstructionList.push_back(I);
4218       if (OpNum < Record.size()) {
4219         if (Opc == Instruction::Add ||
4220             Opc == Instruction::Sub ||
4221             Opc == Instruction::Mul ||
4222             Opc == Instruction::Shl) {
4223           if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
4224             cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
4225           if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
4226             cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
4227         } else if (Opc == Instruction::SDiv ||
4228                    Opc == Instruction::UDiv ||
4229                    Opc == Instruction::LShr ||
4230                    Opc == Instruction::AShr) {
4231           if (Record[OpNum] & (1 << bitc::PEO_EXACT))
4232             cast<BinaryOperator>(I)->setIsExact(true);
4233         } else if (isa<FPMathOperator>(I)) {
4234           FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
4235           if (FMF.any())
4236             I->setFastMathFlags(FMF);
4237         }
4238 
4239       }
4240       break;
4241     }
4242     case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
4243       unsigned OpNum = 0;
4244       Value *Op;
4245       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4246           OpNum+2 != Record.size())
4247         return error("Invalid record");
4248 
4249       Type *ResTy = getTypeByID(Record[OpNum]);
4250       int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
4251       if (Opc == -1 || !ResTy)
4252         return error("Invalid record");
4253       Instruction *Temp = nullptr;
4254       if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
4255         if (Temp) {
4256           InstructionList.push_back(Temp);
4257           assert(CurBB && "No current BB?");
4258           CurBB->getInstList().push_back(Temp);
4259         }
4260       } else {
4261         auto CastOp = (Instruction::CastOps)Opc;
4262         if (!CastInst::castIsValid(CastOp, Op, ResTy))
4263           return error("Invalid cast");
4264         I = CastInst::Create(CastOp, Op, ResTy);
4265       }
4266       InstructionList.push_back(I);
4267       break;
4268     }
4269     case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
4270     case bitc::FUNC_CODE_INST_GEP_OLD:
4271     case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
4272       unsigned OpNum = 0;
4273 
4274       Type *Ty;
4275       bool InBounds;
4276 
4277       if (BitCode == bitc::FUNC_CODE_INST_GEP) {
4278         InBounds = Record[OpNum++];
4279         Ty = getTypeByID(Record[OpNum++]);
4280       } else {
4281         InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
4282         Ty = nullptr;
4283       }
4284 
4285       Value *BasePtr;
4286       if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
4287         return error("Invalid record");
4288 
4289       if (!Ty) {
4290         Ty = BasePtr->getType()->getScalarType()->getPointerElementType();
4291       } else if (!cast<PointerType>(BasePtr->getType()->getScalarType())
4292                       ->isOpaqueOrPointeeTypeMatches(Ty)) {
4293         return error(
4294             "Explicit gep type does not match pointee type of pointer operand");
4295       }
4296 
4297       SmallVector<Value*, 16> GEPIdx;
4298       while (OpNum != Record.size()) {
4299         Value *Op;
4300         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4301           return error("Invalid record");
4302         GEPIdx.push_back(Op);
4303       }
4304 
4305       I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
4306 
4307       InstructionList.push_back(I);
4308       if (InBounds)
4309         cast<GetElementPtrInst>(I)->setIsInBounds(true);
4310       break;
4311     }
4312 
4313     case bitc::FUNC_CODE_INST_EXTRACTVAL: {
4314                                        // EXTRACTVAL: [opty, opval, n x indices]
4315       unsigned OpNum = 0;
4316       Value *Agg;
4317       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
4318         return error("Invalid record");
4319       Type *Ty = Agg->getType();
4320 
4321       unsigned RecSize = Record.size();
4322       if (OpNum == RecSize)
4323         return error("EXTRACTVAL: Invalid instruction with 0 indices");
4324 
4325       SmallVector<unsigned, 4> EXTRACTVALIdx;
4326       for (; OpNum != RecSize; ++OpNum) {
4327         bool IsArray = Ty->isArrayTy();
4328         bool IsStruct = Ty->isStructTy();
4329         uint64_t Index = Record[OpNum];
4330 
4331         if (!IsStruct && !IsArray)
4332           return error("EXTRACTVAL: Invalid type");
4333         if ((unsigned)Index != Index)
4334           return error("Invalid value");
4335         if (IsStruct && Index >= Ty->getStructNumElements())
4336           return error("EXTRACTVAL: Invalid struct index");
4337         if (IsArray && Index >= Ty->getArrayNumElements())
4338           return error("EXTRACTVAL: Invalid array index");
4339         EXTRACTVALIdx.push_back((unsigned)Index);
4340 
4341         if (IsStruct)
4342           Ty = Ty->getStructElementType(Index);
4343         else
4344           Ty = Ty->getArrayElementType();
4345       }
4346 
4347       I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
4348       InstructionList.push_back(I);
4349       break;
4350     }
4351 
4352     case bitc::FUNC_CODE_INST_INSERTVAL: {
4353                            // INSERTVAL: [opty, opval, opty, opval, n x indices]
4354       unsigned OpNum = 0;
4355       Value *Agg;
4356       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
4357         return error("Invalid record");
4358       Value *Val;
4359       if (getValueTypePair(Record, OpNum, NextValueNo, Val))
4360         return error("Invalid record");
4361 
4362       unsigned RecSize = Record.size();
4363       if (OpNum == RecSize)
4364         return error("INSERTVAL: Invalid instruction with 0 indices");
4365 
4366       SmallVector<unsigned, 4> INSERTVALIdx;
4367       Type *CurTy = Agg->getType();
4368       for (; OpNum != RecSize; ++OpNum) {
4369         bool IsArray = CurTy->isArrayTy();
4370         bool IsStruct = CurTy->isStructTy();
4371         uint64_t Index = Record[OpNum];
4372 
4373         if (!IsStruct && !IsArray)
4374           return error("INSERTVAL: Invalid type");
4375         if ((unsigned)Index != Index)
4376           return error("Invalid value");
4377         if (IsStruct && Index >= CurTy->getStructNumElements())
4378           return error("INSERTVAL: Invalid struct index");
4379         if (IsArray && Index >= CurTy->getArrayNumElements())
4380           return error("INSERTVAL: Invalid array index");
4381 
4382         INSERTVALIdx.push_back((unsigned)Index);
4383         if (IsStruct)
4384           CurTy = CurTy->getStructElementType(Index);
4385         else
4386           CurTy = CurTy->getArrayElementType();
4387       }
4388 
4389       if (CurTy != Val->getType())
4390         return error("Inserted value type doesn't match aggregate type");
4391 
4392       I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
4393       InstructionList.push_back(I);
4394       break;
4395     }
4396 
4397     case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
4398       // obsolete form of select
4399       // handles select i1 ... in old bitcode
4400       unsigned OpNum = 0;
4401       Value *TrueVal, *FalseVal, *Cond;
4402       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
4403           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4404           popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
4405         return error("Invalid record");
4406 
4407       I = SelectInst::Create(Cond, TrueVal, FalseVal);
4408       InstructionList.push_back(I);
4409       break;
4410     }
4411 
4412     case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
4413       // new form of select
4414       // handles select i1 or select [N x i1]
4415       unsigned OpNum = 0;
4416       Value *TrueVal, *FalseVal, *Cond;
4417       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
4418           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4419           getValueTypePair(Record, OpNum, NextValueNo, Cond))
4420         return error("Invalid record");
4421 
4422       // select condition can be either i1 or [N x i1]
4423       if (VectorType* vector_type =
4424           dyn_cast<VectorType>(Cond->getType())) {
4425         // expect <n x i1>
4426         if (vector_type->getElementType() != Type::getInt1Ty(Context))
4427           return error("Invalid type for value");
4428       } else {
4429         // expect i1
4430         if (Cond->getType() != Type::getInt1Ty(Context))
4431           return error("Invalid type for value");
4432       }
4433 
4434       I = SelectInst::Create(Cond, TrueVal, FalseVal);
4435       InstructionList.push_back(I);
4436       if (OpNum < Record.size() && isa<FPMathOperator>(I)) {
4437         FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
4438         if (FMF.any())
4439           I->setFastMathFlags(FMF);
4440       }
4441       break;
4442     }
4443 
4444     case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
4445       unsigned OpNum = 0;
4446       Value *Vec, *Idx;
4447       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
4448           getValueTypePair(Record, OpNum, NextValueNo, Idx))
4449         return error("Invalid record");
4450       if (!Vec->getType()->isVectorTy())
4451         return error("Invalid type for value");
4452       I = ExtractElementInst::Create(Vec, Idx);
4453       InstructionList.push_back(I);
4454       break;
4455     }
4456 
4457     case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
4458       unsigned OpNum = 0;
4459       Value *Vec, *Elt, *Idx;
4460       if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
4461         return error("Invalid record");
4462       if (!Vec->getType()->isVectorTy())
4463         return error("Invalid type for value");
4464       if (popValue(Record, OpNum, NextValueNo,
4465                    cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
4466           getValueTypePair(Record, OpNum, NextValueNo, Idx))
4467         return error("Invalid record");
4468       I = InsertElementInst::Create(Vec, Elt, Idx);
4469       InstructionList.push_back(I);
4470       break;
4471     }
4472 
4473     case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
4474       unsigned OpNum = 0;
4475       Value *Vec1, *Vec2, *Mask;
4476       if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
4477           popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
4478         return error("Invalid record");
4479 
4480       if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
4481         return error("Invalid record");
4482       if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
4483         return error("Invalid type for value");
4484 
4485       I = new ShuffleVectorInst(Vec1, Vec2, Mask);
4486       InstructionList.push_back(I);
4487       break;
4488     }
4489 
4490     case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
4491       // Old form of ICmp/FCmp returning bool
4492       // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
4493       // both legal on vectors but had different behaviour.
4494     case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
4495       // FCmp/ICmp returning bool or vector of bool
4496 
4497       unsigned OpNum = 0;
4498       Value *LHS, *RHS;
4499       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4500           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
4501         return error("Invalid record");
4502 
4503       if (OpNum >= Record.size())
4504         return error(
4505             "Invalid record: operand number exceeded available operands");
4506 
4507       unsigned PredVal = Record[OpNum];
4508       bool IsFP = LHS->getType()->isFPOrFPVectorTy();
4509       FastMathFlags FMF;
4510       if (IsFP && Record.size() > OpNum+1)
4511         FMF = getDecodedFastMathFlags(Record[++OpNum]);
4512 
4513       if (OpNum+1 != Record.size())
4514         return error("Invalid record");
4515 
4516       if (LHS->getType()->isFPOrFPVectorTy())
4517         I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
4518       else
4519         I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
4520 
4521       if (FMF.any())
4522         I->setFastMathFlags(FMF);
4523       InstructionList.push_back(I);
4524       break;
4525     }
4526 
4527     case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
4528       {
4529         unsigned Size = Record.size();
4530         if (Size == 0) {
4531           I = ReturnInst::Create(Context);
4532           InstructionList.push_back(I);
4533           break;
4534         }
4535 
4536         unsigned OpNum = 0;
4537         Value *Op = nullptr;
4538         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4539           return error("Invalid record");
4540         if (OpNum != Record.size())
4541           return error("Invalid record");
4542 
4543         I = ReturnInst::Create(Context, Op);
4544         InstructionList.push_back(I);
4545         break;
4546       }
4547     case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
4548       if (Record.size() != 1 && Record.size() != 3)
4549         return error("Invalid record");
4550       BasicBlock *TrueDest = getBasicBlock(Record[0]);
4551       if (!TrueDest)
4552         return error("Invalid record");
4553 
4554       if (Record.size() == 1) {
4555         I = BranchInst::Create(TrueDest);
4556         InstructionList.push_back(I);
4557       }
4558       else {
4559         BasicBlock *FalseDest = getBasicBlock(Record[1]);
4560         Value *Cond = getValue(Record, 2, NextValueNo,
4561                                Type::getInt1Ty(Context));
4562         if (!FalseDest || !Cond)
4563           return error("Invalid record");
4564         I = BranchInst::Create(TrueDest, FalseDest, Cond);
4565         InstructionList.push_back(I);
4566       }
4567       break;
4568     }
4569     case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
4570       if (Record.size() != 1 && Record.size() != 2)
4571         return error("Invalid record");
4572       unsigned Idx = 0;
4573       Value *CleanupPad =
4574           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4575       if (!CleanupPad)
4576         return error("Invalid record");
4577       BasicBlock *UnwindDest = nullptr;
4578       if (Record.size() == 2) {
4579         UnwindDest = getBasicBlock(Record[Idx++]);
4580         if (!UnwindDest)
4581           return error("Invalid record");
4582       }
4583 
4584       I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
4585       InstructionList.push_back(I);
4586       break;
4587     }
4588     case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
4589       if (Record.size() != 2)
4590         return error("Invalid record");
4591       unsigned Idx = 0;
4592       Value *CatchPad =
4593           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4594       if (!CatchPad)
4595         return error("Invalid record");
4596       BasicBlock *BB = getBasicBlock(Record[Idx++]);
4597       if (!BB)
4598         return error("Invalid record");
4599 
4600       I = CatchReturnInst::Create(CatchPad, BB);
4601       InstructionList.push_back(I);
4602       break;
4603     }
4604     case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
4605       // We must have, at minimum, the outer scope and the number of arguments.
4606       if (Record.size() < 2)
4607         return error("Invalid record");
4608 
4609       unsigned Idx = 0;
4610 
4611       Value *ParentPad =
4612           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4613 
4614       unsigned NumHandlers = Record[Idx++];
4615 
4616       SmallVector<BasicBlock *, 2> Handlers;
4617       for (unsigned Op = 0; Op != NumHandlers; ++Op) {
4618         BasicBlock *BB = getBasicBlock(Record[Idx++]);
4619         if (!BB)
4620           return error("Invalid record");
4621         Handlers.push_back(BB);
4622       }
4623 
4624       BasicBlock *UnwindDest = nullptr;
4625       if (Idx + 1 == Record.size()) {
4626         UnwindDest = getBasicBlock(Record[Idx++]);
4627         if (!UnwindDest)
4628           return error("Invalid record");
4629       }
4630 
4631       if (Record.size() != Idx)
4632         return error("Invalid record");
4633 
4634       auto *CatchSwitch =
4635           CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
4636       for (BasicBlock *Handler : Handlers)
4637         CatchSwitch->addHandler(Handler);
4638       I = CatchSwitch;
4639       InstructionList.push_back(I);
4640       break;
4641     }
4642     case bitc::FUNC_CODE_INST_CATCHPAD:
4643     case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
4644       // We must have, at minimum, the outer scope and the number of arguments.
4645       if (Record.size() < 2)
4646         return error("Invalid record");
4647 
4648       unsigned Idx = 0;
4649 
4650       Value *ParentPad =
4651           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4652 
4653       unsigned NumArgOperands = Record[Idx++];
4654 
4655       SmallVector<Value *, 2> Args;
4656       for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4657         Value *Val;
4658         if (getValueTypePair(Record, Idx, NextValueNo, Val))
4659           return error("Invalid record");
4660         Args.push_back(Val);
4661       }
4662 
4663       if (Record.size() != Idx)
4664         return error("Invalid record");
4665 
4666       if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
4667         I = CleanupPadInst::Create(ParentPad, Args);
4668       else
4669         I = CatchPadInst::Create(ParentPad, Args);
4670       InstructionList.push_back(I);
4671       break;
4672     }
4673     case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
4674       // Check magic
4675       if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
4676         // "New" SwitchInst format with case ranges. The changes to write this
4677         // format were reverted but we still recognize bitcode that uses it.
4678         // Hopefully someday we will have support for case ranges and can use
4679         // this format again.
4680 
4681         Type *OpTy = getTypeByID(Record[1]);
4682         unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
4683 
4684         Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
4685         BasicBlock *Default = getBasicBlock(Record[3]);
4686         if (!OpTy || !Cond || !Default)
4687           return error("Invalid record");
4688 
4689         unsigned NumCases = Record[4];
4690 
4691         SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4692         InstructionList.push_back(SI);
4693 
4694         unsigned CurIdx = 5;
4695         for (unsigned i = 0; i != NumCases; ++i) {
4696           SmallVector<ConstantInt*, 1> CaseVals;
4697           unsigned NumItems = Record[CurIdx++];
4698           for (unsigned ci = 0; ci != NumItems; ++ci) {
4699             bool isSingleNumber = Record[CurIdx++];
4700 
4701             APInt Low;
4702             unsigned ActiveWords = 1;
4703             if (ValueBitWidth > 64)
4704               ActiveWords = Record[CurIdx++];
4705             Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
4706                                 ValueBitWidth);
4707             CurIdx += ActiveWords;
4708 
4709             if (!isSingleNumber) {
4710               ActiveWords = 1;
4711               if (ValueBitWidth > 64)
4712                 ActiveWords = Record[CurIdx++];
4713               APInt High = readWideAPInt(
4714                   makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
4715               CurIdx += ActiveWords;
4716 
4717               // FIXME: It is not clear whether values in the range should be
4718               // compared as signed or unsigned values. The partially
4719               // implemented changes that used this format in the past used
4720               // unsigned comparisons.
4721               for ( ; Low.ule(High); ++Low)
4722                 CaseVals.push_back(ConstantInt::get(Context, Low));
4723             } else
4724               CaseVals.push_back(ConstantInt::get(Context, Low));
4725           }
4726           BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
4727           for (ConstantInt *Cst : CaseVals)
4728             SI->addCase(Cst, DestBB);
4729         }
4730         I = SI;
4731         break;
4732       }
4733 
4734       // Old SwitchInst format without case ranges.
4735 
4736       if (Record.size() < 3 || (Record.size() & 1) == 0)
4737         return error("Invalid record");
4738       Type *OpTy = getTypeByID(Record[0]);
4739       Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
4740       BasicBlock *Default = getBasicBlock(Record[2]);
4741       if (!OpTy || !Cond || !Default)
4742         return error("Invalid record");
4743       unsigned NumCases = (Record.size()-3)/2;
4744       SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4745       InstructionList.push_back(SI);
4746       for (unsigned i = 0, e = NumCases; i != e; ++i) {
4747         ConstantInt *CaseVal =
4748           dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4749         BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
4750         if (!CaseVal || !DestBB) {
4751           delete SI;
4752           return error("Invalid record");
4753         }
4754         SI->addCase(CaseVal, DestBB);
4755       }
4756       I = SI;
4757       break;
4758     }
4759     case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
4760       if (Record.size() < 2)
4761         return error("Invalid record");
4762       Type *OpTy = getTypeByID(Record[0]);
4763       Value *Address = getValue(Record, 1, NextValueNo, OpTy);
4764       if (!OpTy || !Address)
4765         return error("Invalid record");
4766       unsigned NumDests = Record.size()-2;
4767       IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
4768       InstructionList.push_back(IBI);
4769       for (unsigned i = 0, e = NumDests; i != e; ++i) {
4770         if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4771           IBI->addDestination(DestBB);
4772         } else {
4773           delete IBI;
4774           return error("Invalid record");
4775         }
4776       }
4777       I = IBI;
4778       break;
4779     }
4780 
4781     case bitc::FUNC_CODE_INST_INVOKE: {
4782       // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
4783       if (Record.size() < 4)
4784         return error("Invalid record");
4785       unsigned OpNum = 0;
4786       AttributeList PAL = getAttributes(Record[OpNum++]);
4787       unsigned CCInfo = Record[OpNum++];
4788       BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4789       BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
4790 
4791       FunctionType *FTy = nullptr;
4792       if ((CCInfo >> 13) & 1) {
4793         FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]));
4794         if (!FTy)
4795           return error("Explicit invoke type is not a function type");
4796       }
4797 
4798       Value *Callee;
4799       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4800         return error("Invalid record");
4801 
4802       PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
4803       if (!CalleeTy)
4804         return error("Callee is not a pointer");
4805       if (!FTy) {
4806         FTy =
4807             dyn_cast<FunctionType>(Callee->getType()->getPointerElementType());
4808         if (!FTy)
4809           return error("Callee is not of pointer to function type");
4810       } else if (!CalleeTy->isOpaqueOrPointeeTypeMatches(FTy))
4811         return error("Explicit invoke type does not match pointee type of "
4812                      "callee operand");
4813       if (Record.size() < FTy->getNumParams() + OpNum)
4814         return error("Insufficient operands to call");
4815 
4816       SmallVector<Value*, 16> Ops;
4817       SmallVector<Type *, 16> ArgsTys;
4818       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4819         Ops.push_back(getValue(Record, OpNum, NextValueNo,
4820                                FTy->getParamType(i)));
4821         ArgsTys.push_back(FTy->getParamType(i));
4822         if (!Ops.back())
4823           return error("Invalid record");
4824       }
4825 
4826       if (!FTy->isVarArg()) {
4827         if (Record.size() != OpNum)
4828           return error("Invalid record");
4829       } else {
4830         // Read type/value pairs for varargs params.
4831         while (OpNum != Record.size()) {
4832           Value *Op;
4833           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4834             return error("Invalid record");
4835           Ops.push_back(Op);
4836           ArgsTys.push_back(Op->getType());
4837         }
4838       }
4839 
4840       I = InvokeInst::Create(FTy, Callee, NormalBB, UnwindBB, Ops,
4841                              OperandBundles);
4842       OperandBundles.clear();
4843       InstructionList.push_back(I);
4844       cast<InvokeInst>(I)->setCallingConv(
4845           static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
4846       cast<InvokeInst>(I)->setAttributes(PAL);
4847       propagateAttributeTypes(cast<CallBase>(I), ArgsTys);
4848 
4849       break;
4850     }
4851     case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4852       unsigned Idx = 0;
4853       Value *Val = nullptr;
4854       if (getValueTypePair(Record, Idx, NextValueNo, Val))
4855         return error("Invalid record");
4856       I = ResumeInst::Create(Val);
4857       InstructionList.push_back(I);
4858       break;
4859     }
4860     case bitc::FUNC_CODE_INST_CALLBR: {
4861       // CALLBR: [attr, cc, norm, transfs, fty, fnid, args]
4862       unsigned OpNum = 0;
4863       AttributeList PAL = getAttributes(Record[OpNum++]);
4864       unsigned CCInfo = Record[OpNum++];
4865 
4866       BasicBlock *DefaultDest = getBasicBlock(Record[OpNum++]);
4867       unsigned NumIndirectDests = Record[OpNum++];
4868       SmallVector<BasicBlock *, 16> IndirectDests;
4869       for (unsigned i = 0, e = NumIndirectDests; i != e; ++i)
4870         IndirectDests.push_back(getBasicBlock(Record[OpNum++]));
4871 
4872       FunctionType *FTy = nullptr;
4873       if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) {
4874         FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]));
4875         if (!FTy)
4876           return error("Explicit call type is not a function type");
4877       }
4878 
4879       Value *Callee;
4880       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4881         return error("Invalid record");
4882 
4883       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
4884       if (!OpTy)
4885         return error("Callee is not a pointer type");
4886       if (!FTy) {
4887         FTy =
4888             dyn_cast<FunctionType>(Callee->getType()->getPointerElementType());
4889         if (!FTy)
4890           return error("Callee is not of pointer to function type");
4891       } else if (!OpTy->isOpaqueOrPointeeTypeMatches(FTy))
4892         return error("Explicit call type does not match pointee type of "
4893                      "callee operand");
4894       if (Record.size() < FTy->getNumParams() + OpNum)
4895         return error("Insufficient operands to call");
4896 
4897       SmallVector<Value*, 16> Args;
4898       SmallVector<Type *, 16> ArgsTys;
4899       // Read the fixed params.
4900       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4901         Value *Arg;
4902         if (FTy->getParamType(i)->isLabelTy())
4903           Arg = getBasicBlock(Record[OpNum]);
4904         else
4905           Arg = getValue(Record, OpNum, NextValueNo, FTy->getParamType(i));
4906         if (!Arg)
4907           return error("Invalid record");
4908         Args.push_back(Arg);
4909         ArgsTys.push_back(Arg->getType());
4910       }
4911 
4912       // Read type/value pairs for varargs params.
4913       if (!FTy->isVarArg()) {
4914         if (OpNum != Record.size())
4915           return error("Invalid record");
4916       } else {
4917         while (OpNum != Record.size()) {
4918           Value *Op;
4919           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4920             return error("Invalid record");
4921           Args.push_back(Op);
4922           ArgsTys.push_back(Op->getType());
4923         }
4924       }
4925 
4926       I = CallBrInst::Create(FTy, Callee, DefaultDest, IndirectDests, Args,
4927                              OperandBundles);
4928       OperandBundles.clear();
4929       InstructionList.push_back(I);
4930       cast<CallBrInst>(I)->setCallingConv(
4931           static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
4932       cast<CallBrInst>(I)->setAttributes(PAL);
4933       propagateAttributeTypes(cast<CallBase>(I), ArgsTys);
4934       break;
4935     }
4936     case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
4937       I = new UnreachableInst(Context);
4938       InstructionList.push_back(I);
4939       break;
4940     case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
4941       if (Record.empty())
4942         return error("Invalid record");
4943       // The first record specifies the type.
4944       Type *Ty = getTypeByID(Record[0]);
4945       if (!Ty)
4946         return error("Invalid record");
4947 
4948       // Phi arguments are pairs of records of [value, basic block].
4949       // There is an optional final record for fast-math-flags if this phi has a
4950       // floating-point type.
4951       size_t NumArgs = (Record.size() - 1) / 2;
4952       PHINode *PN = PHINode::Create(Ty, NumArgs);
4953       if ((Record.size() - 1) % 2 == 1 && !isa<FPMathOperator>(PN))
4954         return error("Invalid record");
4955       InstructionList.push_back(PN);
4956 
4957       for (unsigned i = 0; i != NumArgs; i++) {
4958         Value *V;
4959         // With the new function encoding, it is possible that operands have
4960         // negative IDs (for forward references).  Use a signed VBR
4961         // representation to keep the encoding small.
4962         if (UseRelativeIDs)
4963           V = getValueSigned(Record, i * 2 + 1, NextValueNo, Ty);
4964         else
4965           V = getValue(Record, i * 2 + 1, NextValueNo, Ty);
4966         BasicBlock *BB = getBasicBlock(Record[i * 2 + 2]);
4967         if (!V || !BB)
4968           return error("Invalid record");
4969         PN->addIncoming(V, BB);
4970       }
4971       I = PN;
4972 
4973       // If there are an even number of records, the final record must be FMF.
4974       if (Record.size() % 2 == 0) {
4975         assert(isa<FPMathOperator>(I) && "Unexpected phi type");
4976         FastMathFlags FMF = getDecodedFastMathFlags(Record[Record.size() - 1]);
4977         if (FMF.any())
4978           I->setFastMathFlags(FMF);
4979       }
4980 
4981       break;
4982     }
4983 
4984     case bitc::FUNC_CODE_INST_LANDINGPAD:
4985     case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
4986       // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4987       unsigned Idx = 0;
4988       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4989         if (Record.size() < 3)
4990           return error("Invalid record");
4991       } else {
4992         assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
4993         if (Record.size() < 4)
4994           return error("Invalid record");
4995       }
4996       Type *Ty = getTypeByID(Record[Idx++]);
4997       if (!Ty)
4998         return error("Invalid record");
4999       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
5000         Value *PersFn = nullptr;
5001         if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
5002           return error("Invalid record");
5003 
5004         if (!F->hasPersonalityFn())
5005           F->setPersonalityFn(cast<Constant>(PersFn));
5006         else if (F->getPersonalityFn() != cast<Constant>(PersFn))
5007           return error("Personality function mismatch");
5008       }
5009 
5010       bool IsCleanup = !!Record[Idx++];
5011       unsigned NumClauses = Record[Idx++];
5012       LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
5013       LP->setCleanup(IsCleanup);
5014       for (unsigned J = 0; J != NumClauses; ++J) {
5015         LandingPadInst::ClauseType CT =
5016           LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
5017         Value *Val;
5018 
5019         if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
5020           delete LP;
5021           return error("Invalid record");
5022         }
5023 
5024         assert((CT != LandingPadInst::Catch ||
5025                 !isa<ArrayType>(Val->getType())) &&
5026                "Catch clause has a invalid type!");
5027         assert((CT != LandingPadInst::Filter ||
5028                 isa<ArrayType>(Val->getType())) &&
5029                "Filter clause has invalid type!");
5030         LP->addClause(cast<Constant>(Val));
5031       }
5032 
5033       I = LP;
5034       InstructionList.push_back(I);
5035       break;
5036     }
5037 
5038     case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
5039       if (Record.size() != 4)
5040         return error("Invalid record");
5041       using APV = AllocaPackedValues;
5042       const uint64_t Rec = Record[3];
5043       const bool InAlloca = Bitfield::get<APV::UsedWithInAlloca>(Rec);
5044       const bool SwiftError = Bitfield::get<APV::SwiftError>(Rec);
5045       Type *Ty = getTypeByID(Record[0]);
5046       if (!Bitfield::get<APV::ExplicitType>(Rec)) {
5047         Ty = getElementTypeByID(Record[0]);
5048         if (!Ty)
5049           return error("Missing element type for old-style alloca");
5050       }
5051       Type *OpTy = getTypeByID(Record[1]);
5052       Value *Size = getFnValueByID(Record[2], OpTy);
5053       MaybeAlign Align;
5054       uint64_t AlignExp =
5055           Bitfield::get<APV::AlignLower>(Rec) |
5056           (Bitfield::get<APV::AlignUpper>(Rec) << APV::AlignLower::Bits);
5057       if (Error Err = parseAlignmentValue(AlignExp, Align)) {
5058         return Err;
5059       }
5060       if (!Ty || !Size)
5061         return error("Invalid record");
5062 
5063       // FIXME: Make this an optional field.
5064       const DataLayout &DL = TheModule->getDataLayout();
5065       unsigned AS = DL.getAllocaAddrSpace();
5066 
5067       SmallPtrSet<Type *, 4> Visited;
5068       if (!Align && !Ty->isSized(&Visited))
5069         return error("alloca of unsized type");
5070       if (!Align)
5071         Align = DL.getPrefTypeAlign(Ty);
5072 
5073       AllocaInst *AI = new AllocaInst(Ty, AS, Size, *Align);
5074       AI->setUsedWithInAlloca(InAlloca);
5075       AI->setSwiftError(SwiftError);
5076       I = AI;
5077       InstructionList.push_back(I);
5078       break;
5079     }
5080     case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
5081       unsigned OpNum = 0;
5082       Value *Op;
5083       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
5084           (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
5085         return error("Invalid record");
5086 
5087       if (!isa<PointerType>(Op->getType()))
5088         return error("Load operand is not a pointer type");
5089 
5090       Type *Ty = nullptr;
5091       if (OpNum + 3 == Record.size()) {
5092         Ty = getTypeByID(Record[OpNum++]);
5093       } else {
5094         Ty = Op->getType()->getPointerElementType();
5095       }
5096 
5097       if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
5098         return Err;
5099 
5100       MaybeAlign Align;
5101       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
5102         return Err;
5103       SmallPtrSet<Type *, 4> Visited;
5104       if (!Align && !Ty->isSized(&Visited))
5105         return error("load of unsized type");
5106       if (!Align)
5107         Align = TheModule->getDataLayout().getABITypeAlign(Ty);
5108       I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align);
5109       InstructionList.push_back(I);
5110       break;
5111     }
5112     case bitc::FUNC_CODE_INST_LOADATOMIC: {
5113        // LOADATOMIC: [opty, op, align, vol, ordering, ssid]
5114       unsigned OpNum = 0;
5115       Value *Op;
5116       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
5117           (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
5118         return error("Invalid record");
5119 
5120       if (!isa<PointerType>(Op->getType()))
5121         return error("Load operand is not a pointer type");
5122 
5123       Type *Ty = nullptr;
5124       if (OpNum + 5 == Record.size()) {
5125         Ty = getTypeByID(Record[OpNum++]);
5126       } else {
5127         Ty = Op->getType()->getPointerElementType();
5128       }
5129 
5130       if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
5131         return Err;
5132 
5133       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
5134       if (Ordering == AtomicOrdering::NotAtomic ||
5135           Ordering == AtomicOrdering::Release ||
5136           Ordering == AtomicOrdering::AcquireRelease)
5137         return error("Invalid record");
5138       if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
5139         return error("Invalid record");
5140       SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
5141 
5142       MaybeAlign Align;
5143       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
5144         return Err;
5145       if (!Align)
5146         return error("Alignment missing from atomic load");
5147       I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align, Ordering, SSID);
5148       InstructionList.push_back(I);
5149       break;
5150     }
5151     case bitc::FUNC_CODE_INST_STORE:
5152     case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
5153       unsigned OpNum = 0;
5154       Value *Val, *Ptr;
5155       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
5156           (BitCode == bitc::FUNC_CODE_INST_STORE
5157                ? getValueTypePair(Record, OpNum, NextValueNo, Val)
5158                : popValue(Record, OpNum, NextValueNo,
5159                           Ptr->getType()->getPointerElementType(), Val)) ||
5160           OpNum + 2 != Record.size())
5161         return error("Invalid record");
5162 
5163       if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
5164         return Err;
5165       MaybeAlign Align;
5166       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
5167         return Err;
5168       SmallPtrSet<Type *, 4> Visited;
5169       if (!Align && !Val->getType()->isSized(&Visited))
5170         return error("store of unsized type");
5171       if (!Align)
5172         Align = TheModule->getDataLayout().getABITypeAlign(Val->getType());
5173       I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align);
5174       InstructionList.push_back(I);
5175       break;
5176     }
5177     case bitc::FUNC_CODE_INST_STOREATOMIC:
5178     case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
5179       // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid]
5180       unsigned OpNum = 0;
5181       Value *Val, *Ptr;
5182       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
5183           !isa<PointerType>(Ptr->getType()) ||
5184           (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
5185                ? getValueTypePair(Record, OpNum, NextValueNo, Val)
5186                : popValue(Record, OpNum, NextValueNo,
5187                           Ptr->getType()->getPointerElementType(), Val)) ||
5188           OpNum + 4 != Record.size())
5189         return error("Invalid record");
5190 
5191       if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
5192         return Err;
5193       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
5194       if (Ordering == AtomicOrdering::NotAtomic ||
5195           Ordering == AtomicOrdering::Acquire ||
5196           Ordering == AtomicOrdering::AcquireRelease)
5197         return error("Invalid record");
5198       SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
5199       if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
5200         return error("Invalid record");
5201 
5202       MaybeAlign Align;
5203       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
5204         return Err;
5205       if (!Align)
5206         return error("Alignment missing from atomic store");
5207       I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align, Ordering, SSID);
5208       InstructionList.push_back(I);
5209       break;
5210     }
5211     case bitc::FUNC_CODE_INST_CMPXCHG_OLD: {
5212       // CMPXCHG_OLD: [ptrty, ptr, cmp, val, vol, ordering, synchscope,
5213       // failure_ordering?, weak?]
5214       const size_t NumRecords = Record.size();
5215       unsigned OpNum = 0;
5216       Value *Ptr = nullptr;
5217       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr))
5218         return error("Invalid record");
5219 
5220       if (!isa<PointerType>(Ptr->getType()))
5221         return error("Cmpxchg operand is not a pointer type");
5222 
5223       Value *Cmp = nullptr;
5224       if (popValue(Record, OpNum, NextValueNo,
5225                    cast<PointerType>(Ptr->getType())->getPointerElementType(),
5226                    Cmp))
5227         return error("Invalid record");
5228 
5229       Value *New = nullptr;
5230       if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
5231           NumRecords < OpNum + 3 || NumRecords > OpNum + 5)
5232         return error("Invalid record");
5233 
5234       const AtomicOrdering SuccessOrdering =
5235           getDecodedOrdering(Record[OpNum + 1]);
5236       if (SuccessOrdering == AtomicOrdering::NotAtomic ||
5237           SuccessOrdering == AtomicOrdering::Unordered)
5238         return error("Invalid record");
5239 
5240       const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
5241 
5242       if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
5243         return Err;
5244 
5245       const AtomicOrdering FailureOrdering =
5246           NumRecords < 7
5247               ? AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering)
5248               : getDecodedOrdering(Record[OpNum + 3]);
5249 
5250       if (FailureOrdering == AtomicOrdering::NotAtomic ||
5251           FailureOrdering == AtomicOrdering::Unordered)
5252         return error("Invalid record");
5253 
5254       const Align Alignment(
5255           TheModule->getDataLayout().getTypeStoreSize(Cmp->getType()));
5256 
5257       I = new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment, SuccessOrdering,
5258                                 FailureOrdering, SSID);
5259       cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
5260 
5261       if (NumRecords < 8) {
5262         // Before weak cmpxchgs existed, the instruction simply returned the
5263         // value loaded from memory, so bitcode files from that era will be
5264         // expecting the first component of a modern cmpxchg.
5265         CurBB->getInstList().push_back(I);
5266         I = ExtractValueInst::Create(I, 0);
5267       } else {
5268         cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum + 4]);
5269       }
5270 
5271       InstructionList.push_back(I);
5272       break;
5273     }
5274     case bitc::FUNC_CODE_INST_CMPXCHG: {
5275       // CMPXCHG: [ptrty, ptr, cmp, val, vol, success_ordering, synchscope,
5276       // failure_ordering, weak, align?]
5277       const size_t NumRecords = Record.size();
5278       unsigned OpNum = 0;
5279       Value *Ptr = nullptr;
5280       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr))
5281         return error("Invalid record");
5282 
5283       if (!isa<PointerType>(Ptr->getType()))
5284         return error("Cmpxchg operand is not a pointer type");
5285 
5286       Value *Cmp = nullptr;
5287       if (getValueTypePair(Record, OpNum, NextValueNo, Cmp))
5288         return error("Invalid record");
5289 
5290       Value *Val = nullptr;
5291       if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), Val))
5292         return error("Invalid record");
5293 
5294       if (NumRecords < OpNum + 3 || NumRecords > OpNum + 6)
5295         return error("Invalid record");
5296 
5297       const bool IsVol = Record[OpNum];
5298 
5299       const AtomicOrdering SuccessOrdering =
5300           getDecodedOrdering(Record[OpNum + 1]);
5301       if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
5302         return error("Invalid cmpxchg success ordering");
5303 
5304       const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
5305 
5306       if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
5307         return Err;
5308 
5309       const AtomicOrdering FailureOrdering =
5310           getDecodedOrdering(Record[OpNum + 3]);
5311       if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
5312         return error("Invalid cmpxchg failure ordering");
5313 
5314       const bool IsWeak = Record[OpNum + 4];
5315 
5316       MaybeAlign Alignment;
5317 
5318       if (NumRecords == (OpNum + 6)) {
5319         if (Error Err = parseAlignmentValue(Record[OpNum + 5], Alignment))
5320           return Err;
5321       }
5322       if (!Alignment)
5323         Alignment =
5324             Align(TheModule->getDataLayout().getTypeStoreSize(Cmp->getType()));
5325 
5326       I = new AtomicCmpXchgInst(Ptr, Cmp, Val, *Alignment, SuccessOrdering,
5327                                 FailureOrdering, SSID);
5328       cast<AtomicCmpXchgInst>(I)->setVolatile(IsVol);
5329       cast<AtomicCmpXchgInst>(I)->setWeak(IsWeak);
5330 
5331       InstructionList.push_back(I);
5332       break;
5333     }
5334     case bitc::FUNC_CODE_INST_ATOMICRMW_OLD:
5335     case bitc::FUNC_CODE_INST_ATOMICRMW: {
5336       // ATOMICRMW_OLD: [ptrty, ptr, val, op, vol, ordering, ssid, align?]
5337       // ATOMICRMW: [ptrty, ptr, valty, val, op, vol, ordering, ssid, align?]
5338       const size_t NumRecords = Record.size();
5339       unsigned OpNum = 0;
5340 
5341       Value *Ptr = nullptr;
5342       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr))
5343         return error("Invalid record");
5344 
5345       if (!isa<PointerType>(Ptr->getType()))
5346         return error("Invalid record");
5347 
5348       Value *Val = nullptr;
5349       if (BitCode == bitc::FUNC_CODE_INST_ATOMICRMW_OLD) {
5350         if (popValue(Record, OpNum, NextValueNo,
5351                      cast<PointerType>(Ptr->getType())->getPointerElementType(),
5352                      Val))
5353           return error("Invalid record");
5354       } else {
5355         if (getValueTypePair(Record, OpNum, NextValueNo, Val))
5356           return error("Invalid record");
5357       }
5358 
5359       if (!(NumRecords == (OpNum + 4) || NumRecords == (OpNum + 5)))
5360         return error("Invalid record");
5361 
5362       const AtomicRMWInst::BinOp Operation =
5363           getDecodedRMWOperation(Record[OpNum]);
5364       if (Operation < AtomicRMWInst::FIRST_BINOP ||
5365           Operation > AtomicRMWInst::LAST_BINOP)
5366         return error("Invalid record");
5367 
5368       const bool IsVol = Record[OpNum + 1];
5369 
5370       const AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
5371       if (Ordering == AtomicOrdering::NotAtomic ||
5372           Ordering == AtomicOrdering::Unordered)
5373         return error("Invalid record");
5374 
5375       const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
5376 
5377       MaybeAlign Alignment;
5378 
5379       if (NumRecords == (OpNum + 5)) {
5380         if (Error Err = parseAlignmentValue(Record[OpNum + 4], Alignment))
5381           return Err;
5382       }
5383 
5384       if (!Alignment)
5385         Alignment =
5386             Align(TheModule->getDataLayout().getTypeStoreSize(Val->getType()));
5387 
5388       I = new AtomicRMWInst(Operation, Ptr, Val, *Alignment, Ordering, SSID);
5389       cast<AtomicRMWInst>(I)->setVolatile(IsVol);
5390 
5391       InstructionList.push_back(I);
5392       break;
5393     }
5394     case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid]
5395       if (2 != Record.size())
5396         return error("Invalid record");
5397       AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
5398       if (Ordering == AtomicOrdering::NotAtomic ||
5399           Ordering == AtomicOrdering::Unordered ||
5400           Ordering == AtomicOrdering::Monotonic)
5401         return error("Invalid record");
5402       SyncScope::ID SSID = getDecodedSyncScopeID(Record[1]);
5403       I = new FenceInst(Context, Ordering, SSID);
5404       InstructionList.push_back(I);
5405       break;
5406     }
5407     case bitc::FUNC_CODE_INST_CALL: {
5408       // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
5409       if (Record.size() < 3)
5410         return error("Invalid record");
5411 
5412       unsigned OpNum = 0;
5413       AttributeList PAL = getAttributes(Record[OpNum++]);
5414       unsigned CCInfo = Record[OpNum++];
5415 
5416       FastMathFlags FMF;
5417       if ((CCInfo >> bitc::CALL_FMF) & 1) {
5418         FMF = getDecodedFastMathFlags(Record[OpNum++]);
5419         if (!FMF.any())
5420           return error("Fast math flags indicator set for call with no FMF");
5421       }
5422 
5423       FunctionType *FTy = nullptr;
5424       if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) {
5425         FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]));
5426         if (!FTy)
5427           return error("Explicit call type is not a function type");
5428       }
5429 
5430       Value *Callee;
5431       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
5432         return error("Invalid record");
5433 
5434       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
5435       if (!OpTy)
5436         return error("Callee is not a pointer type");
5437       if (!FTy) {
5438         FTy =
5439             dyn_cast<FunctionType>(Callee->getType()->getPointerElementType());
5440         if (!FTy)
5441           return error("Callee is not of pointer to function type");
5442       } else if (!OpTy->isOpaqueOrPointeeTypeMatches(FTy))
5443         return error("Explicit call type does not match pointee type of "
5444                      "callee operand");
5445       if (Record.size() < FTy->getNumParams() + OpNum)
5446         return error("Insufficient operands to call");
5447 
5448       SmallVector<Value*, 16> Args;
5449       SmallVector<Type *, 16> ArgsTys;
5450       // Read the fixed params.
5451       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5452         if (FTy->getParamType(i)->isLabelTy())
5453           Args.push_back(getBasicBlock(Record[OpNum]));
5454         else
5455           Args.push_back(getValue(Record, OpNum, NextValueNo,
5456                                   FTy->getParamType(i)));
5457         ArgsTys.push_back(FTy->getParamType(i));
5458         if (!Args.back())
5459           return error("Invalid record");
5460       }
5461 
5462       // Read type/value pairs for varargs params.
5463       if (!FTy->isVarArg()) {
5464         if (OpNum != Record.size())
5465           return error("Invalid record");
5466       } else {
5467         while (OpNum != Record.size()) {
5468           Value *Op;
5469           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5470             return error("Invalid record");
5471           Args.push_back(Op);
5472           ArgsTys.push_back(Op->getType());
5473         }
5474       }
5475 
5476       I = CallInst::Create(FTy, Callee, Args, OperandBundles);
5477       OperandBundles.clear();
5478       InstructionList.push_back(I);
5479       cast<CallInst>(I)->setCallingConv(
5480           static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
5481       CallInst::TailCallKind TCK = CallInst::TCK_None;
5482       if (CCInfo & 1 << bitc::CALL_TAIL)
5483         TCK = CallInst::TCK_Tail;
5484       if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
5485         TCK = CallInst::TCK_MustTail;
5486       if (CCInfo & (1 << bitc::CALL_NOTAIL))
5487         TCK = CallInst::TCK_NoTail;
5488       cast<CallInst>(I)->setTailCallKind(TCK);
5489       cast<CallInst>(I)->setAttributes(PAL);
5490       propagateAttributeTypes(cast<CallBase>(I), ArgsTys);
5491       if (FMF.any()) {
5492         if (!isa<FPMathOperator>(I))
5493           return error("Fast-math-flags specified for call without "
5494                        "floating-point scalar or vector return type");
5495         I->setFastMathFlags(FMF);
5496       }
5497       break;
5498     }
5499     case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
5500       if (Record.size() < 3)
5501         return error("Invalid record");
5502       Type *OpTy = getTypeByID(Record[0]);
5503       Value *Op = getValue(Record, 1, NextValueNo, OpTy);
5504       Type *ResTy = getTypeByID(Record[2]);
5505       if (!OpTy || !Op || !ResTy)
5506         return error("Invalid record");
5507       I = new VAArgInst(Op, ResTy);
5508       InstructionList.push_back(I);
5509       break;
5510     }
5511 
5512     case bitc::FUNC_CODE_OPERAND_BUNDLE: {
5513       // A call or an invoke can be optionally prefixed with some variable
5514       // number of operand bundle blocks.  These blocks are read into
5515       // OperandBundles and consumed at the next call or invoke instruction.
5516 
5517       if (Record.empty() || Record[0] >= BundleTags.size())
5518         return error("Invalid record");
5519 
5520       std::vector<Value *> Inputs;
5521 
5522       unsigned OpNum = 1;
5523       while (OpNum != Record.size()) {
5524         Value *Op;
5525         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5526           return error("Invalid record");
5527         Inputs.push_back(Op);
5528       }
5529 
5530       OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
5531       continue;
5532     }
5533 
5534     case bitc::FUNC_CODE_INST_FREEZE: { // FREEZE: [opty,opval]
5535       unsigned OpNum = 0;
5536       Value *Op = nullptr;
5537       if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5538         return error("Invalid record");
5539       if (OpNum != Record.size())
5540         return error("Invalid record");
5541 
5542       I = new FreezeInst(Op);
5543       InstructionList.push_back(I);
5544       break;
5545     }
5546     }
5547 
5548     // Add instruction to end of current BB.  If there is no current BB, reject
5549     // this file.
5550     if (!CurBB) {
5551       I->deleteValue();
5552       return error("Invalid instruction with no BB");
5553     }
5554     if (!OperandBundles.empty()) {
5555       I->deleteValue();
5556       return error("Operand bundles found with no consumer");
5557     }
5558     CurBB->getInstList().push_back(I);
5559 
5560     // If this was a terminator instruction, move to the next block.
5561     if (I->isTerminator()) {
5562       ++CurBBNo;
5563       CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
5564     }
5565 
5566     // Non-void values get registered in the value table for future use.
5567     if (!I->getType()->isVoidTy())
5568       ValueList.assignValue(I, NextValueNo++);
5569   }
5570 
5571 OutOfRecordLoop:
5572 
5573   if (!OperandBundles.empty())
5574     return error("Operand bundles found with no consumer");
5575 
5576   // Check the function list for unresolved values.
5577   if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
5578     if (!A->getParent()) {
5579       // We found at least one unresolved value.  Nuke them all to avoid leaks.
5580       for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
5581         if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
5582           A->replaceAllUsesWith(UndefValue::get(A->getType()));
5583           delete A;
5584         }
5585       }
5586       return error("Never resolved value found in function");
5587     }
5588   }
5589 
5590   // Unexpected unresolved metadata about to be dropped.
5591   if (MDLoader->hasFwdRefs())
5592     return error("Invalid function metadata: outgoing forward refs");
5593 
5594   // Trim the value list down to the size it was before we parsed this function.
5595   ValueList.shrinkTo(ModuleValueListSize);
5596   MDLoader->shrinkTo(ModuleMDLoaderSize);
5597   std::vector<BasicBlock*>().swap(FunctionBBs);
5598   return Error::success();
5599 }
5600 
5601 /// Find the function body in the bitcode stream
5602 Error BitcodeReader::findFunctionInStream(
5603     Function *F,
5604     DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
5605   while (DeferredFunctionInfoIterator->second == 0) {
5606     // This is the fallback handling for the old format bitcode that
5607     // didn't contain the function index in the VST, or when we have
5608     // an anonymous function which would not have a VST entry.
5609     // Assert that we have one of those two cases.
5610     assert(VSTOffset == 0 || !F->hasName());
5611     // Parse the next body in the stream and set its position in the
5612     // DeferredFunctionInfo map.
5613     if (Error Err = rememberAndSkipFunctionBodies())
5614       return Err;
5615   }
5616   return Error::success();
5617 }
5618 
5619 SyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) {
5620   if (Val == SyncScope::SingleThread || Val == SyncScope::System)
5621     return SyncScope::ID(Val);
5622   if (Val >= SSIDs.size())
5623     return SyncScope::System; // Map unknown synchronization scopes to system.
5624   return SSIDs[Val];
5625 }
5626 
5627 //===----------------------------------------------------------------------===//
5628 // GVMaterializer implementation
5629 //===----------------------------------------------------------------------===//
5630 
5631 Error BitcodeReader::materialize(GlobalValue *GV) {
5632   Function *F = dyn_cast<Function>(GV);
5633   // If it's not a function or is already material, ignore the request.
5634   if (!F || !F->isMaterializable())
5635     return Error::success();
5636 
5637   DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
5638   assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
5639   // If its position is recorded as 0, its body is somewhere in the stream
5640   // but we haven't seen it yet.
5641   if (DFII->second == 0)
5642     if (Error Err = findFunctionInStream(F, DFII))
5643       return Err;
5644 
5645   // Materialize metadata before parsing any function bodies.
5646   if (Error Err = materializeMetadata())
5647     return Err;
5648 
5649   // Move the bit stream to the saved position of the deferred function body.
5650   if (Error JumpFailed = Stream.JumpToBit(DFII->second))
5651     return JumpFailed;
5652   if (Error Err = parseFunctionBody(F))
5653     return Err;
5654   F->setIsMaterializable(false);
5655 
5656   if (StripDebugInfo)
5657     stripDebugInfo(*F);
5658 
5659   // Upgrade any old intrinsic calls in the function.
5660   for (auto &I : UpgradedIntrinsics) {
5661     for (User *U : llvm::make_early_inc_range(I.first->materialized_users()))
5662       if (CallInst *CI = dyn_cast<CallInst>(U))
5663         UpgradeIntrinsicCall(CI, I.second);
5664   }
5665 
5666   // Update calls to the remangled intrinsics
5667   for (auto &I : RemangledIntrinsics)
5668     for (User *U : llvm::make_early_inc_range(I.first->materialized_users()))
5669       // Don't expect any other users than call sites
5670       cast<CallBase>(U)->setCalledFunction(I.second);
5671 
5672   // Finish fn->subprogram upgrade for materialized functions.
5673   if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F))
5674     F->setSubprogram(SP);
5675 
5676   // Check if the TBAA Metadata are valid, otherwise we will need to strip them.
5677   if (!MDLoader->isStrippingTBAA()) {
5678     for (auto &I : instructions(F)) {
5679       MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa);
5680       if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA))
5681         continue;
5682       MDLoader->setStripTBAA(true);
5683       stripTBAA(F->getParent());
5684     }
5685   }
5686 
5687   for (auto &I : instructions(F)) {
5688     // "Upgrade" older incorrect branch weights by dropping them.
5689     if (auto *MD = I.getMetadata(LLVMContext::MD_prof)) {
5690       if (MD->getOperand(0) != nullptr && isa<MDString>(MD->getOperand(0))) {
5691         MDString *MDS = cast<MDString>(MD->getOperand(0));
5692         StringRef ProfName = MDS->getString();
5693         // Check consistency of !prof branch_weights metadata.
5694         if (!ProfName.equals("branch_weights"))
5695           continue;
5696         unsigned ExpectedNumOperands = 0;
5697         if (BranchInst *BI = dyn_cast<BranchInst>(&I))
5698           ExpectedNumOperands = BI->getNumSuccessors();
5699         else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I))
5700           ExpectedNumOperands = SI->getNumSuccessors();
5701         else if (isa<CallInst>(&I))
5702           ExpectedNumOperands = 1;
5703         else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I))
5704           ExpectedNumOperands = IBI->getNumDestinations();
5705         else if (isa<SelectInst>(&I))
5706           ExpectedNumOperands = 2;
5707         else
5708           continue; // ignore and continue.
5709 
5710         // If branch weight doesn't match, just strip branch weight.
5711         if (MD->getNumOperands() != 1 + ExpectedNumOperands)
5712           I.setMetadata(LLVMContext::MD_prof, nullptr);
5713       }
5714     }
5715 
5716     // Remove incompatible attributes on function calls.
5717     if (auto *CI = dyn_cast<CallBase>(&I)) {
5718       CI->removeRetAttrs(AttributeFuncs::typeIncompatible(
5719           CI->getFunctionType()->getReturnType()));
5720 
5721       for (unsigned ArgNo = 0; ArgNo < CI->arg_size(); ++ArgNo)
5722         CI->removeParamAttrs(ArgNo, AttributeFuncs::typeIncompatible(
5723                                         CI->getArgOperand(ArgNo)->getType()));
5724     }
5725   }
5726 
5727   // Look for functions that rely on old function attribute behavior.
5728   UpgradeFunctionAttributes(*F);
5729 
5730   // Bring in any functions that this function forward-referenced via
5731   // blockaddresses.
5732   return materializeForwardReferencedFunctions();
5733 }
5734 
5735 Error BitcodeReader::materializeModule() {
5736   if (Error Err = materializeMetadata())
5737     return Err;
5738 
5739   // Promise to materialize all forward references.
5740   WillMaterializeAllForwardRefs = true;
5741 
5742   // Iterate over the module, deserializing any functions that are still on
5743   // disk.
5744   for (Function &F : *TheModule) {
5745     if (Error Err = materialize(&F))
5746       return Err;
5747   }
5748   // At this point, if there are any function bodies, parse the rest of
5749   // the bits in the module past the last function block we have recorded
5750   // through either lazy scanning or the VST.
5751   if (LastFunctionBlockBit || NextUnreadBit)
5752     if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit
5753                                     ? LastFunctionBlockBit
5754                                     : NextUnreadBit))
5755       return Err;
5756 
5757   // Check that all block address forward references got resolved (as we
5758   // promised above).
5759   if (!BasicBlockFwdRefs.empty())
5760     return error("Never resolved function from blockaddress");
5761 
5762   // Upgrade any intrinsic calls that slipped through (should not happen!) and
5763   // delete the old functions to clean up. We can't do this unless the entire
5764   // module is materialized because there could always be another function body
5765   // with calls to the old function.
5766   for (auto &I : UpgradedIntrinsics) {
5767     for (auto *U : I.first->users()) {
5768       if (CallInst *CI = dyn_cast<CallInst>(U))
5769         UpgradeIntrinsicCall(CI, I.second);
5770     }
5771     if (!I.first->use_empty())
5772       I.first->replaceAllUsesWith(I.second);
5773     I.first->eraseFromParent();
5774   }
5775   UpgradedIntrinsics.clear();
5776   // Do the same for remangled intrinsics
5777   for (auto &I : RemangledIntrinsics) {
5778     I.first->replaceAllUsesWith(I.second);
5779     I.first->eraseFromParent();
5780   }
5781   RemangledIntrinsics.clear();
5782 
5783   UpgradeDebugInfo(*TheModule);
5784 
5785   UpgradeModuleFlags(*TheModule);
5786 
5787   UpgradeARCRuntime(*TheModule);
5788 
5789   return Error::success();
5790 }
5791 
5792 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
5793   return IdentifiedStructTypes;
5794 }
5795 
5796 ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
5797     BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex,
5798     StringRef ModulePath, unsigned ModuleId)
5799     : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex),
5800       ModulePath(ModulePath), ModuleId(ModuleId) {}
5801 
5802 void ModuleSummaryIndexBitcodeReader::addThisModule() {
5803   TheIndex.addModule(ModulePath, ModuleId);
5804 }
5805 
5806 ModuleSummaryIndex::ModuleInfo *
5807 ModuleSummaryIndexBitcodeReader::getThisModule() {
5808   return TheIndex.getModule(ModulePath);
5809 }
5810 
5811 std::pair<ValueInfo, GlobalValue::GUID>
5812 ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) {
5813   auto VGI = ValueIdToValueInfoMap[ValueId];
5814   assert(VGI.first);
5815   return VGI;
5816 }
5817 
5818 void ModuleSummaryIndexBitcodeReader::setValueGUID(
5819     uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage,
5820     StringRef SourceFileName) {
5821   std::string GlobalId =
5822       GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
5823   auto ValueGUID = GlobalValue::getGUID(GlobalId);
5824   auto OriginalNameID = ValueGUID;
5825   if (GlobalValue::isLocalLinkage(Linkage))
5826     OriginalNameID = GlobalValue::getGUID(ValueName);
5827   if (PrintSummaryGUIDs)
5828     dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
5829            << ValueName << "\n";
5830 
5831   // UseStrtab is false for legacy summary formats and value names are
5832   // created on stack. In that case we save the name in a string saver in
5833   // the index so that the value name can be recorded.
5834   ValueIdToValueInfoMap[ValueID] = std::make_pair(
5835       TheIndex.getOrInsertValueInfo(
5836           ValueGUID,
5837           UseStrtab ? ValueName : TheIndex.saveString(ValueName)),
5838       OriginalNameID);
5839 }
5840 
5841 // Specialized value symbol table parser used when reading module index
5842 // blocks where we don't actually create global values. The parsed information
5843 // is saved in the bitcode reader for use when later parsing summaries.
5844 Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
5845     uint64_t Offset,
5846     DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
5847   // With a strtab the VST is not required to parse the summary.
5848   if (UseStrtab)
5849     return Error::success();
5850 
5851   assert(Offset > 0 && "Expected non-zero VST offset");
5852   Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream);
5853   if (!MaybeCurrentBit)
5854     return MaybeCurrentBit.takeError();
5855   uint64_t CurrentBit = MaybeCurrentBit.get();
5856 
5857   if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
5858     return Err;
5859 
5860   SmallVector<uint64_t, 64> Record;
5861 
5862   // Read all the records for this value table.
5863   SmallString<128> ValueName;
5864 
5865   while (true) {
5866     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
5867     if (!MaybeEntry)
5868       return MaybeEntry.takeError();
5869     BitstreamEntry Entry = MaybeEntry.get();
5870 
5871     switch (Entry.Kind) {
5872     case BitstreamEntry::SubBlock: // Handled for us already.
5873     case BitstreamEntry::Error:
5874       return error("Malformed block");
5875     case BitstreamEntry::EndBlock:
5876       // Done parsing VST, jump back to wherever we came from.
5877       if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
5878         return JumpFailed;
5879       return Error::success();
5880     case BitstreamEntry::Record:
5881       // The interesting case.
5882       break;
5883     }
5884 
5885     // Read a record.
5886     Record.clear();
5887     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
5888     if (!MaybeRecord)
5889       return MaybeRecord.takeError();
5890     switch (MaybeRecord.get()) {
5891     default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
5892       break;
5893     case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
5894       if (convertToString(Record, 1, ValueName))
5895         return error("Invalid record");
5896       unsigned ValueID = Record[0];
5897       assert(!SourceFileName.empty());
5898       auto VLI = ValueIdToLinkageMap.find(ValueID);
5899       assert(VLI != ValueIdToLinkageMap.end() &&
5900              "No linkage found for VST entry?");
5901       auto Linkage = VLI->second;
5902       setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
5903       ValueName.clear();
5904       break;
5905     }
5906     case bitc::VST_CODE_FNENTRY: {
5907       // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
5908       if (convertToString(Record, 2, ValueName))
5909         return error("Invalid record");
5910       unsigned ValueID = Record[0];
5911       assert(!SourceFileName.empty());
5912       auto VLI = ValueIdToLinkageMap.find(ValueID);
5913       assert(VLI != ValueIdToLinkageMap.end() &&
5914              "No linkage found for VST entry?");
5915       auto Linkage = VLI->second;
5916       setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
5917       ValueName.clear();
5918       break;
5919     }
5920     case bitc::VST_CODE_COMBINED_ENTRY: {
5921       // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
5922       unsigned ValueID = Record[0];
5923       GlobalValue::GUID RefGUID = Record[1];
5924       // The "original name", which is the second value of the pair will be
5925       // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
5926       ValueIdToValueInfoMap[ValueID] =
5927           std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
5928       break;
5929     }
5930     }
5931   }
5932 }
5933 
5934 // Parse just the blocks needed for building the index out of the module.
5935 // At the end of this routine the module Index is populated with a map
5936 // from global value id to GlobalValueSummary objects.
5937 Error ModuleSummaryIndexBitcodeReader::parseModule() {
5938   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5939     return Err;
5940 
5941   SmallVector<uint64_t, 64> Record;
5942   DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
5943   unsigned ValueId = 0;
5944 
5945   // Read the index for this module.
5946   while (true) {
5947     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5948     if (!MaybeEntry)
5949       return MaybeEntry.takeError();
5950     llvm::BitstreamEntry Entry = MaybeEntry.get();
5951 
5952     switch (Entry.Kind) {
5953     case BitstreamEntry::Error:
5954       return error("Malformed block");
5955     case BitstreamEntry::EndBlock:
5956       return Error::success();
5957 
5958     case BitstreamEntry::SubBlock:
5959       switch (Entry.ID) {
5960       default: // Skip unknown content.
5961         if (Error Err = Stream.SkipBlock())
5962           return Err;
5963         break;
5964       case bitc::BLOCKINFO_BLOCK_ID:
5965         // Need to parse these to get abbrev ids (e.g. for VST)
5966         if (Error Err = readBlockInfo())
5967           return Err;
5968         break;
5969       case bitc::VALUE_SYMTAB_BLOCK_ID:
5970         // Should have been parsed earlier via VSTOffset, unless there
5971         // is no summary section.
5972         assert(((SeenValueSymbolTable && VSTOffset > 0) ||
5973                 !SeenGlobalValSummary) &&
5974                "Expected early VST parse via VSTOffset record");
5975         if (Error Err = Stream.SkipBlock())
5976           return Err;
5977         break;
5978       case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
5979       case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID:
5980         // Add the module if it is a per-module index (has a source file name).
5981         if (!SourceFileName.empty())
5982           addThisModule();
5983         assert(!SeenValueSymbolTable &&
5984                "Already read VST when parsing summary block?");
5985         // We might not have a VST if there were no values in the
5986         // summary. An empty summary block generated when we are
5987         // performing ThinLTO compiles so we don't later invoke
5988         // the regular LTO process on them.
5989         if (VSTOffset > 0) {
5990           if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
5991             return Err;
5992           SeenValueSymbolTable = true;
5993         }
5994         SeenGlobalValSummary = true;
5995         if (Error Err = parseEntireSummary(Entry.ID))
5996           return Err;
5997         break;
5998       case bitc::MODULE_STRTAB_BLOCK_ID:
5999         if (Error Err = parseModuleStringTable())
6000           return Err;
6001         break;
6002       }
6003       continue;
6004 
6005     case BitstreamEntry::Record: {
6006         Record.clear();
6007         Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
6008         if (!MaybeBitCode)
6009           return MaybeBitCode.takeError();
6010         switch (MaybeBitCode.get()) {
6011         default:
6012           break; // Default behavior, ignore unknown content.
6013         case bitc::MODULE_CODE_VERSION: {
6014           if (Error Err = parseVersionRecord(Record).takeError())
6015             return Err;
6016           break;
6017         }
6018         /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
6019         case bitc::MODULE_CODE_SOURCE_FILENAME: {
6020           SmallString<128> ValueName;
6021           if (convertToString(Record, 0, ValueName))
6022             return error("Invalid record");
6023           SourceFileName = ValueName.c_str();
6024           break;
6025         }
6026         /// MODULE_CODE_HASH: [5*i32]
6027         case bitc::MODULE_CODE_HASH: {
6028           if (Record.size() != 5)
6029             return error("Invalid hash length " + Twine(Record.size()).str());
6030           auto &Hash = getThisModule()->second.second;
6031           int Pos = 0;
6032           for (auto &Val : Record) {
6033             assert(!(Val >> 32) && "Unexpected high bits set");
6034             Hash[Pos++] = Val;
6035           }
6036           break;
6037         }
6038         /// MODULE_CODE_VSTOFFSET: [offset]
6039         case bitc::MODULE_CODE_VSTOFFSET:
6040           if (Record.empty())
6041             return error("Invalid record");
6042           // Note that we subtract 1 here because the offset is relative to one
6043           // word before the start of the identification or module block, which
6044           // was historically always the start of the regular bitcode header.
6045           VSTOffset = Record[0] - 1;
6046           break;
6047         // v1 GLOBALVAR: [pointer type, isconst,     initid,       linkage, ...]
6048         // v1 FUNCTION:  [type,         callingconv, isproto,      linkage, ...]
6049         // v1 ALIAS:     [alias type,   addrspace,   aliasee val#, linkage, ...]
6050         // v2: [strtab offset, strtab size, v1]
6051         case bitc::MODULE_CODE_GLOBALVAR:
6052         case bitc::MODULE_CODE_FUNCTION:
6053         case bitc::MODULE_CODE_ALIAS: {
6054           StringRef Name;
6055           ArrayRef<uint64_t> GVRecord;
6056           std::tie(Name, GVRecord) = readNameFromStrtab(Record);
6057           if (GVRecord.size() <= 3)
6058             return error("Invalid record");
6059           uint64_t RawLinkage = GVRecord[3];
6060           GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
6061           if (!UseStrtab) {
6062             ValueIdToLinkageMap[ValueId++] = Linkage;
6063             break;
6064           }
6065 
6066           setValueGUID(ValueId++, Name, Linkage, SourceFileName);
6067           break;
6068         }
6069         }
6070       }
6071       continue;
6072     }
6073   }
6074 }
6075 
6076 std::vector<ValueInfo>
6077 ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
6078   std::vector<ValueInfo> Ret;
6079   Ret.reserve(Record.size());
6080   for (uint64_t RefValueId : Record)
6081     Ret.push_back(getValueInfoFromValueId(RefValueId).first);
6082   return Ret;
6083 }
6084 
6085 std::vector<FunctionSummary::EdgeTy>
6086 ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record,
6087                                               bool IsOldProfileFormat,
6088                                               bool HasProfile, bool HasRelBF) {
6089   std::vector<FunctionSummary::EdgeTy> Ret;
6090   Ret.reserve(Record.size());
6091   for (unsigned I = 0, E = Record.size(); I != E; ++I) {
6092     CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
6093     uint64_t RelBF = 0;
6094     ValueInfo Callee = getValueInfoFromValueId(Record[I]).first;
6095     if (IsOldProfileFormat) {
6096       I += 1; // Skip old callsitecount field
6097       if (HasProfile)
6098         I += 1; // Skip old profilecount field
6099     } else if (HasProfile)
6100       Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]);
6101     else if (HasRelBF)
6102       RelBF = Record[++I];
6103     Ret.push_back(FunctionSummary::EdgeTy{Callee, CalleeInfo(Hotness, RelBF)});
6104   }
6105   return Ret;
6106 }
6107 
6108 static void
6109 parseWholeProgramDevirtResolutionByArg(ArrayRef<uint64_t> Record, size_t &Slot,
6110                                        WholeProgramDevirtResolution &Wpd) {
6111   uint64_t ArgNum = Record[Slot++];
6112   WholeProgramDevirtResolution::ByArg &B =
6113       Wpd.ResByArg[{Record.begin() + Slot, Record.begin() + Slot + ArgNum}];
6114   Slot += ArgNum;
6115 
6116   B.TheKind =
6117       static_cast<WholeProgramDevirtResolution::ByArg::Kind>(Record[Slot++]);
6118   B.Info = Record[Slot++];
6119   B.Byte = Record[Slot++];
6120   B.Bit = Record[Slot++];
6121 }
6122 
6123 static void parseWholeProgramDevirtResolution(ArrayRef<uint64_t> Record,
6124                                               StringRef Strtab, size_t &Slot,
6125                                               TypeIdSummary &TypeId) {
6126   uint64_t Id = Record[Slot++];
6127   WholeProgramDevirtResolution &Wpd = TypeId.WPDRes[Id];
6128 
6129   Wpd.TheKind = static_cast<WholeProgramDevirtResolution::Kind>(Record[Slot++]);
6130   Wpd.SingleImplName = {Strtab.data() + Record[Slot],
6131                         static_cast<size_t>(Record[Slot + 1])};
6132   Slot += 2;
6133 
6134   uint64_t ResByArgNum = Record[Slot++];
6135   for (uint64_t I = 0; I != ResByArgNum; ++I)
6136     parseWholeProgramDevirtResolutionByArg(Record, Slot, Wpd);
6137 }
6138 
6139 static void parseTypeIdSummaryRecord(ArrayRef<uint64_t> Record,
6140                                      StringRef Strtab,
6141                                      ModuleSummaryIndex &TheIndex) {
6142   size_t Slot = 0;
6143   TypeIdSummary &TypeId = TheIndex.getOrInsertTypeIdSummary(
6144       {Strtab.data() + Record[Slot], static_cast<size_t>(Record[Slot + 1])});
6145   Slot += 2;
6146 
6147   TypeId.TTRes.TheKind = static_cast<TypeTestResolution::Kind>(Record[Slot++]);
6148   TypeId.TTRes.SizeM1BitWidth = Record[Slot++];
6149   TypeId.TTRes.AlignLog2 = Record[Slot++];
6150   TypeId.TTRes.SizeM1 = Record[Slot++];
6151   TypeId.TTRes.BitMask = Record[Slot++];
6152   TypeId.TTRes.InlineBits = Record[Slot++];
6153 
6154   while (Slot < Record.size())
6155     parseWholeProgramDevirtResolution(Record, Strtab, Slot, TypeId);
6156 }
6157 
6158 std::vector<FunctionSummary::ParamAccess>
6159 ModuleSummaryIndexBitcodeReader::parseParamAccesses(ArrayRef<uint64_t> Record) {
6160   auto ReadRange = [&]() {
6161     APInt Lower(FunctionSummary::ParamAccess::RangeWidth,
6162                 BitcodeReader::decodeSignRotatedValue(Record.front()));
6163     Record = Record.drop_front();
6164     APInt Upper(FunctionSummary::ParamAccess::RangeWidth,
6165                 BitcodeReader::decodeSignRotatedValue(Record.front()));
6166     Record = Record.drop_front();
6167     ConstantRange Range{Lower, Upper};
6168     assert(!Range.isFullSet());
6169     assert(!Range.isUpperSignWrapped());
6170     return Range;
6171   };
6172 
6173   std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
6174   while (!Record.empty()) {
6175     PendingParamAccesses.emplace_back();
6176     FunctionSummary::ParamAccess &ParamAccess = PendingParamAccesses.back();
6177     ParamAccess.ParamNo = Record.front();
6178     Record = Record.drop_front();
6179     ParamAccess.Use = ReadRange();
6180     ParamAccess.Calls.resize(Record.front());
6181     Record = Record.drop_front();
6182     for (auto &Call : ParamAccess.Calls) {
6183       Call.ParamNo = Record.front();
6184       Record = Record.drop_front();
6185       Call.Callee = getValueInfoFromValueId(Record.front()).first;
6186       Record = Record.drop_front();
6187       Call.Offsets = ReadRange();
6188     }
6189   }
6190   return PendingParamAccesses;
6191 }
6192 
6193 void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo(
6194     ArrayRef<uint64_t> Record, size_t &Slot,
6195     TypeIdCompatibleVtableInfo &TypeId) {
6196   uint64_t Offset = Record[Slot++];
6197   ValueInfo Callee = getValueInfoFromValueId(Record[Slot++]).first;
6198   TypeId.push_back({Offset, Callee});
6199 }
6200 
6201 void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord(
6202     ArrayRef<uint64_t> Record) {
6203   size_t Slot = 0;
6204   TypeIdCompatibleVtableInfo &TypeId =
6205       TheIndex.getOrInsertTypeIdCompatibleVtableSummary(
6206           {Strtab.data() + Record[Slot],
6207            static_cast<size_t>(Record[Slot + 1])});
6208   Slot += 2;
6209 
6210   while (Slot < Record.size())
6211     parseTypeIdCompatibleVtableInfo(Record, Slot, TypeId);
6212 }
6213 
6214 static void setSpecialRefs(std::vector<ValueInfo> &Refs, unsigned ROCnt,
6215                            unsigned WOCnt) {
6216   // Readonly and writeonly refs are in the end of the refs list.
6217   assert(ROCnt + WOCnt <= Refs.size());
6218   unsigned FirstWORef = Refs.size() - WOCnt;
6219   unsigned RefNo = FirstWORef - ROCnt;
6220   for (; RefNo < FirstWORef; ++RefNo)
6221     Refs[RefNo].setReadOnly();
6222   for (; RefNo < Refs.size(); ++RefNo)
6223     Refs[RefNo].setWriteOnly();
6224 }
6225 
6226 // Eagerly parse the entire summary block. This populates the GlobalValueSummary
6227 // objects in the index.
6228 Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) {
6229   if (Error Err = Stream.EnterSubBlock(ID))
6230     return Err;
6231   SmallVector<uint64_t, 64> Record;
6232 
6233   // Parse version
6234   {
6235     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
6236     if (!MaybeEntry)
6237       return MaybeEntry.takeError();
6238     BitstreamEntry Entry = MaybeEntry.get();
6239 
6240     if (Entry.Kind != BitstreamEntry::Record)
6241       return error("Invalid Summary Block: record for version expected");
6242     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
6243     if (!MaybeRecord)
6244       return MaybeRecord.takeError();
6245     if (MaybeRecord.get() != bitc::FS_VERSION)
6246       return error("Invalid Summary Block: version expected");
6247   }
6248   const uint64_t Version = Record[0];
6249   const bool IsOldProfileFormat = Version == 1;
6250   if (Version < 1 || Version > ModuleSummaryIndex::BitcodeSummaryVersion)
6251     return error("Invalid summary version " + Twine(Version) +
6252                  ". Version should be in the range [1-" +
6253                  Twine(ModuleSummaryIndex::BitcodeSummaryVersion) +
6254                  "].");
6255   Record.clear();
6256 
6257   // Keep around the last seen summary to be used when we see an optional
6258   // "OriginalName" attachement.
6259   GlobalValueSummary *LastSeenSummary = nullptr;
6260   GlobalValue::GUID LastSeenGUID = 0;
6261 
6262   // We can expect to see any number of type ID information records before
6263   // each function summary records; these variables store the information
6264   // collected so far so that it can be used to create the summary object.
6265   std::vector<GlobalValue::GUID> PendingTypeTests;
6266   std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
6267       PendingTypeCheckedLoadVCalls;
6268   std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
6269       PendingTypeCheckedLoadConstVCalls;
6270   std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
6271 
6272   while (true) {
6273     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
6274     if (!MaybeEntry)
6275       return MaybeEntry.takeError();
6276     BitstreamEntry Entry = MaybeEntry.get();
6277 
6278     switch (Entry.Kind) {
6279     case BitstreamEntry::SubBlock: // Handled for us already.
6280     case BitstreamEntry::Error:
6281       return error("Malformed block");
6282     case BitstreamEntry::EndBlock:
6283       return Error::success();
6284     case BitstreamEntry::Record:
6285       // The interesting case.
6286       break;
6287     }
6288 
6289     // Read a record. The record format depends on whether this
6290     // is a per-module index or a combined index file. In the per-module
6291     // case the records contain the associated value's ID for correlation
6292     // with VST entries. In the combined index the correlation is done
6293     // via the bitcode offset of the summary records (which were saved
6294     // in the combined index VST entries). The records also contain
6295     // information used for ThinLTO renaming and importing.
6296     Record.clear();
6297     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
6298     if (!MaybeBitCode)
6299       return MaybeBitCode.takeError();
6300     switch (unsigned BitCode = MaybeBitCode.get()) {
6301     default: // Default behavior: ignore.
6302       break;
6303     case bitc::FS_FLAGS: {  // [flags]
6304       TheIndex.setFlags(Record[0]);
6305       break;
6306     }
6307     case bitc::FS_VALUE_GUID: { // [valueid, refguid]
6308       uint64_t ValueID = Record[0];
6309       GlobalValue::GUID RefGUID = Record[1];
6310       ValueIdToValueInfoMap[ValueID] =
6311           std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
6312       break;
6313     }
6314     // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs,
6315     //                numrefs x valueid, n x (valueid)]
6316     // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs,
6317     //                        numrefs x valueid,
6318     //                        n x (valueid, hotness)]
6319     // FS_PERMODULE_RELBF: [valueid, flags, instcount, fflags, numrefs,
6320     //                      numrefs x valueid,
6321     //                      n x (valueid, relblockfreq)]
6322     case bitc::FS_PERMODULE:
6323     case bitc::FS_PERMODULE_RELBF:
6324     case bitc::FS_PERMODULE_PROFILE: {
6325       unsigned ValueID = Record[0];
6326       uint64_t RawFlags = Record[1];
6327       unsigned InstCount = Record[2];
6328       uint64_t RawFunFlags = 0;
6329       unsigned NumRefs = Record[3];
6330       unsigned NumRORefs = 0, NumWORefs = 0;
6331       int RefListStartIndex = 4;
6332       if (Version >= 4) {
6333         RawFunFlags = Record[3];
6334         NumRefs = Record[4];
6335         RefListStartIndex = 5;
6336         if (Version >= 5) {
6337           NumRORefs = Record[5];
6338           RefListStartIndex = 6;
6339           if (Version >= 7) {
6340             NumWORefs = Record[6];
6341             RefListStartIndex = 7;
6342           }
6343         }
6344       }
6345 
6346       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6347       // The module path string ref set in the summary must be owned by the
6348       // index's module string table. Since we don't have a module path
6349       // string table section in the per-module index, we create a single
6350       // module path string table entry with an empty (0) ID to take
6351       // ownership.
6352       int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
6353       assert(Record.size() >= RefListStartIndex + NumRefs &&
6354              "Record size inconsistent with number of references");
6355       std::vector<ValueInfo> Refs = makeRefList(
6356           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
6357       bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
6358       bool HasRelBF = (BitCode == bitc::FS_PERMODULE_RELBF);
6359       std::vector<FunctionSummary::EdgeTy> Calls = makeCallList(
6360           ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
6361           IsOldProfileFormat, HasProfile, HasRelBF);
6362       setSpecialRefs(Refs, NumRORefs, NumWORefs);
6363       auto FS = std::make_unique<FunctionSummary>(
6364           Flags, InstCount, getDecodedFFlags(RawFunFlags), /*EntryCount=*/0,
6365           std::move(Refs), std::move(Calls), std::move(PendingTypeTests),
6366           std::move(PendingTypeTestAssumeVCalls),
6367           std::move(PendingTypeCheckedLoadVCalls),
6368           std::move(PendingTypeTestAssumeConstVCalls),
6369           std::move(PendingTypeCheckedLoadConstVCalls),
6370           std::move(PendingParamAccesses));
6371       auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID);
6372       FS->setModulePath(getThisModule()->first());
6373       FS->setOriginalName(VIAndOriginalGUID.second);
6374       TheIndex.addGlobalValueSummary(VIAndOriginalGUID.first, std::move(FS));
6375       break;
6376     }
6377     // FS_ALIAS: [valueid, flags, valueid]
6378     // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
6379     // they expect all aliasee summaries to be available.
6380     case bitc::FS_ALIAS: {
6381       unsigned ValueID = Record[0];
6382       uint64_t RawFlags = Record[1];
6383       unsigned AliaseeID = Record[2];
6384       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6385       auto AS = std::make_unique<AliasSummary>(Flags);
6386       // The module path string ref set in the summary must be owned by the
6387       // index's module string table. Since we don't have a module path
6388       // string table section in the per-module index, we create a single
6389       // module path string table entry with an empty (0) ID to take
6390       // ownership.
6391       AS->setModulePath(getThisModule()->first());
6392 
6393       auto AliaseeVI = getValueInfoFromValueId(AliaseeID).first;
6394       auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, ModulePath);
6395       if (!AliaseeInModule)
6396         return error("Alias expects aliasee summary to be parsed");
6397       AS->setAliasee(AliaseeVI, AliaseeInModule);
6398 
6399       auto GUID = getValueInfoFromValueId(ValueID);
6400       AS->setOriginalName(GUID.second);
6401       TheIndex.addGlobalValueSummary(GUID.first, std::move(AS));
6402       break;
6403     }
6404     // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, n x valueid]
6405     case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
6406       unsigned ValueID = Record[0];
6407       uint64_t RawFlags = Record[1];
6408       unsigned RefArrayStart = 2;
6409       GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false,
6410                                       /* WriteOnly */ false,
6411                                       /* Constant */ false,
6412                                       GlobalObject::VCallVisibilityPublic);
6413       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6414       if (Version >= 5) {
6415         GVF = getDecodedGVarFlags(Record[2]);
6416         RefArrayStart = 3;
6417       }
6418       std::vector<ValueInfo> Refs =
6419           makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
6420       auto FS =
6421           std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
6422       FS->setModulePath(getThisModule()->first());
6423       auto GUID = getValueInfoFromValueId(ValueID);
6424       FS->setOriginalName(GUID.second);
6425       TheIndex.addGlobalValueSummary(GUID.first, std::move(FS));
6426       break;
6427     }
6428     // FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags,
6429     //                        numrefs, numrefs x valueid,
6430     //                        n x (valueid, offset)]
6431     case bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: {
6432       unsigned ValueID = Record[0];
6433       uint64_t RawFlags = Record[1];
6434       GlobalVarSummary::GVarFlags GVF = getDecodedGVarFlags(Record[2]);
6435       unsigned NumRefs = Record[3];
6436       unsigned RefListStartIndex = 4;
6437       unsigned VTableListStartIndex = RefListStartIndex + NumRefs;
6438       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6439       std::vector<ValueInfo> Refs = makeRefList(
6440           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
6441       VTableFuncList VTableFuncs;
6442       for (unsigned I = VTableListStartIndex, E = Record.size(); I != E; ++I) {
6443         ValueInfo Callee = getValueInfoFromValueId(Record[I]).first;
6444         uint64_t Offset = Record[++I];
6445         VTableFuncs.push_back({Callee, Offset});
6446       }
6447       auto VS =
6448           std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
6449       VS->setModulePath(getThisModule()->first());
6450       VS->setVTableFuncs(VTableFuncs);
6451       auto GUID = getValueInfoFromValueId(ValueID);
6452       VS->setOriginalName(GUID.second);
6453       TheIndex.addGlobalValueSummary(GUID.first, std::move(VS));
6454       break;
6455     }
6456     // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs,
6457     //               numrefs x valueid, n x (valueid)]
6458     // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs,
6459     //                       numrefs x valueid, n x (valueid, hotness)]
6460     case bitc::FS_COMBINED:
6461     case bitc::FS_COMBINED_PROFILE: {
6462       unsigned ValueID = Record[0];
6463       uint64_t ModuleId = Record[1];
6464       uint64_t RawFlags = Record[2];
6465       unsigned InstCount = Record[3];
6466       uint64_t RawFunFlags = 0;
6467       uint64_t EntryCount = 0;
6468       unsigned NumRefs = Record[4];
6469       unsigned NumRORefs = 0, NumWORefs = 0;
6470       int RefListStartIndex = 5;
6471 
6472       if (Version >= 4) {
6473         RawFunFlags = Record[4];
6474         RefListStartIndex = 6;
6475         size_t NumRefsIndex = 5;
6476         if (Version >= 5) {
6477           unsigned NumRORefsOffset = 1;
6478           RefListStartIndex = 7;
6479           if (Version >= 6) {
6480             NumRefsIndex = 6;
6481             EntryCount = Record[5];
6482             RefListStartIndex = 8;
6483             if (Version >= 7) {
6484               RefListStartIndex = 9;
6485               NumWORefs = Record[8];
6486               NumRORefsOffset = 2;
6487             }
6488           }
6489           NumRORefs = Record[RefListStartIndex - NumRORefsOffset];
6490         }
6491         NumRefs = Record[NumRefsIndex];
6492       }
6493 
6494       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6495       int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
6496       assert(Record.size() >= RefListStartIndex + NumRefs &&
6497              "Record size inconsistent with number of references");
6498       std::vector<ValueInfo> Refs = makeRefList(
6499           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
6500       bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
6501       std::vector<FunctionSummary::EdgeTy> Edges = makeCallList(
6502           ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
6503           IsOldProfileFormat, HasProfile, false);
6504       ValueInfo VI = getValueInfoFromValueId(ValueID).first;
6505       setSpecialRefs(Refs, NumRORefs, NumWORefs);
6506       auto FS = std::make_unique<FunctionSummary>(
6507           Flags, InstCount, getDecodedFFlags(RawFunFlags), EntryCount,
6508           std::move(Refs), std::move(Edges), std::move(PendingTypeTests),
6509           std::move(PendingTypeTestAssumeVCalls),
6510           std::move(PendingTypeCheckedLoadVCalls),
6511           std::move(PendingTypeTestAssumeConstVCalls),
6512           std::move(PendingTypeCheckedLoadConstVCalls),
6513           std::move(PendingParamAccesses));
6514       LastSeenSummary = FS.get();
6515       LastSeenGUID = VI.getGUID();
6516       FS->setModulePath(ModuleIdMap[ModuleId]);
6517       TheIndex.addGlobalValueSummary(VI, std::move(FS));
6518       break;
6519     }
6520     // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
6521     // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
6522     // they expect all aliasee summaries to be available.
6523     case bitc::FS_COMBINED_ALIAS: {
6524       unsigned ValueID = Record[0];
6525       uint64_t ModuleId = Record[1];
6526       uint64_t RawFlags = Record[2];
6527       unsigned AliaseeValueId = Record[3];
6528       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6529       auto AS = std::make_unique<AliasSummary>(Flags);
6530       LastSeenSummary = AS.get();
6531       AS->setModulePath(ModuleIdMap[ModuleId]);
6532 
6533       auto AliaseeVI = getValueInfoFromValueId(AliaseeValueId).first;
6534       auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, AS->modulePath());
6535       AS->setAliasee(AliaseeVI, AliaseeInModule);
6536 
6537       ValueInfo VI = getValueInfoFromValueId(ValueID).first;
6538       LastSeenGUID = VI.getGUID();
6539       TheIndex.addGlobalValueSummary(VI, std::move(AS));
6540       break;
6541     }
6542     // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
6543     case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
6544       unsigned ValueID = Record[0];
6545       uint64_t ModuleId = Record[1];
6546       uint64_t RawFlags = Record[2];
6547       unsigned RefArrayStart = 3;
6548       GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false,
6549                                       /* WriteOnly */ false,
6550                                       /* Constant */ false,
6551                                       GlobalObject::VCallVisibilityPublic);
6552       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6553       if (Version >= 5) {
6554         GVF = getDecodedGVarFlags(Record[3]);
6555         RefArrayStart = 4;
6556       }
6557       std::vector<ValueInfo> Refs =
6558           makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
6559       auto FS =
6560           std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
6561       LastSeenSummary = FS.get();
6562       FS->setModulePath(ModuleIdMap[ModuleId]);
6563       ValueInfo VI = getValueInfoFromValueId(ValueID).first;
6564       LastSeenGUID = VI.getGUID();
6565       TheIndex.addGlobalValueSummary(VI, std::move(FS));
6566       break;
6567     }
6568     // FS_COMBINED_ORIGINAL_NAME: [original_name]
6569     case bitc::FS_COMBINED_ORIGINAL_NAME: {
6570       uint64_t OriginalName = Record[0];
6571       if (!LastSeenSummary)
6572         return error("Name attachment that does not follow a combined record");
6573       LastSeenSummary->setOriginalName(OriginalName);
6574       TheIndex.addOriginalName(LastSeenGUID, OriginalName);
6575       // Reset the LastSeenSummary
6576       LastSeenSummary = nullptr;
6577       LastSeenGUID = 0;
6578       break;
6579     }
6580     case bitc::FS_TYPE_TESTS:
6581       assert(PendingTypeTests.empty());
6582       llvm::append_range(PendingTypeTests, Record);
6583       break;
6584 
6585     case bitc::FS_TYPE_TEST_ASSUME_VCALLS:
6586       assert(PendingTypeTestAssumeVCalls.empty());
6587       for (unsigned I = 0; I != Record.size(); I += 2)
6588         PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
6589       break;
6590 
6591     case bitc::FS_TYPE_CHECKED_LOAD_VCALLS:
6592       assert(PendingTypeCheckedLoadVCalls.empty());
6593       for (unsigned I = 0; I != Record.size(); I += 2)
6594         PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
6595       break;
6596 
6597     case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL:
6598       PendingTypeTestAssumeConstVCalls.push_back(
6599           {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
6600       break;
6601 
6602     case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL:
6603       PendingTypeCheckedLoadConstVCalls.push_back(
6604           {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
6605       break;
6606 
6607     case bitc::FS_CFI_FUNCTION_DEFS: {
6608       std::set<std::string> &CfiFunctionDefs = TheIndex.cfiFunctionDefs();
6609       for (unsigned I = 0; I != Record.size(); I += 2)
6610         CfiFunctionDefs.insert(
6611             {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
6612       break;
6613     }
6614 
6615     case bitc::FS_CFI_FUNCTION_DECLS: {
6616       std::set<std::string> &CfiFunctionDecls = TheIndex.cfiFunctionDecls();
6617       for (unsigned I = 0; I != Record.size(); I += 2)
6618         CfiFunctionDecls.insert(
6619             {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
6620       break;
6621     }
6622 
6623     case bitc::FS_TYPE_ID:
6624       parseTypeIdSummaryRecord(Record, Strtab, TheIndex);
6625       break;
6626 
6627     case bitc::FS_TYPE_ID_METADATA:
6628       parseTypeIdCompatibleVtableSummaryRecord(Record);
6629       break;
6630 
6631     case bitc::FS_BLOCK_COUNT:
6632       TheIndex.addBlockCount(Record[0]);
6633       break;
6634 
6635     case bitc::FS_PARAM_ACCESS: {
6636       PendingParamAccesses = parseParamAccesses(Record);
6637       break;
6638     }
6639     }
6640   }
6641   llvm_unreachable("Exit infinite loop");
6642 }
6643 
6644 // Parse the  module string table block into the Index.
6645 // This populates the ModulePathStringTable map in the index.
6646 Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
6647   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
6648     return Err;
6649 
6650   SmallVector<uint64_t, 64> Record;
6651 
6652   SmallString<128> ModulePath;
6653   ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr;
6654 
6655   while (true) {
6656     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
6657     if (!MaybeEntry)
6658       return MaybeEntry.takeError();
6659     BitstreamEntry Entry = MaybeEntry.get();
6660 
6661     switch (Entry.Kind) {
6662     case BitstreamEntry::SubBlock: // Handled for us already.
6663     case BitstreamEntry::Error:
6664       return error("Malformed block");
6665     case BitstreamEntry::EndBlock:
6666       return Error::success();
6667     case BitstreamEntry::Record:
6668       // The interesting case.
6669       break;
6670     }
6671 
6672     Record.clear();
6673     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
6674     if (!MaybeRecord)
6675       return MaybeRecord.takeError();
6676     switch (MaybeRecord.get()) {
6677     default: // Default behavior: ignore.
6678       break;
6679     case bitc::MST_CODE_ENTRY: {
6680       // MST_ENTRY: [modid, namechar x N]
6681       uint64_t ModuleId = Record[0];
6682 
6683       if (convertToString(Record, 1, ModulePath))
6684         return error("Invalid record");
6685 
6686       LastSeenModule = TheIndex.addModule(ModulePath, ModuleId);
6687       ModuleIdMap[ModuleId] = LastSeenModule->first();
6688 
6689       ModulePath.clear();
6690       break;
6691     }
6692     /// MST_CODE_HASH: [5*i32]
6693     case bitc::MST_CODE_HASH: {
6694       if (Record.size() != 5)
6695         return error("Invalid hash length " + Twine(Record.size()).str());
6696       if (!LastSeenModule)
6697         return error("Invalid hash that does not follow a module path");
6698       int Pos = 0;
6699       for (auto &Val : Record) {
6700         assert(!(Val >> 32) && "Unexpected high bits set");
6701         LastSeenModule->second.second[Pos++] = Val;
6702       }
6703       // Reset LastSeenModule to avoid overriding the hash unexpectedly.
6704       LastSeenModule = nullptr;
6705       break;
6706     }
6707     }
6708   }
6709   llvm_unreachable("Exit infinite loop");
6710 }
6711 
6712 namespace {
6713 
6714 // FIXME: This class is only here to support the transition to llvm::Error. It
6715 // will be removed once this transition is complete. Clients should prefer to
6716 // deal with the Error value directly, rather than converting to error_code.
6717 class BitcodeErrorCategoryType : public std::error_category {
6718   const char *name() const noexcept override {
6719     return "llvm.bitcode";
6720   }
6721 
6722   std::string message(int IE) const override {
6723     BitcodeError E = static_cast<BitcodeError>(IE);
6724     switch (E) {
6725     case BitcodeError::CorruptedBitcode:
6726       return "Corrupted bitcode";
6727     }
6728     llvm_unreachable("Unknown error type!");
6729   }
6730 };
6731 
6732 } // end anonymous namespace
6733 
6734 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
6735 
6736 const std::error_category &llvm::BitcodeErrorCategory() {
6737   return *ErrorCategory;
6738 }
6739 
6740 static Expected<StringRef> readBlobInRecord(BitstreamCursor &Stream,
6741                                             unsigned Block, unsigned RecordID) {
6742   if (Error Err = Stream.EnterSubBlock(Block))
6743     return std::move(Err);
6744 
6745   StringRef Strtab;
6746   while (true) {
6747     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
6748     if (!MaybeEntry)
6749       return MaybeEntry.takeError();
6750     llvm::BitstreamEntry Entry = MaybeEntry.get();
6751 
6752     switch (Entry.Kind) {
6753     case BitstreamEntry::EndBlock:
6754       return Strtab;
6755 
6756     case BitstreamEntry::Error:
6757       return error("Malformed block");
6758 
6759     case BitstreamEntry::SubBlock:
6760       if (Error Err = Stream.SkipBlock())
6761         return std::move(Err);
6762       break;
6763 
6764     case BitstreamEntry::Record:
6765       StringRef Blob;
6766       SmallVector<uint64_t, 1> Record;
6767       Expected<unsigned> MaybeRecord =
6768           Stream.readRecord(Entry.ID, Record, &Blob);
6769       if (!MaybeRecord)
6770         return MaybeRecord.takeError();
6771       if (MaybeRecord.get() == RecordID)
6772         Strtab = Blob;
6773       break;
6774     }
6775   }
6776 }
6777 
6778 //===----------------------------------------------------------------------===//
6779 // External interface
6780 //===----------------------------------------------------------------------===//
6781 
6782 Expected<std::vector<BitcodeModule>>
6783 llvm::getBitcodeModuleList(MemoryBufferRef Buffer) {
6784   auto FOrErr = getBitcodeFileContents(Buffer);
6785   if (!FOrErr)
6786     return FOrErr.takeError();
6787   return std::move(FOrErr->Mods);
6788 }
6789 
6790 Expected<BitcodeFileContents>
6791 llvm::getBitcodeFileContents(MemoryBufferRef Buffer) {
6792   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
6793   if (!StreamOrErr)
6794     return StreamOrErr.takeError();
6795   BitstreamCursor &Stream = *StreamOrErr;
6796 
6797   BitcodeFileContents F;
6798   while (true) {
6799     uint64_t BCBegin = Stream.getCurrentByteNo();
6800 
6801     // We may be consuming bitcode from a client that leaves garbage at the end
6802     // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to
6803     // the end that there cannot possibly be another module, stop looking.
6804     if (BCBegin + 8 >= Stream.getBitcodeBytes().size())
6805       return F;
6806 
6807     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
6808     if (!MaybeEntry)
6809       return MaybeEntry.takeError();
6810     llvm::BitstreamEntry Entry = MaybeEntry.get();
6811 
6812     switch (Entry.Kind) {
6813     case BitstreamEntry::EndBlock:
6814     case BitstreamEntry::Error:
6815       return error("Malformed block");
6816 
6817     case BitstreamEntry::SubBlock: {
6818       uint64_t IdentificationBit = -1ull;
6819       if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
6820         IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8;
6821         if (Error Err = Stream.SkipBlock())
6822           return std::move(Err);
6823 
6824         {
6825           Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
6826           if (!MaybeEntry)
6827             return MaybeEntry.takeError();
6828           Entry = MaybeEntry.get();
6829         }
6830 
6831         if (Entry.Kind != BitstreamEntry::SubBlock ||
6832             Entry.ID != bitc::MODULE_BLOCK_ID)
6833           return error("Malformed block");
6834       }
6835 
6836       if (Entry.ID == bitc::MODULE_BLOCK_ID) {
6837         uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8;
6838         if (Error Err = Stream.SkipBlock())
6839           return std::move(Err);
6840 
6841         F.Mods.push_back({Stream.getBitcodeBytes().slice(
6842                               BCBegin, Stream.getCurrentByteNo() - BCBegin),
6843                           Buffer.getBufferIdentifier(), IdentificationBit,
6844                           ModuleBit});
6845         continue;
6846       }
6847 
6848       if (Entry.ID == bitc::STRTAB_BLOCK_ID) {
6849         Expected<StringRef> Strtab =
6850             readBlobInRecord(Stream, bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB);
6851         if (!Strtab)
6852           return Strtab.takeError();
6853         // This string table is used by every preceding bitcode module that does
6854         // not have its own string table. A bitcode file may have multiple
6855         // string tables if it was created by binary concatenation, for example
6856         // with "llvm-cat -b".
6857         for (BitcodeModule &I : llvm::reverse(F.Mods)) {
6858           if (!I.Strtab.empty())
6859             break;
6860           I.Strtab = *Strtab;
6861         }
6862         // Similarly, the string table is used by every preceding symbol table;
6863         // normally there will be just one unless the bitcode file was created
6864         // by binary concatenation.
6865         if (!F.Symtab.empty() && F.StrtabForSymtab.empty())
6866           F.StrtabForSymtab = *Strtab;
6867         continue;
6868       }
6869 
6870       if (Entry.ID == bitc::SYMTAB_BLOCK_ID) {
6871         Expected<StringRef> SymtabOrErr =
6872             readBlobInRecord(Stream, bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB);
6873         if (!SymtabOrErr)
6874           return SymtabOrErr.takeError();
6875 
6876         // We can expect the bitcode file to have multiple symbol tables if it
6877         // was created by binary concatenation. In that case we silently
6878         // ignore any subsequent symbol tables, which is fine because this is a
6879         // low level function. The client is expected to notice that the number
6880         // of modules in the symbol table does not match the number of modules
6881         // in the input file and regenerate the symbol table.
6882         if (F.Symtab.empty())
6883           F.Symtab = *SymtabOrErr;
6884         continue;
6885       }
6886 
6887       if (Error Err = Stream.SkipBlock())
6888         return std::move(Err);
6889       continue;
6890     }
6891     case BitstreamEntry::Record:
6892       if (Error E = Stream.skipRecord(Entry.ID).takeError())
6893         return std::move(E);
6894       continue;
6895     }
6896   }
6897 }
6898 
6899 /// Get a lazy one-at-time loading module from bitcode.
6900 ///
6901 /// This isn't always used in a lazy context.  In particular, it's also used by
6902 /// \a parseModule().  If this is truly lazy, then we need to eagerly pull
6903 /// in forward-referenced functions from block address references.
6904 ///
6905 /// \param[in] MaterializeAll Set to \c true if we should materialize
6906 /// everything.
6907 Expected<std::unique_ptr<Module>>
6908 BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll,
6909                              bool ShouldLazyLoadMetadata, bool IsImporting,
6910                              DataLayoutCallbackTy DataLayoutCallback) {
6911   BitstreamCursor Stream(Buffer);
6912 
6913   std::string ProducerIdentification;
6914   if (IdentificationBit != -1ull) {
6915     if (Error JumpFailed = Stream.JumpToBit(IdentificationBit))
6916       return std::move(JumpFailed);
6917     if (Error E =
6918             readIdentificationBlock(Stream).moveInto(ProducerIdentification))
6919       return std::move(E);
6920   }
6921 
6922   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
6923     return std::move(JumpFailed);
6924   auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
6925                               Context);
6926 
6927   std::unique_ptr<Module> M =
6928       std::make_unique<Module>(ModuleIdentifier, Context);
6929   M->setMaterializer(R);
6930 
6931   // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
6932   if (Error Err = R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata,
6933                                       IsImporting, DataLayoutCallback))
6934     return std::move(Err);
6935 
6936   if (MaterializeAll) {
6937     // Read in the entire module, and destroy the BitcodeReader.
6938     if (Error Err = M->materializeAll())
6939       return std::move(Err);
6940   } else {
6941     // Resolve forward references from blockaddresses.
6942     if (Error Err = R->materializeForwardReferencedFunctions())
6943       return std::move(Err);
6944   }
6945   return std::move(M);
6946 }
6947 
6948 Expected<std::unique_ptr<Module>>
6949 BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata,
6950                              bool IsImporting) {
6951   return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting,
6952                        [](StringRef) { return None; });
6953 }
6954 
6955 // Parse the specified bitcode buffer and merge the index into CombinedIndex.
6956 // We don't use ModuleIdentifier here because the client may need to control the
6957 // module path used in the combined summary (e.g. when reading summaries for
6958 // regular LTO modules).
6959 Error BitcodeModule::readSummary(ModuleSummaryIndex &CombinedIndex,
6960                                  StringRef ModulePath, uint64_t ModuleId) {
6961   BitstreamCursor Stream(Buffer);
6962   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
6963     return JumpFailed;
6964 
6965   ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
6966                                     ModulePath, ModuleId);
6967   return R.parseModule();
6968 }
6969 
6970 // Parse the specified bitcode buffer, returning the function info index.
6971 Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() {
6972   BitstreamCursor Stream(Buffer);
6973   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
6974     return std::move(JumpFailed);
6975 
6976   auto Index = std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
6977   ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,
6978                                     ModuleIdentifier, 0);
6979 
6980   if (Error Err = R.parseModule())
6981     return std::move(Err);
6982 
6983   return std::move(Index);
6984 }
6985 
6986 static Expected<bool> getEnableSplitLTOUnitFlag(BitstreamCursor &Stream,
6987                                                 unsigned ID) {
6988   if (Error Err = Stream.EnterSubBlock(ID))
6989     return std::move(Err);
6990   SmallVector<uint64_t, 64> Record;
6991 
6992   while (true) {
6993     BitstreamEntry Entry;
6994     if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
6995       return std::move(E);
6996 
6997     switch (Entry.Kind) {
6998     case BitstreamEntry::SubBlock: // Handled for us already.
6999     case BitstreamEntry::Error:
7000       return error("Malformed block");
7001     case BitstreamEntry::EndBlock:
7002       // If no flags record found, conservatively return true to mimic
7003       // behavior before this flag was added.
7004       return true;
7005     case BitstreamEntry::Record:
7006       // The interesting case.
7007       break;
7008     }
7009 
7010     // Look for the FS_FLAGS record.
7011     Record.clear();
7012     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
7013     if (!MaybeBitCode)
7014       return MaybeBitCode.takeError();
7015     switch (MaybeBitCode.get()) {
7016     default: // Default behavior: ignore.
7017       break;
7018     case bitc::FS_FLAGS: { // [flags]
7019       uint64_t Flags = Record[0];
7020       // Scan flags.
7021       assert(Flags <= 0x7f && "Unexpected bits in flag");
7022 
7023       return Flags & 0x8;
7024     }
7025     }
7026   }
7027   llvm_unreachable("Exit infinite loop");
7028 }
7029 
7030 // Check if the given bitcode buffer contains a global value summary block.
7031 Expected<BitcodeLTOInfo> BitcodeModule::getLTOInfo() {
7032   BitstreamCursor Stream(Buffer);
7033   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
7034     return std::move(JumpFailed);
7035 
7036   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
7037     return std::move(Err);
7038 
7039   while (true) {
7040     llvm::BitstreamEntry Entry;
7041     if (Error E = Stream.advance().moveInto(Entry))
7042       return std::move(E);
7043 
7044     switch (Entry.Kind) {
7045     case BitstreamEntry::Error:
7046       return error("Malformed block");
7047     case BitstreamEntry::EndBlock:
7048       return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/false,
7049                             /*EnableSplitLTOUnit=*/false};
7050 
7051     case BitstreamEntry::SubBlock:
7052       if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) {
7053         Expected<bool> EnableSplitLTOUnit =
7054             getEnableSplitLTOUnitFlag(Stream, Entry.ID);
7055         if (!EnableSplitLTOUnit)
7056           return EnableSplitLTOUnit.takeError();
7057         return BitcodeLTOInfo{/*IsThinLTO=*/true, /*HasSummary=*/true,
7058                               *EnableSplitLTOUnit};
7059       }
7060 
7061       if (Entry.ID == bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID) {
7062         Expected<bool> EnableSplitLTOUnit =
7063             getEnableSplitLTOUnitFlag(Stream, Entry.ID);
7064         if (!EnableSplitLTOUnit)
7065           return EnableSplitLTOUnit.takeError();
7066         return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/true,
7067                               *EnableSplitLTOUnit};
7068       }
7069 
7070       // Ignore other sub-blocks.
7071       if (Error Err = Stream.SkipBlock())
7072         return std::move(Err);
7073       continue;
7074 
7075     case BitstreamEntry::Record:
7076       if (Expected<unsigned> StreamFailed = Stream.skipRecord(Entry.ID))
7077         continue;
7078       else
7079         return StreamFailed.takeError();
7080     }
7081   }
7082 }
7083 
7084 static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) {
7085   Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer);
7086   if (!MsOrErr)
7087     return MsOrErr.takeError();
7088 
7089   if (MsOrErr->size() != 1)
7090     return error("Expected a single module");
7091 
7092   return (*MsOrErr)[0];
7093 }
7094 
7095 Expected<std::unique_ptr<Module>>
7096 llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context,
7097                            bool ShouldLazyLoadMetadata, bool IsImporting) {
7098   Expected<BitcodeModule> BM = getSingleModule(Buffer);
7099   if (!BM)
7100     return BM.takeError();
7101 
7102   return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting);
7103 }
7104 
7105 Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule(
7106     std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
7107     bool ShouldLazyLoadMetadata, bool IsImporting) {
7108   auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata,
7109                                      IsImporting);
7110   if (MOrErr)
7111     (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
7112   return MOrErr;
7113 }
7114 
7115 Expected<std::unique_ptr<Module>>
7116 BitcodeModule::parseModule(LLVMContext &Context,
7117                            DataLayoutCallbackTy DataLayoutCallback) {
7118   return getModuleImpl(Context, true, false, false, DataLayoutCallback);
7119   // TODO: Restore the use-lists to the in-memory state when the bitcode was
7120   // written.  We must defer until the Module has been fully materialized.
7121 }
7122 
7123 Expected<std::unique_ptr<Module>>
7124 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
7125                        DataLayoutCallbackTy DataLayoutCallback) {
7126   Expected<BitcodeModule> BM = getSingleModule(Buffer);
7127   if (!BM)
7128     return BM.takeError();
7129 
7130   return BM->parseModule(Context, DataLayoutCallback);
7131 }
7132 
7133 Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) {
7134   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
7135   if (!StreamOrErr)
7136     return StreamOrErr.takeError();
7137 
7138   return readTriple(*StreamOrErr);
7139 }
7140 
7141 Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) {
7142   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
7143   if (!StreamOrErr)
7144     return StreamOrErr.takeError();
7145 
7146   return hasObjCCategory(*StreamOrErr);
7147 }
7148 
7149 Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) {
7150   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
7151   if (!StreamOrErr)
7152     return StreamOrErr.takeError();
7153 
7154   return readIdentificationCode(*StreamOrErr);
7155 }
7156 
7157 Error llvm::readModuleSummaryIndex(MemoryBufferRef Buffer,
7158                                    ModuleSummaryIndex &CombinedIndex,
7159                                    uint64_t ModuleId) {
7160   Expected<BitcodeModule> BM = getSingleModule(Buffer);
7161   if (!BM)
7162     return BM.takeError();
7163 
7164   return BM->readSummary(CombinedIndex, BM->getModuleIdentifier(), ModuleId);
7165 }
7166 
7167 Expected<std::unique_ptr<ModuleSummaryIndex>>
7168 llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) {
7169   Expected<BitcodeModule> BM = getSingleModule(Buffer);
7170   if (!BM)
7171     return BM.takeError();
7172 
7173   return BM->getSummary();
7174 }
7175 
7176 Expected<BitcodeLTOInfo> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer) {
7177   Expected<BitcodeModule> BM = getSingleModule(Buffer);
7178   if (!BM)
7179     return BM.takeError();
7180 
7181   return BM->getLTOInfo();
7182 }
7183 
7184 Expected<std::unique_ptr<ModuleSummaryIndex>>
7185 llvm::getModuleSummaryIndexForFile(StringRef Path,
7186                                    bool IgnoreEmptyThinLTOIndexFile) {
7187   ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
7188       MemoryBuffer::getFileOrSTDIN(Path);
7189   if (!FileOrErr)
7190     return errorCodeToError(FileOrErr.getError());
7191   if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize())
7192     return nullptr;
7193   return getModuleSummaryIndex(**FileOrErr);
7194 }
7195