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