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