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