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