LCOV - code coverage report
Current view: top level - lib/Bitcode/Reader - BitcodeReader.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 2098 2600 80.7 %
Date: 2018-05-20 00:06:23 Functions: 97 105 92.4 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.13