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