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