10b57cec5SDimitry Andric //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric 
90b57cec5SDimitry Andric #include "llvm/Bitcode/BitcodeReader.h"
100b57cec5SDimitry Andric #include "MetadataLoader.h"
110b57cec5SDimitry Andric #include "ValueList.h"
120b57cec5SDimitry Andric #include "llvm/ADT/APFloat.h"
130b57cec5SDimitry Andric #include "llvm/ADT/APInt.h"
140b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
150b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
160b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
170b57cec5SDimitry Andric #include "llvm/ADT/SmallString.h"
180b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
190b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
200b57cec5SDimitry Andric #include "llvm/ADT/Twine.h"
21e8d8bef9SDimitry Andric #include "llvm/Bitcode/BitcodeCommon.h"
220b57cec5SDimitry Andric #include "llvm/Bitcode/LLVMBitCodes.h"
23e8d8bef9SDimitry Andric #include "llvm/Bitstream/BitstreamReader.h"
240b57cec5SDimitry Andric #include "llvm/Config/llvm-config.h"
250b57cec5SDimitry Andric #include "llvm/IR/Argument.h"
26fe013be4SDimitry Andric #include "llvm/IR/AttributeMask.h"
270b57cec5SDimitry Andric #include "llvm/IR/Attributes.h"
280b57cec5SDimitry Andric #include "llvm/IR/AutoUpgrade.h"
290b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
300b57cec5SDimitry Andric #include "llvm/IR/CallingConv.h"
310b57cec5SDimitry Andric #include "llvm/IR/Comdat.h"
320b57cec5SDimitry Andric #include "llvm/IR/Constant.h"
330b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
340b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
350b57cec5SDimitry Andric #include "llvm/IR/DebugInfo.h"
360b57cec5SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
370b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h"
380b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
390b57cec5SDimitry Andric #include "llvm/IR/Function.h"
400b57cec5SDimitry Andric #include "llvm/IR/GVMaterializer.h"
4181ad6265SDimitry Andric #include "llvm/IR/GetElementPtrTypeIterator.h"
420b57cec5SDimitry Andric #include "llvm/IR/GlobalAlias.h"
430b57cec5SDimitry Andric #include "llvm/IR/GlobalIFunc.h"
440b57cec5SDimitry Andric #include "llvm/IR/GlobalObject.h"
450b57cec5SDimitry Andric #include "llvm/IR/GlobalValue.h"
460b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h"
470b57cec5SDimitry Andric #include "llvm/IR/InlineAsm.h"
480b57cec5SDimitry Andric #include "llvm/IR/InstIterator.h"
490b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h"
500b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
510b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
520b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
5381ad6265SDimitry Andric #include "llvm/IR/IntrinsicsAArch64.h"
5481ad6265SDimitry Andric #include "llvm/IR/IntrinsicsARM.h"
550b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
560b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
570b57cec5SDimitry Andric #include "llvm/IR/Module.h"
580b57cec5SDimitry Andric #include "llvm/IR/ModuleSummaryIndex.h"
590b57cec5SDimitry Andric #include "llvm/IR/Operator.h"
600b57cec5SDimitry Andric #include "llvm/IR/Type.h"
610b57cec5SDimitry Andric #include "llvm/IR/Value.h"
620b57cec5SDimitry Andric #include "llvm/IR/Verifier.h"
630b57cec5SDimitry Andric #include "llvm/Support/AtomicOrdering.h"
640b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
650b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
660b57cec5SDimitry Andric #include "llvm/Support/Compiler.h"
670b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
680b57cec5SDimitry Andric #include "llvm/Support/Error.h"
690b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
700b57cec5SDimitry Andric #include "llvm/Support/ErrorOr.h"
710b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
720b57cec5SDimitry Andric #include "llvm/Support/MemoryBuffer.h"
73bdd1243dSDimitry Andric #include "llvm/Support/ModRef.h"
740b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
75fe013be4SDimitry Andric #include "llvm/TargetParser/Triple.h"
760b57cec5SDimitry Andric #include <algorithm>
770b57cec5SDimitry Andric #include <cassert>
780b57cec5SDimitry Andric #include <cstddef>
790b57cec5SDimitry Andric #include <cstdint>
800b57cec5SDimitry Andric #include <deque>
810b57cec5SDimitry Andric #include <map>
820b57cec5SDimitry Andric #include <memory>
83bdd1243dSDimitry Andric #include <optional>
840b57cec5SDimitry Andric #include <set>
850b57cec5SDimitry Andric #include <string>
860b57cec5SDimitry Andric #include <system_error>
870b57cec5SDimitry Andric #include <tuple>
880b57cec5SDimitry Andric #include <utility>
890b57cec5SDimitry Andric #include <vector>
900b57cec5SDimitry Andric 
910b57cec5SDimitry Andric using namespace llvm;
920b57cec5SDimitry Andric 
930b57cec5SDimitry Andric static cl::opt<bool> PrintSummaryGUIDs(
940b57cec5SDimitry Andric     "print-summary-global-ids", cl::init(false), cl::Hidden,
950b57cec5SDimitry Andric     cl::desc(
960b57cec5SDimitry Andric         "Print the global id for each value when reading the module summary"));
970b57cec5SDimitry Andric 
9881ad6265SDimitry Andric static cl::opt<bool> ExpandConstantExprs(
9981ad6265SDimitry Andric     "expand-constant-exprs", cl::Hidden,
10081ad6265SDimitry Andric     cl::desc(
10181ad6265SDimitry Andric         "Expand constant expressions to instructions for testing purposes"));
10281ad6265SDimitry Andric 
1030b57cec5SDimitry Andric namespace {
1040b57cec5SDimitry Andric 
1050b57cec5SDimitry Andric enum {
1060b57cec5SDimitry Andric   SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
1070b57cec5SDimitry Andric };
1080b57cec5SDimitry Andric 
1090b57cec5SDimitry Andric } // end anonymous namespace
1100b57cec5SDimitry Andric 
error(const Twine & Message)1110b57cec5SDimitry Andric static Error error(const Twine &Message) {
1120b57cec5SDimitry Andric   return make_error<StringError>(
1130b57cec5SDimitry Andric       Message, make_error_code(BitcodeError::CorruptedBitcode));
1140b57cec5SDimitry Andric }
1150b57cec5SDimitry Andric 
hasInvalidBitcodeHeader(BitstreamCursor & Stream)1160b57cec5SDimitry Andric static Error hasInvalidBitcodeHeader(BitstreamCursor &Stream) {
1170b57cec5SDimitry Andric   if (!Stream.canSkipToPos(4))
1180b57cec5SDimitry Andric     return createStringError(std::errc::illegal_byte_sequence,
1190b57cec5SDimitry Andric                              "file too small to contain bitcode header");
1200b57cec5SDimitry Andric   for (unsigned C : {'B', 'C'})
1210b57cec5SDimitry Andric     if (Expected<SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
1220b57cec5SDimitry Andric       if (Res.get() != C)
1230b57cec5SDimitry Andric         return createStringError(std::errc::illegal_byte_sequence,
1240b57cec5SDimitry Andric                                  "file doesn't start with bitcode header");
1250b57cec5SDimitry Andric     } else
1260b57cec5SDimitry Andric       return Res.takeError();
1270b57cec5SDimitry Andric   for (unsigned C : {0x0, 0xC, 0xE, 0xD})
1280b57cec5SDimitry Andric     if (Expected<SimpleBitstreamCursor::word_t> Res = Stream.Read(4)) {
1290b57cec5SDimitry Andric       if (Res.get() != C)
1300b57cec5SDimitry Andric         return createStringError(std::errc::illegal_byte_sequence,
1310b57cec5SDimitry Andric                                  "file doesn't start with bitcode header");
1320b57cec5SDimitry Andric     } else
1330b57cec5SDimitry Andric       return Res.takeError();
1340b57cec5SDimitry Andric   return Error::success();
1350b57cec5SDimitry Andric }
1360b57cec5SDimitry Andric 
initStream(MemoryBufferRef Buffer)1370b57cec5SDimitry Andric static Expected<BitstreamCursor> initStream(MemoryBufferRef Buffer) {
1380b57cec5SDimitry Andric   const unsigned char *BufPtr = (const unsigned char *)Buffer.getBufferStart();
1390b57cec5SDimitry Andric   const unsigned char *BufEnd = BufPtr + Buffer.getBufferSize();
1400b57cec5SDimitry Andric 
1410b57cec5SDimitry Andric   if (Buffer.getBufferSize() & 3)
1420b57cec5SDimitry Andric     return error("Invalid bitcode signature");
1430b57cec5SDimitry Andric 
1440b57cec5SDimitry Andric   // If we have a wrapper header, parse it and ignore the non-bc file contents.
1450b57cec5SDimitry Andric   // The magic number is 0x0B17C0DE stored in little endian.
1460b57cec5SDimitry Andric   if (isBitcodeWrapper(BufPtr, BufEnd))
1470b57cec5SDimitry Andric     if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
1480b57cec5SDimitry Andric       return error("Invalid bitcode wrapper header");
1490b57cec5SDimitry Andric 
1500b57cec5SDimitry Andric   BitstreamCursor Stream(ArrayRef<uint8_t>(BufPtr, BufEnd));
1510b57cec5SDimitry Andric   if (Error Err = hasInvalidBitcodeHeader(Stream))
1520b57cec5SDimitry Andric     return std::move(Err);
1530b57cec5SDimitry Andric 
1540b57cec5SDimitry Andric   return std::move(Stream);
1550b57cec5SDimitry Andric }
1560b57cec5SDimitry Andric 
1570b57cec5SDimitry Andric /// Convert a string from a record into an std::string, return true on failure.
1580b57cec5SDimitry Andric template <typename StrTy>
convertToString(ArrayRef<uint64_t> Record,unsigned Idx,StrTy & Result)1590b57cec5SDimitry Andric static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
1600b57cec5SDimitry Andric                             StrTy &Result) {
1610b57cec5SDimitry Andric   if (Idx > Record.size())
1620b57cec5SDimitry Andric     return true;
1630b57cec5SDimitry Andric 
1645ffd83dbSDimitry Andric   Result.append(Record.begin() + Idx, Record.end());
1650b57cec5SDimitry Andric   return false;
1660b57cec5SDimitry Andric }
1670b57cec5SDimitry Andric 
1680b57cec5SDimitry Andric // Strip all the TBAA attachment for the module.
stripTBAA(Module * M)1690b57cec5SDimitry Andric static void stripTBAA(Module *M) {
1700b57cec5SDimitry Andric   for (auto &F : *M) {
1710b57cec5SDimitry Andric     if (F.isMaterializable())
1720b57cec5SDimitry Andric       continue;
1730b57cec5SDimitry Andric     for (auto &I : instructions(F))
1740b57cec5SDimitry Andric       I.setMetadata(LLVMContext::MD_tbaa, nullptr);
1750b57cec5SDimitry Andric   }
1760b57cec5SDimitry Andric }
1770b57cec5SDimitry Andric 
1780b57cec5SDimitry Andric /// Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the
1790b57cec5SDimitry Andric /// "epoch" encoded in the bitcode, and return the producer name if any.
readIdentificationBlock(BitstreamCursor & Stream)1800b57cec5SDimitry Andric static Expected<std::string> readIdentificationBlock(BitstreamCursor &Stream) {
1810b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
1820b57cec5SDimitry Andric     return std::move(Err);
1830b57cec5SDimitry Andric 
1840b57cec5SDimitry Andric   // Read all the records.
1850b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
1860b57cec5SDimitry Andric 
1870b57cec5SDimitry Andric   std::string ProducerIdentification;
1880b57cec5SDimitry Andric 
1890b57cec5SDimitry Andric   while (true) {
1900b57cec5SDimitry Andric     BitstreamEntry Entry;
191349cc55cSDimitry Andric     if (Error E = Stream.advance().moveInto(Entry))
192349cc55cSDimitry Andric       return std::move(E);
1930b57cec5SDimitry Andric 
1940b57cec5SDimitry Andric     switch (Entry.Kind) {
1950b57cec5SDimitry Andric     default:
1960b57cec5SDimitry Andric     case BitstreamEntry::Error:
1970b57cec5SDimitry Andric       return error("Malformed block");
1980b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
1990b57cec5SDimitry Andric       return ProducerIdentification;
2000b57cec5SDimitry Andric     case BitstreamEntry::Record:
2010b57cec5SDimitry Andric       // The interesting case.
2020b57cec5SDimitry Andric       break;
2030b57cec5SDimitry Andric     }
2040b57cec5SDimitry Andric 
2050b57cec5SDimitry Andric     // Read a record.
2060b57cec5SDimitry Andric     Record.clear();
2070b57cec5SDimitry Andric     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
2080b57cec5SDimitry Andric     if (!MaybeBitCode)
2090b57cec5SDimitry Andric       return MaybeBitCode.takeError();
2100b57cec5SDimitry Andric     switch (MaybeBitCode.get()) {
2110b57cec5SDimitry Andric     default: // Default behavior: reject
2120b57cec5SDimitry Andric       return error("Invalid value");
2130b57cec5SDimitry Andric     case bitc::IDENTIFICATION_CODE_STRING: // IDENTIFICATION: [strchr x N]
2140b57cec5SDimitry Andric       convertToString(Record, 0, ProducerIdentification);
2150b57cec5SDimitry Andric       break;
2160b57cec5SDimitry Andric     case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
2170b57cec5SDimitry Andric       unsigned epoch = (unsigned)Record[0];
2180b57cec5SDimitry Andric       if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
2190b57cec5SDimitry Andric         return error(
2200b57cec5SDimitry Andric           Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
2210b57cec5SDimitry Andric           "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
2220b57cec5SDimitry Andric       }
2230b57cec5SDimitry Andric     }
2240b57cec5SDimitry Andric     }
2250b57cec5SDimitry Andric   }
2260b57cec5SDimitry Andric }
2270b57cec5SDimitry Andric 
readIdentificationCode(BitstreamCursor & Stream)2280b57cec5SDimitry Andric static Expected<std::string> readIdentificationCode(BitstreamCursor &Stream) {
2290b57cec5SDimitry Andric   // We expect a number of well-defined blocks, though we don't necessarily
2300b57cec5SDimitry Andric   // need to understand them all.
2310b57cec5SDimitry Andric   while (true) {
2320b57cec5SDimitry Andric     if (Stream.AtEndOfStream())
2330b57cec5SDimitry Andric       return "";
2340b57cec5SDimitry Andric 
2350b57cec5SDimitry Andric     BitstreamEntry Entry;
236349cc55cSDimitry Andric     if (Error E = Stream.advance().moveInto(Entry))
237349cc55cSDimitry Andric       return std::move(E);
2380b57cec5SDimitry Andric 
2390b57cec5SDimitry Andric     switch (Entry.Kind) {
2400b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
2410b57cec5SDimitry Andric     case BitstreamEntry::Error:
2420b57cec5SDimitry Andric       return error("Malformed block");
2430b57cec5SDimitry Andric 
2440b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
2450b57cec5SDimitry Andric       if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID)
2460b57cec5SDimitry Andric         return readIdentificationBlock(Stream);
2470b57cec5SDimitry Andric 
2480b57cec5SDimitry Andric       // Ignore other sub-blocks.
2490b57cec5SDimitry Andric       if (Error Err = Stream.SkipBlock())
2500b57cec5SDimitry Andric         return std::move(Err);
2510b57cec5SDimitry Andric       continue;
2520b57cec5SDimitry Andric     case BitstreamEntry::Record:
253349cc55cSDimitry Andric       if (Error E = Stream.skipRecord(Entry.ID).takeError())
254349cc55cSDimitry Andric         return std::move(E);
2550b57cec5SDimitry Andric       continue;
2560b57cec5SDimitry Andric     }
2570b57cec5SDimitry Andric   }
2580b57cec5SDimitry Andric }
2590b57cec5SDimitry Andric 
hasObjCCategoryInModule(BitstreamCursor & Stream)2600b57cec5SDimitry Andric static Expected<bool> hasObjCCategoryInModule(BitstreamCursor &Stream) {
2610b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2620b57cec5SDimitry Andric     return std::move(Err);
2630b57cec5SDimitry Andric 
2640b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
2650b57cec5SDimitry Andric   // Read all the records for this module.
2660b57cec5SDimitry Andric 
2670b57cec5SDimitry Andric   while (true) {
2680b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2690b57cec5SDimitry Andric     if (!MaybeEntry)
2700b57cec5SDimitry Andric       return MaybeEntry.takeError();
2710b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
2720b57cec5SDimitry Andric 
2730b57cec5SDimitry Andric     switch (Entry.Kind) {
2740b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
2750b57cec5SDimitry Andric     case BitstreamEntry::Error:
2760b57cec5SDimitry Andric       return error("Malformed block");
2770b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
2780b57cec5SDimitry Andric       return false;
2790b57cec5SDimitry Andric     case BitstreamEntry::Record:
2800b57cec5SDimitry Andric       // The interesting case.
2810b57cec5SDimitry Andric       break;
2820b57cec5SDimitry Andric     }
2830b57cec5SDimitry Andric 
2840b57cec5SDimitry Andric     // Read a record.
2850b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2860b57cec5SDimitry Andric     if (!MaybeRecord)
2870b57cec5SDimitry Andric       return MaybeRecord.takeError();
2880b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
2890b57cec5SDimitry Andric     default:
2900b57cec5SDimitry Andric       break; // Default behavior, ignore unknown content.
2910b57cec5SDimitry Andric     case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
2920b57cec5SDimitry Andric       std::string S;
2930b57cec5SDimitry Andric       if (convertToString(Record, 0, S))
29481ad6265SDimitry Andric         return error("Invalid section name record");
2950b57cec5SDimitry Andric       // Check for the i386 and other (x86_64, ARM) conventions
2960b57cec5SDimitry Andric       if (S.find("__DATA,__objc_catlist") != std::string::npos ||
2970b57cec5SDimitry Andric           S.find("__OBJC,__category") != std::string::npos)
2980b57cec5SDimitry Andric         return true;
2990b57cec5SDimitry Andric       break;
3000b57cec5SDimitry Andric     }
3010b57cec5SDimitry Andric     }
3020b57cec5SDimitry Andric     Record.clear();
3030b57cec5SDimitry Andric   }
3040b57cec5SDimitry Andric   llvm_unreachable("Exit infinite loop");
3050b57cec5SDimitry Andric }
3060b57cec5SDimitry Andric 
hasObjCCategory(BitstreamCursor & Stream)3070b57cec5SDimitry Andric static Expected<bool> hasObjCCategory(BitstreamCursor &Stream) {
3080b57cec5SDimitry Andric   // We expect a number of well-defined blocks, though we don't necessarily
3090b57cec5SDimitry Andric   // need to understand them all.
3100b57cec5SDimitry Andric   while (true) {
3110b57cec5SDimitry Andric     BitstreamEntry Entry;
312349cc55cSDimitry Andric     if (Error E = Stream.advance().moveInto(Entry))
313349cc55cSDimitry Andric       return std::move(E);
3140b57cec5SDimitry Andric 
3150b57cec5SDimitry Andric     switch (Entry.Kind) {
3160b57cec5SDimitry Andric     case BitstreamEntry::Error:
3170b57cec5SDimitry Andric       return error("Malformed block");
3180b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
3190b57cec5SDimitry Andric       return false;
3200b57cec5SDimitry Andric 
3210b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
3220b57cec5SDimitry Andric       if (Entry.ID == bitc::MODULE_BLOCK_ID)
3230b57cec5SDimitry Andric         return hasObjCCategoryInModule(Stream);
3240b57cec5SDimitry Andric 
3250b57cec5SDimitry Andric       // Ignore other sub-blocks.
3260b57cec5SDimitry Andric       if (Error Err = Stream.SkipBlock())
3270b57cec5SDimitry Andric         return std::move(Err);
3280b57cec5SDimitry Andric       continue;
3290b57cec5SDimitry Andric 
3300b57cec5SDimitry Andric     case BitstreamEntry::Record:
331349cc55cSDimitry Andric       if (Error E = Stream.skipRecord(Entry.ID).takeError())
332349cc55cSDimitry Andric         return std::move(E);
3330b57cec5SDimitry Andric       continue;
3340b57cec5SDimitry Andric     }
3350b57cec5SDimitry Andric   }
3360b57cec5SDimitry Andric }
3370b57cec5SDimitry Andric 
readModuleTriple(BitstreamCursor & Stream)3380b57cec5SDimitry Andric static Expected<std::string> readModuleTriple(BitstreamCursor &Stream) {
3390b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3400b57cec5SDimitry Andric     return std::move(Err);
3410b57cec5SDimitry Andric 
3420b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
3430b57cec5SDimitry Andric 
3440b57cec5SDimitry Andric   std::string Triple;
3450b57cec5SDimitry Andric 
3460b57cec5SDimitry Andric   // Read all the records for this module.
3470b57cec5SDimitry Andric   while (true) {
3480b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
3490b57cec5SDimitry Andric     if (!MaybeEntry)
3500b57cec5SDimitry Andric       return MaybeEntry.takeError();
3510b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
3520b57cec5SDimitry Andric 
3530b57cec5SDimitry Andric     switch (Entry.Kind) {
3540b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
3550b57cec5SDimitry Andric     case BitstreamEntry::Error:
3560b57cec5SDimitry Andric       return error("Malformed block");
3570b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
3580b57cec5SDimitry Andric       return Triple;
3590b57cec5SDimitry Andric     case BitstreamEntry::Record:
3600b57cec5SDimitry Andric       // The interesting case.
3610b57cec5SDimitry Andric       break;
3620b57cec5SDimitry Andric     }
3630b57cec5SDimitry Andric 
3640b57cec5SDimitry Andric     // Read a record.
3650b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
3660b57cec5SDimitry Andric     if (!MaybeRecord)
3670b57cec5SDimitry Andric       return MaybeRecord.takeError();
3680b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
3690b57cec5SDimitry Andric     default: break;  // Default behavior, ignore unknown content.
3700b57cec5SDimitry Andric     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
3710b57cec5SDimitry Andric       std::string S;
3720b57cec5SDimitry Andric       if (convertToString(Record, 0, S))
37381ad6265SDimitry Andric         return error("Invalid triple record");
3740b57cec5SDimitry Andric       Triple = S;
3750b57cec5SDimitry Andric       break;
3760b57cec5SDimitry Andric     }
3770b57cec5SDimitry Andric     }
3780b57cec5SDimitry Andric     Record.clear();
3790b57cec5SDimitry Andric   }
3800b57cec5SDimitry Andric   llvm_unreachable("Exit infinite loop");
3810b57cec5SDimitry Andric }
3820b57cec5SDimitry Andric 
readTriple(BitstreamCursor & Stream)3830b57cec5SDimitry Andric static Expected<std::string> readTriple(BitstreamCursor &Stream) {
3840b57cec5SDimitry Andric   // We expect a number of well-defined blocks, though we don't necessarily
3850b57cec5SDimitry Andric   // need to understand them all.
3860b57cec5SDimitry Andric   while (true) {
3870b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advance();
3880b57cec5SDimitry Andric     if (!MaybeEntry)
3890b57cec5SDimitry Andric       return MaybeEntry.takeError();
3900b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
3910b57cec5SDimitry Andric 
3920b57cec5SDimitry Andric     switch (Entry.Kind) {
3930b57cec5SDimitry Andric     case BitstreamEntry::Error:
3940b57cec5SDimitry Andric       return error("Malformed block");
3950b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
3960b57cec5SDimitry Andric       return "";
3970b57cec5SDimitry Andric 
3980b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
3990b57cec5SDimitry Andric       if (Entry.ID == bitc::MODULE_BLOCK_ID)
4000b57cec5SDimitry Andric         return readModuleTriple(Stream);
4010b57cec5SDimitry Andric 
4020b57cec5SDimitry Andric       // Ignore other sub-blocks.
4030b57cec5SDimitry Andric       if (Error Err = Stream.SkipBlock())
4040b57cec5SDimitry Andric         return std::move(Err);
4050b57cec5SDimitry Andric       continue;
4060b57cec5SDimitry Andric 
4070b57cec5SDimitry Andric     case BitstreamEntry::Record:
4080b57cec5SDimitry Andric       if (llvm::Expected<unsigned> Skipped = Stream.skipRecord(Entry.ID))
4090b57cec5SDimitry Andric         continue;
4100b57cec5SDimitry Andric       else
4110b57cec5SDimitry Andric         return Skipped.takeError();
4120b57cec5SDimitry Andric     }
4130b57cec5SDimitry Andric   }
4140b57cec5SDimitry Andric }
4150b57cec5SDimitry Andric 
4160b57cec5SDimitry Andric namespace {
4170b57cec5SDimitry Andric 
4180b57cec5SDimitry Andric class BitcodeReaderBase {
4190b57cec5SDimitry Andric protected:
BitcodeReaderBase(BitstreamCursor Stream,StringRef Strtab)4200b57cec5SDimitry Andric   BitcodeReaderBase(BitstreamCursor Stream, StringRef Strtab)
4210b57cec5SDimitry Andric       : Stream(std::move(Stream)), Strtab(Strtab) {
4220b57cec5SDimitry Andric     this->Stream.setBlockInfo(&BlockInfo);
4230b57cec5SDimitry Andric   }
4240b57cec5SDimitry Andric 
4250b57cec5SDimitry Andric   BitstreamBlockInfo BlockInfo;
4260b57cec5SDimitry Andric   BitstreamCursor Stream;
4270b57cec5SDimitry Andric   StringRef Strtab;
4280b57cec5SDimitry Andric 
4290b57cec5SDimitry Andric   /// In version 2 of the bitcode we store names of global values and comdats in
4300b57cec5SDimitry Andric   /// a string table rather than in the VST.
4310b57cec5SDimitry Andric   bool UseStrtab = false;
4320b57cec5SDimitry Andric 
4330b57cec5SDimitry Andric   Expected<unsigned> parseVersionRecord(ArrayRef<uint64_t> Record);
4340b57cec5SDimitry Andric 
4350b57cec5SDimitry Andric   /// If this module uses a string table, pop the reference to the string table
4360b57cec5SDimitry Andric   /// and return the referenced string and the rest of the record. Otherwise
4370b57cec5SDimitry Andric   /// just return the record itself.
4380b57cec5SDimitry Andric   std::pair<StringRef, ArrayRef<uint64_t>>
4390b57cec5SDimitry Andric   readNameFromStrtab(ArrayRef<uint64_t> Record);
4400b57cec5SDimitry Andric 
44181ad6265SDimitry Andric   Error readBlockInfo();
4420b57cec5SDimitry Andric 
4430b57cec5SDimitry Andric   // Contains an arbitrary and optional string identifying the bitcode producer
4440b57cec5SDimitry Andric   std::string ProducerIdentification;
4450b57cec5SDimitry Andric 
4460b57cec5SDimitry Andric   Error error(const Twine &Message);
4470b57cec5SDimitry Andric };
4480b57cec5SDimitry Andric 
4490b57cec5SDimitry Andric } // end anonymous namespace
4500b57cec5SDimitry Andric 
error(const Twine & Message)4510b57cec5SDimitry Andric Error BitcodeReaderBase::error(const Twine &Message) {
4520b57cec5SDimitry Andric   std::string FullMsg = Message.str();
4530b57cec5SDimitry Andric   if (!ProducerIdentification.empty())
4540b57cec5SDimitry Andric     FullMsg += " (Producer: '" + ProducerIdentification + "' Reader: 'LLVM " +
4550b57cec5SDimitry Andric                LLVM_VERSION_STRING "')";
4560b57cec5SDimitry Andric   return ::error(FullMsg);
4570b57cec5SDimitry Andric }
4580b57cec5SDimitry Andric 
4590b57cec5SDimitry Andric Expected<unsigned>
parseVersionRecord(ArrayRef<uint64_t> Record)4600b57cec5SDimitry Andric BitcodeReaderBase::parseVersionRecord(ArrayRef<uint64_t> Record) {
4610b57cec5SDimitry Andric   if (Record.empty())
46281ad6265SDimitry Andric     return error("Invalid version record");
4630b57cec5SDimitry Andric   unsigned ModuleVersion = Record[0];
4640b57cec5SDimitry Andric   if (ModuleVersion > 2)
4650b57cec5SDimitry Andric     return error("Invalid value");
4660b57cec5SDimitry Andric   UseStrtab = ModuleVersion >= 2;
4670b57cec5SDimitry Andric   return ModuleVersion;
4680b57cec5SDimitry Andric }
4690b57cec5SDimitry Andric 
4700b57cec5SDimitry Andric std::pair<StringRef, ArrayRef<uint64_t>>
readNameFromStrtab(ArrayRef<uint64_t> Record)4710b57cec5SDimitry Andric BitcodeReaderBase::readNameFromStrtab(ArrayRef<uint64_t> Record) {
4720b57cec5SDimitry Andric   if (!UseStrtab)
4730b57cec5SDimitry Andric     return {"", Record};
4740b57cec5SDimitry Andric   // Invalid reference. Let the caller complain about the record being empty.
4750b57cec5SDimitry Andric   if (Record[0] + Record[1] > Strtab.size())
4760b57cec5SDimitry Andric     return {"", {}};
4770b57cec5SDimitry Andric   return {StringRef(Strtab.data() + Record[0], Record[1]), Record.slice(2)};
4780b57cec5SDimitry Andric }
4790b57cec5SDimitry Andric 
4800b57cec5SDimitry Andric namespace {
4810b57cec5SDimitry Andric 
48281ad6265SDimitry Andric /// This represents a constant expression or constant aggregate using a custom
48381ad6265SDimitry Andric /// structure internal to the bitcode reader. Later, this structure will be
48481ad6265SDimitry Andric /// expanded by materializeValue() either into a constant expression/aggregate,
48581ad6265SDimitry Andric /// or into an instruction sequence at the point of use. This allows us to
48681ad6265SDimitry Andric /// upgrade bitcode using constant expressions even if this kind of constant
48781ad6265SDimitry Andric /// expression is no longer supported.
48881ad6265SDimitry Andric class BitcodeConstant final : public Value,
48981ad6265SDimitry Andric                               TrailingObjects<BitcodeConstant, unsigned> {
49081ad6265SDimitry Andric   friend TrailingObjects;
49181ad6265SDimitry Andric 
49281ad6265SDimitry Andric   // Value subclass ID: Pick largest possible value to avoid any clashes.
49381ad6265SDimitry Andric   static constexpr uint8_t SubclassID = 255;
49481ad6265SDimitry Andric 
49581ad6265SDimitry Andric public:
49681ad6265SDimitry Andric   // Opcodes used for non-expressions. This includes constant aggregates
49781ad6265SDimitry Andric   // (struct, array, vector) that might need expansion, as well as non-leaf
49881ad6265SDimitry Andric   // constants that don't need expansion (no_cfi, dso_local, blockaddress),
49981ad6265SDimitry Andric   // but still go through BitcodeConstant to avoid different uselist orders
50081ad6265SDimitry Andric   // between the two cases.
50181ad6265SDimitry Andric   static constexpr uint8_t ConstantStructOpcode = 255;
50281ad6265SDimitry Andric   static constexpr uint8_t ConstantArrayOpcode = 254;
50381ad6265SDimitry Andric   static constexpr uint8_t ConstantVectorOpcode = 253;
50481ad6265SDimitry Andric   static constexpr uint8_t NoCFIOpcode = 252;
50581ad6265SDimitry Andric   static constexpr uint8_t DSOLocalEquivalentOpcode = 251;
50681ad6265SDimitry Andric   static constexpr uint8_t BlockAddressOpcode = 250;
50781ad6265SDimitry Andric   static constexpr uint8_t FirstSpecialOpcode = BlockAddressOpcode;
50881ad6265SDimitry Andric 
50981ad6265SDimitry Andric   // Separate struct to make passing different number of parameters to
51081ad6265SDimitry Andric   // BitcodeConstant::create() more convenient.
51181ad6265SDimitry Andric   struct ExtraInfo {
51281ad6265SDimitry Andric     uint8_t Opcode;
51381ad6265SDimitry Andric     uint8_t Flags;
51481ad6265SDimitry Andric     unsigned Extra;
51581ad6265SDimitry Andric     Type *SrcElemTy;
51681ad6265SDimitry Andric 
ExtraInfo__anon933571fe0411::BitcodeConstant::ExtraInfo51781ad6265SDimitry Andric     ExtraInfo(uint8_t Opcode, uint8_t Flags = 0, unsigned Extra = 0,
51881ad6265SDimitry Andric               Type *SrcElemTy = nullptr)
51981ad6265SDimitry Andric         : Opcode(Opcode), Flags(Flags), Extra(Extra), SrcElemTy(SrcElemTy) {}
52081ad6265SDimitry Andric   };
52181ad6265SDimitry Andric 
52281ad6265SDimitry Andric   uint8_t Opcode;
52381ad6265SDimitry Andric   uint8_t Flags;
52481ad6265SDimitry Andric   unsigned NumOperands;
52581ad6265SDimitry Andric   unsigned Extra;  // GEP inrange index or blockaddress BB id.
52681ad6265SDimitry Andric   Type *SrcElemTy; // GEP source element type.
52781ad6265SDimitry Andric 
52881ad6265SDimitry Andric private:
BitcodeConstant(Type * Ty,const ExtraInfo & Info,ArrayRef<unsigned> OpIDs)52981ad6265SDimitry Andric   BitcodeConstant(Type *Ty, const ExtraInfo &Info, ArrayRef<unsigned> OpIDs)
53081ad6265SDimitry Andric       : Value(Ty, SubclassID), Opcode(Info.Opcode), Flags(Info.Flags),
53181ad6265SDimitry Andric         NumOperands(OpIDs.size()), Extra(Info.Extra),
53281ad6265SDimitry Andric         SrcElemTy(Info.SrcElemTy) {
53381ad6265SDimitry Andric     std::uninitialized_copy(OpIDs.begin(), OpIDs.end(),
53481ad6265SDimitry Andric                             getTrailingObjects<unsigned>());
53581ad6265SDimitry Andric   }
53681ad6265SDimitry Andric 
53781ad6265SDimitry Andric   BitcodeConstant &operator=(const BitcodeConstant &) = delete;
53881ad6265SDimitry Andric 
53981ad6265SDimitry Andric public:
create(BumpPtrAllocator & A,Type * Ty,const ExtraInfo & Info,ArrayRef<unsigned> OpIDs)54081ad6265SDimitry Andric   static BitcodeConstant *create(BumpPtrAllocator &A, Type *Ty,
54181ad6265SDimitry Andric                                  const ExtraInfo &Info,
54281ad6265SDimitry Andric                                  ArrayRef<unsigned> OpIDs) {
54381ad6265SDimitry Andric     void *Mem = A.Allocate(totalSizeToAlloc<unsigned>(OpIDs.size()),
54481ad6265SDimitry Andric                            alignof(BitcodeConstant));
54581ad6265SDimitry Andric     return new (Mem) BitcodeConstant(Ty, Info, OpIDs);
54681ad6265SDimitry Andric   }
54781ad6265SDimitry Andric 
classof(const Value * V)54881ad6265SDimitry Andric   static bool classof(const Value *V) { return V->getValueID() == SubclassID; }
54981ad6265SDimitry Andric 
getOperandIDs() const55081ad6265SDimitry Andric   ArrayRef<unsigned> getOperandIDs() const {
551bdd1243dSDimitry Andric     return ArrayRef(getTrailingObjects<unsigned>(), NumOperands);
55281ad6265SDimitry Andric   }
55381ad6265SDimitry Andric 
getInRangeIndex() const554bdd1243dSDimitry Andric   std::optional<unsigned> getInRangeIndex() const {
55581ad6265SDimitry Andric     assert(Opcode == Instruction::GetElementPtr);
55681ad6265SDimitry Andric     if (Extra == (unsigned)-1)
557bdd1243dSDimitry Andric       return std::nullopt;
55881ad6265SDimitry Andric     return Extra;
55981ad6265SDimitry Andric   }
56081ad6265SDimitry Andric 
getOpcodeName() const56181ad6265SDimitry Andric   const char *getOpcodeName() const {
56281ad6265SDimitry Andric     return Instruction::getOpcodeName(Opcode);
56381ad6265SDimitry Andric   }
56481ad6265SDimitry Andric };
56581ad6265SDimitry Andric 
5660b57cec5SDimitry Andric class BitcodeReader : public BitcodeReaderBase, public GVMaterializer {
5670b57cec5SDimitry Andric   LLVMContext &Context;
5680b57cec5SDimitry Andric   Module *TheModule = nullptr;
5690b57cec5SDimitry Andric   // Next offset to start scanning for lazy parsing of function bodies.
5700b57cec5SDimitry Andric   uint64_t NextUnreadBit = 0;
5710b57cec5SDimitry Andric   // Last function offset found in the VST.
5720b57cec5SDimitry Andric   uint64_t LastFunctionBlockBit = 0;
5730b57cec5SDimitry Andric   bool SeenValueSymbolTable = false;
5740b57cec5SDimitry Andric   uint64_t VSTOffset = 0;
5750b57cec5SDimitry Andric 
5760b57cec5SDimitry Andric   std::vector<std::string> SectionTable;
5770b57cec5SDimitry Andric   std::vector<std::string> GCTable;
5780b57cec5SDimitry Andric 
5790b57cec5SDimitry Andric   std::vector<Type *> TypeList;
58081ad6265SDimitry Andric   /// Track type IDs of contained types. Order is the same as the contained
58181ad6265SDimitry Andric   /// types of a Type*. This is used during upgrades of typed pointer IR in
58281ad6265SDimitry Andric   /// opaque pointer mode.
58381ad6265SDimitry Andric   DenseMap<unsigned, SmallVector<unsigned, 1>> ContainedTypeIDs;
58481ad6265SDimitry Andric   /// In some cases, we need to create a type ID for a type that was not
58581ad6265SDimitry Andric   /// explicitly encoded in the bitcode, or we don't know about at the current
58681ad6265SDimitry Andric   /// point. For example, a global may explicitly encode the value type ID, but
58781ad6265SDimitry Andric   /// not have a type ID for the pointer to value type, for which we create a
58881ad6265SDimitry Andric   /// virtual type ID instead. This map stores the new type ID that was created
58981ad6265SDimitry Andric   /// for the given pair of Type and contained type ID.
59081ad6265SDimitry Andric   DenseMap<std::pair<Type *, unsigned>, unsigned> VirtualTypeIDs;
59181ad6265SDimitry Andric   DenseMap<Function *, unsigned> FunctionTypeIDs;
59281ad6265SDimitry Andric   /// Allocator for BitcodeConstants. This should come before ValueList,
59381ad6265SDimitry Andric   /// because the ValueList might hold ValueHandles to these constants, so
59481ad6265SDimitry Andric   /// ValueList must be destroyed before Alloc.
59581ad6265SDimitry Andric   BumpPtrAllocator Alloc;
5960b57cec5SDimitry Andric   BitcodeReaderValueList ValueList;
597bdd1243dSDimitry Andric   std::optional<MetadataLoader> MDLoader;
5980b57cec5SDimitry Andric   std::vector<Comdat *> ComdatList;
5990eae32dcSDimitry Andric   DenseSet<GlobalObject *> ImplicitComdatObjects;
6000b57cec5SDimitry Andric   SmallVector<Instruction *, 64> InstructionList;
6010b57cec5SDimitry Andric 
6020b57cec5SDimitry Andric   std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInits;
603349cc55cSDimitry Andric   std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInits;
604349cc55cSDimitry Andric 
605349cc55cSDimitry Andric   struct FunctionOperandInfo {
606349cc55cSDimitry Andric     Function *F;
607349cc55cSDimitry Andric     unsigned PersonalityFn;
608349cc55cSDimitry Andric     unsigned Prefix;
609349cc55cSDimitry Andric     unsigned Prologue;
610349cc55cSDimitry Andric   };
611349cc55cSDimitry Andric   std::vector<FunctionOperandInfo> FunctionOperands;
6120b57cec5SDimitry Andric 
6130b57cec5SDimitry Andric   /// The set of attributes by index.  Index zero in the file is for null, and
6140b57cec5SDimitry Andric   /// is thus not represented here.  As such all indices are off by one.
6150b57cec5SDimitry Andric   std::vector<AttributeList> MAttributes;
6160b57cec5SDimitry Andric 
6170b57cec5SDimitry Andric   /// The set of attribute groups.
6180b57cec5SDimitry Andric   std::map<unsigned, AttributeList> MAttributeGroups;
6190b57cec5SDimitry Andric 
6200b57cec5SDimitry Andric   /// While parsing a function body, this is a list of the basic blocks for the
6210b57cec5SDimitry Andric   /// function.
6220b57cec5SDimitry Andric   std::vector<BasicBlock*> FunctionBBs;
6230b57cec5SDimitry Andric 
6240b57cec5SDimitry Andric   // When reading the module header, this list is populated with functions that
6250b57cec5SDimitry Andric   // have bodies later in the file.
6260b57cec5SDimitry Andric   std::vector<Function*> FunctionsWithBodies;
6270b57cec5SDimitry Andric 
6280b57cec5SDimitry Andric   // When intrinsic functions are encountered which require upgrading they are
6290b57cec5SDimitry Andric   // stored here with their replacement function.
6300b57cec5SDimitry Andric   using UpdatedIntrinsicMap = DenseMap<Function *, Function *>;
6310b57cec5SDimitry Andric   UpdatedIntrinsicMap UpgradedIntrinsics;
6320b57cec5SDimitry Andric 
6330b57cec5SDimitry Andric   // Several operations happen after the module header has been read, but
6340b57cec5SDimitry Andric   // before function bodies are processed. This keeps track of whether
6350b57cec5SDimitry Andric   // we've done this yet.
6360b57cec5SDimitry Andric   bool SeenFirstFunctionBody = false;
6370b57cec5SDimitry Andric 
6380b57cec5SDimitry Andric   /// When function bodies are initially scanned, this map contains info about
6390b57cec5SDimitry Andric   /// where to find deferred function body in the stream.
6400b57cec5SDimitry Andric   DenseMap<Function*, uint64_t> DeferredFunctionInfo;
6410b57cec5SDimitry Andric 
6420b57cec5SDimitry Andric   /// When Metadata block is initially scanned when parsing the module, we may
6430b57cec5SDimitry Andric   /// choose to defer parsing of the metadata. This vector contains info about
6440b57cec5SDimitry Andric   /// which Metadata blocks are deferred.
6450b57cec5SDimitry Andric   std::vector<uint64_t> DeferredMetadataInfo;
6460b57cec5SDimitry Andric 
6470b57cec5SDimitry Andric   /// These are basic blocks forward-referenced by block addresses.  They are
6480b57cec5SDimitry Andric   /// inserted lazily into functions when they're loaded.  The basic block ID is
6490b57cec5SDimitry Andric   /// its index into the vector.
6500b57cec5SDimitry Andric   DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
6510b57cec5SDimitry Andric   std::deque<Function *> BasicBlockFwdRefQueue;
6520b57cec5SDimitry Andric 
65381ad6265SDimitry Andric   /// These are Functions that contain BlockAddresses which refer a different
65481ad6265SDimitry Andric   /// Function. When parsing the different Function, queue Functions that refer
65581ad6265SDimitry Andric   /// to the different Function. Those Functions must be materialized in order
65681ad6265SDimitry Andric   /// to resolve their BlockAddress constants before the different Function
65781ad6265SDimitry Andric   /// gets moved into another Module.
65881ad6265SDimitry Andric   std::vector<Function *> BackwardRefFunctions;
65981ad6265SDimitry Andric 
6600b57cec5SDimitry Andric   /// Indicates that we are using a new encoding for instruction operands where
6610b57cec5SDimitry Andric   /// most operands in the current FUNCTION_BLOCK are encoded relative to the
6620b57cec5SDimitry Andric   /// instruction number, for a more compact encoding.  Some instruction
6630b57cec5SDimitry Andric   /// operands are not relative to the instruction ID: basic block numbers, and
6640b57cec5SDimitry Andric   /// types. Once the old style function blocks have been phased out, we would
6650b57cec5SDimitry Andric   /// not need this flag.
6660b57cec5SDimitry Andric   bool UseRelativeIDs = false;
6670b57cec5SDimitry Andric 
6680b57cec5SDimitry Andric   /// True if all functions will be materialized, negating the need to process
6690b57cec5SDimitry Andric   /// (e.g.) blockaddress forward references.
6700b57cec5SDimitry Andric   bool WillMaterializeAllForwardRefs = false;
6710b57cec5SDimitry Andric 
6720b57cec5SDimitry Andric   bool StripDebugInfo = false;
6730b57cec5SDimitry Andric   TBAAVerifier TBAAVerifyHelper;
6740b57cec5SDimitry Andric 
6750b57cec5SDimitry Andric   std::vector<std::string> BundleTags;
6760b57cec5SDimitry Andric   SmallVector<SyncScope::ID, 8> SSIDs;
6770b57cec5SDimitry Andric 
678bdd1243dSDimitry Andric   std::optional<ValueTypeCallbackTy> ValueTypeCallback;
679bdd1243dSDimitry Andric 
6800b57cec5SDimitry Andric public:
6810b57cec5SDimitry Andric   BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
6820b57cec5SDimitry Andric                 StringRef ProducerIdentification, LLVMContext &Context);
6830b57cec5SDimitry Andric 
6840b57cec5SDimitry Andric   Error materializeForwardReferencedFunctions();
6850b57cec5SDimitry Andric 
6860b57cec5SDimitry Andric   Error materialize(GlobalValue *GV) override;
6870b57cec5SDimitry Andric   Error materializeModule() override;
6880b57cec5SDimitry Andric   std::vector<StructType *> getIdentifiedStructTypes() const override;
6890b57cec5SDimitry Andric 
6900b57cec5SDimitry Andric   /// Main interface to parsing a bitcode buffer.
6910b57cec5SDimitry Andric   /// \returns true if an error occurred.
692bdd1243dSDimitry Andric   Error parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata,
693bdd1243dSDimitry Andric                          bool IsImporting, ParserCallbacks Callbacks = {});
6940b57cec5SDimitry Andric 
6950b57cec5SDimitry Andric   static uint64_t decodeSignRotatedValue(uint64_t V);
6960b57cec5SDimitry Andric 
6970b57cec5SDimitry Andric   /// Materialize any deferred Metadata block.
6980b57cec5SDimitry Andric   Error materializeMetadata() override;
6990b57cec5SDimitry Andric 
7000b57cec5SDimitry Andric   void setStripDebugInfo() override;
7010b57cec5SDimitry Andric 
7020b57cec5SDimitry Andric private:
7030b57cec5SDimitry Andric   std::vector<StructType *> IdentifiedStructTypes;
7040b57cec5SDimitry Andric   StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
7050b57cec5SDimitry Andric   StructType *createIdentifiedStructType(LLVMContext &Context);
7060b57cec5SDimitry Andric 
70781ad6265SDimitry Andric   static constexpr unsigned InvalidTypeID = ~0u;
7080b57cec5SDimitry Andric 
70981ad6265SDimitry Andric   Type *getTypeByID(unsigned ID);
71081ad6265SDimitry Andric   Type *getPtrElementTypeByID(unsigned ID);
71181ad6265SDimitry Andric   unsigned getContainedTypeID(unsigned ID, unsigned Idx = 0);
71281ad6265SDimitry Andric   unsigned getVirtualTypeID(Type *Ty, ArrayRef<unsigned> ContainedTypeIDs = {});
71381ad6265SDimitry Andric 
714bdd1243dSDimitry Andric   void callValueTypeCallback(Value *F, unsigned TypeID);
71581ad6265SDimitry Andric   Expected<Value *> materializeValue(unsigned ValID, BasicBlock *InsertBB);
71681ad6265SDimitry Andric   Expected<Constant *> getValueForInitializer(unsigned ID);
71781ad6265SDimitry Andric 
getFnValueByID(unsigned ID,Type * Ty,unsigned TyID,BasicBlock * ConstExprInsertBB)71881ad6265SDimitry Andric   Value *getFnValueByID(unsigned ID, Type *Ty, unsigned TyID,
71981ad6265SDimitry Andric                         BasicBlock *ConstExprInsertBB) {
7200b57cec5SDimitry Andric     if (Ty && Ty->isMetadataTy())
7210b57cec5SDimitry Andric       return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
72281ad6265SDimitry Andric     return ValueList.getValueFwdRef(ID, Ty, TyID, ConstExprInsertBB);
7230b57cec5SDimitry Andric   }
7240b57cec5SDimitry Andric 
getFnMetadataByID(unsigned ID)7250b57cec5SDimitry Andric   Metadata *getFnMetadataByID(unsigned ID) {
7260b57cec5SDimitry Andric     return MDLoader->getMetadataFwdRefOrLoad(ID);
7270b57cec5SDimitry Andric   }
7280b57cec5SDimitry Andric 
getBasicBlock(unsigned ID) const7290b57cec5SDimitry Andric   BasicBlock *getBasicBlock(unsigned ID) const {
7300b57cec5SDimitry Andric     if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
7310b57cec5SDimitry Andric     return FunctionBBs[ID];
7320b57cec5SDimitry Andric   }
7330b57cec5SDimitry Andric 
getAttributes(unsigned i) const7340b57cec5SDimitry Andric   AttributeList getAttributes(unsigned i) const {
7350b57cec5SDimitry Andric     if (i-1 < MAttributes.size())
7360b57cec5SDimitry Andric       return MAttributes[i-1];
7370b57cec5SDimitry Andric     return AttributeList();
7380b57cec5SDimitry Andric   }
7390b57cec5SDimitry Andric 
7400b57cec5SDimitry Andric   /// Read a value/type pair out of the specified record from slot 'Slot'.
7410b57cec5SDimitry Andric   /// Increment Slot past the number of slots used in the record. Return true on
7420b57cec5SDimitry Andric   /// failure.
getValueTypePair(const SmallVectorImpl<uint64_t> & Record,unsigned & Slot,unsigned InstNum,Value * & ResVal,unsigned & TypeID,BasicBlock * ConstExprInsertBB)743e8d8bef9SDimitry Andric   bool getValueTypePair(const SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
74481ad6265SDimitry Andric                         unsigned InstNum, Value *&ResVal, unsigned &TypeID,
74581ad6265SDimitry Andric                         BasicBlock *ConstExprInsertBB) {
7460b57cec5SDimitry Andric     if (Slot == Record.size()) return true;
7470b57cec5SDimitry Andric     unsigned ValNo = (unsigned)Record[Slot++];
7480b57cec5SDimitry Andric     // Adjust the ValNo, if it was encoded relative to the InstNum.
7490b57cec5SDimitry Andric     if (UseRelativeIDs)
7500b57cec5SDimitry Andric       ValNo = InstNum - ValNo;
7510b57cec5SDimitry Andric     if (ValNo < InstNum) {
7520b57cec5SDimitry Andric       // If this is not a forward reference, just return the value we already
7530b57cec5SDimitry Andric       // have.
75481ad6265SDimitry Andric       TypeID = ValueList.getTypeID(ValNo);
75581ad6265SDimitry Andric       ResVal = getFnValueByID(ValNo, nullptr, TypeID, ConstExprInsertBB);
75681ad6265SDimitry Andric       assert((!ResVal || ResVal->getType() == getTypeByID(TypeID)) &&
75781ad6265SDimitry Andric              "Incorrect type ID stored for value");
7580b57cec5SDimitry Andric       return ResVal == nullptr;
7590b57cec5SDimitry Andric     }
7600b57cec5SDimitry Andric     if (Slot == Record.size())
7610b57cec5SDimitry Andric       return true;
7620b57cec5SDimitry Andric 
76381ad6265SDimitry Andric     TypeID = (unsigned)Record[Slot++];
76481ad6265SDimitry Andric     ResVal = getFnValueByID(ValNo, getTypeByID(TypeID), TypeID,
76581ad6265SDimitry Andric                             ConstExprInsertBB);
7660b57cec5SDimitry Andric     return ResVal == nullptr;
7670b57cec5SDimitry Andric   }
7680b57cec5SDimitry Andric 
7690b57cec5SDimitry Andric   /// Read a value out of the specified record from slot 'Slot'. Increment Slot
7700b57cec5SDimitry Andric   /// past the number of slots used by the value in the record. Return true if
7710b57cec5SDimitry Andric   /// there is an error.
popValue(const SmallVectorImpl<uint64_t> & Record,unsigned & Slot,unsigned InstNum,Type * Ty,unsigned TyID,Value * & ResVal,BasicBlock * ConstExprInsertBB)772e8d8bef9SDimitry Andric   bool popValue(const SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
77381ad6265SDimitry Andric                 unsigned InstNum, Type *Ty, unsigned TyID, Value *&ResVal,
77481ad6265SDimitry Andric                 BasicBlock *ConstExprInsertBB) {
77581ad6265SDimitry Andric     if (getValue(Record, Slot, InstNum, Ty, TyID, ResVal, ConstExprInsertBB))
7760b57cec5SDimitry Andric       return true;
7770b57cec5SDimitry Andric     // All values currently take a single record slot.
7780b57cec5SDimitry Andric     ++Slot;
7790b57cec5SDimitry Andric     return false;
7800b57cec5SDimitry Andric   }
7810b57cec5SDimitry Andric 
7820b57cec5SDimitry Andric   /// Like popValue, but does not increment the Slot number.
getValue(const SmallVectorImpl<uint64_t> & Record,unsigned Slot,unsigned InstNum,Type * Ty,unsigned TyID,Value * & ResVal,BasicBlock * ConstExprInsertBB)783e8d8bef9SDimitry Andric   bool getValue(const SmallVectorImpl<uint64_t> &Record, unsigned Slot,
78481ad6265SDimitry Andric                 unsigned InstNum, Type *Ty, unsigned TyID, Value *&ResVal,
78581ad6265SDimitry Andric                 BasicBlock *ConstExprInsertBB) {
78681ad6265SDimitry Andric     ResVal = getValue(Record, Slot, InstNum, Ty, TyID, ConstExprInsertBB);
7870b57cec5SDimitry Andric     return ResVal == nullptr;
7880b57cec5SDimitry Andric   }
7890b57cec5SDimitry Andric 
7900b57cec5SDimitry Andric   /// Version of getValue that returns ResVal directly, or 0 if there is an
7910b57cec5SDimitry Andric   /// error.
getValue(const SmallVectorImpl<uint64_t> & Record,unsigned Slot,unsigned InstNum,Type * Ty,unsigned TyID,BasicBlock * ConstExprInsertBB)792e8d8bef9SDimitry Andric   Value *getValue(const SmallVectorImpl<uint64_t> &Record, unsigned Slot,
79381ad6265SDimitry Andric                   unsigned InstNum, Type *Ty, unsigned TyID,
79481ad6265SDimitry Andric                   BasicBlock *ConstExprInsertBB) {
7950b57cec5SDimitry Andric     if (Slot == Record.size()) return nullptr;
7960b57cec5SDimitry Andric     unsigned ValNo = (unsigned)Record[Slot];
7970b57cec5SDimitry Andric     // Adjust the ValNo, if it was encoded relative to the InstNum.
7980b57cec5SDimitry Andric     if (UseRelativeIDs)
7990b57cec5SDimitry Andric       ValNo = InstNum - ValNo;
80081ad6265SDimitry Andric     return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB);
8010b57cec5SDimitry Andric   }
8020b57cec5SDimitry Andric 
8030b57cec5SDimitry Andric   /// Like getValue, but decodes signed VBRs.
getValueSigned(const SmallVectorImpl<uint64_t> & Record,unsigned Slot,unsigned InstNum,Type * Ty,unsigned TyID,BasicBlock * ConstExprInsertBB)804e8d8bef9SDimitry Andric   Value *getValueSigned(const SmallVectorImpl<uint64_t> &Record, unsigned Slot,
80581ad6265SDimitry Andric                         unsigned InstNum, Type *Ty, unsigned TyID,
80681ad6265SDimitry Andric                         BasicBlock *ConstExprInsertBB) {
8070b57cec5SDimitry Andric     if (Slot == Record.size()) return nullptr;
8080b57cec5SDimitry Andric     unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
8090b57cec5SDimitry Andric     // Adjust the ValNo, if it was encoded relative to the InstNum.
8100b57cec5SDimitry Andric     if (UseRelativeIDs)
8110b57cec5SDimitry Andric       ValNo = InstNum - ValNo;
81281ad6265SDimitry Andric     return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB);
8130b57cec5SDimitry Andric   }
8140b57cec5SDimitry Andric 
815fe6060f1SDimitry Andric   /// Upgrades old-style typeless byval/sret/inalloca attributes by adding the
816fe6060f1SDimitry Andric   /// corresponding argument's pointee type. Also upgrades intrinsics that now
817fe6060f1SDimitry Andric   /// require an elementtype attribute.
81881ad6265SDimitry Andric   Error propagateAttributeTypes(CallBase *CB, ArrayRef<unsigned> ArgsTys);
8190b57cec5SDimitry Andric 
8200b57cec5SDimitry Andric   /// Converts alignment exponent (i.e. power of two (or zero)) to the
8210b57cec5SDimitry Andric   /// corresponding alignment to use. If alignment is too large, returns
8220b57cec5SDimitry Andric   /// a corresponding error code.
8238bcb0991SDimitry Andric   Error parseAlignmentValue(uint64_t Exponent, MaybeAlign &Alignment);
8240b57cec5SDimitry Andric   Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
825bdd1243dSDimitry Andric   Error parseModule(uint64_t ResumeBit, bool ShouldLazyLoadMetadata = false,
826bdd1243dSDimitry Andric                     ParserCallbacks Callbacks = {});
8270b57cec5SDimitry Andric 
8280b57cec5SDimitry Andric   Error parseComdatRecord(ArrayRef<uint64_t> Record);
8290b57cec5SDimitry Andric   Error parseGlobalVarRecord(ArrayRef<uint64_t> Record);
8300b57cec5SDimitry Andric   Error parseFunctionRecord(ArrayRef<uint64_t> Record);
8310b57cec5SDimitry Andric   Error parseGlobalIndirectSymbolRecord(unsigned BitCode,
8320b57cec5SDimitry Andric                                         ArrayRef<uint64_t> Record);
8330b57cec5SDimitry Andric 
8340b57cec5SDimitry Andric   Error parseAttributeBlock();
8350b57cec5SDimitry Andric   Error parseAttributeGroupBlock();
8360b57cec5SDimitry Andric   Error parseTypeTable();
8370b57cec5SDimitry Andric   Error parseTypeTableBody();
8380b57cec5SDimitry Andric   Error parseOperandBundleTags();
8390b57cec5SDimitry Andric   Error parseSyncScopeNames();
8400b57cec5SDimitry Andric 
8410b57cec5SDimitry Andric   Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
8420b57cec5SDimitry Andric                                 unsigned NameIndex, Triple &TT);
8430b57cec5SDimitry Andric   void setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, Function *F,
8440b57cec5SDimitry Andric                                ArrayRef<uint64_t> Record);
8450b57cec5SDimitry Andric   Error parseValueSymbolTable(uint64_t Offset = 0);
8460b57cec5SDimitry Andric   Error parseGlobalValueSymbolTable();
8470b57cec5SDimitry Andric   Error parseConstants();
8480b57cec5SDimitry Andric   Error rememberAndSkipFunctionBodies();
8490b57cec5SDimitry Andric   Error rememberAndSkipFunctionBody();
8500b57cec5SDimitry Andric   /// Save the positions of the Metadata blocks and skip parsing the blocks.
8510b57cec5SDimitry Andric   Error rememberAndSkipMetadata();
8520b57cec5SDimitry Andric   Error typeCheckLoadStoreInst(Type *ValType, Type *PtrType);
8530b57cec5SDimitry Andric   Error parseFunctionBody(Function *F);
8540b57cec5SDimitry Andric   Error globalCleanup();
8550b57cec5SDimitry Andric   Error resolveGlobalAndIndirectSymbolInits();
8560b57cec5SDimitry Andric   Error parseUseLists();
8570b57cec5SDimitry Andric   Error findFunctionInStream(
8580b57cec5SDimitry Andric       Function *F,
8590b57cec5SDimitry Andric       DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
8600b57cec5SDimitry Andric 
8610b57cec5SDimitry Andric   SyncScope::ID getDecodedSyncScopeID(unsigned Val);
8620b57cec5SDimitry Andric };
8630b57cec5SDimitry Andric 
8640b57cec5SDimitry Andric /// Class to manage reading and parsing function summary index bitcode
8650b57cec5SDimitry Andric /// files/sections.
8660b57cec5SDimitry Andric class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase {
8670b57cec5SDimitry Andric   /// The module index built during parsing.
8680b57cec5SDimitry Andric   ModuleSummaryIndex &TheIndex;
8690b57cec5SDimitry Andric 
8700b57cec5SDimitry Andric   /// Indicates whether we have encountered a global value summary section
8710b57cec5SDimitry Andric   /// yet during parsing.
8720b57cec5SDimitry Andric   bool SeenGlobalValSummary = false;
8730b57cec5SDimitry Andric 
8740b57cec5SDimitry Andric   /// Indicates whether we have already parsed the VST, used for error checking.
8750b57cec5SDimitry Andric   bool SeenValueSymbolTable = false;
8760b57cec5SDimitry Andric 
8770b57cec5SDimitry Andric   /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record.
8780b57cec5SDimitry Andric   /// Used to enable on-demand parsing of the VST.
8790b57cec5SDimitry Andric   uint64_t VSTOffset = 0;
8800b57cec5SDimitry Andric 
8810b57cec5SDimitry Andric   // Map to save ValueId to ValueInfo association that was recorded in the
8820b57cec5SDimitry Andric   // ValueSymbolTable. It is used after the VST is parsed to convert
8830b57cec5SDimitry Andric   // call graph edges read from the function summary from referencing
8840b57cec5SDimitry Andric   // callees by their ValueId to using the ValueInfo instead, which is how
8850b57cec5SDimitry Andric   // they are recorded in the summary index being built.
8860b57cec5SDimitry Andric   // We save a GUID which refers to the same global as the ValueInfo, but
8870b57cec5SDimitry Andric   // ignoring the linkage, i.e. for values other than local linkage they are
888bdd1243dSDimitry Andric   // identical (this is the second tuple member).
889bdd1243dSDimitry Andric   // The third tuple member is the real GUID of the ValueInfo.
890bdd1243dSDimitry Andric   DenseMap<unsigned,
891bdd1243dSDimitry Andric            std::tuple<ValueInfo, GlobalValue::GUID, GlobalValue::GUID>>
8920b57cec5SDimitry Andric       ValueIdToValueInfoMap;
8930b57cec5SDimitry Andric 
8940b57cec5SDimitry Andric   /// Map populated during module path string table parsing, from the
8950b57cec5SDimitry Andric   /// module ID to a string reference owned by the index's module
8960b57cec5SDimitry Andric   /// path string table, used to correlate with combined index
8970b57cec5SDimitry Andric   /// summary records.
8980b57cec5SDimitry Andric   DenseMap<uint64_t, StringRef> ModuleIdMap;
8990b57cec5SDimitry Andric 
9000b57cec5SDimitry Andric   /// Original source file name recorded in a bitcode record.
9010b57cec5SDimitry Andric   std::string SourceFileName;
9020b57cec5SDimitry Andric 
9030b57cec5SDimitry Andric   /// The string identifier given to this module by the client, normally the
9040b57cec5SDimitry Andric   /// path to the bitcode file.
9050b57cec5SDimitry Andric   StringRef ModulePath;
9060b57cec5SDimitry Andric 
907bdd1243dSDimitry Andric   /// Callback to ask whether a symbol is the prevailing copy when invoked
908bdd1243dSDimitry Andric   /// during combined index building.
909bdd1243dSDimitry Andric   std::function<bool(GlobalValue::GUID)> IsPrevailing;
910bdd1243dSDimitry Andric 
911bdd1243dSDimitry Andric   /// Saves the stack ids from the STACK_IDS record to consult when adding stack
912bdd1243dSDimitry Andric   /// ids from the lists in the callsite and alloc entries to the index.
913bdd1243dSDimitry Andric   std::vector<uint64_t> StackIds;
914bdd1243dSDimitry Andric 
9150b57cec5SDimitry Andric public:
916bdd1243dSDimitry Andric   ModuleSummaryIndexBitcodeReader(
917bdd1243dSDimitry Andric       BitstreamCursor Stream, StringRef Strtab, ModuleSummaryIndex &TheIndex,
918c9157d92SDimitry Andric       StringRef ModulePath,
919bdd1243dSDimitry Andric       std::function<bool(GlobalValue::GUID)> IsPrevailing = nullptr);
9200b57cec5SDimitry Andric 
9210b57cec5SDimitry Andric   Error parseModule();
9220b57cec5SDimitry Andric 
9230b57cec5SDimitry Andric private:
9240b57cec5SDimitry Andric   void setValueGUID(uint64_t ValueID, StringRef ValueName,
9250b57cec5SDimitry Andric                     GlobalValue::LinkageTypes Linkage,
9260b57cec5SDimitry Andric                     StringRef SourceFileName);
9270b57cec5SDimitry Andric   Error parseValueSymbolTable(
9280b57cec5SDimitry Andric       uint64_t Offset,
9290b57cec5SDimitry Andric       DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
9300b57cec5SDimitry Andric   std::vector<ValueInfo> makeRefList(ArrayRef<uint64_t> Record);
9310b57cec5SDimitry Andric   std::vector<FunctionSummary::EdgeTy> makeCallList(ArrayRef<uint64_t> Record,
9320b57cec5SDimitry Andric                                                     bool IsOldProfileFormat,
9330b57cec5SDimitry Andric                                                     bool HasProfile,
9340b57cec5SDimitry Andric                                                     bool HasRelBF);
9350b57cec5SDimitry Andric   Error parseEntireSummary(unsigned ID);
9360b57cec5SDimitry Andric   Error parseModuleStringTable();
9370b57cec5SDimitry Andric   void parseTypeIdCompatibleVtableSummaryRecord(ArrayRef<uint64_t> Record);
9380b57cec5SDimitry Andric   void parseTypeIdCompatibleVtableInfo(ArrayRef<uint64_t> Record, size_t &Slot,
9390b57cec5SDimitry Andric                                        TypeIdCompatibleVtableInfo &TypeId);
940e8d8bef9SDimitry Andric   std::vector<FunctionSummary::ParamAccess>
941e8d8bef9SDimitry Andric   parseParamAccesses(ArrayRef<uint64_t> Record);
9420b57cec5SDimitry Andric 
943bdd1243dSDimitry Andric   template <bool AllowNullValueInfo = false>
944bdd1243dSDimitry Andric   std::tuple<ValueInfo, GlobalValue::GUID, GlobalValue::GUID>
9450b57cec5SDimitry Andric   getValueInfoFromValueId(unsigned ValueId);
9460b57cec5SDimitry Andric 
9470b57cec5SDimitry Andric   void addThisModule();
9480b57cec5SDimitry Andric   ModuleSummaryIndex::ModuleInfo *getThisModule();
9490b57cec5SDimitry Andric };
9500b57cec5SDimitry Andric 
9510b57cec5SDimitry Andric } // end anonymous namespace
9520b57cec5SDimitry Andric 
errorToErrorCodeAndEmitErrors(LLVMContext & Ctx,Error Err)9530b57cec5SDimitry Andric std::error_code llvm::errorToErrorCodeAndEmitErrors(LLVMContext &Ctx,
9540b57cec5SDimitry Andric                                                     Error Err) {
9550b57cec5SDimitry Andric   if (Err) {
9560b57cec5SDimitry Andric     std::error_code EC;
9570b57cec5SDimitry Andric     handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) {
9580b57cec5SDimitry Andric       EC = EIB.convertToErrorCode();
9590b57cec5SDimitry Andric       Ctx.emitError(EIB.message());
9600b57cec5SDimitry Andric     });
9610b57cec5SDimitry Andric     return EC;
9620b57cec5SDimitry Andric   }
9630b57cec5SDimitry Andric   return std::error_code();
9640b57cec5SDimitry Andric }
9650b57cec5SDimitry Andric 
BitcodeReader(BitstreamCursor Stream,StringRef Strtab,StringRef ProducerIdentification,LLVMContext & Context)9660b57cec5SDimitry Andric BitcodeReader::BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
9670b57cec5SDimitry Andric                              StringRef ProducerIdentification,
9680b57cec5SDimitry Andric                              LLVMContext &Context)
9690b57cec5SDimitry Andric     : BitcodeReaderBase(std::move(Stream), Strtab), Context(Context),
97081ad6265SDimitry Andric       ValueList(this->Stream.SizeInBytes(),
97181ad6265SDimitry Andric                 [this](unsigned ValID, BasicBlock *InsertBB) {
97281ad6265SDimitry Andric                   return materializeValue(ValID, InsertBB);
97381ad6265SDimitry Andric                 }) {
9745ffd83dbSDimitry Andric   this->ProducerIdentification = std::string(ProducerIdentification);
9750b57cec5SDimitry Andric }
9760b57cec5SDimitry Andric 
materializeForwardReferencedFunctions()9770b57cec5SDimitry Andric Error BitcodeReader::materializeForwardReferencedFunctions() {
9780b57cec5SDimitry Andric   if (WillMaterializeAllForwardRefs)
9790b57cec5SDimitry Andric     return Error::success();
9800b57cec5SDimitry Andric 
9810b57cec5SDimitry Andric   // Prevent recursion.
9820b57cec5SDimitry Andric   WillMaterializeAllForwardRefs = true;
9830b57cec5SDimitry Andric 
9840b57cec5SDimitry Andric   while (!BasicBlockFwdRefQueue.empty()) {
9850b57cec5SDimitry Andric     Function *F = BasicBlockFwdRefQueue.front();
9860b57cec5SDimitry Andric     BasicBlockFwdRefQueue.pop_front();
9870b57cec5SDimitry Andric     assert(F && "Expected valid function");
9880b57cec5SDimitry Andric     if (!BasicBlockFwdRefs.count(F))
9890b57cec5SDimitry Andric       // Already materialized.
9900b57cec5SDimitry Andric       continue;
9910b57cec5SDimitry Andric 
9920b57cec5SDimitry Andric     // Check for a function that isn't materializable to prevent an infinite
9930b57cec5SDimitry Andric     // loop.  When parsing a blockaddress stored in a global variable, there
9940b57cec5SDimitry Andric     // isn't a trivial way to check if a function will have a body without a
9950b57cec5SDimitry Andric     // linear search through FunctionsWithBodies, so just check it here.
9960b57cec5SDimitry Andric     if (!F->isMaterializable())
9970b57cec5SDimitry Andric       return error("Never resolved function from blockaddress");
9980b57cec5SDimitry Andric 
9990b57cec5SDimitry Andric     // Try to materialize F.
10000b57cec5SDimitry Andric     if (Error Err = materialize(F))
10010b57cec5SDimitry Andric       return Err;
10020b57cec5SDimitry Andric   }
10030b57cec5SDimitry Andric   assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
10040b57cec5SDimitry Andric 
100581ad6265SDimitry Andric   for (Function *F : BackwardRefFunctions)
100681ad6265SDimitry Andric     if (Error Err = materialize(F))
100781ad6265SDimitry Andric       return Err;
100881ad6265SDimitry Andric   BackwardRefFunctions.clear();
100981ad6265SDimitry Andric 
10100b57cec5SDimitry Andric   // Reset state.
10110b57cec5SDimitry Andric   WillMaterializeAllForwardRefs = false;
10120b57cec5SDimitry Andric   return Error::success();
10130b57cec5SDimitry Andric }
10140b57cec5SDimitry Andric 
10150b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
10160b57cec5SDimitry Andric //  Helper functions to implement forward reference resolution, etc.
10170b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
10180b57cec5SDimitry Andric 
hasImplicitComdat(size_t Val)10190b57cec5SDimitry Andric static bool hasImplicitComdat(size_t Val) {
10200b57cec5SDimitry Andric   switch (Val) {
10210b57cec5SDimitry Andric   default:
10220b57cec5SDimitry Andric     return false;
10230b57cec5SDimitry Andric   case 1:  // Old WeakAnyLinkage
10240b57cec5SDimitry Andric   case 4:  // Old LinkOnceAnyLinkage
10250b57cec5SDimitry Andric   case 10: // Old WeakODRLinkage
10260b57cec5SDimitry Andric   case 11: // Old LinkOnceODRLinkage
10270b57cec5SDimitry Andric     return true;
10280b57cec5SDimitry Andric   }
10290b57cec5SDimitry Andric }
10300b57cec5SDimitry Andric 
getDecodedLinkage(unsigned Val)10310b57cec5SDimitry Andric static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
10320b57cec5SDimitry Andric   switch (Val) {
10330b57cec5SDimitry Andric   default: // Map unknown/new linkages to external
10340b57cec5SDimitry Andric   case 0:
10350b57cec5SDimitry Andric     return GlobalValue::ExternalLinkage;
10360b57cec5SDimitry Andric   case 2:
10370b57cec5SDimitry Andric     return GlobalValue::AppendingLinkage;
10380b57cec5SDimitry Andric   case 3:
10390b57cec5SDimitry Andric     return GlobalValue::InternalLinkage;
10400b57cec5SDimitry Andric   case 5:
10410b57cec5SDimitry Andric     return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
10420b57cec5SDimitry Andric   case 6:
10430b57cec5SDimitry Andric     return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
10440b57cec5SDimitry Andric   case 7:
10450b57cec5SDimitry Andric     return GlobalValue::ExternalWeakLinkage;
10460b57cec5SDimitry Andric   case 8:
10470b57cec5SDimitry Andric     return GlobalValue::CommonLinkage;
10480b57cec5SDimitry Andric   case 9:
10490b57cec5SDimitry Andric     return GlobalValue::PrivateLinkage;
10500b57cec5SDimitry Andric   case 12:
10510b57cec5SDimitry Andric     return GlobalValue::AvailableExternallyLinkage;
10520b57cec5SDimitry Andric   case 13:
10530b57cec5SDimitry Andric     return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
10540b57cec5SDimitry Andric   case 14:
10550b57cec5SDimitry Andric     return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
10560b57cec5SDimitry Andric   case 15:
10570b57cec5SDimitry Andric     return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
10580b57cec5SDimitry Andric   case 1: // Old value with implicit comdat.
10590b57cec5SDimitry Andric   case 16:
10600b57cec5SDimitry Andric     return GlobalValue::WeakAnyLinkage;
10610b57cec5SDimitry Andric   case 10: // Old value with implicit comdat.
10620b57cec5SDimitry Andric   case 17:
10630b57cec5SDimitry Andric     return GlobalValue::WeakODRLinkage;
10640b57cec5SDimitry Andric   case 4: // Old value with implicit comdat.
10650b57cec5SDimitry Andric   case 18:
10660b57cec5SDimitry Andric     return GlobalValue::LinkOnceAnyLinkage;
10670b57cec5SDimitry Andric   case 11: // Old value with implicit comdat.
10680b57cec5SDimitry Andric   case 19:
10690b57cec5SDimitry Andric     return GlobalValue::LinkOnceODRLinkage;
10700b57cec5SDimitry Andric   }
10710b57cec5SDimitry Andric }
10720b57cec5SDimitry Andric 
getDecodedFFlags(uint64_t RawFlags)10730b57cec5SDimitry Andric static FunctionSummary::FFlags getDecodedFFlags(uint64_t RawFlags) {
10740b57cec5SDimitry Andric   FunctionSummary::FFlags Flags;
10750b57cec5SDimitry Andric   Flags.ReadNone = RawFlags & 0x1;
10760b57cec5SDimitry Andric   Flags.ReadOnly = (RawFlags >> 1) & 0x1;
10770b57cec5SDimitry Andric   Flags.NoRecurse = (RawFlags >> 2) & 0x1;
10780b57cec5SDimitry Andric   Flags.ReturnDoesNotAlias = (RawFlags >> 3) & 0x1;
10790b57cec5SDimitry Andric   Flags.NoInline = (RawFlags >> 4) & 0x1;
1080480093f4SDimitry Andric   Flags.AlwaysInline = (RawFlags >> 5) & 0x1;
1081349cc55cSDimitry Andric   Flags.NoUnwind = (RawFlags >> 6) & 0x1;
1082349cc55cSDimitry Andric   Flags.MayThrow = (RawFlags >> 7) & 0x1;
1083349cc55cSDimitry Andric   Flags.HasUnknownCall = (RawFlags >> 8) & 0x1;
10840eae32dcSDimitry Andric   Flags.MustBeUnreachable = (RawFlags >> 9) & 0x1;
10850b57cec5SDimitry Andric   return Flags;
10860b57cec5SDimitry Andric }
10870b57cec5SDimitry Andric 
1088fe6060f1SDimitry Andric // Decode the flags for GlobalValue in the summary. The bits for each attribute:
1089fe6060f1SDimitry Andric //
1090fe6060f1SDimitry Andric // linkage: [0,4), notEligibleToImport: 4, live: 5, local: 6, canAutoHide: 7,
1091fe6060f1SDimitry Andric // visibility: [8, 10).
getDecodedGVSummaryFlags(uint64_t RawFlags,uint64_t Version)10920b57cec5SDimitry Andric static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags,
10930b57cec5SDimitry Andric                                                             uint64_t Version) {
10940b57cec5SDimitry Andric   // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage
10950b57cec5SDimitry Andric   // like getDecodedLinkage() above. Any future change to the linkage enum and
10960b57cec5SDimitry Andric   // to getDecodedLinkage() will need to be taken into account here as above.
10970b57cec5SDimitry Andric   auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits
1098fe6060f1SDimitry Andric   auto Visibility = GlobalValue::VisibilityTypes((RawFlags >> 8) & 3); // 2 bits
10990b57cec5SDimitry Andric   RawFlags = RawFlags >> 4;
11000b57cec5SDimitry Andric   bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3;
11010b57cec5SDimitry Andric   // The Live flag wasn't introduced until version 3. For dead stripping
11020b57cec5SDimitry Andric   // to work correctly on earlier versions, we must conservatively treat all
11030b57cec5SDimitry Andric   // values as live.
11040b57cec5SDimitry Andric   bool Live = (RawFlags & 0x2) || Version < 3;
11050b57cec5SDimitry Andric   bool Local = (RawFlags & 0x4);
11060b57cec5SDimitry Andric   bool AutoHide = (RawFlags & 0x8);
11070b57cec5SDimitry Andric 
1108fe6060f1SDimitry Andric   return GlobalValueSummary::GVFlags(Linkage, Visibility, NotEligibleToImport,
1109fe6060f1SDimitry Andric                                      Live, Local, AutoHide);
11100b57cec5SDimitry Andric }
11110b57cec5SDimitry Andric 
11120b57cec5SDimitry Andric // Decode the flags for GlobalVariable in the summary
getDecodedGVarFlags(uint64_t RawFlags)11130b57cec5SDimitry Andric static GlobalVarSummary::GVarFlags getDecodedGVarFlags(uint64_t RawFlags) {
11145ffd83dbSDimitry Andric   return GlobalVarSummary::GVarFlags(
11155ffd83dbSDimitry Andric       (RawFlags & 0x1) ? true : false, (RawFlags & 0x2) ? true : false,
11165ffd83dbSDimitry Andric       (RawFlags & 0x4) ? true : false,
11175ffd83dbSDimitry Andric       (GlobalObject::VCallVisibility)(RawFlags >> 3));
11180b57cec5SDimitry Andric }
11190b57cec5SDimitry Andric 
1120c9157d92SDimitry Andric static std::pair<CalleeInfo::HotnessType, bool>
getDecodedHotnessCallEdgeInfo(uint64_t RawFlags)1121c9157d92SDimitry Andric getDecodedHotnessCallEdgeInfo(uint64_t RawFlags) {
1122c9157d92SDimitry Andric   CalleeInfo::HotnessType Hotness =
1123c9157d92SDimitry Andric       static_cast<CalleeInfo::HotnessType>(RawFlags & 0x7); // 3 bits
1124c9157d92SDimitry Andric   bool HasTailCall = (RawFlags & 0x8);                      // 1 bit
1125c9157d92SDimitry Andric   return {Hotness, HasTailCall};
1126c9157d92SDimitry Andric }
1127c9157d92SDimitry Andric 
getDecodedRelBFCallEdgeInfo(uint64_t RawFlags,uint64_t & RelBF,bool & HasTailCall)1128c9157d92SDimitry Andric static void getDecodedRelBFCallEdgeInfo(uint64_t RawFlags, uint64_t &RelBF,
1129c9157d92SDimitry Andric                                         bool &HasTailCall) {
1130c9157d92SDimitry Andric   static constexpr uint64_t RelBlockFreqMask =
1131c9157d92SDimitry Andric       (1 << CalleeInfo::RelBlockFreqBits) - 1;
1132c9157d92SDimitry Andric   RelBF = RawFlags & RelBlockFreqMask; // RelBlockFreqBits bits
1133c9157d92SDimitry Andric   HasTailCall = (RawFlags & (1 << CalleeInfo::RelBlockFreqBits)); // 1 bit
1134c9157d92SDimitry Andric }
1135c9157d92SDimitry Andric 
getDecodedVisibility(unsigned Val)11360b57cec5SDimitry Andric static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
11370b57cec5SDimitry Andric   switch (Val) {
11380b57cec5SDimitry Andric   default: // Map unknown visibilities to default.
11390b57cec5SDimitry Andric   case 0: return GlobalValue::DefaultVisibility;
11400b57cec5SDimitry Andric   case 1: return GlobalValue::HiddenVisibility;
11410b57cec5SDimitry Andric   case 2: return GlobalValue::ProtectedVisibility;
11420b57cec5SDimitry Andric   }
11430b57cec5SDimitry Andric }
11440b57cec5SDimitry Andric 
11450b57cec5SDimitry Andric static GlobalValue::DLLStorageClassTypes
getDecodedDLLStorageClass(unsigned Val)11460b57cec5SDimitry Andric getDecodedDLLStorageClass(unsigned Val) {
11470b57cec5SDimitry Andric   switch (Val) {
11480b57cec5SDimitry Andric   default: // Map unknown values to default.
11490b57cec5SDimitry Andric   case 0: return GlobalValue::DefaultStorageClass;
11500b57cec5SDimitry Andric   case 1: return GlobalValue::DLLImportStorageClass;
11510b57cec5SDimitry Andric   case 2: return GlobalValue::DLLExportStorageClass;
11520b57cec5SDimitry Andric   }
11530b57cec5SDimitry Andric }
11540b57cec5SDimitry Andric 
getDecodedDSOLocal(unsigned Val)11550b57cec5SDimitry Andric static bool getDecodedDSOLocal(unsigned Val) {
11560b57cec5SDimitry Andric   switch(Val) {
11570b57cec5SDimitry Andric   default: // Map unknown values to preemptable.
11580b57cec5SDimitry Andric   case 0:  return false;
11590b57cec5SDimitry Andric   case 1:  return true;
11600b57cec5SDimitry Andric   }
11610b57cec5SDimitry Andric }
11620b57cec5SDimitry Andric 
getDecodedCodeModel(unsigned Val)1163c9157d92SDimitry Andric static std::optional<CodeModel::Model> getDecodedCodeModel(unsigned Val) {
1164c9157d92SDimitry Andric   switch (Val) {
1165c9157d92SDimitry Andric   case 1:
1166c9157d92SDimitry Andric     return CodeModel::Tiny;
1167c9157d92SDimitry Andric   case 2:
1168c9157d92SDimitry Andric     return CodeModel::Small;
1169c9157d92SDimitry Andric   case 3:
1170c9157d92SDimitry Andric     return CodeModel::Kernel;
1171c9157d92SDimitry Andric   case 4:
1172c9157d92SDimitry Andric     return CodeModel::Medium;
1173c9157d92SDimitry Andric   case 5:
1174c9157d92SDimitry Andric     return CodeModel::Large;
1175c9157d92SDimitry Andric   }
1176c9157d92SDimitry Andric 
1177c9157d92SDimitry Andric   return {};
1178c9157d92SDimitry Andric }
1179c9157d92SDimitry Andric 
getDecodedThreadLocalMode(unsigned Val)11800b57cec5SDimitry Andric static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
11810b57cec5SDimitry Andric   switch (Val) {
11820b57cec5SDimitry Andric     case 0: return GlobalVariable::NotThreadLocal;
11830b57cec5SDimitry Andric     default: // Map unknown non-zero value to general dynamic.
11840b57cec5SDimitry Andric     case 1: return GlobalVariable::GeneralDynamicTLSModel;
11850b57cec5SDimitry Andric     case 2: return GlobalVariable::LocalDynamicTLSModel;
11860b57cec5SDimitry Andric     case 3: return GlobalVariable::InitialExecTLSModel;
11870b57cec5SDimitry Andric     case 4: return GlobalVariable::LocalExecTLSModel;
11880b57cec5SDimitry Andric   }
11890b57cec5SDimitry Andric }
11900b57cec5SDimitry Andric 
getDecodedUnnamedAddrType(unsigned Val)11910b57cec5SDimitry Andric static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) {
11920b57cec5SDimitry Andric   switch (Val) {
11930b57cec5SDimitry Andric     default: // Map unknown to UnnamedAddr::None.
11940b57cec5SDimitry Andric     case 0: return GlobalVariable::UnnamedAddr::None;
11950b57cec5SDimitry Andric     case 1: return GlobalVariable::UnnamedAddr::Global;
11960b57cec5SDimitry Andric     case 2: return GlobalVariable::UnnamedAddr::Local;
11970b57cec5SDimitry Andric   }
11980b57cec5SDimitry Andric }
11990b57cec5SDimitry Andric 
getDecodedCastOpcode(unsigned Val)12000b57cec5SDimitry Andric static int getDecodedCastOpcode(unsigned Val) {
12010b57cec5SDimitry Andric   switch (Val) {
12020b57cec5SDimitry Andric   default: return -1;
12030b57cec5SDimitry Andric   case bitc::CAST_TRUNC   : return Instruction::Trunc;
12040b57cec5SDimitry Andric   case bitc::CAST_ZEXT    : return Instruction::ZExt;
12050b57cec5SDimitry Andric   case bitc::CAST_SEXT    : return Instruction::SExt;
12060b57cec5SDimitry Andric   case bitc::CAST_FPTOUI  : return Instruction::FPToUI;
12070b57cec5SDimitry Andric   case bitc::CAST_FPTOSI  : return Instruction::FPToSI;
12080b57cec5SDimitry Andric   case bitc::CAST_UITOFP  : return Instruction::UIToFP;
12090b57cec5SDimitry Andric   case bitc::CAST_SITOFP  : return Instruction::SIToFP;
12100b57cec5SDimitry Andric   case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
12110b57cec5SDimitry Andric   case bitc::CAST_FPEXT   : return Instruction::FPExt;
12120b57cec5SDimitry Andric   case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
12130b57cec5SDimitry Andric   case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
12140b57cec5SDimitry Andric   case bitc::CAST_BITCAST : return Instruction::BitCast;
12150b57cec5SDimitry Andric   case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
12160b57cec5SDimitry Andric   }
12170b57cec5SDimitry Andric }
12180b57cec5SDimitry Andric 
getDecodedUnaryOpcode(unsigned Val,Type * Ty)12190b57cec5SDimitry Andric static int getDecodedUnaryOpcode(unsigned Val, Type *Ty) {
12200b57cec5SDimitry Andric   bool IsFP = Ty->isFPOrFPVectorTy();
12210b57cec5SDimitry Andric   // UnOps are only valid for int/fp or vector of int/fp types
12220b57cec5SDimitry Andric   if (!IsFP && !Ty->isIntOrIntVectorTy())
12230b57cec5SDimitry Andric     return -1;
12240b57cec5SDimitry Andric 
12250b57cec5SDimitry Andric   switch (Val) {
12260b57cec5SDimitry Andric   default:
12270b57cec5SDimitry Andric     return -1;
12288bcb0991SDimitry Andric   case bitc::UNOP_FNEG:
12290b57cec5SDimitry Andric     return IsFP ? Instruction::FNeg : -1;
12300b57cec5SDimitry Andric   }
12310b57cec5SDimitry Andric }
12320b57cec5SDimitry Andric 
getDecodedBinaryOpcode(unsigned Val,Type * Ty)12330b57cec5SDimitry Andric static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
12340b57cec5SDimitry Andric   bool IsFP = Ty->isFPOrFPVectorTy();
12350b57cec5SDimitry Andric   // BinOps are only valid for int/fp or vector of int/fp types
12360b57cec5SDimitry Andric   if (!IsFP && !Ty->isIntOrIntVectorTy())
12370b57cec5SDimitry Andric     return -1;
12380b57cec5SDimitry Andric 
12390b57cec5SDimitry Andric   switch (Val) {
12400b57cec5SDimitry Andric   default:
12410b57cec5SDimitry Andric     return -1;
12420b57cec5SDimitry Andric   case bitc::BINOP_ADD:
12430b57cec5SDimitry Andric     return IsFP ? Instruction::FAdd : Instruction::Add;
12440b57cec5SDimitry Andric   case bitc::BINOP_SUB:
12450b57cec5SDimitry Andric     return IsFP ? Instruction::FSub : Instruction::Sub;
12460b57cec5SDimitry Andric   case bitc::BINOP_MUL:
12470b57cec5SDimitry Andric     return IsFP ? Instruction::FMul : Instruction::Mul;
12480b57cec5SDimitry Andric   case bitc::BINOP_UDIV:
12490b57cec5SDimitry Andric     return IsFP ? -1 : Instruction::UDiv;
12500b57cec5SDimitry Andric   case bitc::BINOP_SDIV:
12510b57cec5SDimitry Andric     return IsFP ? Instruction::FDiv : Instruction::SDiv;
12520b57cec5SDimitry Andric   case bitc::BINOP_UREM:
12530b57cec5SDimitry Andric     return IsFP ? -1 : Instruction::URem;
12540b57cec5SDimitry Andric   case bitc::BINOP_SREM:
12550b57cec5SDimitry Andric     return IsFP ? Instruction::FRem : Instruction::SRem;
12560b57cec5SDimitry Andric   case bitc::BINOP_SHL:
12570b57cec5SDimitry Andric     return IsFP ? -1 : Instruction::Shl;
12580b57cec5SDimitry Andric   case bitc::BINOP_LSHR:
12590b57cec5SDimitry Andric     return IsFP ? -1 : Instruction::LShr;
12600b57cec5SDimitry Andric   case bitc::BINOP_ASHR:
12610b57cec5SDimitry Andric     return IsFP ? -1 : Instruction::AShr;
12620b57cec5SDimitry Andric   case bitc::BINOP_AND:
12630b57cec5SDimitry Andric     return IsFP ? -1 : Instruction::And;
12640b57cec5SDimitry Andric   case bitc::BINOP_OR:
12650b57cec5SDimitry Andric     return IsFP ? -1 : Instruction::Or;
12660b57cec5SDimitry Andric   case bitc::BINOP_XOR:
12670b57cec5SDimitry Andric     return IsFP ? -1 : Instruction::Xor;
12680b57cec5SDimitry Andric   }
12690b57cec5SDimitry Andric }
12700b57cec5SDimitry Andric 
getDecodedRMWOperation(unsigned Val)12710b57cec5SDimitry Andric static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
12720b57cec5SDimitry Andric   switch (Val) {
12730b57cec5SDimitry Andric   default: return AtomicRMWInst::BAD_BINOP;
12740b57cec5SDimitry Andric   case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
12750b57cec5SDimitry Andric   case bitc::RMW_ADD: return AtomicRMWInst::Add;
12760b57cec5SDimitry Andric   case bitc::RMW_SUB: return AtomicRMWInst::Sub;
12770b57cec5SDimitry Andric   case bitc::RMW_AND: return AtomicRMWInst::And;
12780b57cec5SDimitry Andric   case bitc::RMW_NAND: return AtomicRMWInst::Nand;
12790b57cec5SDimitry Andric   case bitc::RMW_OR: return AtomicRMWInst::Or;
12800b57cec5SDimitry Andric   case bitc::RMW_XOR: return AtomicRMWInst::Xor;
12810b57cec5SDimitry Andric   case bitc::RMW_MAX: return AtomicRMWInst::Max;
12820b57cec5SDimitry Andric   case bitc::RMW_MIN: return AtomicRMWInst::Min;
12830b57cec5SDimitry Andric   case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
12840b57cec5SDimitry Andric   case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
12850b57cec5SDimitry Andric   case bitc::RMW_FADD: return AtomicRMWInst::FAdd;
12860b57cec5SDimitry Andric   case bitc::RMW_FSUB: return AtomicRMWInst::FSub;
1287753f127fSDimitry Andric   case bitc::RMW_FMAX: return AtomicRMWInst::FMax;
1288753f127fSDimitry Andric   case bitc::RMW_FMIN: return AtomicRMWInst::FMin;
1289bdd1243dSDimitry Andric   case bitc::RMW_UINC_WRAP:
1290bdd1243dSDimitry Andric     return AtomicRMWInst::UIncWrap;
1291bdd1243dSDimitry Andric   case bitc::RMW_UDEC_WRAP:
1292bdd1243dSDimitry Andric     return AtomicRMWInst::UDecWrap;
12930b57cec5SDimitry Andric   }
12940b57cec5SDimitry Andric }
12950b57cec5SDimitry Andric 
getDecodedOrdering(unsigned Val)12960b57cec5SDimitry Andric static AtomicOrdering getDecodedOrdering(unsigned Val) {
12970b57cec5SDimitry Andric   switch (Val) {
12980b57cec5SDimitry Andric   case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic;
12990b57cec5SDimitry Andric   case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered;
13000b57cec5SDimitry Andric   case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic;
13010b57cec5SDimitry Andric   case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire;
13020b57cec5SDimitry Andric   case bitc::ORDERING_RELEASE: return AtomicOrdering::Release;
13030b57cec5SDimitry Andric   case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease;
13040b57cec5SDimitry Andric   default: // Map unknown orderings to sequentially-consistent.
13050b57cec5SDimitry Andric   case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent;
13060b57cec5SDimitry Andric   }
13070b57cec5SDimitry Andric }
13080b57cec5SDimitry Andric 
getDecodedComdatSelectionKind(unsigned Val)13090b57cec5SDimitry Andric static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
13100b57cec5SDimitry Andric   switch (Val) {
13110b57cec5SDimitry Andric   default: // Map unknown selection kinds to any.
13120b57cec5SDimitry Andric   case bitc::COMDAT_SELECTION_KIND_ANY:
13130b57cec5SDimitry Andric     return Comdat::Any;
13140b57cec5SDimitry Andric   case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
13150b57cec5SDimitry Andric     return Comdat::ExactMatch;
13160b57cec5SDimitry Andric   case bitc::COMDAT_SELECTION_KIND_LARGEST:
13170b57cec5SDimitry Andric     return Comdat::Largest;
13180b57cec5SDimitry Andric   case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
1319fe6060f1SDimitry Andric     return Comdat::NoDeduplicate;
13200b57cec5SDimitry Andric   case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
13210b57cec5SDimitry Andric     return Comdat::SameSize;
13220b57cec5SDimitry Andric   }
13230b57cec5SDimitry Andric }
13240b57cec5SDimitry Andric 
getDecodedFastMathFlags(unsigned Val)13250b57cec5SDimitry Andric static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
13260b57cec5SDimitry Andric   FastMathFlags FMF;
13270b57cec5SDimitry Andric   if (0 != (Val & bitc::UnsafeAlgebra))
13280b57cec5SDimitry Andric     FMF.setFast();
13290b57cec5SDimitry Andric   if (0 != (Val & bitc::AllowReassoc))
13300b57cec5SDimitry Andric     FMF.setAllowReassoc();
13310b57cec5SDimitry Andric   if (0 != (Val & bitc::NoNaNs))
13320b57cec5SDimitry Andric     FMF.setNoNaNs();
13330b57cec5SDimitry Andric   if (0 != (Val & bitc::NoInfs))
13340b57cec5SDimitry Andric     FMF.setNoInfs();
13350b57cec5SDimitry Andric   if (0 != (Val & bitc::NoSignedZeros))
13360b57cec5SDimitry Andric     FMF.setNoSignedZeros();
13370b57cec5SDimitry Andric   if (0 != (Val & bitc::AllowReciprocal))
13380b57cec5SDimitry Andric     FMF.setAllowReciprocal();
13390b57cec5SDimitry Andric   if (0 != (Val & bitc::AllowContract))
13400b57cec5SDimitry Andric     FMF.setAllowContract(true);
13410b57cec5SDimitry Andric   if (0 != (Val & bitc::ApproxFunc))
13420b57cec5SDimitry Andric     FMF.setApproxFunc();
13430b57cec5SDimitry Andric   return FMF;
13440b57cec5SDimitry Andric }
13450b57cec5SDimitry Andric 
upgradeDLLImportExportLinkage(GlobalValue * GV,unsigned Val)13460b57cec5SDimitry Andric static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) {
1347bdd1243dSDimitry Andric   // A GlobalValue with local linkage cannot have a DLL storage class.
1348bdd1243dSDimitry Andric   if (GV->hasLocalLinkage())
1349bdd1243dSDimitry Andric     return;
13500b57cec5SDimitry Andric   switch (Val) {
13510b57cec5SDimitry Andric   case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
13520b57cec5SDimitry Andric   case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
13530b57cec5SDimitry Andric   }
13540b57cec5SDimitry Andric }
13550b57cec5SDimitry Andric 
getTypeByID(unsigned ID)1356fe6060f1SDimitry Andric Type *BitcodeReader::getTypeByID(unsigned ID) {
13570b57cec5SDimitry Andric   // The type table size is always specified correctly.
13580b57cec5SDimitry Andric   if (ID >= TypeList.size())
13590b57cec5SDimitry Andric     return nullptr;
13600b57cec5SDimitry Andric 
13610b57cec5SDimitry Andric   if (Type *Ty = TypeList[ID])
13620b57cec5SDimitry Andric     return Ty;
13630b57cec5SDimitry Andric 
13640b57cec5SDimitry Andric   // If we have a forward reference, the only possible case is when it is to a
13650b57cec5SDimitry Andric   // named struct.  Just create a placeholder for now.
13660b57cec5SDimitry Andric   return TypeList[ID] = createIdentifiedStructType(Context);
13670b57cec5SDimitry Andric }
13680b57cec5SDimitry Andric 
getContainedTypeID(unsigned ID,unsigned Idx)136981ad6265SDimitry Andric unsigned BitcodeReader::getContainedTypeID(unsigned ID, unsigned Idx) {
137081ad6265SDimitry Andric   auto It = ContainedTypeIDs.find(ID);
137181ad6265SDimitry Andric   if (It == ContainedTypeIDs.end())
137281ad6265SDimitry Andric     return InvalidTypeID;
137381ad6265SDimitry Andric 
137481ad6265SDimitry Andric   if (Idx >= It->second.size())
137581ad6265SDimitry Andric     return InvalidTypeID;
137681ad6265SDimitry Andric 
137781ad6265SDimitry Andric   return It->second[Idx];
137881ad6265SDimitry Andric }
137981ad6265SDimitry Andric 
getPtrElementTypeByID(unsigned ID)138081ad6265SDimitry Andric Type *BitcodeReader::getPtrElementTypeByID(unsigned ID) {
138181ad6265SDimitry Andric   if (ID >= TypeList.size())
138281ad6265SDimitry Andric     return nullptr;
138381ad6265SDimitry Andric 
138481ad6265SDimitry Andric   Type *Ty = TypeList[ID];
138581ad6265SDimitry Andric   if (!Ty->isPointerTy())
138681ad6265SDimitry Andric     return nullptr;
138781ad6265SDimitry Andric 
1388fe013be4SDimitry Andric   return getTypeByID(getContainedTypeID(ID, 0));
138981ad6265SDimitry Andric }
139081ad6265SDimitry Andric 
getVirtualTypeID(Type * Ty,ArrayRef<unsigned> ChildTypeIDs)139181ad6265SDimitry Andric unsigned BitcodeReader::getVirtualTypeID(Type *Ty,
139281ad6265SDimitry Andric                                          ArrayRef<unsigned> ChildTypeIDs) {
139381ad6265SDimitry Andric   unsigned ChildTypeID = ChildTypeIDs.empty() ? InvalidTypeID : ChildTypeIDs[0];
139481ad6265SDimitry Andric   auto CacheKey = std::make_pair(Ty, ChildTypeID);
139581ad6265SDimitry Andric   auto It = VirtualTypeIDs.find(CacheKey);
139681ad6265SDimitry Andric   if (It != VirtualTypeIDs.end()) {
139781ad6265SDimitry Andric     // The cmpxchg return value is the only place we need more than one
139881ad6265SDimitry Andric     // contained type ID, however the second one will always be the same (i1),
139981ad6265SDimitry Andric     // so we don't need to include it in the cache key. This asserts that the
140081ad6265SDimitry Andric     // contained types are indeed as expected and there are no collisions.
140181ad6265SDimitry Andric     assert((ChildTypeIDs.empty() ||
140281ad6265SDimitry Andric             ContainedTypeIDs[It->second] == ChildTypeIDs) &&
140381ad6265SDimitry Andric            "Incorrect cached contained type IDs");
140481ad6265SDimitry Andric     return It->second;
140581ad6265SDimitry Andric   }
140681ad6265SDimitry Andric 
140781ad6265SDimitry Andric   unsigned TypeID = TypeList.size();
140881ad6265SDimitry Andric   TypeList.push_back(Ty);
140981ad6265SDimitry Andric   if (!ChildTypeIDs.empty())
141081ad6265SDimitry Andric     append_range(ContainedTypeIDs[TypeID], ChildTypeIDs);
141181ad6265SDimitry Andric   VirtualTypeIDs.insert({CacheKey, TypeID});
141281ad6265SDimitry Andric   return TypeID;
141381ad6265SDimitry Andric }
141481ad6265SDimitry Andric 
isConstExprSupported(const BitcodeConstant * BC)1415fe013be4SDimitry Andric static bool isConstExprSupported(const BitcodeConstant *BC) {
1416fe013be4SDimitry Andric   uint8_t Opcode = BC->Opcode;
1417fe013be4SDimitry Andric 
141881ad6265SDimitry Andric   // These are not real constant expressions, always consider them supported.
141981ad6265SDimitry Andric   if (Opcode >= BitcodeConstant::FirstSpecialOpcode)
142081ad6265SDimitry Andric     return true;
142181ad6265SDimitry Andric 
1422bdd1243dSDimitry Andric   // If -expand-constant-exprs is set, we want to consider all expressions
1423bdd1243dSDimitry Andric   // as unsupported.
1424bdd1243dSDimitry Andric   if (ExpandConstantExprs)
1425bdd1243dSDimitry Andric     return false;
1426bdd1243dSDimitry Andric 
1427753f127fSDimitry Andric   if (Instruction::isBinaryOp(Opcode))
1428753f127fSDimitry Andric     return ConstantExpr::isSupportedBinOp(Opcode);
1429753f127fSDimitry Andric 
1430c9157d92SDimitry Andric   if (Instruction::isCast(Opcode))
1431c9157d92SDimitry Andric     return ConstantExpr::isSupportedCastOp(Opcode);
1432c9157d92SDimitry Andric 
1433fe013be4SDimitry Andric   if (Opcode == Instruction::GetElementPtr)
1434fe013be4SDimitry Andric     return ConstantExpr::isSupportedGetElementPtr(BC->SrcElemTy);
1435fe013be4SDimitry Andric 
1436fe013be4SDimitry Andric   switch (Opcode) {
1437fe013be4SDimitry Andric   case Instruction::FNeg:
1438fe013be4SDimitry Andric   case Instruction::Select:
1439fe013be4SDimitry Andric     return false;
1440fe013be4SDimitry Andric   default:
1441fe013be4SDimitry Andric     return true;
1442fe013be4SDimitry Andric   }
144381ad6265SDimitry Andric }
144481ad6265SDimitry Andric 
materializeValue(unsigned StartValID,BasicBlock * InsertBB)144581ad6265SDimitry Andric Expected<Value *> BitcodeReader::materializeValue(unsigned StartValID,
144681ad6265SDimitry Andric                                                   BasicBlock *InsertBB) {
144781ad6265SDimitry Andric   // Quickly handle the case where there is no BitcodeConstant to resolve.
144881ad6265SDimitry Andric   if (StartValID < ValueList.size() && ValueList[StartValID] &&
144981ad6265SDimitry Andric       !isa<BitcodeConstant>(ValueList[StartValID]))
145081ad6265SDimitry Andric     return ValueList[StartValID];
145181ad6265SDimitry Andric 
145281ad6265SDimitry Andric   SmallDenseMap<unsigned, Value *> MaterializedValues;
145381ad6265SDimitry Andric   SmallVector<unsigned> Worklist;
145481ad6265SDimitry Andric   Worklist.push_back(StartValID);
145581ad6265SDimitry Andric   while (!Worklist.empty()) {
145681ad6265SDimitry Andric     unsigned ValID = Worklist.back();
145781ad6265SDimitry Andric     if (MaterializedValues.count(ValID)) {
145881ad6265SDimitry Andric       // Duplicate expression that was already handled.
145981ad6265SDimitry Andric       Worklist.pop_back();
146081ad6265SDimitry Andric       continue;
146181ad6265SDimitry Andric     }
146281ad6265SDimitry Andric 
146381ad6265SDimitry Andric     if (ValID >= ValueList.size() || !ValueList[ValID])
146481ad6265SDimitry Andric       return error("Invalid value ID");
146581ad6265SDimitry Andric 
146681ad6265SDimitry Andric     Value *V = ValueList[ValID];
146781ad6265SDimitry Andric     auto *BC = dyn_cast<BitcodeConstant>(V);
146881ad6265SDimitry Andric     if (!BC) {
146981ad6265SDimitry Andric       MaterializedValues.insert({ValID, V});
147081ad6265SDimitry Andric       Worklist.pop_back();
147181ad6265SDimitry Andric       continue;
147281ad6265SDimitry Andric     }
147381ad6265SDimitry Andric 
147481ad6265SDimitry Andric     // Iterate in reverse, so values will get popped from the worklist in
147581ad6265SDimitry Andric     // expected order.
147681ad6265SDimitry Andric     SmallVector<Value *> Ops;
147781ad6265SDimitry Andric     for (unsigned OpID : reverse(BC->getOperandIDs())) {
147881ad6265SDimitry Andric       auto It = MaterializedValues.find(OpID);
147981ad6265SDimitry Andric       if (It != MaterializedValues.end())
148081ad6265SDimitry Andric         Ops.push_back(It->second);
148181ad6265SDimitry Andric       else
148281ad6265SDimitry Andric         Worklist.push_back(OpID);
148381ad6265SDimitry Andric     }
148481ad6265SDimitry Andric 
148581ad6265SDimitry Andric     // Some expressions have not been resolved yet, handle them first and then
148681ad6265SDimitry Andric     // revisit this one.
148781ad6265SDimitry Andric     if (Ops.size() != BC->getOperandIDs().size())
148881ad6265SDimitry Andric       continue;
148981ad6265SDimitry Andric     std::reverse(Ops.begin(), Ops.end());
149081ad6265SDimitry Andric 
149181ad6265SDimitry Andric     SmallVector<Constant *> ConstOps;
149281ad6265SDimitry Andric     for (Value *Op : Ops)
149381ad6265SDimitry Andric       if (auto *C = dyn_cast<Constant>(Op))
149481ad6265SDimitry Andric         ConstOps.push_back(C);
149581ad6265SDimitry Andric 
149681ad6265SDimitry Andric     // Materialize as constant expression if possible.
1497fe013be4SDimitry Andric     if (isConstExprSupported(BC) && ConstOps.size() == Ops.size()) {
149881ad6265SDimitry Andric       Constant *C;
149981ad6265SDimitry Andric       if (Instruction::isCast(BC->Opcode)) {
150081ad6265SDimitry Andric         C = UpgradeBitCastExpr(BC->Opcode, ConstOps[0], BC->getType());
150181ad6265SDimitry Andric         if (!C)
150281ad6265SDimitry Andric           C = ConstantExpr::getCast(BC->Opcode, ConstOps[0], BC->getType());
150381ad6265SDimitry Andric       } else if (Instruction::isBinaryOp(BC->Opcode)) {
150481ad6265SDimitry Andric         C = ConstantExpr::get(BC->Opcode, ConstOps[0], ConstOps[1], BC->Flags);
150581ad6265SDimitry Andric       } else {
150681ad6265SDimitry Andric         switch (BC->Opcode) {
150781ad6265SDimitry Andric         case BitcodeConstant::NoCFIOpcode: {
150881ad6265SDimitry Andric           auto *GV = dyn_cast<GlobalValue>(ConstOps[0]);
150981ad6265SDimitry Andric           if (!GV)
151081ad6265SDimitry Andric             return error("no_cfi operand must be GlobalValue");
151181ad6265SDimitry Andric           C = NoCFIValue::get(GV);
151281ad6265SDimitry Andric           break;
151381ad6265SDimitry Andric         }
151481ad6265SDimitry Andric         case BitcodeConstant::DSOLocalEquivalentOpcode: {
151581ad6265SDimitry Andric           auto *GV = dyn_cast<GlobalValue>(ConstOps[0]);
151681ad6265SDimitry Andric           if (!GV)
151781ad6265SDimitry Andric             return error("dso_local operand must be GlobalValue");
151881ad6265SDimitry Andric           C = DSOLocalEquivalent::get(GV);
151981ad6265SDimitry Andric           break;
152081ad6265SDimitry Andric         }
152181ad6265SDimitry Andric         case BitcodeConstant::BlockAddressOpcode: {
152281ad6265SDimitry Andric           Function *Fn = dyn_cast<Function>(ConstOps[0]);
152381ad6265SDimitry Andric           if (!Fn)
152481ad6265SDimitry Andric             return error("blockaddress operand must be a function");
152581ad6265SDimitry Andric 
152681ad6265SDimitry Andric           // If the function is already parsed we can insert the block address
152781ad6265SDimitry Andric           // right away.
152881ad6265SDimitry Andric           BasicBlock *BB;
152981ad6265SDimitry Andric           unsigned BBID = BC->Extra;
153081ad6265SDimitry Andric           if (!BBID)
153181ad6265SDimitry Andric             // Invalid reference to entry block.
153281ad6265SDimitry Andric             return error("Invalid ID");
153381ad6265SDimitry Andric           if (!Fn->empty()) {
153481ad6265SDimitry Andric             Function::iterator BBI = Fn->begin(), BBE = Fn->end();
153581ad6265SDimitry Andric             for (size_t I = 0, E = BBID; I != E; ++I) {
153681ad6265SDimitry Andric               if (BBI == BBE)
153781ad6265SDimitry Andric                 return error("Invalid ID");
153881ad6265SDimitry Andric               ++BBI;
153981ad6265SDimitry Andric             }
154081ad6265SDimitry Andric             BB = &*BBI;
154181ad6265SDimitry Andric           } else {
154281ad6265SDimitry Andric             // Otherwise insert a placeholder and remember it so it can be
154381ad6265SDimitry Andric             // inserted when the function is parsed.
154481ad6265SDimitry Andric             auto &FwdBBs = BasicBlockFwdRefs[Fn];
154581ad6265SDimitry Andric             if (FwdBBs.empty())
154681ad6265SDimitry Andric               BasicBlockFwdRefQueue.push_back(Fn);
154781ad6265SDimitry Andric             if (FwdBBs.size() < BBID + 1)
154881ad6265SDimitry Andric               FwdBBs.resize(BBID + 1);
154981ad6265SDimitry Andric             if (!FwdBBs[BBID])
155081ad6265SDimitry Andric               FwdBBs[BBID] = BasicBlock::Create(Context);
155181ad6265SDimitry Andric             BB = FwdBBs[BBID];
155281ad6265SDimitry Andric           }
155381ad6265SDimitry Andric           C = BlockAddress::get(Fn, BB);
155481ad6265SDimitry Andric           break;
155581ad6265SDimitry Andric         }
155681ad6265SDimitry Andric         case BitcodeConstant::ConstantStructOpcode:
155781ad6265SDimitry Andric           C = ConstantStruct::get(cast<StructType>(BC->getType()), ConstOps);
155881ad6265SDimitry Andric           break;
155981ad6265SDimitry Andric         case BitcodeConstant::ConstantArrayOpcode:
156081ad6265SDimitry Andric           C = ConstantArray::get(cast<ArrayType>(BC->getType()), ConstOps);
156181ad6265SDimitry Andric           break;
156281ad6265SDimitry Andric         case BitcodeConstant::ConstantVectorOpcode:
156381ad6265SDimitry Andric           C = ConstantVector::get(ConstOps);
156481ad6265SDimitry Andric           break;
156581ad6265SDimitry Andric         case Instruction::ICmp:
156681ad6265SDimitry Andric         case Instruction::FCmp:
156781ad6265SDimitry Andric           C = ConstantExpr::getCompare(BC->Flags, ConstOps[0], ConstOps[1]);
156881ad6265SDimitry Andric           break;
156981ad6265SDimitry Andric         case Instruction::GetElementPtr:
1570bdd1243dSDimitry Andric           C = ConstantExpr::getGetElementPtr(BC->SrcElemTy, ConstOps[0],
1571bdd1243dSDimitry Andric                                              ArrayRef(ConstOps).drop_front(),
157281ad6265SDimitry Andric                                              BC->Flags, BC->getInRangeIndex());
157381ad6265SDimitry Andric           break;
157481ad6265SDimitry Andric         case Instruction::ExtractElement:
157581ad6265SDimitry Andric           C = ConstantExpr::getExtractElement(ConstOps[0], ConstOps[1]);
157681ad6265SDimitry Andric           break;
157781ad6265SDimitry Andric         case Instruction::InsertElement:
157881ad6265SDimitry Andric           C = ConstantExpr::getInsertElement(ConstOps[0], ConstOps[1],
157981ad6265SDimitry Andric                                              ConstOps[2]);
158081ad6265SDimitry Andric           break;
158181ad6265SDimitry Andric         case Instruction::ShuffleVector: {
158281ad6265SDimitry Andric           SmallVector<int, 16> Mask;
158381ad6265SDimitry Andric           ShuffleVectorInst::getShuffleMask(ConstOps[2], Mask);
158481ad6265SDimitry Andric           C = ConstantExpr::getShuffleVector(ConstOps[0], ConstOps[1], Mask);
158581ad6265SDimitry Andric           break;
158681ad6265SDimitry Andric         }
158781ad6265SDimitry Andric         default:
158881ad6265SDimitry Andric           llvm_unreachable("Unhandled bitcode constant");
158981ad6265SDimitry Andric         }
159081ad6265SDimitry Andric       }
159181ad6265SDimitry Andric 
159281ad6265SDimitry Andric       // Cache resolved constant.
159381ad6265SDimitry Andric       ValueList.replaceValueWithoutRAUW(ValID, C);
159481ad6265SDimitry Andric       MaterializedValues.insert({ValID, C});
159581ad6265SDimitry Andric       Worklist.pop_back();
159681ad6265SDimitry Andric       continue;
159781ad6265SDimitry Andric     }
159881ad6265SDimitry Andric 
159981ad6265SDimitry Andric     if (!InsertBB)
160081ad6265SDimitry Andric       return error(Twine("Value referenced by initializer is an unsupported "
160181ad6265SDimitry Andric                          "constant expression of type ") +
160281ad6265SDimitry Andric                    BC->getOpcodeName());
160381ad6265SDimitry Andric 
160481ad6265SDimitry Andric     // Materialize as instructions if necessary.
160581ad6265SDimitry Andric     Instruction *I;
160681ad6265SDimitry Andric     if (Instruction::isCast(BC->Opcode)) {
160781ad6265SDimitry Andric       I = CastInst::Create((Instruction::CastOps)BC->Opcode, Ops[0],
160881ad6265SDimitry Andric                            BC->getType(), "constexpr", InsertBB);
160981ad6265SDimitry Andric     } else if (Instruction::isUnaryOp(BC->Opcode)) {
161081ad6265SDimitry Andric       I = UnaryOperator::Create((Instruction::UnaryOps)BC->Opcode, Ops[0],
161181ad6265SDimitry Andric                                 "constexpr", InsertBB);
161281ad6265SDimitry Andric     } else if (Instruction::isBinaryOp(BC->Opcode)) {
161381ad6265SDimitry Andric       I = BinaryOperator::Create((Instruction::BinaryOps)BC->Opcode, Ops[0],
161481ad6265SDimitry Andric                                  Ops[1], "constexpr", InsertBB);
161581ad6265SDimitry Andric       if (isa<OverflowingBinaryOperator>(I)) {
161681ad6265SDimitry Andric         if (BC->Flags & OverflowingBinaryOperator::NoSignedWrap)
161781ad6265SDimitry Andric           I->setHasNoSignedWrap();
161881ad6265SDimitry Andric         if (BC->Flags & OverflowingBinaryOperator::NoUnsignedWrap)
161981ad6265SDimitry Andric           I->setHasNoUnsignedWrap();
162081ad6265SDimitry Andric       }
162181ad6265SDimitry Andric       if (isa<PossiblyExactOperator>(I) &&
162281ad6265SDimitry Andric           (BC->Flags & PossiblyExactOperator::IsExact))
162381ad6265SDimitry Andric         I->setIsExact();
162481ad6265SDimitry Andric     } else {
162581ad6265SDimitry Andric       switch (BC->Opcode) {
162681ad6265SDimitry Andric       case BitcodeConstant::ConstantVectorOpcode: {
162781ad6265SDimitry Andric         Type *IdxTy = Type::getInt32Ty(BC->getContext());
162881ad6265SDimitry Andric         Value *V = PoisonValue::get(BC->getType());
162981ad6265SDimitry Andric         for (auto Pair : enumerate(Ops)) {
163081ad6265SDimitry Andric           Value *Idx = ConstantInt::get(IdxTy, Pair.index());
163181ad6265SDimitry Andric           V = InsertElementInst::Create(V, Pair.value(), Idx, "constexpr.ins",
163281ad6265SDimitry Andric                                         InsertBB);
163381ad6265SDimitry Andric         }
163481ad6265SDimitry Andric         I = cast<Instruction>(V);
163581ad6265SDimitry Andric         break;
163681ad6265SDimitry Andric       }
1637bdd1243dSDimitry Andric       case BitcodeConstant::ConstantStructOpcode:
1638bdd1243dSDimitry Andric       case BitcodeConstant::ConstantArrayOpcode: {
1639bdd1243dSDimitry Andric         Value *V = PoisonValue::get(BC->getType());
1640bdd1243dSDimitry Andric         for (auto Pair : enumerate(Ops))
1641bdd1243dSDimitry Andric           V = InsertValueInst::Create(V, Pair.value(), Pair.index(),
1642bdd1243dSDimitry Andric                                       "constexpr.ins", InsertBB);
1643bdd1243dSDimitry Andric         I = cast<Instruction>(V);
1644bdd1243dSDimitry Andric         break;
1645bdd1243dSDimitry Andric       }
164681ad6265SDimitry Andric       case Instruction::ICmp:
164781ad6265SDimitry Andric       case Instruction::FCmp:
164881ad6265SDimitry Andric         I = CmpInst::Create((Instruction::OtherOps)BC->Opcode,
164981ad6265SDimitry Andric                             (CmpInst::Predicate)BC->Flags, Ops[0], Ops[1],
165081ad6265SDimitry Andric                             "constexpr", InsertBB);
165181ad6265SDimitry Andric         break;
165281ad6265SDimitry Andric       case Instruction::GetElementPtr:
165381ad6265SDimitry Andric         I = GetElementPtrInst::Create(BC->SrcElemTy, Ops[0],
1654bdd1243dSDimitry Andric                                       ArrayRef(Ops).drop_front(), "constexpr",
1655bdd1243dSDimitry Andric                                       InsertBB);
165681ad6265SDimitry Andric         if (BC->Flags)
165781ad6265SDimitry Andric           cast<GetElementPtrInst>(I)->setIsInBounds();
165881ad6265SDimitry Andric         break;
165981ad6265SDimitry Andric       case Instruction::Select:
166081ad6265SDimitry Andric         I = SelectInst::Create(Ops[0], Ops[1], Ops[2], "constexpr", InsertBB);
166181ad6265SDimitry Andric         break;
166281ad6265SDimitry Andric       case Instruction::ExtractElement:
166381ad6265SDimitry Andric         I = ExtractElementInst::Create(Ops[0], Ops[1], "constexpr", InsertBB);
166481ad6265SDimitry Andric         break;
166581ad6265SDimitry Andric       case Instruction::InsertElement:
166681ad6265SDimitry Andric         I = InsertElementInst::Create(Ops[0], Ops[1], Ops[2], "constexpr",
166781ad6265SDimitry Andric                                       InsertBB);
166881ad6265SDimitry Andric         break;
166981ad6265SDimitry Andric       case Instruction::ShuffleVector:
167081ad6265SDimitry Andric         I = new ShuffleVectorInst(Ops[0], Ops[1], Ops[2], "constexpr",
167181ad6265SDimitry Andric                                   InsertBB);
167281ad6265SDimitry Andric         break;
167381ad6265SDimitry Andric       default:
167481ad6265SDimitry Andric         llvm_unreachable("Unhandled bitcode constant");
167581ad6265SDimitry Andric       }
167681ad6265SDimitry Andric     }
167781ad6265SDimitry Andric 
167881ad6265SDimitry Andric     MaterializedValues.insert({ValID, I});
167981ad6265SDimitry Andric     Worklist.pop_back();
168081ad6265SDimitry Andric   }
168181ad6265SDimitry Andric 
168281ad6265SDimitry Andric   return MaterializedValues[StartValID];
168381ad6265SDimitry Andric }
168481ad6265SDimitry Andric 
getValueForInitializer(unsigned ID)168581ad6265SDimitry Andric Expected<Constant *> BitcodeReader::getValueForInitializer(unsigned ID) {
168681ad6265SDimitry Andric   Expected<Value *> MaybeV = materializeValue(ID, /* InsertBB */ nullptr);
168781ad6265SDimitry Andric   if (!MaybeV)
168881ad6265SDimitry Andric     return MaybeV.takeError();
168981ad6265SDimitry Andric 
169081ad6265SDimitry Andric   // Result must be Constant if InsertBB is nullptr.
169181ad6265SDimitry Andric   return cast<Constant>(MaybeV.get());
169281ad6265SDimitry Andric }
169381ad6265SDimitry Andric 
createIdentifiedStructType(LLVMContext & Context,StringRef Name)16940b57cec5SDimitry Andric StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
16950b57cec5SDimitry Andric                                                       StringRef Name) {
16960b57cec5SDimitry Andric   auto *Ret = StructType::create(Context, Name);
16970b57cec5SDimitry Andric   IdentifiedStructTypes.push_back(Ret);
16980b57cec5SDimitry Andric   return Ret;
16990b57cec5SDimitry Andric }
17000b57cec5SDimitry Andric 
createIdentifiedStructType(LLVMContext & Context)17010b57cec5SDimitry Andric StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
17020b57cec5SDimitry Andric   auto *Ret = StructType::create(Context);
17030b57cec5SDimitry Andric   IdentifiedStructTypes.push_back(Ret);
17040b57cec5SDimitry Andric   return Ret;
17050b57cec5SDimitry Andric }
17060b57cec5SDimitry Andric 
17070b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
17080b57cec5SDimitry Andric //  Functions for parsing blocks from the bitcode file
17090b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
17100b57cec5SDimitry Andric 
getRawAttributeMask(Attribute::AttrKind Val)17110b57cec5SDimitry Andric static uint64_t getRawAttributeMask(Attribute::AttrKind Val) {
17120b57cec5SDimitry Andric   switch (Val) {
17130b57cec5SDimitry Andric   case Attribute::EndAttrKinds:
17145ffd83dbSDimitry Andric   case Attribute::EmptyKey:
17155ffd83dbSDimitry Andric   case Attribute::TombstoneKey:
17160b57cec5SDimitry Andric     llvm_unreachable("Synthetic enumerators which should never get here");
17170b57cec5SDimitry Andric 
17180b57cec5SDimitry Andric   case Attribute::None:            return 0;
17190b57cec5SDimitry Andric   case Attribute::ZExt:            return 1 << 0;
17200b57cec5SDimitry Andric   case Attribute::SExt:            return 1 << 1;
17210b57cec5SDimitry Andric   case Attribute::NoReturn:        return 1 << 2;
17220b57cec5SDimitry Andric   case Attribute::InReg:           return 1 << 3;
17230b57cec5SDimitry Andric   case Attribute::StructRet:       return 1 << 4;
17240b57cec5SDimitry Andric   case Attribute::NoUnwind:        return 1 << 5;
17250b57cec5SDimitry Andric   case Attribute::NoAlias:         return 1 << 6;
17260b57cec5SDimitry Andric   case Attribute::ByVal:           return 1 << 7;
17270b57cec5SDimitry Andric   case Attribute::Nest:            return 1 << 8;
17280b57cec5SDimitry Andric   case Attribute::ReadNone:        return 1 << 9;
17290b57cec5SDimitry Andric   case Attribute::ReadOnly:        return 1 << 10;
17300b57cec5SDimitry Andric   case Attribute::NoInline:        return 1 << 11;
17310b57cec5SDimitry Andric   case Attribute::AlwaysInline:    return 1 << 12;
17320b57cec5SDimitry Andric   case Attribute::OptimizeForSize: return 1 << 13;
17330b57cec5SDimitry Andric   case Attribute::StackProtect:    return 1 << 14;
17340b57cec5SDimitry Andric   case Attribute::StackProtectReq: return 1 << 15;
17350b57cec5SDimitry Andric   case Attribute::Alignment:       return 31 << 16;
17360b57cec5SDimitry Andric   case Attribute::NoCapture:       return 1 << 21;
17370b57cec5SDimitry Andric   case Attribute::NoRedZone:       return 1 << 22;
17380b57cec5SDimitry Andric   case Attribute::NoImplicitFloat: return 1 << 23;
17390b57cec5SDimitry Andric   case Attribute::Naked:           return 1 << 24;
17400b57cec5SDimitry Andric   case Attribute::InlineHint:      return 1 << 25;
17410b57cec5SDimitry Andric   case Attribute::StackAlignment:  return 7 << 26;
17420b57cec5SDimitry Andric   case Attribute::ReturnsTwice:    return 1 << 29;
17430b57cec5SDimitry Andric   case Attribute::UWTable:         return 1 << 30;
17440b57cec5SDimitry Andric   case Attribute::NonLazyBind:     return 1U << 31;
17450b57cec5SDimitry Andric   case Attribute::SanitizeAddress: return 1ULL << 32;
17460b57cec5SDimitry Andric   case Attribute::MinSize:         return 1ULL << 33;
17470b57cec5SDimitry Andric   case Attribute::NoDuplicate:     return 1ULL << 34;
17480b57cec5SDimitry Andric   case Attribute::StackProtectStrong: return 1ULL << 35;
17490b57cec5SDimitry Andric   case Attribute::SanitizeThread:  return 1ULL << 36;
17500b57cec5SDimitry Andric   case Attribute::SanitizeMemory:  return 1ULL << 37;
17510b57cec5SDimitry Andric   case Attribute::NoBuiltin:       return 1ULL << 38;
17520b57cec5SDimitry Andric   case Attribute::Returned:        return 1ULL << 39;
17530b57cec5SDimitry Andric   case Attribute::Cold:            return 1ULL << 40;
17540b57cec5SDimitry Andric   case Attribute::Builtin:         return 1ULL << 41;
17550b57cec5SDimitry Andric   case Attribute::OptimizeNone:    return 1ULL << 42;
17560b57cec5SDimitry Andric   case Attribute::InAlloca:        return 1ULL << 43;
17570b57cec5SDimitry Andric   case Attribute::NonNull:         return 1ULL << 44;
17580b57cec5SDimitry Andric   case Attribute::JumpTable:       return 1ULL << 45;
17590b57cec5SDimitry Andric   case Attribute::Convergent:      return 1ULL << 46;
17600b57cec5SDimitry Andric   case Attribute::SafeStack:       return 1ULL << 47;
17610b57cec5SDimitry Andric   case Attribute::NoRecurse:       return 1ULL << 48;
1762bdd1243dSDimitry Andric   // 1ULL << 49 is InaccessibleMemOnly, which is upgraded separately.
1763bdd1243dSDimitry Andric   // 1ULL << 50 is InaccessibleMemOrArgMemOnly, which is upgraded separately.
17640b57cec5SDimitry Andric   case Attribute::SwiftSelf:       return 1ULL << 51;
17650b57cec5SDimitry Andric   case Attribute::SwiftError:      return 1ULL << 52;
17660b57cec5SDimitry Andric   case Attribute::WriteOnly:       return 1ULL << 53;
17670b57cec5SDimitry Andric   case Attribute::Speculatable:    return 1ULL << 54;
17680b57cec5SDimitry Andric   case Attribute::StrictFP:        return 1ULL << 55;
17690b57cec5SDimitry Andric   case Attribute::SanitizeHWAddress: return 1ULL << 56;
17700b57cec5SDimitry Andric   case Attribute::NoCfCheck:       return 1ULL << 57;
17710b57cec5SDimitry Andric   case Attribute::OptForFuzzing:   return 1ULL << 58;
17720b57cec5SDimitry Andric   case Attribute::ShadowCallStack: return 1ULL << 59;
17730b57cec5SDimitry Andric   case Attribute::SpeculativeLoadHardening:
17740b57cec5SDimitry Andric     return 1ULL << 60;
17750b57cec5SDimitry Andric   case Attribute::ImmArg:
17760b57cec5SDimitry Andric     return 1ULL << 61;
17770b57cec5SDimitry Andric   case Attribute::WillReturn:
17780b57cec5SDimitry Andric     return 1ULL << 62;
17790b57cec5SDimitry Andric   case Attribute::NoFree:
17800b57cec5SDimitry Andric     return 1ULL << 63;
17815ffd83dbSDimitry Andric   default:
17825ffd83dbSDimitry Andric     // Other attributes are not supported in the raw format,
17835ffd83dbSDimitry Andric     // as we ran out of space.
17845ffd83dbSDimitry Andric     return 0;
17850b57cec5SDimitry Andric   }
17860b57cec5SDimitry Andric   llvm_unreachable("Unsupported attribute type");
17870b57cec5SDimitry Andric }
17880b57cec5SDimitry Andric 
addRawAttributeValue(AttrBuilder & B,uint64_t Val)17890b57cec5SDimitry Andric static void addRawAttributeValue(AttrBuilder &B, uint64_t Val) {
17900b57cec5SDimitry Andric   if (!Val) return;
17910b57cec5SDimitry Andric 
17920b57cec5SDimitry Andric   for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
17930b57cec5SDimitry Andric        I = Attribute::AttrKind(I + 1)) {
17940b57cec5SDimitry Andric     if (uint64_t A = (Val & getRawAttributeMask(I))) {
17950b57cec5SDimitry Andric       if (I == Attribute::Alignment)
17960b57cec5SDimitry Andric         B.addAlignmentAttr(1ULL << ((A >> 16) - 1));
17970b57cec5SDimitry Andric       else if (I == Attribute::StackAlignment)
17980b57cec5SDimitry Andric         B.addStackAlignmentAttr(1ULL << ((A >> 26)-1));
1799fe6060f1SDimitry Andric       else if (Attribute::isTypeAttrKind(I))
1800fe6060f1SDimitry Andric         B.addTypeAttr(I, nullptr); // Type will be auto-upgraded.
18010b57cec5SDimitry Andric       else
18020b57cec5SDimitry Andric         B.addAttribute(I);
18030b57cec5SDimitry Andric     }
18040b57cec5SDimitry Andric   }
18050b57cec5SDimitry Andric }
18060b57cec5SDimitry Andric 
18070b57cec5SDimitry Andric /// This fills an AttrBuilder object with the LLVM attributes that have
18080b57cec5SDimitry Andric /// been decoded from the given integer. This function must stay in sync with
18090b57cec5SDimitry Andric /// 'encodeLLVMAttributesForBitcode'.
decodeLLVMAttributesForBitcode(AttrBuilder & B,uint64_t EncodedAttrs,uint64_t AttrIdx)18100b57cec5SDimitry Andric static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1811bdd1243dSDimitry Andric                                            uint64_t EncodedAttrs,
1812bdd1243dSDimitry Andric                                            uint64_t AttrIdx) {
18130b57cec5SDimitry Andric   // The alignment is stored as a 16-bit raw value from bits 31--16.  We shift
18140b57cec5SDimitry Andric   // the bits above 31 down by 11 bits.
18150b57cec5SDimitry Andric   unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
18160b57cec5SDimitry Andric   assert((!Alignment || isPowerOf2_32(Alignment)) &&
18170b57cec5SDimitry Andric          "Alignment must be a power of two.");
18180b57cec5SDimitry Andric 
18190b57cec5SDimitry Andric   if (Alignment)
18200b57cec5SDimitry Andric     B.addAlignmentAttr(Alignment);
1821bdd1243dSDimitry Andric 
1822bdd1243dSDimitry Andric   uint64_t Attrs = ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1823bdd1243dSDimitry Andric                    (EncodedAttrs & 0xffff);
1824bdd1243dSDimitry Andric 
1825bdd1243dSDimitry Andric   if (AttrIdx == AttributeList::FunctionIndex) {
1826bdd1243dSDimitry Andric     // Upgrade old memory attributes.
1827bdd1243dSDimitry Andric     MemoryEffects ME = MemoryEffects::unknown();
1828bdd1243dSDimitry Andric     if (Attrs & (1ULL << 9)) {
1829bdd1243dSDimitry Andric       // ReadNone
1830bdd1243dSDimitry Andric       Attrs &= ~(1ULL << 9);
1831bdd1243dSDimitry Andric       ME &= MemoryEffects::none();
1832bdd1243dSDimitry Andric     }
1833bdd1243dSDimitry Andric     if (Attrs & (1ULL << 10)) {
1834bdd1243dSDimitry Andric       // ReadOnly
1835bdd1243dSDimitry Andric       Attrs &= ~(1ULL << 10);
1836bdd1243dSDimitry Andric       ME &= MemoryEffects::readOnly();
1837bdd1243dSDimitry Andric     }
1838bdd1243dSDimitry Andric     if (Attrs & (1ULL << 49)) {
1839bdd1243dSDimitry Andric       // InaccessibleMemOnly
1840bdd1243dSDimitry Andric       Attrs &= ~(1ULL << 49);
1841bdd1243dSDimitry Andric       ME &= MemoryEffects::inaccessibleMemOnly();
1842bdd1243dSDimitry Andric     }
1843bdd1243dSDimitry Andric     if (Attrs & (1ULL << 50)) {
1844bdd1243dSDimitry Andric       // InaccessibleMemOrArgMemOnly
1845bdd1243dSDimitry Andric       Attrs &= ~(1ULL << 50);
1846bdd1243dSDimitry Andric       ME &= MemoryEffects::inaccessibleOrArgMemOnly();
1847bdd1243dSDimitry Andric     }
1848bdd1243dSDimitry Andric     if (Attrs & (1ULL << 53)) {
1849bdd1243dSDimitry Andric       // WriteOnly
1850bdd1243dSDimitry Andric       Attrs &= ~(1ULL << 53);
1851bdd1243dSDimitry Andric       ME &= MemoryEffects::writeOnly();
1852bdd1243dSDimitry Andric     }
1853bdd1243dSDimitry Andric     if (ME != MemoryEffects::unknown())
1854bdd1243dSDimitry Andric       B.addMemoryAttr(ME);
1855bdd1243dSDimitry Andric   }
1856bdd1243dSDimitry Andric 
1857bdd1243dSDimitry Andric   addRawAttributeValue(B, Attrs);
18580b57cec5SDimitry Andric }
18590b57cec5SDimitry Andric 
parseAttributeBlock()18600b57cec5SDimitry Andric Error BitcodeReader::parseAttributeBlock() {
18610b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
18620b57cec5SDimitry Andric     return Err;
18630b57cec5SDimitry Andric 
18640b57cec5SDimitry Andric   if (!MAttributes.empty())
18650b57cec5SDimitry Andric     return error("Invalid multiple blocks");
18660b57cec5SDimitry Andric 
18670b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
18680b57cec5SDimitry Andric 
18690b57cec5SDimitry Andric   SmallVector<AttributeList, 8> Attrs;
18700b57cec5SDimitry Andric 
18710b57cec5SDimitry Andric   // Read all the records.
18720b57cec5SDimitry Andric   while (true) {
18730b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
18740b57cec5SDimitry Andric     if (!MaybeEntry)
18750b57cec5SDimitry Andric       return MaybeEntry.takeError();
18760b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
18770b57cec5SDimitry Andric 
18780b57cec5SDimitry Andric     switch (Entry.Kind) {
18790b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
18800b57cec5SDimitry Andric     case BitstreamEntry::Error:
18810b57cec5SDimitry Andric       return error("Malformed block");
18820b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
18830b57cec5SDimitry Andric       return Error::success();
18840b57cec5SDimitry Andric     case BitstreamEntry::Record:
18850b57cec5SDimitry Andric       // The interesting case.
18860b57cec5SDimitry Andric       break;
18870b57cec5SDimitry Andric     }
18880b57cec5SDimitry Andric 
18890b57cec5SDimitry Andric     // Read a record.
18900b57cec5SDimitry Andric     Record.clear();
18910b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
18920b57cec5SDimitry Andric     if (!MaybeRecord)
18930b57cec5SDimitry Andric       return MaybeRecord.takeError();
18940b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
18950b57cec5SDimitry Andric     default:  // Default behavior: ignore.
18960b57cec5SDimitry Andric       break;
18970b57cec5SDimitry Andric     case bitc::PARAMATTR_CODE_ENTRY_OLD: // ENTRY: [paramidx0, attr0, ...]
18985ffd83dbSDimitry Andric       // Deprecated, but still needed to read old bitcode files.
18990b57cec5SDimitry Andric       if (Record.size() & 1)
190081ad6265SDimitry Andric         return error("Invalid parameter attribute record");
19010b57cec5SDimitry Andric 
19020b57cec5SDimitry Andric       for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
190304eeddc0SDimitry Andric         AttrBuilder B(Context);
1904bdd1243dSDimitry Andric         decodeLLVMAttributesForBitcode(B, Record[i+1], Record[i]);
19050b57cec5SDimitry Andric         Attrs.push_back(AttributeList::get(Context, Record[i], B));
19060b57cec5SDimitry Andric       }
19070b57cec5SDimitry Andric 
19080b57cec5SDimitry Andric       MAttributes.push_back(AttributeList::get(Context, Attrs));
19090b57cec5SDimitry Andric       Attrs.clear();
19100b57cec5SDimitry Andric       break;
19110b57cec5SDimitry Andric     case bitc::PARAMATTR_CODE_ENTRY: // ENTRY: [attrgrp0, attrgrp1, ...]
19120b57cec5SDimitry Andric       for (unsigned i = 0, e = Record.size(); i != e; ++i)
19130b57cec5SDimitry Andric         Attrs.push_back(MAttributeGroups[Record[i]]);
19140b57cec5SDimitry Andric 
19150b57cec5SDimitry Andric       MAttributes.push_back(AttributeList::get(Context, Attrs));
19160b57cec5SDimitry Andric       Attrs.clear();
19170b57cec5SDimitry Andric       break;
19180b57cec5SDimitry Andric     }
19190b57cec5SDimitry Andric   }
19200b57cec5SDimitry Andric }
19210b57cec5SDimitry Andric 
19220b57cec5SDimitry Andric // Returns Attribute::None on unrecognized codes.
getAttrFromCode(uint64_t Code)19230b57cec5SDimitry Andric static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
19240b57cec5SDimitry Andric   switch (Code) {
19250b57cec5SDimitry Andric   default:
19260b57cec5SDimitry Andric     return Attribute::None;
19270b57cec5SDimitry Andric   case bitc::ATTR_KIND_ALIGNMENT:
19280b57cec5SDimitry Andric     return Attribute::Alignment;
19290b57cec5SDimitry Andric   case bitc::ATTR_KIND_ALWAYS_INLINE:
19300b57cec5SDimitry Andric     return Attribute::AlwaysInline;
19310b57cec5SDimitry Andric   case bitc::ATTR_KIND_BUILTIN:
19320b57cec5SDimitry Andric     return Attribute::Builtin;
19330b57cec5SDimitry Andric   case bitc::ATTR_KIND_BY_VAL:
19340b57cec5SDimitry Andric     return Attribute::ByVal;
19350b57cec5SDimitry Andric   case bitc::ATTR_KIND_IN_ALLOCA:
19360b57cec5SDimitry Andric     return Attribute::InAlloca;
19370b57cec5SDimitry Andric   case bitc::ATTR_KIND_COLD:
19380b57cec5SDimitry Andric     return Attribute::Cold;
19390b57cec5SDimitry Andric   case bitc::ATTR_KIND_CONVERGENT:
19400b57cec5SDimitry Andric     return Attribute::Convergent;
1941349cc55cSDimitry Andric   case bitc::ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION:
1942349cc55cSDimitry Andric     return Attribute::DisableSanitizerInstrumentation;
1943fe6060f1SDimitry Andric   case bitc::ATTR_KIND_ELEMENTTYPE:
1944fe6060f1SDimitry Andric     return Attribute::ElementType;
1945753f127fSDimitry Andric   case bitc::ATTR_KIND_FNRETTHUNK_EXTERN:
1946753f127fSDimitry Andric     return Attribute::FnRetThunkExtern;
19470b57cec5SDimitry Andric   case bitc::ATTR_KIND_INLINE_HINT:
19480b57cec5SDimitry Andric     return Attribute::InlineHint;
19490b57cec5SDimitry Andric   case bitc::ATTR_KIND_IN_REG:
19500b57cec5SDimitry Andric     return Attribute::InReg;
19510b57cec5SDimitry Andric   case bitc::ATTR_KIND_JUMP_TABLE:
19520b57cec5SDimitry Andric     return Attribute::JumpTable;
1953bdd1243dSDimitry Andric   case bitc::ATTR_KIND_MEMORY:
1954bdd1243dSDimitry Andric     return Attribute::Memory;
1955fe013be4SDimitry Andric   case bitc::ATTR_KIND_NOFPCLASS:
1956fe013be4SDimitry Andric     return Attribute::NoFPClass;
19570b57cec5SDimitry Andric   case bitc::ATTR_KIND_MIN_SIZE:
19580b57cec5SDimitry Andric     return Attribute::MinSize;
19590b57cec5SDimitry Andric   case bitc::ATTR_KIND_NAKED:
19600b57cec5SDimitry Andric     return Attribute::Naked;
19610b57cec5SDimitry Andric   case bitc::ATTR_KIND_NEST:
19620b57cec5SDimitry Andric     return Attribute::Nest;
19630b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_ALIAS:
19640b57cec5SDimitry Andric     return Attribute::NoAlias;
19650b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_BUILTIN:
19660b57cec5SDimitry Andric     return Attribute::NoBuiltin;
1967e8d8bef9SDimitry Andric   case bitc::ATTR_KIND_NO_CALLBACK:
1968e8d8bef9SDimitry Andric     return Attribute::NoCallback;
19690b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_CAPTURE:
19700b57cec5SDimitry Andric     return Attribute::NoCapture;
19710b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_DUPLICATE:
19720b57cec5SDimitry Andric     return Attribute::NoDuplicate;
19730b57cec5SDimitry Andric   case bitc::ATTR_KIND_NOFREE:
19740b57cec5SDimitry Andric     return Attribute::NoFree;
19750b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
19760b57cec5SDimitry Andric     return Attribute::NoImplicitFloat;
19770b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_INLINE:
19780b57cec5SDimitry Andric     return Attribute::NoInline;
19790b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_RECURSE:
19800b57cec5SDimitry Andric     return Attribute::NoRecurse;
19815ffd83dbSDimitry Andric   case bitc::ATTR_KIND_NO_MERGE:
19825ffd83dbSDimitry Andric     return Attribute::NoMerge;
19830b57cec5SDimitry Andric   case bitc::ATTR_KIND_NON_LAZY_BIND:
19840b57cec5SDimitry Andric     return Attribute::NonLazyBind;
19850b57cec5SDimitry Andric   case bitc::ATTR_KIND_NON_NULL:
19860b57cec5SDimitry Andric     return Attribute::NonNull;
19870b57cec5SDimitry Andric   case bitc::ATTR_KIND_DEREFERENCEABLE:
19880b57cec5SDimitry Andric     return Attribute::Dereferenceable;
19890b57cec5SDimitry Andric   case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
19900b57cec5SDimitry Andric     return Attribute::DereferenceableOrNull;
199181ad6265SDimitry Andric   case bitc::ATTR_KIND_ALLOC_ALIGN:
199281ad6265SDimitry Andric     return Attribute::AllocAlign;
199381ad6265SDimitry Andric   case bitc::ATTR_KIND_ALLOC_KIND:
199481ad6265SDimitry Andric     return Attribute::AllocKind;
19950b57cec5SDimitry Andric   case bitc::ATTR_KIND_ALLOC_SIZE:
19960b57cec5SDimitry Andric     return Attribute::AllocSize;
199781ad6265SDimitry Andric   case bitc::ATTR_KIND_ALLOCATED_POINTER:
199881ad6265SDimitry Andric     return Attribute::AllocatedPointer;
19990b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_RED_ZONE:
20000b57cec5SDimitry Andric     return Attribute::NoRedZone;
20010b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_RETURN:
20020b57cec5SDimitry Andric     return Attribute::NoReturn;
20030b57cec5SDimitry Andric   case bitc::ATTR_KIND_NOSYNC:
20040b57cec5SDimitry Andric     return Attribute::NoSync;
20050b57cec5SDimitry Andric   case bitc::ATTR_KIND_NOCF_CHECK:
20060b57cec5SDimitry Andric     return Attribute::NoCfCheck;
2007fe6060f1SDimitry Andric   case bitc::ATTR_KIND_NO_PROFILE:
2008fe6060f1SDimitry Andric     return Attribute::NoProfile;
2009bdd1243dSDimitry Andric   case bitc::ATTR_KIND_SKIP_PROFILE:
2010bdd1243dSDimitry Andric     return Attribute::SkipProfile;
20110b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_UNWIND:
20120b57cec5SDimitry Andric     return Attribute::NoUnwind;
201381ad6265SDimitry Andric   case bitc::ATTR_KIND_NO_SANITIZE_BOUNDS:
201481ad6265SDimitry Andric     return Attribute::NoSanitizeBounds;
2015fe6060f1SDimitry Andric   case bitc::ATTR_KIND_NO_SANITIZE_COVERAGE:
2016fe6060f1SDimitry Andric     return Attribute::NoSanitizeCoverage;
20175ffd83dbSDimitry Andric   case bitc::ATTR_KIND_NULL_POINTER_IS_VALID:
20185ffd83dbSDimitry Andric     return Attribute::NullPointerIsValid;
2019c9157d92SDimitry Andric   case bitc::ATTR_KIND_OPTIMIZE_FOR_DEBUGGING:
2020c9157d92SDimitry Andric     return Attribute::OptimizeForDebugging;
20210b57cec5SDimitry Andric   case bitc::ATTR_KIND_OPT_FOR_FUZZING:
20220b57cec5SDimitry Andric     return Attribute::OptForFuzzing;
20230b57cec5SDimitry Andric   case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
20240b57cec5SDimitry Andric     return Attribute::OptimizeForSize;
20250b57cec5SDimitry Andric   case bitc::ATTR_KIND_OPTIMIZE_NONE:
20260b57cec5SDimitry Andric     return Attribute::OptimizeNone;
20270b57cec5SDimitry Andric   case bitc::ATTR_KIND_READ_NONE:
20280b57cec5SDimitry Andric     return Attribute::ReadNone;
20290b57cec5SDimitry Andric   case bitc::ATTR_KIND_READ_ONLY:
20300b57cec5SDimitry Andric     return Attribute::ReadOnly;
20310b57cec5SDimitry Andric   case bitc::ATTR_KIND_RETURNED:
20320b57cec5SDimitry Andric     return Attribute::Returned;
20330b57cec5SDimitry Andric   case bitc::ATTR_KIND_RETURNS_TWICE:
20340b57cec5SDimitry Andric     return Attribute::ReturnsTwice;
20350b57cec5SDimitry Andric   case bitc::ATTR_KIND_S_EXT:
20360b57cec5SDimitry Andric     return Attribute::SExt;
20370b57cec5SDimitry Andric   case bitc::ATTR_KIND_SPECULATABLE:
20380b57cec5SDimitry Andric     return Attribute::Speculatable;
20390b57cec5SDimitry Andric   case bitc::ATTR_KIND_STACK_ALIGNMENT:
20400b57cec5SDimitry Andric     return Attribute::StackAlignment;
20410b57cec5SDimitry Andric   case bitc::ATTR_KIND_STACK_PROTECT:
20420b57cec5SDimitry Andric     return Attribute::StackProtect;
20430b57cec5SDimitry Andric   case bitc::ATTR_KIND_STACK_PROTECT_REQ:
20440b57cec5SDimitry Andric     return Attribute::StackProtectReq;
20450b57cec5SDimitry Andric   case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
20460b57cec5SDimitry Andric     return Attribute::StackProtectStrong;
20470b57cec5SDimitry Andric   case bitc::ATTR_KIND_SAFESTACK:
20480b57cec5SDimitry Andric     return Attribute::SafeStack;
20490b57cec5SDimitry Andric   case bitc::ATTR_KIND_SHADOWCALLSTACK:
20500b57cec5SDimitry Andric     return Attribute::ShadowCallStack;
20510b57cec5SDimitry Andric   case bitc::ATTR_KIND_STRICT_FP:
20520b57cec5SDimitry Andric     return Attribute::StrictFP;
20530b57cec5SDimitry Andric   case bitc::ATTR_KIND_STRUCT_RET:
20540b57cec5SDimitry Andric     return Attribute::StructRet;
20550b57cec5SDimitry Andric   case bitc::ATTR_KIND_SANITIZE_ADDRESS:
20560b57cec5SDimitry Andric     return Attribute::SanitizeAddress;
20570b57cec5SDimitry Andric   case bitc::ATTR_KIND_SANITIZE_HWADDRESS:
20580b57cec5SDimitry Andric     return Attribute::SanitizeHWAddress;
20590b57cec5SDimitry Andric   case bitc::ATTR_KIND_SANITIZE_THREAD:
20600b57cec5SDimitry Andric     return Attribute::SanitizeThread;
20610b57cec5SDimitry Andric   case bitc::ATTR_KIND_SANITIZE_MEMORY:
20620b57cec5SDimitry Andric     return Attribute::SanitizeMemory;
20630b57cec5SDimitry Andric   case bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING:
20640b57cec5SDimitry Andric     return Attribute::SpeculativeLoadHardening;
20650b57cec5SDimitry Andric   case bitc::ATTR_KIND_SWIFT_ERROR:
20660b57cec5SDimitry Andric     return Attribute::SwiftError;
20670b57cec5SDimitry Andric   case bitc::ATTR_KIND_SWIFT_SELF:
20680b57cec5SDimitry Andric     return Attribute::SwiftSelf;
2069fe6060f1SDimitry Andric   case bitc::ATTR_KIND_SWIFT_ASYNC:
2070fe6060f1SDimitry Andric     return Attribute::SwiftAsync;
20710b57cec5SDimitry Andric   case bitc::ATTR_KIND_UW_TABLE:
20720b57cec5SDimitry Andric     return Attribute::UWTable;
2073fe6060f1SDimitry Andric   case bitc::ATTR_KIND_VSCALE_RANGE:
2074fe6060f1SDimitry Andric     return Attribute::VScaleRange;
20750b57cec5SDimitry Andric   case bitc::ATTR_KIND_WILLRETURN:
20760b57cec5SDimitry Andric     return Attribute::WillReturn;
20770b57cec5SDimitry Andric   case bitc::ATTR_KIND_WRITEONLY:
20780b57cec5SDimitry Andric     return Attribute::WriteOnly;
20790b57cec5SDimitry Andric   case bitc::ATTR_KIND_Z_EXT:
20800b57cec5SDimitry Andric     return Attribute::ZExt;
20810b57cec5SDimitry Andric   case bitc::ATTR_KIND_IMMARG:
20820b57cec5SDimitry Andric     return Attribute::ImmArg;
20830b57cec5SDimitry Andric   case bitc::ATTR_KIND_SANITIZE_MEMTAG:
20840b57cec5SDimitry Andric     return Attribute::SanitizeMemTag;
20855ffd83dbSDimitry Andric   case bitc::ATTR_KIND_PREALLOCATED:
20865ffd83dbSDimitry Andric     return Attribute::Preallocated;
20875ffd83dbSDimitry Andric   case bitc::ATTR_KIND_NOUNDEF:
20885ffd83dbSDimitry Andric     return Attribute::NoUndef;
2089e8d8bef9SDimitry Andric   case bitc::ATTR_KIND_BYREF:
2090e8d8bef9SDimitry Andric     return Attribute::ByRef;
2091e8d8bef9SDimitry Andric   case bitc::ATTR_KIND_MUSTPROGRESS:
2092e8d8bef9SDimitry Andric     return Attribute::MustProgress;
2093e8d8bef9SDimitry Andric   case bitc::ATTR_KIND_HOT:
2094e8d8bef9SDimitry Andric     return Attribute::Hot;
209581ad6265SDimitry Andric   case bitc::ATTR_KIND_PRESPLIT_COROUTINE:
209681ad6265SDimitry Andric     return Attribute::PresplitCoroutine;
2097c9157d92SDimitry Andric   case bitc::ATTR_KIND_WRITABLE:
2098c9157d92SDimitry Andric     return Attribute::Writable;
2099c9157d92SDimitry Andric   case bitc::ATTR_KIND_CORO_ONLY_DESTROY_WHEN_COMPLETE:
2100c9157d92SDimitry Andric     return Attribute::CoroDestroyOnlyWhenComplete;
2101c9157d92SDimitry Andric   case bitc::ATTR_KIND_DEAD_ON_UNWIND:
2102c9157d92SDimitry Andric     return Attribute::DeadOnUnwind;
21030b57cec5SDimitry Andric   }
21040b57cec5SDimitry Andric }
21050b57cec5SDimitry Andric 
parseAlignmentValue(uint64_t Exponent,MaybeAlign & Alignment)21060b57cec5SDimitry Andric Error BitcodeReader::parseAlignmentValue(uint64_t Exponent,
21078bcb0991SDimitry Andric                                          MaybeAlign &Alignment) {
21080b57cec5SDimitry Andric   // Note: Alignment in bitcode files is incremented by 1, so that zero
21090b57cec5SDimitry Andric   // can be used for default alignment.
21100b57cec5SDimitry Andric   if (Exponent > Value::MaxAlignmentExponent + 1)
21110b57cec5SDimitry Andric     return error("Invalid alignment value");
21128bcb0991SDimitry Andric   Alignment = decodeMaybeAlign(Exponent);
21130b57cec5SDimitry Andric   return Error::success();
21140b57cec5SDimitry Andric }
21150b57cec5SDimitry Andric 
parseAttrKind(uint64_t Code,Attribute::AttrKind * Kind)21160b57cec5SDimitry Andric Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) {
21170b57cec5SDimitry Andric   *Kind = getAttrFromCode(Code);
21180b57cec5SDimitry Andric   if (*Kind == Attribute::None)
21190b57cec5SDimitry Andric     return error("Unknown attribute kind (" + Twine(Code) + ")");
21200b57cec5SDimitry Andric   return Error::success();
21210b57cec5SDimitry Andric }
21220b57cec5SDimitry Andric 
upgradeOldMemoryAttribute(MemoryEffects & ME,uint64_t EncodedKind)2123bdd1243dSDimitry Andric static bool upgradeOldMemoryAttribute(MemoryEffects &ME, uint64_t EncodedKind) {
2124bdd1243dSDimitry Andric   switch (EncodedKind) {
2125bdd1243dSDimitry Andric   case bitc::ATTR_KIND_READ_NONE:
2126bdd1243dSDimitry Andric     ME &= MemoryEffects::none();
2127bdd1243dSDimitry Andric     return true;
2128bdd1243dSDimitry Andric   case bitc::ATTR_KIND_READ_ONLY:
2129bdd1243dSDimitry Andric     ME &= MemoryEffects::readOnly();
2130bdd1243dSDimitry Andric     return true;
2131bdd1243dSDimitry Andric   case bitc::ATTR_KIND_WRITEONLY:
2132bdd1243dSDimitry Andric     ME &= MemoryEffects::writeOnly();
2133bdd1243dSDimitry Andric     return true;
2134bdd1243dSDimitry Andric   case bitc::ATTR_KIND_ARGMEMONLY:
2135bdd1243dSDimitry Andric     ME &= MemoryEffects::argMemOnly();
2136bdd1243dSDimitry Andric     return true;
2137bdd1243dSDimitry Andric   case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY:
2138bdd1243dSDimitry Andric     ME &= MemoryEffects::inaccessibleMemOnly();
2139bdd1243dSDimitry Andric     return true;
2140bdd1243dSDimitry Andric   case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY:
2141bdd1243dSDimitry Andric     ME &= MemoryEffects::inaccessibleOrArgMemOnly();
2142bdd1243dSDimitry Andric     return true;
2143bdd1243dSDimitry Andric   default:
2144bdd1243dSDimitry Andric     return false;
2145bdd1243dSDimitry Andric   }
2146bdd1243dSDimitry Andric }
2147bdd1243dSDimitry Andric 
parseAttributeGroupBlock()21480b57cec5SDimitry Andric Error BitcodeReader::parseAttributeGroupBlock() {
21490b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
21500b57cec5SDimitry Andric     return Err;
21510b57cec5SDimitry Andric 
21520b57cec5SDimitry Andric   if (!MAttributeGroups.empty())
21530b57cec5SDimitry Andric     return error("Invalid multiple blocks");
21540b57cec5SDimitry Andric 
21550b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
21560b57cec5SDimitry Andric 
21570b57cec5SDimitry Andric   // Read all the records.
21580b57cec5SDimitry Andric   while (true) {
21590b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
21600b57cec5SDimitry Andric     if (!MaybeEntry)
21610b57cec5SDimitry Andric       return MaybeEntry.takeError();
21620b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
21630b57cec5SDimitry Andric 
21640b57cec5SDimitry Andric     switch (Entry.Kind) {
21650b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
21660b57cec5SDimitry Andric     case BitstreamEntry::Error:
21670b57cec5SDimitry Andric       return error("Malformed block");
21680b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
21690b57cec5SDimitry Andric       return Error::success();
21700b57cec5SDimitry Andric     case BitstreamEntry::Record:
21710b57cec5SDimitry Andric       // The interesting case.
21720b57cec5SDimitry Andric       break;
21730b57cec5SDimitry Andric     }
21740b57cec5SDimitry Andric 
21750b57cec5SDimitry Andric     // Read a record.
21760b57cec5SDimitry Andric     Record.clear();
21770b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
21780b57cec5SDimitry Andric     if (!MaybeRecord)
21790b57cec5SDimitry Andric       return MaybeRecord.takeError();
21800b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
21810b57cec5SDimitry Andric     default:  // Default behavior: ignore.
21820b57cec5SDimitry Andric       break;
21830b57cec5SDimitry Andric     case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
21840b57cec5SDimitry Andric       if (Record.size() < 3)
218581ad6265SDimitry Andric         return error("Invalid grp record");
21860b57cec5SDimitry Andric 
21870b57cec5SDimitry Andric       uint64_t GrpID = Record[0];
21880b57cec5SDimitry Andric       uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
21890b57cec5SDimitry Andric 
219004eeddc0SDimitry Andric       AttrBuilder B(Context);
2191bdd1243dSDimitry Andric       MemoryEffects ME = MemoryEffects::unknown();
21920b57cec5SDimitry Andric       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
21930b57cec5SDimitry Andric         if (Record[i] == 0) {        // Enum attribute
21940b57cec5SDimitry Andric           Attribute::AttrKind Kind;
2195bdd1243dSDimitry Andric           uint64_t EncodedKind = Record[++i];
2196bdd1243dSDimitry Andric           if (Idx == AttributeList::FunctionIndex &&
2197bdd1243dSDimitry Andric               upgradeOldMemoryAttribute(ME, EncodedKind))
2198bdd1243dSDimitry Andric             continue;
2199bdd1243dSDimitry Andric 
2200bdd1243dSDimitry Andric           if (Error Err = parseAttrKind(EncodedKind, &Kind))
22010b57cec5SDimitry Andric             return Err;
22020b57cec5SDimitry Andric 
22030b57cec5SDimitry Andric           // Upgrade old-style byval attribute to one with a type, even if it's
22040b57cec5SDimitry Andric           // nullptr. We will have to insert the real type when we associate
22050b57cec5SDimitry Andric           // this AttributeList with a function.
22060b57cec5SDimitry Andric           if (Kind == Attribute::ByVal)
22070b57cec5SDimitry Andric             B.addByValAttr(nullptr);
2208e8d8bef9SDimitry Andric           else if (Kind == Attribute::StructRet)
2209e8d8bef9SDimitry Andric             B.addStructRetAttr(nullptr);
2210fe6060f1SDimitry Andric           else if (Kind == Attribute::InAlloca)
2211fe6060f1SDimitry Andric             B.addInAllocaAttr(nullptr);
221281ad6265SDimitry Andric           else if (Kind == Attribute::UWTable)
221381ad6265SDimitry Andric             B.addUWTableAttr(UWTableKind::Default);
2214fe6060f1SDimitry Andric           else if (Attribute::isEnumAttrKind(Kind))
22150b57cec5SDimitry Andric             B.addAttribute(Kind);
2216fe6060f1SDimitry Andric           else
2217fe6060f1SDimitry Andric             return error("Not an enum attribute");
22180b57cec5SDimitry Andric         } else if (Record[i] == 1) { // Integer attribute
22190b57cec5SDimitry Andric           Attribute::AttrKind Kind;
22200b57cec5SDimitry Andric           if (Error Err = parseAttrKind(Record[++i], &Kind))
22210b57cec5SDimitry Andric             return Err;
2222fe6060f1SDimitry Andric           if (!Attribute::isIntAttrKind(Kind))
2223fe6060f1SDimitry Andric             return error("Not an int attribute");
22240b57cec5SDimitry Andric           if (Kind == Attribute::Alignment)
22250b57cec5SDimitry Andric             B.addAlignmentAttr(Record[++i]);
22260b57cec5SDimitry Andric           else if (Kind == Attribute::StackAlignment)
22270b57cec5SDimitry Andric             B.addStackAlignmentAttr(Record[++i]);
22280b57cec5SDimitry Andric           else if (Kind == Attribute::Dereferenceable)
22290b57cec5SDimitry Andric             B.addDereferenceableAttr(Record[++i]);
22300b57cec5SDimitry Andric           else if (Kind == Attribute::DereferenceableOrNull)
22310b57cec5SDimitry Andric             B.addDereferenceableOrNullAttr(Record[++i]);
22320b57cec5SDimitry Andric           else if (Kind == Attribute::AllocSize)
22330b57cec5SDimitry Andric             B.addAllocSizeAttrFromRawRepr(Record[++i]);
2234fe6060f1SDimitry Andric           else if (Kind == Attribute::VScaleRange)
2235fe6060f1SDimitry Andric             B.addVScaleRangeAttrFromRawRepr(Record[++i]);
223681ad6265SDimitry Andric           else if (Kind == Attribute::UWTable)
223781ad6265SDimitry Andric             B.addUWTableAttr(UWTableKind(Record[++i]));
223881ad6265SDimitry Andric           else if (Kind == Attribute::AllocKind)
223981ad6265SDimitry Andric             B.addAllocKindAttr(static_cast<AllocFnKind>(Record[++i]));
2240bdd1243dSDimitry Andric           else if (Kind == Attribute::Memory)
2241bdd1243dSDimitry Andric             B.addMemoryAttr(MemoryEffects::createFromIntValue(Record[++i]));
2242fe013be4SDimitry Andric           else if (Kind == Attribute::NoFPClass)
2243fe013be4SDimitry Andric             B.addNoFPClassAttr(
2244fe013be4SDimitry Andric                 static_cast<FPClassTest>(Record[++i] & fcAllFlags));
22450b57cec5SDimitry Andric         } else if (Record[i] == 3 || Record[i] == 4) { // String attribute
22460b57cec5SDimitry Andric           bool HasValue = (Record[i++] == 4);
22470b57cec5SDimitry Andric           SmallString<64> KindStr;
22480b57cec5SDimitry Andric           SmallString<64> ValStr;
22490b57cec5SDimitry Andric 
22500b57cec5SDimitry Andric           while (Record[i] != 0 && i != e)
22510b57cec5SDimitry Andric             KindStr += Record[i++];
22520b57cec5SDimitry Andric           assert(Record[i] == 0 && "Kind string not null terminated");
22530b57cec5SDimitry Andric 
22540b57cec5SDimitry Andric           if (HasValue) {
22550b57cec5SDimitry Andric             // Has a value associated with it.
22560b57cec5SDimitry Andric             ++i; // Skip the '0' that terminates the "kind" string.
22570b57cec5SDimitry Andric             while (Record[i] != 0 && i != e)
22580b57cec5SDimitry Andric               ValStr += Record[i++];
22590b57cec5SDimitry Andric             assert(Record[i] == 0 && "Value string not null terminated");
22600b57cec5SDimitry Andric           }
22610b57cec5SDimitry Andric 
22620b57cec5SDimitry Andric           B.addAttribute(KindStr.str(), ValStr.str());
226381ad6265SDimitry Andric         } else if (Record[i] == 5 || Record[i] == 6) {
22640b57cec5SDimitry Andric           bool HasType = Record[i] == 6;
22650b57cec5SDimitry Andric           Attribute::AttrKind Kind;
22660b57cec5SDimitry Andric           if (Error Err = parseAttrKind(Record[++i], &Kind))
22670b57cec5SDimitry Andric             return Err;
2268fe6060f1SDimitry Andric           if (!Attribute::isTypeAttrKind(Kind))
2269fe6060f1SDimitry Andric             return error("Not a type attribute");
2270fe6060f1SDimitry Andric 
2271fe6060f1SDimitry Andric           B.addTypeAttr(Kind, HasType ? getTypeByID(Record[++i]) : nullptr);
227281ad6265SDimitry Andric         } else {
227381ad6265SDimitry Andric           return error("Invalid attribute group entry");
22740b57cec5SDimitry Andric         }
22750b57cec5SDimitry Andric       }
22760b57cec5SDimitry Andric 
2277bdd1243dSDimitry Andric       if (ME != MemoryEffects::unknown())
2278bdd1243dSDimitry Andric         B.addMemoryAttr(ME);
2279bdd1243dSDimitry Andric 
22805ffd83dbSDimitry Andric       UpgradeAttributes(B);
22810b57cec5SDimitry Andric       MAttributeGroups[GrpID] = AttributeList::get(Context, Idx, B);
22820b57cec5SDimitry Andric       break;
22830b57cec5SDimitry Andric     }
22840b57cec5SDimitry Andric     }
22850b57cec5SDimitry Andric   }
22860b57cec5SDimitry Andric }
22870b57cec5SDimitry Andric 
parseTypeTable()22880b57cec5SDimitry Andric Error BitcodeReader::parseTypeTable() {
22890b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
22900b57cec5SDimitry Andric     return Err;
22910b57cec5SDimitry Andric 
22920b57cec5SDimitry Andric   return parseTypeTableBody();
22930b57cec5SDimitry Andric }
22940b57cec5SDimitry Andric 
parseTypeTableBody()22950b57cec5SDimitry Andric Error BitcodeReader::parseTypeTableBody() {
22960b57cec5SDimitry Andric   if (!TypeList.empty())
22970b57cec5SDimitry Andric     return error("Invalid multiple blocks");
22980b57cec5SDimitry Andric 
22990b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
23000b57cec5SDimitry Andric   unsigned NumRecords = 0;
23010b57cec5SDimitry Andric 
23020b57cec5SDimitry Andric   SmallString<64> TypeName;
23030b57cec5SDimitry Andric 
23040b57cec5SDimitry Andric   // Read all the records for this type table.
23050b57cec5SDimitry Andric   while (true) {
23060b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
23070b57cec5SDimitry Andric     if (!MaybeEntry)
23080b57cec5SDimitry Andric       return MaybeEntry.takeError();
23090b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
23100b57cec5SDimitry Andric 
23110b57cec5SDimitry Andric     switch (Entry.Kind) {
23120b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
23130b57cec5SDimitry Andric     case BitstreamEntry::Error:
23140b57cec5SDimitry Andric       return error("Malformed block");
23150b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
23160b57cec5SDimitry Andric       if (NumRecords != TypeList.size())
23170b57cec5SDimitry Andric         return error("Malformed block");
23180b57cec5SDimitry Andric       return Error::success();
23190b57cec5SDimitry Andric     case BitstreamEntry::Record:
23200b57cec5SDimitry Andric       // The interesting case.
23210b57cec5SDimitry Andric       break;
23220b57cec5SDimitry Andric     }
23230b57cec5SDimitry Andric 
23240b57cec5SDimitry Andric     // Read a record.
23250b57cec5SDimitry Andric     Record.clear();
23260b57cec5SDimitry Andric     Type *ResultTy = nullptr;
232781ad6265SDimitry Andric     SmallVector<unsigned> ContainedIDs;
23280b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
23290b57cec5SDimitry Andric     if (!MaybeRecord)
23300b57cec5SDimitry Andric       return MaybeRecord.takeError();
23310b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
23320b57cec5SDimitry Andric     default:
23330b57cec5SDimitry Andric       return error("Invalid value");
23340b57cec5SDimitry Andric     case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
23350b57cec5SDimitry Andric       // TYPE_CODE_NUMENTRY contains a count of the number of types in the
23360b57cec5SDimitry Andric       // type list.  This allows us to reserve space.
2337e8d8bef9SDimitry Andric       if (Record.empty())
233881ad6265SDimitry Andric         return error("Invalid numentry record");
23390b57cec5SDimitry Andric       TypeList.resize(Record[0]);
23400b57cec5SDimitry Andric       continue;
23410b57cec5SDimitry Andric     case bitc::TYPE_CODE_VOID:      // VOID
23420b57cec5SDimitry Andric       ResultTy = Type::getVoidTy(Context);
23430b57cec5SDimitry Andric       break;
23440b57cec5SDimitry Andric     case bitc::TYPE_CODE_HALF:     // HALF
23450b57cec5SDimitry Andric       ResultTy = Type::getHalfTy(Context);
23460b57cec5SDimitry Andric       break;
23475ffd83dbSDimitry Andric     case bitc::TYPE_CODE_BFLOAT:    // BFLOAT
23485ffd83dbSDimitry Andric       ResultTy = Type::getBFloatTy(Context);
23495ffd83dbSDimitry Andric       break;
23500b57cec5SDimitry Andric     case bitc::TYPE_CODE_FLOAT:     // FLOAT
23510b57cec5SDimitry Andric       ResultTy = Type::getFloatTy(Context);
23520b57cec5SDimitry Andric       break;
23530b57cec5SDimitry Andric     case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
23540b57cec5SDimitry Andric       ResultTy = Type::getDoubleTy(Context);
23550b57cec5SDimitry Andric       break;
23560b57cec5SDimitry Andric     case bitc::TYPE_CODE_X86_FP80:  // X86_FP80
23570b57cec5SDimitry Andric       ResultTy = Type::getX86_FP80Ty(Context);
23580b57cec5SDimitry Andric       break;
23590b57cec5SDimitry Andric     case bitc::TYPE_CODE_FP128:     // FP128
23600b57cec5SDimitry Andric       ResultTy = Type::getFP128Ty(Context);
23610b57cec5SDimitry Andric       break;
23620b57cec5SDimitry Andric     case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
23630b57cec5SDimitry Andric       ResultTy = Type::getPPC_FP128Ty(Context);
23640b57cec5SDimitry Andric       break;
23650b57cec5SDimitry Andric     case bitc::TYPE_CODE_LABEL:     // LABEL
23660b57cec5SDimitry Andric       ResultTy = Type::getLabelTy(Context);
23670b57cec5SDimitry Andric       break;
23680b57cec5SDimitry Andric     case bitc::TYPE_CODE_METADATA:  // METADATA
23690b57cec5SDimitry Andric       ResultTy = Type::getMetadataTy(Context);
23700b57cec5SDimitry Andric       break;
23710b57cec5SDimitry Andric     case bitc::TYPE_CODE_X86_MMX:   // X86_MMX
23720b57cec5SDimitry Andric       ResultTy = Type::getX86_MMXTy(Context);
23730b57cec5SDimitry Andric       break;
2374e8d8bef9SDimitry Andric     case bitc::TYPE_CODE_X86_AMX:   // X86_AMX
2375e8d8bef9SDimitry Andric       ResultTy = Type::getX86_AMXTy(Context);
2376e8d8bef9SDimitry Andric       break;
23770b57cec5SDimitry Andric     case bitc::TYPE_CODE_TOKEN:     // TOKEN
23780b57cec5SDimitry Andric       ResultTy = Type::getTokenTy(Context);
23790b57cec5SDimitry Andric       break;
23800b57cec5SDimitry Andric     case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
2381e8d8bef9SDimitry Andric       if (Record.empty())
238281ad6265SDimitry Andric         return error("Invalid integer record");
23830b57cec5SDimitry Andric 
23840b57cec5SDimitry Andric       uint64_t NumBits = Record[0];
23850b57cec5SDimitry Andric       if (NumBits < IntegerType::MIN_INT_BITS ||
23860b57cec5SDimitry Andric           NumBits > IntegerType::MAX_INT_BITS)
23870b57cec5SDimitry Andric         return error("Bitwidth for integer type out of range");
23880b57cec5SDimitry Andric       ResultTy = IntegerType::get(Context, NumBits);
23890b57cec5SDimitry Andric       break;
23900b57cec5SDimitry Andric     }
23910b57cec5SDimitry Andric     case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
23920b57cec5SDimitry Andric                                     //          [pointee type, address space]
2393e8d8bef9SDimitry Andric       if (Record.empty())
239481ad6265SDimitry Andric         return error("Invalid pointer record");
23950b57cec5SDimitry Andric       unsigned AddressSpace = 0;
23960b57cec5SDimitry Andric       if (Record.size() == 2)
23970b57cec5SDimitry Andric         AddressSpace = Record[1];
23980b57cec5SDimitry Andric       ResultTy = getTypeByID(Record[0]);
23990b57cec5SDimitry Andric       if (!ResultTy ||
24000b57cec5SDimitry Andric           !PointerType::isValidElementType(ResultTy))
24010b57cec5SDimitry Andric         return error("Invalid type");
240281ad6265SDimitry Andric       ContainedIDs.push_back(Record[0]);
24030b57cec5SDimitry Andric       ResultTy = PointerType::get(ResultTy, AddressSpace);
24040b57cec5SDimitry Andric       break;
24050b57cec5SDimitry Andric     }
2406fe6060f1SDimitry Andric     case bitc::TYPE_CODE_OPAQUE_POINTER: { // OPAQUE_POINTER: [addrspace]
2407fe6060f1SDimitry Andric       if (Record.size() != 1)
240881ad6265SDimitry Andric         return error("Invalid opaque pointer record");
2409fe6060f1SDimitry Andric       unsigned AddressSpace = Record[0];
2410fe6060f1SDimitry Andric       ResultTy = PointerType::get(Context, AddressSpace);
2411fe6060f1SDimitry Andric       break;
2412fe6060f1SDimitry Andric     }
24130b57cec5SDimitry Andric     case bitc::TYPE_CODE_FUNCTION_OLD: {
24145ffd83dbSDimitry Andric       // Deprecated, but still needed to read old bitcode files.
24150b57cec5SDimitry Andric       // FUNCTION: [vararg, attrid, retty, paramty x N]
24160b57cec5SDimitry Andric       if (Record.size() < 3)
241781ad6265SDimitry Andric         return error("Invalid function record");
24180b57cec5SDimitry Andric       SmallVector<Type*, 8> ArgTys;
24190b57cec5SDimitry Andric       for (unsigned i = 3, e = Record.size(); i != e; ++i) {
24200b57cec5SDimitry Andric         if (Type *T = getTypeByID(Record[i]))
24210b57cec5SDimitry Andric           ArgTys.push_back(T);
24220b57cec5SDimitry Andric         else
24230b57cec5SDimitry Andric           break;
24240b57cec5SDimitry Andric       }
24250b57cec5SDimitry Andric 
24260b57cec5SDimitry Andric       ResultTy = getTypeByID(Record[2]);
24270b57cec5SDimitry Andric       if (!ResultTy || ArgTys.size() < Record.size()-3)
24280b57cec5SDimitry Andric         return error("Invalid type");
24290b57cec5SDimitry Andric 
243081ad6265SDimitry Andric       ContainedIDs.append(Record.begin() + 2, Record.end());
24310b57cec5SDimitry Andric       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
24320b57cec5SDimitry Andric       break;
24330b57cec5SDimitry Andric     }
24340b57cec5SDimitry Andric     case bitc::TYPE_CODE_FUNCTION: {
24350b57cec5SDimitry Andric       // FUNCTION: [vararg, retty, paramty x N]
24360b57cec5SDimitry Andric       if (Record.size() < 2)
243781ad6265SDimitry Andric         return error("Invalid function record");
24380b57cec5SDimitry Andric       SmallVector<Type*, 8> ArgTys;
24390b57cec5SDimitry Andric       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
24400b57cec5SDimitry Andric         if (Type *T = getTypeByID(Record[i])) {
24410b57cec5SDimitry Andric           if (!FunctionType::isValidArgumentType(T))
24420b57cec5SDimitry Andric             return error("Invalid function argument type");
24430b57cec5SDimitry Andric           ArgTys.push_back(T);
24440b57cec5SDimitry Andric         }
24450b57cec5SDimitry Andric         else
24460b57cec5SDimitry Andric           break;
24470b57cec5SDimitry Andric       }
24480b57cec5SDimitry Andric 
24490b57cec5SDimitry Andric       ResultTy = getTypeByID(Record[1]);
24500b57cec5SDimitry Andric       if (!ResultTy || ArgTys.size() < Record.size()-2)
24510b57cec5SDimitry Andric         return error("Invalid type");
24520b57cec5SDimitry Andric 
245381ad6265SDimitry Andric       ContainedIDs.append(Record.begin() + 1, Record.end());
24540b57cec5SDimitry Andric       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
24550b57cec5SDimitry Andric       break;
24560b57cec5SDimitry Andric     }
24570b57cec5SDimitry Andric     case bitc::TYPE_CODE_STRUCT_ANON: {  // STRUCT: [ispacked, eltty x N]
2458e8d8bef9SDimitry Andric       if (Record.empty())
245981ad6265SDimitry Andric         return error("Invalid anon struct record");
24600b57cec5SDimitry Andric       SmallVector<Type*, 8> EltTys;
24610b57cec5SDimitry Andric       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
24620b57cec5SDimitry Andric         if (Type *T = getTypeByID(Record[i]))
24630b57cec5SDimitry Andric           EltTys.push_back(T);
24640b57cec5SDimitry Andric         else
24650b57cec5SDimitry Andric           break;
24660b57cec5SDimitry Andric       }
24670b57cec5SDimitry Andric       if (EltTys.size() != Record.size()-1)
24680b57cec5SDimitry Andric         return error("Invalid type");
246981ad6265SDimitry Andric       ContainedIDs.append(Record.begin() + 1, Record.end());
24700b57cec5SDimitry Andric       ResultTy = StructType::get(Context, EltTys, Record[0]);
24710b57cec5SDimitry Andric       break;
24720b57cec5SDimitry Andric     }
24730b57cec5SDimitry Andric     case bitc::TYPE_CODE_STRUCT_NAME:   // STRUCT_NAME: [strchr x N]
24740b57cec5SDimitry Andric       if (convertToString(Record, 0, TypeName))
247581ad6265SDimitry Andric         return error("Invalid struct name record");
24760b57cec5SDimitry Andric       continue;
24770b57cec5SDimitry Andric 
24780b57cec5SDimitry Andric     case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
2479e8d8bef9SDimitry Andric       if (Record.empty())
248081ad6265SDimitry Andric         return error("Invalid named struct record");
24810b57cec5SDimitry Andric 
24820b57cec5SDimitry Andric       if (NumRecords >= TypeList.size())
24830b57cec5SDimitry Andric         return error("Invalid TYPE table");
24840b57cec5SDimitry Andric 
24850b57cec5SDimitry Andric       // Check to see if this was forward referenced, if so fill in the temp.
24860b57cec5SDimitry Andric       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
24870b57cec5SDimitry Andric       if (Res) {
24880b57cec5SDimitry Andric         Res->setName(TypeName);
24890b57cec5SDimitry Andric         TypeList[NumRecords] = nullptr;
24900b57cec5SDimitry Andric       } else  // Otherwise, create a new struct.
24910b57cec5SDimitry Andric         Res = createIdentifiedStructType(Context, TypeName);
24920b57cec5SDimitry Andric       TypeName.clear();
24930b57cec5SDimitry Andric 
24940b57cec5SDimitry Andric       SmallVector<Type*, 8> EltTys;
24950b57cec5SDimitry Andric       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
24960b57cec5SDimitry Andric         if (Type *T = getTypeByID(Record[i]))
24970b57cec5SDimitry Andric           EltTys.push_back(T);
24980b57cec5SDimitry Andric         else
24990b57cec5SDimitry Andric           break;
25000b57cec5SDimitry Andric       }
25010b57cec5SDimitry Andric       if (EltTys.size() != Record.size()-1)
250281ad6265SDimitry Andric         return error("Invalid named struct record");
25030b57cec5SDimitry Andric       Res->setBody(EltTys, Record[0]);
250481ad6265SDimitry Andric       ContainedIDs.append(Record.begin() + 1, Record.end());
25050b57cec5SDimitry Andric       ResultTy = Res;
25060b57cec5SDimitry Andric       break;
25070b57cec5SDimitry Andric     }
25080b57cec5SDimitry Andric     case bitc::TYPE_CODE_OPAQUE: {       // OPAQUE: []
25090b57cec5SDimitry Andric       if (Record.size() != 1)
251081ad6265SDimitry Andric         return error("Invalid opaque type record");
25110b57cec5SDimitry Andric 
25120b57cec5SDimitry Andric       if (NumRecords >= TypeList.size())
25130b57cec5SDimitry Andric         return error("Invalid TYPE table");
25140b57cec5SDimitry Andric 
25150b57cec5SDimitry Andric       // Check to see if this was forward referenced, if so fill in the temp.
25160b57cec5SDimitry Andric       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
25170b57cec5SDimitry Andric       if (Res) {
25180b57cec5SDimitry Andric         Res->setName(TypeName);
25190b57cec5SDimitry Andric         TypeList[NumRecords] = nullptr;
25200b57cec5SDimitry Andric       } else  // Otherwise, create a new struct with no body.
25210b57cec5SDimitry Andric         Res = createIdentifiedStructType(Context, TypeName);
25220b57cec5SDimitry Andric       TypeName.clear();
25230b57cec5SDimitry Andric       ResultTy = Res;
25240b57cec5SDimitry Andric       break;
25250b57cec5SDimitry Andric     }
2526bdd1243dSDimitry Andric     case bitc::TYPE_CODE_TARGET_TYPE: { // TARGET_TYPE: [NumTy, Tys..., Ints...]
2527bdd1243dSDimitry Andric       if (Record.size() < 1)
2528bdd1243dSDimitry Andric         return error("Invalid target extension type record");
2529bdd1243dSDimitry Andric 
2530bdd1243dSDimitry Andric       if (NumRecords >= TypeList.size())
2531bdd1243dSDimitry Andric         return error("Invalid TYPE table");
2532bdd1243dSDimitry Andric 
2533bdd1243dSDimitry Andric       if (Record[0] >= Record.size())
2534bdd1243dSDimitry Andric         return error("Too many type parameters");
2535bdd1243dSDimitry Andric 
2536bdd1243dSDimitry Andric       unsigned NumTys = Record[0];
2537bdd1243dSDimitry Andric       SmallVector<Type *, 4> TypeParams;
2538bdd1243dSDimitry Andric       SmallVector<unsigned, 8> IntParams;
2539bdd1243dSDimitry Andric       for (unsigned i = 0; i < NumTys; i++) {
2540bdd1243dSDimitry Andric         if (Type *T = getTypeByID(Record[i + 1]))
2541bdd1243dSDimitry Andric           TypeParams.push_back(T);
2542bdd1243dSDimitry Andric         else
2543bdd1243dSDimitry Andric           return error("Invalid type");
2544bdd1243dSDimitry Andric       }
2545bdd1243dSDimitry Andric 
2546bdd1243dSDimitry Andric       for (unsigned i = NumTys + 1, e = Record.size(); i < e; i++) {
2547bdd1243dSDimitry Andric         if (Record[i] > UINT_MAX)
2548bdd1243dSDimitry Andric           return error("Integer parameter too large");
2549bdd1243dSDimitry Andric         IntParams.push_back(Record[i]);
2550bdd1243dSDimitry Andric       }
2551bdd1243dSDimitry Andric       ResultTy = TargetExtType::get(Context, TypeName, TypeParams, IntParams);
2552bdd1243dSDimitry Andric       TypeName.clear();
2553bdd1243dSDimitry Andric       break;
2554bdd1243dSDimitry Andric     }
25550b57cec5SDimitry Andric     case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
25560b57cec5SDimitry Andric       if (Record.size() < 2)
255781ad6265SDimitry Andric         return error("Invalid array type record");
25580b57cec5SDimitry Andric       ResultTy = getTypeByID(Record[1]);
25590b57cec5SDimitry Andric       if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
25600b57cec5SDimitry Andric         return error("Invalid type");
256181ad6265SDimitry Andric       ContainedIDs.push_back(Record[1]);
25620b57cec5SDimitry Andric       ResultTy = ArrayType::get(ResultTy, Record[0]);
25630b57cec5SDimitry Andric       break;
25640b57cec5SDimitry Andric     case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty] or
25650b57cec5SDimitry Andric                                     //         [numelts, eltty, scalable]
25660b57cec5SDimitry Andric       if (Record.size() < 2)
256781ad6265SDimitry Andric         return error("Invalid vector type record");
25680b57cec5SDimitry Andric       if (Record[0] == 0)
25690b57cec5SDimitry Andric         return error("Invalid vector length");
25700b57cec5SDimitry Andric       ResultTy = getTypeByID(Record[1]);
2571349cc55cSDimitry Andric       if (!ResultTy || !VectorType::isValidElementType(ResultTy))
25720b57cec5SDimitry Andric         return error("Invalid type");
25730b57cec5SDimitry Andric       bool Scalable = Record.size() > 2 ? Record[2] : false;
257481ad6265SDimitry Andric       ContainedIDs.push_back(Record[1]);
25750b57cec5SDimitry Andric       ResultTy = VectorType::get(ResultTy, Record[0], Scalable);
25760b57cec5SDimitry Andric       break;
25770b57cec5SDimitry Andric     }
25780b57cec5SDimitry Andric 
25790b57cec5SDimitry Andric     if (NumRecords >= TypeList.size())
25800b57cec5SDimitry Andric       return error("Invalid TYPE table");
25810b57cec5SDimitry Andric     if (TypeList[NumRecords])
25820b57cec5SDimitry Andric       return error(
25830b57cec5SDimitry Andric           "Invalid TYPE table: Only named structs can be forward referenced");
25840b57cec5SDimitry Andric     assert(ResultTy && "Didn't read a type?");
258581ad6265SDimitry Andric     TypeList[NumRecords] = ResultTy;
258681ad6265SDimitry Andric     if (!ContainedIDs.empty())
258781ad6265SDimitry Andric       ContainedTypeIDs[NumRecords] = std::move(ContainedIDs);
258881ad6265SDimitry Andric     ++NumRecords;
25890b57cec5SDimitry Andric   }
25900b57cec5SDimitry Andric }
25910b57cec5SDimitry Andric 
parseOperandBundleTags()25920b57cec5SDimitry Andric Error BitcodeReader::parseOperandBundleTags() {
25930b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
25940b57cec5SDimitry Andric     return Err;
25950b57cec5SDimitry Andric 
25960b57cec5SDimitry Andric   if (!BundleTags.empty())
25970b57cec5SDimitry Andric     return error("Invalid multiple blocks");
25980b57cec5SDimitry Andric 
25990b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
26000b57cec5SDimitry Andric 
26010b57cec5SDimitry Andric   while (true) {
26020b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
26030b57cec5SDimitry Andric     if (!MaybeEntry)
26040b57cec5SDimitry Andric       return MaybeEntry.takeError();
26050b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
26060b57cec5SDimitry Andric 
26070b57cec5SDimitry Andric     switch (Entry.Kind) {
26080b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
26090b57cec5SDimitry Andric     case BitstreamEntry::Error:
26100b57cec5SDimitry Andric       return error("Malformed block");
26110b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
26120b57cec5SDimitry Andric       return Error::success();
26130b57cec5SDimitry Andric     case BitstreamEntry::Record:
26140b57cec5SDimitry Andric       // The interesting case.
26150b57cec5SDimitry Andric       break;
26160b57cec5SDimitry Andric     }
26170b57cec5SDimitry Andric 
26180b57cec5SDimitry Andric     // Tags are implicitly mapped to integers by their order.
26190b57cec5SDimitry Andric 
26200b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
26210b57cec5SDimitry Andric     if (!MaybeRecord)
26220b57cec5SDimitry Andric       return MaybeRecord.takeError();
26230b57cec5SDimitry Andric     if (MaybeRecord.get() != bitc::OPERAND_BUNDLE_TAG)
262481ad6265SDimitry Andric       return error("Invalid operand bundle record");
26250b57cec5SDimitry Andric 
26260b57cec5SDimitry Andric     // OPERAND_BUNDLE_TAG: [strchr x N]
26270b57cec5SDimitry Andric     BundleTags.emplace_back();
26280b57cec5SDimitry Andric     if (convertToString(Record, 0, BundleTags.back()))
262981ad6265SDimitry Andric       return error("Invalid operand bundle record");
26300b57cec5SDimitry Andric     Record.clear();
26310b57cec5SDimitry Andric   }
26320b57cec5SDimitry Andric }
26330b57cec5SDimitry Andric 
parseSyncScopeNames()26340b57cec5SDimitry Andric Error BitcodeReader::parseSyncScopeNames() {
26350b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID))
26360b57cec5SDimitry Andric     return Err;
26370b57cec5SDimitry Andric 
26380b57cec5SDimitry Andric   if (!SSIDs.empty())
26390b57cec5SDimitry Andric     return error("Invalid multiple synchronization scope names blocks");
26400b57cec5SDimitry Andric 
26410b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
26420b57cec5SDimitry Andric   while (true) {
26430b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
26440b57cec5SDimitry Andric     if (!MaybeEntry)
26450b57cec5SDimitry Andric       return MaybeEntry.takeError();
26460b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
26470b57cec5SDimitry Andric 
26480b57cec5SDimitry Andric     switch (Entry.Kind) {
26490b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
26500b57cec5SDimitry Andric     case BitstreamEntry::Error:
26510b57cec5SDimitry Andric       return error("Malformed block");
26520b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
26530b57cec5SDimitry Andric       if (SSIDs.empty())
26540b57cec5SDimitry Andric         return error("Invalid empty synchronization scope names block");
26550b57cec5SDimitry Andric       return Error::success();
26560b57cec5SDimitry Andric     case BitstreamEntry::Record:
26570b57cec5SDimitry Andric       // The interesting case.
26580b57cec5SDimitry Andric       break;
26590b57cec5SDimitry Andric     }
26600b57cec5SDimitry Andric 
26610b57cec5SDimitry Andric     // Synchronization scope names are implicitly mapped to synchronization
26620b57cec5SDimitry Andric     // scope IDs by their order.
26630b57cec5SDimitry Andric 
26640b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
26650b57cec5SDimitry Andric     if (!MaybeRecord)
26660b57cec5SDimitry Andric       return MaybeRecord.takeError();
26670b57cec5SDimitry Andric     if (MaybeRecord.get() != bitc::SYNC_SCOPE_NAME)
266881ad6265SDimitry Andric       return error("Invalid sync scope record");
26690b57cec5SDimitry Andric 
26700b57cec5SDimitry Andric     SmallString<16> SSN;
26710b57cec5SDimitry Andric     if (convertToString(Record, 0, SSN))
267281ad6265SDimitry Andric       return error("Invalid sync scope record");
26730b57cec5SDimitry Andric 
26740b57cec5SDimitry Andric     SSIDs.push_back(Context.getOrInsertSyncScopeID(SSN));
26750b57cec5SDimitry Andric     Record.clear();
26760b57cec5SDimitry Andric   }
26770b57cec5SDimitry Andric }
26780b57cec5SDimitry Andric 
26790b57cec5SDimitry Andric /// Associate a value with its name from the given index in the provided record.
recordValue(SmallVectorImpl<uint64_t> & Record,unsigned NameIndex,Triple & TT)26800b57cec5SDimitry Andric Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
26810b57cec5SDimitry Andric                                              unsigned NameIndex, Triple &TT) {
26820b57cec5SDimitry Andric   SmallString<128> ValueName;
26830b57cec5SDimitry Andric   if (convertToString(Record, NameIndex, ValueName))
26840b57cec5SDimitry Andric     return error("Invalid record");
26850b57cec5SDimitry Andric   unsigned ValueID = Record[0];
26860b57cec5SDimitry Andric   if (ValueID >= ValueList.size() || !ValueList[ValueID])
26870b57cec5SDimitry Andric     return error("Invalid record");
26880b57cec5SDimitry Andric   Value *V = ValueList[ValueID];
26890b57cec5SDimitry Andric 
26900b57cec5SDimitry Andric   StringRef NameStr(ValueName.data(), ValueName.size());
2691c9157d92SDimitry Andric   if (NameStr.contains(0))
26920b57cec5SDimitry Andric     return error("Invalid value name");
26930b57cec5SDimitry Andric   V->setName(NameStr);
26940b57cec5SDimitry Andric   auto *GO = dyn_cast<GlobalObject>(V);
26950eae32dcSDimitry Andric   if (GO && ImplicitComdatObjects.contains(GO) && TT.supportsCOMDAT())
26960b57cec5SDimitry Andric     GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
26970b57cec5SDimitry Andric   return V;
26980b57cec5SDimitry Andric }
26990b57cec5SDimitry Andric 
27000b57cec5SDimitry Andric /// Helper to note and return the current location, and jump to the given
27010b57cec5SDimitry Andric /// offset.
jumpToValueSymbolTable(uint64_t Offset,BitstreamCursor & Stream)27020b57cec5SDimitry Andric static Expected<uint64_t> jumpToValueSymbolTable(uint64_t Offset,
27030b57cec5SDimitry Andric                                                  BitstreamCursor &Stream) {
27040b57cec5SDimitry Andric   // Save the current parsing location so we can jump back at the end
27050b57cec5SDimitry Andric   // of the VST read.
27060b57cec5SDimitry Andric   uint64_t CurrentBit = Stream.GetCurrentBitNo();
27070b57cec5SDimitry Andric   if (Error JumpFailed = Stream.JumpToBit(Offset * 32))
27080b57cec5SDimitry Andric     return std::move(JumpFailed);
27090b57cec5SDimitry Andric   Expected<BitstreamEntry> MaybeEntry = Stream.advance();
27100b57cec5SDimitry Andric   if (!MaybeEntry)
27110b57cec5SDimitry Andric     return MaybeEntry.takeError();
271281ad6265SDimitry Andric   if (MaybeEntry.get().Kind != BitstreamEntry::SubBlock ||
271381ad6265SDimitry Andric       MaybeEntry.get().ID != bitc::VALUE_SYMTAB_BLOCK_ID)
271481ad6265SDimitry Andric     return error("Expected value symbol table subblock");
27150b57cec5SDimitry Andric   return CurrentBit;
27160b57cec5SDimitry Andric }
27170b57cec5SDimitry Andric 
setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta,Function * F,ArrayRef<uint64_t> Record)27180b57cec5SDimitry Andric void BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta,
27190b57cec5SDimitry Andric                                             Function *F,
27200b57cec5SDimitry Andric                                             ArrayRef<uint64_t> Record) {
27210b57cec5SDimitry Andric   // Note that we subtract 1 here because the offset is relative to one word
27220b57cec5SDimitry Andric   // before the start of the identification or module block, which was
27230b57cec5SDimitry Andric   // historically always the start of the regular bitcode header.
27240b57cec5SDimitry Andric   uint64_t FuncWordOffset = Record[1] - 1;
27250b57cec5SDimitry Andric   uint64_t FuncBitOffset = FuncWordOffset * 32;
27260b57cec5SDimitry Andric   DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
27270b57cec5SDimitry Andric   // Set the LastFunctionBlockBit to point to the last function block.
27280b57cec5SDimitry Andric   // Later when parsing is resumed after function materialization,
27290b57cec5SDimitry Andric   // we can simply skip that last function block.
27300b57cec5SDimitry Andric   if (FuncBitOffset > LastFunctionBlockBit)
27310b57cec5SDimitry Andric     LastFunctionBlockBit = FuncBitOffset;
27320b57cec5SDimitry Andric }
27330b57cec5SDimitry Andric 
27340b57cec5SDimitry Andric /// Read a new-style GlobalValue symbol table.
parseGlobalValueSymbolTable()27350b57cec5SDimitry Andric Error BitcodeReader::parseGlobalValueSymbolTable() {
27360b57cec5SDimitry Andric   unsigned FuncBitcodeOffsetDelta =
27370b57cec5SDimitry Andric       Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
27380b57cec5SDimitry Andric 
27390b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
27400b57cec5SDimitry Andric     return Err;
27410b57cec5SDimitry Andric 
27420b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
27430b57cec5SDimitry Andric   while (true) {
27440b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
27450b57cec5SDimitry Andric     if (!MaybeEntry)
27460b57cec5SDimitry Andric       return MaybeEntry.takeError();
27470b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
27480b57cec5SDimitry Andric 
27490b57cec5SDimitry Andric     switch (Entry.Kind) {
27500b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
27510b57cec5SDimitry Andric     case BitstreamEntry::Error:
27520b57cec5SDimitry Andric       return error("Malformed block");
27530b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
27540b57cec5SDimitry Andric       return Error::success();
27550b57cec5SDimitry Andric     case BitstreamEntry::Record:
27560b57cec5SDimitry Andric       break;
27570b57cec5SDimitry Andric     }
27580b57cec5SDimitry Andric 
27590b57cec5SDimitry Andric     Record.clear();
27600b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
27610b57cec5SDimitry Andric     if (!MaybeRecord)
27620b57cec5SDimitry Andric       return MaybeRecord.takeError();
27630b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
276481ad6265SDimitry Andric     case bitc::VST_CODE_FNENTRY: { // [valueid, offset]
276581ad6265SDimitry Andric       unsigned ValueID = Record[0];
276681ad6265SDimitry Andric       if (ValueID >= ValueList.size() || !ValueList[ValueID])
276781ad6265SDimitry Andric         return error("Invalid value reference in symbol table");
27680b57cec5SDimitry Andric       setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
276981ad6265SDimitry Andric                               cast<Function>(ValueList[ValueID]), Record);
27700b57cec5SDimitry Andric       break;
27710b57cec5SDimitry Andric     }
27720b57cec5SDimitry Andric     }
27730b57cec5SDimitry Andric   }
277481ad6265SDimitry Andric }
27750b57cec5SDimitry Andric 
27760b57cec5SDimitry Andric /// Parse the value symbol table at either the current parsing location or
27770b57cec5SDimitry Andric /// at the given bit offset if provided.
parseValueSymbolTable(uint64_t Offset)27780b57cec5SDimitry Andric Error BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
27790b57cec5SDimitry Andric   uint64_t CurrentBit;
27800b57cec5SDimitry Andric   // Pass in the Offset to distinguish between calling for the module-level
27810b57cec5SDimitry Andric   // VST (where we want to jump to the VST offset) and the function-level
27820b57cec5SDimitry Andric   // VST (where we don't).
27830b57cec5SDimitry Andric   if (Offset > 0) {
27840b57cec5SDimitry Andric     Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream);
27850b57cec5SDimitry Andric     if (!MaybeCurrentBit)
27860b57cec5SDimitry Andric       return MaybeCurrentBit.takeError();
27870b57cec5SDimitry Andric     CurrentBit = MaybeCurrentBit.get();
27880b57cec5SDimitry Andric     // If this module uses a string table, read this as a module-level VST.
27890b57cec5SDimitry Andric     if (UseStrtab) {
27900b57cec5SDimitry Andric       if (Error Err = parseGlobalValueSymbolTable())
27910b57cec5SDimitry Andric         return Err;
27920b57cec5SDimitry Andric       if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
27930b57cec5SDimitry Andric         return JumpFailed;
27940b57cec5SDimitry Andric       return Error::success();
27950b57cec5SDimitry Andric     }
27960b57cec5SDimitry Andric     // Otherwise, the VST will be in a similar format to a function-level VST,
27970b57cec5SDimitry Andric     // and will contain symbol names.
27980b57cec5SDimitry Andric   }
27990b57cec5SDimitry Andric 
28000b57cec5SDimitry Andric   // Compute the delta between the bitcode indices in the VST (the word offset
28010b57cec5SDimitry Andric   // to the word-aligned ENTER_SUBBLOCK for the function block, and that
28020b57cec5SDimitry Andric   // expected by the lazy reader. The reader's EnterSubBlock expects to have
28030b57cec5SDimitry Andric   // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
28040b57cec5SDimitry Andric   // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
28050b57cec5SDimitry Andric   // just before entering the VST subblock because: 1) the EnterSubBlock
28060b57cec5SDimitry Andric   // changes the AbbrevID width; 2) the VST block is nested within the same
28070b57cec5SDimitry Andric   // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
28080b57cec5SDimitry Andric   // AbbrevID width before calling EnterSubBlock; and 3) when we want to
28090b57cec5SDimitry Andric   // jump to the FUNCTION_BLOCK using this offset later, we don't want
28100b57cec5SDimitry Andric   // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
28110b57cec5SDimitry Andric   unsigned FuncBitcodeOffsetDelta =
28120b57cec5SDimitry Andric       Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
28130b57cec5SDimitry Andric 
28140b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
28150b57cec5SDimitry Andric     return Err;
28160b57cec5SDimitry Andric 
28170b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
28180b57cec5SDimitry Andric 
28190b57cec5SDimitry Andric   Triple TT(TheModule->getTargetTriple());
28200b57cec5SDimitry Andric 
28210b57cec5SDimitry Andric   // Read all the records for this value table.
28220b57cec5SDimitry Andric   SmallString<128> ValueName;
28230b57cec5SDimitry Andric 
28240b57cec5SDimitry Andric   while (true) {
28250b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
28260b57cec5SDimitry Andric     if (!MaybeEntry)
28270b57cec5SDimitry Andric       return MaybeEntry.takeError();
28280b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
28290b57cec5SDimitry Andric 
28300b57cec5SDimitry Andric     switch (Entry.Kind) {
28310b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
28320b57cec5SDimitry Andric     case BitstreamEntry::Error:
28330b57cec5SDimitry Andric       return error("Malformed block");
28340b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
28350b57cec5SDimitry Andric       if (Offset > 0)
28360b57cec5SDimitry Andric         if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
28370b57cec5SDimitry Andric           return JumpFailed;
28380b57cec5SDimitry Andric       return Error::success();
28390b57cec5SDimitry Andric     case BitstreamEntry::Record:
28400b57cec5SDimitry Andric       // The interesting case.
28410b57cec5SDimitry Andric       break;
28420b57cec5SDimitry Andric     }
28430b57cec5SDimitry Andric 
28440b57cec5SDimitry Andric     // Read a record.
28450b57cec5SDimitry Andric     Record.clear();
28460b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
28470b57cec5SDimitry Andric     if (!MaybeRecord)
28480b57cec5SDimitry Andric       return MaybeRecord.takeError();
28490b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
28500b57cec5SDimitry Andric     default:  // Default behavior: unknown type.
28510b57cec5SDimitry Andric       break;
28520b57cec5SDimitry Andric     case bitc::VST_CODE_ENTRY: {  // VST_CODE_ENTRY: [valueid, namechar x N]
28530b57cec5SDimitry Andric       Expected<Value *> ValOrErr = recordValue(Record, 1, TT);
28540b57cec5SDimitry Andric       if (Error Err = ValOrErr.takeError())
28550b57cec5SDimitry Andric         return Err;
28560b57cec5SDimitry Andric       ValOrErr.get();
28570b57cec5SDimitry Andric       break;
28580b57cec5SDimitry Andric     }
28590b57cec5SDimitry Andric     case bitc::VST_CODE_FNENTRY: {
28600b57cec5SDimitry Andric       // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
28610b57cec5SDimitry Andric       Expected<Value *> ValOrErr = recordValue(Record, 2, TT);
28620b57cec5SDimitry Andric       if (Error Err = ValOrErr.takeError())
28630b57cec5SDimitry Andric         return Err;
28640b57cec5SDimitry Andric       Value *V = ValOrErr.get();
28650b57cec5SDimitry Andric 
28660b57cec5SDimitry Andric       // Ignore function offsets emitted for aliases of functions in older
28670b57cec5SDimitry Andric       // versions of LLVM.
28680b57cec5SDimitry Andric       if (auto *F = dyn_cast<Function>(V))
28690b57cec5SDimitry Andric         setDeferredFunctionInfo(FuncBitcodeOffsetDelta, F, Record);
28700b57cec5SDimitry Andric       break;
28710b57cec5SDimitry Andric     }
28720b57cec5SDimitry Andric     case bitc::VST_CODE_BBENTRY: {
28730b57cec5SDimitry Andric       if (convertToString(Record, 1, ValueName))
287481ad6265SDimitry Andric         return error("Invalid bbentry record");
28750b57cec5SDimitry Andric       BasicBlock *BB = getBasicBlock(Record[0]);
28760b57cec5SDimitry Andric       if (!BB)
287781ad6265SDimitry Andric         return error("Invalid bbentry record");
28780b57cec5SDimitry Andric 
28790b57cec5SDimitry Andric       BB->setName(StringRef(ValueName.data(), ValueName.size()));
28800b57cec5SDimitry Andric       ValueName.clear();
28810b57cec5SDimitry Andric       break;
28820b57cec5SDimitry Andric     }
28830b57cec5SDimitry Andric     }
28840b57cec5SDimitry Andric   }
28850b57cec5SDimitry Andric }
28860b57cec5SDimitry Andric 
28870b57cec5SDimitry Andric /// Decode a signed value stored with the sign bit in the LSB for dense VBR
28880b57cec5SDimitry Andric /// encoding.
decodeSignRotatedValue(uint64_t V)28890b57cec5SDimitry Andric uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
28900b57cec5SDimitry Andric   if ((V & 1) == 0)
28910b57cec5SDimitry Andric     return V >> 1;
28920b57cec5SDimitry Andric   if (V != 1)
28930b57cec5SDimitry Andric     return -(V >> 1);
28940b57cec5SDimitry Andric   // There is no such thing as -0 with integers.  "-0" really means MININT.
28950b57cec5SDimitry Andric   return 1ULL << 63;
28960b57cec5SDimitry Andric }
28970b57cec5SDimitry Andric 
28980b57cec5SDimitry Andric /// Resolve all of the initializers for global values and aliases that we can.
resolveGlobalAndIndirectSymbolInits()28990b57cec5SDimitry Andric Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
29000b57cec5SDimitry Andric   std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist;
2901349cc55cSDimitry Andric   std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInitWorklist;
2902349cc55cSDimitry Andric   std::vector<FunctionOperandInfo> FunctionOperandWorklist;
29030b57cec5SDimitry Andric 
29040b57cec5SDimitry Andric   GlobalInitWorklist.swap(GlobalInits);
29050b57cec5SDimitry Andric   IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
2906349cc55cSDimitry Andric   FunctionOperandWorklist.swap(FunctionOperands);
29070b57cec5SDimitry Andric 
29080b57cec5SDimitry Andric   while (!GlobalInitWorklist.empty()) {
29090b57cec5SDimitry Andric     unsigned ValID = GlobalInitWorklist.back().second;
29100b57cec5SDimitry Andric     if (ValID >= ValueList.size()) {
29110b57cec5SDimitry Andric       // Not ready to resolve this yet, it requires something later in the file.
29120b57cec5SDimitry Andric       GlobalInits.push_back(GlobalInitWorklist.back());
29130b57cec5SDimitry Andric     } else {
291481ad6265SDimitry Andric       Expected<Constant *> MaybeC = getValueForInitializer(ValID);
291581ad6265SDimitry Andric       if (!MaybeC)
291681ad6265SDimitry Andric         return MaybeC.takeError();
291781ad6265SDimitry Andric       GlobalInitWorklist.back().first->setInitializer(MaybeC.get());
29180b57cec5SDimitry Andric     }
29190b57cec5SDimitry Andric     GlobalInitWorklist.pop_back();
29200b57cec5SDimitry Andric   }
29210b57cec5SDimitry Andric 
29220b57cec5SDimitry Andric   while (!IndirectSymbolInitWorklist.empty()) {
29230b57cec5SDimitry Andric     unsigned ValID = IndirectSymbolInitWorklist.back().second;
29240b57cec5SDimitry Andric     if (ValID >= ValueList.size()) {
29250b57cec5SDimitry Andric       IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
29260b57cec5SDimitry Andric     } else {
292781ad6265SDimitry Andric       Expected<Constant *> MaybeC = getValueForInitializer(ValID);
292881ad6265SDimitry Andric       if (!MaybeC)
292981ad6265SDimitry Andric         return MaybeC.takeError();
293081ad6265SDimitry Andric       Constant *C = MaybeC.get();
2931349cc55cSDimitry Andric       GlobalValue *GV = IndirectSymbolInitWorklist.back().first;
2932349cc55cSDimitry Andric       if (auto *GA = dyn_cast<GlobalAlias>(GV)) {
2933349cc55cSDimitry Andric         if (C->getType() != GV->getType())
29340b57cec5SDimitry Andric           return error("Alias and aliasee types don't match");
2935349cc55cSDimitry Andric         GA->setAliasee(C);
2936349cc55cSDimitry Andric       } else if (auto *GI = dyn_cast<GlobalIFunc>(GV)) {
2937c9157d92SDimitry Andric         GI->setResolver(C);
2938349cc55cSDimitry Andric       } else {
2939349cc55cSDimitry Andric         return error("Expected an alias or an ifunc");
2940349cc55cSDimitry Andric       }
29410b57cec5SDimitry Andric     }
29420b57cec5SDimitry Andric     IndirectSymbolInitWorklist.pop_back();
29430b57cec5SDimitry Andric   }
29440b57cec5SDimitry Andric 
2945349cc55cSDimitry Andric   while (!FunctionOperandWorklist.empty()) {
2946349cc55cSDimitry Andric     FunctionOperandInfo &Info = FunctionOperandWorklist.back();
2947349cc55cSDimitry Andric     if (Info.PersonalityFn) {
2948349cc55cSDimitry Andric       unsigned ValID = Info.PersonalityFn - 1;
2949349cc55cSDimitry Andric       if (ValID < ValueList.size()) {
295081ad6265SDimitry Andric         Expected<Constant *> MaybeC = getValueForInitializer(ValID);
295181ad6265SDimitry Andric         if (!MaybeC)
295281ad6265SDimitry Andric           return MaybeC.takeError();
295381ad6265SDimitry Andric         Info.F->setPersonalityFn(MaybeC.get());
2954349cc55cSDimitry Andric         Info.PersonalityFn = 0;
29550b57cec5SDimitry Andric       }
29560b57cec5SDimitry Andric     }
2957349cc55cSDimitry Andric     if (Info.Prefix) {
2958349cc55cSDimitry Andric       unsigned ValID = Info.Prefix - 1;
2959349cc55cSDimitry Andric       if (ValID < ValueList.size()) {
296081ad6265SDimitry Andric         Expected<Constant *> MaybeC = getValueForInitializer(ValID);
296181ad6265SDimitry Andric         if (!MaybeC)
296281ad6265SDimitry Andric           return MaybeC.takeError();
296381ad6265SDimitry Andric         Info.F->setPrefixData(MaybeC.get());
2964349cc55cSDimitry Andric         Info.Prefix = 0;
29650b57cec5SDimitry Andric       }
29660b57cec5SDimitry Andric     }
2967349cc55cSDimitry Andric     if (Info.Prologue) {
2968349cc55cSDimitry Andric       unsigned ValID = Info.Prologue - 1;
2969349cc55cSDimitry Andric       if (ValID < ValueList.size()) {
297081ad6265SDimitry Andric         Expected<Constant *> MaybeC = getValueForInitializer(ValID);
297181ad6265SDimitry Andric         if (!MaybeC)
297281ad6265SDimitry Andric           return MaybeC.takeError();
297381ad6265SDimitry Andric         Info.F->setPrologueData(MaybeC.get());
2974349cc55cSDimitry Andric         Info.Prologue = 0;
29750b57cec5SDimitry Andric       }
2976349cc55cSDimitry Andric     }
2977349cc55cSDimitry Andric     if (Info.PersonalityFn || Info.Prefix || Info.Prologue)
2978349cc55cSDimitry Andric       FunctionOperands.push_back(Info);
2979349cc55cSDimitry Andric     FunctionOperandWorklist.pop_back();
29800b57cec5SDimitry Andric   }
29810b57cec5SDimitry Andric 
29820b57cec5SDimitry Andric   return Error::success();
29830b57cec5SDimitry Andric }
29840b57cec5SDimitry Andric 
readWideAPInt(ArrayRef<uint64_t> Vals,unsigned TypeBits)29855ffd83dbSDimitry Andric APInt llvm::readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
29860b57cec5SDimitry Andric   SmallVector<uint64_t, 8> Words(Vals.size());
29870b57cec5SDimitry Andric   transform(Vals, Words.begin(),
29880b57cec5SDimitry Andric                  BitcodeReader::decodeSignRotatedValue);
29890b57cec5SDimitry Andric 
29900b57cec5SDimitry Andric   return APInt(TypeBits, Words);
29910b57cec5SDimitry Andric }
29920b57cec5SDimitry Andric 
parseConstants()29930b57cec5SDimitry Andric Error BitcodeReader::parseConstants() {
29940b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
29950b57cec5SDimitry Andric     return Err;
29960b57cec5SDimitry Andric 
29970b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
29980b57cec5SDimitry Andric 
29990b57cec5SDimitry Andric   // Read all the records for this value table.
30000b57cec5SDimitry Andric   Type *CurTy = Type::getInt32Ty(Context);
300181ad6265SDimitry Andric   unsigned Int32TyID = getVirtualTypeID(CurTy);
300281ad6265SDimitry Andric   unsigned CurTyID = Int32TyID;
300381ad6265SDimitry Andric   Type *CurElemTy = nullptr;
30040b57cec5SDimitry Andric   unsigned NextCstNo = ValueList.size();
30050b57cec5SDimitry Andric 
30060b57cec5SDimitry Andric   while (true) {
30070b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
30080b57cec5SDimitry Andric     if (!MaybeEntry)
30090b57cec5SDimitry Andric       return MaybeEntry.takeError();
30100b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
30110b57cec5SDimitry Andric 
30120b57cec5SDimitry Andric     switch (Entry.Kind) {
30130b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
30140b57cec5SDimitry Andric     case BitstreamEntry::Error:
30150b57cec5SDimitry Andric       return error("Malformed block");
30160b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
30170b57cec5SDimitry Andric       if (NextCstNo != ValueList.size())
30180b57cec5SDimitry Andric         return error("Invalid constant reference");
30190b57cec5SDimitry Andric       return Error::success();
30200b57cec5SDimitry Andric     case BitstreamEntry::Record:
30210b57cec5SDimitry Andric       // The interesting case.
30220b57cec5SDimitry Andric       break;
30230b57cec5SDimitry Andric     }
30240b57cec5SDimitry Andric 
30250b57cec5SDimitry Andric     // Read a record.
30260b57cec5SDimitry Andric     Record.clear();
30270b57cec5SDimitry Andric     Type *VoidType = Type::getVoidTy(Context);
30280b57cec5SDimitry Andric     Value *V = nullptr;
30290b57cec5SDimitry Andric     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
30300b57cec5SDimitry Andric     if (!MaybeBitCode)
30310b57cec5SDimitry Andric       return MaybeBitCode.takeError();
30320b57cec5SDimitry Andric     switch (unsigned BitCode = MaybeBitCode.get()) {
30330b57cec5SDimitry Andric     default:  // Default behavior: unknown constant
30340b57cec5SDimitry Andric     case bitc::CST_CODE_UNDEF:     // UNDEF
30350b57cec5SDimitry Andric       V = UndefValue::get(CurTy);
30360b57cec5SDimitry Andric       break;
3037e8d8bef9SDimitry Andric     case bitc::CST_CODE_POISON:    // POISON
3038e8d8bef9SDimitry Andric       V = PoisonValue::get(CurTy);
3039e8d8bef9SDimitry Andric       break;
30400b57cec5SDimitry Andric     case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
30410b57cec5SDimitry Andric       if (Record.empty())
304281ad6265SDimitry Andric         return error("Invalid settype record");
30430b57cec5SDimitry Andric       if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
304481ad6265SDimitry Andric         return error("Invalid settype record");
30450b57cec5SDimitry Andric       if (TypeList[Record[0]] == VoidType)
30460b57cec5SDimitry Andric         return error("Invalid constant type");
304781ad6265SDimitry Andric       CurTyID = Record[0];
304881ad6265SDimitry Andric       CurTy = TypeList[CurTyID];
304981ad6265SDimitry Andric       CurElemTy = getPtrElementTypeByID(CurTyID);
30500b57cec5SDimitry Andric       continue;  // Skip the ValueList manipulation.
30510b57cec5SDimitry Andric     case bitc::CST_CODE_NULL:      // NULL
30528bcb0991SDimitry Andric       if (CurTy->isVoidTy() || CurTy->isFunctionTy() || CurTy->isLabelTy())
30538bcb0991SDimitry Andric         return error("Invalid type for a constant null value");
3054bdd1243dSDimitry Andric       if (auto *TETy = dyn_cast<TargetExtType>(CurTy))
3055bdd1243dSDimitry Andric         if (!TETy->hasProperty(TargetExtType::HasZeroInit))
3056bdd1243dSDimitry Andric           return error("Invalid type for a constant null value");
30570b57cec5SDimitry Andric       V = Constant::getNullValue(CurTy);
30580b57cec5SDimitry Andric       break;
30590b57cec5SDimitry Andric     case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
30600b57cec5SDimitry Andric       if (!CurTy->isIntegerTy() || Record.empty())
306181ad6265SDimitry Andric         return error("Invalid integer const record");
30620b57cec5SDimitry Andric       V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
30630b57cec5SDimitry Andric       break;
30640b57cec5SDimitry Andric     case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
30650b57cec5SDimitry Andric       if (!CurTy->isIntegerTy() || Record.empty())
306681ad6265SDimitry Andric         return error("Invalid wide integer const record");
30670b57cec5SDimitry Andric 
30680b57cec5SDimitry Andric       APInt VInt =
30690b57cec5SDimitry Andric           readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
30700b57cec5SDimitry Andric       V = ConstantInt::get(Context, VInt);
30710b57cec5SDimitry Andric 
30720b57cec5SDimitry Andric       break;
30730b57cec5SDimitry Andric     }
30740b57cec5SDimitry Andric     case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
30750b57cec5SDimitry Andric       if (Record.empty())
307681ad6265SDimitry Andric         return error("Invalid float const record");
30770b57cec5SDimitry Andric       if (CurTy->isHalfTy())
30780b57cec5SDimitry Andric         V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf(),
30790b57cec5SDimitry Andric                                              APInt(16, (uint16_t)Record[0])));
30805ffd83dbSDimitry Andric       else if (CurTy->isBFloatTy())
30815ffd83dbSDimitry Andric         V = ConstantFP::get(Context, APFloat(APFloat::BFloat(),
30825ffd83dbSDimitry Andric                                              APInt(16, (uint32_t)Record[0])));
30830b57cec5SDimitry Andric       else if (CurTy->isFloatTy())
30840b57cec5SDimitry Andric         V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle(),
30850b57cec5SDimitry Andric                                              APInt(32, (uint32_t)Record[0])));
30860b57cec5SDimitry Andric       else if (CurTy->isDoubleTy())
30870b57cec5SDimitry Andric         V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble(),
30880b57cec5SDimitry Andric                                              APInt(64, Record[0])));
30890b57cec5SDimitry Andric       else if (CurTy->isX86_FP80Ty()) {
30900b57cec5SDimitry Andric         // Bits are not stored the same way as a normal i80 APInt, compensate.
30910b57cec5SDimitry Andric         uint64_t Rearrange[2];
30920b57cec5SDimitry Andric         Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
30930b57cec5SDimitry Andric         Rearrange[1] = Record[0] >> 48;
30940b57cec5SDimitry Andric         V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended(),
30950b57cec5SDimitry Andric                                              APInt(80, Rearrange)));
30960b57cec5SDimitry Andric       } else if (CurTy->isFP128Ty())
30970b57cec5SDimitry Andric         V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad(),
30980b57cec5SDimitry Andric                                              APInt(128, Record)));
30990b57cec5SDimitry Andric       else if (CurTy->isPPC_FP128Ty())
31000b57cec5SDimitry Andric         V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble(),
31010b57cec5SDimitry Andric                                              APInt(128, Record)));
31020b57cec5SDimitry Andric       else
31030b57cec5SDimitry Andric         V = UndefValue::get(CurTy);
31040b57cec5SDimitry Andric       break;
31050b57cec5SDimitry Andric     }
31060b57cec5SDimitry Andric 
31070b57cec5SDimitry Andric     case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
31080b57cec5SDimitry Andric       if (Record.empty())
310981ad6265SDimitry Andric         return error("Invalid aggregate record");
31100b57cec5SDimitry Andric 
31110b57cec5SDimitry Andric       unsigned Size = Record.size();
311281ad6265SDimitry Andric       SmallVector<unsigned, 16> Elts;
311381ad6265SDimitry Andric       for (unsigned i = 0; i != Size; ++i)
311481ad6265SDimitry Andric         Elts.push_back(Record[i]);
31150b57cec5SDimitry Andric 
311681ad6265SDimitry Andric       if (isa<StructType>(CurTy)) {
311781ad6265SDimitry Andric         V = BitcodeConstant::create(
311881ad6265SDimitry Andric             Alloc, CurTy, BitcodeConstant::ConstantStructOpcode, Elts);
311981ad6265SDimitry Andric       } else if (isa<ArrayType>(CurTy)) {
312081ad6265SDimitry Andric         V = BitcodeConstant::create(Alloc, CurTy,
312181ad6265SDimitry Andric                                     BitcodeConstant::ConstantArrayOpcode, Elts);
312281ad6265SDimitry Andric       } else if (isa<VectorType>(CurTy)) {
312381ad6265SDimitry Andric         V = BitcodeConstant::create(
312481ad6265SDimitry Andric             Alloc, CurTy, BitcodeConstant::ConstantVectorOpcode, Elts);
31250b57cec5SDimitry Andric       } else {
31260b57cec5SDimitry Andric         V = UndefValue::get(CurTy);
31270b57cec5SDimitry Andric       }
31280b57cec5SDimitry Andric       break;
31290b57cec5SDimitry Andric     }
31300b57cec5SDimitry Andric     case bitc::CST_CODE_STRING:    // STRING: [values]
31310b57cec5SDimitry Andric     case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
31320b57cec5SDimitry Andric       if (Record.empty())
313381ad6265SDimitry Andric         return error("Invalid string record");
31340b57cec5SDimitry Andric 
31350b57cec5SDimitry Andric       SmallString<16> Elts(Record.begin(), Record.end());
31360b57cec5SDimitry Andric       V = ConstantDataArray::getString(Context, Elts,
31370b57cec5SDimitry Andric                                        BitCode == bitc::CST_CODE_CSTRING);
31380b57cec5SDimitry Andric       break;
31390b57cec5SDimitry Andric     }
31400b57cec5SDimitry Andric     case bitc::CST_CODE_DATA: {// DATA: [n x value]
31410b57cec5SDimitry Andric       if (Record.empty())
314281ad6265SDimitry Andric         return error("Invalid data record");
31430b57cec5SDimitry Andric 
31445ffd83dbSDimitry Andric       Type *EltTy;
31455ffd83dbSDimitry Andric       if (auto *Array = dyn_cast<ArrayType>(CurTy))
31465ffd83dbSDimitry Andric         EltTy = Array->getElementType();
31475ffd83dbSDimitry Andric       else
31485ffd83dbSDimitry Andric         EltTy = cast<VectorType>(CurTy)->getElementType();
31490b57cec5SDimitry Andric       if (EltTy->isIntegerTy(8)) {
31500b57cec5SDimitry Andric         SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
31510b57cec5SDimitry Andric         if (isa<VectorType>(CurTy))
31520b57cec5SDimitry Andric           V = ConstantDataVector::get(Context, Elts);
31530b57cec5SDimitry Andric         else
31540b57cec5SDimitry Andric           V = ConstantDataArray::get(Context, Elts);
31550b57cec5SDimitry Andric       } else if (EltTy->isIntegerTy(16)) {
31560b57cec5SDimitry Andric         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
31570b57cec5SDimitry Andric         if (isa<VectorType>(CurTy))
31580b57cec5SDimitry Andric           V = ConstantDataVector::get(Context, Elts);
31590b57cec5SDimitry Andric         else
31600b57cec5SDimitry Andric           V = ConstantDataArray::get(Context, Elts);
31610b57cec5SDimitry Andric       } else if (EltTy->isIntegerTy(32)) {
31620b57cec5SDimitry Andric         SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
31630b57cec5SDimitry Andric         if (isa<VectorType>(CurTy))
31640b57cec5SDimitry Andric           V = ConstantDataVector::get(Context, Elts);
31650b57cec5SDimitry Andric         else
31660b57cec5SDimitry Andric           V = ConstantDataArray::get(Context, Elts);
31670b57cec5SDimitry Andric       } else if (EltTy->isIntegerTy(64)) {
31680b57cec5SDimitry Andric         SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
31690b57cec5SDimitry Andric         if (isa<VectorType>(CurTy))
31700b57cec5SDimitry Andric           V = ConstantDataVector::get(Context, Elts);
31710b57cec5SDimitry Andric         else
31720b57cec5SDimitry Andric           V = ConstantDataArray::get(Context, Elts);
31730b57cec5SDimitry Andric       } else if (EltTy->isHalfTy()) {
31740b57cec5SDimitry Andric         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
31750b57cec5SDimitry Andric         if (isa<VectorType>(CurTy))
31765ffd83dbSDimitry Andric           V = ConstantDataVector::getFP(EltTy, Elts);
31770b57cec5SDimitry Andric         else
31785ffd83dbSDimitry Andric           V = ConstantDataArray::getFP(EltTy, Elts);
31795ffd83dbSDimitry Andric       } else if (EltTy->isBFloatTy()) {
31805ffd83dbSDimitry Andric         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
31815ffd83dbSDimitry Andric         if (isa<VectorType>(CurTy))
31825ffd83dbSDimitry Andric           V = ConstantDataVector::getFP(EltTy, Elts);
31835ffd83dbSDimitry Andric         else
31845ffd83dbSDimitry Andric           V = ConstantDataArray::getFP(EltTy, Elts);
31850b57cec5SDimitry Andric       } else if (EltTy->isFloatTy()) {
31860b57cec5SDimitry Andric         SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
31870b57cec5SDimitry Andric         if (isa<VectorType>(CurTy))
31885ffd83dbSDimitry Andric           V = ConstantDataVector::getFP(EltTy, Elts);
31890b57cec5SDimitry Andric         else
31905ffd83dbSDimitry Andric           V = ConstantDataArray::getFP(EltTy, Elts);
31910b57cec5SDimitry Andric       } else if (EltTy->isDoubleTy()) {
31920b57cec5SDimitry Andric         SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
31930b57cec5SDimitry Andric         if (isa<VectorType>(CurTy))
31945ffd83dbSDimitry Andric           V = ConstantDataVector::getFP(EltTy, Elts);
31950b57cec5SDimitry Andric         else
31965ffd83dbSDimitry Andric           V = ConstantDataArray::getFP(EltTy, Elts);
31970b57cec5SDimitry Andric       } else {
31980b57cec5SDimitry Andric         return error("Invalid type for value");
31990b57cec5SDimitry Andric       }
32000b57cec5SDimitry Andric       break;
32010b57cec5SDimitry Andric     }
32020b57cec5SDimitry Andric     case bitc::CST_CODE_CE_UNOP: {  // CE_UNOP: [opcode, opval]
32030b57cec5SDimitry Andric       if (Record.size() < 2)
320481ad6265SDimitry Andric         return error("Invalid unary op constexpr record");
32050b57cec5SDimitry Andric       int Opc = getDecodedUnaryOpcode(Record[0], CurTy);
32060b57cec5SDimitry Andric       if (Opc < 0) {
32070b57cec5SDimitry Andric         V = UndefValue::get(CurTy);  // Unknown unop.
32080b57cec5SDimitry Andric       } else {
320981ad6265SDimitry Andric         V = BitcodeConstant::create(Alloc, CurTy, Opc, (unsigned)Record[1]);
32100b57cec5SDimitry Andric       }
32110b57cec5SDimitry Andric       break;
32120b57cec5SDimitry Andric     }
32130b57cec5SDimitry Andric     case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
32140b57cec5SDimitry Andric       if (Record.size() < 3)
321581ad6265SDimitry Andric         return error("Invalid binary op constexpr record");
32160b57cec5SDimitry Andric       int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
32170b57cec5SDimitry Andric       if (Opc < 0) {
32180b57cec5SDimitry Andric         V = UndefValue::get(CurTy);  // Unknown binop.
32190b57cec5SDimitry Andric       } else {
322081ad6265SDimitry Andric         uint8_t Flags = 0;
32210b57cec5SDimitry Andric         if (Record.size() >= 4) {
32220b57cec5SDimitry Andric           if (Opc == Instruction::Add ||
32230b57cec5SDimitry Andric               Opc == Instruction::Sub ||
32240b57cec5SDimitry Andric               Opc == Instruction::Mul ||
32250b57cec5SDimitry Andric               Opc == Instruction::Shl) {
32260b57cec5SDimitry Andric             if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
32270b57cec5SDimitry Andric               Flags |= OverflowingBinaryOperator::NoSignedWrap;
32280b57cec5SDimitry Andric             if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
32290b57cec5SDimitry Andric               Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
32300b57cec5SDimitry Andric           } else if (Opc == Instruction::SDiv ||
32310b57cec5SDimitry Andric                      Opc == Instruction::UDiv ||
32320b57cec5SDimitry Andric                      Opc == Instruction::LShr ||
32330b57cec5SDimitry Andric                      Opc == Instruction::AShr) {
32340b57cec5SDimitry Andric             if (Record[3] & (1 << bitc::PEO_EXACT))
3235c9157d92SDimitry Andric               Flags |= PossiblyExactOperator::IsExact;
32360b57cec5SDimitry Andric           }
32370b57cec5SDimitry Andric         }
323881ad6265SDimitry Andric         V = BitcodeConstant::create(Alloc, CurTy, {(uint8_t)Opc, Flags},
323981ad6265SDimitry Andric                                     {(unsigned)Record[1], (unsigned)Record[2]});
32400b57cec5SDimitry Andric       }
32410b57cec5SDimitry Andric       break;
32420b57cec5SDimitry Andric     }
32430b57cec5SDimitry Andric     case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
32440b57cec5SDimitry Andric       if (Record.size() < 3)
324581ad6265SDimitry Andric         return error("Invalid cast constexpr record");
32460b57cec5SDimitry Andric       int Opc = getDecodedCastOpcode(Record[0]);
32470b57cec5SDimitry Andric       if (Opc < 0) {
32480b57cec5SDimitry Andric         V = UndefValue::get(CurTy);  // Unknown cast.
32490b57cec5SDimitry Andric       } else {
325081ad6265SDimitry Andric         unsigned OpTyID = Record[1];
325181ad6265SDimitry Andric         Type *OpTy = getTypeByID(OpTyID);
32520b57cec5SDimitry Andric         if (!OpTy)
325381ad6265SDimitry Andric           return error("Invalid cast constexpr record");
325481ad6265SDimitry Andric         V = BitcodeConstant::create(Alloc, CurTy, Opc, (unsigned)Record[2]);
32550b57cec5SDimitry Andric       }
32560b57cec5SDimitry Andric       break;
32570b57cec5SDimitry Andric     }
32580b57cec5SDimitry Andric     case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands]
32590b57cec5SDimitry Andric     case bitc::CST_CODE_CE_GEP: // [ty, n x operands]
32600b57cec5SDimitry Andric     case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX: { // [ty, flags, n x
32610b57cec5SDimitry Andric                                                      // operands]
326281ad6265SDimitry Andric       if (Record.size() < 2)
326381ad6265SDimitry Andric         return error("Constant GEP record must have at least two elements");
32640b57cec5SDimitry Andric       unsigned OpNum = 0;
32650b57cec5SDimitry Andric       Type *PointeeType = nullptr;
32660b57cec5SDimitry Andric       if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX ||
32670b57cec5SDimitry Andric           Record.size() % 2)
32680b57cec5SDimitry Andric         PointeeType = getTypeByID(Record[OpNum++]);
32690b57cec5SDimitry Andric 
32700b57cec5SDimitry Andric       bool InBounds = false;
3271bdd1243dSDimitry Andric       std::optional<unsigned> InRangeIndex;
32720b57cec5SDimitry Andric       if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX) {
32730b57cec5SDimitry Andric         uint64_t Op = Record[OpNum++];
32740b57cec5SDimitry Andric         InBounds = Op & 1;
32750b57cec5SDimitry Andric         InRangeIndex = Op >> 1;
32760b57cec5SDimitry Andric       } else if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
32770b57cec5SDimitry Andric         InBounds = true;
32780b57cec5SDimitry Andric 
327981ad6265SDimitry Andric       SmallVector<unsigned, 16> Elts;
328081ad6265SDimitry Andric       unsigned BaseTypeID = Record[OpNum];
32810b57cec5SDimitry Andric       while (OpNum != Record.size()) {
328281ad6265SDimitry Andric         unsigned ElTyID = Record[OpNum++];
328381ad6265SDimitry Andric         Type *ElTy = getTypeByID(ElTyID);
32840b57cec5SDimitry Andric         if (!ElTy)
328581ad6265SDimitry Andric           return error("Invalid getelementptr constexpr record");
328681ad6265SDimitry Andric         Elts.push_back(Record[OpNum++]);
32870b57cec5SDimitry Andric       }
32880b57cec5SDimitry Andric 
32890b57cec5SDimitry Andric       if (Elts.size() < 1)
32900b57cec5SDimitry Andric         return error("Invalid gep with no operands");
32910b57cec5SDimitry Andric 
329281ad6265SDimitry Andric       Type *BaseType = getTypeByID(BaseTypeID);
329381ad6265SDimitry Andric       if (isa<VectorType>(BaseType)) {
329481ad6265SDimitry Andric         BaseTypeID = getContainedTypeID(BaseTypeID, 0);
329581ad6265SDimitry Andric         BaseType = getTypeByID(BaseTypeID);
329681ad6265SDimitry Andric       }
329781ad6265SDimitry Andric 
329881ad6265SDimitry Andric       PointerType *OrigPtrTy = dyn_cast_or_null<PointerType>(BaseType);
329981ad6265SDimitry Andric       if (!OrigPtrTy)
330081ad6265SDimitry Andric         return error("GEP base operand must be pointer or vector of pointer");
330181ad6265SDimitry Andric 
330281ad6265SDimitry Andric       if (!PointeeType) {
330381ad6265SDimitry Andric         PointeeType = getPtrElementTypeByID(BaseTypeID);
33040b57cec5SDimitry Andric         if (!PointeeType)
330581ad6265SDimitry Andric           return error("Missing element type for old-style constant GEP");
3306fe013be4SDimitry Andric       }
33070b57cec5SDimitry Andric 
330881ad6265SDimitry Andric       V = BitcodeConstant::create(Alloc, CurTy,
330981ad6265SDimitry Andric                                   {Instruction::GetElementPtr, InBounds,
331081ad6265SDimitry Andric                                    InRangeIndex.value_or(-1), PointeeType},
331181ad6265SDimitry Andric                                   Elts);
33120b57cec5SDimitry Andric       break;
33130b57cec5SDimitry Andric     }
33140b57cec5SDimitry Andric     case bitc::CST_CODE_CE_SELECT: {  // CE_SELECT: [opval#, opval#, opval#]
33150b57cec5SDimitry Andric       if (Record.size() < 3)
331681ad6265SDimitry Andric         return error("Invalid select constexpr record");
33170b57cec5SDimitry Andric 
331881ad6265SDimitry Andric       V = BitcodeConstant::create(
331981ad6265SDimitry Andric           Alloc, CurTy, Instruction::Select,
332081ad6265SDimitry Andric           {(unsigned)Record[0], (unsigned)Record[1], (unsigned)Record[2]});
332181ad6265SDimitry Andric       break;
33220b57cec5SDimitry Andric     }
33230b57cec5SDimitry Andric     case bitc::CST_CODE_CE_EXTRACTELT
33240b57cec5SDimitry Andric         : { // CE_EXTRACTELT: [opty, opval, opty, opval]
33250b57cec5SDimitry Andric       if (Record.size() < 3)
332681ad6265SDimitry Andric         return error("Invalid extractelement constexpr record");
332781ad6265SDimitry Andric       unsigned OpTyID = Record[0];
33280b57cec5SDimitry Andric       VectorType *OpTy =
332981ad6265SDimitry Andric         dyn_cast_or_null<VectorType>(getTypeByID(OpTyID));
33300b57cec5SDimitry Andric       if (!OpTy)
333181ad6265SDimitry Andric         return error("Invalid extractelement constexpr record");
333281ad6265SDimitry Andric       unsigned IdxRecord;
33330b57cec5SDimitry Andric       if (Record.size() == 4) {
333481ad6265SDimitry Andric         unsigned IdxTyID = Record[2];
333581ad6265SDimitry Andric         Type *IdxTy = getTypeByID(IdxTyID);
33360b57cec5SDimitry Andric         if (!IdxTy)
333781ad6265SDimitry Andric           return error("Invalid extractelement constexpr record");
333881ad6265SDimitry Andric         IdxRecord = Record[3];
33395ffd83dbSDimitry Andric       } else {
33405ffd83dbSDimitry Andric         // Deprecated, but still needed to read old bitcode files.
334181ad6265SDimitry Andric         IdxRecord = Record[2];
33425ffd83dbSDimitry Andric       }
334381ad6265SDimitry Andric       V = BitcodeConstant::create(Alloc, CurTy, Instruction::ExtractElement,
334481ad6265SDimitry Andric                                   {(unsigned)Record[1], IdxRecord});
33450b57cec5SDimitry Andric       break;
33460b57cec5SDimitry Andric     }
33470b57cec5SDimitry Andric     case bitc::CST_CODE_CE_INSERTELT
33480b57cec5SDimitry Andric         : { // CE_INSERTELT: [opval, opval, opty, opval]
33490b57cec5SDimitry Andric       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
33500b57cec5SDimitry Andric       if (Record.size() < 3 || !OpTy)
335181ad6265SDimitry Andric         return error("Invalid insertelement constexpr record");
335281ad6265SDimitry Andric       unsigned IdxRecord;
33530b57cec5SDimitry Andric       if (Record.size() == 4) {
335481ad6265SDimitry Andric         unsigned IdxTyID = Record[2];
335581ad6265SDimitry Andric         Type *IdxTy = getTypeByID(IdxTyID);
33560b57cec5SDimitry Andric         if (!IdxTy)
335781ad6265SDimitry Andric           return error("Invalid insertelement constexpr record");
335881ad6265SDimitry Andric         IdxRecord = Record[3];
33595ffd83dbSDimitry Andric       } else {
33605ffd83dbSDimitry Andric         // Deprecated, but still needed to read old bitcode files.
336181ad6265SDimitry Andric         IdxRecord = Record[2];
33625ffd83dbSDimitry Andric       }
336381ad6265SDimitry Andric       V = BitcodeConstant::create(
336481ad6265SDimitry Andric           Alloc, CurTy, Instruction::InsertElement,
336581ad6265SDimitry Andric           {(unsigned)Record[0], (unsigned)Record[1], IdxRecord});
33660b57cec5SDimitry Andric       break;
33670b57cec5SDimitry Andric     }
33680b57cec5SDimitry Andric     case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
33690b57cec5SDimitry Andric       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
33700b57cec5SDimitry Andric       if (Record.size() < 3 || !OpTy)
337181ad6265SDimitry Andric         return error("Invalid shufflevector constexpr record");
337281ad6265SDimitry Andric       V = BitcodeConstant::create(
337381ad6265SDimitry Andric           Alloc, CurTy, Instruction::ShuffleVector,
337481ad6265SDimitry Andric           {(unsigned)Record[0], (unsigned)Record[1], (unsigned)Record[2]});
337581ad6265SDimitry Andric       break;
33760b57cec5SDimitry Andric     }
33770b57cec5SDimitry Andric     case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
33780b57cec5SDimitry Andric       VectorType *RTy = dyn_cast<VectorType>(CurTy);
33790b57cec5SDimitry Andric       VectorType *OpTy =
33800b57cec5SDimitry Andric         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
33810b57cec5SDimitry Andric       if (Record.size() < 4 || !RTy || !OpTy)
338281ad6265SDimitry Andric         return error("Invalid shufflevector constexpr record");
338381ad6265SDimitry Andric       V = BitcodeConstant::create(
338481ad6265SDimitry Andric           Alloc, CurTy, Instruction::ShuffleVector,
338581ad6265SDimitry Andric           {(unsigned)Record[1], (unsigned)Record[2], (unsigned)Record[3]});
338681ad6265SDimitry Andric       break;
33870b57cec5SDimitry Andric     }
33880b57cec5SDimitry Andric     case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
33890b57cec5SDimitry Andric       if (Record.size() < 4)
339081ad6265SDimitry Andric         return error("Invalid cmp constexpt record");
339181ad6265SDimitry Andric       unsigned OpTyID = Record[0];
339281ad6265SDimitry Andric       Type *OpTy = getTypeByID(OpTyID);
33930b57cec5SDimitry Andric       if (!OpTy)
339481ad6265SDimitry Andric         return error("Invalid cmp constexpr record");
339581ad6265SDimitry Andric       V = BitcodeConstant::create(
339681ad6265SDimitry Andric           Alloc, CurTy,
339781ad6265SDimitry Andric           {(uint8_t)(OpTy->isFPOrFPVectorTy() ? Instruction::FCmp
339881ad6265SDimitry Andric                                               : Instruction::ICmp),
339981ad6265SDimitry Andric            (uint8_t)Record[3]},
340081ad6265SDimitry Andric           {(unsigned)Record[1], (unsigned)Record[2]});
34010b57cec5SDimitry Andric       break;
34020b57cec5SDimitry Andric     }
34030b57cec5SDimitry Andric     // This maintains backward compatibility, pre-asm dialect keywords.
34045ffd83dbSDimitry Andric     // Deprecated, but still needed to read old bitcode files.
34050b57cec5SDimitry Andric     case bitc::CST_CODE_INLINEASM_OLD: {
34060b57cec5SDimitry Andric       if (Record.size() < 2)
340781ad6265SDimitry Andric         return error("Invalid inlineasm record");
34080b57cec5SDimitry Andric       std::string AsmStr, ConstrStr;
34090b57cec5SDimitry Andric       bool HasSideEffects = Record[0] & 1;
34100b57cec5SDimitry Andric       bool IsAlignStack = Record[0] >> 1;
34110b57cec5SDimitry Andric       unsigned AsmStrSize = Record[1];
34120b57cec5SDimitry Andric       if (2+AsmStrSize >= Record.size())
341381ad6265SDimitry Andric         return error("Invalid inlineasm record");
34140b57cec5SDimitry Andric       unsigned ConstStrSize = Record[2+AsmStrSize];
34150b57cec5SDimitry Andric       if (3+AsmStrSize+ConstStrSize > Record.size())
341681ad6265SDimitry Andric         return error("Invalid inlineasm record");
34170b57cec5SDimitry Andric 
34180b57cec5SDimitry Andric       for (unsigned i = 0; i != AsmStrSize; ++i)
34190b57cec5SDimitry Andric         AsmStr += (char)Record[2+i];
34200b57cec5SDimitry Andric       for (unsigned i = 0; i != ConstStrSize; ++i)
34210b57cec5SDimitry Andric         ConstrStr += (char)Record[3+AsmStrSize+i];
34220b57cec5SDimitry Andric       UpgradeInlineAsmString(&AsmStr);
342381ad6265SDimitry Andric       if (!CurElemTy)
342481ad6265SDimitry Andric         return error("Missing element type for old-style inlineasm");
342581ad6265SDimitry Andric       V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr,
342681ad6265SDimitry Andric                          HasSideEffects, IsAlignStack);
34270b57cec5SDimitry Andric       break;
34280b57cec5SDimitry Andric     }
34290b57cec5SDimitry Andric     // This version adds support for the asm dialect keywords (e.g.,
34300b57cec5SDimitry Andric     // inteldialect).
3431fe6060f1SDimitry Andric     case bitc::CST_CODE_INLINEASM_OLD2: {
34320b57cec5SDimitry Andric       if (Record.size() < 2)
343381ad6265SDimitry Andric         return error("Invalid inlineasm record");
34340b57cec5SDimitry Andric       std::string AsmStr, ConstrStr;
34350b57cec5SDimitry Andric       bool HasSideEffects = Record[0] & 1;
34360b57cec5SDimitry Andric       bool IsAlignStack = (Record[0] >> 1) & 1;
34370b57cec5SDimitry Andric       unsigned AsmDialect = Record[0] >> 2;
34380b57cec5SDimitry Andric       unsigned AsmStrSize = Record[1];
34390b57cec5SDimitry Andric       if (2+AsmStrSize >= Record.size())
344081ad6265SDimitry Andric         return error("Invalid inlineasm record");
34410b57cec5SDimitry Andric       unsigned ConstStrSize = Record[2+AsmStrSize];
34420b57cec5SDimitry Andric       if (3+AsmStrSize+ConstStrSize > Record.size())
344381ad6265SDimitry Andric         return error("Invalid inlineasm record");
34440b57cec5SDimitry Andric 
34450b57cec5SDimitry Andric       for (unsigned i = 0; i != AsmStrSize; ++i)
34460b57cec5SDimitry Andric         AsmStr += (char)Record[2+i];
34470b57cec5SDimitry Andric       for (unsigned i = 0; i != ConstStrSize; ++i)
34480b57cec5SDimitry Andric         ConstrStr += (char)Record[3+AsmStrSize+i];
34490b57cec5SDimitry Andric       UpgradeInlineAsmString(&AsmStr);
345081ad6265SDimitry Andric       if (!CurElemTy)
345181ad6265SDimitry Andric         return error("Missing element type for old-style inlineasm");
345281ad6265SDimitry Andric       V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr,
345381ad6265SDimitry Andric                          HasSideEffects, IsAlignStack,
34540b57cec5SDimitry Andric                          InlineAsm::AsmDialect(AsmDialect));
34550b57cec5SDimitry Andric       break;
34560b57cec5SDimitry Andric     }
3457fe6060f1SDimitry Andric     // This version adds support for the unwind keyword.
345804eeddc0SDimitry Andric     case bitc::CST_CODE_INLINEASM_OLD3: {
3459fe6060f1SDimitry Andric       if (Record.size() < 2)
346081ad6265SDimitry Andric         return error("Invalid inlineasm record");
346104eeddc0SDimitry Andric       unsigned OpNum = 0;
3462fe6060f1SDimitry Andric       std::string AsmStr, ConstrStr;
346304eeddc0SDimitry Andric       bool HasSideEffects = Record[OpNum] & 1;
346404eeddc0SDimitry Andric       bool IsAlignStack = (Record[OpNum] >> 1) & 1;
346504eeddc0SDimitry Andric       unsigned AsmDialect = (Record[OpNum] >> 2) & 1;
346604eeddc0SDimitry Andric       bool CanThrow = (Record[OpNum] >> 3) & 1;
346704eeddc0SDimitry Andric       ++OpNum;
346804eeddc0SDimitry Andric       unsigned AsmStrSize = Record[OpNum];
346904eeddc0SDimitry Andric       ++OpNum;
347004eeddc0SDimitry Andric       if (OpNum + AsmStrSize >= Record.size())
347181ad6265SDimitry Andric         return error("Invalid inlineasm record");
347204eeddc0SDimitry Andric       unsigned ConstStrSize = Record[OpNum + AsmStrSize];
347304eeddc0SDimitry Andric       if (OpNum + 1 + AsmStrSize + ConstStrSize > Record.size())
347481ad6265SDimitry Andric         return error("Invalid inlineasm record");
3475fe6060f1SDimitry Andric 
3476fe6060f1SDimitry Andric       for (unsigned i = 0; i != AsmStrSize; ++i)
347704eeddc0SDimitry Andric         AsmStr += (char)Record[OpNum + i];
347804eeddc0SDimitry Andric       ++OpNum;
3479fe6060f1SDimitry Andric       for (unsigned i = 0; i != ConstStrSize; ++i)
348004eeddc0SDimitry Andric         ConstrStr += (char)Record[OpNum + AsmStrSize + i];
3481fe6060f1SDimitry Andric       UpgradeInlineAsmString(&AsmStr);
348281ad6265SDimitry Andric       if (!CurElemTy)
348381ad6265SDimitry Andric         return error("Missing element type for old-style inlineasm");
348481ad6265SDimitry Andric       V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr,
348581ad6265SDimitry Andric                          HasSideEffects, IsAlignStack,
3486fe6060f1SDimitry Andric                          InlineAsm::AsmDialect(AsmDialect), CanThrow);
3487fe6060f1SDimitry Andric       break;
3488fe6060f1SDimitry Andric     }
348904eeddc0SDimitry Andric     // This version adds explicit function type.
349004eeddc0SDimitry Andric     case bitc::CST_CODE_INLINEASM: {
349104eeddc0SDimitry Andric       if (Record.size() < 3)
349281ad6265SDimitry Andric         return error("Invalid inlineasm record");
349304eeddc0SDimitry Andric       unsigned OpNum = 0;
349404eeddc0SDimitry Andric       auto *FnTy = dyn_cast_or_null<FunctionType>(getTypeByID(Record[OpNum]));
349504eeddc0SDimitry Andric       ++OpNum;
349604eeddc0SDimitry Andric       if (!FnTy)
349781ad6265SDimitry Andric         return error("Invalid inlineasm record");
349804eeddc0SDimitry Andric       std::string AsmStr, ConstrStr;
349904eeddc0SDimitry Andric       bool HasSideEffects = Record[OpNum] & 1;
350004eeddc0SDimitry Andric       bool IsAlignStack = (Record[OpNum] >> 1) & 1;
350104eeddc0SDimitry Andric       unsigned AsmDialect = (Record[OpNum] >> 2) & 1;
350204eeddc0SDimitry Andric       bool CanThrow = (Record[OpNum] >> 3) & 1;
350304eeddc0SDimitry Andric       ++OpNum;
350404eeddc0SDimitry Andric       unsigned AsmStrSize = Record[OpNum];
350504eeddc0SDimitry Andric       ++OpNum;
350604eeddc0SDimitry Andric       if (OpNum + AsmStrSize >= Record.size())
350781ad6265SDimitry Andric         return error("Invalid inlineasm record");
350804eeddc0SDimitry Andric       unsigned ConstStrSize = Record[OpNum + AsmStrSize];
350904eeddc0SDimitry Andric       if (OpNum + 1 + AsmStrSize + ConstStrSize > Record.size())
351081ad6265SDimitry Andric         return error("Invalid inlineasm record");
351104eeddc0SDimitry Andric 
351204eeddc0SDimitry Andric       for (unsigned i = 0; i != AsmStrSize; ++i)
351304eeddc0SDimitry Andric         AsmStr += (char)Record[OpNum + i];
351404eeddc0SDimitry Andric       ++OpNum;
351504eeddc0SDimitry Andric       for (unsigned i = 0; i != ConstStrSize; ++i)
351604eeddc0SDimitry Andric         ConstrStr += (char)Record[OpNum + AsmStrSize + i];
351704eeddc0SDimitry Andric       UpgradeInlineAsmString(&AsmStr);
351804eeddc0SDimitry Andric       V = InlineAsm::get(FnTy, AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
351904eeddc0SDimitry Andric                          InlineAsm::AsmDialect(AsmDialect), CanThrow);
352004eeddc0SDimitry Andric       break;
352104eeddc0SDimitry Andric     }
35220b57cec5SDimitry Andric     case bitc::CST_CODE_BLOCKADDRESS:{
35230b57cec5SDimitry Andric       if (Record.size() < 3)
352481ad6265SDimitry Andric         return error("Invalid blockaddress record");
352581ad6265SDimitry Andric       unsigned FnTyID = Record[0];
352681ad6265SDimitry Andric       Type *FnTy = getTypeByID(FnTyID);
35270b57cec5SDimitry Andric       if (!FnTy)
352881ad6265SDimitry Andric         return error("Invalid blockaddress record");
352981ad6265SDimitry Andric       V = BitcodeConstant::create(
353081ad6265SDimitry Andric           Alloc, CurTy,
353181ad6265SDimitry Andric           {BitcodeConstant::BlockAddressOpcode, 0, (unsigned)Record[2]},
353281ad6265SDimitry Andric           Record[1]);
35330b57cec5SDimitry Andric       break;
35340b57cec5SDimitry Andric     }
3535fe6060f1SDimitry Andric     case bitc::CST_CODE_DSO_LOCAL_EQUIVALENT: {
3536fe6060f1SDimitry Andric       if (Record.size() < 2)
353781ad6265SDimitry Andric         return error("Invalid dso_local record");
353881ad6265SDimitry Andric       unsigned GVTyID = Record[0];
353981ad6265SDimitry Andric       Type *GVTy = getTypeByID(GVTyID);
3540fe6060f1SDimitry Andric       if (!GVTy)
354181ad6265SDimitry Andric         return error("Invalid dso_local record");
354281ad6265SDimitry Andric       V = BitcodeConstant::create(
354381ad6265SDimitry Andric           Alloc, CurTy, BitcodeConstant::DSOLocalEquivalentOpcode, Record[1]);
3544fe6060f1SDimitry Andric       break;
3545fe6060f1SDimitry Andric     }
35460eae32dcSDimitry Andric     case bitc::CST_CODE_NO_CFI_VALUE: {
35470eae32dcSDimitry Andric       if (Record.size() < 2)
354881ad6265SDimitry Andric         return error("Invalid no_cfi record");
354981ad6265SDimitry Andric       unsigned GVTyID = Record[0];
355081ad6265SDimitry Andric       Type *GVTy = getTypeByID(GVTyID);
35510eae32dcSDimitry Andric       if (!GVTy)
355281ad6265SDimitry Andric         return error("Invalid no_cfi record");
355381ad6265SDimitry Andric       V = BitcodeConstant::create(Alloc, CurTy, BitcodeConstant::NoCFIOpcode,
355481ad6265SDimitry Andric                                   Record[1]);
35550eae32dcSDimitry Andric       break;
35560eae32dcSDimitry Andric     }
35570b57cec5SDimitry Andric     }
35580b57cec5SDimitry Andric 
355981ad6265SDimitry Andric     assert(V->getType() == getTypeByID(CurTyID) && "Incorrect result type ID");
356081ad6265SDimitry Andric     if (Error Err = ValueList.assignValue(NextCstNo, V, CurTyID))
356181ad6265SDimitry Andric       return Err;
35620b57cec5SDimitry Andric     ++NextCstNo;
35630b57cec5SDimitry Andric   }
35640b57cec5SDimitry Andric }
35650b57cec5SDimitry Andric 
parseUseLists()35660b57cec5SDimitry Andric Error BitcodeReader::parseUseLists() {
35670b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
35680b57cec5SDimitry Andric     return Err;
35690b57cec5SDimitry Andric 
35700b57cec5SDimitry Andric   // Read all the records.
35710b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
35720b57cec5SDimitry Andric 
35730b57cec5SDimitry Andric   while (true) {
35740b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
35750b57cec5SDimitry Andric     if (!MaybeEntry)
35760b57cec5SDimitry Andric       return MaybeEntry.takeError();
35770b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
35780b57cec5SDimitry Andric 
35790b57cec5SDimitry Andric     switch (Entry.Kind) {
35800b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
35810b57cec5SDimitry Andric     case BitstreamEntry::Error:
35820b57cec5SDimitry Andric       return error("Malformed block");
35830b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
35840b57cec5SDimitry Andric       return Error::success();
35850b57cec5SDimitry Andric     case BitstreamEntry::Record:
35860b57cec5SDimitry Andric       // The interesting case.
35870b57cec5SDimitry Andric       break;
35880b57cec5SDimitry Andric     }
35890b57cec5SDimitry Andric 
35900b57cec5SDimitry Andric     // Read a use list record.
35910b57cec5SDimitry Andric     Record.clear();
35920b57cec5SDimitry Andric     bool IsBB = false;
35930b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
35940b57cec5SDimitry Andric     if (!MaybeRecord)
35950b57cec5SDimitry Andric       return MaybeRecord.takeError();
35960b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
35970b57cec5SDimitry Andric     default:  // Default behavior: unknown type.
35980b57cec5SDimitry Andric       break;
35990b57cec5SDimitry Andric     case bitc::USELIST_CODE_BB:
36000b57cec5SDimitry Andric       IsBB = true;
3601bdd1243dSDimitry Andric       [[fallthrough]];
36020b57cec5SDimitry Andric     case bitc::USELIST_CODE_DEFAULT: {
36030b57cec5SDimitry Andric       unsigned RecordLength = Record.size();
36040b57cec5SDimitry Andric       if (RecordLength < 3)
36050b57cec5SDimitry Andric         // Records should have at least an ID and two indexes.
36060b57cec5SDimitry Andric         return error("Invalid record");
3607e8d8bef9SDimitry Andric       unsigned ID = Record.pop_back_val();
36080b57cec5SDimitry Andric 
36090b57cec5SDimitry Andric       Value *V;
36100b57cec5SDimitry Andric       if (IsBB) {
36110b57cec5SDimitry Andric         assert(ID < FunctionBBs.size() && "Basic block not found");
36120b57cec5SDimitry Andric         V = FunctionBBs[ID];
36130b57cec5SDimitry Andric       } else
36140b57cec5SDimitry Andric         V = ValueList[ID];
36150b57cec5SDimitry Andric       unsigned NumUses = 0;
36160b57cec5SDimitry Andric       SmallDenseMap<const Use *, unsigned, 16> Order;
36170b57cec5SDimitry Andric       for (const Use &U : V->materialized_uses()) {
36180b57cec5SDimitry Andric         if (++NumUses > Record.size())
36190b57cec5SDimitry Andric           break;
36200b57cec5SDimitry Andric         Order[&U] = Record[NumUses - 1];
36210b57cec5SDimitry Andric       }
36220b57cec5SDimitry Andric       if (Order.size() != Record.size() || NumUses > Record.size())
36230b57cec5SDimitry Andric         // Mismatches can happen if the functions are being materialized lazily
36240b57cec5SDimitry Andric         // (out-of-order), or a value has been upgraded.
36250b57cec5SDimitry Andric         break;
36260b57cec5SDimitry Andric 
36270b57cec5SDimitry Andric       V->sortUseList([&](const Use &L, const Use &R) {
36280b57cec5SDimitry Andric         return Order.lookup(&L) < Order.lookup(&R);
36290b57cec5SDimitry Andric       });
36300b57cec5SDimitry Andric       break;
36310b57cec5SDimitry Andric     }
36320b57cec5SDimitry Andric     }
36330b57cec5SDimitry Andric   }
36340b57cec5SDimitry Andric }
36350b57cec5SDimitry Andric 
36360b57cec5SDimitry Andric /// When we see the block for metadata, remember where it is and then skip it.
36370b57cec5SDimitry Andric /// This lets us lazily deserialize the metadata.
rememberAndSkipMetadata()36380b57cec5SDimitry Andric Error BitcodeReader::rememberAndSkipMetadata() {
36390b57cec5SDimitry Andric   // Save the current stream state.
36400b57cec5SDimitry Andric   uint64_t CurBit = Stream.GetCurrentBitNo();
36410b57cec5SDimitry Andric   DeferredMetadataInfo.push_back(CurBit);
36420b57cec5SDimitry Andric 
36430b57cec5SDimitry Andric   // Skip over the block for now.
36440b57cec5SDimitry Andric   if (Error Err = Stream.SkipBlock())
36450b57cec5SDimitry Andric     return Err;
36460b57cec5SDimitry Andric   return Error::success();
36470b57cec5SDimitry Andric }
36480b57cec5SDimitry Andric 
materializeMetadata()36490b57cec5SDimitry Andric Error BitcodeReader::materializeMetadata() {
36500b57cec5SDimitry Andric   for (uint64_t BitPos : DeferredMetadataInfo) {
36510b57cec5SDimitry Andric     // Move the bit stream to the saved position.
36520b57cec5SDimitry Andric     if (Error JumpFailed = Stream.JumpToBit(BitPos))
36530b57cec5SDimitry Andric       return JumpFailed;
36540b57cec5SDimitry Andric     if (Error Err = MDLoader->parseModuleMetadata())
36550b57cec5SDimitry Andric       return Err;
36560b57cec5SDimitry Andric   }
36570b57cec5SDimitry Andric 
36580b57cec5SDimitry Andric   // Upgrade "Linker Options" module flag to "llvm.linker.options" module-level
3659e8d8bef9SDimitry Andric   // metadata. Only upgrade if the new option doesn't exist to avoid upgrade
3660e8d8bef9SDimitry Andric   // multiple times.
3661e8d8bef9SDimitry Andric   if (!TheModule->getNamedMetadata("llvm.linker.options")) {
36620b57cec5SDimitry Andric     if (Metadata *Val = TheModule->getModuleFlag("Linker Options")) {
36630b57cec5SDimitry Andric       NamedMDNode *LinkerOpts =
36640b57cec5SDimitry Andric           TheModule->getOrInsertNamedMetadata("llvm.linker.options");
36650b57cec5SDimitry Andric       for (const MDOperand &MDOptions : cast<MDNode>(Val)->operands())
36660b57cec5SDimitry Andric         LinkerOpts->addOperand(cast<MDNode>(MDOptions));
36670b57cec5SDimitry Andric     }
3668e8d8bef9SDimitry Andric   }
36690b57cec5SDimitry Andric 
36700b57cec5SDimitry Andric   DeferredMetadataInfo.clear();
36710b57cec5SDimitry Andric   return Error::success();
36720b57cec5SDimitry Andric }
36730b57cec5SDimitry Andric 
setStripDebugInfo()36740b57cec5SDimitry Andric void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
36750b57cec5SDimitry Andric 
36760b57cec5SDimitry Andric /// When we see the block for a function body, remember where it is and then
36770b57cec5SDimitry Andric /// skip it.  This lets us lazily deserialize the functions.
rememberAndSkipFunctionBody()36780b57cec5SDimitry Andric Error BitcodeReader::rememberAndSkipFunctionBody() {
36790b57cec5SDimitry Andric   // Get the function we are talking about.
36800b57cec5SDimitry Andric   if (FunctionsWithBodies.empty())
36810b57cec5SDimitry Andric     return error("Insufficient function protos");
36820b57cec5SDimitry Andric 
36830b57cec5SDimitry Andric   Function *Fn = FunctionsWithBodies.back();
36840b57cec5SDimitry Andric   FunctionsWithBodies.pop_back();
36850b57cec5SDimitry Andric 
36860b57cec5SDimitry Andric   // Save the current stream state.
36870b57cec5SDimitry Andric   uint64_t CurBit = Stream.GetCurrentBitNo();
36880b57cec5SDimitry Andric   assert(
36890b57cec5SDimitry Andric       (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
36900b57cec5SDimitry Andric       "Mismatch between VST and scanned function offsets");
36910b57cec5SDimitry Andric   DeferredFunctionInfo[Fn] = CurBit;
36920b57cec5SDimitry Andric 
36930b57cec5SDimitry Andric   // Skip over the function block for now.
36940b57cec5SDimitry Andric   if (Error Err = Stream.SkipBlock())
36950b57cec5SDimitry Andric     return Err;
36960b57cec5SDimitry Andric   return Error::success();
36970b57cec5SDimitry Andric }
36980b57cec5SDimitry Andric 
globalCleanup()36990b57cec5SDimitry Andric Error BitcodeReader::globalCleanup() {
37000b57cec5SDimitry Andric   // Patch the initializers for globals and aliases up.
37010b57cec5SDimitry Andric   if (Error Err = resolveGlobalAndIndirectSymbolInits())
37020b57cec5SDimitry Andric     return Err;
37030b57cec5SDimitry Andric   if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
37040b57cec5SDimitry Andric     return error("Malformed global initializer set");
37050b57cec5SDimitry Andric 
37060b57cec5SDimitry Andric   // Look for intrinsic functions which need to be upgraded at some point
37075ffd83dbSDimitry Andric   // and functions that need to have their function attributes upgraded.
37080b57cec5SDimitry Andric   for (Function &F : *TheModule) {
37090b57cec5SDimitry Andric     MDLoader->upgradeDebugIntrinsics(F);
37100b57cec5SDimitry Andric     Function *NewFn;
37110b57cec5SDimitry Andric     if (UpgradeIntrinsicFunction(&F, NewFn))
37120b57cec5SDimitry Andric       UpgradedIntrinsics[&F] = NewFn;
37135ffd83dbSDimitry Andric     // Look for functions that rely on old function attribute behavior.
37145ffd83dbSDimitry Andric     UpgradeFunctionAttributes(F);
37150b57cec5SDimitry Andric   }
37160b57cec5SDimitry Andric 
37170b57cec5SDimitry Andric   // Look for global variables which need to be renamed.
37180b57cec5SDimitry Andric   std::vector<std::pair<GlobalVariable *, GlobalVariable *>> UpgradedVariables;
37190b57cec5SDimitry Andric   for (GlobalVariable &GV : TheModule->globals())
37200b57cec5SDimitry Andric     if (GlobalVariable *Upgraded = UpgradeGlobalVariable(&GV))
37210b57cec5SDimitry Andric       UpgradedVariables.emplace_back(&GV, Upgraded);
37220b57cec5SDimitry Andric   for (auto &Pair : UpgradedVariables) {
37230b57cec5SDimitry Andric     Pair.first->eraseFromParent();
3724fe013be4SDimitry Andric     TheModule->insertGlobalVariable(Pair.second);
37250b57cec5SDimitry Andric   }
37260b57cec5SDimitry Andric 
37270b57cec5SDimitry Andric   // Force deallocation of memory for these vectors to favor the client that
37280b57cec5SDimitry Andric   // want lazy deserialization.
37290b57cec5SDimitry Andric   std::vector<std::pair<GlobalVariable *, unsigned>>().swap(GlobalInits);
3730349cc55cSDimitry Andric   std::vector<std::pair<GlobalValue *, unsigned>>().swap(IndirectSymbolInits);
37310b57cec5SDimitry Andric   return Error::success();
37320b57cec5SDimitry Andric }
37330b57cec5SDimitry Andric 
37340b57cec5SDimitry Andric /// Support for lazy parsing of function bodies. This is required if we
37350b57cec5SDimitry Andric /// either have an old bitcode file without a VST forward declaration record,
37360b57cec5SDimitry Andric /// or if we have an anonymous function being materialized, since anonymous
37370b57cec5SDimitry Andric /// functions do not have a name and are therefore not in the VST.
rememberAndSkipFunctionBodies()37380b57cec5SDimitry Andric Error BitcodeReader::rememberAndSkipFunctionBodies() {
37390b57cec5SDimitry Andric   if (Error JumpFailed = Stream.JumpToBit(NextUnreadBit))
37400b57cec5SDimitry Andric     return JumpFailed;
37410b57cec5SDimitry Andric 
37420b57cec5SDimitry Andric   if (Stream.AtEndOfStream())
37430b57cec5SDimitry Andric     return error("Could not find function in stream");
37440b57cec5SDimitry Andric 
37450b57cec5SDimitry Andric   if (!SeenFirstFunctionBody)
37460b57cec5SDimitry Andric     return error("Trying to materialize functions before seeing function blocks");
37470b57cec5SDimitry Andric 
37480b57cec5SDimitry Andric   // An old bitcode file with the symbol table at the end would have
37490b57cec5SDimitry Andric   // finished the parse greedily.
37500b57cec5SDimitry Andric   assert(SeenValueSymbolTable);
37510b57cec5SDimitry Andric 
37520b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
37530b57cec5SDimitry Andric 
37540b57cec5SDimitry Andric   while (true) {
37550b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
37560b57cec5SDimitry Andric     if (!MaybeEntry)
37570b57cec5SDimitry Andric       return MaybeEntry.takeError();
37580b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
37590b57cec5SDimitry Andric 
37600b57cec5SDimitry Andric     switch (Entry.Kind) {
37610b57cec5SDimitry Andric     default:
37620b57cec5SDimitry Andric       return error("Expect SubBlock");
37630b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
37640b57cec5SDimitry Andric       switch (Entry.ID) {
37650b57cec5SDimitry Andric       default:
37660b57cec5SDimitry Andric         return error("Expect function block");
37670b57cec5SDimitry Andric       case bitc::FUNCTION_BLOCK_ID:
37680b57cec5SDimitry Andric         if (Error Err = rememberAndSkipFunctionBody())
37690b57cec5SDimitry Andric           return Err;
37700b57cec5SDimitry Andric         NextUnreadBit = Stream.GetCurrentBitNo();
37710b57cec5SDimitry Andric         return Error::success();
37720b57cec5SDimitry Andric       }
37730b57cec5SDimitry Andric     }
37740b57cec5SDimitry Andric   }
37750b57cec5SDimitry Andric }
37760b57cec5SDimitry Andric 
readBlockInfo()377781ad6265SDimitry Andric Error BitcodeReaderBase::readBlockInfo() {
3778bdd1243dSDimitry Andric   Expected<std::optional<BitstreamBlockInfo>> MaybeNewBlockInfo =
37790b57cec5SDimitry Andric       Stream.ReadBlockInfoBlock();
37800b57cec5SDimitry Andric   if (!MaybeNewBlockInfo)
378181ad6265SDimitry Andric     return MaybeNewBlockInfo.takeError();
3782bdd1243dSDimitry Andric   std::optional<BitstreamBlockInfo> NewBlockInfo =
37830b57cec5SDimitry Andric       std::move(MaybeNewBlockInfo.get());
37840b57cec5SDimitry Andric   if (!NewBlockInfo)
378581ad6265SDimitry Andric     return error("Malformed block");
37860b57cec5SDimitry Andric   BlockInfo = std::move(*NewBlockInfo);
378781ad6265SDimitry Andric   return Error::success();
37880b57cec5SDimitry Andric }
37890b57cec5SDimitry Andric 
parseComdatRecord(ArrayRef<uint64_t> Record)37900b57cec5SDimitry Andric Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) {
37910b57cec5SDimitry Andric   // v1: [selection_kind, name]
37920b57cec5SDimitry Andric   // v2: [strtab_offset, strtab_size, selection_kind]
37930b57cec5SDimitry Andric   StringRef Name;
37940b57cec5SDimitry Andric   std::tie(Name, Record) = readNameFromStrtab(Record);
37950b57cec5SDimitry Andric 
37960b57cec5SDimitry Andric   if (Record.empty())
37970b57cec5SDimitry Andric     return error("Invalid record");
37980b57cec5SDimitry Andric   Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
37990b57cec5SDimitry Andric   std::string OldFormatName;
38000b57cec5SDimitry Andric   if (!UseStrtab) {
38010b57cec5SDimitry Andric     if (Record.size() < 2)
38020b57cec5SDimitry Andric       return error("Invalid record");
38030b57cec5SDimitry Andric     unsigned ComdatNameSize = Record[1];
380481ad6265SDimitry Andric     if (ComdatNameSize > Record.size() - 2)
380581ad6265SDimitry Andric       return error("Comdat name size too large");
38060b57cec5SDimitry Andric     OldFormatName.reserve(ComdatNameSize);
38070b57cec5SDimitry Andric     for (unsigned i = 0; i != ComdatNameSize; ++i)
38080b57cec5SDimitry Andric       OldFormatName += (char)Record[2 + i];
38090b57cec5SDimitry Andric     Name = OldFormatName;
38100b57cec5SDimitry Andric   }
38110b57cec5SDimitry Andric   Comdat *C = TheModule->getOrInsertComdat(Name);
38120b57cec5SDimitry Andric   C->setSelectionKind(SK);
38130b57cec5SDimitry Andric   ComdatList.push_back(C);
38140b57cec5SDimitry Andric   return Error::success();
38150b57cec5SDimitry Andric }
38160b57cec5SDimitry Andric 
inferDSOLocal(GlobalValue * GV)38170b57cec5SDimitry Andric static void inferDSOLocal(GlobalValue *GV) {
38180b57cec5SDimitry Andric   // infer dso_local from linkage and visibility if it is not encoded.
38190b57cec5SDimitry Andric   if (GV->hasLocalLinkage() ||
38200b57cec5SDimitry Andric       (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage()))
38210b57cec5SDimitry Andric     GV->setDSOLocal(true);
38220b57cec5SDimitry Andric }
38230b57cec5SDimitry Andric 
deserializeSanitizerMetadata(unsigned V)382481ad6265SDimitry Andric GlobalValue::SanitizerMetadata deserializeSanitizerMetadata(unsigned V) {
382581ad6265SDimitry Andric   GlobalValue::SanitizerMetadata Meta;
382681ad6265SDimitry Andric   if (V & (1 << 0))
382781ad6265SDimitry Andric     Meta.NoAddress = true;
382881ad6265SDimitry Andric   if (V & (1 << 1))
382981ad6265SDimitry Andric     Meta.NoHWAddress = true;
383081ad6265SDimitry Andric   if (V & (1 << 2))
3831753f127fSDimitry Andric     Meta.Memtag = true;
383281ad6265SDimitry Andric   if (V & (1 << 3))
383381ad6265SDimitry Andric     Meta.IsDynInit = true;
383481ad6265SDimitry Andric   return Meta;
383581ad6265SDimitry Andric }
383681ad6265SDimitry Andric 
parseGlobalVarRecord(ArrayRef<uint64_t> Record)38370b57cec5SDimitry Andric Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) {
38380b57cec5SDimitry Andric   // v1: [pointer type, isconst, initid, linkage, alignment, section,
38390b57cec5SDimitry Andric   // visibility, threadlocal, unnamed_addr, externally_initialized,
38400b57cec5SDimitry Andric   // dllstorageclass, comdat, attributes, preemption specifier,
38410b57cec5SDimitry Andric   // partition strtab offset, partition strtab size] (name in VST)
38420b57cec5SDimitry Andric   // v2: [strtab_offset, strtab_size, v1]
3843c9157d92SDimitry Andric   // v3: [v2, code_model]
38440b57cec5SDimitry Andric   StringRef Name;
38450b57cec5SDimitry Andric   std::tie(Name, Record) = readNameFromStrtab(Record);
38460b57cec5SDimitry Andric 
38470b57cec5SDimitry Andric   if (Record.size() < 6)
38480b57cec5SDimitry Andric     return error("Invalid record");
384981ad6265SDimitry Andric   unsigned TyID = Record[0];
385081ad6265SDimitry Andric   Type *Ty = getTypeByID(TyID);
38510b57cec5SDimitry Andric   if (!Ty)
38520b57cec5SDimitry Andric     return error("Invalid record");
38530b57cec5SDimitry Andric   bool isConstant = Record[1] & 1;
38540b57cec5SDimitry Andric   bool explicitType = Record[1] & 2;
38550b57cec5SDimitry Andric   unsigned AddressSpace;
38560b57cec5SDimitry Andric   if (explicitType) {
38570b57cec5SDimitry Andric     AddressSpace = Record[1] >> 2;
38580b57cec5SDimitry Andric   } else {
38590b57cec5SDimitry Andric     if (!Ty->isPointerTy())
38600b57cec5SDimitry Andric       return error("Invalid type for value");
38610b57cec5SDimitry Andric     AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
386281ad6265SDimitry Andric     TyID = getContainedTypeID(TyID);
386381ad6265SDimitry Andric     Ty = getTypeByID(TyID);
386481ad6265SDimitry Andric     if (!Ty)
386581ad6265SDimitry Andric       return error("Missing element type for old-style global");
38660b57cec5SDimitry Andric   }
38670b57cec5SDimitry Andric 
38680b57cec5SDimitry Andric   uint64_t RawLinkage = Record[3];
38690b57cec5SDimitry Andric   GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
38708bcb0991SDimitry Andric   MaybeAlign Alignment;
38710b57cec5SDimitry Andric   if (Error Err = parseAlignmentValue(Record[4], Alignment))
38720b57cec5SDimitry Andric     return Err;
38730b57cec5SDimitry Andric   std::string Section;
38740b57cec5SDimitry Andric   if (Record[5]) {
38750b57cec5SDimitry Andric     if (Record[5] - 1 >= SectionTable.size())
38760b57cec5SDimitry Andric       return error("Invalid ID");
38770b57cec5SDimitry Andric     Section = SectionTable[Record[5] - 1];
38780b57cec5SDimitry Andric   }
38790b57cec5SDimitry Andric   GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
38800b57cec5SDimitry Andric   // Local linkage must have default visibility.
38815ffd83dbSDimitry Andric   // auto-upgrade `hidden` and `protected` for old bitcode.
38820b57cec5SDimitry Andric   if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
38830b57cec5SDimitry Andric     Visibility = getDecodedVisibility(Record[6]);
38840b57cec5SDimitry Andric 
38850b57cec5SDimitry Andric   GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
38860b57cec5SDimitry Andric   if (Record.size() > 7)
38870b57cec5SDimitry Andric     TLM = getDecodedThreadLocalMode(Record[7]);
38880b57cec5SDimitry Andric 
38890b57cec5SDimitry Andric   GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
38900b57cec5SDimitry Andric   if (Record.size() > 8)
38910b57cec5SDimitry Andric     UnnamedAddr = getDecodedUnnamedAddrType(Record[8]);
38920b57cec5SDimitry Andric 
38930b57cec5SDimitry Andric   bool ExternallyInitialized = false;
38940b57cec5SDimitry Andric   if (Record.size() > 9)
38950b57cec5SDimitry Andric     ExternallyInitialized = Record[9];
38960b57cec5SDimitry Andric 
38970b57cec5SDimitry Andric   GlobalVariable *NewGV =
38980b57cec5SDimitry Andric       new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, Name,
38990b57cec5SDimitry Andric                          nullptr, TLM, AddressSpace, ExternallyInitialized);
3900fe013be4SDimitry Andric   if (Alignment)
3901fe013be4SDimitry Andric     NewGV->setAlignment(*Alignment);
39020b57cec5SDimitry Andric   if (!Section.empty())
39030b57cec5SDimitry Andric     NewGV->setSection(Section);
39040b57cec5SDimitry Andric   NewGV->setVisibility(Visibility);
39050b57cec5SDimitry Andric   NewGV->setUnnamedAddr(UnnamedAddr);
39060b57cec5SDimitry Andric 
3907bdd1243dSDimitry Andric   if (Record.size() > 10) {
3908bdd1243dSDimitry Andric     // A GlobalValue with local linkage cannot have a DLL storage class.
3909bdd1243dSDimitry Andric     if (!NewGV->hasLocalLinkage()) {
39100b57cec5SDimitry Andric       NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
3911bdd1243dSDimitry Andric     }
3912bdd1243dSDimitry Andric   } else {
39130b57cec5SDimitry Andric     upgradeDLLImportExportLinkage(NewGV, RawLinkage);
3914bdd1243dSDimitry Andric   }
39150b57cec5SDimitry Andric 
391681ad6265SDimitry Andric   ValueList.push_back(NewGV, getVirtualTypeID(NewGV->getType(), TyID));
39170b57cec5SDimitry Andric 
39180b57cec5SDimitry Andric   // Remember which value to use for the global initializer.
39190b57cec5SDimitry Andric   if (unsigned InitID = Record[2])
39200b57cec5SDimitry Andric     GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));
39210b57cec5SDimitry Andric 
39220b57cec5SDimitry Andric   if (Record.size() > 11) {
39230b57cec5SDimitry Andric     if (unsigned ComdatID = Record[11]) {
39240b57cec5SDimitry Andric       if (ComdatID > ComdatList.size())
39250b57cec5SDimitry Andric         return error("Invalid global variable comdat ID");
39260b57cec5SDimitry Andric       NewGV->setComdat(ComdatList[ComdatID - 1]);
39270b57cec5SDimitry Andric     }
39280b57cec5SDimitry Andric   } else if (hasImplicitComdat(RawLinkage)) {
39290eae32dcSDimitry Andric     ImplicitComdatObjects.insert(NewGV);
39300b57cec5SDimitry Andric   }
39310b57cec5SDimitry Andric 
39320b57cec5SDimitry Andric   if (Record.size() > 12) {
3933349cc55cSDimitry Andric     auto AS = getAttributes(Record[12]).getFnAttrs();
39340b57cec5SDimitry Andric     NewGV->setAttributes(AS);
39350b57cec5SDimitry Andric   }
39360b57cec5SDimitry Andric 
39370b57cec5SDimitry Andric   if (Record.size() > 13) {
39380b57cec5SDimitry Andric     NewGV->setDSOLocal(getDecodedDSOLocal(Record[13]));
39390b57cec5SDimitry Andric   }
39400b57cec5SDimitry Andric   inferDSOLocal(NewGV);
39410b57cec5SDimitry Andric 
39420b57cec5SDimitry Andric   // Check whether we have enough values to read a partition name.
39430b57cec5SDimitry Andric   if (Record.size() > 15)
39440b57cec5SDimitry Andric     NewGV->setPartition(StringRef(Strtab.data() + Record[14], Record[15]));
39450b57cec5SDimitry Andric 
394681ad6265SDimitry Andric   if (Record.size() > 16 && Record[16]) {
394781ad6265SDimitry Andric     llvm::GlobalValue::SanitizerMetadata Meta =
394881ad6265SDimitry Andric         deserializeSanitizerMetadata(Record[16]);
394981ad6265SDimitry Andric     NewGV->setSanitizerMetadata(Meta);
395081ad6265SDimitry Andric   }
395181ad6265SDimitry Andric 
3952c9157d92SDimitry Andric   if (Record.size() > 17 && Record[17]) {
3953c9157d92SDimitry Andric     if (auto CM = getDecodedCodeModel(Record[17]))
3954c9157d92SDimitry Andric       NewGV->setCodeModel(*CM);
3955c9157d92SDimitry Andric     else
3956c9157d92SDimitry Andric       return error("Invalid global variable code model");
3957c9157d92SDimitry Andric   }
3958c9157d92SDimitry Andric 
39590b57cec5SDimitry Andric   return Error::success();
39600b57cec5SDimitry Andric }
39610b57cec5SDimitry Andric 
callValueTypeCallback(Value * F,unsigned TypeID)3962bdd1243dSDimitry Andric void BitcodeReader::callValueTypeCallback(Value *F, unsigned TypeID) {
3963bdd1243dSDimitry Andric   if (ValueTypeCallback) {
3964bdd1243dSDimitry Andric     (*ValueTypeCallback)(
3965bdd1243dSDimitry Andric         F, TypeID, [this](unsigned I) { return getTypeByID(I); },
3966bdd1243dSDimitry Andric         [this](unsigned I, unsigned J) { return getContainedTypeID(I, J); });
3967bdd1243dSDimitry Andric   }
3968bdd1243dSDimitry Andric }
3969bdd1243dSDimitry Andric 
parseFunctionRecord(ArrayRef<uint64_t> Record)39700b57cec5SDimitry Andric Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) {
39710b57cec5SDimitry Andric   // v1: [type, callingconv, isproto, linkage, paramattr, alignment, section,
39720b57cec5SDimitry Andric   // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat,
39730b57cec5SDimitry Andric   // prefixdata,  personalityfn, preemption specifier, addrspace] (name in VST)
39740b57cec5SDimitry Andric   // v2: [strtab_offset, strtab_size, v1]
39750b57cec5SDimitry Andric   StringRef Name;
39760b57cec5SDimitry Andric   std::tie(Name, Record) = readNameFromStrtab(Record);
39770b57cec5SDimitry Andric 
39780b57cec5SDimitry Andric   if (Record.size() < 8)
39790b57cec5SDimitry Andric     return error("Invalid record");
398081ad6265SDimitry Andric   unsigned FTyID = Record[0];
398181ad6265SDimitry Andric   Type *FTy = getTypeByID(FTyID);
39820b57cec5SDimitry Andric   if (!FTy)
39830b57cec5SDimitry Andric     return error("Invalid record");
398481ad6265SDimitry Andric   if (isa<PointerType>(FTy)) {
398581ad6265SDimitry Andric     FTyID = getContainedTypeID(FTyID, 0);
398681ad6265SDimitry Andric     FTy = getTypeByID(FTyID);
398781ad6265SDimitry Andric     if (!FTy)
398881ad6265SDimitry Andric       return error("Missing element type for old-style function");
398981ad6265SDimitry Andric   }
39900b57cec5SDimitry Andric 
39910b57cec5SDimitry Andric   if (!isa<FunctionType>(FTy))
39920b57cec5SDimitry Andric     return error("Invalid type for value");
39930b57cec5SDimitry Andric   auto CC = static_cast<CallingConv::ID>(Record[1]);
39940b57cec5SDimitry Andric   if (CC & ~CallingConv::MaxID)
39950b57cec5SDimitry Andric     return error("Invalid calling convention ID");
39960b57cec5SDimitry Andric 
39970b57cec5SDimitry Andric   unsigned AddrSpace = TheModule->getDataLayout().getProgramAddressSpace();
39980b57cec5SDimitry Andric   if (Record.size() > 16)
39990b57cec5SDimitry Andric     AddrSpace = Record[16];
40000b57cec5SDimitry Andric 
40010b57cec5SDimitry Andric   Function *Func =
40020b57cec5SDimitry Andric       Function::Create(cast<FunctionType>(FTy), GlobalValue::ExternalLinkage,
40030b57cec5SDimitry Andric                        AddrSpace, Name, TheModule);
40040b57cec5SDimitry Andric 
4005fe6060f1SDimitry Andric   assert(Func->getFunctionType() == FTy &&
40060b57cec5SDimitry Andric          "Incorrect fully specified type provided for function");
400781ad6265SDimitry Andric   FunctionTypeIDs[Func] = FTyID;
40080b57cec5SDimitry Andric 
40090b57cec5SDimitry Andric   Func->setCallingConv(CC);
40100b57cec5SDimitry Andric   bool isProto = Record[2];
40110b57cec5SDimitry Andric   uint64_t RawLinkage = Record[3];
40120b57cec5SDimitry Andric   Func->setLinkage(getDecodedLinkage(RawLinkage));
40130b57cec5SDimitry Andric   Func->setAttributes(getAttributes(Record[4]));
4014bdd1243dSDimitry Andric   callValueTypeCallback(Func, FTyID);
40150b57cec5SDimitry Andric 
4016e8d8bef9SDimitry Andric   // Upgrade any old-style byval or sret without a type by propagating the
4017e8d8bef9SDimitry Andric   // argument's pointee type. There should be no opaque pointers where the byval
4018e8d8bef9SDimitry Andric   // type is implicit.
40190b57cec5SDimitry Andric   for (unsigned i = 0; i != Func->arg_size(); ++i) {
4020fe6060f1SDimitry Andric     for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
4021fe6060f1SDimitry Andric                                      Attribute::InAlloca}) {
4022e8d8bef9SDimitry Andric       if (!Func->hasParamAttribute(i, Kind))
40230b57cec5SDimitry Andric         continue;
40240b57cec5SDimitry Andric 
4025fe6060f1SDimitry Andric       if (Func->getParamAttribute(i, Kind).getValueAsType())
4026fe6060f1SDimitry Andric         continue;
4027fe6060f1SDimitry Andric 
4028e8d8bef9SDimitry Andric       Func->removeParamAttr(i, Kind);
4029e8d8bef9SDimitry Andric 
403081ad6265SDimitry Andric       unsigned ParamTypeID = getContainedTypeID(FTyID, i + 1);
403181ad6265SDimitry Andric       Type *PtrEltTy = getPtrElementTypeByID(ParamTypeID);
403281ad6265SDimitry Andric       if (!PtrEltTy)
403381ad6265SDimitry Andric         return error("Missing param element type for attribute upgrade");
403481ad6265SDimitry Andric 
4035fe6060f1SDimitry Andric       Attribute NewAttr;
4036fe6060f1SDimitry Andric       switch (Kind) {
4037fe6060f1SDimitry Andric       case Attribute::ByVal:
4038fe6060f1SDimitry Andric         NewAttr = Attribute::getWithByValType(Context, PtrEltTy);
4039fe6060f1SDimitry Andric         break;
4040fe6060f1SDimitry Andric       case Attribute::StructRet:
4041fe6060f1SDimitry Andric         NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy);
4042fe6060f1SDimitry Andric         break;
4043fe6060f1SDimitry Andric       case Attribute::InAlloca:
4044fe6060f1SDimitry Andric         NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy);
4045fe6060f1SDimitry Andric         break;
4046fe6060f1SDimitry Andric       default:
4047fe6060f1SDimitry Andric         llvm_unreachable("not an upgraded type attribute");
4048fe6060f1SDimitry Andric       }
4049fe6060f1SDimitry Andric 
4050e8d8bef9SDimitry Andric       Func->addParamAttr(i, NewAttr);
4051e8d8bef9SDimitry Andric     }
40520b57cec5SDimitry Andric   }
40530b57cec5SDimitry Andric 
405481ad6265SDimitry Andric   if (Func->getCallingConv() == CallingConv::X86_INTR &&
405581ad6265SDimitry Andric       !Func->arg_empty() && !Func->hasParamAttribute(0, Attribute::ByVal)) {
405681ad6265SDimitry Andric     unsigned ParamTypeID = getContainedTypeID(FTyID, 1);
405781ad6265SDimitry Andric     Type *ByValTy = getPtrElementTypeByID(ParamTypeID);
405881ad6265SDimitry Andric     if (!ByValTy)
405981ad6265SDimitry Andric       return error("Missing param element type for x86_intrcc upgrade");
406081ad6265SDimitry Andric     Attribute NewAttr = Attribute::getWithByValType(Context, ByValTy);
406181ad6265SDimitry Andric     Func->addParamAttr(0, NewAttr);
406281ad6265SDimitry Andric   }
406381ad6265SDimitry Andric 
40648bcb0991SDimitry Andric   MaybeAlign Alignment;
40650b57cec5SDimitry Andric   if (Error Err = parseAlignmentValue(Record[5], Alignment))
40660b57cec5SDimitry Andric     return Err;
4067fe013be4SDimitry Andric   if (Alignment)
4068fe013be4SDimitry Andric     Func->setAlignment(*Alignment);
40690b57cec5SDimitry Andric   if (Record[6]) {
40700b57cec5SDimitry Andric     if (Record[6] - 1 >= SectionTable.size())
40710b57cec5SDimitry Andric       return error("Invalid ID");
40720b57cec5SDimitry Andric     Func->setSection(SectionTable[Record[6] - 1]);
40730b57cec5SDimitry Andric   }
40740b57cec5SDimitry Andric   // Local linkage must have default visibility.
40755ffd83dbSDimitry Andric   // auto-upgrade `hidden` and `protected` for old bitcode.
40760b57cec5SDimitry Andric   if (!Func->hasLocalLinkage())
40770b57cec5SDimitry Andric     Func->setVisibility(getDecodedVisibility(Record[7]));
40780b57cec5SDimitry Andric   if (Record.size() > 8 && Record[8]) {
40790b57cec5SDimitry Andric     if (Record[8] - 1 >= GCTable.size())
40800b57cec5SDimitry Andric       return error("Invalid ID");
40810b57cec5SDimitry Andric     Func->setGC(GCTable[Record[8] - 1]);
40820b57cec5SDimitry Andric   }
40830b57cec5SDimitry Andric   GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
40840b57cec5SDimitry Andric   if (Record.size() > 9)
40850b57cec5SDimitry Andric     UnnamedAddr = getDecodedUnnamedAddrType(Record[9]);
40860b57cec5SDimitry Andric   Func->setUnnamedAddr(UnnamedAddr);
4087349cc55cSDimitry Andric 
4088349cc55cSDimitry Andric   FunctionOperandInfo OperandInfo = {Func, 0, 0, 0};
4089349cc55cSDimitry Andric   if (Record.size() > 10)
4090349cc55cSDimitry Andric     OperandInfo.Prologue = Record[10];
40910b57cec5SDimitry Andric 
4092bdd1243dSDimitry Andric   if (Record.size() > 11) {
4093bdd1243dSDimitry Andric     // A GlobalValue with local linkage cannot have a DLL storage class.
4094bdd1243dSDimitry Andric     if (!Func->hasLocalLinkage()) {
40950b57cec5SDimitry Andric       Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
4096bdd1243dSDimitry Andric     }
4097bdd1243dSDimitry Andric   } else {
40980b57cec5SDimitry Andric     upgradeDLLImportExportLinkage(Func, RawLinkage);
4099bdd1243dSDimitry Andric   }
41000b57cec5SDimitry Andric 
41010b57cec5SDimitry Andric   if (Record.size() > 12) {
41020b57cec5SDimitry Andric     if (unsigned ComdatID = Record[12]) {
41030b57cec5SDimitry Andric       if (ComdatID > ComdatList.size())
41040b57cec5SDimitry Andric         return error("Invalid function comdat ID");
41050b57cec5SDimitry Andric       Func->setComdat(ComdatList[ComdatID - 1]);
41060b57cec5SDimitry Andric     }
41070b57cec5SDimitry Andric   } else if (hasImplicitComdat(RawLinkage)) {
41080eae32dcSDimitry Andric     ImplicitComdatObjects.insert(Func);
41090b57cec5SDimitry Andric   }
41100b57cec5SDimitry Andric 
4111349cc55cSDimitry Andric   if (Record.size() > 13)
4112349cc55cSDimitry Andric     OperandInfo.Prefix = Record[13];
41130b57cec5SDimitry Andric 
4114349cc55cSDimitry Andric   if (Record.size() > 14)
4115349cc55cSDimitry Andric     OperandInfo.PersonalityFn = Record[14];
41160b57cec5SDimitry Andric 
41170b57cec5SDimitry Andric   if (Record.size() > 15) {
41180b57cec5SDimitry Andric     Func->setDSOLocal(getDecodedDSOLocal(Record[15]));
41190b57cec5SDimitry Andric   }
41200b57cec5SDimitry Andric   inferDSOLocal(Func);
41210b57cec5SDimitry Andric 
41220b57cec5SDimitry Andric   // Record[16] is the address space number.
41230b57cec5SDimitry Andric 
4124fe6060f1SDimitry Andric   // Check whether we have enough values to read a partition name. Also make
4125fe6060f1SDimitry Andric   // sure Strtab has enough values.
4126fe6060f1SDimitry Andric   if (Record.size() > 18 && Strtab.data() &&
4127fe6060f1SDimitry Andric       Record[17] + Record[18] <= Strtab.size()) {
41280b57cec5SDimitry Andric     Func->setPartition(StringRef(Strtab.data() + Record[17], Record[18]));
4129fe6060f1SDimitry Andric   }
41300b57cec5SDimitry Andric 
413181ad6265SDimitry Andric   ValueList.push_back(Func, getVirtualTypeID(Func->getType(), FTyID));
41320b57cec5SDimitry Andric 
4133349cc55cSDimitry Andric   if (OperandInfo.PersonalityFn || OperandInfo.Prefix || OperandInfo.Prologue)
4134349cc55cSDimitry Andric     FunctionOperands.push_back(OperandInfo);
4135349cc55cSDimitry Andric 
41360b57cec5SDimitry Andric   // If this is a function with a body, remember the prototype we are
41370b57cec5SDimitry Andric   // creating now, so that we can match up the body with them later.
41380b57cec5SDimitry Andric   if (!isProto) {
41390b57cec5SDimitry Andric     Func->setIsMaterializable(true);
41400b57cec5SDimitry Andric     FunctionsWithBodies.push_back(Func);
41410b57cec5SDimitry Andric     DeferredFunctionInfo[Func] = 0;
41420b57cec5SDimitry Andric   }
41430b57cec5SDimitry Andric   return Error::success();
41440b57cec5SDimitry Andric }
41450b57cec5SDimitry Andric 
parseGlobalIndirectSymbolRecord(unsigned BitCode,ArrayRef<uint64_t> Record)41460b57cec5SDimitry Andric Error BitcodeReader::parseGlobalIndirectSymbolRecord(
41470b57cec5SDimitry Andric     unsigned BitCode, ArrayRef<uint64_t> Record) {
41480b57cec5SDimitry Andric   // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST)
41490b57cec5SDimitry Andric   // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
41500b57cec5SDimitry Andric   // dllstorageclass, threadlocal, unnamed_addr,
41510b57cec5SDimitry Andric   // preemption specifier] (name in VST)
41520b57cec5SDimitry Andric   // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage,
41530b57cec5SDimitry Andric   // visibility, dllstorageclass, threadlocal, unnamed_addr,
41540b57cec5SDimitry Andric   // preemption specifier] (name in VST)
41550b57cec5SDimitry Andric   // v2: [strtab_offset, strtab_size, v1]
41560b57cec5SDimitry Andric   StringRef Name;
41570b57cec5SDimitry Andric   std::tie(Name, Record) = readNameFromStrtab(Record);
41580b57cec5SDimitry Andric 
41590b57cec5SDimitry Andric   bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
41600b57cec5SDimitry Andric   if (Record.size() < (3 + (unsigned)NewRecord))
41610b57cec5SDimitry Andric     return error("Invalid record");
41620b57cec5SDimitry Andric   unsigned OpNum = 0;
416381ad6265SDimitry Andric   unsigned TypeID = Record[OpNum++];
416481ad6265SDimitry Andric   Type *Ty = getTypeByID(TypeID);
41650b57cec5SDimitry Andric   if (!Ty)
41660b57cec5SDimitry Andric     return error("Invalid record");
41670b57cec5SDimitry Andric 
41680b57cec5SDimitry Andric   unsigned AddrSpace;
41690b57cec5SDimitry Andric   if (!NewRecord) {
41700b57cec5SDimitry Andric     auto *PTy = dyn_cast<PointerType>(Ty);
41710b57cec5SDimitry Andric     if (!PTy)
41720b57cec5SDimitry Andric       return error("Invalid type for value");
41730b57cec5SDimitry Andric     AddrSpace = PTy->getAddressSpace();
417481ad6265SDimitry Andric     TypeID = getContainedTypeID(TypeID);
417581ad6265SDimitry Andric     Ty = getTypeByID(TypeID);
417681ad6265SDimitry Andric     if (!Ty)
417781ad6265SDimitry Andric       return error("Missing element type for old-style indirect symbol");
41780b57cec5SDimitry Andric   } else {
41790b57cec5SDimitry Andric     AddrSpace = Record[OpNum++];
41800b57cec5SDimitry Andric   }
41810b57cec5SDimitry Andric 
41820b57cec5SDimitry Andric   auto Val = Record[OpNum++];
41830b57cec5SDimitry Andric   auto Linkage = Record[OpNum++];
4184349cc55cSDimitry Andric   GlobalValue *NewGA;
41850b57cec5SDimitry Andric   if (BitCode == bitc::MODULE_CODE_ALIAS ||
41860b57cec5SDimitry Andric       BitCode == bitc::MODULE_CODE_ALIAS_OLD)
41870b57cec5SDimitry Andric     NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
41880b57cec5SDimitry Andric                                 TheModule);
41890b57cec5SDimitry Andric   else
41900b57cec5SDimitry Andric     NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
41910b57cec5SDimitry Andric                                 nullptr, TheModule);
41920b57cec5SDimitry Andric 
41930b57cec5SDimitry Andric   // Local linkage must have default visibility.
41945ffd83dbSDimitry Andric   // auto-upgrade `hidden` and `protected` for old bitcode.
41950b57cec5SDimitry Andric   if (OpNum != Record.size()) {
41960b57cec5SDimitry Andric     auto VisInd = OpNum++;
41970b57cec5SDimitry Andric     if (!NewGA->hasLocalLinkage())
41980b57cec5SDimitry Andric       NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
41990b57cec5SDimitry Andric   }
42000b57cec5SDimitry Andric   if (BitCode == bitc::MODULE_CODE_ALIAS ||
42010b57cec5SDimitry Andric       BitCode == bitc::MODULE_CODE_ALIAS_OLD) {
4202bdd1243dSDimitry Andric     if (OpNum != Record.size()) {
4203bdd1243dSDimitry Andric       auto S = Record[OpNum++];
4204bdd1243dSDimitry Andric       // A GlobalValue with local linkage cannot have a DLL storage class.
4205bdd1243dSDimitry Andric       if (!NewGA->hasLocalLinkage())
4206bdd1243dSDimitry Andric         NewGA->setDLLStorageClass(getDecodedDLLStorageClass(S));
4207bdd1243dSDimitry Andric     }
42080b57cec5SDimitry Andric     else
42090b57cec5SDimitry Andric       upgradeDLLImportExportLinkage(NewGA, Linkage);
42100b57cec5SDimitry Andric     if (OpNum != Record.size())
42110b57cec5SDimitry Andric       NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
42120b57cec5SDimitry Andric     if (OpNum != Record.size())
42130b57cec5SDimitry Andric       NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++]));
42140b57cec5SDimitry Andric   }
42150b57cec5SDimitry Andric   if (OpNum != Record.size())
42160b57cec5SDimitry Andric     NewGA->setDSOLocal(getDecodedDSOLocal(Record[OpNum++]));
42170b57cec5SDimitry Andric   inferDSOLocal(NewGA);
42180b57cec5SDimitry Andric 
42190b57cec5SDimitry Andric   // Check whether we have enough values to read a partition name.
42200b57cec5SDimitry Andric   if (OpNum + 1 < Record.size()) {
4221*de8261c4SDimitry Andric     // Check Strtab has enough values for the partition.
4222*de8261c4SDimitry Andric     if (Record[OpNum] + Record[OpNum + 1] > Strtab.size())
4223*de8261c4SDimitry Andric       return error("Malformed partition, too large.");
42240b57cec5SDimitry Andric     NewGA->setPartition(
42250b57cec5SDimitry Andric         StringRef(Strtab.data() + Record[OpNum], Record[OpNum + 1]));
42260b57cec5SDimitry Andric     OpNum += 2;
42270b57cec5SDimitry Andric   }
42280b57cec5SDimitry Andric 
422981ad6265SDimitry Andric   ValueList.push_back(NewGA, getVirtualTypeID(NewGA->getType(), TypeID));
42300b57cec5SDimitry Andric   IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
42310b57cec5SDimitry Andric   return Error::success();
42320b57cec5SDimitry Andric }
42330b57cec5SDimitry Andric 
parseModule(uint64_t ResumeBit,bool ShouldLazyLoadMetadata,ParserCallbacks Callbacks)42340b57cec5SDimitry Andric Error BitcodeReader::parseModule(uint64_t ResumeBit,
42355ffd83dbSDimitry Andric                                  bool ShouldLazyLoadMetadata,
4236bdd1243dSDimitry Andric                                  ParserCallbacks Callbacks) {
4237bdd1243dSDimitry Andric   this->ValueTypeCallback = std::move(Callbacks.ValueType);
42380b57cec5SDimitry Andric   if (ResumeBit) {
42390b57cec5SDimitry Andric     if (Error JumpFailed = Stream.JumpToBit(ResumeBit))
42400b57cec5SDimitry Andric       return JumpFailed;
42410b57cec5SDimitry Andric   } else if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
42420b57cec5SDimitry Andric     return Err;
42430b57cec5SDimitry Andric 
42440b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
42450b57cec5SDimitry Andric 
42465ffd83dbSDimitry Andric   // Parts of bitcode parsing depend on the datalayout.  Make sure we
42475ffd83dbSDimitry Andric   // finalize the datalayout before we run any of that code.
42485ffd83dbSDimitry Andric   bool ResolvedDataLayout = false;
4249bdd1243dSDimitry Andric   // In order to support importing modules with illegal data layout strings,
4250bdd1243dSDimitry Andric   // delay parsing the data layout string until after upgrades and overrides
4251bdd1243dSDimitry Andric   // have been applied, allowing to fix illegal data layout strings.
4252bdd1243dSDimitry Andric   // Initialize to the current module's layout string in case none is specified.
4253bdd1243dSDimitry Andric   std::string TentativeDataLayoutStr = TheModule->getDataLayoutStr();
42545ffd83dbSDimitry Andric 
4255bdd1243dSDimitry Andric   auto ResolveDataLayout = [&]() -> Error {
4256bdd1243dSDimitry Andric     if (ResolvedDataLayout)
4257bdd1243dSDimitry Andric       return Error::success();
4258bdd1243dSDimitry Andric 
4259bdd1243dSDimitry Andric     // Datalayout and triple can't be parsed after this point.
42605ffd83dbSDimitry Andric     ResolvedDataLayout = true;
42615ffd83dbSDimitry Andric 
4262bdd1243dSDimitry Andric     // Auto-upgrade the layout string
4263bdd1243dSDimitry Andric     TentativeDataLayoutStr = llvm::UpgradeDataLayoutString(
4264bdd1243dSDimitry Andric         TentativeDataLayoutStr, TheModule->getTargetTriple());
42655ffd83dbSDimitry Andric 
4266bdd1243dSDimitry Andric     // Apply override
4267bdd1243dSDimitry Andric     if (Callbacks.DataLayout) {
4268bdd1243dSDimitry Andric       if (auto LayoutOverride = (*Callbacks.DataLayout)(
4269bdd1243dSDimitry Andric               TheModule->getTargetTriple(), TentativeDataLayoutStr))
4270bdd1243dSDimitry Andric         TentativeDataLayoutStr = *LayoutOverride;
4271bdd1243dSDimitry Andric     }
4272bdd1243dSDimitry Andric 
4273bdd1243dSDimitry Andric     // Now the layout string is finalized in TentativeDataLayoutStr. Parse it.
4274bdd1243dSDimitry Andric     Expected<DataLayout> MaybeDL = DataLayout::parse(TentativeDataLayoutStr);
4275bdd1243dSDimitry Andric     if (!MaybeDL)
4276bdd1243dSDimitry Andric       return MaybeDL.takeError();
4277bdd1243dSDimitry Andric 
4278bdd1243dSDimitry Andric     TheModule->setDataLayout(MaybeDL.get());
4279bdd1243dSDimitry Andric     return Error::success();
42805ffd83dbSDimitry Andric   };
42815ffd83dbSDimitry Andric 
42820b57cec5SDimitry Andric   // Read all the records for this module.
42830b57cec5SDimitry Andric   while (true) {
42840b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
42850b57cec5SDimitry Andric     if (!MaybeEntry)
42860b57cec5SDimitry Andric       return MaybeEntry.takeError();
42870b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
42880b57cec5SDimitry Andric 
42890b57cec5SDimitry Andric     switch (Entry.Kind) {
42900b57cec5SDimitry Andric     case BitstreamEntry::Error:
42910b57cec5SDimitry Andric       return error("Malformed block");
42920b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
4293bdd1243dSDimitry Andric       if (Error Err = ResolveDataLayout())
4294bdd1243dSDimitry Andric         return Err;
42950b57cec5SDimitry Andric       return globalCleanup();
42960b57cec5SDimitry Andric 
42970b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
42980b57cec5SDimitry Andric       switch (Entry.ID) {
42990b57cec5SDimitry Andric       default:  // Skip unknown content.
43000b57cec5SDimitry Andric         if (Error Err = Stream.SkipBlock())
43010b57cec5SDimitry Andric           return Err;
43020b57cec5SDimitry Andric         break;
43030b57cec5SDimitry Andric       case bitc::BLOCKINFO_BLOCK_ID:
430481ad6265SDimitry Andric         if (Error Err = readBlockInfo())
430581ad6265SDimitry Andric           return Err;
43060b57cec5SDimitry Andric         break;
43070b57cec5SDimitry Andric       case bitc::PARAMATTR_BLOCK_ID:
43080b57cec5SDimitry Andric         if (Error Err = parseAttributeBlock())
43090b57cec5SDimitry Andric           return Err;
43100b57cec5SDimitry Andric         break;
43110b57cec5SDimitry Andric       case bitc::PARAMATTR_GROUP_BLOCK_ID:
43120b57cec5SDimitry Andric         if (Error Err = parseAttributeGroupBlock())
43130b57cec5SDimitry Andric           return Err;
43140b57cec5SDimitry Andric         break;
43150b57cec5SDimitry Andric       case bitc::TYPE_BLOCK_ID_NEW:
43160b57cec5SDimitry Andric         if (Error Err = parseTypeTable())
43170b57cec5SDimitry Andric           return Err;
43180b57cec5SDimitry Andric         break;
43190b57cec5SDimitry Andric       case bitc::VALUE_SYMTAB_BLOCK_ID:
43200b57cec5SDimitry Andric         if (!SeenValueSymbolTable) {
43210b57cec5SDimitry Andric           // Either this is an old form VST without function index and an
43220b57cec5SDimitry Andric           // associated VST forward declaration record (which would have caused
43230b57cec5SDimitry Andric           // the VST to be jumped to and parsed before it was encountered
43240b57cec5SDimitry Andric           // normally in the stream), or there were no function blocks to
43250b57cec5SDimitry Andric           // trigger an earlier parsing of the VST.
43260b57cec5SDimitry Andric           assert(VSTOffset == 0 || FunctionsWithBodies.empty());
43270b57cec5SDimitry Andric           if (Error Err = parseValueSymbolTable())
43280b57cec5SDimitry Andric             return Err;
43290b57cec5SDimitry Andric           SeenValueSymbolTable = true;
43300b57cec5SDimitry Andric         } else {
43310b57cec5SDimitry Andric           // We must have had a VST forward declaration record, which caused
43320b57cec5SDimitry Andric           // the parser to jump to and parse the VST earlier.
43330b57cec5SDimitry Andric           assert(VSTOffset > 0);
43340b57cec5SDimitry Andric           if (Error Err = Stream.SkipBlock())
43350b57cec5SDimitry Andric             return Err;
43360b57cec5SDimitry Andric         }
43370b57cec5SDimitry Andric         break;
43380b57cec5SDimitry Andric       case bitc::CONSTANTS_BLOCK_ID:
43390b57cec5SDimitry Andric         if (Error Err = parseConstants())
43400b57cec5SDimitry Andric           return Err;
43410b57cec5SDimitry Andric         if (Error Err = resolveGlobalAndIndirectSymbolInits())
43420b57cec5SDimitry Andric           return Err;
43430b57cec5SDimitry Andric         break;
43440b57cec5SDimitry Andric       case bitc::METADATA_BLOCK_ID:
43450b57cec5SDimitry Andric         if (ShouldLazyLoadMetadata) {
43460b57cec5SDimitry Andric           if (Error Err = rememberAndSkipMetadata())
43470b57cec5SDimitry Andric             return Err;
43480b57cec5SDimitry Andric           break;
43490b57cec5SDimitry Andric         }
43500b57cec5SDimitry Andric         assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
43510b57cec5SDimitry Andric         if (Error Err = MDLoader->parseModuleMetadata())
43520b57cec5SDimitry Andric           return Err;
43530b57cec5SDimitry Andric         break;
43540b57cec5SDimitry Andric       case bitc::METADATA_KIND_BLOCK_ID:
43550b57cec5SDimitry Andric         if (Error Err = MDLoader->parseMetadataKinds())
43560b57cec5SDimitry Andric           return Err;
43570b57cec5SDimitry Andric         break;
43580b57cec5SDimitry Andric       case bitc::FUNCTION_BLOCK_ID:
4359bdd1243dSDimitry Andric         if (Error Err = ResolveDataLayout())
4360bdd1243dSDimitry Andric           return Err;
43615ffd83dbSDimitry Andric 
43620b57cec5SDimitry Andric         // If this is the first function body we've seen, reverse the
43630b57cec5SDimitry Andric         // FunctionsWithBodies list.
43640b57cec5SDimitry Andric         if (!SeenFirstFunctionBody) {
43650b57cec5SDimitry Andric           std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
43660b57cec5SDimitry Andric           if (Error Err = globalCleanup())
43670b57cec5SDimitry Andric             return Err;
43680b57cec5SDimitry Andric           SeenFirstFunctionBody = true;
43690b57cec5SDimitry Andric         }
43700b57cec5SDimitry Andric 
43710b57cec5SDimitry Andric         if (VSTOffset > 0) {
43720b57cec5SDimitry Andric           // If we have a VST forward declaration record, make sure we
43730b57cec5SDimitry Andric           // parse the VST now if we haven't already. It is needed to
43740b57cec5SDimitry Andric           // set up the DeferredFunctionInfo vector for lazy reading.
43750b57cec5SDimitry Andric           if (!SeenValueSymbolTable) {
43760b57cec5SDimitry Andric             if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
43770b57cec5SDimitry Andric               return Err;
43780b57cec5SDimitry Andric             SeenValueSymbolTable = true;
43790b57cec5SDimitry Andric             // Fall through so that we record the NextUnreadBit below.
43800b57cec5SDimitry Andric             // This is necessary in case we have an anonymous function that
43810b57cec5SDimitry Andric             // is later materialized. Since it will not have a VST entry we
43820b57cec5SDimitry Andric             // need to fall back to the lazy parse to find its offset.
43830b57cec5SDimitry Andric           } else {
43840b57cec5SDimitry Andric             // If we have a VST forward declaration record, but have already
43850b57cec5SDimitry Andric             // parsed the VST (just above, when the first function body was
43860b57cec5SDimitry Andric             // encountered here), then we are resuming the parse after
43870b57cec5SDimitry Andric             // materializing functions. The ResumeBit points to the
43880b57cec5SDimitry Andric             // start of the last function block recorded in the
43890b57cec5SDimitry Andric             // DeferredFunctionInfo map. Skip it.
43900b57cec5SDimitry Andric             if (Error Err = Stream.SkipBlock())
43910b57cec5SDimitry Andric               return Err;
43920b57cec5SDimitry Andric             continue;
43930b57cec5SDimitry Andric           }
43940b57cec5SDimitry Andric         }
43950b57cec5SDimitry Andric 
43960b57cec5SDimitry Andric         // Support older bitcode files that did not have the function
43970b57cec5SDimitry Andric         // index in the VST, nor a VST forward declaration record, as
43980b57cec5SDimitry Andric         // well as anonymous functions that do not have VST entries.
43990b57cec5SDimitry Andric         // Build the DeferredFunctionInfo vector on the fly.
44000b57cec5SDimitry Andric         if (Error Err = rememberAndSkipFunctionBody())
44010b57cec5SDimitry Andric           return Err;
44020b57cec5SDimitry Andric 
44030b57cec5SDimitry Andric         // Suspend parsing when we reach the function bodies. Subsequent
44040b57cec5SDimitry Andric         // materialization calls will resume it when necessary. If the bitcode
44050b57cec5SDimitry Andric         // file is old, the symbol table will be at the end instead and will not
44060b57cec5SDimitry Andric         // have been seen yet. In this case, just finish the parse now.
44070b57cec5SDimitry Andric         if (SeenValueSymbolTable) {
44080b57cec5SDimitry Andric           NextUnreadBit = Stream.GetCurrentBitNo();
44090b57cec5SDimitry Andric           // After the VST has been parsed, we need to make sure intrinsic name
44100b57cec5SDimitry Andric           // are auto-upgraded.
44110b57cec5SDimitry Andric           return globalCleanup();
44120b57cec5SDimitry Andric         }
44130b57cec5SDimitry Andric         break;
44140b57cec5SDimitry Andric       case bitc::USELIST_BLOCK_ID:
44150b57cec5SDimitry Andric         if (Error Err = parseUseLists())
44160b57cec5SDimitry Andric           return Err;
44170b57cec5SDimitry Andric         break;
44180b57cec5SDimitry Andric       case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
44190b57cec5SDimitry Andric         if (Error Err = parseOperandBundleTags())
44200b57cec5SDimitry Andric           return Err;
44210b57cec5SDimitry Andric         break;
44220b57cec5SDimitry Andric       case bitc::SYNC_SCOPE_NAMES_BLOCK_ID:
44230b57cec5SDimitry Andric         if (Error Err = parseSyncScopeNames())
44240b57cec5SDimitry Andric           return Err;
44250b57cec5SDimitry Andric         break;
44260b57cec5SDimitry Andric       }
44270b57cec5SDimitry Andric       continue;
44280b57cec5SDimitry Andric 
44290b57cec5SDimitry Andric     case BitstreamEntry::Record:
44300b57cec5SDimitry Andric       // The interesting case.
44310b57cec5SDimitry Andric       break;
44320b57cec5SDimitry Andric     }
44330b57cec5SDimitry Andric 
44340b57cec5SDimitry Andric     // Read a record.
44350b57cec5SDimitry Andric     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
44360b57cec5SDimitry Andric     if (!MaybeBitCode)
44370b57cec5SDimitry Andric       return MaybeBitCode.takeError();
44380b57cec5SDimitry Andric     switch (unsigned BitCode = MaybeBitCode.get()) {
44390b57cec5SDimitry Andric     default: break;  // Default behavior, ignore unknown content.
44400b57cec5SDimitry Andric     case bitc::MODULE_CODE_VERSION: {
44410b57cec5SDimitry Andric       Expected<unsigned> VersionOrErr = parseVersionRecord(Record);
44420b57cec5SDimitry Andric       if (!VersionOrErr)
44430b57cec5SDimitry Andric         return VersionOrErr.takeError();
44440b57cec5SDimitry Andric       UseRelativeIDs = *VersionOrErr >= 1;
44450b57cec5SDimitry Andric       break;
44460b57cec5SDimitry Andric     }
44470b57cec5SDimitry Andric     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
44485ffd83dbSDimitry Andric       if (ResolvedDataLayout)
44495ffd83dbSDimitry Andric         return error("target triple too late in module");
44500b57cec5SDimitry Andric       std::string S;
44510b57cec5SDimitry Andric       if (convertToString(Record, 0, S))
44520b57cec5SDimitry Andric         return error("Invalid record");
44530b57cec5SDimitry Andric       TheModule->setTargetTriple(S);
44540b57cec5SDimitry Andric       break;
44550b57cec5SDimitry Andric     }
44560b57cec5SDimitry Andric     case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
44575ffd83dbSDimitry Andric       if (ResolvedDataLayout)
44585ffd83dbSDimitry Andric         return error("datalayout too late in module");
4459bdd1243dSDimitry Andric       if (convertToString(Record, 0, TentativeDataLayoutStr))
44600b57cec5SDimitry Andric         return error("Invalid record");
44610b57cec5SDimitry Andric       break;
44620b57cec5SDimitry Andric     }
44630b57cec5SDimitry Andric     case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
44640b57cec5SDimitry Andric       std::string S;
44650b57cec5SDimitry Andric       if (convertToString(Record, 0, S))
44660b57cec5SDimitry Andric         return error("Invalid record");
44670b57cec5SDimitry Andric       TheModule->setModuleInlineAsm(S);
44680b57cec5SDimitry Andric       break;
44690b57cec5SDimitry Andric     }
44700b57cec5SDimitry Andric     case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
44715ffd83dbSDimitry Andric       // Deprecated, but still needed to read old bitcode files.
44720b57cec5SDimitry Andric       std::string S;
44730b57cec5SDimitry Andric       if (convertToString(Record, 0, S))
44740b57cec5SDimitry Andric         return error("Invalid record");
44750b57cec5SDimitry Andric       // Ignore value.
44760b57cec5SDimitry Andric       break;
44770b57cec5SDimitry Andric     }
44780b57cec5SDimitry Andric     case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
44790b57cec5SDimitry Andric       std::string S;
44800b57cec5SDimitry Andric       if (convertToString(Record, 0, S))
44810b57cec5SDimitry Andric         return error("Invalid record");
44820b57cec5SDimitry Andric       SectionTable.push_back(S);
44830b57cec5SDimitry Andric       break;
44840b57cec5SDimitry Andric     }
44850b57cec5SDimitry Andric     case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
44860b57cec5SDimitry Andric       std::string S;
44870b57cec5SDimitry Andric       if (convertToString(Record, 0, S))
44880b57cec5SDimitry Andric         return error("Invalid record");
44890b57cec5SDimitry Andric       GCTable.push_back(S);
44900b57cec5SDimitry Andric       break;
44910b57cec5SDimitry Andric     }
44920b57cec5SDimitry Andric     case bitc::MODULE_CODE_COMDAT:
44930b57cec5SDimitry Andric       if (Error Err = parseComdatRecord(Record))
44940b57cec5SDimitry Andric         return Err;
44950b57cec5SDimitry Andric       break;
449604eeddc0SDimitry Andric     // FIXME: BitcodeReader should handle {GLOBALVAR, FUNCTION, ALIAS, IFUNC}
449704eeddc0SDimitry Andric     // written by ThinLinkBitcodeWriter. See
449804eeddc0SDimitry Andric     // `ThinLinkBitcodeWriter::writeSimplifiedModuleInfo` for the format of each
449904eeddc0SDimitry Andric     // record
450004eeddc0SDimitry Andric     // (https://github.com/llvm/llvm-project/blob/b6a93967d9c11e79802b5e75cec1584d6c8aa472/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp#L4714)
45010b57cec5SDimitry Andric     case bitc::MODULE_CODE_GLOBALVAR:
45020b57cec5SDimitry Andric       if (Error Err = parseGlobalVarRecord(Record))
45030b57cec5SDimitry Andric         return Err;
45040b57cec5SDimitry Andric       break;
45050b57cec5SDimitry Andric     case bitc::MODULE_CODE_FUNCTION:
4506bdd1243dSDimitry Andric       if (Error Err = ResolveDataLayout())
4507bdd1243dSDimitry Andric         return Err;
45080b57cec5SDimitry Andric       if (Error Err = parseFunctionRecord(Record))
45090b57cec5SDimitry Andric         return Err;
45100b57cec5SDimitry Andric       break;
45110b57cec5SDimitry Andric     case bitc::MODULE_CODE_IFUNC:
45120b57cec5SDimitry Andric     case bitc::MODULE_CODE_ALIAS:
45130b57cec5SDimitry Andric     case bitc::MODULE_CODE_ALIAS_OLD:
45140b57cec5SDimitry Andric       if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
45150b57cec5SDimitry Andric         return Err;
45160b57cec5SDimitry Andric       break;
45170b57cec5SDimitry Andric     /// MODULE_CODE_VSTOFFSET: [offset]
45180b57cec5SDimitry Andric     case bitc::MODULE_CODE_VSTOFFSET:
4519e8d8bef9SDimitry Andric       if (Record.empty())
45200b57cec5SDimitry Andric         return error("Invalid record");
45210b57cec5SDimitry Andric       // Note that we subtract 1 here because the offset is relative to one word
45220b57cec5SDimitry Andric       // before the start of the identification or module block, which was
45230b57cec5SDimitry Andric       // historically always the start of the regular bitcode header.
45240b57cec5SDimitry Andric       VSTOffset = Record[0] - 1;
45250b57cec5SDimitry Andric       break;
45260b57cec5SDimitry Andric     /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
45270b57cec5SDimitry Andric     case bitc::MODULE_CODE_SOURCE_FILENAME:
45280b57cec5SDimitry Andric       SmallString<128> ValueName;
45290b57cec5SDimitry Andric       if (convertToString(Record, 0, ValueName))
45300b57cec5SDimitry Andric         return error("Invalid record");
45310b57cec5SDimitry Andric       TheModule->setSourceFileName(ValueName);
45320b57cec5SDimitry Andric       break;
45330b57cec5SDimitry Andric     }
45340b57cec5SDimitry Andric     Record.clear();
45350b57cec5SDimitry Andric   }
4536bdd1243dSDimitry Andric   this->ValueTypeCallback = std::nullopt;
4537bdd1243dSDimitry Andric   return Error::success();
45380b57cec5SDimitry Andric }
45390b57cec5SDimitry Andric 
parseBitcodeInto(Module * M,bool ShouldLazyLoadMetadata,bool IsImporting,ParserCallbacks Callbacks)45400b57cec5SDimitry Andric Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata,
45415ffd83dbSDimitry Andric                                       bool IsImporting,
4542bdd1243dSDimitry Andric                                       ParserCallbacks Callbacks) {
45430b57cec5SDimitry Andric   TheModule = M;
4544bdd1243dSDimitry Andric   MetadataLoaderCallbacks MDCallbacks;
4545bdd1243dSDimitry Andric   MDCallbacks.GetTypeByID = [&](unsigned ID) { return getTypeByID(ID); };
4546bdd1243dSDimitry Andric   MDCallbacks.GetContainedTypeID = [&](unsigned I, unsigned J) {
4547bdd1243dSDimitry Andric     return getContainedTypeID(I, J);
4548bdd1243dSDimitry Andric   };
4549bdd1243dSDimitry Andric   MDCallbacks.MDType = Callbacks.MDType;
4550bdd1243dSDimitry Andric   MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting, MDCallbacks);
4551bdd1243dSDimitry Andric   return parseModule(0, ShouldLazyLoadMetadata, Callbacks);
45520b57cec5SDimitry Andric }
45530b57cec5SDimitry Andric 
typeCheckLoadStoreInst(Type * ValType,Type * PtrType)45540b57cec5SDimitry Andric Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
45550b57cec5SDimitry Andric   if (!isa<PointerType>(PtrType))
45560b57cec5SDimitry Andric     return error("Load/Store operand is not a pointer type");
4557fe6060f1SDimitry Andric   if (!PointerType::isLoadableOrStorableType(ValType))
45580b57cec5SDimitry Andric     return error("Cannot load/store from pointer");
45590b57cec5SDimitry Andric   return Error::success();
45600b57cec5SDimitry Andric }
45610b57cec5SDimitry Andric 
propagateAttributeTypes(CallBase * CB,ArrayRef<unsigned> ArgTyIDs)456281ad6265SDimitry Andric Error BitcodeReader::propagateAttributeTypes(CallBase *CB,
456381ad6265SDimitry Andric                                              ArrayRef<unsigned> ArgTyIDs) {
456481ad6265SDimitry Andric   AttributeList Attrs = CB->getAttributes();
45650b57cec5SDimitry Andric   for (unsigned i = 0; i != CB->arg_size(); ++i) {
4566fe6060f1SDimitry Andric     for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
4567fe6060f1SDimitry Andric                                      Attribute::InAlloca}) {
456881ad6265SDimitry Andric       if (!Attrs.hasParamAttr(i, Kind) ||
456981ad6265SDimitry Andric           Attrs.getParamAttr(i, Kind).getValueAsType())
45700b57cec5SDimitry Andric         continue;
45710b57cec5SDimitry Andric 
457281ad6265SDimitry Andric       Type *PtrEltTy = getPtrElementTypeByID(ArgTyIDs[i]);
457381ad6265SDimitry Andric       if (!PtrEltTy)
457481ad6265SDimitry Andric         return error("Missing element type for typed attribute upgrade");
4575e8d8bef9SDimitry Andric 
4576fe6060f1SDimitry Andric       Attribute NewAttr;
4577fe6060f1SDimitry Andric       switch (Kind) {
4578fe6060f1SDimitry Andric       case Attribute::ByVal:
4579fe6060f1SDimitry Andric         NewAttr = Attribute::getWithByValType(Context, PtrEltTy);
4580fe6060f1SDimitry Andric         break;
4581fe6060f1SDimitry Andric       case Attribute::StructRet:
4582fe6060f1SDimitry Andric         NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy);
4583fe6060f1SDimitry Andric         break;
4584fe6060f1SDimitry Andric       case Attribute::InAlloca:
4585fe6060f1SDimitry Andric         NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy);
4586fe6060f1SDimitry Andric         break;
4587fe6060f1SDimitry Andric       default:
4588fe6060f1SDimitry Andric         llvm_unreachable("not an upgraded type attribute");
4589fe6060f1SDimitry Andric       }
4590fe6060f1SDimitry Andric 
459181ad6265SDimitry Andric       Attrs = Attrs.addParamAttribute(Context, i, NewAttr);
4592e8d8bef9SDimitry Andric     }
45930b57cec5SDimitry Andric   }
4594fe6060f1SDimitry Andric 
459504eeddc0SDimitry Andric   if (CB->isInlineAsm()) {
459604eeddc0SDimitry Andric     const InlineAsm *IA = cast<InlineAsm>(CB->getCalledOperand());
459704eeddc0SDimitry Andric     unsigned ArgNo = 0;
459804eeddc0SDimitry Andric     for (const InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
459904eeddc0SDimitry Andric       if (!CI.hasArg())
460004eeddc0SDimitry Andric         continue;
460104eeddc0SDimitry Andric 
460281ad6265SDimitry Andric       if (CI.isIndirect && !Attrs.getParamElementType(ArgNo)) {
460381ad6265SDimitry Andric         Type *ElemTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
460481ad6265SDimitry Andric         if (!ElemTy)
460581ad6265SDimitry Andric           return error("Missing element type for inline asm upgrade");
460681ad6265SDimitry Andric         Attrs = Attrs.addParamAttribute(
460781ad6265SDimitry Andric             Context, ArgNo,
460881ad6265SDimitry Andric             Attribute::get(Context, Attribute::ElementType, ElemTy));
460904eeddc0SDimitry Andric       }
461004eeddc0SDimitry Andric 
461104eeddc0SDimitry Andric       ArgNo++;
461204eeddc0SDimitry Andric     }
461304eeddc0SDimitry Andric   }
461404eeddc0SDimitry Andric 
4615fe6060f1SDimitry Andric   switch (CB->getIntrinsicID()) {
4616fe6060f1SDimitry Andric   case Intrinsic::preserve_array_access_index:
4617fe6060f1SDimitry Andric   case Intrinsic::preserve_struct_access_index:
461881ad6265SDimitry Andric   case Intrinsic::aarch64_ldaxr:
461981ad6265SDimitry Andric   case Intrinsic::aarch64_ldxr:
462081ad6265SDimitry Andric   case Intrinsic::aarch64_stlxr:
462181ad6265SDimitry Andric   case Intrinsic::aarch64_stxr:
462281ad6265SDimitry Andric   case Intrinsic::arm_ldaex:
462381ad6265SDimitry Andric   case Intrinsic::arm_ldrex:
462481ad6265SDimitry Andric   case Intrinsic::arm_stlex:
462581ad6265SDimitry Andric   case Intrinsic::arm_strex: {
462681ad6265SDimitry Andric     unsigned ArgNo;
462781ad6265SDimitry Andric     switch (CB->getIntrinsicID()) {
462881ad6265SDimitry Andric     case Intrinsic::aarch64_stlxr:
462981ad6265SDimitry Andric     case Intrinsic::aarch64_stxr:
463081ad6265SDimitry Andric     case Intrinsic::arm_stlex:
463181ad6265SDimitry Andric     case Intrinsic::arm_strex:
463281ad6265SDimitry Andric       ArgNo = 1;
463381ad6265SDimitry Andric       break;
463481ad6265SDimitry Andric     default:
463581ad6265SDimitry Andric       ArgNo = 0;
463681ad6265SDimitry Andric       break;
463781ad6265SDimitry Andric     }
463881ad6265SDimitry Andric     if (!Attrs.getParamElementType(ArgNo)) {
463981ad6265SDimitry Andric       Type *ElTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
464081ad6265SDimitry Andric       if (!ElTy)
464181ad6265SDimitry Andric         return error("Missing element type for elementtype upgrade");
4642fe6060f1SDimitry Andric       Attribute NewAttr = Attribute::get(Context, Attribute::ElementType, ElTy);
464381ad6265SDimitry Andric       Attrs = Attrs.addParamAttribute(Context, ArgNo, NewAttr);
4644fe6060f1SDimitry Andric     }
4645fe6060f1SDimitry Andric     break;
464681ad6265SDimitry Andric   }
4647fe6060f1SDimitry Andric   default:
4648fe6060f1SDimitry Andric     break;
4649fe6060f1SDimitry Andric   }
465081ad6265SDimitry Andric 
465181ad6265SDimitry Andric   CB->setAttributes(Attrs);
465281ad6265SDimitry Andric   return Error::success();
46530b57cec5SDimitry Andric }
46540b57cec5SDimitry Andric 
46550b57cec5SDimitry Andric /// Lazily parse the specified function body block.
parseFunctionBody(Function * F)46560b57cec5SDimitry Andric Error BitcodeReader::parseFunctionBody(Function *F) {
46570b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
46580b57cec5SDimitry Andric     return Err;
46590b57cec5SDimitry Andric 
46600b57cec5SDimitry Andric   // Unexpected unresolved metadata when parsing function.
46610b57cec5SDimitry Andric   if (MDLoader->hasFwdRefs())
46620b57cec5SDimitry Andric     return error("Invalid function metadata: incoming forward references");
46630b57cec5SDimitry Andric 
46640b57cec5SDimitry Andric   InstructionList.clear();
46650b57cec5SDimitry Andric   unsigned ModuleValueListSize = ValueList.size();
46660b57cec5SDimitry Andric   unsigned ModuleMDLoaderSize = MDLoader->size();
46670b57cec5SDimitry Andric 
46680b57cec5SDimitry Andric   // Add all the function arguments to the value table.
46690b57cec5SDimitry Andric   unsigned ArgNo = 0;
467081ad6265SDimitry Andric   unsigned FTyID = FunctionTypeIDs[F];
46710b57cec5SDimitry Andric   for (Argument &I : F->args()) {
467281ad6265SDimitry Andric     unsigned ArgTyID = getContainedTypeID(FTyID, ArgNo + 1);
467381ad6265SDimitry Andric     assert(I.getType() == getTypeByID(ArgTyID) &&
46740b57cec5SDimitry Andric            "Incorrect fully specified type for Function Argument");
467581ad6265SDimitry Andric     ValueList.push_back(&I, ArgTyID);
467681ad6265SDimitry Andric     ++ArgNo;
46770b57cec5SDimitry Andric   }
46780b57cec5SDimitry Andric   unsigned NextValueNo = ValueList.size();
46790b57cec5SDimitry Andric   BasicBlock *CurBB = nullptr;
46800b57cec5SDimitry Andric   unsigned CurBBNo = 0;
468181ad6265SDimitry Andric   // Block into which constant expressions from phi nodes are materialized.
468281ad6265SDimitry Andric   BasicBlock *PhiConstExprBB = nullptr;
468381ad6265SDimitry Andric   // Edge blocks for phi nodes into which constant expressions have been
468481ad6265SDimitry Andric   // expanded.
468581ad6265SDimitry Andric   SmallMapVector<std::pair<BasicBlock *, BasicBlock *>, BasicBlock *, 4>
468681ad6265SDimitry Andric     ConstExprEdgeBBs;
46870b57cec5SDimitry Andric 
46880b57cec5SDimitry Andric   DebugLoc LastLoc;
46890b57cec5SDimitry Andric   auto getLastInstruction = [&]() -> Instruction * {
46900b57cec5SDimitry Andric     if (CurBB && !CurBB->empty())
46910b57cec5SDimitry Andric       return &CurBB->back();
46920b57cec5SDimitry Andric     else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
46930b57cec5SDimitry Andric              !FunctionBBs[CurBBNo - 1]->empty())
46940b57cec5SDimitry Andric       return &FunctionBBs[CurBBNo - 1]->back();
46950b57cec5SDimitry Andric     return nullptr;
46960b57cec5SDimitry Andric   };
46970b57cec5SDimitry Andric 
46980b57cec5SDimitry Andric   std::vector<OperandBundleDef> OperandBundles;
46990b57cec5SDimitry Andric 
47000b57cec5SDimitry Andric   // Read all the records.
47010b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
47020b57cec5SDimitry Andric 
47030b57cec5SDimitry Andric   while (true) {
47040b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
47050b57cec5SDimitry Andric     if (!MaybeEntry)
47060b57cec5SDimitry Andric       return MaybeEntry.takeError();
47070b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
47080b57cec5SDimitry Andric 
47090b57cec5SDimitry Andric     switch (Entry.Kind) {
47100b57cec5SDimitry Andric     case BitstreamEntry::Error:
47110b57cec5SDimitry Andric       return error("Malformed block");
47120b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
47130b57cec5SDimitry Andric       goto OutOfRecordLoop;
47140b57cec5SDimitry Andric 
47150b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
47160b57cec5SDimitry Andric       switch (Entry.ID) {
47170b57cec5SDimitry Andric       default:  // Skip unknown content.
47180b57cec5SDimitry Andric         if (Error Err = Stream.SkipBlock())
47190b57cec5SDimitry Andric           return Err;
47200b57cec5SDimitry Andric         break;
47210b57cec5SDimitry Andric       case bitc::CONSTANTS_BLOCK_ID:
47220b57cec5SDimitry Andric         if (Error Err = parseConstants())
47230b57cec5SDimitry Andric           return Err;
47240b57cec5SDimitry Andric         NextValueNo = ValueList.size();
47250b57cec5SDimitry Andric         break;
47260b57cec5SDimitry Andric       case bitc::VALUE_SYMTAB_BLOCK_ID:
47270b57cec5SDimitry Andric         if (Error Err = parseValueSymbolTable())
47280b57cec5SDimitry Andric           return Err;
47290b57cec5SDimitry Andric         break;
47300b57cec5SDimitry Andric       case bitc::METADATA_ATTACHMENT_ID:
47310b57cec5SDimitry Andric         if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList))
47320b57cec5SDimitry Andric           return Err;
47330b57cec5SDimitry Andric         break;
47340b57cec5SDimitry Andric       case bitc::METADATA_BLOCK_ID:
47350b57cec5SDimitry Andric         assert(DeferredMetadataInfo.empty() &&
47360b57cec5SDimitry Andric                "Must read all module-level metadata before function-level");
47370b57cec5SDimitry Andric         if (Error Err = MDLoader->parseFunctionMetadata())
47380b57cec5SDimitry Andric           return Err;
47390b57cec5SDimitry Andric         break;
47400b57cec5SDimitry Andric       case bitc::USELIST_BLOCK_ID:
47410b57cec5SDimitry Andric         if (Error Err = parseUseLists())
47420b57cec5SDimitry Andric           return Err;
47430b57cec5SDimitry Andric         break;
47440b57cec5SDimitry Andric       }
47450b57cec5SDimitry Andric       continue;
47460b57cec5SDimitry Andric 
47470b57cec5SDimitry Andric     case BitstreamEntry::Record:
47480b57cec5SDimitry Andric       // The interesting case.
47490b57cec5SDimitry Andric       break;
47500b57cec5SDimitry Andric     }
47510b57cec5SDimitry Andric 
47520b57cec5SDimitry Andric     // Read a record.
47530b57cec5SDimitry Andric     Record.clear();
47540b57cec5SDimitry Andric     Instruction *I = nullptr;
475581ad6265SDimitry Andric     unsigned ResTypeID = InvalidTypeID;
47560b57cec5SDimitry Andric     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
47570b57cec5SDimitry Andric     if (!MaybeBitCode)
47580b57cec5SDimitry Andric       return MaybeBitCode.takeError();
47590b57cec5SDimitry Andric     switch (unsigned BitCode = MaybeBitCode.get()) {
47600b57cec5SDimitry Andric     default: // Default behavior: reject
47610b57cec5SDimitry Andric       return error("Invalid value");
47620b57cec5SDimitry Andric     case bitc::FUNC_CODE_DECLAREBLOCKS: {   // DECLAREBLOCKS: [nblocks]
4763e8d8bef9SDimitry Andric       if (Record.empty() || Record[0] == 0)
47640b57cec5SDimitry Andric         return error("Invalid record");
47650b57cec5SDimitry Andric       // Create all the basic blocks for the function.
47660b57cec5SDimitry Andric       FunctionBBs.resize(Record[0]);
47670b57cec5SDimitry Andric 
47680b57cec5SDimitry Andric       // See if anything took the address of blocks in this function.
47690b57cec5SDimitry Andric       auto BBFRI = BasicBlockFwdRefs.find(F);
47700b57cec5SDimitry Andric       if (BBFRI == BasicBlockFwdRefs.end()) {
47714824e7fdSDimitry Andric         for (BasicBlock *&BB : FunctionBBs)
47724824e7fdSDimitry Andric           BB = BasicBlock::Create(Context, "", F);
47730b57cec5SDimitry Andric       } else {
47740b57cec5SDimitry Andric         auto &BBRefs = BBFRI->second;
47750b57cec5SDimitry Andric         // Check for invalid basic block references.
47760b57cec5SDimitry Andric         if (BBRefs.size() > FunctionBBs.size())
47770b57cec5SDimitry Andric           return error("Invalid ID");
47780b57cec5SDimitry Andric         assert(!BBRefs.empty() && "Unexpected empty array");
47790b57cec5SDimitry Andric         assert(!BBRefs.front() && "Invalid reference to entry block");
47800b57cec5SDimitry Andric         for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
47810b57cec5SDimitry Andric              ++I)
47820b57cec5SDimitry Andric           if (I < RE && BBRefs[I]) {
47830b57cec5SDimitry Andric             BBRefs[I]->insertInto(F);
47840b57cec5SDimitry Andric             FunctionBBs[I] = BBRefs[I];
47850b57cec5SDimitry Andric           } else {
47860b57cec5SDimitry Andric             FunctionBBs[I] = BasicBlock::Create(Context, "", F);
47870b57cec5SDimitry Andric           }
47880b57cec5SDimitry Andric 
47890b57cec5SDimitry Andric         // Erase from the table.
47900b57cec5SDimitry Andric         BasicBlockFwdRefs.erase(BBFRI);
47910b57cec5SDimitry Andric       }
47920b57cec5SDimitry Andric 
47930b57cec5SDimitry Andric       CurBB = FunctionBBs[0];
47940b57cec5SDimitry Andric       continue;
47950b57cec5SDimitry Andric     }
47960b57cec5SDimitry Andric 
479781ad6265SDimitry Andric     case bitc::FUNC_CODE_BLOCKADDR_USERS: // BLOCKADDR_USERS: [vals...]
479881ad6265SDimitry Andric       // The record should not be emitted if it's an empty list.
479981ad6265SDimitry Andric       if (Record.empty())
480081ad6265SDimitry Andric         return error("Invalid record");
480181ad6265SDimitry Andric       // When we have the RARE case of a BlockAddress Constant that is not
480281ad6265SDimitry Andric       // scoped to the Function it refers to, we need to conservatively
480381ad6265SDimitry Andric       // materialize the referred to Function, regardless of whether or not
480481ad6265SDimitry Andric       // that Function will ultimately be linked, otherwise users of
480581ad6265SDimitry Andric       // BitcodeReader might start splicing out Function bodies such that we
480681ad6265SDimitry Andric       // might no longer be able to materialize the BlockAddress since the
480781ad6265SDimitry Andric       // BasicBlock (and entire body of the Function) the BlockAddress refers
480881ad6265SDimitry Andric       // to may have been moved. In the case that the user of BitcodeReader
480981ad6265SDimitry Andric       // decides ultimately not to link the Function body, materializing here
481081ad6265SDimitry Andric       // could be considered wasteful, but it's better than a deserialization
481181ad6265SDimitry Andric       // failure as described. This keeps BitcodeReader unaware of complex
481281ad6265SDimitry Andric       // linkage policy decisions such as those use by LTO, leaving those
481381ad6265SDimitry Andric       // decisions "one layer up."
481481ad6265SDimitry Andric       for (uint64_t ValID : Record)
481581ad6265SDimitry Andric         if (auto *F = dyn_cast<Function>(ValueList[ValID]))
481681ad6265SDimitry Andric           BackwardRefFunctions.push_back(F);
481781ad6265SDimitry Andric         else
481881ad6265SDimitry Andric           return error("Invalid record");
481981ad6265SDimitry Andric 
482081ad6265SDimitry Andric       continue;
482181ad6265SDimitry Andric 
48220b57cec5SDimitry Andric     case bitc::FUNC_CODE_DEBUG_LOC_AGAIN:  // DEBUG_LOC_AGAIN
48230b57cec5SDimitry Andric       // This record indicates that the last instruction is at the same
48240b57cec5SDimitry Andric       // location as the previous instruction with a location.
48250b57cec5SDimitry Andric       I = getLastInstruction();
48260b57cec5SDimitry Andric 
48270b57cec5SDimitry Andric       if (!I)
48280b57cec5SDimitry Andric         return error("Invalid record");
48290b57cec5SDimitry Andric       I->setDebugLoc(LastLoc);
48300b57cec5SDimitry Andric       I = nullptr;
48310b57cec5SDimitry Andric       continue;
48320b57cec5SDimitry Andric 
48330b57cec5SDimitry Andric     case bitc::FUNC_CODE_DEBUG_LOC: {      // DEBUG_LOC: [line, col, scope, ia]
48340b57cec5SDimitry Andric       I = getLastInstruction();
48350b57cec5SDimitry Andric       if (!I || Record.size() < 4)
48360b57cec5SDimitry Andric         return error("Invalid record");
48370b57cec5SDimitry Andric 
48380b57cec5SDimitry Andric       unsigned Line = Record[0], Col = Record[1];
48390b57cec5SDimitry Andric       unsigned ScopeID = Record[2], IAID = Record[3];
48400b57cec5SDimitry Andric       bool isImplicitCode = Record.size() == 5 && Record[4];
48410b57cec5SDimitry Andric 
48420b57cec5SDimitry Andric       MDNode *Scope = nullptr, *IA = nullptr;
48430b57cec5SDimitry Andric       if (ScopeID) {
48440b57cec5SDimitry Andric         Scope = dyn_cast_or_null<MDNode>(
48450b57cec5SDimitry Andric             MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1));
48460b57cec5SDimitry Andric         if (!Scope)
48470b57cec5SDimitry Andric           return error("Invalid record");
48480b57cec5SDimitry Andric       }
48490b57cec5SDimitry Andric       if (IAID) {
48500b57cec5SDimitry Andric         IA = dyn_cast_or_null<MDNode>(
48510b57cec5SDimitry Andric             MDLoader->getMetadataFwdRefOrLoad(IAID - 1));
48520b57cec5SDimitry Andric         if (!IA)
48530b57cec5SDimitry Andric           return error("Invalid record");
48540b57cec5SDimitry Andric       }
4855e8d8bef9SDimitry Andric       LastLoc = DILocation::get(Scope->getContext(), Line, Col, Scope, IA,
4856e8d8bef9SDimitry Andric                                 isImplicitCode);
48570b57cec5SDimitry Andric       I->setDebugLoc(LastLoc);
48580b57cec5SDimitry Andric       I = nullptr;
48590b57cec5SDimitry Andric       continue;
48600b57cec5SDimitry Andric     }
48610b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_UNOP: {    // UNOP: [opval, ty, opcode]
48620b57cec5SDimitry Andric       unsigned OpNum = 0;
48630b57cec5SDimitry Andric       Value *LHS;
486481ad6265SDimitry Andric       unsigned TypeID;
486581ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, LHS, TypeID, CurBB) ||
48660b57cec5SDimitry Andric           OpNum+1 > Record.size())
48670b57cec5SDimitry Andric         return error("Invalid record");
48680b57cec5SDimitry Andric 
48690b57cec5SDimitry Andric       int Opc = getDecodedUnaryOpcode(Record[OpNum++], LHS->getType());
48700b57cec5SDimitry Andric       if (Opc == -1)
48710b57cec5SDimitry Andric         return error("Invalid record");
48720b57cec5SDimitry Andric       I = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS);
487381ad6265SDimitry Andric       ResTypeID = TypeID;
48740b57cec5SDimitry Andric       InstructionList.push_back(I);
48750b57cec5SDimitry Andric       if (OpNum < Record.size()) {
48760b57cec5SDimitry Andric         if (isa<FPMathOperator>(I)) {
48770b57cec5SDimitry Andric           FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
48780b57cec5SDimitry Andric           if (FMF.any())
48790b57cec5SDimitry Andric             I->setFastMathFlags(FMF);
48800b57cec5SDimitry Andric         }
48810b57cec5SDimitry Andric       }
48820b57cec5SDimitry Andric       break;
48830b57cec5SDimitry Andric     }
48840b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
48850b57cec5SDimitry Andric       unsigned OpNum = 0;
48860b57cec5SDimitry Andric       Value *LHS, *RHS;
488781ad6265SDimitry Andric       unsigned TypeID;
488881ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, LHS, TypeID, CurBB) ||
488981ad6265SDimitry Andric           popValue(Record, OpNum, NextValueNo, LHS->getType(), TypeID, RHS,
489081ad6265SDimitry Andric                    CurBB) ||
48910b57cec5SDimitry Andric           OpNum+1 > Record.size())
48920b57cec5SDimitry Andric         return error("Invalid record");
48930b57cec5SDimitry Andric 
48940b57cec5SDimitry Andric       int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
48950b57cec5SDimitry Andric       if (Opc == -1)
48960b57cec5SDimitry Andric         return error("Invalid record");
48970b57cec5SDimitry Andric       I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
489881ad6265SDimitry Andric       ResTypeID = TypeID;
48990b57cec5SDimitry Andric       InstructionList.push_back(I);
49000b57cec5SDimitry Andric       if (OpNum < Record.size()) {
49010b57cec5SDimitry Andric         if (Opc == Instruction::Add ||
49020b57cec5SDimitry Andric             Opc == Instruction::Sub ||
49030b57cec5SDimitry Andric             Opc == Instruction::Mul ||
49040b57cec5SDimitry Andric             Opc == Instruction::Shl) {
49050b57cec5SDimitry Andric           if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
49060b57cec5SDimitry Andric             cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
49070b57cec5SDimitry Andric           if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
49080b57cec5SDimitry Andric             cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
49090b57cec5SDimitry Andric         } else if (Opc == Instruction::SDiv ||
49100b57cec5SDimitry Andric                    Opc == Instruction::UDiv ||
49110b57cec5SDimitry Andric                    Opc == Instruction::LShr ||
49120b57cec5SDimitry Andric                    Opc == Instruction::AShr) {
49130b57cec5SDimitry Andric           if (Record[OpNum] & (1 << bitc::PEO_EXACT))
49140b57cec5SDimitry Andric             cast<BinaryOperator>(I)->setIsExact(true);
4915c9157d92SDimitry Andric         } else if (Opc == Instruction::Or) {
4916c9157d92SDimitry Andric           if (Record[OpNum] & (1 << bitc::PDI_DISJOINT))
4917c9157d92SDimitry Andric             cast<PossiblyDisjointInst>(I)->setIsDisjoint(true);
49180b57cec5SDimitry Andric         } else if (isa<FPMathOperator>(I)) {
49190b57cec5SDimitry Andric           FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
49200b57cec5SDimitry Andric           if (FMF.any())
49210b57cec5SDimitry Andric             I->setFastMathFlags(FMF);
49220b57cec5SDimitry Andric         }
49230b57cec5SDimitry Andric       }
49240b57cec5SDimitry Andric       break;
49250b57cec5SDimitry Andric     }
49260b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
49270b57cec5SDimitry Andric       unsigned OpNum = 0;
49280b57cec5SDimitry Andric       Value *Op;
492981ad6265SDimitry Andric       unsigned OpTypeID;
493081ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) ||
4931c9157d92SDimitry Andric           OpNum + 1 > Record.size())
49320b57cec5SDimitry Andric         return error("Invalid record");
49330b57cec5SDimitry Andric 
4934c9157d92SDimitry Andric       ResTypeID = Record[OpNum++];
493581ad6265SDimitry Andric       Type *ResTy = getTypeByID(ResTypeID);
4936c9157d92SDimitry Andric       int Opc = getDecodedCastOpcode(Record[OpNum++]);
4937c9157d92SDimitry Andric 
49380b57cec5SDimitry Andric       if (Opc == -1 || !ResTy)
49390b57cec5SDimitry Andric         return error("Invalid record");
49400b57cec5SDimitry Andric       Instruction *Temp = nullptr;
49410b57cec5SDimitry Andric       if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
49420b57cec5SDimitry Andric         if (Temp) {
49430b57cec5SDimitry Andric           InstructionList.push_back(Temp);
4944480093f4SDimitry Andric           assert(CurBB && "No current BB?");
4945bdd1243dSDimitry Andric           Temp->insertInto(CurBB, CurBB->end());
49460b57cec5SDimitry Andric         }
49470b57cec5SDimitry Andric       } else {
49480b57cec5SDimitry Andric         auto CastOp = (Instruction::CastOps)Opc;
49490b57cec5SDimitry Andric         if (!CastInst::castIsValid(CastOp, Op, ResTy))
49500b57cec5SDimitry Andric           return error("Invalid cast");
49510b57cec5SDimitry Andric         I = CastInst::Create(CastOp, Op, ResTy);
49520b57cec5SDimitry Andric       }
4953c9157d92SDimitry Andric       if (OpNum < Record.size() && isa<PossiblyNonNegInst>(I) &&
4954c9157d92SDimitry Andric           (Record[OpNum] & (1 << bitc::PNNI_NON_NEG)))
4955c9157d92SDimitry Andric         I->setNonNeg(true);
49560b57cec5SDimitry Andric       InstructionList.push_back(I);
49570b57cec5SDimitry Andric       break;
49580b57cec5SDimitry Andric     }
49590b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
49600b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_GEP_OLD:
49610b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
49620b57cec5SDimitry Andric       unsigned OpNum = 0;
49630b57cec5SDimitry Andric 
496481ad6265SDimitry Andric       unsigned TyID;
49650b57cec5SDimitry Andric       Type *Ty;
49660b57cec5SDimitry Andric       bool InBounds;
49670b57cec5SDimitry Andric 
49680b57cec5SDimitry Andric       if (BitCode == bitc::FUNC_CODE_INST_GEP) {
49690b57cec5SDimitry Andric         InBounds = Record[OpNum++];
497081ad6265SDimitry Andric         TyID = Record[OpNum++];
497181ad6265SDimitry Andric         Ty = getTypeByID(TyID);
49720b57cec5SDimitry Andric       } else {
49730b57cec5SDimitry Andric         InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
497481ad6265SDimitry Andric         TyID = InvalidTypeID;
49750b57cec5SDimitry Andric         Ty = nullptr;
49760b57cec5SDimitry Andric       }
49770b57cec5SDimitry Andric 
49780b57cec5SDimitry Andric       Value *BasePtr;
497981ad6265SDimitry Andric       unsigned BasePtrTypeID;
498081ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr, BasePtrTypeID,
498181ad6265SDimitry Andric                            CurBB))
49820b57cec5SDimitry Andric         return error("Invalid record");
49830b57cec5SDimitry Andric 
49840b57cec5SDimitry Andric       if (!Ty) {
498581ad6265SDimitry Andric         TyID = getContainedTypeID(BasePtrTypeID);
498681ad6265SDimitry Andric         if (BasePtr->getType()->isVectorTy())
498781ad6265SDimitry Andric           TyID = getContainedTypeID(TyID);
498881ad6265SDimitry Andric         Ty = getTypeByID(TyID);
4989fe6060f1SDimitry Andric       }
49900b57cec5SDimitry Andric 
49910b57cec5SDimitry Andric       SmallVector<Value*, 16> GEPIdx;
49920b57cec5SDimitry Andric       while (OpNum != Record.size()) {
49930b57cec5SDimitry Andric         Value *Op;
499481ad6265SDimitry Andric         unsigned OpTypeID;
499581ad6265SDimitry Andric         if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
49960b57cec5SDimitry Andric           return error("Invalid record");
49970b57cec5SDimitry Andric         GEPIdx.push_back(Op);
49980b57cec5SDimitry Andric       }
49990b57cec5SDimitry Andric 
50000b57cec5SDimitry Andric       I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
50010b57cec5SDimitry Andric 
500281ad6265SDimitry Andric       ResTypeID = TyID;
500381ad6265SDimitry Andric       if (cast<GEPOperator>(I)->getNumIndices() != 0) {
500481ad6265SDimitry Andric         auto GTI = std::next(gep_type_begin(I));
500581ad6265SDimitry Andric         for (Value *Idx : drop_begin(cast<GEPOperator>(I)->indices())) {
500681ad6265SDimitry Andric           unsigned SubType = 0;
500781ad6265SDimitry Andric           if (GTI.isStruct()) {
500881ad6265SDimitry Andric             ConstantInt *IdxC =
500981ad6265SDimitry Andric                 Idx->getType()->isVectorTy()
501081ad6265SDimitry Andric                     ? cast<ConstantInt>(cast<Constant>(Idx)->getSplatValue())
501181ad6265SDimitry Andric                     : cast<ConstantInt>(Idx);
501281ad6265SDimitry Andric             SubType = IdxC->getZExtValue();
501381ad6265SDimitry Andric           }
501481ad6265SDimitry Andric           ResTypeID = getContainedTypeID(ResTypeID, SubType);
501581ad6265SDimitry Andric           ++GTI;
501681ad6265SDimitry Andric         }
501781ad6265SDimitry Andric       }
501881ad6265SDimitry Andric 
501981ad6265SDimitry Andric       // At this point ResTypeID is the result element type. We need a pointer
502081ad6265SDimitry Andric       // or vector of pointer to it.
502181ad6265SDimitry Andric       ResTypeID = getVirtualTypeID(I->getType()->getScalarType(), ResTypeID);
502281ad6265SDimitry Andric       if (I->getType()->isVectorTy())
502381ad6265SDimitry Andric         ResTypeID = getVirtualTypeID(I->getType(), ResTypeID);
502481ad6265SDimitry Andric 
50250b57cec5SDimitry Andric       InstructionList.push_back(I);
50260b57cec5SDimitry Andric       if (InBounds)
50270b57cec5SDimitry Andric         cast<GetElementPtrInst>(I)->setIsInBounds(true);
50280b57cec5SDimitry Andric       break;
50290b57cec5SDimitry Andric     }
50300b57cec5SDimitry Andric 
50310b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_EXTRACTVAL: {
50320b57cec5SDimitry Andric                                        // EXTRACTVAL: [opty, opval, n x indices]
50330b57cec5SDimitry Andric       unsigned OpNum = 0;
50340b57cec5SDimitry Andric       Value *Agg;
503581ad6265SDimitry Andric       unsigned AggTypeID;
503681ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
50370b57cec5SDimitry Andric         return error("Invalid record");
5038fe6060f1SDimitry Andric       Type *Ty = Agg->getType();
50390b57cec5SDimitry Andric 
50400b57cec5SDimitry Andric       unsigned RecSize = Record.size();
50410b57cec5SDimitry Andric       if (OpNum == RecSize)
50420b57cec5SDimitry Andric         return error("EXTRACTVAL: Invalid instruction with 0 indices");
50430b57cec5SDimitry Andric 
50440b57cec5SDimitry Andric       SmallVector<unsigned, 4> EXTRACTVALIdx;
504581ad6265SDimitry Andric       ResTypeID = AggTypeID;
50460b57cec5SDimitry Andric       for (; OpNum != RecSize; ++OpNum) {
5047fe6060f1SDimitry Andric         bool IsArray = Ty->isArrayTy();
5048fe6060f1SDimitry Andric         bool IsStruct = Ty->isStructTy();
50490b57cec5SDimitry Andric         uint64_t Index = Record[OpNum];
50500b57cec5SDimitry Andric 
50510b57cec5SDimitry Andric         if (!IsStruct && !IsArray)
50520b57cec5SDimitry Andric           return error("EXTRACTVAL: Invalid type");
50530b57cec5SDimitry Andric         if ((unsigned)Index != Index)
50540b57cec5SDimitry Andric           return error("Invalid value");
5055fe6060f1SDimitry Andric         if (IsStruct && Index >= Ty->getStructNumElements())
50560b57cec5SDimitry Andric           return error("EXTRACTVAL: Invalid struct index");
5057fe6060f1SDimitry Andric         if (IsArray && Index >= Ty->getArrayNumElements())
50580b57cec5SDimitry Andric           return error("EXTRACTVAL: Invalid array index");
50590b57cec5SDimitry Andric         EXTRACTVALIdx.push_back((unsigned)Index);
50600b57cec5SDimitry Andric 
506181ad6265SDimitry Andric         if (IsStruct) {
5062fe6060f1SDimitry Andric           Ty = Ty->getStructElementType(Index);
506381ad6265SDimitry Andric           ResTypeID = getContainedTypeID(ResTypeID, Index);
506481ad6265SDimitry Andric         } else {
5065fe6060f1SDimitry Andric           Ty = Ty->getArrayElementType();
506681ad6265SDimitry Andric           ResTypeID = getContainedTypeID(ResTypeID);
506781ad6265SDimitry Andric         }
50680b57cec5SDimitry Andric       }
50690b57cec5SDimitry Andric 
50700b57cec5SDimitry Andric       I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
50710b57cec5SDimitry Andric       InstructionList.push_back(I);
50720b57cec5SDimitry Andric       break;
50730b57cec5SDimitry Andric     }
50740b57cec5SDimitry Andric 
50750b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_INSERTVAL: {
50760b57cec5SDimitry Andric                            // INSERTVAL: [opty, opval, opty, opval, n x indices]
50770b57cec5SDimitry Andric       unsigned OpNum = 0;
50780b57cec5SDimitry Andric       Value *Agg;
507981ad6265SDimitry Andric       unsigned AggTypeID;
508081ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
50810b57cec5SDimitry Andric         return error("Invalid record");
50820b57cec5SDimitry Andric       Value *Val;
508381ad6265SDimitry Andric       unsigned ValTypeID;
508481ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
50850b57cec5SDimitry Andric         return error("Invalid record");
50860b57cec5SDimitry Andric 
50870b57cec5SDimitry Andric       unsigned RecSize = Record.size();
50880b57cec5SDimitry Andric       if (OpNum == RecSize)
50890b57cec5SDimitry Andric         return error("INSERTVAL: Invalid instruction with 0 indices");
50900b57cec5SDimitry Andric 
50910b57cec5SDimitry Andric       SmallVector<unsigned, 4> INSERTVALIdx;
50920b57cec5SDimitry Andric       Type *CurTy = Agg->getType();
50930b57cec5SDimitry Andric       for (; OpNum != RecSize; ++OpNum) {
50940b57cec5SDimitry Andric         bool IsArray = CurTy->isArrayTy();
50950b57cec5SDimitry Andric         bool IsStruct = CurTy->isStructTy();
50960b57cec5SDimitry Andric         uint64_t Index = Record[OpNum];
50970b57cec5SDimitry Andric 
50980b57cec5SDimitry Andric         if (!IsStruct && !IsArray)
50990b57cec5SDimitry Andric           return error("INSERTVAL: Invalid type");
51000b57cec5SDimitry Andric         if ((unsigned)Index != Index)
51010b57cec5SDimitry Andric           return error("Invalid value");
51020b57cec5SDimitry Andric         if (IsStruct && Index >= CurTy->getStructNumElements())
51030b57cec5SDimitry Andric           return error("INSERTVAL: Invalid struct index");
51040b57cec5SDimitry Andric         if (IsArray && Index >= CurTy->getArrayNumElements())
51050b57cec5SDimitry Andric           return error("INSERTVAL: Invalid array index");
51060b57cec5SDimitry Andric 
51070b57cec5SDimitry Andric         INSERTVALIdx.push_back((unsigned)Index);
51080b57cec5SDimitry Andric         if (IsStruct)
51090b57cec5SDimitry Andric           CurTy = CurTy->getStructElementType(Index);
51100b57cec5SDimitry Andric         else
51110b57cec5SDimitry Andric           CurTy = CurTy->getArrayElementType();
51120b57cec5SDimitry Andric       }
51130b57cec5SDimitry Andric 
51140b57cec5SDimitry Andric       if (CurTy != Val->getType())
51150b57cec5SDimitry Andric         return error("Inserted value type doesn't match aggregate type");
51160b57cec5SDimitry Andric 
51170b57cec5SDimitry Andric       I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
511881ad6265SDimitry Andric       ResTypeID = AggTypeID;
51190b57cec5SDimitry Andric       InstructionList.push_back(I);
51200b57cec5SDimitry Andric       break;
51210b57cec5SDimitry Andric     }
51220b57cec5SDimitry Andric 
51230b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
51240b57cec5SDimitry Andric       // obsolete form of select
51250b57cec5SDimitry Andric       // handles select i1 ... in old bitcode
51260b57cec5SDimitry Andric       unsigned OpNum = 0;
51270b57cec5SDimitry Andric       Value *TrueVal, *FalseVal, *Cond;
512881ad6265SDimitry Andric       unsigned TypeID;
512981ad6265SDimitry Andric       Type *CondType = Type::getInt1Ty(Context);
513081ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, TypeID,
513181ad6265SDimitry Andric                            CurBB) ||
513281ad6265SDimitry Andric           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), TypeID,
513381ad6265SDimitry Andric                    FalseVal, CurBB) ||
513481ad6265SDimitry Andric           popValue(Record, OpNum, NextValueNo, CondType,
513581ad6265SDimitry Andric                    getVirtualTypeID(CondType), Cond, CurBB))
51360b57cec5SDimitry Andric         return error("Invalid record");
51370b57cec5SDimitry Andric 
51380b57cec5SDimitry Andric       I = SelectInst::Create(Cond, TrueVal, FalseVal);
513981ad6265SDimitry Andric       ResTypeID = TypeID;
51400b57cec5SDimitry Andric       InstructionList.push_back(I);
51410b57cec5SDimitry Andric       break;
51420b57cec5SDimitry Andric     }
51430b57cec5SDimitry Andric 
51440b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
51450b57cec5SDimitry Andric       // new form of select
51460b57cec5SDimitry Andric       // handles select i1 or select [N x i1]
51470b57cec5SDimitry Andric       unsigned OpNum = 0;
51480b57cec5SDimitry Andric       Value *TrueVal, *FalseVal, *Cond;
514981ad6265SDimitry Andric       unsigned ValTypeID, CondTypeID;
515081ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, ValTypeID,
515181ad6265SDimitry Andric                            CurBB) ||
515281ad6265SDimitry Andric           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), ValTypeID,
515381ad6265SDimitry Andric                    FalseVal, CurBB) ||
515481ad6265SDimitry Andric           getValueTypePair(Record, OpNum, NextValueNo, Cond, CondTypeID, CurBB))
51550b57cec5SDimitry Andric         return error("Invalid record");
51560b57cec5SDimitry Andric 
51570b57cec5SDimitry Andric       // select condition can be either i1 or [N x i1]
51580b57cec5SDimitry Andric       if (VectorType* vector_type =
51590b57cec5SDimitry Andric           dyn_cast<VectorType>(Cond->getType())) {
51600b57cec5SDimitry Andric         // expect <n x i1>
51610b57cec5SDimitry Andric         if (vector_type->getElementType() != Type::getInt1Ty(Context))
51620b57cec5SDimitry Andric           return error("Invalid type for value");
51630b57cec5SDimitry Andric       } else {
51640b57cec5SDimitry Andric         // expect i1
51650b57cec5SDimitry Andric         if (Cond->getType() != Type::getInt1Ty(Context))
51660b57cec5SDimitry Andric           return error("Invalid type for value");
51670b57cec5SDimitry Andric       }
51680b57cec5SDimitry Andric 
51690b57cec5SDimitry Andric       I = SelectInst::Create(Cond, TrueVal, FalseVal);
517081ad6265SDimitry Andric       ResTypeID = ValTypeID;
51710b57cec5SDimitry Andric       InstructionList.push_back(I);
51720b57cec5SDimitry Andric       if (OpNum < Record.size() && isa<FPMathOperator>(I)) {
51730b57cec5SDimitry Andric         FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
51740b57cec5SDimitry Andric         if (FMF.any())
51750b57cec5SDimitry Andric           I->setFastMathFlags(FMF);
51760b57cec5SDimitry Andric       }
51770b57cec5SDimitry Andric       break;
51780b57cec5SDimitry Andric     }
51790b57cec5SDimitry Andric 
51800b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
51810b57cec5SDimitry Andric       unsigned OpNum = 0;
51820b57cec5SDimitry Andric       Value *Vec, *Idx;
518381ad6265SDimitry Andric       unsigned VecTypeID, IdxTypeID;
518481ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB) ||
518581ad6265SDimitry Andric           getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB))
51860b57cec5SDimitry Andric         return error("Invalid record");
51870b57cec5SDimitry Andric       if (!Vec->getType()->isVectorTy())
51880b57cec5SDimitry Andric         return error("Invalid type for value");
51890b57cec5SDimitry Andric       I = ExtractElementInst::Create(Vec, Idx);
519081ad6265SDimitry Andric       ResTypeID = getContainedTypeID(VecTypeID);
51910b57cec5SDimitry Andric       InstructionList.push_back(I);
51920b57cec5SDimitry Andric       break;
51930b57cec5SDimitry Andric     }
51940b57cec5SDimitry Andric 
51950b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
51960b57cec5SDimitry Andric       unsigned OpNum = 0;
51970b57cec5SDimitry Andric       Value *Vec, *Elt, *Idx;
519881ad6265SDimitry Andric       unsigned VecTypeID, IdxTypeID;
519981ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB))
52000b57cec5SDimitry Andric         return error("Invalid record");
52010b57cec5SDimitry Andric       if (!Vec->getType()->isVectorTy())
52020b57cec5SDimitry Andric         return error("Invalid type for value");
52030b57cec5SDimitry Andric       if (popValue(Record, OpNum, NextValueNo,
520481ad6265SDimitry Andric                    cast<VectorType>(Vec->getType())->getElementType(),
520581ad6265SDimitry Andric                    getContainedTypeID(VecTypeID), Elt, CurBB) ||
520681ad6265SDimitry Andric           getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB))
52070b57cec5SDimitry Andric         return error("Invalid record");
52080b57cec5SDimitry Andric       I = InsertElementInst::Create(Vec, Elt, Idx);
520981ad6265SDimitry Andric       ResTypeID = VecTypeID;
52100b57cec5SDimitry Andric       InstructionList.push_back(I);
52110b57cec5SDimitry Andric       break;
52120b57cec5SDimitry Andric     }
52130b57cec5SDimitry Andric 
52140b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
52150b57cec5SDimitry Andric       unsigned OpNum = 0;
52160b57cec5SDimitry Andric       Value *Vec1, *Vec2, *Mask;
521781ad6265SDimitry Andric       unsigned Vec1TypeID;
521881ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Vec1, Vec1TypeID,
521981ad6265SDimitry Andric                            CurBB) ||
522081ad6265SDimitry Andric           popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec1TypeID,
522181ad6265SDimitry Andric                    Vec2, CurBB))
52220b57cec5SDimitry Andric         return error("Invalid record");
52230b57cec5SDimitry Andric 
522481ad6265SDimitry Andric       unsigned MaskTypeID;
522581ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Mask, MaskTypeID, CurBB))
52260b57cec5SDimitry Andric         return error("Invalid record");
52270b57cec5SDimitry Andric       if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
52280b57cec5SDimitry Andric         return error("Invalid type for value");
52295ffd83dbSDimitry Andric 
52300b57cec5SDimitry Andric       I = new ShuffleVectorInst(Vec1, Vec2, Mask);
523181ad6265SDimitry Andric       ResTypeID =
523281ad6265SDimitry Andric           getVirtualTypeID(I->getType(), getContainedTypeID(Vec1TypeID));
52330b57cec5SDimitry Andric       InstructionList.push_back(I);
52340b57cec5SDimitry Andric       break;
52350b57cec5SDimitry Andric     }
52360b57cec5SDimitry Andric 
52370b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
52380b57cec5SDimitry Andric       // Old form of ICmp/FCmp returning bool
52390b57cec5SDimitry Andric       // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
52400b57cec5SDimitry Andric       // both legal on vectors but had different behaviour.
52410b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
52420b57cec5SDimitry Andric       // FCmp/ICmp returning bool or vector of bool
52430b57cec5SDimitry Andric 
52440b57cec5SDimitry Andric       unsigned OpNum = 0;
52450b57cec5SDimitry Andric       Value *LHS, *RHS;
524681ad6265SDimitry Andric       unsigned LHSTypeID;
524781ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, LHS, LHSTypeID, CurBB) ||
524881ad6265SDimitry Andric           popValue(Record, OpNum, NextValueNo, LHS->getType(), LHSTypeID, RHS,
524981ad6265SDimitry Andric                    CurBB))
52500b57cec5SDimitry Andric         return error("Invalid record");
52510b57cec5SDimitry Andric 
52520b57cec5SDimitry Andric       if (OpNum >= Record.size())
52530b57cec5SDimitry Andric         return error(
52540b57cec5SDimitry Andric             "Invalid record: operand number exceeded available operands");
52550b57cec5SDimitry Andric 
5256c9157d92SDimitry Andric       CmpInst::Predicate PredVal = CmpInst::Predicate(Record[OpNum]);
52570b57cec5SDimitry Andric       bool IsFP = LHS->getType()->isFPOrFPVectorTy();
52580b57cec5SDimitry Andric       FastMathFlags FMF;
52590b57cec5SDimitry Andric       if (IsFP && Record.size() > OpNum+1)
52600b57cec5SDimitry Andric         FMF = getDecodedFastMathFlags(Record[++OpNum]);
52610b57cec5SDimitry Andric 
52620b57cec5SDimitry Andric       if (OpNum+1 != Record.size())
52630b57cec5SDimitry Andric         return error("Invalid record");
52640b57cec5SDimitry Andric 
5265c9157d92SDimitry Andric       if (IsFP) {
5266c9157d92SDimitry Andric         if (!CmpInst::isFPPredicate(PredVal))
5267c9157d92SDimitry Andric           return error("Invalid fcmp predicate");
5268c9157d92SDimitry Andric         I = new FCmpInst(PredVal, LHS, RHS);
5269c9157d92SDimitry Andric       } else {
5270c9157d92SDimitry Andric         if (!CmpInst::isIntPredicate(PredVal))
5271c9157d92SDimitry Andric           return error("Invalid icmp predicate");
5272c9157d92SDimitry Andric         I = new ICmpInst(PredVal, LHS, RHS);
5273c9157d92SDimitry Andric       }
52740b57cec5SDimitry Andric 
527581ad6265SDimitry Andric       ResTypeID = getVirtualTypeID(I->getType()->getScalarType());
527681ad6265SDimitry Andric       if (LHS->getType()->isVectorTy())
527781ad6265SDimitry Andric         ResTypeID = getVirtualTypeID(I->getType(), ResTypeID);
527881ad6265SDimitry Andric 
52790b57cec5SDimitry Andric       if (FMF.any())
52800b57cec5SDimitry Andric         I->setFastMathFlags(FMF);
52810b57cec5SDimitry Andric       InstructionList.push_back(I);
52820b57cec5SDimitry Andric       break;
52830b57cec5SDimitry Andric     }
52840b57cec5SDimitry Andric 
52850b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
52860b57cec5SDimitry Andric       {
52870b57cec5SDimitry Andric         unsigned Size = Record.size();
52880b57cec5SDimitry Andric         if (Size == 0) {
52890b57cec5SDimitry Andric           I = ReturnInst::Create(Context);
52900b57cec5SDimitry Andric           InstructionList.push_back(I);
52910b57cec5SDimitry Andric           break;
52920b57cec5SDimitry Andric         }
52930b57cec5SDimitry Andric 
52940b57cec5SDimitry Andric         unsigned OpNum = 0;
52950b57cec5SDimitry Andric         Value *Op = nullptr;
529681ad6265SDimitry Andric         unsigned OpTypeID;
529781ad6265SDimitry Andric         if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
52980b57cec5SDimitry Andric           return error("Invalid record");
52990b57cec5SDimitry Andric         if (OpNum != Record.size())
53000b57cec5SDimitry Andric           return error("Invalid record");
53010b57cec5SDimitry Andric 
53020b57cec5SDimitry Andric         I = ReturnInst::Create(Context, Op);
53030b57cec5SDimitry Andric         InstructionList.push_back(I);
53040b57cec5SDimitry Andric         break;
53050b57cec5SDimitry Andric       }
53060b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
53070b57cec5SDimitry Andric       if (Record.size() != 1 && Record.size() != 3)
53080b57cec5SDimitry Andric         return error("Invalid record");
53090b57cec5SDimitry Andric       BasicBlock *TrueDest = getBasicBlock(Record[0]);
53100b57cec5SDimitry Andric       if (!TrueDest)
53110b57cec5SDimitry Andric         return error("Invalid record");
53120b57cec5SDimitry Andric 
53130b57cec5SDimitry Andric       if (Record.size() == 1) {
53140b57cec5SDimitry Andric         I = BranchInst::Create(TrueDest);
53150b57cec5SDimitry Andric         InstructionList.push_back(I);
53160b57cec5SDimitry Andric       }
53170b57cec5SDimitry Andric       else {
53180b57cec5SDimitry Andric         BasicBlock *FalseDest = getBasicBlock(Record[1]);
531981ad6265SDimitry Andric         Type *CondType = Type::getInt1Ty(Context);
532081ad6265SDimitry Andric         Value *Cond = getValue(Record, 2, NextValueNo, CondType,
532181ad6265SDimitry Andric                                getVirtualTypeID(CondType), CurBB);
53220b57cec5SDimitry Andric         if (!FalseDest || !Cond)
53230b57cec5SDimitry Andric           return error("Invalid record");
53240b57cec5SDimitry Andric         I = BranchInst::Create(TrueDest, FalseDest, Cond);
53250b57cec5SDimitry Andric         InstructionList.push_back(I);
53260b57cec5SDimitry Andric       }
53270b57cec5SDimitry Andric       break;
53280b57cec5SDimitry Andric     }
53290b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
53300b57cec5SDimitry Andric       if (Record.size() != 1 && Record.size() != 2)
53310b57cec5SDimitry Andric         return error("Invalid record");
53320b57cec5SDimitry Andric       unsigned Idx = 0;
533381ad6265SDimitry Andric       Type *TokenTy = Type::getTokenTy(Context);
533481ad6265SDimitry Andric       Value *CleanupPad = getValue(Record, Idx++, NextValueNo, TokenTy,
533581ad6265SDimitry Andric                                    getVirtualTypeID(TokenTy), CurBB);
53360b57cec5SDimitry Andric       if (!CleanupPad)
53370b57cec5SDimitry Andric         return error("Invalid record");
53380b57cec5SDimitry Andric       BasicBlock *UnwindDest = nullptr;
53390b57cec5SDimitry Andric       if (Record.size() == 2) {
53400b57cec5SDimitry Andric         UnwindDest = getBasicBlock(Record[Idx++]);
53410b57cec5SDimitry Andric         if (!UnwindDest)
53420b57cec5SDimitry Andric           return error("Invalid record");
53430b57cec5SDimitry Andric       }
53440b57cec5SDimitry Andric 
53450b57cec5SDimitry Andric       I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
53460b57cec5SDimitry Andric       InstructionList.push_back(I);
53470b57cec5SDimitry Andric       break;
53480b57cec5SDimitry Andric     }
53490b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
53500b57cec5SDimitry Andric       if (Record.size() != 2)
53510b57cec5SDimitry Andric         return error("Invalid record");
53520b57cec5SDimitry Andric       unsigned Idx = 0;
535381ad6265SDimitry Andric       Type *TokenTy = Type::getTokenTy(Context);
535481ad6265SDimitry Andric       Value *CatchPad = getValue(Record, Idx++, NextValueNo, TokenTy,
535581ad6265SDimitry Andric                                  getVirtualTypeID(TokenTy), CurBB);
53560b57cec5SDimitry Andric       if (!CatchPad)
53570b57cec5SDimitry Andric         return error("Invalid record");
53580b57cec5SDimitry Andric       BasicBlock *BB = getBasicBlock(Record[Idx++]);
53590b57cec5SDimitry Andric       if (!BB)
53600b57cec5SDimitry Andric         return error("Invalid record");
53610b57cec5SDimitry Andric 
53620b57cec5SDimitry Andric       I = CatchReturnInst::Create(CatchPad, BB);
53630b57cec5SDimitry Andric       InstructionList.push_back(I);
53640b57cec5SDimitry Andric       break;
53650b57cec5SDimitry Andric     }
53660b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
53670b57cec5SDimitry Andric       // We must have, at minimum, the outer scope and the number of arguments.
53680b57cec5SDimitry Andric       if (Record.size() < 2)
53690b57cec5SDimitry Andric         return error("Invalid record");
53700b57cec5SDimitry Andric 
53710b57cec5SDimitry Andric       unsigned Idx = 0;
53720b57cec5SDimitry Andric 
537381ad6265SDimitry Andric       Type *TokenTy = Type::getTokenTy(Context);
537481ad6265SDimitry Andric       Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy,
537581ad6265SDimitry Andric                                   getVirtualTypeID(TokenTy), CurBB);
5376c9157d92SDimitry Andric       if (!ParentPad)
5377c9157d92SDimitry Andric         return error("Invalid record");
53780b57cec5SDimitry Andric 
53790b57cec5SDimitry Andric       unsigned NumHandlers = Record[Idx++];
53800b57cec5SDimitry Andric 
53810b57cec5SDimitry Andric       SmallVector<BasicBlock *, 2> Handlers;
53820b57cec5SDimitry Andric       for (unsigned Op = 0; Op != NumHandlers; ++Op) {
53830b57cec5SDimitry Andric         BasicBlock *BB = getBasicBlock(Record[Idx++]);
53840b57cec5SDimitry Andric         if (!BB)
53850b57cec5SDimitry Andric           return error("Invalid record");
53860b57cec5SDimitry Andric         Handlers.push_back(BB);
53870b57cec5SDimitry Andric       }
53880b57cec5SDimitry Andric 
53890b57cec5SDimitry Andric       BasicBlock *UnwindDest = nullptr;
53900b57cec5SDimitry Andric       if (Idx + 1 == Record.size()) {
53910b57cec5SDimitry Andric         UnwindDest = getBasicBlock(Record[Idx++]);
53920b57cec5SDimitry Andric         if (!UnwindDest)
53930b57cec5SDimitry Andric           return error("Invalid record");
53940b57cec5SDimitry Andric       }
53950b57cec5SDimitry Andric 
53960b57cec5SDimitry Andric       if (Record.size() != Idx)
53970b57cec5SDimitry Andric         return error("Invalid record");
53980b57cec5SDimitry Andric 
53990b57cec5SDimitry Andric       auto *CatchSwitch =
54000b57cec5SDimitry Andric           CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
54010b57cec5SDimitry Andric       for (BasicBlock *Handler : Handlers)
54020b57cec5SDimitry Andric         CatchSwitch->addHandler(Handler);
54030b57cec5SDimitry Andric       I = CatchSwitch;
540481ad6265SDimitry Andric       ResTypeID = getVirtualTypeID(I->getType());
54050b57cec5SDimitry Andric       InstructionList.push_back(I);
54060b57cec5SDimitry Andric       break;
54070b57cec5SDimitry Andric     }
54080b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CATCHPAD:
54090b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
54100b57cec5SDimitry Andric       // We must have, at minimum, the outer scope and the number of arguments.
54110b57cec5SDimitry Andric       if (Record.size() < 2)
54120b57cec5SDimitry Andric         return error("Invalid record");
54130b57cec5SDimitry Andric 
54140b57cec5SDimitry Andric       unsigned Idx = 0;
54150b57cec5SDimitry Andric 
541681ad6265SDimitry Andric       Type *TokenTy = Type::getTokenTy(Context);
541781ad6265SDimitry Andric       Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy,
541881ad6265SDimitry Andric                                   getVirtualTypeID(TokenTy), CurBB);
5419c9157d92SDimitry Andric       if (!ParentPad)
5420c9157d92SDimitry Andric         return error("Invald record");
54210b57cec5SDimitry Andric 
54220b57cec5SDimitry Andric       unsigned NumArgOperands = Record[Idx++];
54230b57cec5SDimitry Andric 
54240b57cec5SDimitry Andric       SmallVector<Value *, 2> Args;
54250b57cec5SDimitry Andric       for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
54260b57cec5SDimitry Andric         Value *Val;
542781ad6265SDimitry Andric         unsigned ValTypeID;
542881ad6265SDimitry Andric         if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, nullptr))
54290b57cec5SDimitry Andric           return error("Invalid record");
54300b57cec5SDimitry Andric         Args.push_back(Val);
54310b57cec5SDimitry Andric       }
54320b57cec5SDimitry Andric 
54330b57cec5SDimitry Andric       if (Record.size() != Idx)
54340b57cec5SDimitry Andric         return error("Invalid record");
54350b57cec5SDimitry Andric 
54360b57cec5SDimitry Andric       if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
54370b57cec5SDimitry Andric         I = CleanupPadInst::Create(ParentPad, Args);
54380b57cec5SDimitry Andric       else
54390b57cec5SDimitry Andric         I = CatchPadInst::Create(ParentPad, Args);
544081ad6265SDimitry Andric       ResTypeID = getVirtualTypeID(I->getType());
54410b57cec5SDimitry Andric       InstructionList.push_back(I);
54420b57cec5SDimitry Andric       break;
54430b57cec5SDimitry Andric     }
54440b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
54450b57cec5SDimitry Andric       // Check magic
54460b57cec5SDimitry Andric       if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
54470b57cec5SDimitry Andric         // "New" SwitchInst format with case ranges. The changes to write this
54480b57cec5SDimitry Andric         // format were reverted but we still recognize bitcode that uses it.
54490b57cec5SDimitry Andric         // Hopefully someday we will have support for case ranges and can use
54500b57cec5SDimitry Andric         // this format again.
54510b57cec5SDimitry Andric 
545281ad6265SDimitry Andric         unsigned OpTyID = Record[1];
545381ad6265SDimitry Andric         Type *OpTy = getTypeByID(OpTyID);
54540b57cec5SDimitry Andric         unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
54550b57cec5SDimitry Andric 
545681ad6265SDimitry Andric         Value *Cond = getValue(Record, 2, NextValueNo, OpTy, OpTyID, CurBB);
54570b57cec5SDimitry Andric         BasicBlock *Default = getBasicBlock(Record[3]);
54580b57cec5SDimitry Andric         if (!OpTy || !Cond || !Default)
54590b57cec5SDimitry Andric           return error("Invalid record");
54600b57cec5SDimitry Andric 
54610b57cec5SDimitry Andric         unsigned NumCases = Record[4];
54620b57cec5SDimitry Andric 
54630b57cec5SDimitry Andric         SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
54640b57cec5SDimitry Andric         InstructionList.push_back(SI);
54650b57cec5SDimitry Andric 
54660b57cec5SDimitry Andric         unsigned CurIdx = 5;
54670b57cec5SDimitry Andric         for (unsigned i = 0; i != NumCases; ++i) {
54680b57cec5SDimitry Andric           SmallVector<ConstantInt*, 1> CaseVals;
54690b57cec5SDimitry Andric           unsigned NumItems = Record[CurIdx++];
54700b57cec5SDimitry Andric           for (unsigned ci = 0; ci != NumItems; ++ci) {
54710b57cec5SDimitry Andric             bool isSingleNumber = Record[CurIdx++];
54720b57cec5SDimitry Andric 
54730b57cec5SDimitry Andric             APInt Low;
54740b57cec5SDimitry Andric             unsigned ActiveWords = 1;
54750b57cec5SDimitry Andric             if (ValueBitWidth > 64)
54760b57cec5SDimitry Andric               ActiveWords = Record[CurIdx++];
5477bdd1243dSDimitry Andric             Low = readWideAPInt(ArrayRef(&Record[CurIdx], ActiveWords),
54780b57cec5SDimitry Andric                                 ValueBitWidth);
54790b57cec5SDimitry Andric             CurIdx += ActiveWords;
54800b57cec5SDimitry Andric 
54810b57cec5SDimitry Andric             if (!isSingleNumber) {
54820b57cec5SDimitry Andric               ActiveWords = 1;
54830b57cec5SDimitry Andric               if (ValueBitWidth > 64)
54840b57cec5SDimitry Andric                 ActiveWords = Record[CurIdx++];
5485bdd1243dSDimitry Andric               APInt High = readWideAPInt(ArrayRef(&Record[CurIdx], ActiveWords),
5486bdd1243dSDimitry Andric                                          ValueBitWidth);
54870b57cec5SDimitry Andric               CurIdx += ActiveWords;
54880b57cec5SDimitry Andric 
54890b57cec5SDimitry Andric               // FIXME: It is not clear whether values in the range should be
54900b57cec5SDimitry Andric               // compared as signed or unsigned values. The partially
54910b57cec5SDimitry Andric               // implemented changes that used this format in the past used
54920b57cec5SDimitry Andric               // unsigned comparisons.
54930b57cec5SDimitry Andric               for ( ; Low.ule(High); ++Low)
54940b57cec5SDimitry Andric                 CaseVals.push_back(ConstantInt::get(Context, Low));
54950b57cec5SDimitry Andric             } else
54960b57cec5SDimitry Andric               CaseVals.push_back(ConstantInt::get(Context, Low));
54970b57cec5SDimitry Andric           }
54980b57cec5SDimitry Andric           BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
54994824e7fdSDimitry Andric           for (ConstantInt *Cst : CaseVals)
55004824e7fdSDimitry Andric             SI->addCase(Cst, DestBB);
55010b57cec5SDimitry Andric         }
55020b57cec5SDimitry Andric         I = SI;
55030b57cec5SDimitry Andric         break;
55040b57cec5SDimitry Andric       }
55050b57cec5SDimitry Andric 
55060b57cec5SDimitry Andric       // Old SwitchInst format without case ranges.
55070b57cec5SDimitry Andric 
55080b57cec5SDimitry Andric       if (Record.size() < 3 || (Record.size() & 1) == 0)
55090b57cec5SDimitry Andric         return error("Invalid record");
551081ad6265SDimitry Andric       unsigned OpTyID = Record[0];
551181ad6265SDimitry Andric       Type *OpTy = getTypeByID(OpTyID);
551281ad6265SDimitry Andric       Value *Cond = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
55130b57cec5SDimitry Andric       BasicBlock *Default = getBasicBlock(Record[2]);
55140b57cec5SDimitry Andric       if (!OpTy || !Cond || !Default)
55150b57cec5SDimitry Andric         return error("Invalid record");
55160b57cec5SDimitry Andric       unsigned NumCases = (Record.size()-3)/2;
55170b57cec5SDimitry Andric       SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
55180b57cec5SDimitry Andric       InstructionList.push_back(SI);
55190b57cec5SDimitry Andric       for (unsigned i = 0, e = NumCases; i != e; ++i) {
552081ad6265SDimitry Andric         ConstantInt *CaseVal = dyn_cast_or_null<ConstantInt>(
552181ad6265SDimitry Andric             getFnValueByID(Record[3+i*2], OpTy, OpTyID, nullptr));
55220b57cec5SDimitry Andric         BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
55230b57cec5SDimitry Andric         if (!CaseVal || !DestBB) {
55240b57cec5SDimitry Andric           delete SI;
55250b57cec5SDimitry Andric           return error("Invalid record");
55260b57cec5SDimitry Andric         }
55270b57cec5SDimitry Andric         SI->addCase(CaseVal, DestBB);
55280b57cec5SDimitry Andric       }
55290b57cec5SDimitry Andric       I = SI;
55300b57cec5SDimitry Andric       break;
55310b57cec5SDimitry Andric     }
55320b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
55330b57cec5SDimitry Andric       if (Record.size() < 2)
55340b57cec5SDimitry Andric         return error("Invalid record");
553581ad6265SDimitry Andric       unsigned OpTyID = Record[0];
553681ad6265SDimitry Andric       Type *OpTy = getTypeByID(OpTyID);
553781ad6265SDimitry Andric       Value *Address = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
55380b57cec5SDimitry Andric       if (!OpTy || !Address)
55390b57cec5SDimitry Andric         return error("Invalid record");
55400b57cec5SDimitry Andric       unsigned NumDests = Record.size()-2;
55410b57cec5SDimitry Andric       IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
55420b57cec5SDimitry Andric       InstructionList.push_back(IBI);
55430b57cec5SDimitry Andric       for (unsigned i = 0, e = NumDests; i != e; ++i) {
55440b57cec5SDimitry Andric         if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
55450b57cec5SDimitry Andric           IBI->addDestination(DestBB);
55460b57cec5SDimitry Andric         } else {
55470b57cec5SDimitry Andric           delete IBI;
55480b57cec5SDimitry Andric           return error("Invalid record");
55490b57cec5SDimitry Andric         }
55500b57cec5SDimitry Andric       }
55510b57cec5SDimitry Andric       I = IBI;
55520b57cec5SDimitry Andric       break;
55530b57cec5SDimitry Andric     }
55540b57cec5SDimitry Andric 
55550b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_INVOKE: {
55560b57cec5SDimitry Andric       // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
55570b57cec5SDimitry Andric       if (Record.size() < 4)
55580b57cec5SDimitry Andric         return error("Invalid record");
55590b57cec5SDimitry Andric       unsigned OpNum = 0;
55600b57cec5SDimitry Andric       AttributeList PAL = getAttributes(Record[OpNum++]);
55610b57cec5SDimitry Andric       unsigned CCInfo = Record[OpNum++];
55620b57cec5SDimitry Andric       BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
55630b57cec5SDimitry Andric       BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
55640b57cec5SDimitry Andric 
556581ad6265SDimitry Andric       unsigned FTyID = InvalidTypeID;
55660b57cec5SDimitry Andric       FunctionType *FTy = nullptr;
55670b57cec5SDimitry Andric       if ((CCInfo >> 13) & 1) {
556881ad6265SDimitry Andric         FTyID = Record[OpNum++];
556981ad6265SDimitry Andric         FTy = dyn_cast<FunctionType>(getTypeByID(FTyID));
5570fe6060f1SDimitry Andric         if (!FTy)
55710b57cec5SDimitry Andric           return error("Explicit invoke type is not a function type");
55720b57cec5SDimitry Andric       }
55730b57cec5SDimitry Andric 
55740b57cec5SDimitry Andric       Value *Callee;
557581ad6265SDimitry Andric       unsigned CalleeTypeID;
557681ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
557781ad6265SDimitry Andric                            CurBB))
55780b57cec5SDimitry Andric         return error("Invalid record");
55790b57cec5SDimitry Andric 
55800b57cec5SDimitry Andric       PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
55810b57cec5SDimitry Andric       if (!CalleeTy)
55820b57cec5SDimitry Andric         return error("Callee is not a pointer");
55830b57cec5SDimitry Andric       if (!FTy) {
558481ad6265SDimitry Andric         FTyID = getContainedTypeID(CalleeTypeID);
558581ad6265SDimitry Andric         FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
5586fe6060f1SDimitry Andric         if (!FTy)
55870b57cec5SDimitry Andric           return error("Callee is not of pointer to function type");
5588fe013be4SDimitry Andric       }
55890b57cec5SDimitry Andric       if (Record.size() < FTy->getNumParams() + OpNum)
55900b57cec5SDimitry Andric         return error("Insufficient operands to call");
55910b57cec5SDimitry Andric 
55920b57cec5SDimitry Andric       SmallVector<Value*, 16> Ops;
559381ad6265SDimitry Andric       SmallVector<unsigned, 16> ArgTyIDs;
55940b57cec5SDimitry Andric       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
559581ad6265SDimitry Andric         unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
559681ad6265SDimitry Andric         Ops.push_back(getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
559781ad6265SDimitry Andric                                ArgTyID, CurBB));
559881ad6265SDimitry Andric         ArgTyIDs.push_back(ArgTyID);
55990b57cec5SDimitry Andric         if (!Ops.back())
56000b57cec5SDimitry Andric           return error("Invalid record");
56010b57cec5SDimitry Andric       }
56020b57cec5SDimitry Andric 
56030b57cec5SDimitry Andric       if (!FTy->isVarArg()) {
56040b57cec5SDimitry Andric         if (Record.size() != OpNum)
56050b57cec5SDimitry Andric           return error("Invalid record");
56060b57cec5SDimitry Andric       } else {
56070b57cec5SDimitry Andric         // Read type/value pairs for varargs params.
56080b57cec5SDimitry Andric         while (OpNum != Record.size()) {
56090b57cec5SDimitry Andric           Value *Op;
561081ad6265SDimitry Andric           unsigned OpTypeID;
561181ad6265SDimitry Andric           if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
56120b57cec5SDimitry Andric             return error("Invalid record");
56130b57cec5SDimitry Andric           Ops.push_back(Op);
561481ad6265SDimitry Andric           ArgTyIDs.push_back(OpTypeID);
56150b57cec5SDimitry Andric         }
56160b57cec5SDimitry Andric       }
56170b57cec5SDimitry Andric 
561881ad6265SDimitry Andric       // Upgrade the bundles if needed.
561981ad6265SDimitry Andric       if (!OperandBundles.empty())
562081ad6265SDimitry Andric         UpgradeOperandBundles(OperandBundles);
562181ad6265SDimitry Andric 
56220b57cec5SDimitry Andric       I = InvokeInst::Create(FTy, Callee, NormalBB, UnwindBB, Ops,
56230b57cec5SDimitry Andric                              OperandBundles);
562481ad6265SDimitry Andric       ResTypeID = getContainedTypeID(FTyID);
56250b57cec5SDimitry Andric       OperandBundles.clear();
56260b57cec5SDimitry Andric       InstructionList.push_back(I);
56270b57cec5SDimitry Andric       cast<InvokeInst>(I)->setCallingConv(
56280b57cec5SDimitry Andric           static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
56290b57cec5SDimitry Andric       cast<InvokeInst>(I)->setAttributes(PAL);
563081ad6265SDimitry Andric       if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) {
563181ad6265SDimitry Andric         I->deleteValue();
563281ad6265SDimitry Andric         return Err;
563381ad6265SDimitry Andric       }
56340b57cec5SDimitry Andric 
56350b57cec5SDimitry Andric       break;
56360b57cec5SDimitry Andric     }
56370b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
56380b57cec5SDimitry Andric       unsigned Idx = 0;
56390b57cec5SDimitry Andric       Value *Val = nullptr;
564081ad6265SDimitry Andric       unsigned ValTypeID;
564181ad6265SDimitry Andric       if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, CurBB))
56420b57cec5SDimitry Andric         return error("Invalid record");
56430b57cec5SDimitry Andric       I = ResumeInst::Create(Val);
56440b57cec5SDimitry Andric       InstructionList.push_back(I);
56450b57cec5SDimitry Andric       break;
56460b57cec5SDimitry Andric     }
56470b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CALLBR: {
56480b57cec5SDimitry Andric       // CALLBR: [attr, cc, norm, transfs, fty, fnid, args]
56490b57cec5SDimitry Andric       unsigned OpNum = 0;
56500b57cec5SDimitry Andric       AttributeList PAL = getAttributes(Record[OpNum++]);
56510b57cec5SDimitry Andric       unsigned CCInfo = Record[OpNum++];
56520b57cec5SDimitry Andric 
56530b57cec5SDimitry Andric       BasicBlock *DefaultDest = getBasicBlock(Record[OpNum++]);
56540b57cec5SDimitry Andric       unsigned NumIndirectDests = Record[OpNum++];
56550b57cec5SDimitry Andric       SmallVector<BasicBlock *, 16> IndirectDests;
56560b57cec5SDimitry Andric       for (unsigned i = 0, e = NumIndirectDests; i != e; ++i)
56570b57cec5SDimitry Andric         IndirectDests.push_back(getBasicBlock(Record[OpNum++]));
56580b57cec5SDimitry Andric 
565981ad6265SDimitry Andric       unsigned FTyID = InvalidTypeID;
56600b57cec5SDimitry Andric       FunctionType *FTy = nullptr;
56610b57cec5SDimitry Andric       if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) {
566281ad6265SDimitry Andric         FTyID = Record[OpNum++];
566381ad6265SDimitry Andric         FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
5664fe6060f1SDimitry Andric         if (!FTy)
56650b57cec5SDimitry Andric           return error("Explicit call type is not a function type");
56660b57cec5SDimitry Andric       }
56670b57cec5SDimitry Andric 
56680b57cec5SDimitry Andric       Value *Callee;
566981ad6265SDimitry Andric       unsigned CalleeTypeID;
567081ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
567181ad6265SDimitry Andric                            CurBB))
56720b57cec5SDimitry Andric         return error("Invalid record");
56730b57cec5SDimitry Andric 
56740b57cec5SDimitry Andric       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
56750b57cec5SDimitry Andric       if (!OpTy)
56760b57cec5SDimitry Andric         return error("Callee is not a pointer type");
56770b57cec5SDimitry Andric       if (!FTy) {
567881ad6265SDimitry Andric         FTyID = getContainedTypeID(CalleeTypeID);
567981ad6265SDimitry Andric         FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
5680fe6060f1SDimitry Andric         if (!FTy)
56810b57cec5SDimitry Andric           return error("Callee is not of pointer to function type");
5682fe013be4SDimitry Andric       }
56830b57cec5SDimitry Andric       if (Record.size() < FTy->getNumParams() + OpNum)
56840b57cec5SDimitry Andric         return error("Insufficient operands to call");
56850b57cec5SDimitry Andric 
56860b57cec5SDimitry Andric       SmallVector<Value*, 16> Args;
568781ad6265SDimitry Andric       SmallVector<unsigned, 16> ArgTyIDs;
56880b57cec5SDimitry Andric       // Read the fixed params.
56890b57cec5SDimitry Andric       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
569004eeddc0SDimitry Andric         Value *Arg;
569181ad6265SDimitry Andric         unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
56920b57cec5SDimitry Andric         if (FTy->getParamType(i)->isLabelTy())
569304eeddc0SDimitry Andric           Arg = getBasicBlock(Record[OpNum]);
56940b57cec5SDimitry Andric         else
569581ad6265SDimitry Andric           Arg = getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
569681ad6265SDimitry Andric                          ArgTyID, CurBB);
569704eeddc0SDimitry Andric         if (!Arg)
56980b57cec5SDimitry Andric           return error("Invalid record");
569904eeddc0SDimitry Andric         Args.push_back(Arg);
570081ad6265SDimitry Andric         ArgTyIDs.push_back(ArgTyID);
57010b57cec5SDimitry Andric       }
57020b57cec5SDimitry Andric 
57030b57cec5SDimitry Andric       // Read type/value pairs for varargs params.
57040b57cec5SDimitry Andric       if (!FTy->isVarArg()) {
57050b57cec5SDimitry Andric         if (OpNum != Record.size())
57060b57cec5SDimitry Andric           return error("Invalid record");
57070b57cec5SDimitry Andric       } else {
57080b57cec5SDimitry Andric         while (OpNum != Record.size()) {
57090b57cec5SDimitry Andric           Value *Op;
571081ad6265SDimitry Andric           unsigned OpTypeID;
571181ad6265SDimitry Andric           if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
57120b57cec5SDimitry Andric             return error("Invalid record");
57130b57cec5SDimitry Andric           Args.push_back(Op);
571481ad6265SDimitry Andric           ArgTyIDs.push_back(OpTypeID);
57150b57cec5SDimitry Andric         }
57160b57cec5SDimitry Andric       }
57170b57cec5SDimitry Andric 
571881ad6265SDimitry Andric       // Upgrade the bundles if needed.
571981ad6265SDimitry Andric       if (!OperandBundles.empty())
572081ad6265SDimitry Andric         UpgradeOperandBundles(OperandBundles);
572181ad6265SDimitry Andric 
5722fcaf7f86SDimitry Andric       if (auto *IA = dyn_cast<InlineAsm>(Callee)) {
5723fcaf7f86SDimitry Andric         InlineAsm::ConstraintInfoVector ConstraintInfo = IA->ParseConstraints();
5724fcaf7f86SDimitry Andric         auto IsLabelConstraint = [](const InlineAsm::ConstraintInfo &CI) {
5725fcaf7f86SDimitry Andric           return CI.Type == InlineAsm::isLabel;
5726fcaf7f86SDimitry Andric         };
5727fcaf7f86SDimitry Andric         if (none_of(ConstraintInfo, IsLabelConstraint)) {
5728fcaf7f86SDimitry Andric           // Upgrade explicit blockaddress arguments to label constraints.
5729fcaf7f86SDimitry Andric           // Verify that the last arguments are blockaddress arguments that
5730fcaf7f86SDimitry Andric           // match the indirect destinations. Clang always generates callbr
5731fcaf7f86SDimitry Andric           // in this form. We could support reordering with more effort.
5732fcaf7f86SDimitry Andric           unsigned FirstBlockArg = Args.size() - IndirectDests.size();
5733fcaf7f86SDimitry Andric           for (unsigned ArgNo = FirstBlockArg; ArgNo < Args.size(); ++ArgNo) {
5734fcaf7f86SDimitry Andric             unsigned LabelNo = ArgNo - FirstBlockArg;
5735fcaf7f86SDimitry Andric             auto *BA = dyn_cast<BlockAddress>(Args[ArgNo]);
5736fcaf7f86SDimitry Andric             if (!BA || BA->getFunction() != F ||
5737fcaf7f86SDimitry Andric                 LabelNo > IndirectDests.size() ||
5738fcaf7f86SDimitry Andric                 BA->getBasicBlock() != IndirectDests[LabelNo])
5739fcaf7f86SDimitry Andric               return error("callbr argument does not match indirect dest");
5740fcaf7f86SDimitry Andric           }
5741fcaf7f86SDimitry Andric 
5742fcaf7f86SDimitry Andric           // Remove blockaddress arguments.
5743fcaf7f86SDimitry Andric           Args.erase(Args.begin() + FirstBlockArg, Args.end());
5744fcaf7f86SDimitry Andric           ArgTyIDs.erase(ArgTyIDs.begin() + FirstBlockArg, ArgTyIDs.end());
5745fcaf7f86SDimitry Andric 
5746fcaf7f86SDimitry Andric           // Recreate the function type with less arguments.
5747fcaf7f86SDimitry Andric           SmallVector<Type *> ArgTys;
5748fcaf7f86SDimitry Andric           for (Value *Arg : Args)
5749fcaf7f86SDimitry Andric             ArgTys.push_back(Arg->getType());
5750fcaf7f86SDimitry Andric           FTy =
5751fcaf7f86SDimitry Andric               FunctionType::get(FTy->getReturnType(), ArgTys, FTy->isVarArg());
5752fcaf7f86SDimitry Andric 
5753fcaf7f86SDimitry Andric           // Update constraint string to use label constraints.
5754fcaf7f86SDimitry Andric           std::string Constraints = IA->getConstraintString();
5755fcaf7f86SDimitry Andric           unsigned ArgNo = 0;
5756fcaf7f86SDimitry Andric           size_t Pos = 0;
5757fcaf7f86SDimitry Andric           for (const auto &CI : ConstraintInfo) {
5758fcaf7f86SDimitry Andric             if (CI.hasArg()) {
5759fcaf7f86SDimitry Andric               if (ArgNo >= FirstBlockArg)
5760fcaf7f86SDimitry Andric                 Constraints.insert(Pos, "!");
5761fcaf7f86SDimitry Andric               ++ArgNo;
5762fcaf7f86SDimitry Andric             }
5763fcaf7f86SDimitry Andric 
5764fcaf7f86SDimitry Andric             // Go to next constraint in string.
5765fcaf7f86SDimitry Andric             Pos = Constraints.find(',', Pos);
5766fcaf7f86SDimitry Andric             if (Pos == std::string::npos)
5767fcaf7f86SDimitry Andric               break;
5768fcaf7f86SDimitry Andric             ++Pos;
5769fcaf7f86SDimitry Andric           }
5770fcaf7f86SDimitry Andric 
5771fcaf7f86SDimitry Andric           Callee = InlineAsm::get(FTy, IA->getAsmString(), Constraints,
5772fcaf7f86SDimitry Andric                                   IA->hasSideEffects(), IA->isAlignStack(),
5773fcaf7f86SDimitry Andric                                   IA->getDialect(), IA->canThrow());
5774fcaf7f86SDimitry Andric         }
5775fcaf7f86SDimitry Andric       }
5776fcaf7f86SDimitry Andric 
57770b57cec5SDimitry Andric       I = CallBrInst::Create(FTy, Callee, DefaultDest, IndirectDests, Args,
57780b57cec5SDimitry Andric                              OperandBundles);
577981ad6265SDimitry Andric       ResTypeID = getContainedTypeID(FTyID);
57800b57cec5SDimitry Andric       OperandBundles.clear();
57810b57cec5SDimitry Andric       InstructionList.push_back(I);
57820b57cec5SDimitry Andric       cast<CallBrInst>(I)->setCallingConv(
57830b57cec5SDimitry Andric           static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
57840b57cec5SDimitry Andric       cast<CallBrInst>(I)->setAttributes(PAL);
578581ad6265SDimitry Andric       if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) {
578681ad6265SDimitry Andric         I->deleteValue();
578781ad6265SDimitry Andric         return Err;
578881ad6265SDimitry Andric       }
57890b57cec5SDimitry Andric       break;
57900b57cec5SDimitry Andric     }
57910b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
57920b57cec5SDimitry Andric       I = new UnreachableInst(Context);
57930b57cec5SDimitry Andric       InstructionList.push_back(I);
57940b57cec5SDimitry Andric       break;
57950b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
5796e8d8bef9SDimitry Andric       if (Record.empty())
579781ad6265SDimitry Andric         return error("Invalid phi record");
57988bcb0991SDimitry Andric       // The first record specifies the type.
579981ad6265SDimitry Andric       unsigned TyID = Record[0];
580081ad6265SDimitry Andric       Type *Ty = getTypeByID(TyID);
58010b57cec5SDimitry Andric       if (!Ty)
580281ad6265SDimitry Andric         return error("Invalid phi record");
58030b57cec5SDimitry Andric 
58048bcb0991SDimitry Andric       // Phi arguments are pairs of records of [value, basic block].
58058bcb0991SDimitry Andric       // There is an optional final record for fast-math-flags if this phi has a
58068bcb0991SDimitry Andric       // floating-point type.
58078bcb0991SDimitry Andric       size_t NumArgs = (Record.size() - 1) / 2;
58088bcb0991SDimitry Andric       PHINode *PN = PHINode::Create(Ty, NumArgs);
580981ad6265SDimitry Andric       if ((Record.size() - 1) % 2 == 1 && !isa<FPMathOperator>(PN)) {
581081ad6265SDimitry Andric         PN->deleteValue();
581181ad6265SDimitry Andric         return error("Invalid phi record");
581281ad6265SDimitry Andric       }
58130b57cec5SDimitry Andric       InstructionList.push_back(PN);
58140b57cec5SDimitry Andric 
581581ad6265SDimitry Andric       SmallDenseMap<BasicBlock *, Value *> Args;
58168bcb0991SDimitry Andric       for (unsigned i = 0; i != NumArgs; i++) {
581781ad6265SDimitry Andric         BasicBlock *BB = getBasicBlock(Record[i * 2 + 2]);
581881ad6265SDimitry Andric         if (!BB) {
581981ad6265SDimitry Andric           PN->deleteValue();
582081ad6265SDimitry Andric           return error("Invalid phi BB");
582181ad6265SDimitry Andric         }
582281ad6265SDimitry Andric 
582381ad6265SDimitry Andric         // Phi nodes may contain the same predecessor multiple times, in which
582481ad6265SDimitry Andric         // case the incoming value must be identical. Directly reuse the already
582581ad6265SDimitry Andric         // seen value here, to avoid expanding a constant expression multiple
582681ad6265SDimitry Andric         // times.
582781ad6265SDimitry Andric         auto It = Args.find(BB);
582881ad6265SDimitry Andric         if (It != Args.end()) {
582981ad6265SDimitry Andric           PN->addIncoming(It->second, BB);
583081ad6265SDimitry Andric           continue;
583181ad6265SDimitry Andric         }
583281ad6265SDimitry Andric 
583381ad6265SDimitry Andric         // If there already is a block for this edge (from a different phi),
583481ad6265SDimitry Andric         // use it.
583581ad6265SDimitry Andric         BasicBlock *EdgeBB = ConstExprEdgeBBs.lookup({BB, CurBB});
583681ad6265SDimitry Andric         if (!EdgeBB) {
583781ad6265SDimitry Andric           // Otherwise, use a temporary block (that we will discard if it
583881ad6265SDimitry Andric           // turns out to be unnecessary).
583981ad6265SDimitry Andric           if (!PhiConstExprBB)
584081ad6265SDimitry Andric             PhiConstExprBB = BasicBlock::Create(Context, "phi.constexpr", F);
584181ad6265SDimitry Andric           EdgeBB = PhiConstExprBB;
584281ad6265SDimitry Andric         }
584381ad6265SDimitry Andric 
58440b57cec5SDimitry Andric         // With the new function encoding, it is possible that operands have
58450b57cec5SDimitry Andric         // negative IDs (for forward references).  Use a signed VBR
58460b57cec5SDimitry Andric         // representation to keep the encoding small.
584781ad6265SDimitry Andric         Value *V;
58480b57cec5SDimitry Andric         if (UseRelativeIDs)
584981ad6265SDimitry Andric           V = getValueSigned(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
58500b57cec5SDimitry Andric         else
585181ad6265SDimitry Andric           V = getValue(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
585281ad6265SDimitry Andric         if (!V) {
585381ad6265SDimitry Andric           PN->deleteValue();
585481ad6265SDimitry Andric           PhiConstExprBB->eraseFromParent();
585581ad6265SDimitry Andric           return error("Invalid phi record");
585681ad6265SDimitry Andric         }
585781ad6265SDimitry Andric 
585881ad6265SDimitry Andric         if (EdgeBB == PhiConstExprBB && !EdgeBB->empty()) {
585981ad6265SDimitry Andric           ConstExprEdgeBBs.insert({{BB, CurBB}, EdgeBB});
586081ad6265SDimitry Andric           PhiConstExprBB = nullptr;
586181ad6265SDimitry Andric         }
58620b57cec5SDimitry Andric         PN->addIncoming(V, BB);
586381ad6265SDimitry Andric         Args.insert({BB, V});
58640b57cec5SDimitry Andric       }
58650b57cec5SDimitry Andric       I = PN;
586681ad6265SDimitry Andric       ResTypeID = TyID;
58678bcb0991SDimitry Andric 
58688bcb0991SDimitry Andric       // If there are an even number of records, the final record must be FMF.
58698bcb0991SDimitry Andric       if (Record.size() % 2 == 0) {
58708bcb0991SDimitry Andric         assert(isa<FPMathOperator>(I) && "Unexpected phi type");
58718bcb0991SDimitry Andric         FastMathFlags FMF = getDecodedFastMathFlags(Record[Record.size() - 1]);
58728bcb0991SDimitry Andric         if (FMF.any())
58738bcb0991SDimitry Andric           I->setFastMathFlags(FMF);
58748bcb0991SDimitry Andric       }
58758bcb0991SDimitry Andric 
58760b57cec5SDimitry Andric       break;
58770b57cec5SDimitry Andric     }
58780b57cec5SDimitry Andric 
58790b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_LANDINGPAD:
58800b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
58810b57cec5SDimitry Andric       // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
58820b57cec5SDimitry Andric       unsigned Idx = 0;
58830b57cec5SDimitry Andric       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
58840b57cec5SDimitry Andric         if (Record.size() < 3)
58850b57cec5SDimitry Andric           return error("Invalid record");
58860b57cec5SDimitry Andric       } else {
58870b57cec5SDimitry Andric         assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
58880b57cec5SDimitry Andric         if (Record.size() < 4)
58890b57cec5SDimitry Andric           return error("Invalid record");
58900b57cec5SDimitry Andric       }
589181ad6265SDimitry Andric       ResTypeID = Record[Idx++];
589281ad6265SDimitry Andric       Type *Ty = getTypeByID(ResTypeID);
58930b57cec5SDimitry Andric       if (!Ty)
58940b57cec5SDimitry Andric         return error("Invalid record");
58950b57cec5SDimitry Andric       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
58960b57cec5SDimitry Andric         Value *PersFn = nullptr;
589781ad6265SDimitry Andric         unsigned PersFnTypeID;
589881ad6265SDimitry Andric         if (getValueTypePair(Record, Idx, NextValueNo, PersFn, PersFnTypeID,
589981ad6265SDimitry Andric                              nullptr))
59000b57cec5SDimitry Andric           return error("Invalid record");
59010b57cec5SDimitry Andric 
59020b57cec5SDimitry Andric         if (!F->hasPersonalityFn())
59030b57cec5SDimitry Andric           F->setPersonalityFn(cast<Constant>(PersFn));
59040b57cec5SDimitry Andric         else if (F->getPersonalityFn() != cast<Constant>(PersFn))
59050b57cec5SDimitry Andric           return error("Personality function mismatch");
59060b57cec5SDimitry Andric       }
59070b57cec5SDimitry Andric 
59080b57cec5SDimitry Andric       bool IsCleanup = !!Record[Idx++];
59090b57cec5SDimitry Andric       unsigned NumClauses = Record[Idx++];
59100b57cec5SDimitry Andric       LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
59110b57cec5SDimitry Andric       LP->setCleanup(IsCleanup);
59120b57cec5SDimitry Andric       for (unsigned J = 0; J != NumClauses; ++J) {
59130b57cec5SDimitry Andric         LandingPadInst::ClauseType CT =
59140b57cec5SDimitry Andric           LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
59150b57cec5SDimitry Andric         Value *Val;
591681ad6265SDimitry Andric         unsigned ValTypeID;
59170b57cec5SDimitry Andric 
591881ad6265SDimitry Andric         if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID,
591981ad6265SDimitry Andric                              nullptr)) {
59200b57cec5SDimitry Andric           delete LP;
59210b57cec5SDimitry Andric           return error("Invalid record");
59220b57cec5SDimitry Andric         }
59230b57cec5SDimitry Andric 
59240b57cec5SDimitry Andric         assert((CT != LandingPadInst::Catch ||
59250b57cec5SDimitry Andric                 !isa<ArrayType>(Val->getType())) &&
59260b57cec5SDimitry Andric                "Catch clause has a invalid type!");
59270b57cec5SDimitry Andric         assert((CT != LandingPadInst::Filter ||
59280b57cec5SDimitry Andric                 isa<ArrayType>(Val->getType())) &&
59290b57cec5SDimitry Andric                "Filter clause has invalid type!");
59300b57cec5SDimitry Andric         LP->addClause(cast<Constant>(Val));
59310b57cec5SDimitry Andric       }
59320b57cec5SDimitry Andric 
59330b57cec5SDimitry Andric       I = LP;
59340b57cec5SDimitry Andric       InstructionList.push_back(I);
59350b57cec5SDimitry Andric       break;
59360b57cec5SDimitry Andric     }
59370b57cec5SDimitry Andric 
59380b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
593981ad6265SDimitry Andric       if (Record.size() != 4 && Record.size() != 5)
59400b57cec5SDimitry Andric         return error("Invalid record");
5941e8d8bef9SDimitry Andric       using APV = AllocaPackedValues;
5942e8d8bef9SDimitry Andric       const uint64_t Rec = Record[3];
5943e8d8bef9SDimitry Andric       const bool InAlloca = Bitfield::get<APV::UsedWithInAlloca>(Rec);
5944e8d8bef9SDimitry Andric       const bool SwiftError = Bitfield::get<APV::SwiftError>(Rec);
594581ad6265SDimitry Andric       unsigned TyID = Record[0];
594681ad6265SDimitry Andric       Type *Ty = getTypeByID(TyID);
5947e8d8bef9SDimitry Andric       if (!Bitfield::get<APV::ExplicitType>(Rec)) {
594881ad6265SDimitry Andric         TyID = getContainedTypeID(TyID);
594981ad6265SDimitry Andric         Ty = getTypeByID(TyID);
595081ad6265SDimitry Andric         if (!Ty)
595181ad6265SDimitry Andric           return error("Missing element type for old-style alloca");
59520b57cec5SDimitry Andric       }
595381ad6265SDimitry Andric       unsigned OpTyID = Record[1];
595481ad6265SDimitry Andric       Type *OpTy = getTypeByID(OpTyID);
595581ad6265SDimitry Andric       Value *Size = getFnValueByID(Record[2], OpTy, OpTyID, CurBB);
59568bcb0991SDimitry Andric       MaybeAlign Align;
5957349cc55cSDimitry Andric       uint64_t AlignExp =
5958349cc55cSDimitry Andric           Bitfield::get<APV::AlignLower>(Rec) |
5959349cc55cSDimitry Andric           (Bitfield::get<APV::AlignUpper>(Rec) << APV::AlignLower::Bits);
5960349cc55cSDimitry Andric       if (Error Err = parseAlignmentValue(AlignExp, Align)) {
59610b57cec5SDimitry Andric         return Err;
59620b57cec5SDimitry Andric       }
59630b57cec5SDimitry Andric       if (!Ty || !Size)
59640b57cec5SDimitry Andric         return error("Invalid record");
59650b57cec5SDimitry Andric 
59660b57cec5SDimitry Andric       const DataLayout &DL = TheModule->getDataLayout();
596781ad6265SDimitry Andric       unsigned AS = Record.size() == 5 ? Record[4] : DL.getAllocaAddrSpace();
59680b57cec5SDimitry Andric 
59695ffd83dbSDimitry Andric       SmallPtrSet<Type *, 4> Visited;
59705ffd83dbSDimitry Andric       if (!Align && !Ty->isSized(&Visited))
59715ffd83dbSDimitry Andric         return error("alloca of unsized type");
59725ffd83dbSDimitry Andric       if (!Align)
59735ffd83dbSDimitry Andric         Align = DL.getPrefTypeAlign(Ty);
59745ffd83dbSDimitry Andric 
5975c9157d92SDimitry Andric       if (!Size->getType()->isIntegerTy())
5976c9157d92SDimitry Andric         return error("alloca element count must have integer type");
5977c9157d92SDimitry Andric 
59785ffd83dbSDimitry Andric       AllocaInst *AI = new AllocaInst(Ty, AS, Size, *Align);
59790b57cec5SDimitry Andric       AI->setUsedWithInAlloca(InAlloca);
59800b57cec5SDimitry Andric       AI->setSwiftError(SwiftError);
59810b57cec5SDimitry Andric       I = AI;
598281ad6265SDimitry Andric       ResTypeID = getVirtualTypeID(AI->getType(), TyID);
59830b57cec5SDimitry Andric       InstructionList.push_back(I);
59840b57cec5SDimitry Andric       break;
59850b57cec5SDimitry Andric     }
59860b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
59870b57cec5SDimitry Andric       unsigned OpNum = 0;
59880b57cec5SDimitry Andric       Value *Op;
598981ad6265SDimitry Andric       unsigned OpTypeID;
599081ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) ||
59910b57cec5SDimitry Andric           (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
59920b57cec5SDimitry Andric         return error("Invalid record");
59930b57cec5SDimitry Andric 
59940b57cec5SDimitry Andric       if (!isa<PointerType>(Op->getType()))
59950b57cec5SDimitry Andric         return error("Load operand is not a pointer type");
59960b57cec5SDimitry Andric 
59970b57cec5SDimitry Andric       Type *Ty = nullptr;
59980b57cec5SDimitry Andric       if (OpNum + 3 == Record.size()) {
599981ad6265SDimitry Andric         ResTypeID = Record[OpNum++];
600081ad6265SDimitry Andric         Ty = getTypeByID(ResTypeID);
6001fe6060f1SDimitry Andric       } else {
600281ad6265SDimitry Andric         ResTypeID = getContainedTypeID(OpTypeID);
600381ad6265SDimitry Andric         Ty = getTypeByID(ResTypeID);
6004fe6060f1SDimitry Andric       }
60050b57cec5SDimitry Andric 
6006c9157d92SDimitry Andric       if (!Ty)
6007c9157d92SDimitry Andric         return error("Missing load type");
6008c9157d92SDimitry Andric 
60090b57cec5SDimitry Andric       if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
60100b57cec5SDimitry Andric         return Err;
60110b57cec5SDimitry Andric 
60128bcb0991SDimitry Andric       MaybeAlign Align;
60130b57cec5SDimitry Andric       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
60140b57cec5SDimitry Andric         return Err;
60155ffd83dbSDimitry Andric       SmallPtrSet<Type *, 4> Visited;
60165ffd83dbSDimitry Andric       if (!Align && !Ty->isSized(&Visited))
60175ffd83dbSDimitry Andric         return error("load of unsized type");
60185ffd83dbSDimitry Andric       if (!Align)
60195ffd83dbSDimitry Andric         Align = TheModule->getDataLayout().getABITypeAlign(Ty);
60205ffd83dbSDimitry Andric       I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align);
60210b57cec5SDimitry Andric       InstructionList.push_back(I);
60220b57cec5SDimitry Andric       break;
60230b57cec5SDimitry Andric     }
60240b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_LOADATOMIC: {
60250b57cec5SDimitry Andric        // LOADATOMIC: [opty, op, align, vol, ordering, ssid]
60260b57cec5SDimitry Andric       unsigned OpNum = 0;
60270b57cec5SDimitry Andric       Value *Op;
602881ad6265SDimitry Andric       unsigned OpTypeID;
602981ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) ||
60300b57cec5SDimitry Andric           (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
60310b57cec5SDimitry Andric         return error("Invalid record");
60320b57cec5SDimitry Andric 
60330b57cec5SDimitry Andric       if (!isa<PointerType>(Op->getType()))
60340b57cec5SDimitry Andric         return error("Load operand is not a pointer type");
60350b57cec5SDimitry Andric 
60360b57cec5SDimitry Andric       Type *Ty = nullptr;
60370b57cec5SDimitry Andric       if (OpNum + 5 == Record.size()) {
603881ad6265SDimitry Andric         ResTypeID = Record[OpNum++];
603981ad6265SDimitry Andric         Ty = getTypeByID(ResTypeID);
6040fe6060f1SDimitry Andric       } else {
604181ad6265SDimitry Andric         ResTypeID = getContainedTypeID(OpTypeID);
604281ad6265SDimitry Andric         Ty = getTypeByID(ResTypeID);
6043fe6060f1SDimitry Andric       }
60440b57cec5SDimitry Andric 
6045c9157d92SDimitry Andric       if (!Ty)
6046c9157d92SDimitry Andric         return error("Missing atomic load type");
6047c9157d92SDimitry Andric 
60480b57cec5SDimitry Andric       if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
60490b57cec5SDimitry Andric         return Err;
60500b57cec5SDimitry Andric 
60510b57cec5SDimitry Andric       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
60520b57cec5SDimitry Andric       if (Ordering == AtomicOrdering::NotAtomic ||
60530b57cec5SDimitry Andric           Ordering == AtomicOrdering::Release ||
60540b57cec5SDimitry Andric           Ordering == AtomicOrdering::AcquireRelease)
60550b57cec5SDimitry Andric         return error("Invalid record");
60560b57cec5SDimitry Andric       if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
60570b57cec5SDimitry Andric         return error("Invalid record");
60580b57cec5SDimitry Andric       SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
60590b57cec5SDimitry Andric 
60608bcb0991SDimitry Andric       MaybeAlign Align;
60610b57cec5SDimitry Andric       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
60620b57cec5SDimitry Andric         return Err;
60635ffd83dbSDimitry Andric       if (!Align)
60645ffd83dbSDimitry Andric         return error("Alignment missing from atomic load");
60655ffd83dbSDimitry Andric       I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align, Ordering, SSID);
60660b57cec5SDimitry Andric       InstructionList.push_back(I);
60670b57cec5SDimitry Andric       break;
60680b57cec5SDimitry Andric     }
60690b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_STORE:
60700b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
60710b57cec5SDimitry Andric       unsigned OpNum = 0;
60720b57cec5SDimitry Andric       Value *Val, *Ptr;
607381ad6265SDimitry Andric       unsigned PtrTypeID, ValTypeID;
607481ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
607581ad6265SDimitry Andric         return error("Invalid record");
607681ad6265SDimitry Andric 
607781ad6265SDimitry Andric       if (BitCode == bitc::FUNC_CODE_INST_STORE) {
607881ad6265SDimitry Andric         if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
607981ad6265SDimitry Andric           return error("Invalid record");
608081ad6265SDimitry Andric       } else {
608181ad6265SDimitry Andric         ValTypeID = getContainedTypeID(PtrTypeID);
608281ad6265SDimitry Andric         if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
608381ad6265SDimitry Andric                      ValTypeID, Val, CurBB))
608481ad6265SDimitry Andric           return error("Invalid record");
608581ad6265SDimitry Andric       }
608681ad6265SDimitry Andric 
608781ad6265SDimitry Andric       if (OpNum + 2 != Record.size())
60880b57cec5SDimitry Andric         return error("Invalid record");
60890b57cec5SDimitry Andric 
60900b57cec5SDimitry Andric       if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
60910b57cec5SDimitry Andric         return Err;
60928bcb0991SDimitry Andric       MaybeAlign Align;
60930b57cec5SDimitry Andric       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
60940b57cec5SDimitry Andric         return Err;
60955ffd83dbSDimitry Andric       SmallPtrSet<Type *, 4> Visited;
60965ffd83dbSDimitry Andric       if (!Align && !Val->getType()->isSized(&Visited))
60975ffd83dbSDimitry Andric         return error("store of unsized type");
60985ffd83dbSDimitry Andric       if (!Align)
60995ffd83dbSDimitry Andric         Align = TheModule->getDataLayout().getABITypeAlign(Val->getType());
61005ffd83dbSDimitry Andric       I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align);
61010b57cec5SDimitry Andric       InstructionList.push_back(I);
61020b57cec5SDimitry Andric       break;
61030b57cec5SDimitry Andric     }
61040b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_STOREATOMIC:
61050b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
61060b57cec5SDimitry Andric       // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid]
61070b57cec5SDimitry Andric       unsigned OpNum = 0;
61080b57cec5SDimitry Andric       Value *Val, *Ptr;
610981ad6265SDimitry Andric       unsigned PtrTypeID, ValTypeID;
611081ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB) ||
611181ad6265SDimitry Andric           !isa<PointerType>(Ptr->getType()))
611281ad6265SDimitry Andric         return error("Invalid record");
611381ad6265SDimitry Andric       if (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC) {
611481ad6265SDimitry Andric         if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
611581ad6265SDimitry Andric           return error("Invalid record");
611681ad6265SDimitry Andric       } else {
611781ad6265SDimitry Andric         ValTypeID = getContainedTypeID(PtrTypeID);
611881ad6265SDimitry Andric         if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
611981ad6265SDimitry Andric                      ValTypeID, Val, CurBB))
612081ad6265SDimitry Andric           return error("Invalid record");
612181ad6265SDimitry Andric       }
612281ad6265SDimitry Andric 
612381ad6265SDimitry Andric       if (OpNum + 4 != Record.size())
61240b57cec5SDimitry Andric         return error("Invalid record");
61250b57cec5SDimitry Andric 
61260b57cec5SDimitry Andric       if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
61270b57cec5SDimitry Andric         return Err;
61280b57cec5SDimitry Andric       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
61290b57cec5SDimitry Andric       if (Ordering == AtomicOrdering::NotAtomic ||
61300b57cec5SDimitry Andric           Ordering == AtomicOrdering::Acquire ||
61310b57cec5SDimitry Andric           Ordering == AtomicOrdering::AcquireRelease)
61320b57cec5SDimitry Andric         return error("Invalid record");
61330b57cec5SDimitry Andric       SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
61340b57cec5SDimitry Andric       if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
61350b57cec5SDimitry Andric         return error("Invalid record");
61360b57cec5SDimitry Andric 
61378bcb0991SDimitry Andric       MaybeAlign Align;
61380b57cec5SDimitry Andric       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
61390b57cec5SDimitry Andric         return Err;
61405ffd83dbSDimitry Andric       if (!Align)
61415ffd83dbSDimitry Andric         return error("Alignment missing from atomic store");
61425ffd83dbSDimitry Andric       I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align, Ordering, SSID);
61430b57cec5SDimitry Andric       InstructionList.push_back(I);
61440b57cec5SDimitry Andric       break;
61450b57cec5SDimitry Andric     }
6146e8d8bef9SDimitry Andric     case bitc::FUNC_CODE_INST_CMPXCHG_OLD: {
6147e8d8bef9SDimitry Andric       // CMPXCHG_OLD: [ptrty, ptr, cmp, val, vol, ordering, synchscope,
6148e8d8bef9SDimitry Andric       // failure_ordering?, weak?]
6149e8d8bef9SDimitry Andric       const size_t NumRecords = Record.size();
61500b57cec5SDimitry Andric       unsigned OpNum = 0;
6151e8d8bef9SDimitry Andric       Value *Ptr = nullptr;
615281ad6265SDimitry Andric       unsigned PtrTypeID;
615381ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
61540b57cec5SDimitry Andric         return error("Invalid record");
61550b57cec5SDimitry Andric 
61560b57cec5SDimitry Andric       if (!isa<PointerType>(Ptr->getType()))
61570b57cec5SDimitry Andric         return error("Cmpxchg operand is not a pointer type");
61580b57cec5SDimitry Andric 
6159e8d8bef9SDimitry Andric       Value *Cmp = nullptr;
616081ad6265SDimitry Andric       unsigned CmpTypeID = getContainedTypeID(PtrTypeID);
616181ad6265SDimitry Andric       if (popValue(Record, OpNum, NextValueNo, getTypeByID(CmpTypeID),
616281ad6265SDimitry Andric                    CmpTypeID, Cmp, CurBB))
61630b57cec5SDimitry Andric         return error("Invalid record");
6164e8d8bef9SDimitry Andric 
6165e8d8bef9SDimitry Andric       Value *New = nullptr;
616681ad6265SDimitry Andric       if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), CmpTypeID,
616781ad6265SDimitry Andric                    New, CurBB) ||
6168e8d8bef9SDimitry Andric           NumRecords < OpNum + 3 || NumRecords > OpNum + 5)
61690b57cec5SDimitry Andric         return error("Invalid record");
61700b57cec5SDimitry Andric 
6171e8d8bef9SDimitry Andric       const AtomicOrdering SuccessOrdering =
6172e8d8bef9SDimitry Andric           getDecodedOrdering(Record[OpNum + 1]);
61730b57cec5SDimitry Andric       if (SuccessOrdering == AtomicOrdering::NotAtomic ||
61740b57cec5SDimitry Andric           SuccessOrdering == AtomicOrdering::Unordered)
61750b57cec5SDimitry Andric         return error("Invalid record");
6176e8d8bef9SDimitry Andric 
6177e8d8bef9SDimitry Andric       const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
61780b57cec5SDimitry Andric 
61790b57cec5SDimitry Andric       if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
61800b57cec5SDimitry Andric         return Err;
61810b57cec5SDimitry Andric 
6182e8d8bef9SDimitry Andric       const AtomicOrdering FailureOrdering =
6183e8d8bef9SDimitry Andric           NumRecords < 7
6184e8d8bef9SDimitry Andric               ? AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering)
6185e8d8bef9SDimitry Andric               : getDecodedOrdering(Record[OpNum + 3]);
6186e8d8bef9SDimitry Andric 
6187fe6060f1SDimitry Andric       if (FailureOrdering == AtomicOrdering::NotAtomic ||
6188fe6060f1SDimitry Andric           FailureOrdering == AtomicOrdering::Unordered)
6189fe6060f1SDimitry Andric         return error("Invalid record");
6190fe6060f1SDimitry Andric 
6191e8d8bef9SDimitry Andric       const Align Alignment(
61925ffd83dbSDimitry Andric           TheModule->getDataLayout().getTypeStoreSize(Cmp->getType()));
6193e8d8bef9SDimitry Andric 
61945ffd83dbSDimitry Andric       I = new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment, SuccessOrdering,
61955ffd83dbSDimitry Andric                                 FailureOrdering, SSID);
61960b57cec5SDimitry Andric       cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
61970b57cec5SDimitry Andric 
6198e8d8bef9SDimitry Andric       if (NumRecords < 8) {
61990b57cec5SDimitry Andric         // Before weak cmpxchgs existed, the instruction simply returned the
62000b57cec5SDimitry Andric         // value loaded from memory, so bitcode files from that era will be
62010b57cec5SDimitry Andric         // expecting the first component of a modern cmpxchg.
6202bdd1243dSDimitry Andric         I->insertInto(CurBB, CurBB->end());
62030b57cec5SDimitry Andric         I = ExtractValueInst::Create(I, 0);
620481ad6265SDimitry Andric         ResTypeID = CmpTypeID;
62050b57cec5SDimitry Andric       } else {
62060b57cec5SDimitry Andric         cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum + 4]);
620781ad6265SDimitry Andric         unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(Context));
620881ad6265SDimitry Andric         ResTypeID = getVirtualTypeID(I->getType(), {CmpTypeID, I1TypeID});
62090b57cec5SDimitry Andric       }
62100b57cec5SDimitry Andric 
62110b57cec5SDimitry Andric       InstructionList.push_back(I);
62120b57cec5SDimitry Andric       break;
62130b57cec5SDimitry Andric     }
6214e8d8bef9SDimitry Andric     case bitc::FUNC_CODE_INST_CMPXCHG: {
6215e8d8bef9SDimitry Andric       // CMPXCHG: [ptrty, ptr, cmp, val, vol, success_ordering, synchscope,
6216fe6060f1SDimitry Andric       // failure_ordering, weak, align?]
6217e8d8bef9SDimitry Andric       const size_t NumRecords = Record.size();
6218e8d8bef9SDimitry Andric       unsigned OpNum = 0;
6219e8d8bef9SDimitry Andric       Value *Ptr = nullptr;
622081ad6265SDimitry Andric       unsigned PtrTypeID;
622181ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6222e8d8bef9SDimitry Andric         return error("Invalid record");
6223e8d8bef9SDimitry Andric 
6224e8d8bef9SDimitry Andric       if (!isa<PointerType>(Ptr->getType()))
6225e8d8bef9SDimitry Andric         return error("Cmpxchg operand is not a pointer type");
6226e8d8bef9SDimitry Andric 
6227e8d8bef9SDimitry Andric       Value *Cmp = nullptr;
622881ad6265SDimitry Andric       unsigned CmpTypeID;
622981ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Cmp, CmpTypeID, CurBB))
6230e8d8bef9SDimitry Andric         return error("Invalid record");
6231e8d8bef9SDimitry Andric 
6232e8d8bef9SDimitry Andric       Value *Val = nullptr;
623381ad6265SDimitry Andric       if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), CmpTypeID, Val,
623481ad6265SDimitry Andric                    CurBB))
6235e8d8bef9SDimitry Andric         return error("Invalid record");
6236e8d8bef9SDimitry Andric 
6237fe6060f1SDimitry Andric       if (NumRecords < OpNum + 3 || NumRecords > OpNum + 6)
6238fe6060f1SDimitry Andric         return error("Invalid record");
6239fe6060f1SDimitry Andric 
6240fe6060f1SDimitry Andric       const bool IsVol = Record[OpNum];
6241fe6060f1SDimitry Andric 
6242e8d8bef9SDimitry Andric       const AtomicOrdering SuccessOrdering =
6243e8d8bef9SDimitry Andric           getDecodedOrdering(Record[OpNum + 1]);
6244fe6060f1SDimitry Andric       if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
6245fe6060f1SDimitry Andric         return error("Invalid cmpxchg success ordering");
6246e8d8bef9SDimitry Andric 
6247e8d8bef9SDimitry Andric       const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
6248e8d8bef9SDimitry Andric 
6249e8d8bef9SDimitry Andric       if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
6250e8d8bef9SDimitry Andric         return Err;
6251e8d8bef9SDimitry Andric 
6252e8d8bef9SDimitry Andric       const AtomicOrdering FailureOrdering =
6253e8d8bef9SDimitry Andric           getDecodedOrdering(Record[OpNum + 3]);
6254fe6060f1SDimitry Andric       if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
6255fe6060f1SDimitry Andric         return error("Invalid cmpxchg failure ordering");
6256e8d8bef9SDimitry Andric 
6257fe6060f1SDimitry Andric       const bool IsWeak = Record[OpNum + 4];
6258e8d8bef9SDimitry Andric 
6259fe6060f1SDimitry Andric       MaybeAlign Alignment;
6260fe6060f1SDimitry Andric 
6261fe6060f1SDimitry Andric       if (NumRecords == (OpNum + 6)) {
6262fe6060f1SDimitry Andric         if (Error Err = parseAlignmentValue(Record[OpNum + 5], Alignment))
6263fe6060f1SDimitry Andric           return Err;
6264fe6060f1SDimitry Andric       }
6265fe6060f1SDimitry Andric       if (!Alignment)
6266fe6060f1SDimitry Andric         Alignment =
6267fe6060f1SDimitry Andric             Align(TheModule->getDataLayout().getTypeStoreSize(Cmp->getType()));
6268fe6060f1SDimitry Andric 
6269fe6060f1SDimitry Andric       I = new AtomicCmpXchgInst(Ptr, Cmp, Val, *Alignment, SuccessOrdering,
6270e8d8bef9SDimitry Andric                                 FailureOrdering, SSID);
6271fe6060f1SDimitry Andric       cast<AtomicCmpXchgInst>(I)->setVolatile(IsVol);
6272fe6060f1SDimitry Andric       cast<AtomicCmpXchgInst>(I)->setWeak(IsWeak);
6273e8d8bef9SDimitry Andric 
627481ad6265SDimitry Andric       unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(Context));
627581ad6265SDimitry Andric       ResTypeID = getVirtualTypeID(I->getType(), {CmpTypeID, I1TypeID});
627681ad6265SDimitry Andric 
6277e8d8bef9SDimitry Andric       InstructionList.push_back(I);
6278e8d8bef9SDimitry Andric       break;
6279e8d8bef9SDimitry Andric     }
6280fe6060f1SDimitry Andric     case bitc::FUNC_CODE_INST_ATOMICRMW_OLD:
62810b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_ATOMICRMW: {
6282fe6060f1SDimitry Andric       // ATOMICRMW_OLD: [ptrty, ptr, val, op, vol, ordering, ssid, align?]
6283fe6060f1SDimitry Andric       // ATOMICRMW: [ptrty, ptr, valty, val, op, vol, ordering, ssid, align?]
6284fe6060f1SDimitry Andric       const size_t NumRecords = Record.size();
62850b57cec5SDimitry Andric       unsigned OpNum = 0;
6286fe6060f1SDimitry Andric 
6287fe6060f1SDimitry Andric       Value *Ptr = nullptr;
628881ad6265SDimitry Andric       unsigned PtrTypeID;
628981ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
62900b57cec5SDimitry Andric         return error("Invalid record");
6291fe6060f1SDimitry Andric 
6292fe6060f1SDimitry Andric       if (!isa<PointerType>(Ptr->getType()))
6293fe6060f1SDimitry Andric         return error("Invalid record");
6294fe6060f1SDimitry Andric 
6295fe6060f1SDimitry Andric       Value *Val = nullptr;
629681ad6265SDimitry Andric       unsigned ValTypeID = InvalidTypeID;
6297fe6060f1SDimitry Andric       if (BitCode == bitc::FUNC_CODE_INST_ATOMICRMW_OLD) {
629881ad6265SDimitry Andric         ValTypeID = getContainedTypeID(PtrTypeID);
6299fe6060f1SDimitry Andric         if (popValue(Record, OpNum, NextValueNo,
630081ad6265SDimitry Andric                      getTypeByID(ValTypeID), ValTypeID, Val, CurBB))
6301fe6060f1SDimitry Andric           return error("Invalid record");
6302fe6060f1SDimitry Andric       } else {
630381ad6265SDimitry Andric         if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6304fe6060f1SDimitry Andric           return error("Invalid record");
6305fe6060f1SDimitry Andric       }
6306fe6060f1SDimitry Andric 
6307fe6060f1SDimitry Andric       if (!(NumRecords == (OpNum + 4) || NumRecords == (OpNum + 5)))
6308fe6060f1SDimitry Andric         return error("Invalid record");
6309fe6060f1SDimitry Andric 
6310fe6060f1SDimitry Andric       const AtomicRMWInst::BinOp Operation =
6311fe6060f1SDimitry Andric           getDecodedRMWOperation(Record[OpNum]);
63120b57cec5SDimitry Andric       if (Operation < AtomicRMWInst::FIRST_BINOP ||
63130b57cec5SDimitry Andric           Operation > AtomicRMWInst::LAST_BINOP)
63140b57cec5SDimitry Andric         return error("Invalid record");
6315fe6060f1SDimitry Andric 
6316fe6060f1SDimitry Andric       const bool IsVol = Record[OpNum + 1];
6317fe6060f1SDimitry Andric 
6318fe6060f1SDimitry Andric       const AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
63190b57cec5SDimitry Andric       if (Ordering == AtomicOrdering::NotAtomic ||
63200b57cec5SDimitry Andric           Ordering == AtomicOrdering::Unordered)
63210b57cec5SDimitry Andric         return error("Invalid record");
6322fe6060f1SDimitry Andric 
6323fe6060f1SDimitry Andric       const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6324fe6060f1SDimitry Andric 
6325fe6060f1SDimitry Andric       MaybeAlign Alignment;
6326fe6060f1SDimitry Andric 
6327fe6060f1SDimitry Andric       if (NumRecords == (OpNum + 5)) {
6328fe6060f1SDimitry Andric         if (Error Err = parseAlignmentValue(Record[OpNum + 4], Alignment))
6329fe6060f1SDimitry Andric           return Err;
6330fe6060f1SDimitry Andric       }
6331fe6060f1SDimitry Andric 
6332fe6060f1SDimitry Andric       if (!Alignment)
6333fe6060f1SDimitry Andric         Alignment =
6334fe6060f1SDimitry Andric             Align(TheModule->getDataLayout().getTypeStoreSize(Val->getType()));
6335fe6060f1SDimitry Andric 
6336fe6060f1SDimitry Andric       I = new AtomicRMWInst(Operation, Ptr, Val, *Alignment, Ordering, SSID);
633781ad6265SDimitry Andric       ResTypeID = ValTypeID;
6338fe6060f1SDimitry Andric       cast<AtomicRMWInst>(I)->setVolatile(IsVol);
6339fe6060f1SDimitry Andric 
63400b57cec5SDimitry Andric       InstructionList.push_back(I);
63410b57cec5SDimitry Andric       break;
63420b57cec5SDimitry Andric     }
63430b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid]
63440b57cec5SDimitry Andric       if (2 != Record.size())
63450b57cec5SDimitry Andric         return error("Invalid record");
63460b57cec5SDimitry Andric       AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
63470b57cec5SDimitry Andric       if (Ordering == AtomicOrdering::NotAtomic ||
63480b57cec5SDimitry Andric           Ordering == AtomicOrdering::Unordered ||
63490b57cec5SDimitry Andric           Ordering == AtomicOrdering::Monotonic)
63500b57cec5SDimitry Andric         return error("Invalid record");
63510b57cec5SDimitry Andric       SyncScope::ID SSID = getDecodedSyncScopeID(Record[1]);
63520b57cec5SDimitry Andric       I = new FenceInst(Context, Ordering, SSID);
63530b57cec5SDimitry Andric       InstructionList.push_back(I);
63540b57cec5SDimitry Andric       break;
63550b57cec5SDimitry Andric     }
63560b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CALL: {
63570b57cec5SDimitry Andric       // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
63580b57cec5SDimitry Andric       if (Record.size() < 3)
63590b57cec5SDimitry Andric         return error("Invalid record");
63600b57cec5SDimitry Andric 
63610b57cec5SDimitry Andric       unsigned OpNum = 0;
63620b57cec5SDimitry Andric       AttributeList PAL = getAttributes(Record[OpNum++]);
63630b57cec5SDimitry Andric       unsigned CCInfo = Record[OpNum++];
63640b57cec5SDimitry Andric 
63650b57cec5SDimitry Andric       FastMathFlags FMF;
63660b57cec5SDimitry Andric       if ((CCInfo >> bitc::CALL_FMF) & 1) {
63670b57cec5SDimitry Andric         FMF = getDecodedFastMathFlags(Record[OpNum++]);
63680b57cec5SDimitry Andric         if (!FMF.any())
63690b57cec5SDimitry Andric           return error("Fast math flags indicator set for call with no FMF");
63700b57cec5SDimitry Andric       }
63710b57cec5SDimitry Andric 
637281ad6265SDimitry Andric       unsigned FTyID = InvalidTypeID;
63730b57cec5SDimitry Andric       FunctionType *FTy = nullptr;
63740b57cec5SDimitry Andric       if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) {
637581ad6265SDimitry Andric         FTyID = Record[OpNum++];
637681ad6265SDimitry Andric         FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
6377fe6060f1SDimitry Andric         if (!FTy)
63780b57cec5SDimitry Andric           return error("Explicit call type is not a function type");
63790b57cec5SDimitry Andric       }
63800b57cec5SDimitry Andric 
63810b57cec5SDimitry Andric       Value *Callee;
638281ad6265SDimitry Andric       unsigned CalleeTypeID;
638381ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
638481ad6265SDimitry Andric                            CurBB))
63850b57cec5SDimitry Andric         return error("Invalid record");
63860b57cec5SDimitry Andric 
63870b57cec5SDimitry Andric       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
63880b57cec5SDimitry Andric       if (!OpTy)
63890b57cec5SDimitry Andric         return error("Callee is not a pointer type");
63900b57cec5SDimitry Andric       if (!FTy) {
639181ad6265SDimitry Andric         FTyID = getContainedTypeID(CalleeTypeID);
639281ad6265SDimitry Andric         FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
6393fe6060f1SDimitry Andric         if (!FTy)
63940b57cec5SDimitry Andric           return error("Callee is not of pointer to function type");
6395fe013be4SDimitry Andric       }
63960b57cec5SDimitry Andric       if (Record.size() < FTy->getNumParams() + OpNum)
63970b57cec5SDimitry Andric         return error("Insufficient operands to call");
63980b57cec5SDimitry Andric 
63990b57cec5SDimitry Andric       SmallVector<Value*, 16> Args;
640081ad6265SDimitry Andric       SmallVector<unsigned, 16> ArgTyIDs;
64010b57cec5SDimitry Andric       // Read the fixed params.
64020b57cec5SDimitry Andric       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
640381ad6265SDimitry Andric         unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
64040b57cec5SDimitry Andric         if (FTy->getParamType(i)->isLabelTy())
64050b57cec5SDimitry Andric           Args.push_back(getBasicBlock(Record[OpNum]));
64060b57cec5SDimitry Andric         else
64070b57cec5SDimitry Andric           Args.push_back(getValue(Record, OpNum, NextValueNo,
640881ad6265SDimitry Andric                                   FTy->getParamType(i), ArgTyID, CurBB));
640981ad6265SDimitry Andric         ArgTyIDs.push_back(ArgTyID);
64100b57cec5SDimitry Andric         if (!Args.back())
64110b57cec5SDimitry Andric           return error("Invalid record");
64120b57cec5SDimitry Andric       }
64130b57cec5SDimitry Andric 
64140b57cec5SDimitry Andric       // Read type/value pairs for varargs params.
64150b57cec5SDimitry Andric       if (!FTy->isVarArg()) {
64160b57cec5SDimitry Andric         if (OpNum != Record.size())
64170b57cec5SDimitry Andric           return error("Invalid record");
64180b57cec5SDimitry Andric       } else {
64190b57cec5SDimitry Andric         while (OpNum != Record.size()) {
64200b57cec5SDimitry Andric           Value *Op;
642181ad6265SDimitry Andric           unsigned OpTypeID;
642281ad6265SDimitry Andric           if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
64230b57cec5SDimitry Andric             return error("Invalid record");
64240b57cec5SDimitry Andric           Args.push_back(Op);
642581ad6265SDimitry Andric           ArgTyIDs.push_back(OpTypeID);
64260b57cec5SDimitry Andric         }
64270b57cec5SDimitry Andric       }
64280b57cec5SDimitry Andric 
642981ad6265SDimitry Andric       // Upgrade the bundles if needed.
643081ad6265SDimitry Andric       if (!OperandBundles.empty())
643181ad6265SDimitry Andric         UpgradeOperandBundles(OperandBundles);
643281ad6265SDimitry Andric 
64330b57cec5SDimitry Andric       I = CallInst::Create(FTy, Callee, Args, OperandBundles);
643481ad6265SDimitry Andric       ResTypeID = getContainedTypeID(FTyID);
64350b57cec5SDimitry Andric       OperandBundles.clear();
64360b57cec5SDimitry Andric       InstructionList.push_back(I);
64370b57cec5SDimitry Andric       cast<CallInst>(I)->setCallingConv(
64380b57cec5SDimitry Andric           static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
64390b57cec5SDimitry Andric       CallInst::TailCallKind TCK = CallInst::TCK_None;
6440c9157d92SDimitry Andric       if (CCInfo & (1 << bitc::CALL_TAIL))
64410b57cec5SDimitry Andric         TCK = CallInst::TCK_Tail;
64420b57cec5SDimitry Andric       if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
64430b57cec5SDimitry Andric         TCK = CallInst::TCK_MustTail;
64440b57cec5SDimitry Andric       if (CCInfo & (1 << bitc::CALL_NOTAIL))
64450b57cec5SDimitry Andric         TCK = CallInst::TCK_NoTail;
64460b57cec5SDimitry Andric       cast<CallInst>(I)->setTailCallKind(TCK);
64470b57cec5SDimitry Andric       cast<CallInst>(I)->setAttributes(PAL);
644881ad6265SDimitry Andric       if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) {
644981ad6265SDimitry Andric         I->deleteValue();
645081ad6265SDimitry Andric         return Err;
645181ad6265SDimitry Andric       }
64520b57cec5SDimitry Andric       if (FMF.any()) {
64530b57cec5SDimitry Andric         if (!isa<FPMathOperator>(I))
64540b57cec5SDimitry Andric           return error("Fast-math-flags specified for call without "
64550b57cec5SDimitry Andric                        "floating-point scalar or vector return type");
64560b57cec5SDimitry Andric         I->setFastMathFlags(FMF);
64570b57cec5SDimitry Andric       }
64580b57cec5SDimitry Andric       break;
64590b57cec5SDimitry Andric     }
64600b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
64610b57cec5SDimitry Andric       if (Record.size() < 3)
64620b57cec5SDimitry Andric         return error("Invalid record");
646381ad6265SDimitry Andric       unsigned OpTyID = Record[0];
646481ad6265SDimitry Andric       Type *OpTy = getTypeByID(OpTyID);
646581ad6265SDimitry Andric       Value *Op = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
646681ad6265SDimitry Andric       ResTypeID = Record[2];
646781ad6265SDimitry Andric       Type *ResTy = getTypeByID(ResTypeID);
64680b57cec5SDimitry Andric       if (!OpTy || !Op || !ResTy)
64690b57cec5SDimitry Andric         return error("Invalid record");
64700b57cec5SDimitry Andric       I = new VAArgInst(Op, ResTy);
64710b57cec5SDimitry Andric       InstructionList.push_back(I);
64720b57cec5SDimitry Andric       break;
64730b57cec5SDimitry Andric     }
64740b57cec5SDimitry Andric 
64750b57cec5SDimitry Andric     case bitc::FUNC_CODE_OPERAND_BUNDLE: {
64760b57cec5SDimitry Andric       // A call or an invoke can be optionally prefixed with some variable
64770b57cec5SDimitry Andric       // number of operand bundle blocks.  These blocks are read into
64780b57cec5SDimitry Andric       // OperandBundles and consumed at the next call or invoke instruction.
64790b57cec5SDimitry Andric 
6480e8d8bef9SDimitry Andric       if (Record.empty() || Record[0] >= BundleTags.size())
64810b57cec5SDimitry Andric         return error("Invalid record");
64820b57cec5SDimitry Andric 
64830b57cec5SDimitry Andric       std::vector<Value *> Inputs;
64840b57cec5SDimitry Andric 
64850b57cec5SDimitry Andric       unsigned OpNum = 1;
64860b57cec5SDimitry Andric       while (OpNum != Record.size()) {
64870b57cec5SDimitry Andric         Value *Op;
648881ad6265SDimitry Andric         unsigned OpTypeID;
648981ad6265SDimitry Andric         if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
64900b57cec5SDimitry Andric           return error("Invalid record");
64910b57cec5SDimitry Andric         Inputs.push_back(Op);
64920b57cec5SDimitry Andric       }
64930b57cec5SDimitry Andric 
64940b57cec5SDimitry Andric       OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
64950b57cec5SDimitry Andric       continue;
64960b57cec5SDimitry Andric     }
6497480093f4SDimitry Andric 
6498480093f4SDimitry Andric     case bitc::FUNC_CODE_INST_FREEZE: { // FREEZE: [opty,opval]
6499480093f4SDimitry Andric       unsigned OpNum = 0;
6500480093f4SDimitry Andric       Value *Op = nullptr;
650181ad6265SDimitry Andric       unsigned OpTypeID;
650281ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
6503480093f4SDimitry Andric         return error("Invalid record");
6504480093f4SDimitry Andric       if (OpNum != Record.size())
6505480093f4SDimitry Andric         return error("Invalid record");
6506480093f4SDimitry Andric 
6507480093f4SDimitry Andric       I = new FreezeInst(Op);
650881ad6265SDimitry Andric       ResTypeID = OpTypeID;
6509480093f4SDimitry Andric       InstructionList.push_back(I);
6510480093f4SDimitry Andric       break;
6511480093f4SDimitry Andric     }
65120b57cec5SDimitry Andric     }
65130b57cec5SDimitry Andric 
65140b57cec5SDimitry Andric     // Add instruction to end of current BB.  If there is no current BB, reject
65150b57cec5SDimitry Andric     // this file.
65160b57cec5SDimitry Andric     if (!CurBB) {
65170b57cec5SDimitry Andric       I->deleteValue();
65180b57cec5SDimitry Andric       return error("Invalid instruction with no BB");
65190b57cec5SDimitry Andric     }
65200b57cec5SDimitry Andric     if (!OperandBundles.empty()) {
65210b57cec5SDimitry Andric       I->deleteValue();
65220b57cec5SDimitry Andric       return error("Operand bundles found with no consumer");
65230b57cec5SDimitry Andric     }
6524bdd1243dSDimitry Andric     I->insertInto(CurBB, CurBB->end());
65250b57cec5SDimitry Andric 
65260b57cec5SDimitry Andric     // If this was a terminator instruction, move to the next block.
65270b57cec5SDimitry Andric     if (I->isTerminator()) {
65280b57cec5SDimitry Andric       ++CurBBNo;
65290b57cec5SDimitry Andric       CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
65300b57cec5SDimitry Andric     }
65310b57cec5SDimitry Andric 
65320b57cec5SDimitry Andric     // Non-void values get registered in the value table for future use.
653381ad6265SDimitry Andric     if (!I->getType()->isVoidTy()) {
653481ad6265SDimitry Andric       assert(I->getType() == getTypeByID(ResTypeID) &&
653581ad6265SDimitry Andric              "Incorrect result type ID");
653681ad6265SDimitry Andric       if (Error Err = ValueList.assignValue(NextValueNo++, I, ResTypeID))
653781ad6265SDimitry Andric         return Err;
653881ad6265SDimitry Andric     }
65390b57cec5SDimitry Andric   }
65400b57cec5SDimitry Andric 
65410b57cec5SDimitry Andric OutOfRecordLoop:
65420b57cec5SDimitry Andric 
65430b57cec5SDimitry Andric   if (!OperandBundles.empty())
65440b57cec5SDimitry Andric     return error("Operand bundles found with no consumer");
65450b57cec5SDimitry Andric 
65460b57cec5SDimitry Andric   // Check the function list for unresolved values.
65470b57cec5SDimitry Andric   if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
65480b57cec5SDimitry Andric     if (!A->getParent()) {
65490b57cec5SDimitry Andric       // We found at least one unresolved value.  Nuke them all to avoid leaks.
65500b57cec5SDimitry Andric       for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
65510b57cec5SDimitry Andric         if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
6552bdd1243dSDimitry Andric           A->replaceAllUsesWith(PoisonValue::get(A->getType()));
65530b57cec5SDimitry Andric           delete A;
65540b57cec5SDimitry Andric         }
65550b57cec5SDimitry Andric       }
65560b57cec5SDimitry Andric       return error("Never resolved value found in function");
65570b57cec5SDimitry Andric     }
65580b57cec5SDimitry Andric   }
65590b57cec5SDimitry Andric 
65600b57cec5SDimitry Andric   // Unexpected unresolved metadata about to be dropped.
65610b57cec5SDimitry Andric   if (MDLoader->hasFwdRefs())
65620b57cec5SDimitry Andric     return error("Invalid function metadata: outgoing forward refs");
65630b57cec5SDimitry Andric 
656481ad6265SDimitry Andric   if (PhiConstExprBB)
656581ad6265SDimitry Andric     PhiConstExprBB->eraseFromParent();
656681ad6265SDimitry Andric 
656781ad6265SDimitry Andric   for (const auto &Pair : ConstExprEdgeBBs) {
656881ad6265SDimitry Andric     BasicBlock *From = Pair.first.first;
656981ad6265SDimitry Andric     BasicBlock *To = Pair.first.second;
657081ad6265SDimitry Andric     BasicBlock *EdgeBB = Pair.second;
657181ad6265SDimitry Andric     BranchInst::Create(To, EdgeBB);
657281ad6265SDimitry Andric     From->getTerminator()->replaceSuccessorWith(To, EdgeBB);
657381ad6265SDimitry Andric     To->replacePhiUsesWith(From, EdgeBB);
657481ad6265SDimitry Andric     EdgeBB->moveBefore(To);
657581ad6265SDimitry Andric   }
657681ad6265SDimitry Andric 
65770b57cec5SDimitry Andric   // Trim the value list down to the size it was before we parsed this function.
65780b57cec5SDimitry Andric   ValueList.shrinkTo(ModuleValueListSize);
65790b57cec5SDimitry Andric   MDLoader->shrinkTo(ModuleMDLoaderSize);
65800b57cec5SDimitry Andric   std::vector<BasicBlock*>().swap(FunctionBBs);
65810b57cec5SDimitry Andric   return Error::success();
65820b57cec5SDimitry Andric }
65830b57cec5SDimitry Andric 
65840b57cec5SDimitry Andric /// Find the function body in the bitcode stream
findFunctionInStream(Function * F,DenseMap<Function *,uint64_t>::iterator DeferredFunctionInfoIterator)65850b57cec5SDimitry Andric Error BitcodeReader::findFunctionInStream(
65860b57cec5SDimitry Andric     Function *F,
65870b57cec5SDimitry Andric     DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
65880b57cec5SDimitry Andric   while (DeferredFunctionInfoIterator->second == 0) {
65890b57cec5SDimitry Andric     // This is the fallback handling for the old format bitcode that
65900b57cec5SDimitry Andric     // didn't contain the function index in the VST, or when we have
65910b57cec5SDimitry Andric     // an anonymous function which would not have a VST entry.
65920b57cec5SDimitry Andric     // Assert that we have one of those two cases.
65930b57cec5SDimitry Andric     assert(VSTOffset == 0 || !F->hasName());
65940b57cec5SDimitry Andric     // Parse the next body in the stream and set its position in the
65950b57cec5SDimitry Andric     // DeferredFunctionInfo map.
65960b57cec5SDimitry Andric     if (Error Err = rememberAndSkipFunctionBodies())
65970b57cec5SDimitry Andric       return Err;
65980b57cec5SDimitry Andric   }
65990b57cec5SDimitry Andric   return Error::success();
66000b57cec5SDimitry Andric }
66010b57cec5SDimitry Andric 
getDecodedSyncScopeID(unsigned Val)66020b57cec5SDimitry Andric SyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) {
66030b57cec5SDimitry Andric   if (Val == SyncScope::SingleThread || Val == SyncScope::System)
66040b57cec5SDimitry Andric     return SyncScope::ID(Val);
66050b57cec5SDimitry Andric   if (Val >= SSIDs.size())
66060b57cec5SDimitry Andric     return SyncScope::System; // Map unknown synchronization scopes to system.
66070b57cec5SDimitry Andric   return SSIDs[Val];
66080b57cec5SDimitry Andric }
66090b57cec5SDimitry Andric 
66100b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
66110b57cec5SDimitry Andric // GVMaterializer implementation
66120b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
66130b57cec5SDimitry Andric 
materialize(GlobalValue * GV)66140b57cec5SDimitry Andric Error BitcodeReader::materialize(GlobalValue *GV) {
66150b57cec5SDimitry Andric   Function *F = dyn_cast<Function>(GV);
66160b57cec5SDimitry Andric   // If it's not a function or is already material, ignore the request.
66170b57cec5SDimitry Andric   if (!F || !F->isMaterializable())
66180b57cec5SDimitry Andric     return Error::success();
66190b57cec5SDimitry Andric 
66200b57cec5SDimitry Andric   DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
66210b57cec5SDimitry Andric   assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
66220b57cec5SDimitry Andric   // If its position is recorded as 0, its body is somewhere in the stream
66230b57cec5SDimitry Andric   // but we haven't seen it yet.
66240b57cec5SDimitry Andric   if (DFII->second == 0)
66250b57cec5SDimitry Andric     if (Error Err = findFunctionInStream(F, DFII))
66260b57cec5SDimitry Andric       return Err;
66270b57cec5SDimitry Andric 
66280b57cec5SDimitry Andric   // Materialize metadata before parsing any function bodies.
66290b57cec5SDimitry Andric   if (Error Err = materializeMetadata())
66300b57cec5SDimitry Andric     return Err;
66310b57cec5SDimitry Andric 
66320b57cec5SDimitry Andric   // Move the bit stream to the saved position of the deferred function body.
66330b57cec5SDimitry Andric   if (Error JumpFailed = Stream.JumpToBit(DFII->second))
66340b57cec5SDimitry Andric     return JumpFailed;
66350b57cec5SDimitry Andric   if (Error Err = parseFunctionBody(F))
66360b57cec5SDimitry Andric     return Err;
66370b57cec5SDimitry Andric   F->setIsMaterializable(false);
66380b57cec5SDimitry Andric 
66390b57cec5SDimitry Andric   if (StripDebugInfo)
66400b57cec5SDimitry Andric     stripDebugInfo(*F);
66410b57cec5SDimitry Andric 
66420b57cec5SDimitry Andric   // Upgrade any old intrinsic calls in the function.
66430b57cec5SDimitry Andric   for (auto &I : UpgradedIntrinsics) {
6644349cc55cSDimitry Andric     for (User *U : llvm::make_early_inc_range(I.first->materialized_users()))
66450b57cec5SDimitry Andric       if (CallInst *CI = dyn_cast<CallInst>(U))
66460b57cec5SDimitry Andric         UpgradeIntrinsicCall(CI, I.second);
66470b57cec5SDimitry Andric   }
66480b57cec5SDimitry Andric 
66490b57cec5SDimitry Andric   // Finish fn->subprogram upgrade for materialized functions.
66500b57cec5SDimitry Andric   if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F))
66510b57cec5SDimitry Andric     F->setSubprogram(SP);
66520b57cec5SDimitry Andric 
66530b57cec5SDimitry Andric   // Check if the TBAA Metadata are valid, otherwise we will need to strip them.
66540b57cec5SDimitry Andric   if (!MDLoader->isStrippingTBAA()) {
66550b57cec5SDimitry Andric     for (auto &I : instructions(F)) {
66560b57cec5SDimitry Andric       MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa);
66570b57cec5SDimitry Andric       if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA))
66580b57cec5SDimitry Andric         continue;
66590b57cec5SDimitry Andric       MDLoader->setStripTBAA(true);
66600b57cec5SDimitry Andric       stripTBAA(F->getParent());
66610b57cec5SDimitry Andric     }
66620b57cec5SDimitry Andric   }
66630b57cec5SDimitry Andric 
6664e8d8bef9SDimitry Andric   for (auto &I : instructions(F)) {
6665fe6060f1SDimitry Andric     // "Upgrade" older incorrect branch weights by dropping them.
6666e8d8bef9SDimitry Andric     if (auto *MD = I.getMetadata(LLVMContext::MD_prof)) {
6667e8d8bef9SDimitry Andric       if (MD->getOperand(0) != nullptr && isa<MDString>(MD->getOperand(0))) {
6668e8d8bef9SDimitry Andric         MDString *MDS = cast<MDString>(MD->getOperand(0));
6669e8d8bef9SDimitry Andric         StringRef ProfName = MDS->getString();
6670e8d8bef9SDimitry Andric         // Check consistency of !prof branch_weights metadata.
6671e8d8bef9SDimitry Andric         if (!ProfName.equals("branch_weights"))
6672e8d8bef9SDimitry Andric           continue;
6673e8d8bef9SDimitry Andric         unsigned ExpectedNumOperands = 0;
6674e8d8bef9SDimitry Andric         if (BranchInst *BI = dyn_cast<BranchInst>(&I))
6675e8d8bef9SDimitry Andric           ExpectedNumOperands = BI->getNumSuccessors();
6676e8d8bef9SDimitry Andric         else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I))
6677e8d8bef9SDimitry Andric           ExpectedNumOperands = SI->getNumSuccessors();
6678e8d8bef9SDimitry Andric         else if (isa<CallInst>(&I))
6679e8d8bef9SDimitry Andric           ExpectedNumOperands = 1;
6680e8d8bef9SDimitry Andric         else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I))
6681e8d8bef9SDimitry Andric           ExpectedNumOperands = IBI->getNumDestinations();
6682e8d8bef9SDimitry Andric         else if (isa<SelectInst>(&I))
6683e8d8bef9SDimitry Andric           ExpectedNumOperands = 2;
6684e8d8bef9SDimitry Andric         else
6685e8d8bef9SDimitry Andric           continue; // ignore and continue.
6686e8d8bef9SDimitry Andric 
6687e8d8bef9SDimitry Andric         // If branch weight doesn't match, just strip branch weight.
6688e8d8bef9SDimitry Andric         if (MD->getNumOperands() != 1 + ExpectedNumOperands)
6689e8d8bef9SDimitry Andric           I.setMetadata(LLVMContext::MD_prof, nullptr);
6690e8d8bef9SDimitry Andric       }
6691e8d8bef9SDimitry Andric     }
6692fe6060f1SDimitry Andric 
6693fe6060f1SDimitry Andric     // Remove incompatible attributes on function calls.
6694fe6060f1SDimitry Andric     if (auto *CI = dyn_cast<CallBase>(&I)) {
6695349cc55cSDimitry Andric       CI->removeRetAttrs(AttributeFuncs::typeIncompatible(
6696fe6060f1SDimitry Andric           CI->getFunctionType()->getReturnType()));
6697fe6060f1SDimitry Andric 
6698fe6060f1SDimitry Andric       for (unsigned ArgNo = 0; ArgNo < CI->arg_size(); ++ArgNo)
6699fe6060f1SDimitry Andric         CI->removeParamAttrs(ArgNo, AttributeFuncs::typeIncompatible(
6700fe6060f1SDimitry Andric                                         CI->getArgOperand(ArgNo)->getType()));
6701fe6060f1SDimitry Andric     }
6702e8d8bef9SDimitry Andric   }
6703e8d8bef9SDimitry Andric 
67045ffd83dbSDimitry Andric   // Look for functions that rely on old function attribute behavior.
67055ffd83dbSDimitry Andric   UpgradeFunctionAttributes(*F);
67065ffd83dbSDimitry Andric 
67070b57cec5SDimitry Andric   // Bring in any functions that this function forward-referenced via
67080b57cec5SDimitry Andric   // blockaddresses.
67090b57cec5SDimitry Andric   return materializeForwardReferencedFunctions();
67100b57cec5SDimitry Andric }
67110b57cec5SDimitry Andric 
materializeModule()67120b57cec5SDimitry Andric Error BitcodeReader::materializeModule() {
67130b57cec5SDimitry Andric   if (Error Err = materializeMetadata())
67140b57cec5SDimitry Andric     return Err;
67150b57cec5SDimitry Andric 
67160b57cec5SDimitry Andric   // Promise to materialize all forward references.
67170b57cec5SDimitry Andric   WillMaterializeAllForwardRefs = true;
67180b57cec5SDimitry Andric 
67190b57cec5SDimitry Andric   // Iterate over the module, deserializing any functions that are still on
67200b57cec5SDimitry Andric   // disk.
67210b57cec5SDimitry Andric   for (Function &F : *TheModule) {
67220b57cec5SDimitry Andric     if (Error Err = materialize(&F))
67230b57cec5SDimitry Andric       return Err;
67240b57cec5SDimitry Andric   }
67250b57cec5SDimitry Andric   // At this point, if there are any function bodies, parse the rest of
67260b57cec5SDimitry Andric   // the bits in the module past the last function block we have recorded
67270b57cec5SDimitry Andric   // through either lazy scanning or the VST.
67280b57cec5SDimitry Andric   if (LastFunctionBlockBit || NextUnreadBit)
67290b57cec5SDimitry Andric     if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit
67300b57cec5SDimitry Andric                                     ? LastFunctionBlockBit
67310b57cec5SDimitry Andric                                     : NextUnreadBit))
67320b57cec5SDimitry Andric       return Err;
67330b57cec5SDimitry Andric 
67340b57cec5SDimitry Andric   // Check that all block address forward references got resolved (as we
67350b57cec5SDimitry Andric   // promised above).
67360b57cec5SDimitry Andric   if (!BasicBlockFwdRefs.empty())
67370b57cec5SDimitry Andric     return error("Never resolved function from blockaddress");
67380b57cec5SDimitry Andric 
67390b57cec5SDimitry Andric   // Upgrade any intrinsic calls that slipped through (should not happen!) and
67400b57cec5SDimitry Andric   // delete the old functions to clean up. We can't do this unless the entire
67410b57cec5SDimitry Andric   // module is materialized because there could always be another function body
67420b57cec5SDimitry Andric   // with calls to the old function.
67430b57cec5SDimitry Andric   for (auto &I : UpgradedIntrinsics) {
67440b57cec5SDimitry Andric     for (auto *U : I.first->users()) {
67450b57cec5SDimitry Andric       if (CallInst *CI = dyn_cast<CallInst>(U))
67460b57cec5SDimitry Andric         UpgradeIntrinsicCall(CI, I.second);
67470b57cec5SDimitry Andric     }
67480b57cec5SDimitry Andric     if (!I.first->use_empty())
67490b57cec5SDimitry Andric       I.first->replaceAllUsesWith(I.second);
67500b57cec5SDimitry Andric     I.first->eraseFromParent();
67510b57cec5SDimitry Andric   }
67520b57cec5SDimitry Andric   UpgradedIntrinsics.clear();
67530b57cec5SDimitry Andric 
67540b57cec5SDimitry Andric   UpgradeDebugInfo(*TheModule);
67550b57cec5SDimitry Andric 
67560b57cec5SDimitry Andric   UpgradeModuleFlags(*TheModule);
67570b57cec5SDimitry Andric 
67588bcb0991SDimitry Andric   UpgradeARCRuntime(*TheModule);
67590b57cec5SDimitry Andric 
67600b57cec5SDimitry Andric   return Error::success();
67610b57cec5SDimitry Andric }
67620b57cec5SDimitry Andric 
getIdentifiedStructTypes() const67630b57cec5SDimitry Andric std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
67640b57cec5SDimitry Andric   return IdentifiedStructTypes;
67650b57cec5SDimitry Andric }
67660b57cec5SDimitry Andric 
ModuleSummaryIndexBitcodeReader(BitstreamCursor Cursor,StringRef Strtab,ModuleSummaryIndex & TheIndex,StringRef ModulePath,std::function<bool (GlobalValue::GUID)> IsPrevailing)67670b57cec5SDimitry Andric ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
67680b57cec5SDimitry Andric     BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex,
6769c9157d92SDimitry Andric     StringRef ModulePath, std::function<bool(GlobalValue::GUID)> IsPrevailing)
67700b57cec5SDimitry Andric     : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex),
6771c9157d92SDimitry Andric       ModulePath(ModulePath), IsPrevailing(IsPrevailing) {}
67720b57cec5SDimitry Andric 
addThisModule()67730b57cec5SDimitry Andric void ModuleSummaryIndexBitcodeReader::addThisModule() {
6774c9157d92SDimitry Andric   TheIndex.addModule(ModulePath);
67750b57cec5SDimitry Andric }
67760b57cec5SDimitry Andric 
67770b57cec5SDimitry Andric ModuleSummaryIndex::ModuleInfo *
getThisModule()67780b57cec5SDimitry Andric ModuleSummaryIndexBitcodeReader::getThisModule() {
67790b57cec5SDimitry Andric   return TheIndex.getModule(ModulePath);
67800b57cec5SDimitry Andric }
67810b57cec5SDimitry Andric 
6782bdd1243dSDimitry Andric template <bool AllowNullValueInfo>
6783bdd1243dSDimitry Andric std::tuple<ValueInfo, GlobalValue::GUID, GlobalValue::GUID>
getValueInfoFromValueId(unsigned ValueId)67840b57cec5SDimitry Andric ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) {
67850b57cec5SDimitry Andric   auto VGI = ValueIdToValueInfoMap[ValueId];
6786bdd1243dSDimitry Andric   // We can have a null value info for memprof callsite info records in
6787bdd1243dSDimitry Andric   // distributed ThinLTO index files when the callee function summary is not
6788bdd1243dSDimitry Andric   // included in the index. The bitcode writer records 0 in that case,
6789bdd1243dSDimitry Andric   // and the caller of this helper will set AllowNullValueInfo to true.
6790bdd1243dSDimitry Andric   assert(AllowNullValueInfo || std::get<0>(VGI));
67910b57cec5SDimitry Andric   return VGI;
67920b57cec5SDimitry Andric }
67930b57cec5SDimitry Andric 
setValueGUID(uint64_t ValueID,StringRef ValueName,GlobalValue::LinkageTypes Linkage,StringRef SourceFileName)67940b57cec5SDimitry Andric void ModuleSummaryIndexBitcodeReader::setValueGUID(
67950b57cec5SDimitry Andric     uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage,
67960b57cec5SDimitry Andric     StringRef SourceFileName) {
67970b57cec5SDimitry Andric   std::string GlobalId =
67980b57cec5SDimitry Andric       GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
67990b57cec5SDimitry Andric   auto ValueGUID = GlobalValue::getGUID(GlobalId);
68000b57cec5SDimitry Andric   auto OriginalNameID = ValueGUID;
68010b57cec5SDimitry Andric   if (GlobalValue::isLocalLinkage(Linkage))
68020b57cec5SDimitry Andric     OriginalNameID = GlobalValue::getGUID(ValueName);
68030b57cec5SDimitry Andric   if (PrintSummaryGUIDs)
68040b57cec5SDimitry Andric     dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
68050b57cec5SDimitry Andric            << ValueName << "\n";
68060b57cec5SDimitry Andric 
68070b57cec5SDimitry Andric   // UseStrtab is false for legacy summary formats and value names are
68080b57cec5SDimitry Andric   // created on stack. In that case we save the name in a string saver in
68090b57cec5SDimitry Andric   // the index so that the value name can be recorded.
6810bdd1243dSDimitry Andric   ValueIdToValueInfoMap[ValueID] = std::make_tuple(
68110b57cec5SDimitry Andric       TheIndex.getOrInsertValueInfo(
6812bdd1243dSDimitry Andric           ValueGUID, UseStrtab ? ValueName : TheIndex.saveString(ValueName)),
6813bdd1243dSDimitry Andric       OriginalNameID, ValueGUID);
68140b57cec5SDimitry Andric }
68150b57cec5SDimitry Andric 
68160b57cec5SDimitry Andric // Specialized value symbol table parser used when reading module index
68170b57cec5SDimitry Andric // blocks where we don't actually create global values. The parsed information
68180b57cec5SDimitry Andric // is saved in the bitcode reader for use when later parsing summaries.
parseValueSymbolTable(uint64_t Offset,DenseMap<unsigned,GlobalValue::LinkageTypes> & ValueIdToLinkageMap)68190b57cec5SDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
68200b57cec5SDimitry Andric     uint64_t Offset,
68210b57cec5SDimitry Andric     DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
68220b57cec5SDimitry Andric   // With a strtab the VST is not required to parse the summary.
68230b57cec5SDimitry Andric   if (UseStrtab)
68240b57cec5SDimitry Andric     return Error::success();
68250b57cec5SDimitry Andric 
68260b57cec5SDimitry Andric   assert(Offset > 0 && "Expected non-zero VST offset");
68270b57cec5SDimitry Andric   Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream);
68280b57cec5SDimitry Andric   if (!MaybeCurrentBit)
68290b57cec5SDimitry Andric     return MaybeCurrentBit.takeError();
68300b57cec5SDimitry Andric   uint64_t CurrentBit = MaybeCurrentBit.get();
68310b57cec5SDimitry Andric 
68320b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
68330b57cec5SDimitry Andric     return Err;
68340b57cec5SDimitry Andric 
68350b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
68360b57cec5SDimitry Andric 
68370b57cec5SDimitry Andric   // Read all the records for this value table.
68380b57cec5SDimitry Andric   SmallString<128> ValueName;
68390b57cec5SDimitry Andric 
68400b57cec5SDimitry Andric   while (true) {
68410b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
68420b57cec5SDimitry Andric     if (!MaybeEntry)
68430b57cec5SDimitry Andric       return MaybeEntry.takeError();
68440b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
68450b57cec5SDimitry Andric 
68460b57cec5SDimitry Andric     switch (Entry.Kind) {
68470b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
68480b57cec5SDimitry Andric     case BitstreamEntry::Error:
68490b57cec5SDimitry Andric       return error("Malformed block");
68500b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
68510b57cec5SDimitry Andric       // Done parsing VST, jump back to wherever we came from.
68520b57cec5SDimitry Andric       if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
68530b57cec5SDimitry Andric         return JumpFailed;
68540b57cec5SDimitry Andric       return Error::success();
68550b57cec5SDimitry Andric     case BitstreamEntry::Record:
68560b57cec5SDimitry Andric       // The interesting case.
68570b57cec5SDimitry Andric       break;
68580b57cec5SDimitry Andric     }
68590b57cec5SDimitry Andric 
68600b57cec5SDimitry Andric     // Read a record.
68610b57cec5SDimitry Andric     Record.clear();
68620b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
68630b57cec5SDimitry Andric     if (!MaybeRecord)
68640b57cec5SDimitry Andric       return MaybeRecord.takeError();
68650b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
68660b57cec5SDimitry Andric     default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
68670b57cec5SDimitry Andric       break;
68680b57cec5SDimitry Andric     case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
68690b57cec5SDimitry Andric       if (convertToString(Record, 1, ValueName))
68700b57cec5SDimitry Andric         return error("Invalid record");
68710b57cec5SDimitry Andric       unsigned ValueID = Record[0];
68720b57cec5SDimitry Andric       assert(!SourceFileName.empty());
68730b57cec5SDimitry Andric       auto VLI = ValueIdToLinkageMap.find(ValueID);
68740b57cec5SDimitry Andric       assert(VLI != ValueIdToLinkageMap.end() &&
68750b57cec5SDimitry Andric              "No linkage found for VST entry?");
68760b57cec5SDimitry Andric       auto Linkage = VLI->second;
68770b57cec5SDimitry Andric       setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
68780b57cec5SDimitry Andric       ValueName.clear();
68790b57cec5SDimitry Andric       break;
68800b57cec5SDimitry Andric     }
68810b57cec5SDimitry Andric     case bitc::VST_CODE_FNENTRY: {
68820b57cec5SDimitry Andric       // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
68830b57cec5SDimitry Andric       if (convertToString(Record, 2, ValueName))
68840b57cec5SDimitry Andric         return error("Invalid record");
68850b57cec5SDimitry Andric       unsigned ValueID = Record[0];
68860b57cec5SDimitry Andric       assert(!SourceFileName.empty());
68870b57cec5SDimitry Andric       auto VLI = ValueIdToLinkageMap.find(ValueID);
68880b57cec5SDimitry Andric       assert(VLI != ValueIdToLinkageMap.end() &&
68890b57cec5SDimitry Andric              "No linkage found for VST entry?");
68900b57cec5SDimitry Andric       auto Linkage = VLI->second;
68910b57cec5SDimitry Andric       setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
68920b57cec5SDimitry Andric       ValueName.clear();
68930b57cec5SDimitry Andric       break;
68940b57cec5SDimitry Andric     }
68950b57cec5SDimitry Andric     case bitc::VST_CODE_COMBINED_ENTRY: {
68960b57cec5SDimitry Andric       // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
68970b57cec5SDimitry Andric       unsigned ValueID = Record[0];
68980b57cec5SDimitry Andric       GlobalValue::GUID RefGUID = Record[1];
68990b57cec5SDimitry Andric       // The "original name", which is the second value of the pair will be
69000b57cec5SDimitry Andric       // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
6901bdd1243dSDimitry Andric       ValueIdToValueInfoMap[ValueID] = std::make_tuple(
6902bdd1243dSDimitry Andric           TheIndex.getOrInsertValueInfo(RefGUID), RefGUID, RefGUID);
69030b57cec5SDimitry Andric       break;
69040b57cec5SDimitry Andric     }
69050b57cec5SDimitry Andric     }
69060b57cec5SDimitry Andric   }
69070b57cec5SDimitry Andric }
69080b57cec5SDimitry Andric 
69090b57cec5SDimitry Andric // Parse just the blocks needed for building the index out of the module.
69100b57cec5SDimitry Andric // At the end of this routine the module Index is populated with a map
69110b57cec5SDimitry Andric // from global value id to GlobalValueSummary objects.
parseModule()69120b57cec5SDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseModule() {
69130b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
69140b57cec5SDimitry Andric     return Err;
69150b57cec5SDimitry Andric 
69160b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
69170b57cec5SDimitry Andric   DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
69180b57cec5SDimitry Andric   unsigned ValueId = 0;
69190b57cec5SDimitry Andric 
69200b57cec5SDimitry Andric   // Read the index for this module.
69210b57cec5SDimitry Andric   while (true) {
69220b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
69230b57cec5SDimitry Andric     if (!MaybeEntry)
69240b57cec5SDimitry Andric       return MaybeEntry.takeError();
69250b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
69260b57cec5SDimitry Andric 
69270b57cec5SDimitry Andric     switch (Entry.Kind) {
69280b57cec5SDimitry Andric     case BitstreamEntry::Error:
69290b57cec5SDimitry Andric       return error("Malformed block");
69300b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
69310b57cec5SDimitry Andric       return Error::success();
69320b57cec5SDimitry Andric 
69330b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
69340b57cec5SDimitry Andric       switch (Entry.ID) {
69350b57cec5SDimitry Andric       default: // Skip unknown content.
69360b57cec5SDimitry Andric         if (Error Err = Stream.SkipBlock())
69370b57cec5SDimitry Andric           return Err;
69380b57cec5SDimitry Andric         break;
69390b57cec5SDimitry Andric       case bitc::BLOCKINFO_BLOCK_ID:
69400b57cec5SDimitry Andric         // Need to parse these to get abbrev ids (e.g. for VST)
694181ad6265SDimitry Andric         if (Error Err = readBlockInfo())
694281ad6265SDimitry Andric           return Err;
69430b57cec5SDimitry Andric         break;
69440b57cec5SDimitry Andric       case bitc::VALUE_SYMTAB_BLOCK_ID:
69450b57cec5SDimitry Andric         // Should have been parsed earlier via VSTOffset, unless there
69460b57cec5SDimitry Andric         // is no summary section.
69470b57cec5SDimitry Andric         assert(((SeenValueSymbolTable && VSTOffset > 0) ||
69480b57cec5SDimitry Andric                 !SeenGlobalValSummary) &&
69490b57cec5SDimitry Andric                "Expected early VST parse via VSTOffset record");
69500b57cec5SDimitry Andric         if (Error Err = Stream.SkipBlock())
69510b57cec5SDimitry Andric           return Err;
69520b57cec5SDimitry Andric         break;
69530b57cec5SDimitry Andric       case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
69540b57cec5SDimitry Andric       case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID:
69550b57cec5SDimitry Andric         // Add the module if it is a per-module index (has a source file name).
69560b57cec5SDimitry Andric         if (!SourceFileName.empty())
69570b57cec5SDimitry Andric           addThisModule();
69580b57cec5SDimitry Andric         assert(!SeenValueSymbolTable &&
69590b57cec5SDimitry Andric                "Already read VST when parsing summary block?");
69600b57cec5SDimitry Andric         // We might not have a VST if there were no values in the
69610b57cec5SDimitry Andric         // summary. An empty summary block generated when we are
69620b57cec5SDimitry Andric         // performing ThinLTO compiles so we don't later invoke
69630b57cec5SDimitry Andric         // the regular LTO process on them.
69640b57cec5SDimitry Andric         if (VSTOffset > 0) {
69650b57cec5SDimitry Andric           if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
69660b57cec5SDimitry Andric             return Err;
69670b57cec5SDimitry Andric           SeenValueSymbolTable = true;
69680b57cec5SDimitry Andric         }
69690b57cec5SDimitry Andric         SeenGlobalValSummary = true;
69700b57cec5SDimitry Andric         if (Error Err = parseEntireSummary(Entry.ID))
69710b57cec5SDimitry Andric           return Err;
69720b57cec5SDimitry Andric         break;
69730b57cec5SDimitry Andric       case bitc::MODULE_STRTAB_BLOCK_ID:
69740b57cec5SDimitry Andric         if (Error Err = parseModuleStringTable())
69750b57cec5SDimitry Andric           return Err;
69760b57cec5SDimitry Andric         break;
69770b57cec5SDimitry Andric       }
69780b57cec5SDimitry Andric       continue;
69790b57cec5SDimitry Andric 
69800b57cec5SDimitry Andric     case BitstreamEntry::Record: {
69810b57cec5SDimitry Andric         Record.clear();
69820b57cec5SDimitry Andric         Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
69830b57cec5SDimitry Andric         if (!MaybeBitCode)
69840b57cec5SDimitry Andric           return MaybeBitCode.takeError();
69850b57cec5SDimitry Andric         switch (MaybeBitCode.get()) {
69860b57cec5SDimitry Andric         default:
69870b57cec5SDimitry Andric           break; // Default behavior, ignore unknown content.
69880b57cec5SDimitry Andric         case bitc::MODULE_CODE_VERSION: {
69890b57cec5SDimitry Andric           if (Error Err = parseVersionRecord(Record).takeError())
69900b57cec5SDimitry Andric             return Err;
69910b57cec5SDimitry Andric           break;
69920b57cec5SDimitry Andric         }
69930b57cec5SDimitry Andric         /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
69940b57cec5SDimitry Andric         case bitc::MODULE_CODE_SOURCE_FILENAME: {
69950b57cec5SDimitry Andric           SmallString<128> ValueName;
69960b57cec5SDimitry Andric           if (convertToString(Record, 0, ValueName))
69970b57cec5SDimitry Andric             return error("Invalid record");
69980b57cec5SDimitry Andric           SourceFileName = ValueName.c_str();
69990b57cec5SDimitry Andric           break;
70000b57cec5SDimitry Andric         }
70010b57cec5SDimitry Andric         /// MODULE_CODE_HASH: [5*i32]
70020b57cec5SDimitry Andric         case bitc::MODULE_CODE_HASH: {
70030b57cec5SDimitry Andric           if (Record.size() != 5)
70040b57cec5SDimitry Andric             return error("Invalid hash length " + Twine(Record.size()).str());
7005c9157d92SDimitry Andric           auto &Hash = getThisModule()->second;
70060b57cec5SDimitry Andric           int Pos = 0;
70070b57cec5SDimitry Andric           for (auto &Val : Record) {
70080b57cec5SDimitry Andric             assert(!(Val >> 32) && "Unexpected high bits set");
70090b57cec5SDimitry Andric             Hash[Pos++] = Val;
70100b57cec5SDimitry Andric           }
70110b57cec5SDimitry Andric           break;
70120b57cec5SDimitry Andric         }
70130b57cec5SDimitry Andric         /// MODULE_CODE_VSTOFFSET: [offset]
70140b57cec5SDimitry Andric         case bitc::MODULE_CODE_VSTOFFSET:
7015e8d8bef9SDimitry Andric           if (Record.empty())
70160b57cec5SDimitry Andric             return error("Invalid record");
70170b57cec5SDimitry Andric           // Note that we subtract 1 here because the offset is relative to one
70180b57cec5SDimitry Andric           // word before the start of the identification or module block, which
70190b57cec5SDimitry Andric           // was historically always the start of the regular bitcode header.
70200b57cec5SDimitry Andric           VSTOffset = Record[0] - 1;
70210b57cec5SDimitry Andric           break;
70220b57cec5SDimitry Andric         // v1 GLOBALVAR: [pointer type, isconst,     initid,       linkage, ...]
70230b57cec5SDimitry Andric         // v1 FUNCTION:  [type,         callingconv, isproto,      linkage, ...]
70240b57cec5SDimitry Andric         // v1 ALIAS:     [alias type,   addrspace,   aliasee val#, linkage, ...]
70250b57cec5SDimitry Andric         // v2: [strtab offset, strtab size, v1]
70260b57cec5SDimitry Andric         case bitc::MODULE_CODE_GLOBALVAR:
70270b57cec5SDimitry Andric         case bitc::MODULE_CODE_FUNCTION:
70280b57cec5SDimitry Andric         case bitc::MODULE_CODE_ALIAS: {
70290b57cec5SDimitry Andric           StringRef Name;
70300b57cec5SDimitry Andric           ArrayRef<uint64_t> GVRecord;
70310b57cec5SDimitry Andric           std::tie(Name, GVRecord) = readNameFromStrtab(Record);
70320b57cec5SDimitry Andric           if (GVRecord.size() <= 3)
70330b57cec5SDimitry Andric             return error("Invalid record");
70340b57cec5SDimitry Andric           uint64_t RawLinkage = GVRecord[3];
70350b57cec5SDimitry Andric           GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
70360b57cec5SDimitry Andric           if (!UseStrtab) {
70370b57cec5SDimitry Andric             ValueIdToLinkageMap[ValueId++] = Linkage;
70380b57cec5SDimitry Andric             break;
70390b57cec5SDimitry Andric           }
70400b57cec5SDimitry Andric 
70410b57cec5SDimitry Andric           setValueGUID(ValueId++, Name, Linkage, SourceFileName);
70420b57cec5SDimitry Andric           break;
70430b57cec5SDimitry Andric         }
70440b57cec5SDimitry Andric         }
70450b57cec5SDimitry Andric       }
70460b57cec5SDimitry Andric       continue;
70470b57cec5SDimitry Andric     }
70480b57cec5SDimitry Andric   }
70490b57cec5SDimitry Andric }
70500b57cec5SDimitry Andric 
70510b57cec5SDimitry Andric std::vector<ValueInfo>
makeRefList(ArrayRef<uint64_t> Record)70520b57cec5SDimitry Andric ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
70530b57cec5SDimitry Andric   std::vector<ValueInfo> Ret;
70540b57cec5SDimitry Andric   Ret.reserve(Record.size());
70550b57cec5SDimitry Andric   for (uint64_t RefValueId : Record)
7056bdd1243dSDimitry Andric     Ret.push_back(std::get<0>(getValueInfoFromValueId(RefValueId)));
70570b57cec5SDimitry Andric   return Ret;
70580b57cec5SDimitry Andric }
70590b57cec5SDimitry Andric 
70600b57cec5SDimitry Andric std::vector<FunctionSummary::EdgeTy>
makeCallList(ArrayRef<uint64_t> Record,bool IsOldProfileFormat,bool HasProfile,bool HasRelBF)70610b57cec5SDimitry Andric ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record,
70620b57cec5SDimitry Andric                                               bool IsOldProfileFormat,
70630b57cec5SDimitry Andric                                               bool HasProfile, bool HasRelBF) {
70640b57cec5SDimitry Andric   std::vector<FunctionSummary::EdgeTy> Ret;
70650b57cec5SDimitry Andric   Ret.reserve(Record.size());
70660b57cec5SDimitry Andric   for (unsigned I = 0, E = Record.size(); I != E; ++I) {
70670b57cec5SDimitry Andric     CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
7068c9157d92SDimitry Andric     bool HasTailCall = false;
70690b57cec5SDimitry Andric     uint64_t RelBF = 0;
7070bdd1243dSDimitry Andric     ValueInfo Callee = std::get<0>(getValueInfoFromValueId(Record[I]));
70710b57cec5SDimitry Andric     if (IsOldProfileFormat) {
70720b57cec5SDimitry Andric       I += 1; // Skip old callsitecount field
70730b57cec5SDimitry Andric       if (HasProfile)
70740b57cec5SDimitry Andric         I += 1; // Skip old profilecount field
70750b57cec5SDimitry Andric     } else if (HasProfile)
7076c9157d92SDimitry Andric       std::tie(Hotness, HasTailCall) =
7077c9157d92SDimitry Andric           getDecodedHotnessCallEdgeInfo(Record[++I]);
70780b57cec5SDimitry Andric     else if (HasRelBF)
7079c9157d92SDimitry Andric       getDecodedRelBFCallEdgeInfo(Record[++I], RelBF, HasTailCall);
7080c9157d92SDimitry Andric     Ret.push_back(FunctionSummary::EdgeTy{
7081c9157d92SDimitry Andric         Callee, CalleeInfo(Hotness, HasTailCall, RelBF)});
70820b57cec5SDimitry Andric   }
70830b57cec5SDimitry Andric   return Ret;
70840b57cec5SDimitry Andric }
70850b57cec5SDimitry Andric 
70860b57cec5SDimitry Andric static void
parseWholeProgramDevirtResolutionByArg(ArrayRef<uint64_t> Record,size_t & Slot,WholeProgramDevirtResolution & Wpd)70870b57cec5SDimitry Andric parseWholeProgramDevirtResolutionByArg(ArrayRef<uint64_t> Record, size_t &Slot,
70880b57cec5SDimitry Andric                                        WholeProgramDevirtResolution &Wpd) {
70890b57cec5SDimitry Andric   uint64_t ArgNum = Record[Slot++];
70900b57cec5SDimitry Andric   WholeProgramDevirtResolution::ByArg &B =
70910b57cec5SDimitry Andric       Wpd.ResByArg[{Record.begin() + Slot, Record.begin() + Slot + ArgNum}];
70920b57cec5SDimitry Andric   Slot += ArgNum;
70930b57cec5SDimitry Andric 
70940b57cec5SDimitry Andric   B.TheKind =
70950b57cec5SDimitry Andric       static_cast<WholeProgramDevirtResolution::ByArg::Kind>(Record[Slot++]);
70960b57cec5SDimitry Andric   B.Info = Record[Slot++];
70970b57cec5SDimitry Andric   B.Byte = Record[Slot++];
70980b57cec5SDimitry Andric   B.Bit = Record[Slot++];
70990b57cec5SDimitry Andric }
71000b57cec5SDimitry Andric 
parseWholeProgramDevirtResolution(ArrayRef<uint64_t> Record,StringRef Strtab,size_t & Slot,TypeIdSummary & TypeId)71010b57cec5SDimitry Andric static void parseWholeProgramDevirtResolution(ArrayRef<uint64_t> Record,
71020b57cec5SDimitry Andric                                               StringRef Strtab, size_t &Slot,
71030b57cec5SDimitry Andric                                               TypeIdSummary &TypeId) {
71040b57cec5SDimitry Andric   uint64_t Id = Record[Slot++];
71050b57cec5SDimitry Andric   WholeProgramDevirtResolution &Wpd = TypeId.WPDRes[Id];
71060b57cec5SDimitry Andric 
71070b57cec5SDimitry Andric   Wpd.TheKind = static_cast<WholeProgramDevirtResolution::Kind>(Record[Slot++]);
71080b57cec5SDimitry Andric   Wpd.SingleImplName = {Strtab.data() + Record[Slot],
71090b57cec5SDimitry Andric                         static_cast<size_t>(Record[Slot + 1])};
71100b57cec5SDimitry Andric   Slot += 2;
71110b57cec5SDimitry Andric 
71120b57cec5SDimitry Andric   uint64_t ResByArgNum = Record[Slot++];
71130b57cec5SDimitry Andric   for (uint64_t I = 0; I != ResByArgNum; ++I)
71140b57cec5SDimitry Andric     parseWholeProgramDevirtResolutionByArg(Record, Slot, Wpd);
71150b57cec5SDimitry Andric }
71160b57cec5SDimitry Andric 
parseTypeIdSummaryRecord(ArrayRef<uint64_t> Record,StringRef Strtab,ModuleSummaryIndex & TheIndex)71170b57cec5SDimitry Andric static void parseTypeIdSummaryRecord(ArrayRef<uint64_t> Record,
71180b57cec5SDimitry Andric                                      StringRef Strtab,
71190b57cec5SDimitry Andric                                      ModuleSummaryIndex &TheIndex) {
71200b57cec5SDimitry Andric   size_t Slot = 0;
71210b57cec5SDimitry Andric   TypeIdSummary &TypeId = TheIndex.getOrInsertTypeIdSummary(
71220b57cec5SDimitry Andric       {Strtab.data() + Record[Slot], static_cast<size_t>(Record[Slot + 1])});
71230b57cec5SDimitry Andric   Slot += 2;
71240b57cec5SDimitry Andric 
71250b57cec5SDimitry Andric   TypeId.TTRes.TheKind = static_cast<TypeTestResolution::Kind>(Record[Slot++]);
71260b57cec5SDimitry Andric   TypeId.TTRes.SizeM1BitWidth = Record[Slot++];
71270b57cec5SDimitry Andric   TypeId.TTRes.AlignLog2 = Record[Slot++];
71280b57cec5SDimitry Andric   TypeId.TTRes.SizeM1 = Record[Slot++];
71290b57cec5SDimitry Andric   TypeId.TTRes.BitMask = Record[Slot++];
71300b57cec5SDimitry Andric   TypeId.TTRes.InlineBits = Record[Slot++];
71310b57cec5SDimitry Andric 
71320b57cec5SDimitry Andric   while (Slot < Record.size())
71330b57cec5SDimitry Andric     parseWholeProgramDevirtResolution(Record, Strtab, Slot, TypeId);
71340b57cec5SDimitry Andric }
71350b57cec5SDimitry Andric 
7136e8d8bef9SDimitry Andric std::vector<FunctionSummary::ParamAccess>
parseParamAccesses(ArrayRef<uint64_t> Record)7137e8d8bef9SDimitry Andric ModuleSummaryIndexBitcodeReader::parseParamAccesses(ArrayRef<uint64_t> Record) {
71385ffd83dbSDimitry Andric   auto ReadRange = [&]() {
71395ffd83dbSDimitry Andric     APInt Lower(FunctionSummary::ParamAccess::RangeWidth,
71405ffd83dbSDimitry Andric                 BitcodeReader::decodeSignRotatedValue(Record.front()));
71415ffd83dbSDimitry Andric     Record = Record.drop_front();
71425ffd83dbSDimitry Andric     APInt Upper(FunctionSummary::ParamAccess::RangeWidth,
71435ffd83dbSDimitry Andric                 BitcodeReader::decodeSignRotatedValue(Record.front()));
71445ffd83dbSDimitry Andric     Record = Record.drop_front();
71455ffd83dbSDimitry Andric     ConstantRange Range{Lower, Upper};
71465ffd83dbSDimitry Andric     assert(!Range.isFullSet());
71475ffd83dbSDimitry Andric     assert(!Range.isUpperSignWrapped());
71485ffd83dbSDimitry Andric     return Range;
71495ffd83dbSDimitry Andric   };
71505ffd83dbSDimitry Andric 
71515ffd83dbSDimitry Andric   std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
71525ffd83dbSDimitry Andric   while (!Record.empty()) {
71535ffd83dbSDimitry Andric     PendingParamAccesses.emplace_back();
71545ffd83dbSDimitry Andric     FunctionSummary::ParamAccess &ParamAccess = PendingParamAccesses.back();
71555ffd83dbSDimitry Andric     ParamAccess.ParamNo = Record.front();
71565ffd83dbSDimitry Andric     Record = Record.drop_front();
71575ffd83dbSDimitry Andric     ParamAccess.Use = ReadRange();
71585ffd83dbSDimitry Andric     ParamAccess.Calls.resize(Record.front());
71595ffd83dbSDimitry Andric     Record = Record.drop_front();
71605ffd83dbSDimitry Andric     for (auto &Call : ParamAccess.Calls) {
71615ffd83dbSDimitry Andric       Call.ParamNo = Record.front();
71625ffd83dbSDimitry Andric       Record = Record.drop_front();
7163bdd1243dSDimitry Andric       Call.Callee = std::get<0>(getValueInfoFromValueId(Record.front()));
71645ffd83dbSDimitry Andric       Record = Record.drop_front();
71655ffd83dbSDimitry Andric       Call.Offsets = ReadRange();
71665ffd83dbSDimitry Andric     }
71675ffd83dbSDimitry Andric   }
71685ffd83dbSDimitry Andric   return PendingParamAccesses;
71695ffd83dbSDimitry Andric }
71705ffd83dbSDimitry Andric 
parseTypeIdCompatibleVtableInfo(ArrayRef<uint64_t> Record,size_t & Slot,TypeIdCompatibleVtableInfo & TypeId)71710b57cec5SDimitry Andric void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo(
71720b57cec5SDimitry Andric     ArrayRef<uint64_t> Record, size_t &Slot,
71730b57cec5SDimitry Andric     TypeIdCompatibleVtableInfo &TypeId) {
71740b57cec5SDimitry Andric   uint64_t Offset = Record[Slot++];
7175bdd1243dSDimitry Andric   ValueInfo Callee = std::get<0>(getValueInfoFromValueId(Record[Slot++]));
71760b57cec5SDimitry Andric   TypeId.push_back({Offset, Callee});
71770b57cec5SDimitry Andric }
71780b57cec5SDimitry Andric 
parseTypeIdCompatibleVtableSummaryRecord(ArrayRef<uint64_t> Record)71790b57cec5SDimitry Andric void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord(
71800b57cec5SDimitry Andric     ArrayRef<uint64_t> Record) {
71810b57cec5SDimitry Andric   size_t Slot = 0;
71820b57cec5SDimitry Andric   TypeIdCompatibleVtableInfo &TypeId =
71830b57cec5SDimitry Andric       TheIndex.getOrInsertTypeIdCompatibleVtableSummary(
71840b57cec5SDimitry Andric           {Strtab.data() + Record[Slot],
71850b57cec5SDimitry Andric            static_cast<size_t>(Record[Slot + 1])});
71860b57cec5SDimitry Andric   Slot += 2;
71870b57cec5SDimitry Andric 
71880b57cec5SDimitry Andric   while (Slot < Record.size())
71890b57cec5SDimitry Andric     parseTypeIdCompatibleVtableInfo(Record, Slot, TypeId);
71900b57cec5SDimitry Andric }
71910b57cec5SDimitry Andric 
setSpecialRefs(std::vector<ValueInfo> & Refs,unsigned ROCnt,unsigned WOCnt)71920b57cec5SDimitry Andric static void setSpecialRefs(std::vector<ValueInfo> &Refs, unsigned ROCnt,
71930b57cec5SDimitry Andric                            unsigned WOCnt) {
71940b57cec5SDimitry Andric   // Readonly and writeonly refs are in the end of the refs list.
71950b57cec5SDimitry Andric   assert(ROCnt + WOCnt <= Refs.size());
71960b57cec5SDimitry Andric   unsigned FirstWORef = Refs.size() - WOCnt;
71970b57cec5SDimitry Andric   unsigned RefNo = FirstWORef - ROCnt;
71980b57cec5SDimitry Andric   for (; RefNo < FirstWORef; ++RefNo)
71990b57cec5SDimitry Andric     Refs[RefNo].setReadOnly();
72000b57cec5SDimitry Andric   for (; RefNo < Refs.size(); ++RefNo)
72010b57cec5SDimitry Andric     Refs[RefNo].setWriteOnly();
72020b57cec5SDimitry Andric }
72030b57cec5SDimitry Andric 
72040b57cec5SDimitry Andric // Eagerly parse the entire summary block. This populates the GlobalValueSummary
72050b57cec5SDimitry Andric // objects in the index.
parseEntireSummary(unsigned ID)72060b57cec5SDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) {
72070b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(ID))
72080b57cec5SDimitry Andric     return Err;
72090b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
72100b57cec5SDimitry Andric 
72110b57cec5SDimitry Andric   // Parse version
72120b57cec5SDimitry Andric   {
72130b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
72140b57cec5SDimitry Andric     if (!MaybeEntry)
72150b57cec5SDimitry Andric       return MaybeEntry.takeError();
72160b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
72170b57cec5SDimitry Andric 
72180b57cec5SDimitry Andric     if (Entry.Kind != BitstreamEntry::Record)
72190b57cec5SDimitry Andric       return error("Invalid Summary Block: record for version expected");
72200b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
72210b57cec5SDimitry Andric     if (!MaybeRecord)
72220b57cec5SDimitry Andric       return MaybeRecord.takeError();
72230b57cec5SDimitry Andric     if (MaybeRecord.get() != bitc::FS_VERSION)
72240b57cec5SDimitry Andric       return error("Invalid Summary Block: version expected");
72250b57cec5SDimitry Andric   }
72260b57cec5SDimitry Andric   const uint64_t Version = Record[0];
72270b57cec5SDimitry Andric   const bool IsOldProfileFormat = Version == 1;
7228480093f4SDimitry Andric   if (Version < 1 || Version > ModuleSummaryIndex::BitcodeSummaryVersion)
72290b57cec5SDimitry Andric     return error("Invalid summary version " + Twine(Version) +
7230480093f4SDimitry Andric                  ". Version should be in the range [1-" +
7231480093f4SDimitry Andric                  Twine(ModuleSummaryIndex::BitcodeSummaryVersion) +
7232480093f4SDimitry Andric                  "].");
72330b57cec5SDimitry Andric   Record.clear();
72340b57cec5SDimitry Andric 
72350b57cec5SDimitry Andric   // Keep around the last seen summary to be used when we see an optional
72360b57cec5SDimitry Andric   // "OriginalName" attachement.
72370b57cec5SDimitry Andric   GlobalValueSummary *LastSeenSummary = nullptr;
72380b57cec5SDimitry Andric   GlobalValue::GUID LastSeenGUID = 0;
72390b57cec5SDimitry Andric 
72400b57cec5SDimitry Andric   // We can expect to see any number of type ID information records before
72410b57cec5SDimitry Andric   // each function summary records; these variables store the information
72420b57cec5SDimitry Andric   // collected so far so that it can be used to create the summary object.
72430b57cec5SDimitry Andric   std::vector<GlobalValue::GUID> PendingTypeTests;
72440b57cec5SDimitry Andric   std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
72450b57cec5SDimitry Andric       PendingTypeCheckedLoadVCalls;
72460b57cec5SDimitry Andric   std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
72470b57cec5SDimitry Andric       PendingTypeCheckedLoadConstVCalls;
72485ffd83dbSDimitry Andric   std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
72490b57cec5SDimitry Andric 
7250bdd1243dSDimitry Andric   std::vector<CallsiteInfo> PendingCallsites;
7251bdd1243dSDimitry Andric   std::vector<AllocInfo> PendingAllocs;
7252bdd1243dSDimitry Andric 
72530b57cec5SDimitry Andric   while (true) {
72540b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
72550b57cec5SDimitry Andric     if (!MaybeEntry)
72560b57cec5SDimitry Andric       return MaybeEntry.takeError();
72570b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
72580b57cec5SDimitry Andric 
72590b57cec5SDimitry Andric     switch (Entry.Kind) {
72600b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
72610b57cec5SDimitry Andric     case BitstreamEntry::Error:
72620b57cec5SDimitry Andric       return error("Malformed block");
72630b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
72640b57cec5SDimitry Andric       return Error::success();
72650b57cec5SDimitry Andric     case BitstreamEntry::Record:
72660b57cec5SDimitry Andric       // The interesting case.
72670b57cec5SDimitry Andric       break;
72680b57cec5SDimitry Andric     }
72690b57cec5SDimitry Andric 
72700b57cec5SDimitry Andric     // Read a record. The record format depends on whether this
72710b57cec5SDimitry Andric     // is a per-module index or a combined index file. In the per-module
72720b57cec5SDimitry Andric     // case the records contain the associated value's ID for correlation
72730b57cec5SDimitry Andric     // with VST entries. In the combined index the correlation is done
72740b57cec5SDimitry Andric     // via the bitcode offset of the summary records (which were saved
72750b57cec5SDimitry Andric     // in the combined index VST entries). The records also contain
72760b57cec5SDimitry Andric     // information used for ThinLTO renaming and importing.
72770b57cec5SDimitry Andric     Record.clear();
72780b57cec5SDimitry Andric     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
72790b57cec5SDimitry Andric     if (!MaybeBitCode)
72800b57cec5SDimitry Andric       return MaybeBitCode.takeError();
72810b57cec5SDimitry Andric     switch (unsigned BitCode = MaybeBitCode.get()) {
72820b57cec5SDimitry Andric     default: // Default behavior: ignore.
72830b57cec5SDimitry Andric       break;
72840b57cec5SDimitry Andric     case bitc::FS_FLAGS: {  // [flags]
72855ffd83dbSDimitry Andric       TheIndex.setFlags(Record[0]);
72860b57cec5SDimitry Andric       break;
72870b57cec5SDimitry Andric     }
72880b57cec5SDimitry Andric     case bitc::FS_VALUE_GUID: { // [valueid, refguid]
72890b57cec5SDimitry Andric       uint64_t ValueID = Record[0];
72900b57cec5SDimitry Andric       GlobalValue::GUID RefGUID = Record[1];
7291bdd1243dSDimitry Andric       ValueIdToValueInfoMap[ValueID] = std::make_tuple(
7292bdd1243dSDimitry Andric           TheIndex.getOrInsertValueInfo(RefGUID), RefGUID, RefGUID);
72930b57cec5SDimitry Andric       break;
72940b57cec5SDimitry Andric     }
7295c9157d92SDimitry Andric     // FS_PERMODULE is legacy and does not have support for the tail call flag.
72960b57cec5SDimitry Andric     // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs,
72970b57cec5SDimitry Andric     //                numrefs x valueid, n x (valueid)]
72980b57cec5SDimitry Andric     // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs,
72990b57cec5SDimitry Andric     //                        numrefs x valueid,
7300c9157d92SDimitry Andric     //                        n x (valueid, hotness+tailcall flags)]
73010b57cec5SDimitry Andric     // FS_PERMODULE_RELBF: [valueid, flags, instcount, fflags, numrefs,
73020b57cec5SDimitry Andric     //                      numrefs x valueid,
7303c9157d92SDimitry Andric     //                      n x (valueid, relblockfreq+tailcall)]
73040b57cec5SDimitry Andric     case bitc::FS_PERMODULE:
73050b57cec5SDimitry Andric     case bitc::FS_PERMODULE_RELBF:
73060b57cec5SDimitry Andric     case bitc::FS_PERMODULE_PROFILE: {
73070b57cec5SDimitry Andric       unsigned ValueID = Record[0];
73080b57cec5SDimitry Andric       uint64_t RawFlags = Record[1];
73090b57cec5SDimitry Andric       unsigned InstCount = Record[2];
73100b57cec5SDimitry Andric       uint64_t RawFunFlags = 0;
73110b57cec5SDimitry Andric       unsigned NumRefs = Record[3];
73120b57cec5SDimitry Andric       unsigned NumRORefs = 0, NumWORefs = 0;
73130b57cec5SDimitry Andric       int RefListStartIndex = 4;
73140b57cec5SDimitry Andric       if (Version >= 4) {
73150b57cec5SDimitry Andric         RawFunFlags = Record[3];
73160b57cec5SDimitry Andric         NumRefs = Record[4];
73170b57cec5SDimitry Andric         RefListStartIndex = 5;
73180b57cec5SDimitry Andric         if (Version >= 5) {
73190b57cec5SDimitry Andric           NumRORefs = Record[5];
73200b57cec5SDimitry Andric           RefListStartIndex = 6;
73210b57cec5SDimitry Andric           if (Version >= 7) {
73220b57cec5SDimitry Andric             NumWORefs = Record[6];
73230b57cec5SDimitry Andric             RefListStartIndex = 7;
73240b57cec5SDimitry Andric           }
73250b57cec5SDimitry Andric         }
73260b57cec5SDimitry Andric       }
73270b57cec5SDimitry Andric 
73280b57cec5SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
73290b57cec5SDimitry Andric       // The module path string ref set in the summary must be owned by the
73300b57cec5SDimitry Andric       // index's module string table. Since we don't have a module path
73310b57cec5SDimitry Andric       // string table section in the per-module index, we create a single
73320b57cec5SDimitry Andric       // module path string table entry with an empty (0) ID to take
73330b57cec5SDimitry Andric       // ownership.
73340b57cec5SDimitry Andric       int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
73350b57cec5SDimitry Andric       assert(Record.size() >= RefListStartIndex + NumRefs &&
73360b57cec5SDimitry Andric              "Record size inconsistent with number of references");
73370b57cec5SDimitry Andric       std::vector<ValueInfo> Refs = makeRefList(
73380b57cec5SDimitry Andric           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
73390b57cec5SDimitry Andric       bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
73400b57cec5SDimitry Andric       bool HasRelBF = (BitCode == bitc::FS_PERMODULE_RELBF);
73410b57cec5SDimitry Andric       std::vector<FunctionSummary::EdgeTy> Calls = makeCallList(
73420b57cec5SDimitry Andric           ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
73430b57cec5SDimitry Andric           IsOldProfileFormat, HasProfile, HasRelBF);
73440b57cec5SDimitry Andric       setSpecialRefs(Refs, NumRORefs, NumWORefs);
7345bdd1243dSDimitry Andric       auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID);
7346bdd1243dSDimitry Andric       // In order to save memory, only record the memprof summaries if this is
7347bdd1243dSDimitry Andric       // the prevailing copy of a symbol. The linker doesn't resolve local
7348bdd1243dSDimitry Andric       // linkage values so don't check whether those are prevailing.
7349bdd1243dSDimitry Andric       auto LT = (GlobalValue::LinkageTypes)Flags.Linkage;
7350bdd1243dSDimitry Andric       if (IsPrevailing &&
7351bdd1243dSDimitry Andric           !GlobalValue::isLocalLinkage(LT) &&
7352bdd1243dSDimitry Andric           !IsPrevailing(std::get<2>(VIAndOriginalGUID))) {
7353bdd1243dSDimitry Andric         PendingCallsites.clear();
7354bdd1243dSDimitry Andric         PendingAllocs.clear();
7355bdd1243dSDimitry Andric       }
73568bcb0991SDimitry Andric       auto FS = std::make_unique<FunctionSummary>(
73570b57cec5SDimitry Andric           Flags, InstCount, getDecodedFFlags(RawFunFlags), /*EntryCount=*/0,
73580b57cec5SDimitry Andric           std::move(Refs), std::move(Calls), std::move(PendingTypeTests),
73590b57cec5SDimitry Andric           std::move(PendingTypeTestAssumeVCalls),
73600b57cec5SDimitry Andric           std::move(PendingTypeCheckedLoadVCalls),
73610b57cec5SDimitry Andric           std::move(PendingTypeTestAssumeConstVCalls),
73625ffd83dbSDimitry Andric           std::move(PendingTypeCheckedLoadConstVCalls),
7363bdd1243dSDimitry Andric           std::move(PendingParamAccesses), std::move(PendingCallsites),
7364bdd1243dSDimitry Andric           std::move(PendingAllocs));
73650b57cec5SDimitry Andric       FS->setModulePath(getThisModule()->first());
7366bdd1243dSDimitry Andric       FS->setOriginalName(std::get<1>(VIAndOriginalGUID));
7367bdd1243dSDimitry Andric       TheIndex.addGlobalValueSummary(std::get<0>(VIAndOriginalGUID),
7368bdd1243dSDimitry Andric                                      std::move(FS));
73690b57cec5SDimitry Andric       break;
73700b57cec5SDimitry Andric     }
73710b57cec5SDimitry Andric     // FS_ALIAS: [valueid, flags, valueid]
73720b57cec5SDimitry Andric     // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
73730b57cec5SDimitry Andric     // they expect all aliasee summaries to be available.
73740b57cec5SDimitry Andric     case bitc::FS_ALIAS: {
73750b57cec5SDimitry Andric       unsigned ValueID = Record[0];
73760b57cec5SDimitry Andric       uint64_t RawFlags = Record[1];
73770b57cec5SDimitry Andric       unsigned AliaseeID = Record[2];
73780b57cec5SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
73798bcb0991SDimitry Andric       auto AS = std::make_unique<AliasSummary>(Flags);
73800b57cec5SDimitry Andric       // The module path string ref set in the summary must be owned by the
73810b57cec5SDimitry Andric       // index's module string table. Since we don't have a module path
73820b57cec5SDimitry Andric       // string table section in the per-module index, we create a single
73830b57cec5SDimitry Andric       // module path string table entry with an empty (0) ID to take
73840b57cec5SDimitry Andric       // ownership.
73850b57cec5SDimitry Andric       AS->setModulePath(getThisModule()->first());
73860b57cec5SDimitry Andric 
7387bdd1243dSDimitry Andric       auto AliaseeVI = std::get<0>(getValueInfoFromValueId(AliaseeID));
73880b57cec5SDimitry Andric       auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, ModulePath);
73890b57cec5SDimitry Andric       if (!AliaseeInModule)
73900b57cec5SDimitry Andric         return error("Alias expects aliasee summary to be parsed");
73910b57cec5SDimitry Andric       AS->setAliasee(AliaseeVI, AliaseeInModule);
73920b57cec5SDimitry Andric 
73930b57cec5SDimitry Andric       auto GUID = getValueInfoFromValueId(ValueID);
7394bdd1243dSDimitry Andric       AS->setOriginalName(std::get<1>(GUID));
7395bdd1243dSDimitry Andric       TheIndex.addGlobalValueSummary(std::get<0>(GUID), std::move(AS));
73960b57cec5SDimitry Andric       break;
73970b57cec5SDimitry Andric     }
73980b57cec5SDimitry Andric     // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, n x valueid]
73990b57cec5SDimitry Andric     case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
74000b57cec5SDimitry Andric       unsigned ValueID = Record[0];
74010b57cec5SDimitry Andric       uint64_t RawFlags = Record[1];
74020b57cec5SDimitry Andric       unsigned RefArrayStart = 2;
74030b57cec5SDimitry Andric       GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false,
74045ffd83dbSDimitry Andric                                       /* WriteOnly */ false,
74055ffd83dbSDimitry Andric                                       /* Constant */ false,
74065ffd83dbSDimitry Andric                                       GlobalObject::VCallVisibilityPublic);
74070b57cec5SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
74080b57cec5SDimitry Andric       if (Version >= 5) {
74090b57cec5SDimitry Andric         GVF = getDecodedGVarFlags(Record[2]);
74100b57cec5SDimitry Andric         RefArrayStart = 3;
74110b57cec5SDimitry Andric       }
74120b57cec5SDimitry Andric       std::vector<ValueInfo> Refs =
74130b57cec5SDimitry Andric           makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
74140b57cec5SDimitry Andric       auto FS =
74158bcb0991SDimitry Andric           std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
74160b57cec5SDimitry Andric       FS->setModulePath(getThisModule()->first());
74170b57cec5SDimitry Andric       auto GUID = getValueInfoFromValueId(ValueID);
7418bdd1243dSDimitry Andric       FS->setOriginalName(std::get<1>(GUID));
7419bdd1243dSDimitry Andric       TheIndex.addGlobalValueSummary(std::get<0>(GUID), std::move(FS));
74200b57cec5SDimitry Andric       break;
74210b57cec5SDimitry Andric     }
74220b57cec5SDimitry Andric     // FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags,
74230b57cec5SDimitry Andric     //                        numrefs, numrefs x valueid,
74240b57cec5SDimitry Andric     //                        n x (valueid, offset)]
74250b57cec5SDimitry Andric     case bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: {
74260b57cec5SDimitry Andric       unsigned ValueID = Record[0];
74270b57cec5SDimitry Andric       uint64_t RawFlags = Record[1];
74280b57cec5SDimitry Andric       GlobalVarSummary::GVarFlags GVF = getDecodedGVarFlags(Record[2]);
74290b57cec5SDimitry Andric       unsigned NumRefs = Record[3];
74300b57cec5SDimitry Andric       unsigned RefListStartIndex = 4;
74310b57cec5SDimitry Andric       unsigned VTableListStartIndex = RefListStartIndex + NumRefs;
74320b57cec5SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
74330b57cec5SDimitry Andric       std::vector<ValueInfo> Refs = makeRefList(
74340b57cec5SDimitry Andric           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
74350b57cec5SDimitry Andric       VTableFuncList VTableFuncs;
74360b57cec5SDimitry Andric       for (unsigned I = VTableListStartIndex, E = Record.size(); I != E; ++I) {
7437bdd1243dSDimitry Andric         ValueInfo Callee = std::get<0>(getValueInfoFromValueId(Record[I]));
74380b57cec5SDimitry Andric         uint64_t Offset = Record[++I];
74390b57cec5SDimitry Andric         VTableFuncs.push_back({Callee, Offset});
74400b57cec5SDimitry Andric       }
74410b57cec5SDimitry Andric       auto VS =
74428bcb0991SDimitry Andric           std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
74430b57cec5SDimitry Andric       VS->setModulePath(getThisModule()->first());
74440b57cec5SDimitry Andric       VS->setVTableFuncs(VTableFuncs);
74450b57cec5SDimitry Andric       auto GUID = getValueInfoFromValueId(ValueID);
7446bdd1243dSDimitry Andric       VS->setOriginalName(std::get<1>(GUID));
7447bdd1243dSDimitry Andric       TheIndex.addGlobalValueSummary(std::get<0>(GUID), std::move(VS));
74480b57cec5SDimitry Andric       break;
74490b57cec5SDimitry Andric     }
7450c9157d92SDimitry Andric     // FS_COMBINED is legacy and does not have support for the tail call flag.
74510b57cec5SDimitry Andric     // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs,
74520b57cec5SDimitry Andric     //               numrefs x valueid, n x (valueid)]
74530b57cec5SDimitry Andric     // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs,
7454c9157d92SDimitry Andric     //                       numrefs x valueid,
7455c9157d92SDimitry Andric     //                       n x (valueid, hotness+tailcall flags)]
74560b57cec5SDimitry Andric     case bitc::FS_COMBINED:
74570b57cec5SDimitry Andric     case bitc::FS_COMBINED_PROFILE: {
74580b57cec5SDimitry Andric       unsigned ValueID = Record[0];
74590b57cec5SDimitry Andric       uint64_t ModuleId = Record[1];
74600b57cec5SDimitry Andric       uint64_t RawFlags = Record[2];
74610b57cec5SDimitry Andric       unsigned InstCount = Record[3];
74620b57cec5SDimitry Andric       uint64_t RawFunFlags = 0;
74630b57cec5SDimitry Andric       uint64_t EntryCount = 0;
74640b57cec5SDimitry Andric       unsigned NumRefs = Record[4];
74650b57cec5SDimitry Andric       unsigned NumRORefs = 0, NumWORefs = 0;
74660b57cec5SDimitry Andric       int RefListStartIndex = 5;
74670b57cec5SDimitry Andric 
74680b57cec5SDimitry Andric       if (Version >= 4) {
74690b57cec5SDimitry Andric         RawFunFlags = Record[4];
74700b57cec5SDimitry Andric         RefListStartIndex = 6;
74710b57cec5SDimitry Andric         size_t NumRefsIndex = 5;
74720b57cec5SDimitry Andric         if (Version >= 5) {
74730b57cec5SDimitry Andric           unsigned NumRORefsOffset = 1;
74740b57cec5SDimitry Andric           RefListStartIndex = 7;
74750b57cec5SDimitry Andric           if (Version >= 6) {
74760b57cec5SDimitry Andric             NumRefsIndex = 6;
74770b57cec5SDimitry Andric             EntryCount = Record[5];
74780b57cec5SDimitry Andric             RefListStartIndex = 8;
74790b57cec5SDimitry Andric             if (Version >= 7) {
74800b57cec5SDimitry Andric               RefListStartIndex = 9;
74810b57cec5SDimitry Andric               NumWORefs = Record[8];
74820b57cec5SDimitry Andric               NumRORefsOffset = 2;
74830b57cec5SDimitry Andric             }
74840b57cec5SDimitry Andric           }
74850b57cec5SDimitry Andric           NumRORefs = Record[RefListStartIndex - NumRORefsOffset];
74860b57cec5SDimitry Andric         }
74870b57cec5SDimitry Andric         NumRefs = Record[NumRefsIndex];
74880b57cec5SDimitry Andric       }
74890b57cec5SDimitry Andric 
74900b57cec5SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
74910b57cec5SDimitry Andric       int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
74920b57cec5SDimitry Andric       assert(Record.size() >= RefListStartIndex + NumRefs &&
74930b57cec5SDimitry Andric              "Record size inconsistent with number of references");
74940b57cec5SDimitry Andric       std::vector<ValueInfo> Refs = makeRefList(
74950b57cec5SDimitry Andric           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
74960b57cec5SDimitry Andric       bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
74970b57cec5SDimitry Andric       std::vector<FunctionSummary::EdgeTy> Edges = makeCallList(
74980b57cec5SDimitry Andric           ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
74990b57cec5SDimitry Andric           IsOldProfileFormat, HasProfile, false);
7500bdd1243dSDimitry Andric       ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
75010b57cec5SDimitry Andric       setSpecialRefs(Refs, NumRORefs, NumWORefs);
75028bcb0991SDimitry Andric       auto FS = std::make_unique<FunctionSummary>(
75030b57cec5SDimitry Andric           Flags, InstCount, getDecodedFFlags(RawFunFlags), EntryCount,
75040b57cec5SDimitry Andric           std::move(Refs), std::move(Edges), std::move(PendingTypeTests),
75050b57cec5SDimitry Andric           std::move(PendingTypeTestAssumeVCalls),
75060b57cec5SDimitry Andric           std::move(PendingTypeCheckedLoadVCalls),
75070b57cec5SDimitry Andric           std::move(PendingTypeTestAssumeConstVCalls),
75085ffd83dbSDimitry Andric           std::move(PendingTypeCheckedLoadConstVCalls),
7509bdd1243dSDimitry Andric           std::move(PendingParamAccesses), std::move(PendingCallsites),
7510bdd1243dSDimitry Andric           std::move(PendingAllocs));
75110b57cec5SDimitry Andric       LastSeenSummary = FS.get();
75120b57cec5SDimitry Andric       LastSeenGUID = VI.getGUID();
75130b57cec5SDimitry Andric       FS->setModulePath(ModuleIdMap[ModuleId]);
75140b57cec5SDimitry Andric       TheIndex.addGlobalValueSummary(VI, std::move(FS));
75150b57cec5SDimitry Andric       break;
75160b57cec5SDimitry Andric     }
75170b57cec5SDimitry Andric     // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
75180b57cec5SDimitry Andric     // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
75190b57cec5SDimitry Andric     // they expect all aliasee summaries to be available.
75200b57cec5SDimitry Andric     case bitc::FS_COMBINED_ALIAS: {
75210b57cec5SDimitry Andric       unsigned ValueID = Record[0];
75220b57cec5SDimitry Andric       uint64_t ModuleId = Record[1];
75230b57cec5SDimitry Andric       uint64_t RawFlags = Record[2];
75240b57cec5SDimitry Andric       unsigned AliaseeValueId = Record[3];
75250b57cec5SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
75268bcb0991SDimitry Andric       auto AS = std::make_unique<AliasSummary>(Flags);
75270b57cec5SDimitry Andric       LastSeenSummary = AS.get();
75280b57cec5SDimitry Andric       AS->setModulePath(ModuleIdMap[ModuleId]);
75290b57cec5SDimitry Andric 
7530bdd1243dSDimitry Andric       auto AliaseeVI = std::get<0>(getValueInfoFromValueId(AliaseeValueId));
75310b57cec5SDimitry Andric       auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, AS->modulePath());
75320b57cec5SDimitry Andric       AS->setAliasee(AliaseeVI, AliaseeInModule);
75330b57cec5SDimitry Andric 
7534bdd1243dSDimitry Andric       ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
75350b57cec5SDimitry Andric       LastSeenGUID = VI.getGUID();
75360b57cec5SDimitry Andric       TheIndex.addGlobalValueSummary(VI, std::move(AS));
75370b57cec5SDimitry Andric       break;
75380b57cec5SDimitry Andric     }
75390b57cec5SDimitry Andric     // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
75400b57cec5SDimitry Andric     case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
75410b57cec5SDimitry Andric       unsigned ValueID = Record[0];
75420b57cec5SDimitry Andric       uint64_t ModuleId = Record[1];
75430b57cec5SDimitry Andric       uint64_t RawFlags = Record[2];
75440b57cec5SDimitry Andric       unsigned RefArrayStart = 3;
75450b57cec5SDimitry Andric       GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false,
75465ffd83dbSDimitry Andric                                       /* WriteOnly */ false,
75475ffd83dbSDimitry Andric                                       /* Constant */ false,
75485ffd83dbSDimitry Andric                                       GlobalObject::VCallVisibilityPublic);
75490b57cec5SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
75500b57cec5SDimitry Andric       if (Version >= 5) {
75510b57cec5SDimitry Andric         GVF = getDecodedGVarFlags(Record[3]);
75520b57cec5SDimitry Andric         RefArrayStart = 4;
75530b57cec5SDimitry Andric       }
75540b57cec5SDimitry Andric       std::vector<ValueInfo> Refs =
75550b57cec5SDimitry Andric           makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
75560b57cec5SDimitry Andric       auto FS =
75578bcb0991SDimitry Andric           std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
75580b57cec5SDimitry Andric       LastSeenSummary = FS.get();
75590b57cec5SDimitry Andric       FS->setModulePath(ModuleIdMap[ModuleId]);
7560bdd1243dSDimitry Andric       ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
75610b57cec5SDimitry Andric       LastSeenGUID = VI.getGUID();
75620b57cec5SDimitry Andric       TheIndex.addGlobalValueSummary(VI, std::move(FS));
75630b57cec5SDimitry Andric       break;
75640b57cec5SDimitry Andric     }
75650b57cec5SDimitry Andric     // FS_COMBINED_ORIGINAL_NAME: [original_name]
75660b57cec5SDimitry Andric     case bitc::FS_COMBINED_ORIGINAL_NAME: {
75670b57cec5SDimitry Andric       uint64_t OriginalName = Record[0];
75680b57cec5SDimitry Andric       if (!LastSeenSummary)
75690b57cec5SDimitry Andric         return error("Name attachment that does not follow a combined record");
75700b57cec5SDimitry Andric       LastSeenSummary->setOriginalName(OriginalName);
75710b57cec5SDimitry Andric       TheIndex.addOriginalName(LastSeenGUID, OriginalName);
75720b57cec5SDimitry Andric       // Reset the LastSeenSummary
75730b57cec5SDimitry Andric       LastSeenSummary = nullptr;
75740b57cec5SDimitry Andric       LastSeenGUID = 0;
75750b57cec5SDimitry Andric       break;
75760b57cec5SDimitry Andric     }
75770b57cec5SDimitry Andric     case bitc::FS_TYPE_TESTS:
75780b57cec5SDimitry Andric       assert(PendingTypeTests.empty());
7579e8d8bef9SDimitry Andric       llvm::append_range(PendingTypeTests, Record);
75800b57cec5SDimitry Andric       break;
75810b57cec5SDimitry Andric 
75820b57cec5SDimitry Andric     case bitc::FS_TYPE_TEST_ASSUME_VCALLS:
75830b57cec5SDimitry Andric       assert(PendingTypeTestAssumeVCalls.empty());
75840b57cec5SDimitry Andric       for (unsigned I = 0; I != Record.size(); I += 2)
75850b57cec5SDimitry Andric         PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
75860b57cec5SDimitry Andric       break;
75870b57cec5SDimitry Andric 
75880b57cec5SDimitry Andric     case bitc::FS_TYPE_CHECKED_LOAD_VCALLS:
75890b57cec5SDimitry Andric       assert(PendingTypeCheckedLoadVCalls.empty());
75900b57cec5SDimitry Andric       for (unsigned I = 0; I != Record.size(); I += 2)
75910b57cec5SDimitry Andric         PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
75920b57cec5SDimitry Andric       break;
75930b57cec5SDimitry Andric 
75940b57cec5SDimitry Andric     case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL:
75950b57cec5SDimitry Andric       PendingTypeTestAssumeConstVCalls.push_back(
75960b57cec5SDimitry Andric           {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
75970b57cec5SDimitry Andric       break;
75980b57cec5SDimitry Andric 
75990b57cec5SDimitry Andric     case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL:
76000b57cec5SDimitry Andric       PendingTypeCheckedLoadConstVCalls.push_back(
76010b57cec5SDimitry Andric           {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
76020b57cec5SDimitry Andric       break;
76030b57cec5SDimitry Andric 
76040b57cec5SDimitry Andric     case bitc::FS_CFI_FUNCTION_DEFS: {
76050b57cec5SDimitry Andric       std::set<std::string> &CfiFunctionDefs = TheIndex.cfiFunctionDefs();
76060b57cec5SDimitry Andric       for (unsigned I = 0; I != Record.size(); I += 2)
76070b57cec5SDimitry Andric         CfiFunctionDefs.insert(
76080b57cec5SDimitry Andric             {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
76090b57cec5SDimitry Andric       break;
76100b57cec5SDimitry Andric     }
76110b57cec5SDimitry Andric 
76120b57cec5SDimitry Andric     case bitc::FS_CFI_FUNCTION_DECLS: {
76130b57cec5SDimitry Andric       std::set<std::string> &CfiFunctionDecls = TheIndex.cfiFunctionDecls();
76140b57cec5SDimitry Andric       for (unsigned I = 0; I != Record.size(); I += 2)
76150b57cec5SDimitry Andric         CfiFunctionDecls.insert(
76160b57cec5SDimitry Andric             {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
76170b57cec5SDimitry Andric       break;
76180b57cec5SDimitry Andric     }
76190b57cec5SDimitry Andric 
76200b57cec5SDimitry Andric     case bitc::FS_TYPE_ID:
76210b57cec5SDimitry Andric       parseTypeIdSummaryRecord(Record, Strtab, TheIndex);
76220b57cec5SDimitry Andric       break;
76230b57cec5SDimitry Andric 
76240b57cec5SDimitry Andric     case bitc::FS_TYPE_ID_METADATA:
76250b57cec5SDimitry Andric       parseTypeIdCompatibleVtableSummaryRecord(Record);
76260b57cec5SDimitry Andric       break;
76275ffd83dbSDimitry Andric 
76285ffd83dbSDimitry Andric     case bitc::FS_BLOCK_COUNT:
76295ffd83dbSDimitry Andric       TheIndex.addBlockCount(Record[0]);
76305ffd83dbSDimitry Andric       break;
76315ffd83dbSDimitry Andric 
76325ffd83dbSDimitry Andric     case bitc::FS_PARAM_ACCESS: {
76335ffd83dbSDimitry Andric       PendingParamAccesses = parseParamAccesses(Record);
76345ffd83dbSDimitry Andric       break;
76355ffd83dbSDimitry Andric     }
7636bdd1243dSDimitry Andric 
7637bdd1243dSDimitry Andric     case bitc::FS_STACK_IDS: { // [n x stackid]
7638bdd1243dSDimitry Andric       // Save stack ids in the reader to consult when adding stack ids from the
7639bdd1243dSDimitry Andric       // lists in the stack node and alloc node entries.
7640bdd1243dSDimitry Andric       StackIds = ArrayRef<uint64_t>(Record);
7641bdd1243dSDimitry Andric       break;
7642bdd1243dSDimitry Andric     }
7643bdd1243dSDimitry Andric 
7644bdd1243dSDimitry Andric     case bitc::FS_PERMODULE_CALLSITE_INFO: {
7645bdd1243dSDimitry Andric       unsigned ValueID = Record[0];
7646bdd1243dSDimitry Andric       SmallVector<unsigned> StackIdList;
7647bdd1243dSDimitry Andric       for (auto R = Record.begin() + 1; R != Record.end(); R++) {
7648bdd1243dSDimitry Andric         assert(*R < StackIds.size());
7649bdd1243dSDimitry Andric         StackIdList.push_back(TheIndex.addOrGetStackIdIndex(StackIds[*R]));
7650bdd1243dSDimitry Andric       }
7651bdd1243dSDimitry Andric       ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
7652bdd1243dSDimitry Andric       PendingCallsites.push_back(CallsiteInfo({VI, std::move(StackIdList)}));
7653bdd1243dSDimitry Andric       break;
7654bdd1243dSDimitry Andric     }
7655bdd1243dSDimitry Andric 
7656bdd1243dSDimitry Andric     case bitc::FS_COMBINED_CALLSITE_INFO: {
7657bdd1243dSDimitry Andric       auto RecordIter = Record.begin();
7658bdd1243dSDimitry Andric       unsigned ValueID = *RecordIter++;
7659bdd1243dSDimitry Andric       unsigned NumStackIds = *RecordIter++;
7660bdd1243dSDimitry Andric       unsigned NumVersions = *RecordIter++;
7661bdd1243dSDimitry Andric       assert(Record.size() == 3 + NumStackIds + NumVersions);
7662bdd1243dSDimitry Andric       SmallVector<unsigned> StackIdList;
7663bdd1243dSDimitry Andric       for (unsigned J = 0; J < NumStackIds; J++) {
7664bdd1243dSDimitry Andric         assert(*RecordIter < StackIds.size());
7665bdd1243dSDimitry Andric         StackIdList.push_back(
7666bdd1243dSDimitry Andric             TheIndex.addOrGetStackIdIndex(StackIds[*RecordIter++]));
7667bdd1243dSDimitry Andric       }
7668bdd1243dSDimitry Andric       SmallVector<unsigned> Versions;
7669bdd1243dSDimitry Andric       for (unsigned J = 0; J < NumVersions; J++)
7670bdd1243dSDimitry Andric         Versions.push_back(*RecordIter++);
7671bdd1243dSDimitry Andric       ValueInfo VI = std::get<0>(
7672bdd1243dSDimitry Andric           getValueInfoFromValueId</*AllowNullValueInfo*/ true>(ValueID));
7673bdd1243dSDimitry Andric       PendingCallsites.push_back(
7674bdd1243dSDimitry Andric           CallsiteInfo({VI, std::move(Versions), std::move(StackIdList)}));
7675bdd1243dSDimitry Andric       break;
7676bdd1243dSDimitry Andric     }
7677bdd1243dSDimitry Andric 
7678bdd1243dSDimitry Andric     case bitc::FS_PERMODULE_ALLOC_INFO: {
7679bdd1243dSDimitry Andric       unsigned I = 0;
7680bdd1243dSDimitry Andric       std::vector<MIBInfo> MIBs;
7681bdd1243dSDimitry Andric       while (I < Record.size()) {
7682bdd1243dSDimitry Andric         assert(Record.size() - I >= 2);
7683bdd1243dSDimitry Andric         AllocationType AllocType = (AllocationType)Record[I++];
7684bdd1243dSDimitry Andric         unsigned NumStackEntries = Record[I++];
7685bdd1243dSDimitry Andric         assert(Record.size() - I >= NumStackEntries);
7686bdd1243dSDimitry Andric         SmallVector<unsigned> StackIdList;
7687bdd1243dSDimitry Andric         for (unsigned J = 0; J < NumStackEntries; J++) {
7688bdd1243dSDimitry Andric           assert(Record[I] < StackIds.size());
7689bdd1243dSDimitry Andric           StackIdList.push_back(
7690bdd1243dSDimitry Andric               TheIndex.addOrGetStackIdIndex(StackIds[Record[I++]]));
7691bdd1243dSDimitry Andric         }
7692bdd1243dSDimitry Andric         MIBs.push_back(MIBInfo(AllocType, std::move(StackIdList)));
7693bdd1243dSDimitry Andric       }
7694bdd1243dSDimitry Andric       PendingAllocs.push_back(AllocInfo(std::move(MIBs)));
7695bdd1243dSDimitry Andric       break;
7696bdd1243dSDimitry Andric     }
7697bdd1243dSDimitry Andric 
7698bdd1243dSDimitry Andric     case bitc::FS_COMBINED_ALLOC_INFO: {
7699bdd1243dSDimitry Andric       unsigned I = 0;
7700bdd1243dSDimitry Andric       std::vector<MIBInfo> MIBs;
7701bdd1243dSDimitry Andric       unsigned NumMIBs = Record[I++];
7702bdd1243dSDimitry Andric       unsigned NumVersions = Record[I++];
7703bdd1243dSDimitry Andric       unsigned MIBsRead = 0;
7704bdd1243dSDimitry Andric       while (MIBsRead++ < NumMIBs) {
7705bdd1243dSDimitry Andric         assert(Record.size() - I >= 2);
7706bdd1243dSDimitry Andric         AllocationType AllocType = (AllocationType)Record[I++];
7707bdd1243dSDimitry Andric         unsigned NumStackEntries = Record[I++];
7708bdd1243dSDimitry Andric         assert(Record.size() - I >= NumStackEntries);
7709bdd1243dSDimitry Andric         SmallVector<unsigned> StackIdList;
7710bdd1243dSDimitry Andric         for (unsigned J = 0; J < NumStackEntries; J++) {
7711bdd1243dSDimitry Andric           assert(Record[I] < StackIds.size());
7712bdd1243dSDimitry Andric           StackIdList.push_back(
7713bdd1243dSDimitry Andric               TheIndex.addOrGetStackIdIndex(StackIds[Record[I++]]));
7714bdd1243dSDimitry Andric         }
7715bdd1243dSDimitry Andric         MIBs.push_back(MIBInfo(AllocType, std::move(StackIdList)));
7716bdd1243dSDimitry Andric       }
7717bdd1243dSDimitry Andric       assert(Record.size() - I >= NumVersions);
7718bdd1243dSDimitry Andric       SmallVector<uint8_t> Versions;
7719bdd1243dSDimitry Andric       for (unsigned J = 0; J < NumVersions; J++)
7720bdd1243dSDimitry Andric         Versions.push_back(Record[I++]);
7721bdd1243dSDimitry Andric       PendingAllocs.push_back(
7722bdd1243dSDimitry Andric           AllocInfo(std::move(Versions), std::move(MIBs)));
7723bdd1243dSDimitry Andric       break;
7724bdd1243dSDimitry Andric     }
77250b57cec5SDimitry Andric     }
77260b57cec5SDimitry Andric   }
77270b57cec5SDimitry Andric   llvm_unreachable("Exit infinite loop");
77280b57cec5SDimitry Andric }
77290b57cec5SDimitry Andric 
77300b57cec5SDimitry Andric // Parse the  module string table block into the Index.
77310b57cec5SDimitry Andric // This populates the ModulePathStringTable map in the index.
parseModuleStringTable()77320b57cec5SDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
77330b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
77340b57cec5SDimitry Andric     return Err;
77350b57cec5SDimitry Andric 
77360b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
77370b57cec5SDimitry Andric 
77380b57cec5SDimitry Andric   SmallString<128> ModulePath;
77390b57cec5SDimitry Andric   ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr;
77400b57cec5SDimitry Andric 
77410b57cec5SDimitry Andric   while (true) {
77420b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
77430b57cec5SDimitry Andric     if (!MaybeEntry)
77440b57cec5SDimitry Andric       return MaybeEntry.takeError();
77450b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
77460b57cec5SDimitry Andric 
77470b57cec5SDimitry Andric     switch (Entry.Kind) {
77480b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
77490b57cec5SDimitry Andric     case BitstreamEntry::Error:
77500b57cec5SDimitry Andric       return error("Malformed block");
77510b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
77520b57cec5SDimitry Andric       return Error::success();
77530b57cec5SDimitry Andric     case BitstreamEntry::Record:
77540b57cec5SDimitry Andric       // The interesting case.
77550b57cec5SDimitry Andric       break;
77560b57cec5SDimitry Andric     }
77570b57cec5SDimitry Andric 
77580b57cec5SDimitry Andric     Record.clear();
77590b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
77600b57cec5SDimitry Andric     if (!MaybeRecord)
77610b57cec5SDimitry Andric       return MaybeRecord.takeError();
77620b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
77630b57cec5SDimitry Andric     default: // Default behavior: ignore.
77640b57cec5SDimitry Andric       break;
77650b57cec5SDimitry Andric     case bitc::MST_CODE_ENTRY: {
77660b57cec5SDimitry Andric       // MST_ENTRY: [modid, namechar x N]
77670b57cec5SDimitry Andric       uint64_t ModuleId = Record[0];
77680b57cec5SDimitry Andric 
77690b57cec5SDimitry Andric       if (convertToString(Record, 1, ModulePath))
77700b57cec5SDimitry Andric         return error("Invalid record");
77710b57cec5SDimitry Andric 
7772c9157d92SDimitry Andric       LastSeenModule = TheIndex.addModule(ModulePath);
77730b57cec5SDimitry Andric       ModuleIdMap[ModuleId] = LastSeenModule->first();
77740b57cec5SDimitry Andric 
77750b57cec5SDimitry Andric       ModulePath.clear();
77760b57cec5SDimitry Andric       break;
77770b57cec5SDimitry Andric     }
77780b57cec5SDimitry Andric     /// MST_CODE_HASH: [5*i32]
77790b57cec5SDimitry Andric     case bitc::MST_CODE_HASH: {
77800b57cec5SDimitry Andric       if (Record.size() != 5)
77810b57cec5SDimitry Andric         return error("Invalid hash length " + Twine(Record.size()).str());
77820b57cec5SDimitry Andric       if (!LastSeenModule)
77830b57cec5SDimitry Andric         return error("Invalid hash that does not follow a module path");
77840b57cec5SDimitry Andric       int Pos = 0;
77850b57cec5SDimitry Andric       for (auto &Val : Record) {
77860b57cec5SDimitry Andric         assert(!(Val >> 32) && "Unexpected high bits set");
7787c9157d92SDimitry Andric         LastSeenModule->second[Pos++] = Val;
77880b57cec5SDimitry Andric       }
77890b57cec5SDimitry Andric       // Reset LastSeenModule to avoid overriding the hash unexpectedly.
77900b57cec5SDimitry Andric       LastSeenModule = nullptr;
77910b57cec5SDimitry Andric       break;
77920b57cec5SDimitry Andric     }
77930b57cec5SDimitry Andric     }
77940b57cec5SDimitry Andric   }
77950b57cec5SDimitry Andric   llvm_unreachable("Exit infinite loop");
77960b57cec5SDimitry Andric }
77970b57cec5SDimitry Andric 
77980b57cec5SDimitry Andric namespace {
77990b57cec5SDimitry Andric 
78000b57cec5SDimitry Andric // FIXME: This class is only here to support the transition to llvm::Error. It
78010b57cec5SDimitry Andric // will be removed once this transition is complete. Clients should prefer to
78020b57cec5SDimitry Andric // deal with the Error value directly, rather than converting to error_code.
78030b57cec5SDimitry Andric class BitcodeErrorCategoryType : public std::error_category {
name() const78040b57cec5SDimitry Andric   const char *name() const noexcept override {
78050b57cec5SDimitry Andric     return "llvm.bitcode";
78060b57cec5SDimitry Andric   }
78070b57cec5SDimitry Andric 
message(int IE) const78080b57cec5SDimitry Andric   std::string message(int IE) const override {
78090b57cec5SDimitry Andric     BitcodeError E = static_cast<BitcodeError>(IE);
78100b57cec5SDimitry Andric     switch (E) {
78110b57cec5SDimitry Andric     case BitcodeError::CorruptedBitcode:
78120b57cec5SDimitry Andric       return "Corrupted bitcode";
78130b57cec5SDimitry Andric     }
78140b57cec5SDimitry Andric     llvm_unreachable("Unknown error type!");
78150b57cec5SDimitry Andric   }
78160b57cec5SDimitry Andric };
78170b57cec5SDimitry Andric 
78180b57cec5SDimitry Andric } // end anonymous namespace
78190b57cec5SDimitry Andric 
BitcodeErrorCategory()78200b57cec5SDimitry Andric const std::error_category &llvm::BitcodeErrorCategory() {
7821753f127fSDimitry Andric   static BitcodeErrorCategoryType ErrorCategory;
7822753f127fSDimitry Andric   return ErrorCategory;
78230b57cec5SDimitry Andric }
78240b57cec5SDimitry Andric 
readBlobInRecord(BitstreamCursor & Stream,unsigned Block,unsigned RecordID)78250b57cec5SDimitry Andric static Expected<StringRef> readBlobInRecord(BitstreamCursor &Stream,
78260b57cec5SDimitry Andric                                             unsigned Block, unsigned RecordID) {
78270b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(Block))
78280b57cec5SDimitry Andric     return std::move(Err);
78290b57cec5SDimitry Andric 
78300b57cec5SDimitry Andric   StringRef Strtab;
78310b57cec5SDimitry Andric   while (true) {
78320b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
78330b57cec5SDimitry Andric     if (!MaybeEntry)
78340b57cec5SDimitry Andric       return MaybeEntry.takeError();
78350b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
78360b57cec5SDimitry Andric 
78370b57cec5SDimitry Andric     switch (Entry.Kind) {
78380b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
78390b57cec5SDimitry Andric       return Strtab;
78400b57cec5SDimitry Andric 
78410b57cec5SDimitry Andric     case BitstreamEntry::Error:
78420b57cec5SDimitry Andric       return error("Malformed block");
78430b57cec5SDimitry Andric 
78440b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
78450b57cec5SDimitry Andric       if (Error Err = Stream.SkipBlock())
78460b57cec5SDimitry Andric         return std::move(Err);
78470b57cec5SDimitry Andric       break;
78480b57cec5SDimitry Andric 
78490b57cec5SDimitry Andric     case BitstreamEntry::Record:
78500b57cec5SDimitry Andric       StringRef Blob;
78510b57cec5SDimitry Andric       SmallVector<uint64_t, 1> Record;
78520b57cec5SDimitry Andric       Expected<unsigned> MaybeRecord =
78530b57cec5SDimitry Andric           Stream.readRecord(Entry.ID, Record, &Blob);
78540b57cec5SDimitry Andric       if (!MaybeRecord)
78550b57cec5SDimitry Andric         return MaybeRecord.takeError();
78560b57cec5SDimitry Andric       if (MaybeRecord.get() == RecordID)
78570b57cec5SDimitry Andric         Strtab = Blob;
78580b57cec5SDimitry Andric       break;
78590b57cec5SDimitry Andric     }
78600b57cec5SDimitry Andric   }
78610b57cec5SDimitry Andric }
78620b57cec5SDimitry Andric 
78630b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
78640b57cec5SDimitry Andric // External interface
78650b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
78660b57cec5SDimitry Andric 
78670b57cec5SDimitry Andric Expected<std::vector<BitcodeModule>>
getBitcodeModuleList(MemoryBufferRef Buffer)78680b57cec5SDimitry Andric llvm::getBitcodeModuleList(MemoryBufferRef Buffer) {
78690b57cec5SDimitry Andric   auto FOrErr = getBitcodeFileContents(Buffer);
78700b57cec5SDimitry Andric   if (!FOrErr)
78710b57cec5SDimitry Andric     return FOrErr.takeError();
78720b57cec5SDimitry Andric   return std::move(FOrErr->Mods);
78730b57cec5SDimitry Andric }
78740b57cec5SDimitry Andric 
78750b57cec5SDimitry Andric Expected<BitcodeFileContents>
getBitcodeFileContents(MemoryBufferRef Buffer)78760b57cec5SDimitry Andric llvm::getBitcodeFileContents(MemoryBufferRef Buffer) {
78770b57cec5SDimitry Andric   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
78780b57cec5SDimitry Andric   if (!StreamOrErr)
78790b57cec5SDimitry Andric     return StreamOrErr.takeError();
78800b57cec5SDimitry Andric   BitstreamCursor &Stream = *StreamOrErr;
78810b57cec5SDimitry Andric 
78820b57cec5SDimitry Andric   BitcodeFileContents F;
78830b57cec5SDimitry Andric   while (true) {
78840b57cec5SDimitry Andric     uint64_t BCBegin = Stream.getCurrentByteNo();
78850b57cec5SDimitry Andric 
78860b57cec5SDimitry Andric     // We may be consuming bitcode from a client that leaves garbage at the end
78870b57cec5SDimitry Andric     // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to
78880b57cec5SDimitry Andric     // the end that there cannot possibly be another module, stop looking.
78890b57cec5SDimitry Andric     if (BCBegin + 8 >= Stream.getBitcodeBytes().size())
78900b57cec5SDimitry Andric       return F;
78910b57cec5SDimitry Andric 
78920b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
78930b57cec5SDimitry Andric     if (!MaybeEntry)
78940b57cec5SDimitry Andric       return MaybeEntry.takeError();
78950b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
78960b57cec5SDimitry Andric 
78970b57cec5SDimitry Andric     switch (Entry.Kind) {
78980b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
78990b57cec5SDimitry Andric     case BitstreamEntry::Error:
79000b57cec5SDimitry Andric       return error("Malformed block");
79010b57cec5SDimitry Andric 
79020b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: {
79030b57cec5SDimitry Andric       uint64_t IdentificationBit = -1ull;
79040b57cec5SDimitry Andric       if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
79050b57cec5SDimitry Andric         IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8;
79060b57cec5SDimitry Andric         if (Error Err = Stream.SkipBlock())
79070b57cec5SDimitry Andric           return std::move(Err);
79080b57cec5SDimitry Andric 
79090b57cec5SDimitry Andric         {
79100b57cec5SDimitry Andric           Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
79110b57cec5SDimitry Andric           if (!MaybeEntry)
79120b57cec5SDimitry Andric             return MaybeEntry.takeError();
79130b57cec5SDimitry Andric           Entry = MaybeEntry.get();
79140b57cec5SDimitry Andric         }
79150b57cec5SDimitry Andric 
79160b57cec5SDimitry Andric         if (Entry.Kind != BitstreamEntry::SubBlock ||
79170b57cec5SDimitry Andric             Entry.ID != bitc::MODULE_BLOCK_ID)
79180b57cec5SDimitry Andric           return error("Malformed block");
79190b57cec5SDimitry Andric       }
79200b57cec5SDimitry Andric 
79210b57cec5SDimitry Andric       if (Entry.ID == bitc::MODULE_BLOCK_ID) {
79220b57cec5SDimitry Andric         uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8;
79230b57cec5SDimitry Andric         if (Error Err = Stream.SkipBlock())
79240b57cec5SDimitry Andric           return std::move(Err);
79250b57cec5SDimitry Andric 
79260b57cec5SDimitry Andric         F.Mods.push_back({Stream.getBitcodeBytes().slice(
79270b57cec5SDimitry Andric                               BCBegin, Stream.getCurrentByteNo() - BCBegin),
79280b57cec5SDimitry Andric                           Buffer.getBufferIdentifier(), IdentificationBit,
79290b57cec5SDimitry Andric                           ModuleBit});
79300b57cec5SDimitry Andric         continue;
79310b57cec5SDimitry Andric       }
79320b57cec5SDimitry Andric 
79330b57cec5SDimitry Andric       if (Entry.ID == bitc::STRTAB_BLOCK_ID) {
79340b57cec5SDimitry Andric         Expected<StringRef> Strtab =
79350b57cec5SDimitry Andric             readBlobInRecord(Stream, bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB);
79360b57cec5SDimitry Andric         if (!Strtab)
79370b57cec5SDimitry Andric           return Strtab.takeError();
79380b57cec5SDimitry Andric         // This string table is used by every preceding bitcode module that does
79390b57cec5SDimitry Andric         // not have its own string table. A bitcode file may have multiple
79400b57cec5SDimitry Andric         // string tables if it was created by binary concatenation, for example
79410b57cec5SDimitry Andric         // with "llvm-cat -b".
79420eae32dcSDimitry Andric         for (BitcodeModule &I : llvm::reverse(F.Mods)) {
79430eae32dcSDimitry Andric           if (!I.Strtab.empty())
79440b57cec5SDimitry Andric             break;
79450eae32dcSDimitry Andric           I.Strtab = *Strtab;
79460b57cec5SDimitry Andric         }
79470b57cec5SDimitry Andric         // Similarly, the string table is used by every preceding symbol table;
79480b57cec5SDimitry Andric         // normally there will be just one unless the bitcode file was created
79490b57cec5SDimitry Andric         // by binary concatenation.
79500b57cec5SDimitry Andric         if (!F.Symtab.empty() && F.StrtabForSymtab.empty())
79510b57cec5SDimitry Andric           F.StrtabForSymtab = *Strtab;
79520b57cec5SDimitry Andric         continue;
79530b57cec5SDimitry Andric       }
79540b57cec5SDimitry Andric 
79550b57cec5SDimitry Andric       if (Entry.ID == bitc::SYMTAB_BLOCK_ID) {
79560b57cec5SDimitry Andric         Expected<StringRef> SymtabOrErr =
79570b57cec5SDimitry Andric             readBlobInRecord(Stream, bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB);
79580b57cec5SDimitry Andric         if (!SymtabOrErr)
79590b57cec5SDimitry Andric           return SymtabOrErr.takeError();
79600b57cec5SDimitry Andric 
79610b57cec5SDimitry Andric         // We can expect the bitcode file to have multiple symbol tables if it
79620b57cec5SDimitry Andric         // was created by binary concatenation. In that case we silently
79630b57cec5SDimitry Andric         // ignore any subsequent symbol tables, which is fine because this is a
79640b57cec5SDimitry Andric         // low level function. The client is expected to notice that the number
79650b57cec5SDimitry Andric         // of modules in the symbol table does not match the number of modules
79660b57cec5SDimitry Andric         // in the input file and regenerate the symbol table.
79670b57cec5SDimitry Andric         if (F.Symtab.empty())
79680b57cec5SDimitry Andric           F.Symtab = *SymtabOrErr;
79690b57cec5SDimitry Andric         continue;
79700b57cec5SDimitry Andric       }
79710b57cec5SDimitry Andric 
79720b57cec5SDimitry Andric       if (Error Err = Stream.SkipBlock())
79730b57cec5SDimitry Andric         return std::move(Err);
79740b57cec5SDimitry Andric       continue;
79750b57cec5SDimitry Andric     }
79760b57cec5SDimitry Andric     case BitstreamEntry::Record:
7977349cc55cSDimitry Andric       if (Error E = Stream.skipRecord(Entry.ID).takeError())
7978349cc55cSDimitry Andric         return std::move(E);
79790b57cec5SDimitry Andric       continue;
79800b57cec5SDimitry Andric     }
79810b57cec5SDimitry Andric   }
79820b57cec5SDimitry Andric }
79830b57cec5SDimitry Andric 
79840b57cec5SDimitry Andric /// Get a lazy one-at-time loading module from bitcode.
79850b57cec5SDimitry Andric ///
79860b57cec5SDimitry Andric /// This isn't always used in a lazy context.  In particular, it's also used by
79870b57cec5SDimitry Andric /// \a parseModule().  If this is truly lazy, then we need to eagerly pull
79880b57cec5SDimitry Andric /// in forward-referenced functions from block address references.
79890b57cec5SDimitry Andric ///
79900b57cec5SDimitry Andric /// \param[in] MaterializeAll Set to \c true if we should materialize
79910b57cec5SDimitry Andric /// everything.
79920b57cec5SDimitry Andric Expected<std::unique_ptr<Module>>
getModuleImpl(LLVMContext & Context,bool MaterializeAll,bool ShouldLazyLoadMetadata,bool IsImporting,ParserCallbacks Callbacks)79930b57cec5SDimitry Andric BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll,
79945ffd83dbSDimitry Andric                              bool ShouldLazyLoadMetadata, bool IsImporting,
7995bdd1243dSDimitry Andric                              ParserCallbacks Callbacks) {
79960b57cec5SDimitry Andric   BitstreamCursor Stream(Buffer);
79970b57cec5SDimitry Andric 
79980b57cec5SDimitry Andric   std::string ProducerIdentification;
79990b57cec5SDimitry Andric   if (IdentificationBit != -1ull) {
80000b57cec5SDimitry Andric     if (Error JumpFailed = Stream.JumpToBit(IdentificationBit))
80010b57cec5SDimitry Andric       return std::move(JumpFailed);
8002349cc55cSDimitry Andric     if (Error E =
8003349cc55cSDimitry Andric             readIdentificationBlock(Stream).moveInto(ProducerIdentification))
8004349cc55cSDimitry Andric       return std::move(E);
80050b57cec5SDimitry Andric   }
80060b57cec5SDimitry Andric 
80070b57cec5SDimitry Andric   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
80080b57cec5SDimitry Andric     return std::move(JumpFailed);
80090b57cec5SDimitry Andric   auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
80100b57cec5SDimitry Andric                               Context);
80110b57cec5SDimitry Andric 
80120b57cec5SDimitry Andric   std::unique_ptr<Module> M =
80138bcb0991SDimitry Andric       std::make_unique<Module>(ModuleIdentifier, Context);
80140b57cec5SDimitry Andric   M->setMaterializer(R);
80150b57cec5SDimitry Andric 
80160b57cec5SDimitry Andric   // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
80175ffd83dbSDimitry Andric   if (Error Err = R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata,
8018bdd1243dSDimitry Andric                                       IsImporting, Callbacks))
80190b57cec5SDimitry Andric     return std::move(Err);
80200b57cec5SDimitry Andric 
80210b57cec5SDimitry Andric   if (MaterializeAll) {
80220b57cec5SDimitry Andric     // Read in the entire module, and destroy the BitcodeReader.
80230b57cec5SDimitry Andric     if (Error Err = M->materializeAll())
80240b57cec5SDimitry Andric       return std::move(Err);
80250b57cec5SDimitry Andric   } else {
80260b57cec5SDimitry Andric     // Resolve forward references from blockaddresses.
80270b57cec5SDimitry Andric     if (Error Err = R->materializeForwardReferencedFunctions())
80280b57cec5SDimitry Andric       return std::move(Err);
80290b57cec5SDimitry Andric   }
80300b57cec5SDimitry Andric   return std::move(M);
80310b57cec5SDimitry Andric }
80320b57cec5SDimitry Andric 
80330b57cec5SDimitry Andric Expected<std::unique_ptr<Module>>
getLazyModule(LLVMContext & Context,bool ShouldLazyLoadMetadata,bool IsImporting,ParserCallbacks Callbacks)80340b57cec5SDimitry Andric BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata,
8035bdd1243dSDimitry Andric                              bool IsImporting, ParserCallbacks Callbacks) {
80365ffd83dbSDimitry Andric   return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting,
8037bdd1243dSDimitry Andric                        Callbacks);
80380b57cec5SDimitry Andric }
80390b57cec5SDimitry Andric 
80400b57cec5SDimitry Andric // Parse the specified bitcode buffer and merge the index into CombinedIndex.
80410b57cec5SDimitry Andric // We don't use ModuleIdentifier here because the client may need to control the
80420b57cec5SDimitry Andric // module path used in the combined summary (e.g. when reading summaries for
80430b57cec5SDimitry Andric // regular LTO modules).
readSummary(ModuleSummaryIndex & CombinedIndex,StringRef ModulePath,std::function<bool (GlobalValue::GUID)> IsPrevailing)8044bdd1243dSDimitry Andric Error BitcodeModule::readSummary(
8045c9157d92SDimitry Andric     ModuleSummaryIndex &CombinedIndex, StringRef ModulePath,
8046bdd1243dSDimitry Andric     std::function<bool(GlobalValue::GUID)> IsPrevailing) {
80470b57cec5SDimitry Andric   BitstreamCursor Stream(Buffer);
80480b57cec5SDimitry Andric   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
80490b57cec5SDimitry Andric     return JumpFailed;
80500b57cec5SDimitry Andric 
80510b57cec5SDimitry Andric   ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
8052c9157d92SDimitry Andric                                     ModulePath, IsPrevailing);
80530b57cec5SDimitry Andric   return R.parseModule();
80540b57cec5SDimitry Andric }
80550b57cec5SDimitry Andric 
80560b57cec5SDimitry Andric // Parse the specified bitcode buffer, returning the function info index.
getSummary()80570b57cec5SDimitry Andric Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() {
80580b57cec5SDimitry Andric   BitstreamCursor Stream(Buffer);
80590b57cec5SDimitry Andric   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
80600b57cec5SDimitry Andric     return std::move(JumpFailed);
80610b57cec5SDimitry Andric 
80628bcb0991SDimitry Andric   auto Index = std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
80630b57cec5SDimitry Andric   ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,
80640b57cec5SDimitry Andric                                     ModuleIdentifier, 0);
80650b57cec5SDimitry Andric 
80660b57cec5SDimitry Andric   if (Error Err = R.parseModule())
80670b57cec5SDimitry Andric     return std::move(Err);
80680b57cec5SDimitry Andric 
80690b57cec5SDimitry Andric   return std::move(Index);
80700b57cec5SDimitry Andric }
80710b57cec5SDimitry Andric 
8072fe013be4SDimitry Andric static Expected<std::pair<bool, bool>>
getEnableSplitLTOUnitAndUnifiedFlag(BitstreamCursor & Stream,unsigned ID,BitcodeLTOInfo & LTOInfo)8073fe013be4SDimitry Andric getEnableSplitLTOUnitAndUnifiedFlag(BitstreamCursor &Stream,
8074fe013be4SDimitry Andric                                                  unsigned ID,
8075fe013be4SDimitry Andric                                                  BitcodeLTOInfo &LTOInfo) {
80760b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(ID))
80770b57cec5SDimitry Andric     return std::move(Err);
80780b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
80790b57cec5SDimitry Andric 
80800b57cec5SDimitry Andric   while (true) {
8081349cc55cSDimitry Andric     BitstreamEntry Entry;
8082fe013be4SDimitry Andric     std::pair<bool, bool> Result = {false,false};
8083349cc55cSDimitry Andric     if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
8084349cc55cSDimitry Andric       return std::move(E);
80850b57cec5SDimitry Andric 
80860b57cec5SDimitry Andric     switch (Entry.Kind) {
80870b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
80880b57cec5SDimitry Andric     case BitstreamEntry::Error:
80890b57cec5SDimitry Andric       return error("Malformed block");
8090fe013be4SDimitry Andric     case BitstreamEntry::EndBlock: {
8091fe013be4SDimitry Andric       // If no flags record found, set both flags to false.
8092fe013be4SDimitry Andric       return Result;
8093fe013be4SDimitry Andric     }
80940b57cec5SDimitry Andric     case BitstreamEntry::Record:
80950b57cec5SDimitry Andric       // The interesting case.
80960b57cec5SDimitry Andric       break;
80970b57cec5SDimitry Andric     }
80980b57cec5SDimitry Andric 
80990b57cec5SDimitry Andric     // Look for the FS_FLAGS record.
81000b57cec5SDimitry Andric     Record.clear();
81010b57cec5SDimitry Andric     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
81020b57cec5SDimitry Andric     if (!MaybeBitCode)
81030b57cec5SDimitry Andric       return MaybeBitCode.takeError();
81040b57cec5SDimitry Andric     switch (MaybeBitCode.get()) {
81050b57cec5SDimitry Andric     default: // Default behavior: ignore.
81060b57cec5SDimitry Andric       break;
81070b57cec5SDimitry Andric     case bitc::FS_FLAGS: { // [flags]
81080b57cec5SDimitry Andric       uint64_t Flags = Record[0];
81090b57cec5SDimitry Andric       // Scan flags.
8110fe013be4SDimitry Andric       assert(Flags <= 0x2ff && "Unexpected bits in flag");
81110b57cec5SDimitry Andric 
8112fe013be4SDimitry Andric       bool EnableSplitLTOUnit = Flags & 0x8;
8113fe013be4SDimitry Andric       bool UnifiedLTO = Flags & 0x200;
8114fe013be4SDimitry Andric       Result = {EnableSplitLTOUnit, UnifiedLTO};
8115fe013be4SDimitry Andric 
8116fe013be4SDimitry Andric       return Result;
81170b57cec5SDimitry Andric     }
81180b57cec5SDimitry Andric     }
81190b57cec5SDimitry Andric   }
81200b57cec5SDimitry Andric   llvm_unreachable("Exit infinite loop");
81210b57cec5SDimitry Andric }
81220b57cec5SDimitry Andric 
81230b57cec5SDimitry Andric // Check if the given bitcode buffer contains a global value summary block.
getLTOInfo()81240b57cec5SDimitry Andric Expected<BitcodeLTOInfo> BitcodeModule::getLTOInfo() {
81250b57cec5SDimitry Andric   BitstreamCursor Stream(Buffer);
81260b57cec5SDimitry Andric   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
81270b57cec5SDimitry Andric     return std::move(JumpFailed);
81280b57cec5SDimitry Andric 
81290b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
81300b57cec5SDimitry Andric     return std::move(Err);
81310b57cec5SDimitry Andric 
81320b57cec5SDimitry Andric   while (true) {
8133349cc55cSDimitry Andric     llvm::BitstreamEntry Entry;
8134349cc55cSDimitry Andric     if (Error E = Stream.advance().moveInto(Entry))
8135349cc55cSDimitry Andric       return std::move(E);
81360b57cec5SDimitry Andric 
81370b57cec5SDimitry Andric     switch (Entry.Kind) {
81380b57cec5SDimitry Andric     case BitstreamEntry::Error:
81390b57cec5SDimitry Andric       return error("Malformed block");
81400b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
81410b57cec5SDimitry Andric       return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/false,
8142fe013be4SDimitry Andric                             /*EnableSplitLTOUnit=*/false, /*UnifiedLTO=*/false};
81430b57cec5SDimitry Andric 
81440b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
81450b57cec5SDimitry Andric       if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) {
8146fe013be4SDimitry Andric         BitcodeLTOInfo LTOInfo;
8147fe013be4SDimitry Andric         Expected<std::pair<bool, bool>> Flags =
8148fe013be4SDimitry Andric             getEnableSplitLTOUnitAndUnifiedFlag(Stream, Entry.ID, LTOInfo);
8149fe013be4SDimitry Andric         if (!Flags)
8150fe013be4SDimitry Andric           return Flags.takeError();
8151fe013be4SDimitry Andric         std::tie(LTOInfo.EnableSplitLTOUnit, LTOInfo.UnifiedLTO) = Flags.get();
8152fe013be4SDimitry Andric         LTOInfo.IsThinLTO = true;
8153fe013be4SDimitry Andric         LTOInfo.HasSummary = true;
8154fe013be4SDimitry Andric         return LTOInfo;
81550b57cec5SDimitry Andric       }
81560b57cec5SDimitry Andric 
81570b57cec5SDimitry Andric       if (Entry.ID == bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID) {
8158fe013be4SDimitry Andric         BitcodeLTOInfo LTOInfo;
8159fe013be4SDimitry Andric         Expected<std::pair<bool, bool>> Flags =
8160fe013be4SDimitry Andric             getEnableSplitLTOUnitAndUnifiedFlag(Stream, Entry.ID, LTOInfo);
8161fe013be4SDimitry Andric         if (!Flags)
8162fe013be4SDimitry Andric           return Flags.takeError();
8163fe013be4SDimitry Andric         std::tie(LTOInfo.EnableSplitLTOUnit, LTOInfo.UnifiedLTO) = Flags.get();
8164fe013be4SDimitry Andric         LTOInfo.IsThinLTO = false;
8165fe013be4SDimitry Andric         LTOInfo.HasSummary = true;
8166fe013be4SDimitry Andric         return LTOInfo;
81670b57cec5SDimitry Andric       }
81680b57cec5SDimitry Andric 
81690b57cec5SDimitry Andric       // Ignore other sub-blocks.
81700b57cec5SDimitry Andric       if (Error Err = Stream.SkipBlock())
81710b57cec5SDimitry Andric         return std::move(Err);
81720b57cec5SDimitry Andric       continue;
81730b57cec5SDimitry Andric 
81740b57cec5SDimitry Andric     case BitstreamEntry::Record:
81750b57cec5SDimitry Andric       if (Expected<unsigned> StreamFailed = Stream.skipRecord(Entry.ID))
81760b57cec5SDimitry Andric         continue;
81770b57cec5SDimitry Andric       else
81780b57cec5SDimitry Andric         return StreamFailed.takeError();
81790b57cec5SDimitry Andric     }
81800b57cec5SDimitry Andric   }
81810b57cec5SDimitry Andric }
81820b57cec5SDimitry Andric 
getSingleModule(MemoryBufferRef Buffer)81830b57cec5SDimitry Andric static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) {
81840b57cec5SDimitry Andric   Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer);
81850b57cec5SDimitry Andric   if (!MsOrErr)
81860b57cec5SDimitry Andric     return MsOrErr.takeError();
81870b57cec5SDimitry Andric 
81880b57cec5SDimitry Andric   if (MsOrErr->size() != 1)
81890b57cec5SDimitry Andric     return error("Expected a single module");
81900b57cec5SDimitry Andric 
81910b57cec5SDimitry Andric   return (*MsOrErr)[0];
81920b57cec5SDimitry Andric }
81930b57cec5SDimitry Andric 
81940b57cec5SDimitry Andric Expected<std::unique_ptr<Module>>
getLazyBitcodeModule(MemoryBufferRef Buffer,LLVMContext & Context,bool ShouldLazyLoadMetadata,bool IsImporting,ParserCallbacks Callbacks)81950b57cec5SDimitry Andric llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context,
8196bdd1243dSDimitry Andric                            bool ShouldLazyLoadMetadata, bool IsImporting,
8197bdd1243dSDimitry Andric                            ParserCallbacks Callbacks) {
81980b57cec5SDimitry Andric   Expected<BitcodeModule> BM = getSingleModule(Buffer);
81990b57cec5SDimitry Andric   if (!BM)
82000b57cec5SDimitry Andric     return BM.takeError();
82010b57cec5SDimitry Andric 
8202bdd1243dSDimitry Andric   return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting,
8203bdd1243dSDimitry Andric                            Callbacks);
82040b57cec5SDimitry Andric }
82050b57cec5SDimitry Andric 
getOwningLazyBitcodeModule(std::unique_ptr<MemoryBuffer> && Buffer,LLVMContext & Context,bool ShouldLazyLoadMetadata,bool IsImporting,ParserCallbacks Callbacks)82060b57cec5SDimitry Andric Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule(
82070b57cec5SDimitry Andric     std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
8208bdd1243dSDimitry Andric     bool ShouldLazyLoadMetadata, bool IsImporting, ParserCallbacks Callbacks) {
82090b57cec5SDimitry Andric   auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata,
8210bdd1243dSDimitry Andric                                      IsImporting, Callbacks);
82110b57cec5SDimitry Andric   if (MOrErr)
82120b57cec5SDimitry Andric     (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
82130b57cec5SDimitry Andric   return MOrErr;
82140b57cec5SDimitry Andric }
82150b57cec5SDimitry Andric 
82160b57cec5SDimitry Andric Expected<std::unique_ptr<Module>>
parseModule(LLVMContext & Context,ParserCallbacks Callbacks)8217bdd1243dSDimitry Andric BitcodeModule::parseModule(LLVMContext &Context, ParserCallbacks Callbacks) {
8218bdd1243dSDimitry Andric   return getModuleImpl(Context, true, false, false, Callbacks);
82190b57cec5SDimitry Andric   // TODO: Restore the use-lists to the in-memory state when the bitcode was
82200b57cec5SDimitry Andric   // written.  We must defer until the Module has been fully materialized.
82210b57cec5SDimitry Andric }
82220b57cec5SDimitry Andric 
82235ffd83dbSDimitry Andric Expected<std::unique_ptr<Module>>
parseBitcodeFile(MemoryBufferRef Buffer,LLVMContext & Context,ParserCallbacks Callbacks)82245ffd83dbSDimitry Andric llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
8225bdd1243dSDimitry Andric                        ParserCallbacks Callbacks) {
82260b57cec5SDimitry Andric   Expected<BitcodeModule> BM = getSingleModule(Buffer);
82270b57cec5SDimitry Andric   if (!BM)
82280b57cec5SDimitry Andric     return BM.takeError();
82290b57cec5SDimitry Andric 
8230bdd1243dSDimitry Andric   return BM->parseModule(Context, Callbacks);
82310b57cec5SDimitry Andric }
82320b57cec5SDimitry Andric 
getBitcodeTargetTriple(MemoryBufferRef Buffer)82330b57cec5SDimitry Andric Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) {
82340b57cec5SDimitry Andric   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
82350b57cec5SDimitry Andric   if (!StreamOrErr)
82360b57cec5SDimitry Andric     return StreamOrErr.takeError();
82370b57cec5SDimitry Andric 
82380b57cec5SDimitry Andric   return readTriple(*StreamOrErr);
82390b57cec5SDimitry Andric }
82400b57cec5SDimitry Andric 
isBitcodeContainingObjCCategory(MemoryBufferRef Buffer)82410b57cec5SDimitry Andric Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) {
82420b57cec5SDimitry Andric   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
82430b57cec5SDimitry Andric   if (!StreamOrErr)
82440b57cec5SDimitry Andric     return StreamOrErr.takeError();
82450b57cec5SDimitry Andric 
82460b57cec5SDimitry Andric   return hasObjCCategory(*StreamOrErr);
82470b57cec5SDimitry Andric }
82480b57cec5SDimitry Andric 
getBitcodeProducerString(MemoryBufferRef Buffer)82490b57cec5SDimitry Andric Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) {
82500b57cec5SDimitry Andric   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
82510b57cec5SDimitry Andric   if (!StreamOrErr)
82520b57cec5SDimitry Andric     return StreamOrErr.takeError();
82530b57cec5SDimitry Andric 
82540b57cec5SDimitry Andric   return readIdentificationCode(*StreamOrErr);
82550b57cec5SDimitry Andric }
82560b57cec5SDimitry Andric 
readModuleSummaryIndex(MemoryBufferRef Buffer,ModuleSummaryIndex & CombinedIndex)82570b57cec5SDimitry Andric Error llvm::readModuleSummaryIndex(MemoryBufferRef Buffer,
8258c9157d92SDimitry Andric                                    ModuleSummaryIndex &CombinedIndex) {
82590b57cec5SDimitry Andric   Expected<BitcodeModule> BM = getSingleModule(Buffer);
82600b57cec5SDimitry Andric   if (!BM)
82610b57cec5SDimitry Andric     return BM.takeError();
82620b57cec5SDimitry Andric 
8263c9157d92SDimitry Andric   return BM->readSummary(CombinedIndex, BM->getModuleIdentifier());
82640b57cec5SDimitry Andric }
82650b57cec5SDimitry Andric 
82660b57cec5SDimitry Andric Expected<std::unique_ptr<ModuleSummaryIndex>>
getModuleSummaryIndex(MemoryBufferRef Buffer)82670b57cec5SDimitry Andric llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) {
82680b57cec5SDimitry Andric   Expected<BitcodeModule> BM = getSingleModule(Buffer);
82690b57cec5SDimitry Andric   if (!BM)
82700b57cec5SDimitry Andric     return BM.takeError();
82710b57cec5SDimitry Andric 
82720b57cec5SDimitry Andric   return BM->getSummary();
82730b57cec5SDimitry Andric }
82740b57cec5SDimitry Andric 
getBitcodeLTOInfo(MemoryBufferRef Buffer)82750b57cec5SDimitry Andric Expected<BitcodeLTOInfo> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer) {
82760b57cec5SDimitry Andric   Expected<BitcodeModule> BM = getSingleModule(Buffer);
82770b57cec5SDimitry Andric   if (!BM)
82780b57cec5SDimitry Andric     return BM.takeError();
82790b57cec5SDimitry Andric 
82800b57cec5SDimitry Andric   return BM->getLTOInfo();
82810b57cec5SDimitry Andric }
82820b57cec5SDimitry Andric 
82830b57cec5SDimitry Andric Expected<std::unique_ptr<ModuleSummaryIndex>>
getModuleSummaryIndexForFile(StringRef Path,bool IgnoreEmptyThinLTOIndexFile)82840b57cec5SDimitry Andric llvm::getModuleSummaryIndexForFile(StringRef Path,
82850b57cec5SDimitry Andric                                    bool IgnoreEmptyThinLTOIndexFile) {
82860b57cec5SDimitry Andric   ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
82870b57cec5SDimitry Andric       MemoryBuffer::getFileOrSTDIN(Path);
82880b57cec5SDimitry Andric   if (!FileOrErr)
82890b57cec5SDimitry Andric     return errorCodeToError(FileOrErr.getError());
82900b57cec5SDimitry Andric   if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize())
82910b57cec5SDimitry Andric     return nullptr;
82920b57cec5SDimitry Andric   return getModuleSummaryIndex(**FileOrErr);
82930b57cec5SDimitry Andric }
8294