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