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