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