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