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