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 
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 
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 
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>
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.
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.
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 
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 
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 
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 
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 
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:
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 
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>
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>>
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 
51781ad6265SDimitry 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:
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:
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 
54881ad6265SDimitry Andric   static bool classof(const Value *V) { return V->getValueID() == SubclassID; }
54981ad6265SDimitry Andric 
55081ad6265SDimitry Andric   ArrayRef<unsigned> getOperandIDs() const {
551bdd1243dSDimitry Andric     return ArrayRef(getTrailingObjects<unsigned>(), NumOperands);
55281ad6265SDimitry Andric   }
55381ad6265SDimitry Andric 
554bdd1243dSDimitry 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 
56181ad6265SDimitry 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 
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 
7250b57cec5SDimitry Andric   Metadata *getFnMetadataByID(unsigned ID) {
7260b57cec5SDimitry Andric     return MDLoader->getMetadataFwdRefOrLoad(ID);
7270b57cec5SDimitry Andric   }
7280b57cec5SDimitry Andric 
7290b57cec5SDimitry 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 
7340b57cec5SDimitry 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.
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.
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.
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.
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.
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,
918*c9157d92SDimitry 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 
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 
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 
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 
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 
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 
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).
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
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 
1120*c9157d92SDimitry Andric static std::pair<CalleeInfo::HotnessType, bool>
1121*c9157d92SDimitry Andric getDecodedHotnessCallEdgeInfo(uint64_t RawFlags) {
1122*c9157d92SDimitry Andric   CalleeInfo::HotnessType Hotness =
1123*c9157d92SDimitry Andric       static_cast<CalleeInfo::HotnessType>(RawFlags & 0x7); // 3 bits
1124*c9157d92SDimitry Andric   bool HasTailCall = (RawFlags & 0x8);                      // 1 bit
1125*c9157d92SDimitry Andric   return {Hotness, HasTailCall};
1126*c9157d92SDimitry Andric }
1127*c9157d92SDimitry Andric 
1128*c9157d92SDimitry Andric static void getDecodedRelBFCallEdgeInfo(uint64_t RawFlags, uint64_t &RelBF,
1129*c9157d92SDimitry Andric                                         bool &HasTailCall) {
1130*c9157d92SDimitry Andric   static constexpr uint64_t RelBlockFreqMask =
1131*c9157d92SDimitry Andric       (1 << CalleeInfo::RelBlockFreqBits) - 1;
1132*c9157d92SDimitry Andric   RelBF = RawFlags & RelBlockFreqMask; // RelBlockFreqBits bits
1133*c9157d92SDimitry Andric   HasTailCall = (RawFlags & (1 << CalleeInfo::RelBlockFreqBits)); // 1 bit
1134*c9157d92SDimitry Andric }
1135*c9157d92SDimitry Andric 
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
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 
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 
1163*c9157d92SDimitry Andric static std::optional<CodeModel::Model> getDecodedCodeModel(unsigned Val) {
1164*c9157d92SDimitry Andric   switch (Val) {
1165*c9157d92SDimitry Andric   case 1:
1166*c9157d92SDimitry Andric     return CodeModel::Tiny;
1167*c9157d92SDimitry Andric   case 2:
1168*c9157d92SDimitry Andric     return CodeModel::Small;
1169*c9157d92SDimitry Andric   case 3:
1170*c9157d92SDimitry Andric     return CodeModel::Kernel;
1171*c9157d92SDimitry Andric   case 4:
1172*c9157d92SDimitry Andric     return CodeModel::Medium;
1173*c9157d92SDimitry Andric   case 5:
1174*c9157d92SDimitry Andric     return CodeModel::Large;
1175*c9157d92SDimitry Andric   }
1176*c9157d92SDimitry Andric 
1177*c9157d92SDimitry Andric   return {};
1178*c9157d92SDimitry Andric }
1179*c9157d92SDimitry Andric 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
1430*c9157d92SDimitry Andric   if (Instruction::isCast(Opcode))
1431*c9157d92SDimitry Andric     return ConstantExpr::isSupportedCastOp(Opcode);
1432*c9157d92SDimitry 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 
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 
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 
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 
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 
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 
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'.
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 
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.
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;
2019*c9157d92SDimitry Andric   case bitc::ATTR_KIND_OPTIMIZE_FOR_DEBUGGING:
2020*c9157d92SDimitry 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;
2097*c9157d92SDimitry Andric   case bitc::ATTR_KIND_WRITABLE:
2098*c9157d92SDimitry Andric     return Attribute::Writable;
2099*c9157d92SDimitry Andric   case bitc::ATTR_KIND_CORO_ONLY_DESTROY_WHEN_COMPLETE:
2100*c9157d92SDimitry Andric     return Attribute::CoroDestroyOnlyWhenComplete;
2101*c9157d92SDimitry Andric   case bitc::ATTR_KIND_DEAD_ON_UNWIND:
2102*c9157d92SDimitry Andric     return Attribute::DeadOnUnwind;
21030b57cec5SDimitry Andric   }
21040b57cec5SDimitry Andric }
21050b57cec5SDimitry Andric 
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 
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 
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 
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 
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 
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 
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 
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.
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());
2691*c9157d92SDimitry 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.
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 
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.
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.
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.
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.
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)) {
2937*c9157d92SDimitry 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 
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 
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))
3235*c9157d92SDimitry 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 
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.
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 
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 
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.
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 
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.
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 
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 
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 
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 
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 
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]
3843*c9157d92SDimitry 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 
3952*c9157d92SDimitry Andric   if (Record.size() > 17 && Record[17]) {
3953*c9157d92SDimitry Andric     if (auto CM = getDecodedCodeModel(Record[17]))
3954*c9157d92SDimitry Andric       NewGV->setCodeModel(*CM);
3955*c9157d92SDimitry Andric     else
3956*c9157d92SDimitry Andric       return error("Invalid global variable code model");
3957*c9157d92SDimitry Andric   }
3958*c9157d92SDimitry Andric 
39590b57cec5SDimitry Andric   return Error::success();
39600b57cec5SDimitry Andric }
39610b57cec5SDimitry Andric 
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 
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 
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()) {
42210b57cec5SDimitry Andric     NewGA->setPartition(
42220b57cec5SDimitry Andric         StringRef(Strtab.data() + Record[OpNum], Record[OpNum + 1]));
42230b57cec5SDimitry Andric     OpNum += 2;
42240b57cec5SDimitry Andric   }
42250b57cec5SDimitry Andric 
422681ad6265SDimitry Andric   ValueList.push_back(NewGA, getVirtualTypeID(NewGA->getType(), TypeID));
42270b57cec5SDimitry Andric   IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
42280b57cec5SDimitry Andric   return Error::success();
42290b57cec5SDimitry Andric }
42300b57cec5SDimitry Andric 
42310b57cec5SDimitry Andric Error BitcodeReader::parseModule(uint64_t ResumeBit,
42325ffd83dbSDimitry Andric                                  bool ShouldLazyLoadMetadata,
4233bdd1243dSDimitry Andric                                  ParserCallbacks Callbacks) {
4234bdd1243dSDimitry Andric   this->ValueTypeCallback = std::move(Callbacks.ValueType);
42350b57cec5SDimitry Andric   if (ResumeBit) {
42360b57cec5SDimitry Andric     if (Error JumpFailed = Stream.JumpToBit(ResumeBit))
42370b57cec5SDimitry Andric       return JumpFailed;
42380b57cec5SDimitry Andric   } else if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
42390b57cec5SDimitry Andric     return Err;
42400b57cec5SDimitry Andric 
42410b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
42420b57cec5SDimitry Andric 
42435ffd83dbSDimitry Andric   // Parts of bitcode parsing depend on the datalayout.  Make sure we
42445ffd83dbSDimitry Andric   // finalize the datalayout before we run any of that code.
42455ffd83dbSDimitry Andric   bool ResolvedDataLayout = false;
4246bdd1243dSDimitry Andric   // In order to support importing modules with illegal data layout strings,
4247bdd1243dSDimitry Andric   // delay parsing the data layout string until after upgrades and overrides
4248bdd1243dSDimitry Andric   // have been applied, allowing to fix illegal data layout strings.
4249bdd1243dSDimitry Andric   // Initialize to the current module's layout string in case none is specified.
4250bdd1243dSDimitry Andric   std::string TentativeDataLayoutStr = TheModule->getDataLayoutStr();
42515ffd83dbSDimitry Andric 
4252bdd1243dSDimitry Andric   auto ResolveDataLayout = [&]() -> Error {
4253bdd1243dSDimitry Andric     if (ResolvedDataLayout)
4254bdd1243dSDimitry Andric       return Error::success();
4255bdd1243dSDimitry Andric 
4256bdd1243dSDimitry Andric     // Datalayout and triple can't be parsed after this point.
42575ffd83dbSDimitry Andric     ResolvedDataLayout = true;
42585ffd83dbSDimitry Andric 
4259bdd1243dSDimitry Andric     // Auto-upgrade the layout string
4260bdd1243dSDimitry Andric     TentativeDataLayoutStr = llvm::UpgradeDataLayoutString(
4261bdd1243dSDimitry Andric         TentativeDataLayoutStr, TheModule->getTargetTriple());
42625ffd83dbSDimitry Andric 
4263bdd1243dSDimitry Andric     // Apply override
4264bdd1243dSDimitry Andric     if (Callbacks.DataLayout) {
4265bdd1243dSDimitry Andric       if (auto LayoutOverride = (*Callbacks.DataLayout)(
4266bdd1243dSDimitry Andric               TheModule->getTargetTriple(), TentativeDataLayoutStr))
4267bdd1243dSDimitry Andric         TentativeDataLayoutStr = *LayoutOverride;
4268bdd1243dSDimitry Andric     }
4269bdd1243dSDimitry Andric 
4270bdd1243dSDimitry Andric     // Now the layout string is finalized in TentativeDataLayoutStr. Parse it.
4271bdd1243dSDimitry Andric     Expected<DataLayout> MaybeDL = DataLayout::parse(TentativeDataLayoutStr);
4272bdd1243dSDimitry Andric     if (!MaybeDL)
4273bdd1243dSDimitry Andric       return MaybeDL.takeError();
4274bdd1243dSDimitry Andric 
4275bdd1243dSDimitry Andric     TheModule->setDataLayout(MaybeDL.get());
4276bdd1243dSDimitry Andric     return Error::success();
42775ffd83dbSDimitry Andric   };
42785ffd83dbSDimitry Andric 
42790b57cec5SDimitry Andric   // Read all the records for this module.
42800b57cec5SDimitry Andric   while (true) {
42810b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
42820b57cec5SDimitry Andric     if (!MaybeEntry)
42830b57cec5SDimitry Andric       return MaybeEntry.takeError();
42840b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
42850b57cec5SDimitry Andric 
42860b57cec5SDimitry Andric     switch (Entry.Kind) {
42870b57cec5SDimitry Andric     case BitstreamEntry::Error:
42880b57cec5SDimitry Andric       return error("Malformed block");
42890b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
4290bdd1243dSDimitry Andric       if (Error Err = ResolveDataLayout())
4291bdd1243dSDimitry Andric         return Err;
42920b57cec5SDimitry Andric       return globalCleanup();
42930b57cec5SDimitry Andric 
42940b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
42950b57cec5SDimitry Andric       switch (Entry.ID) {
42960b57cec5SDimitry Andric       default:  // Skip unknown content.
42970b57cec5SDimitry Andric         if (Error Err = Stream.SkipBlock())
42980b57cec5SDimitry Andric           return Err;
42990b57cec5SDimitry Andric         break;
43000b57cec5SDimitry Andric       case bitc::BLOCKINFO_BLOCK_ID:
430181ad6265SDimitry Andric         if (Error Err = readBlockInfo())
430281ad6265SDimitry Andric           return Err;
43030b57cec5SDimitry Andric         break;
43040b57cec5SDimitry Andric       case bitc::PARAMATTR_BLOCK_ID:
43050b57cec5SDimitry Andric         if (Error Err = parseAttributeBlock())
43060b57cec5SDimitry Andric           return Err;
43070b57cec5SDimitry Andric         break;
43080b57cec5SDimitry Andric       case bitc::PARAMATTR_GROUP_BLOCK_ID:
43090b57cec5SDimitry Andric         if (Error Err = parseAttributeGroupBlock())
43100b57cec5SDimitry Andric           return Err;
43110b57cec5SDimitry Andric         break;
43120b57cec5SDimitry Andric       case bitc::TYPE_BLOCK_ID_NEW:
43130b57cec5SDimitry Andric         if (Error Err = parseTypeTable())
43140b57cec5SDimitry Andric           return Err;
43150b57cec5SDimitry Andric         break;
43160b57cec5SDimitry Andric       case bitc::VALUE_SYMTAB_BLOCK_ID:
43170b57cec5SDimitry Andric         if (!SeenValueSymbolTable) {
43180b57cec5SDimitry Andric           // Either this is an old form VST without function index and an
43190b57cec5SDimitry Andric           // associated VST forward declaration record (which would have caused
43200b57cec5SDimitry Andric           // the VST to be jumped to and parsed before it was encountered
43210b57cec5SDimitry Andric           // normally in the stream), or there were no function blocks to
43220b57cec5SDimitry Andric           // trigger an earlier parsing of the VST.
43230b57cec5SDimitry Andric           assert(VSTOffset == 0 || FunctionsWithBodies.empty());
43240b57cec5SDimitry Andric           if (Error Err = parseValueSymbolTable())
43250b57cec5SDimitry Andric             return Err;
43260b57cec5SDimitry Andric           SeenValueSymbolTable = true;
43270b57cec5SDimitry Andric         } else {
43280b57cec5SDimitry Andric           // We must have had a VST forward declaration record, which caused
43290b57cec5SDimitry Andric           // the parser to jump to and parse the VST earlier.
43300b57cec5SDimitry Andric           assert(VSTOffset > 0);
43310b57cec5SDimitry Andric           if (Error Err = Stream.SkipBlock())
43320b57cec5SDimitry Andric             return Err;
43330b57cec5SDimitry Andric         }
43340b57cec5SDimitry Andric         break;
43350b57cec5SDimitry Andric       case bitc::CONSTANTS_BLOCK_ID:
43360b57cec5SDimitry Andric         if (Error Err = parseConstants())
43370b57cec5SDimitry Andric           return Err;
43380b57cec5SDimitry Andric         if (Error Err = resolveGlobalAndIndirectSymbolInits())
43390b57cec5SDimitry Andric           return Err;
43400b57cec5SDimitry Andric         break;
43410b57cec5SDimitry Andric       case bitc::METADATA_BLOCK_ID:
43420b57cec5SDimitry Andric         if (ShouldLazyLoadMetadata) {
43430b57cec5SDimitry Andric           if (Error Err = rememberAndSkipMetadata())
43440b57cec5SDimitry Andric             return Err;
43450b57cec5SDimitry Andric           break;
43460b57cec5SDimitry Andric         }
43470b57cec5SDimitry Andric         assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
43480b57cec5SDimitry Andric         if (Error Err = MDLoader->parseModuleMetadata())
43490b57cec5SDimitry Andric           return Err;
43500b57cec5SDimitry Andric         break;
43510b57cec5SDimitry Andric       case bitc::METADATA_KIND_BLOCK_ID:
43520b57cec5SDimitry Andric         if (Error Err = MDLoader->parseMetadataKinds())
43530b57cec5SDimitry Andric           return Err;
43540b57cec5SDimitry Andric         break;
43550b57cec5SDimitry Andric       case bitc::FUNCTION_BLOCK_ID:
4356bdd1243dSDimitry Andric         if (Error Err = ResolveDataLayout())
4357bdd1243dSDimitry Andric           return Err;
43585ffd83dbSDimitry Andric 
43590b57cec5SDimitry Andric         // If this is the first function body we've seen, reverse the
43600b57cec5SDimitry Andric         // FunctionsWithBodies list.
43610b57cec5SDimitry Andric         if (!SeenFirstFunctionBody) {
43620b57cec5SDimitry Andric           std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
43630b57cec5SDimitry Andric           if (Error Err = globalCleanup())
43640b57cec5SDimitry Andric             return Err;
43650b57cec5SDimitry Andric           SeenFirstFunctionBody = true;
43660b57cec5SDimitry Andric         }
43670b57cec5SDimitry Andric 
43680b57cec5SDimitry Andric         if (VSTOffset > 0) {
43690b57cec5SDimitry Andric           // If we have a VST forward declaration record, make sure we
43700b57cec5SDimitry Andric           // parse the VST now if we haven't already. It is needed to
43710b57cec5SDimitry Andric           // set up the DeferredFunctionInfo vector for lazy reading.
43720b57cec5SDimitry Andric           if (!SeenValueSymbolTable) {
43730b57cec5SDimitry Andric             if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
43740b57cec5SDimitry Andric               return Err;
43750b57cec5SDimitry Andric             SeenValueSymbolTable = true;
43760b57cec5SDimitry Andric             // Fall through so that we record the NextUnreadBit below.
43770b57cec5SDimitry Andric             // This is necessary in case we have an anonymous function that
43780b57cec5SDimitry Andric             // is later materialized. Since it will not have a VST entry we
43790b57cec5SDimitry Andric             // need to fall back to the lazy parse to find its offset.
43800b57cec5SDimitry Andric           } else {
43810b57cec5SDimitry Andric             // If we have a VST forward declaration record, but have already
43820b57cec5SDimitry Andric             // parsed the VST (just above, when the first function body was
43830b57cec5SDimitry Andric             // encountered here), then we are resuming the parse after
43840b57cec5SDimitry Andric             // materializing functions. The ResumeBit points to the
43850b57cec5SDimitry Andric             // start of the last function block recorded in the
43860b57cec5SDimitry Andric             // DeferredFunctionInfo map. Skip it.
43870b57cec5SDimitry Andric             if (Error Err = Stream.SkipBlock())
43880b57cec5SDimitry Andric               return Err;
43890b57cec5SDimitry Andric             continue;
43900b57cec5SDimitry Andric           }
43910b57cec5SDimitry Andric         }
43920b57cec5SDimitry Andric 
43930b57cec5SDimitry Andric         // Support older bitcode files that did not have the function
43940b57cec5SDimitry Andric         // index in the VST, nor a VST forward declaration record, as
43950b57cec5SDimitry Andric         // well as anonymous functions that do not have VST entries.
43960b57cec5SDimitry Andric         // Build the DeferredFunctionInfo vector on the fly.
43970b57cec5SDimitry Andric         if (Error Err = rememberAndSkipFunctionBody())
43980b57cec5SDimitry Andric           return Err;
43990b57cec5SDimitry Andric 
44000b57cec5SDimitry Andric         // Suspend parsing when we reach the function bodies. Subsequent
44010b57cec5SDimitry Andric         // materialization calls will resume it when necessary. If the bitcode
44020b57cec5SDimitry Andric         // file is old, the symbol table will be at the end instead and will not
44030b57cec5SDimitry Andric         // have been seen yet. In this case, just finish the parse now.
44040b57cec5SDimitry Andric         if (SeenValueSymbolTable) {
44050b57cec5SDimitry Andric           NextUnreadBit = Stream.GetCurrentBitNo();
44060b57cec5SDimitry Andric           // After the VST has been parsed, we need to make sure intrinsic name
44070b57cec5SDimitry Andric           // are auto-upgraded.
44080b57cec5SDimitry Andric           return globalCleanup();
44090b57cec5SDimitry Andric         }
44100b57cec5SDimitry Andric         break;
44110b57cec5SDimitry Andric       case bitc::USELIST_BLOCK_ID:
44120b57cec5SDimitry Andric         if (Error Err = parseUseLists())
44130b57cec5SDimitry Andric           return Err;
44140b57cec5SDimitry Andric         break;
44150b57cec5SDimitry Andric       case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
44160b57cec5SDimitry Andric         if (Error Err = parseOperandBundleTags())
44170b57cec5SDimitry Andric           return Err;
44180b57cec5SDimitry Andric         break;
44190b57cec5SDimitry Andric       case bitc::SYNC_SCOPE_NAMES_BLOCK_ID:
44200b57cec5SDimitry Andric         if (Error Err = parseSyncScopeNames())
44210b57cec5SDimitry Andric           return Err;
44220b57cec5SDimitry Andric         break;
44230b57cec5SDimitry Andric       }
44240b57cec5SDimitry Andric       continue;
44250b57cec5SDimitry Andric 
44260b57cec5SDimitry Andric     case BitstreamEntry::Record:
44270b57cec5SDimitry Andric       // The interesting case.
44280b57cec5SDimitry Andric       break;
44290b57cec5SDimitry Andric     }
44300b57cec5SDimitry Andric 
44310b57cec5SDimitry Andric     // Read a record.
44320b57cec5SDimitry Andric     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
44330b57cec5SDimitry Andric     if (!MaybeBitCode)
44340b57cec5SDimitry Andric       return MaybeBitCode.takeError();
44350b57cec5SDimitry Andric     switch (unsigned BitCode = MaybeBitCode.get()) {
44360b57cec5SDimitry Andric     default: break;  // Default behavior, ignore unknown content.
44370b57cec5SDimitry Andric     case bitc::MODULE_CODE_VERSION: {
44380b57cec5SDimitry Andric       Expected<unsigned> VersionOrErr = parseVersionRecord(Record);
44390b57cec5SDimitry Andric       if (!VersionOrErr)
44400b57cec5SDimitry Andric         return VersionOrErr.takeError();
44410b57cec5SDimitry Andric       UseRelativeIDs = *VersionOrErr >= 1;
44420b57cec5SDimitry Andric       break;
44430b57cec5SDimitry Andric     }
44440b57cec5SDimitry Andric     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
44455ffd83dbSDimitry Andric       if (ResolvedDataLayout)
44465ffd83dbSDimitry Andric         return error("target triple too late in module");
44470b57cec5SDimitry Andric       std::string S;
44480b57cec5SDimitry Andric       if (convertToString(Record, 0, S))
44490b57cec5SDimitry Andric         return error("Invalid record");
44500b57cec5SDimitry Andric       TheModule->setTargetTriple(S);
44510b57cec5SDimitry Andric       break;
44520b57cec5SDimitry Andric     }
44530b57cec5SDimitry Andric     case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
44545ffd83dbSDimitry Andric       if (ResolvedDataLayout)
44555ffd83dbSDimitry Andric         return error("datalayout too late in module");
4456bdd1243dSDimitry Andric       if (convertToString(Record, 0, TentativeDataLayoutStr))
44570b57cec5SDimitry Andric         return error("Invalid record");
44580b57cec5SDimitry Andric       break;
44590b57cec5SDimitry Andric     }
44600b57cec5SDimitry Andric     case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
44610b57cec5SDimitry Andric       std::string S;
44620b57cec5SDimitry Andric       if (convertToString(Record, 0, S))
44630b57cec5SDimitry Andric         return error("Invalid record");
44640b57cec5SDimitry Andric       TheModule->setModuleInlineAsm(S);
44650b57cec5SDimitry Andric       break;
44660b57cec5SDimitry Andric     }
44670b57cec5SDimitry Andric     case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
44685ffd83dbSDimitry Andric       // Deprecated, but still needed to read old bitcode files.
44690b57cec5SDimitry Andric       std::string S;
44700b57cec5SDimitry Andric       if (convertToString(Record, 0, S))
44710b57cec5SDimitry Andric         return error("Invalid record");
44720b57cec5SDimitry Andric       // Ignore value.
44730b57cec5SDimitry Andric       break;
44740b57cec5SDimitry Andric     }
44750b57cec5SDimitry Andric     case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
44760b57cec5SDimitry Andric       std::string S;
44770b57cec5SDimitry Andric       if (convertToString(Record, 0, S))
44780b57cec5SDimitry Andric         return error("Invalid record");
44790b57cec5SDimitry Andric       SectionTable.push_back(S);
44800b57cec5SDimitry Andric       break;
44810b57cec5SDimitry Andric     }
44820b57cec5SDimitry Andric     case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
44830b57cec5SDimitry Andric       std::string S;
44840b57cec5SDimitry Andric       if (convertToString(Record, 0, S))
44850b57cec5SDimitry Andric         return error("Invalid record");
44860b57cec5SDimitry Andric       GCTable.push_back(S);
44870b57cec5SDimitry Andric       break;
44880b57cec5SDimitry Andric     }
44890b57cec5SDimitry Andric     case bitc::MODULE_CODE_COMDAT:
44900b57cec5SDimitry Andric       if (Error Err = parseComdatRecord(Record))
44910b57cec5SDimitry Andric         return Err;
44920b57cec5SDimitry Andric       break;
449304eeddc0SDimitry Andric     // FIXME: BitcodeReader should handle {GLOBALVAR, FUNCTION, ALIAS, IFUNC}
449404eeddc0SDimitry Andric     // written by ThinLinkBitcodeWriter. See
449504eeddc0SDimitry Andric     // `ThinLinkBitcodeWriter::writeSimplifiedModuleInfo` for the format of each
449604eeddc0SDimitry Andric     // record
449704eeddc0SDimitry Andric     // (https://github.com/llvm/llvm-project/blob/b6a93967d9c11e79802b5e75cec1584d6c8aa472/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp#L4714)
44980b57cec5SDimitry Andric     case bitc::MODULE_CODE_GLOBALVAR:
44990b57cec5SDimitry Andric       if (Error Err = parseGlobalVarRecord(Record))
45000b57cec5SDimitry Andric         return Err;
45010b57cec5SDimitry Andric       break;
45020b57cec5SDimitry Andric     case bitc::MODULE_CODE_FUNCTION:
4503bdd1243dSDimitry Andric       if (Error Err = ResolveDataLayout())
4504bdd1243dSDimitry Andric         return Err;
45050b57cec5SDimitry Andric       if (Error Err = parseFunctionRecord(Record))
45060b57cec5SDimitry Andric         return Err;
45070b57cec5SDimitry Andric       break;
45080b57cec5SDimitry Andric     case bitc::MODULE_CODE_IFUNC:
45090b57cec5SDimitry Andric     case bitc::MODULE_CODE_ALIAS:
45100b57cec5SDimitry Andric     case bitc::MODULE_CODE_ALIAS_OLD:
45110b57cec5SDimitry Andric       if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
45120b57cec5SDimitry Andric         return Err;
45130b57cec5SDimitry Andric       break;
45140b57cec5SDimitry Andric     /// MODULE_CODE_VSTOFFSET: [offset]
45150b57cec5SDimitry Andric     case bitc::MODULE_CODE_VSTOFFSET:
4516e8d8bef9SDimitry Andric       if (Record.empty())
45170b57cec5SDimitry Andric         return error("Invalid record");
45180b57cec5SDimitry Andric       // Note that we subtract 1 here because the offset is relative to one word
45190b57cec5SDimitry Andric       // before the start of the identification or module block, which was
45200b57cec5SDimitry Andric       // historically always the start of the regular bitcode header.
45210b57cec5SDimitry Andric       VSTOffset = Record[0] - 1;
45220b57cec5SDimitry Andric       break;
45230b57cec5SDimitry Andric     /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
45240b57cec5SDimitry Andric     case bitc::MODULE_CODE_SOURCE_FILENAME:
45250b57cec5SDimitry Andric       SmallString<128> ValueName;
45260b57cec5SDimitry Andric       if (convertToString(Record, 0, ValueName))
45270b57cec5SDimitry Andric         return error("Invalid record");
45280b57cec5SDimitry Andric       TheModule->setSourceFileName(ValueName);
45290b57cec5SDimitry Andric       break;
45300b57cec5SDimitry Andric     }
45310b57cec5SDimitry Andric     Record.clear();
45320b57cec5SDimitry Andric   }
4533bdd1243dSDimitry Andric   this->ValueTypeCallback = std::nullopt;
4534bdd1243dSDimitry Andric   return Error::success();
45350b57cec5SDimitry Andric }
45360b57cec5SDimitry Andric 
45370b57cec5SDimitry Andric Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata,
45385ffd83dbSDimitry Andric                                       bool IsImporting,
4539bdd1243dSDimitry Andric                                       ParserCallbacks Callbacks) {
45400b57cec5SDimitry Andric   TheModule = M;
4541bdd1243dSDimitry Andric   MetadataLoaderCallbacks MDCallbacks;
4542bdd1243dSDimitry Andric   MDCallbacks.GetTypeByID = [&](unsigned ID) { return getTypeByID(ID); };
4543bdd1243dSDimitry Andric   MDCallbacks.GetContainedTypeID = [&](unsigned I, unsigned J) {
4544bdd1243dSDimitry Andric     return getContainedTypeID(I, J);
4545bdd1243dSDimitry Andric   };
4546bdd1243dSDimitry Andric   MDCallbacks.MDType = Callbacks.MDType;
4547bdd1243dSDimitry Andric   MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting, MDCallbacks);
4548bdd1243dSDimitry Andric   return parseModule(0, ShouldLazyLoadMetadata, Callbacks);
45490b57cec5SDimitry Andric }
45500b57cec5SDimitry Andric 
45510b57cec5SDimitry Andric Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
45520b57cec5SDimitry Andric   if (!isa<PointerType>(PtrType))
45530b57cec5SDimitry Andric     return error("Load/Store operand is not a pointer type");
4554fe6060f1SDimitry Andric   if (!PointerType::isLoadableOrStorableType(ValType))
45550b57cec5SDimitry Andric     return error("Cannot load/store from pointer");
45560b57cec5SDimitry Andric   return Error::success();
45570b57cec5SDimitry Andric }
45580b57cec5SDimitry Andric 
455981ad6265SDimitry Andric Error BitcodeReader::propagateAttributeTypes(CallBase *CB,
456081ad6265SDimitry Andric                                              ArrayRef<unsigned> ArgTyIDs) {
456181ad6265SDimitry Andric   AttributeList Attrs = CB->getAttributes();
45620b57cec5SDimitry Andric   for (unsigned i = 0; i != CB->arg_size(); ++i) {
4563fe6060f1SDimitry Andric     for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
4564fe6060f1SDimitry Andric                                      Attribute::InAlloca}) {
456581ad6265SDimitry Andric       if (!Attrs.hasParamAttr(i, Kind) ||
456681ad6265SDimitry Andric           Attrs.getParamAttr(i, Kind).getValueAsType())
45670b57cec5SDimitry Andric         continue;
45680b57cec5SDimitry Andric 
456981ad6265SDimitry Andric       Type *PtrEltTy = getPtrElementTypeByID(ArgTyIDs[i]);
457081ad6265SDimitry Andric       if (!PtrEltTy)
457181ad6265SDimitry Andric         return error("Missing element type for typed attribute upgrade");
4572e8d8bef9SDimitry Andric 
4573fe6060f1SDimitry Andric       Attribute NewAttr;
4574fe6060f1SDimitry Andric       switch (Kind) {
4575fe6060f1SDimitry Andric       case Attribute::ByVal:
4576fe6060f1SDimitry Andric         NewAttr = Attribute::getWithByValType(Context, PtrEltTy);
4577fe6060f1SDimitry Andric         break;
4578fe6060f1SDimitry Andric       case Attribute::StructRet:
4579fe6060f1SDimitry Andric         NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy);
4580fe6060f1SDimitry Andric         break;
4581fe6060f1SDimitry Andric       case Attribute::InAlloca:
4582fe6060f1SDimitry Andric         NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy);
4583fe6060f1SDimitry Andric         break;
4584fe6060f1SDimitry Andric       default:
4585fe6060f1SDimitry Andric         llvm_unreachable("not an upgraded type attribute");
4586fe6060f1SDimitry Andric       }
4587fe6060f1SDimitry Andric 
458881ad6265SDimitry Andric       Attrs = Attrs.addParamAttribute(Context, i, NewAttr);
4589e8d8bef9SDimitry Andric     }
45900b57cec5SDimitry Andric   }
4591fe6060f1SDimitry Andric 
459204eeddc0SDimitry Andric   if (CB->isInlineAsm()) {
459304eeddc0SDimitry Andric     const InlineAsm *IA = cast<InlineAsm>(CB->getCalledOperand());
459404eeddc0SDimitry Andric     unsigned ArgNo = 0;
459504eeddc0SDimitry Andric     for (const InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
459604eeddc0SDimitry Andric       if (!CI.hasArg())
459704eeddc0SDimitry Andric         continue;
459804eeddc0SDimitry Andric 
459981ad6265SDimitry Andric       if (CI.isIndirect && !Attrs.getParamElementType(ArgNo)) {
460081ad6265SDimitry Andric         Type *ElemTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
460181ad6265SDimitry Andric         if (!ElemTy)
460281ad6265SDimitry Andric           return error("Missing element type for inline asm upgrade");
460381ad6265SDimitry Andric         Attrs = Attrs.addParamAttribute(
460481ad6265SDimitry Andric             Context, ArgNo,
460581ad6265SDimitry Andric             Attribute::get(Context, Attribute::ElementType, ElemTy));
460604eeddc0SDimitry Andric       }
460704eeddc0SDimitry Andric 
460804eeddc0SDimitry Andric       ArgNo++;
460904eeddc0SDimitry Andric     }
461004eeddc0SDimitry Andric   }
461104eeddc0SDimitry Andric 
4612fe6060f1SDimitry Andric   switch (CB->getIntrinsicID()) {
4613fe6060f1SDimitry Andric   case Intrinsic::preserve_array_access_index:
4614fe6060f1SDimitry Andric   case Intrinsic::preserve_struct_access_index:
461581ad6265SDimitry Andric   case Intrinsic::aarch64_ldaxr:
461681ad6265SDimitry Andric   case Intrinsic::aarch64_ldxr:
461781ad6265SDimitry Andric   case Intrinsic::aarch64_stlxr:
461881ad6265SDimitry Andric   case Intrinsic::aarch64_stxr:
461981ad6265SDimitry Andric   case Intrinsic::arm_ldaex:
462081ad6265SDimitry Andric   case Intrinsic::arm_ldrex:
462181ad6265SDimitry Andric   case Intrinsic::arm_stlex:
462281ad6265SDimitry Andric   case Intrinsic::arm_strex: {
462381ad6265SDimitry Andric     unsigned ArgNo;
462481ad6265SDimitry Andric     switch (CB->getIntrinsicID()) {
462581ad6265SDimitry Andric     case Intrinsic::aarch64_stlxr:
462681ad6265SDimitry Andric     case Intrinsic::aarch64_stxr:
462781ad6265SDimitry Andric     case Intrinsic::arm_stlex:
462881ad6265SDimitry Andric     case Intrinsic::arm_strex:
462981ad6265SDimitry Andric       ArgNo = 1;
463081ad6265SDimitry Andric       break;
463181ad6265SDimitry Andric     default:
463281ad6265SDimitry Andric       ArgNo = 0;
463381ad6265SDimitry Andric       break;
463481ad6265SDimitry Andric     }
463581ad6265SDimitry Andric     if (!Attrs.getParamElementType(ArgNo)) {
463681ad6265SDimitry Andric       Type *ElTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
463781ad6265SDimitry Andric       if (!ElTy)
463881ad6265SDimitry Andric         return error("Missing element type for elementtype upgrade");
4639fe6060f1SDimitry Andric       Attribute NewAttr = Attribute::get(Context, Attribute::ElementType, ElTy);
464081ad6265SDimitry Andric       Attrs = Attrs.addParamAttribute(Context, ArgNo, NewAttr);
4641fe6060f1SDimitry Andric     }
4642fe6060f1SDimitry Andric     break;
464381ad6265SDimitry Andric   }
4644fe6060f1SDimitry Andric   default:
4645fe6060f1SDimitry Andric     break;
4646fe6060f1SDimitry Andric   }
464781ad6265SDimitry Andric 
464881ad6265SDimitry Andric   CB->setAttributes(Attrs);
464981ad6265SDimitry Andric   return Error::success();
46500b57cec5SDimitry Andric }
46510b57cec5SDimitry Andric 
46520b57cec5SDimitry Andric /// Lazily parse the specified function body block.
46530b57cec5SDimitry Andric Error BitcodeReader::parseFunctionBody(Function *F) {
46540b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
46550b57cec5SDimitry Andric     return Err;
46560b57cec5SDimitry Andric 
46570b57cec5SDimitry Andric   // Unexpected unresolved metadata when parsing function.
46580b57cec5SDimitry Andric   if (MDLoader->hasFwdRefs())
46590b57cec5SDimitry Andric     return error("Invalid function metadata: incoming forward references");
46600b57cec5SDimitry Andric 
46610b57cec5SDimitry Andric   InstructionList.clear();
46620b57cec5SDimitry Andric   unsigned ModuleValueListSize = ValueList.size();
46630b57cec5SDimitry Andric   unsigned ModuleMDLoaderSize = MDLoader->size();
46640b57cec5SDimitry Andric 
46650b57cec5SDimitry Andric   // Add all the function arguments to the value table.
46660b57cec5SDimitry Andric   unsigned ArgNo = 0;
466781ad6265SDimitry Andric   unsigned FTyID = FunctionTypeIDs[F];
46680b57cec5SDimitry Andric   for (Argument &I : F->args()) {
466981ad6265SDimitry Andric     unsigned ArgTyID = getContainedTypeID(FTyID, ArgNo + 1);
467081ad6265SDimitry Andric     assert(I.getType() == getTypeByID(ArgTyID) &&
46710b57cec5SDimitry Andric            "Incorrect fully specified type for Function Argument");
467281ad6265SDimitry Andric     ValueList.push_back(&I, ArgTyID);
467381ad6265SDimitry Andric     ++ArgNo;
46740b57cec5SDimitry Andric   }
46750b57cec5SDimitry Andric   unsigned NextValueNo = ValueList.size();
46760b57cec5SDimitry Andric   BasicBlock *CurBB = nullptr;
46770b57cec5SDimitry Andric   unsigned CurBBNo = 0;
467881ad6265SDimitry Andric   // Block into which constant expressions from phi nodes are materialized.
467981ad6265SDimitry Andric   BasicBlock *PhiConstExprBB = nullptr;
468081ad6265SDimitry Andric   // Edge blocks for phi nodes into which constant expressions have been
468181ad6265SDimitry Andric   // expanded.
468281ad6265SDimitry Andric   SmallMapVector<std::pair<BasicBlock *, BasicBlock *>, BasicBlock *, 4>
468381ad6265SDimitry Andric     ConstExprEdgeBBs;
46840b57cec5SDimitry Andric 
46850b57cec5SDimitry Andric   DebugLoc LastLoc;
46860b57cec5SDimitry Andric   auto getLastInstruction = [&]() -> Instruction * {
46870b57cec5SDimitry Andric     if (CurBB && !CurBB->empty())
46880b57cec5SDimitry Andric       return &CurBB->back();
46890b57cec5SDimitry Andric     else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
46900b57cec5SDimitry Andric              !FunctionBBs[CurBBNo - 1]->empty())
46910b57cec5SDimitry Andric       return &FunctionBBs[CurBBNo - 1]->back();
46920b57cec5SDimitry Andric     return nullptr;
46930b57cec5SDimitry Andric   };
46940b57cec5SDimitry Andric 
46950b57cec5SDimitry Andric   std::vector<OperandBundleDef> OperandBundles;
46960b57cec5SDimitry Andric 
46970b57cec5SDimitry Andric   // Read all the records.
46980b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
46990b57cec5SDimitry Andric 
47000b57cec5SDimitry Andric   while (true) {
47010b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
47020b57cec5SDimitry Andric     if (!MaybeEntry)
47030b57cec5SDimitry Andric       return MaybeEntry.takeError();
47040b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
47050b57cec5SDimitry Andric 
47060b57cec5SDimitry Andric     switch (Entry.Kind) {
47070b57cec5SDimitry Andric     case BitstreamEntry::Error:
47080b57cec5SDimitry Andric       return error("Malformed block");
47090b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
47100b57cec5SDimitry Andric       goto OutOfRecordLoop;
47110b57cec5SDimitry Andric 
47120b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
47130b57cec5SDimitry Andric       switch (Entry.ID) {
47140b57cec5SDimitry Andric       default:  // Skip unknown content.
47150b57cec5SDimitry Andric         if (Error Err = Stream.SkipBlock())
47160b57cec5SDimitry Andric           return Err;
47170b57cec5SDimitry Andric         break;
47180b57cec5SDimitry Andric       case bitc::CONSTANTS_BLOCK_ID:
47190b57cec5SDimitry Andric         if (Error Err = parseConstants())
47200b57cec5SDimitry Andric           return Err;
47210b57cec5SDimitry Andric         NextValueNo = ValueList.size();
47220b57cec5SDimitry Andric         break;
47230b57cec5SDimitry Andric       case bitc::VALUE_SYMTAB_BLOCK_ID:
47240b57cec5SDimitry Andric         if (Error Err = parseValueSymbolTable())
47250b57cec5SDimitry Andric           return Err;
47260b57cec5SDimitry Andric         break;
47270b57cec5SDimitry Andric       case bitc::METADATA_ATTACHMENT_ID:
47280b57cec5SDimitry Andric         if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList))
47290b57cec5SDimitry Andric           return Err;
47300b57cec5SDimitry Andric         break;
47310b57cec5SDimitry Andric       case bitc::METADATA_BLOCK_ID:
47320b57cec5SDimitry Andric         assert(DeferredMetadataInfo.empty() &&
47330b57cec5SDimitry Andric                "Must read all module-level metadata before function-level");
47340b57cec5SDimitry Andric         if (Error Err = MDLoader->parseFunctionMetadata())
47350b57cec5SDimitry Andric           return Err;
47360b57cec5SDimitry Andric         break;
47370b57cec5SDimitry Andric       case bitc::USELIST_BLOCK_ID:
47380b57cec5SDimitry Andric         if (Error Err = parseUseLists())
47390b57cec5SDimitry Andric           return Err;
47400b57cec5SDimitry Andric         break;
47410b57cec5SDimitry Andric       }
47420b57cec5SDimitry Andric       continue;
47430b57cec5SDimitry Andric 
47440b57cec5SDimitry Andric     case BitstreamEntry::Record:
47450b57cec5SDimitry Andric       // The interesting case.
47460b57cec5SDimitry Andric       break;
47470b57cec5SDimitry Andric     }
47480b57cec5SDimitry Andric 
47490b57cec5SDimitry Andric     // Read a record.
47500b57cec5SDimitry Andric     Record.clear();
47510b57cec5SDimitry Andric     Instruction *I = nullptr;
475281ad6265SDimitry Andric     unsigned ResTypeID = InvalidTypeID;
47530b57cec5SDimitry Andric     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
47540b57cec5SDimitry Andric     if (!MaybeBitCode)
47550b57cec5SDimitry Andric       return MaybeBitCode.takeError();
47560b57cec5SDimitry Andric     switch (unsigned BitCode = MaybeBitCode.get()) {
47570b57cec5SDimitry Andric     default: // Default behavior: reject
47580b57cec5SDimitry Andric       return error("Invalid value");
47590b57cec5SDimitry Andric     case bitc::FUNC_CODE_DECLAREBLOCKS: {   // DECLAREBLOCKS: [nblocks]
4760e8d8bef9SDimitry Andric       if (Record.empty() || Record[0] == 0)
47610b57cec5SDimitry Andric         return error("Invalid record");
47620b57cec5SDimitry Andric       // Create all the basic blocks for the function.
47630b57cec5SDimitry Andric       FunctionBBs.resize(Record[0]);
47640b57cec5SDimitry Andric 
47650b57cec5SDimitry Andric       // See if anything took the address of blocks in this function.
47660b57cec5SDimitry Andric       auto BBFRI = BasicBlockFwdRefs.find(F);
47670b57cec5SDimitry Andric       if (BBFRI == BasicBlockFwdRefs.end()) {
47684824e7fdSDimitry Andric         for (BasicBlock *&BB : FunctionBBs)
47694824e7fdSDimitry Andric           BB = BasicBlock::Create(Context, "", F);
47700b57cec5SDimitry Andric       } else {
47710b57cec5SDimitry Andric         auto &BBRefs = BBFRI->second;
47720b57cec5SDimitry Andric         // Check for invalid basic block references.
47730b57cec5SDimitry Andric         if (BBRefs.size() > FunctionBBs.size())
47740b57cec5SDimitry Andric           return error("Invalid ID");
47750b57cec5SDimitry Andric         assert(!BBRefs.empty() && "Unexpected empty array");
47760b57cec5SDimitry Andric         assert(!BBRefs.front() && "Invalid reference to entry block");
47770b57cec5SDimitry Andric         for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
47780b57cec5SDimitry Andric              ++I)
47790b57cec5SDimitry Andric           if (I < RE && BBRefs[I]) {
47800b57cec5SDimitry Andric             BBRefs[I]->insertInto(F);
47810b57cec5SDimitry Andric             FunctionBBs[I] = BBRefs[I];
47820b57cec5SDimitry Andric           } else {
47830b57cec5SDimitry Andric             FunctionBBs[I] = BasicBlock::Create(Context, "", F);
47840b57cec5SDimitry Andric           }
47850b57cec5SDimitry Andric 
47860b57cec5SDimitry Andric         // Erase from the table.
47870b57cec5SDimitry Andric         BasicBlockFwdRefs.erase(BBFRI);
47880b57cec5SDimitry Andric       }
47890b57cec5SDimitry Andric 
47900b57cec5SDimitry Andric       CurBB = FunctionBBs[0];
47910b57cec5SDimitry Andric       continue;
47920b57cec5SDimitry Andric     }
47930b57cec5SDimitry Andric 
479481ad6265SDimitry Andric     case bitc::FUNC_CODE_BLOCKADDR_USERS: // BLOCKADDR_USERS: [vals...]
479581ad6265SDimitry Andric       // The record should not be emitted if it's an empty list.
479681ad6265SDimitry Andric       if (Record.empty())
479781ad6265SDimitry Andric         return error("Invalid record");
479881ad6265SDimitry Andric       // When we have the RARE case of a BlockAddress Constant that is not
479981ad6265SDimitry Andric       // scoped to the Function it refers to, we need to conservatively
480081ad6265SDimitry Andric       // materialize the referred to Function, regardless of whether or not
480181ad6265SDimitry Andric       // that Function will ultimately be linked, otherwise users of
480281ad6265SDimitry Andric       // BitcodeReader might start splicing out Function bodies such that we
480381ad6265SDimitry Andric       // might no longer be able to materialize the BlockAddress since the
480481ad6265SDimitry Andric       // BasicBlock (and entire body of the Function) the BlockAddress refers
480581ad6265SDimitry Andric       // to may have been moved. In the case that the user of BitcodeReader
480681ad6265SDimitry Andric       // decides ultimately not to link the Function body, materializing here
480781ad6265SDimitry Andric       // could be considered wasteful, but it's better than a deserialization
480881ad6265SDimitry Andric       // failure as described. This keeps BitcodeReader unaware of complex
480981ad6265SDimitry Andric       // linkage policy decisions such as those use by LTO, leaving those
481081ad6265SDimitry Andric       // decisions "one layer up."
481181ad6265SDimitry Andric       for (uint64_t ValID : Record)
481281ad6265SDimitry Andric         if (auto *F = dyn_cast<Function>(ValueList[ValID]))
481381ad6265SDimitry Andric           BackwardRefFunctions.push_back(F);
481481ad6265SDimitry Andric         else
481581ad6265SDimitry Andric           return error("Invalid record");
481681ad6265SDimitry Andric 
481781ad6265SDimitry Andric       continue;
481881ad6265SDimitry Andric 
48190b57cec5SDimitry Andric     case bitc::FUNC_CODE_DEBUG_LOC_AGAIN:  // DEBUG_LOC_AGAIN
48200b57cec5SDimitry Andric       // This record indicates that the last instruction is at the same
48210b57cec5SDimitry Andric       // location as the previous instruction with a location.
48220b57cec5SDimitry Andric       I = getLastInstruction();
48230b57cec5SDimitry Andric 
48240b57cec5SDimitry Andric       if (!I)
48250b57cec5SDimitry Andric         return error("Invalid record");
48260b57cec5SDimitry Andric       I->setDebugLoc(LastLoc);
48270b57cec5SDimitry Andric       I = nullptr;
48280b57cec5SDimitry Andric       continue;
48290b57cec5SDimitry Andric 
48300b57cec5SDimitry Andric     case bitc::FUNC_CODE_DEBUG_LOC: {      // DEBUG_LOC: [line, col, scope, ia]
48310b57cec5SDimitry Andric       I = getLastInstruction();
48320b57cec5SDimitry Andric       if (!I || Record.size() < 4)
48330b57cec5SDimitry Andric         return error("Invalid record");
48340b57cec5SDimitry Andric 
48350b57cec5SDimitry Andric       unsigned Line = Record[0], Col = Record[1];
48360b57cec5SDimitry Andric       unsigned ScopeID = Record[2], IAID = Record[3];
48370b57cec5SDimitry Andric       bool isImplicitCode = Record.size() == 5 && Record[4];
48380b57cec5SDimitry Andric 
48390b57cec5SDimitry Andric       MDNode *Scope = nullptr, *IA = nullptr;
48400b57cec5SDimitry Andric       if (ScopeID) {
48410b57cec5SDimitry Andric         Scope = dyn_cast_or_null<MDNode>(
48420b57cec5SDimitry Andric             MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1));
48430b57cec5SDimitry Andric         if (!Scope)
48440b57cec5SDimitry Andric           return error("Invalid record");
48450b57cec5SDimitry Andric       }
48460b57cec5SDimitry Andric       if (IAID) {
48470b57cec5SDimitry Andric         IA = dyn_cast_or_null<MDNode>(
48480b57cec5SDimitry Andric             MDLoader->getMetadataFwdRefOrLoad(IAID - 1));
48490b57cec5SDimitry Andric         if (!IA)
48500b57cec5SDimitry Andric           return error("Invalid record");
48510b57cec5SDimitry Andric       }
4852e8d8bef9SDimitry Andric       LastLoc = DILocation::get(Scope->getContext(), Line, Col, Scope, IA,
4853e8d8bef9SDimitry Andric                                 isImplicitCode);
48540b57cec5SDimitry Andric       I->setDebugLoc(LastLoc);
48550b57cec5SDimitry Andric       I = nullptr;
48560b57cec5SDimitry Andric       continue;
48570b57cec5SDimitry Andric     }
48580b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_UNOP: {    // UNOP: [opval, ty, opcode]
48590b57cec5SDimitry Andric       unsigned OpNum = 0;
48600b57cec5SDimitry Andric       Value *LHS;
486181ad6265SDimitry Andric       unsigned TypeID;
486281ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, LHS, TypeID, CurBB) ||
48630b57cec5SDimitry Andric           OpNum+1 > Record.size())
48640b57cec5SDimitry Andric         return error("Invalid record");
48650b57cec5SDimitry Andric 
48660b57cec5SDimitry Andric       int Opc = getDecodedUnaryOpcode(Record[OpNum++], LHS->getType());
48670b57cec5SDimitry Andric       if (Opc == -1)
48680b57cec5SDimitry Andric         return error("Invalid record");
48690b57cec5SDimitry Andric       I = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS);
487081ad6265SDimitry Andric       ResTypeID = TypeID;
48710b57cec5SDimitry Andric       InstructionList.push_back(I);
48720b57cec5SDimitry Andric       if (OpNum < Record.size()) {
48730b57cec5SDimitry Andric         if (isa<FPMathOperator>(I)) {
48740b57cec5SDimitry Andric           FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
48750b57cec5SDimitry Andric           if (FMF.any())
48760b57cec5SDimitry Andric             I->setFastMathFlags(FMF);
48770b57cec5SDimitry Andric         }
48780b57cec5SDimitry Andric       }
48790b57cec5SDimitry Andric       break;
48800b57cec5SDimitry Andric     }
48810b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
48820b57cec5SDimitry Andric       unsigned OpNum = 0;
48830b57cec5SDimitry Andric       Value *LHS, *RHS;
488481ad6265SDimitry Andric       unsigned TypeID;
488581ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, LHS, TypeID, CurBB) ||
488681ad6265SDimitry Andric           popValue(Record, OpNum, NextValueNo, LHS->getType(), TypeID, RHS,
488781ad6265SDimitry Andric                    CurBB) ||
48880b57cec5SDimitry Andric           OpNum+1 > Record.size())
48890b57cec5SDimitry Andric         return error("Invalid record");
48900b57cec5SDimitry Andric 
48910b57cec5SDimitry Andric       int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
48920b57cec5SDimitry Andric       if (Opc == -1)
48930b57cec5SDimitry Andric         return error("Invalid record");
48940b57cec5SDimitry Andric       I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
489581ad6265SDimitry Andric       ResTypeID = TypeID;
48960b57cec5SDimitry Andric       InstructionList.push_back(I);
48970b57cec5SDimitry Andric       if (OpNum < Record.size()) {
48980b57cec5SDimitry Andric         if (Opc == Instruction::Add ||
48990b57cec5SDimitry Andric             Opc == Instruction::Sub ||
49000b57cec5SDimitry Andric             Opc == Instruction::Mul ||
49010b57cec5SDimitry Andric             Opc == Instruction::Shl) {
49020b57cec5SDimitry Andric           if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
49030b57cec5SDimitry Andric             cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
49040b57cec5SDimitry Andric           if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
49050b57cec5SDimitry Andric             cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
49060b57cec5SDimitry Andric         } else if (Opc == Instruction::SDiv ||
49070b57cec5SDimitry Andric                    Opc == Instruction::UDiv ||
49080b57cec5SDimitry Andric                    Opc == Instruction::LShr ||
49090b57cec5SDimitry Andric                    Opc == Instruction::AShr) {
49100b57cec5SDimitry Andric           if (Record[OpNum] & (1 << bitc::PEO_EXACT))
49110b57cec5SDimitry Andric             cast<BinaryOperator>(I)->setIsExact(true);
4912*c9157d92SDimitry Andric         } else if (Opc == Instruction::Or) {
4913*c9157d92SDimitry Andric           if (Record[OpNum] & (1 << bitc::PDI_DISJOINT))
4914*c9157d92SDimitry Andric             cast<PossiblyDisjointInst>(I)->setIsDisjoint(true);
49150b57cec5SDimitry Andric         } else if (isa<FPMathOperator>(I)) {
49160b57cec5SDimitry Andric           FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
49170b57cec5SDimitry Andric           if (FMF.any())
49180b57cec5SDimitry Andric             I->setFastMathFlags(FMF);
49190b57cec5SDimitry Andric         }
49200b57cec5SDimitry Andric       }
49210b57cec5SDimitry Andric       break;
49220b57cec5SDimitry Andric     }
49230b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
49240b57cec5SDimitry Andric       unsigned OpNum = 0;
49250b57cec5SDimitry Andric       Value *Op;
492681ad6265SDimitry Andric       unsigned OpTypeID;
492781ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) ||
4928*c9157d92SDimitry Andric           OpNum + 1 > Record.size())
49290b57cec5SDimitry Andric         return error("Invalid record");
49300b57cec5SDimitry Andric 
4931*c9157d92SDimitry Andric       ResTypeID = Record[OpNum++];
493281ad6265SDimitry Andric       Type *ResTy = getTypeByID(ResTypeID);
4933*c9157d92SDimitry Andric       int Opc = getDecodedCastOpcode(Record[OpNum++]);
4934*c9157d92SDimitry Andric 
49350b57cec5SDimitry Andric       if (Opc == -1 || !ResTy)
49360b57cec5SDimitry Andric         return error("Invalid record");
49370b57cec5SDimitry Andric       Instruction *Temp = nullptr;
49380b57cec5SDimitry Andric       if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
49390b57cec5SDimitry Andric         if (Temp) {
49400b57cec5SDimitry Andric           InstructionList.push_back(Temp);
4941480093f4SDimitry Andric           assert(CurBB && "No current BB?");
4942bdd1243dSDimitry Andric           Temp->insertInto(CurBB, CurBB->end());
49430b57cec5SDimitry Andric         }
49440b57cec5SDimitry Andric       } else {
49450b57cec5SDimitry Andric         auto CastOp = (Instruction::CastOps)Opc;
49460b57cec5SDimitry Andric         if (!CastInst::castIsValid(CastOp, Op, ResTy))
49470b57cec5SDimitry Andric           return error("Invalid cast");
49480b57cec5SDimitry Andric         I = CastInst::Create(CastOp, Op, ResTy);
49490b57cec5SDimitry Andric       }
4950*c9157d92SDimitry Andric       if (OpNum < Record.size() && isa<PossiblyNonNegInst>(I) &&
4951*c9157d92SDimitry Andric           (Record[OpNum] & (1 << bitc::PNNI_NON_NEG)))
4952*c9157d92SDimitry Andric         I->setNonNeg(true);
49530b57cec5SDimitry Andric       InstructionList.push_back(I);
49540b57cec5SDimitry Andric       break;
49550b57cec5SDimitry Andric     }
49560b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
49570b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_GEP_OLD:
49580b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
49590b57cec5SDimitry Andric       unsigned OpNum = 0;
49600b57cec5SDimitry Andric 
496181ad6265SDimitry Andric       unsigned TyID;
49620b57cec5SDimitry Andric       Type *Ty;
49630b57cec5SDimitry Andric       bool InBounds;
49640b57cec5SDimitry Andric 
49650b57cec5SDimitry Andric       if (BitCode == bitc::FUNC_CODE_INST_GEP) {
49660b57cec5SDimitry Andric         InBounds = Record[OpNum++];
496781ad6265SDimitry Andric         TyID = Record[OpNum++];
496881ad6265SDimitry Andric         Ty = getTypeByID(TyID);
49690b57cec5SDimitry Andric       } else {
49700b57cec5SDimitry Andric         InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
497181ad6265SDimitry Andric         TyID = InvalidTypeID;
49720b57cec5SDimitry Andric         Ty = nullptr;
49730b57cec5SDimitry Andric       }
49740b57cec5SDimitry Andric 
49750b57cec5SDimitry Andric       Value *BasePtr;
497681ad6265SDimitry Andric       unsigned BasePtrTypeID;
497781ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr, BasePtrTypeID,
497881ad6265SDimitry Andric                            CurBB))
49790b57cec5SDimitry Andric         return error("Invalid record");
49800b57cec5SDimitry Andric 
49810b57cec5SDimitry Andric       if (!Ty) {
498281ad6265SDimitry Andric         TyID = getContainedTypeID(BasePtrTypeID);
498381ad6265SDimitry Andric         if (BasePtr->getType()->isVectorTy())
498481ad6265SDimitry Andric           TyID = getContainedTypeID(TyID);
498581ad6265SDimitry Andric         Ty = getTypeByID(TyID);
4986fe6060f1SDimitry Andric       }
49870b57cec5SDimitry Andric 
49880b57cec5SDimitry Andric       SmallVector<Value*, 16> GEPIdx;
49890b57cec5SDimitry Andric       while (OpNum != Record.size()) {
49900b57cec5SDimitry Andric         Value *Op;
499181ad6265SDimitry Andric         unsigned OpTypeID;
499281ad6265SDimitry Andric         if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
49930b57cec5SDimitry Andric           return error("Invalid record");
49940b57cec5SDimitry Andric         GEPIdx.push_back(Op);
49950b57cec5SDimitry Andric       }
49960b57cec5SDimitry Andric 
49970b57cec5SDimitry Andric       I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
49980b57cec5SDimitry Andric 
499981ad6265SDimitry Andric       ResTypeID = TyID;
500081ad6265SDimitry Andric       if (cast<GEPOperator>(I)->getNumIndices() != 0) {
500181ad6265SDimitry Andric         auto GTI = std::next(gep_type_begin(I));
500281ad6265SDimitry Andric         for (Value *Idx : drop_begin(cast<GEPOperator>(I)->indices())) {
500381ad6265SDimitry Andric           unsigned SubType = 0;
500481ad6265SDimitry Andric           if (GTI.isStruct()) {
500581ad6265SDimitry Andric             ConstantInt *IdxC =
500681ad6265SDimitry Andric                 Idx->getType()->isVectorTy()
500781ad6265SDimitry Andric                     ? cast<ConstantInt>(cast<Constant>(Idx)->getSplatValue())
500881ad6265SDimitry Andric                     : cast<ConstantInt>(Idx);
500981ad6265SDimitry Andric             SubType = IdxC->getZExtValue();
501081ad6265SDimitry Andric           }
501181ad6265SDimitry Andric           ResTypeID = getContainedTypeID(ResTypeID, SubType);
501281ad6265SDimitry Andric           ++GTI;
501381ad6265SDimitry Andric         }
501481ad6265SDimitry Andric       }
501581ad6265SDimitry Andric 
501681ad6265SDimitry Andric       // At this point ResTypeID is the result element type. We need a pointer
501781ad6265SDimitry Andric       // or vector of pointer to it.
501881ad6265SDimitry Andric       ResTypeID = getVirtualTypeID(I->getType()->getScalarType(), ResTypeID);
501981ad6265SDimitry Andric       if (I->getType()->isVectorTy())
502081ad6265SDimitry Andric         ResTypeID = getVirtualTypeID(I->getType(), ResTypeID);
502181ad6265SDimitry Andric 
50220b57cec5SDimitry Andric       InstructionList.push_back(I);
50230b57cec5SDimitry Andric       if (InBounds)
50240b57cec5SDimitry Andric         cast<GetElementPtrInst>(I)->setIsInBounds(true);
50250b57cec5SDimitry Andric       break;
50260b57cec5SDimitry Andric     }
50270b57cec5SDimitry Andric 
50280b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_EXTRACTVAL: {
50290b57cec5SDimitry Andric                                        // EXTRACTVAL: [opty, opval, n x indices]
50300b57cec5SDimitry Andric       unsigned OpNum = 0;
50310b57cec5SDimitry Andric       Value *Agg;
503281ad6265SDimitry Andric       unsigned AggTypeID;
503381ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
50340b57cec5SDimitry Andric         return error("Invalid record");
5035fe6060f1SDimitry Andric       Type *Ty = Agg->getType();
50360b57cec5SDimitry Andric 
50370b57cec5SDimitry Andric       unsigned RecSize = Record.size();
50380b57cec5SDimitry Andric       if (OpNum == RecSize)
50390b57cec5SDimitry Andric         return error("EXTRACTVAL: Invalid instruction with 0 indices");
50400b57cec5SDimitry Andric 
50410b57cec5SDimitry Andric       SmallVector<unsigned, 4> EXTRACTVALIdx;
504281ad6265SDimitry Andric       ResTypeID = AggTypeID;
50430b57cec5SDimitry Andric       for (; OpNum != RecSize; ++OpNum) {
5044fe6060f1SDimitry Andric         bool IsArray = Ty->isArrayTy();
5045fe6060f1SDimitry Andric         bool IsStruct = Ty->isStructTy();
50460b57cec5SDimitry Andric         uint64_t Index = Record[OpNum];
50470b57cec5SDimitry Andric 
50480b57cec5SDimitry Andric         if (!IsStruct && !IsArray)
50490b57cec5SDimitry Andric           return error("EXTRACTVAL: Invalid type");
50500b57cec5SDimitry Andric         if ((unsigned)Index != Index)
50510b57cec5SDimitry Andric           return error("Invalid value");
5052fe6060f1SDimitry Andric         if (IsStruct && Index >= Ty->getStructNumElements())
50530b57cec5SDimitry Andric           return error("EXTRACTVAL: Invalid struct index");
5054fe6060f1SDimitry Andric         if (IsArray && Index >= Ty->getArrayNumElements())
50550b57cec5SDimitry Andric           return error("EXTRACTVAL: Invalid array index");
50560b57cec5SDimitry Andric         EXTRACTVALIdx.push_back((unsigned)Index);
50570b57cec5SDimitry Andric 
505881ad6265SDimitry Andric         if (IsStruct) {
5059fe6060f1SDimitry Andric           Ty = Ty->getStructElementType(Index);
506081ad6265SDimitry Andric           ResTypeID = getContainedTypeID(ResTypeID, Index);
506181ad6265SDimitry Andric         } else {
5062fe6060f1SDimitry Andric           Ty = Ty->getArrayElementType();
506381ad6265SDimitry Andric           ResTypeID = getContainedTypeID(ResTypeID);
506481ad6265SDimitry Andric         }
50650b57cec5SDimitry Andric       }
50660b57cec5SDimitry Andric 
50670b57cec5SDimitry Andric       I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
50680b57cec5SDimitry Andric       InstructionList.push_back(I);
50690b57cec5SDimitry Andric       break;
50700b57cec5SDimitry Andric     }
50710b57cec5SDimitry Andric 
50720b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_INSERTVAL: {
50730b57cec5SDimitry Andric                            // INSERTVAL: [opty, opval, opty, opval, n x indices]
50740b57cec5SDimitry Andric       unsigned OpNum = 0;
50750b57cec5SDimitry Andric       Value *Agg;
507681ad6265SDimitry Andric       unsigned AggTypeID;
507781ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
50780b57cec5SDimitry Andric         return error("Invalid record");
50790b57cec5SDimitry Andric       Value *Val;
508081ad6265SDimitry Andric       unsigned ValTypeID;
508181ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
50820b57cec5SDimitry Andric         return error("Invalid record");
50830b57cec5SDimitry Andric 
50840b57cec5SDimitry Andric       unsigned RecSize = Record.size();
50850b57cec5SDimitry Andric       if (OpNum == RecSize)
50860b57cec5SDimitry Andric         return error("INSERTVAL: Invalid instruction with 0 indices");
50870b57cec5SDimitry Andric 
50880b57cec5SDimitry Andric       SmallVector<unsigned, 4> INSERTVALIdx;
50890b57cec5SDimitry Andric       Type *CurTy = Agg->getType();
50900b57cec5SDimitry Andric       for (; OpNum != RecSize; ++OpNum) {
50910b57cec5SDimitry Andric         bool IsArray = CurTy->isArrayTy();
50920b57cec5SDimitry Andric         bool IsStruct = CurTy->isStructTy();
50930b57cec5SDimitry Andric         uint64_t Index = Record[OpNum];
50940b57cec5SDimitry Andric 
50950b57cec5SDimitry Andric         if (!IsStruct && !IsArray)
50960b57cec5SDimitry Andric           return error("INSERTVAL: Invalid type");
50970b57cec5SDimitry Andric         if ((unsigned)Index != Index)
50980b57cec5SDimitry Andric           return error("Invalid value");
50990b57cec5SDimitry Andric         if (IsStruct && Index >= CurTy->getStructNumElements())
51000b57cec5SDimitry Andric           return error("INSERTVAL: Invalid struct index");
51010b57cec5SDimitry Andric         if (IsArray && Index >= CurTy->getArrayNumElements())
51020b57cec5SDimitry Andric           return error("INSERTVAL: Invalid array index");
51030b57cec5SDimitry Andric 
51040b57cec5SDimitry Andric         INSERTVALIdx.push_back((unsigned)Index);
51050b57cec5SDimitry Andric         if (IsStruct)
51060b57cec5SDimitry Andric           CurTy = CurTy->getStructElementType(Index);
51070b57cec5SDimitry Andric         else
51080b57cec5SDimitry Andric           CurTy = CurTy->getArrayElementType();
51090b57cec5SDimitry Andric       }
51100b57cec5SDimitry Andric 
51110b57cec5SDimitry Andric       if (CurTy != Val->getType())
51120b57cec5SDimitry Andric         return error("Inserted value type doesn't match aggregate type");
51130b57cec5SDimitry Andric 
51140b57cec5SDimitry Andric       I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
511581ad6265SDimitry Andric       ResTypeID = AggTypeID;
51160b57cec5SDimitry Andric       InstructionList.push_back(I);
51170b57cec5SDimitry Andric       break;
51180b57cec5SDimitry Andric     }
51190b57cec5SDimitry Andric 
51200b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
51210b57cec5SDimitry Andric       // obsolete form of select
51220b57cec5SDimitry Andric       // handles select i1 ... in old bitcode
51230b57cec5SDimitry Andric       unsigned OpNum = 0;
51240b57cec5SDimitry Andric       Value *TrueVal, *FalseVal, *Cond;
512581ad6265SDimitry Andric       unsigned TypeID;
512681ad6265SDimitry Andric       Type *CondType = Type::getInt1Ty(Context);
512781ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, TypeID,
512881ad6265SDimitry Andric                            CurBB) ||
512981ad6265SDimitry Andric           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), TypeID,
513081ad6265SDimitry Andric                    FalseVal, CurBB) ||
513181ad6265SDimitry Andric           popValue(Record, OpNum, NextValueNo, CondType,
513281ad6265SDimitry Andric                    getVirtualTypeID(CondType), Cond, CurBB))
51330b57cec5SDimitry Andric         return error("Invalid record");
51340b57cec5SDimitry Andric 
51350b57cec5SDimitry Andric       I = SelectInst::Create(Cond, TrueVal, FalseVal);
513681ad6265SDimitry Andric       ResTypeID = TypeID;
51370b57cec5SDimitry Andric       InstructionList.push_back(I);
51380b57cec5SDimitry Andric       break;
51390b57cec5SDimitry Andric     }
51400b57cec5SDimitry Andric 
51410b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
51420b57cec5SDimitry Andric       // new form of select
51430b57cec5SDimitry Andric       // handles select i1 or select [N x i1]
51440b57cec5SDimitry Andric       unsigned OpNum = 0;
51450b57cec5SDimitry Andric       Value *TrueVal, *FalseVal, *Cond;
514681ad6265SDimitry Andric       unsigned ValTypeID, CondTypeID;
514781ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, ValTypeID,
514881ad6265SDimitry Andric                            CurBB) ||
514981ad6265SDimitry Andric           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), ValTypeID,
515081ad6265SDimitry Andric                    FalseVal, CurBB) ||
515181ad6265SDimitry Andric           getValueTypePair(Record, OpNum, NextValueNo, Cond, CondTypeID, CurBB))
51520b57cec5SDimitry Andric         return error("Invalid record");
51530b57cec5SDimitry Andric 
51540b57cec5SDimitry Andric       // select condition can be either i1 or [N x i1]
51550b57cec5SDimitry Andric       if (VectorType* vector_type =
51560b57cec5SDimitry Andric           dyn_cast<VectorType>(Cond->getType())) {
51570b57cec5SDimitry Andric         // expect <n x i1>
51580b57cec5SDimitry Andric         if (vector_type->getElementType() != Type::getInt1Ty(Context))
51590b57cec5SDimitry Andric           return error("Invalid type for value");
51600b57cec5SDimitry Andric       } else {
51610b57cec5SDimitry Andric         // expect i1
51620b57cec5SDimitry Andric         if (Cond->getType() != Type::getInt1Ty(Context))
51630b57cec5SDimitry Andric           return error("Invalid type for value");
51640b57cec5SDimitry Andric       }
51650b57cec5SDimitry Andric 
51660b57cec5SDimitry Andric       I = SelectInst::Create(Cond, TrueVal, FalseVal);
516781ad6265SDimitry Andric       ResTypeID = ValTypeID;
51680b57cec5SDimitry Andric       InstructionList.push_back(I);
51690b57cec5SDimitry Andric       if (OpNum < Record.size() && isa<FPMathOperator>(I)) {
51700b57cec5SDimitry Andric         FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
51710b57cec5SDimitry Andric         if (FMF.any())
51720b57cec5SDimitry Andric           I->setFastMathFlags(FMF);
51730b57cec5SDimitry Andric       }
51740b57cec5SDimitry Andric       break;
51750b57cec5SDimitry Andric     }
51760b57cec5SDimitry Andric 
51770b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
51780b57cec5SDimitry Andric       unsigned OpNum = 0;
51790b57cec5SDimitry Andric       Value *Vec, *Idx;
518081ad6265SDimitry Andric       unsigned VecTypeID, IdxTypeID;
518181ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB) ||
518281ad6265SDimitry Andric           getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB))
51830b57cec5SDimitry Andric         return error("Invalid record");
51840b57cec5SDimitry Andric       if (!Vec->getType()->isVectorTy())
51850b57cec5SDimitry Andric         return error("Invalid type for value");
51860b57cec5SDimitry Andric       I = ExtractElementInst::Create(Vec, Idx);
518781ad6265SDimitry Andric       ResTypeID = getContainedTypeID(VecTypeID);
51880b57cec5SDimitry Andric       InstructionList.push_back(I);
51890b57cec5SDimitry Andric       break;
51900b57cec5SDimitry Andric     }
51910b57cec5SDimitry Andric 
51920b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
51930b57cec5SDimitry Andric       unsigned OpNum = 0;
51940b57cec5SDimitry Andric       Value *Vec, *Elt, *Idx;
519581ad6265SDimitry Andric       unsigned VecTypeID, IdxTypeID;
519681ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB))
51970b57cec5SDimitry Andric         return error("Invalid record");
51980b57cec5SDimitry Andric       if (!Vec->getType()->isVectorTy())
51990b57cec5SDimitry Andric         return error("Invalid type for value");
52000b57cec5SDimitry Andric       if (popValue(Record, OpNum, NextValueNo,
520181ad6265SDimitry Andric                    cast<VectorType>(Vec->getType())->getElementType(),
520281ad6265SDimitry Andric                    getContainedTypeID(VecTypeID), Elt, CurBB) ||
520381ad6265SDimitry Andric           getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB))
52040b57cec5SDimitry Andric         return error("Invalid record");
52050b57cec5SDimitry Andric       I = InsertElementInst::Create(Vec, Elt, Idx);
520681ad6265SDimitry Andric       ResTypeID = VecTypeID;
52070b57cec5SDimitry Andric       InstructionList.push_back(I);
52080b57cec5SDimitry Andric       break;
52090b57cec5SDimitry Andric     }
52100b57cec5SDimitry Andric 
52110b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
52120b57cec5SDimitry Andric       unsigned OpNum = 0;
52130b57cec5SDimitry Andric       Value *Vec1, *Vec2, *Mask;
521481ad6265SDimitry Andric       unsigned Vec1TypeID;
521581ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Vec1, Vec1TypeID,
521681ad6265SDimitry Andric                            CurBB) ||
521781ad6265SDimitry Andric           popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec1TypeID,
521881ad6265SDimitry Andric                    Vec2, CurBB))
52190b57cec5SDimitry Andric         return error("Invalid record");
52200b57cec5SDimitry Andric 
522181ad6265SDimitry Andric       unsigned MaskTypeID;
522281ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Mask, MaskTypeID, CurBB))
52230b57cec5SDimitry Andric         return error("Invalid record");
52240b57cec5SDimitry Andric       if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
52250b57cec5SDimitry Andric         return error("Invalid type for value");
52265ffd83dbSDimitry Andric 
52270b57cec5SDimitry Andric       I = new ShuffleVectorInst(Vec1, Vec2, Mask);
522881ad6265SDimitry Andric       ResTypeID =
522981ad6265SDimitry Andric           getVirtualTypeID(I->getType(), getContainedTypeID(Vec1TypeID));
52300b57cec5SDimitry Andric       InstructionList.push_back(I);
52310b57cec5SDimitry Andric       break;
52320b57cec5SDimitry Andric     }
52330b57cec5SDimitry Andric 
52340b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
52350b57cec5SDimitry Andric       // Old form of ICmp/FCmp returning bool
52360b57cec5SDimitry Andric       // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
52370b57cec5SDimitry Andric       // both legal on vectors but had different behaviour.
52380b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
52390b57cec5SDimitry Andric       // FCmp/ICmp returning bool or vector of bool
52400b57cec5SDimitry Andric 
52410b57cec5SDimitry Andric       unsigned OpNum = 0;
52420b57cec5SDimitry Andric       Value *LHS, *RHS;
524381ad6265SDimitry Andric       unsigned LHSTypeID;
524481ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, LHS, LHSTypeID, CurBB) ||
524581ad6265SDimitry Andric           popValue(Record, OpNum, NextValueNo, LHS->getType(), LHSTypeID, RHS,
524681ad6265SDimitry Andric                    CurBB))
52470b57cec5SDimitry Andric         return error("Invalid record");
52480b57cec5SDimitry Andric 
52490b57cec5SDimitry Andric       if (OpNum >= Record.size())
52500b57cec5SDimitry Andric         return error(
52510b57cec5SDimitry Andric             "Invalid record: operand number exceeded available operands");
52520b57cec5SDimitry Andric 
5253*c9157d92SDimitry Andric       CmpInst::Predicate PredVal = CmpInst::Predicate(Record[OpNum]);
52540b57cec5SDimitry Andric       bool IsFP = LHS->getType()->isFPOrFPVectorTy();
52550b57cec5SDimitry Andric       FastMathFlags FMF;
52560b57cec5SDimitry Andric       if (IsFP && Record.size() > OpNum+1)
52570b57cec5SDimitry Andric         FMF = getDecodedFastMathFlags(Record[++OpNum]);
52580b57cec5SDimitry Andric 
52590b57cec5SDimitry Andric       if (OpNum+1 != Record.size())
52600b57cec5SDimitry Andric         return error("Invalid record");
52610b57cec5SDimitry Andric 
5262*c9157d92SDimitry Andric       if (IsFP) {
5263*c9157d92SDimitry Andric         if (!CmpInst::isFPPredicate(PredVal))
5264*c9157d92SDimitry Andric           return error("Invalid fcmp predicate");
5265*c9157d92SDimitry Andric         I = new FCmpInst(PredVal, LHS, RHS);
5266*c9157d92SDimitry Andric       } else {
5267*c9157d92SDimitry Andric         if (!CmpInst::isIntPredicate(PredVal))
5268*c9157d92SDimitry Andric           return error("Invalid icmp predicate");
5269*c9157d92SDimitry Andric         I = new ICmpInst(PredVal, LHS, RHS);
5270*c9157d92SDimitry Andric       }
52710b57cec5SDimitry Andric 
527281ad6265SDimitry Andric       ResTypeID = getVirtualTypeID(I->getType()->getScalarType());
527381ad6265SDimitry Andric       if (LHS->getType()->isVectorTy())
527481ad6265SDimitry Andric         ResTypeID = getVirtualTypeID(I->getType(), ResTypeID);
527581ad6265SDimitry Andric 
52760b57cec5SDimitry Andric       if (FMF.any())
52770b57cec5SDimitry Andric         I->setFastMathFlags(FMF);
52780b57cec5SDimitry Andric       InstructionList.push_back(I);
52790b57cec5SDimitry Andric       break;
52800b57cec5SDimitry Andric     }
52810b57cec5SDimitry Andric 
52820b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
52830b57cec5SDimitry Andric       {
52840b57cec5SDimitry Andric         unsigned Size = Record.size();
52850b57cec5SDimitry Andric         if (Size == 0) {
52860b57cec5SDimitry Andric           I = ReturnInst::Create(Context);
52870b57cec5SDimitry Andric           InstructionList.push_back(I);
52880b57cec5SDimitry Andric           break;
52890b57cec5SDimitry Andric         }
52900b57cec5SDimitry Andric 
52910b57cec5SDimitry Andric         unsigned OpNum = 0;
52920b57cec5SDimitry Andric         Value *Op = nullptr;
529381ad6265SDimitry Andric         unsigned OpTypeID;
529481ad6265SDimitry Andric         if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
52950b57cec5SDimitry Andric           return error("Invalid record");
52960b57cec5SDimitry Andric         if (OpNum != Record.size())
52970b57cec5SDimitry Andric           return error("Invalid record");
52980b57cec5SDimitry Andric 
52990b57cec5SDimitry Andric         I = ReturnInst::Create(Context, Op);
53000b57cec5SDimitry Andric         InstructionList.push_back(I);
53010b57cec5SDimitry Andric         break;
53020b57cec5SDimitry Andric       }
53030b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
53040b57cec5SDimitry Andric       if (Record.size() != 1 && Record.size() != 3)
53050b57cec5SDimitry Andric         return error("Invalid record");
53060b57cec5SDimitry Andric       BasicBlock *TrueDest = getBasicBlock(Record[0]);
53070b57cec5SDimitry Andric       if (!TrueDest)
53080b57cec5SDimitry Andric         return error("Invalid record");
53090b57cec5SDimitry Andric 
53100b57cec5SDimitry Andric       if (Record.size() == 1) {
53110b57cec5SDimitry Andric         I = BranchInst::Create(TrueDest);
53120b57cec5SDimitry Andric         InstructionList.push_back(I);
53130b57cec5SDimitry Andric       }
53140b57cec5SDimitry Andric       else {
53150b57cec5SDimitry Andric         BasicBlock *FalseDest = getBasicBlock(Record[1]);
531681ad6265SDimitry Andric         Type *CondType = Type::getInt1Ty(Context);
531781ad6265SDimitry Andric         Value *Cond = getValue(Record, 2, NextValueNo, CondType,
531881ad6265SDimitry Andric                                getVirtualTypeID(CondType), CurBB);
53190b57cec5SDimitry Andric         if (!FalseDest || !Cond)
53200b57cec5SDimitry Andric           return error("Invalid record");
53210b57cec5SDimitry Andric         I = BranchInst::Create(TrueDest, FalseDest, Cond);
53220b57cec5SDimitry Andric         InstructionList.push_back(I);
53230b57cec5SDimitry Andric       }
53240b57cec5SDimitry Andric       break;
53250b57cec5SDimitry Andric     }
53260b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
53270b57cec5SDimitry Andric       if (Record.size() != 1 && Record.size() != 2)
53280b57cec5SDimitry Andric         return error("Invalid record");
53290b57cec5SDimitry Andric       unsigned Idx = 0;
533081ad6265SDimitry Andric       Type *TokenTy = Type::getTokenTy(Context);
533181ad6265SDimitry Andric       Value *CleanupPad = getValue(Record, Idx++, NextValueNo, TokenTy,
533281ad6265SDimitry Andric                                    getVirtualTypeID(TokenTy), CurBB);
53330b57cec5SDimitry Andric       if (!CleanupPad)
53340b57cec5SDimitry Andric         return error("Invalid record");
53350b57cec5SDimitry Andric       BasicBlock *UnwindDest = nullptr;
53360b57cec5SDimitry Andric       if (Record.size() == 2) {
53370b57cec5SDimitry Andric         UnwindDest = getBasicBlock(Record[Idx++]);
53380b57cec5SDimitry Andric         if (!UnwindDest)
53390b57cec5SDimitry Andric           return error("Invalid record");
53400b57cec5SDimitry Andric       }
53410b57cec5SDimitry Andric 
53420b57cec5SDimitry Andric       I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
53430b57cec5SDimitry Andric       InstructionList.push_back(I);
53440b57cec5SDimitry Andric       break;
53450b57cec5SDimitry Andric     }
53460b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
53470b57cec5SDimitry Andric       if (Record.size() != 2)
53480b57cec5SDimitry Andric         return error("Invalid record");
53490b57cec5SDimitry Andric       unsigned Idx = 0;
535081ad6265SDimitry Andric       Type *TokenTy = Type::getTokenTy(Context);
535181ad6265SDimitry Andric       Value *CatchPad = getValue(Record, Idx++, NextValueNo, TokenTy,
535281ad6265SDimitry Andric                                  getVirtualTypeID(TokenTy), CurBB);
53530b57cec5SDimitry Andric       if (!CatchPad)
53540b57cec5SDimitry Andric         return error("Invalid record");
53550b57cec5SDimitry Andric       BasicBlock *BB = getBasicBlock(Record[Idx++]);
53560b57cec5SDimitry Andric       if (!BB)
53570b57cec5SDimitry Andric         return error("Invalid record");
53580b57cec5SDimitry Andric 
53590b57cec5SDimitry Andric       I = CatchReturnInst::Create(CatchPad, BB);
53600b57cec5SDimitry Andric       InstructionList.push_back(I);
53610b57cec5SDimitry Andric       break;
53620b57cec5SDimitry Andric     }
53630b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
53640b57cec5SDimitry Andric       // We must have, at minimum, the outer scope and the number of arguments.
53650b57cec5SDimitry Andric       if (Record.size() < 2)
53660b57cec5SDimitry Andric         return error("Invalid record");
53670b57cec5SDimitry Andric 
53680b57cec5SDimitry Andric       unsigned Idx = 0;
53690b57cec5SDimitry Andric 
537081ad6265SDimitry Andric       Type *TokenTy = Type::getTokenTy(Context);
537181ad6265SDimitry Andric       Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy,
537281ad6265SDimitry Andric                                   getVirtualTypeID(TokenTy), CurBB);
5373*c9157d92SDimitry Andric       if (!ParentPad)
5374*c9157d92SDimitry Andric         return error("Invalid record");
53750b57cec5SDimitry Andric 
53760b57cec5SDimitry Andric       unsigned NumHandlers = Record[Idx++];
53770b57cec5SDimitry Andric 
53780b57cec5SDimitry Andric       SmallVector<BasicBlock *, 2> Handlers;
53790b57cec5SDimitry Andric       for (unsigned Op = 0; Op != NumHandlers; ++Op) {
53800b57cec5SDimitry Andric         BasicBlock *BB = getBasicBlock(Record[Idx++]);
53810b57cec5SDimitry Andric         if (!BB)
53820b57cec5SDimitry Andric           return error("Invalid record");
53830b57cec5SDimitry Andric         Handlers.push_back(BB);
53840b57cec5SDimitry Andric       }
53850b57cec5SDimitry Andric 
53860b57cec5SDimitry Andric       BasicBlock *UnwindDest = nullptr;
53870b57cec5SDimitry Andric       if (Idx + 1 == Record.size()) {
53880b57cec5SDimitry Andric         UnwindDest = getBasicBlock(Record[Idx++]);
53890b57cec5SDimitry Andric         if (!UnwindDest)
53900b57cec5SDimitry Andric           return error("Invalid record");
53910b57cec5SDimitry Andric       }
53920b57cec5SDimitry Andric 
53930b57cec5SDimitry Andric       if (Record.size() != Idx)
53940b57cec5SDimitry Andric         return error("Invalid record");
53950b57cec5SDimitry Andric 
53960b57cec5SDimitry Andric       auto *CatchSwitch =
53970b57cec5SDimitry Andric           CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
53980b57cec5SDimitry Andric       for (BasicBlock *Handler : Handlers)
53990b57cec5SDimitry Andric         CatchSwitch->addHandler(Handler);
54000b57cec5SDimitry Andric       I = CatchSwitch;
540181ad6265SDimitry Andric       ResTypeID = getVirtualTypeID(I->getType());
54020b57cec5SDimitry Andric       InstructionList.push_back(I);
54030b57cec5SDimitry Andric       break;
54040b57cec5SDimitry Andric     }
54050b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CATCHPAD:
54060b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
54070b57cec5SDimitry Andric       // We must have, at minimum, the outer scope and the number of arguments.
54080b57cec5SDimitry Andric       if (Record.size() < 2)
54090b57cec5SDimitry Andric         return error("Invalid record");
54100b57cec5SDimitry Andric 
54110b57cec5SDimitry Andric       unsigned Idx = 0;
54120b57cec5SDimitry Andric 
541381ad6265SDimitry Andric       Type *TokenTy = Type::getTokenTy(Context);
541481ad6265SDimitry Andric       Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy,
541581ad6265SDimitry Andric                                   getVirtualTypeID(TokenTy), CurBB);
5416*c9157d92SDimitry Andric       if (!ParentPad)
5417*c9157d92SDimitry Andric         return error("Invald record");
54180b57cec5SDimitry Andric 
54190b57cec5SDimitry Andric       unsigned NumArgOperands = Record[Idx++];
54200b57cec5SDimitry Andric 
54210b57cec5SDimitry Andric       SmallVector<Value *, 2> Args;
54220b57cec5SDimitry Andric       for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
54230b57cec5SDimitry Andric         Value *Val;
542481ad6265SDimitry Andric         unsigned ValTypeID;
542581ad6265SDimitry Andric         if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, nullptr))
54260b57cec5SDimitry Andric           return error("Invalid record");
54270b57cec5SDimitry Andric         Args.push_back(Val);
54280b57cec5SDimitry Andric       }
54290b57cec5SDimitry Andric 
54300b57cec5SDimitry Andric       if (Record.size() != Idx)
54310b57cec5SDimitry Andric         return error("Invalid record");
54320b57cec5SDimitry Andric 
54330b57cec5SDimitry Andric       if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
54340b57cec5SDimitry Andric         I = CleanupPadInst::Create(ParentPad, Args);
54350b57cec5SDimitry Andric       else
54360b57cec5SDimitry Andric         I = CatchPadInst::Create(ParentPad, Args);
543781ad6265SDimitry Andric       ResTypeID = getVirtualTypeID(I->getType());
54380b57cec5SDimitry Andric       InstructionList.push_back(I);
54390b57cec5SDimitry Andric       break;
54400b57cec5SDimitry Andric     }
54410b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
54420b57cec5SDimitry Andric       // Check magic
54430b57cec5SDimitry Andric       if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
54440b57cec5SDimitry Andric         // "New" SwitchInst format with case ranges. The changes to write this
54450b57cec5SDimitry Andric         // format were reverted but we still recognize bitcode that uses it.
54460b57cec5SDimitry Andric         // Hopefully someday we will have support for case ranges and can use
54470b57cec5SDimitry Andric         // this format again.
54480b57cec5SDimitry Andric 
544981ad6265SDimitry Andric         unsigned OpTyID = Record[1];
545081ad6265SDimitry Andric         Type *OpTy = getTypeByID(OpTyID);
54510b57cec5SDimitry Andric         unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
54520b57cec5SDimitry Andric 
545381ad6265SDimitry Andric         Value *Cond = getValue(Record, 2, NextValueNo, OpTy, OpTyID, CurBB);
54540b57cec5SDimitry Andric         BasicBlock *Default = getBasicBlock(Record[3]);
54550b57cec5SDimitry Andric         if (!OpTy || !Cond || !Default)
54560b57cec5SDimitry Andric           return error("Invalid record");
54570b57cec5SDimitry Andric 
54580b57cec5SDimitry Andric         unsigned NumCases = Record[4];
54590b57cec5SDimitry Andric 
54600b57cec5SDimitry Andric         SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
54610b57cec5SDimitry Andric         InstructionList.push_back(SI);
54620b57cec5SDimitry Andric 
54630b57cec5SDimitry Andric         unsigned CurIdx = 5;
54640b57cec5SDimitry Andric         for (unsigned i = 0; i != NumCases; ++i) {
54650b57cec5SDimitry Andric           SmallVector<ConstantInt*, 1> CaseVals;
54660b57cec5SDimitry Andric           unsigned NumItems = Record[CurIdx++];
54670b57cec5SDimitry Andric           for (unsigned ci = 0; ci != NumItems; ++ci) {
54680b57cec5SDimitry Andric             bool isSingleNumber = Record[CurIdx++];
54690b57cec5SDimitry Andric 
54700b57cec5SDimitry Andric             APInt Low;
54710b57cec5SDimitry Andric             unsigned ActiveWords = 1;
54720b57cec5SDimitry Andric             if (ValueBitWidth > 64)
54730b57cec5SDimitry Andric               ActiveWords = Record[CurIdx++];
5474bdd1243dSDimitry Andric             Low = readWideAPInt(ArrayRef(&Record[CurIdx], ActiveWords),
54750b57cec5SDimitry Andric                                 ValueBitWidth);
54760b57cec5SDimitry Andric             CurIdx += ActiveWords;
54770b57cec5SDimitry Andric 
54780b57cec5SDimitry Andric             if (!isSingleNumber) {
54790b57cec5SDimitry Andric               ActiveWords = 1;
54800b57cec5SDimitry Andric               if (ValueBitWidth > 64)
54810b57cec5SDimitry Andric                 ActiveWords = Record[CurIdx++];
5482bdd1243dSDimitry Andric               APInt High = readWideAPInt(ArrayRef(&Record[CurIdx], ActiveWords),
5483bdd1243dSDimitry Andric                                          ValueBitWidth);
54840b57cec5SDimitry Andric               CurIdx += ActiveWords;
54850b57cec5SDimitry Andric 
54860b57cec5SDimitry Andric               // FIXME: It is not clear whether values in the range should be
54870b57cec5SDimitry Andric               // compared as signed or unsigned values. The partially
54880b57cec5SDimitry Andric               // implemented changes that used this format in the past used
54890b57cec5SDimitry Andric               // unsigned comparisons.
54900b57cec5SDimitry Andric               for ( ; Low.ule(High); ++Low)
54910b57cec5SDimitry Andric                 CaseVals.push_back(ConstantInt::get(Context, Low));
54920b57cec5SDimitry Andric             } else
54930b57cec5SDimitry Andric               CaseVals.push_back(ConstantInt::get(Context, Low));
54940b57cec5SDimitry Andric           }
54950b57cec5SDimitry Andric           BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
54964824e7fdSDimitry Andric           for (ConstantInt *Cst : CaseVals)
54974824e7fdSDimitry Andric             SI->addCase(Cst, DestBB);
54980b57cec5SDimitry Andric         }
54990b57cec5SDimitry Andric         I = SI;
55000b57cec5SDimitry Andric         break;
55010b57cec5SDimitry Andric       }
55020b57cec5SDimitry Andric 
55030b57cec5SDimitry Andric       // Old SwitchInst format without case ranges.
55040b57cec5SDimitry Andric 
55050b57cec5SDimitry Andric       if (Record.size() < 3 || (Record.size() & 1) == 0)
55060b57cec5SDimitry Andric         return error("Invalid record");
550781ad6265SDimitry Andric       unsigned OpTyID = Record[0];
550881ad6265SDimitry Andric       Type *OpTy = getTypeByID(OpTyID);
550981ad6265SDimitry Andric       Value *Cond = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
55100b57cec5SDimitry Andric       BasicBlock *Default = getBasicBlock(Record[2]);
55110b57cec5SDimitry Andric       if (!OpTy || !Cond || !Default)
55120b57cec5SDimitry Andric         return error("Invalid record");
55130b57cec5SDimitry Andric       unsigned NumCases = (Record.size()-3)/2;
55140b57cec5SDimitry Andric       SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
55150b57cec5SDimitry Andric       InstructionList.push_back(SI);
55160b57cec5SDimitry Andric       for (unsigned i = 0, e = NumCases; i != e; ++i) {
551781ad6265SDimitry Andric         ConstantInt *CaseVal = dyn_cast_or_null<ConstantInt>(
551881ad6265SDimitry Andric             getFnValueByID(Record[3+i*2], OpTy, OpTyID, nullptr));
55190b57cec5SDimitry Andric         BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
55200b57cec5SDimitry Andric         if (!CaseVal || !DestBB) {
55210b57cec5SDimitry Andric           delete SI;
55220b57cec5SDimitry Andric           return error("Invalid record");
55230b57cec5SDimitry Andric         }
55240b57cec5SDimitry Andric         SI->addCase(CaseVal, DestBB);
55250b57cec5SDimitry Andric       }
55260b57cec5SDimitry Andric       I = SI;
55270b57cec5SDimitry Andric       break;
55280b57cec5SDimitry Andric     }
55290b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
55300b57cec5SDimitry Andric       if (Record.size() < 2)
55310b57cec5SDimitry Andric         return error("Invalid record");
553281ad6265SDimitry Andric       unsigned OpTyID = Record[0];
553381ad6265SDimitry Andric       Type *OpTy = getTypeByID(OpTyID);
553481ad6265SDimitry Andric       Value *Address = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
55350b57cec5SDimitry Andric       if (!OpTy || !Address)
55360b57cec5SDimitry Andric         return error("Invalid record");
55370b57cec5SDimitry Andric       unsigned NumDests = Record.size()-2;
55380b57cec5SDimitry Andric       IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
55390b57cec5SDimitry Andric       InstructionList.push_back(IBI);
55400b57cec5SDimitry Andric       for (unsigned i = 0, e = NumDests; i != e; ++i) {
55410b57cec5SDimitry Andric         if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
55420b57cec5SDimitry Andric           IBI->addDestination(DestBB);
55430b57cec5SDimitry Andric         } else {
55440b57cec5SDimitry Andric           delete IBI;
55450b57cec5SDimitry Andric           return error("Invalid record");
55460b57cec5SDimitry Andric         }
55470b57cec5SDimitry Andric       }
55480b57cec5SDimitry Andric       I = IBI;
55490b57cec5SDimitry Andric       break;
55500b57cec5SDimitry Andric     }
55510b57cec5SDimitry Andric 
55520b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_INVOKE: {
55530b57cec5SDimitry Andric       // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
55540b57cec5SDimitry Andric       if (Record.size() < 4)
55550b57cec5SDimitry Andric         return error("Invalid record");
55560b57cec5SDimitry Andric       unsigned OpNum = 0;
55570b57cec5SDimitry Andric       AttributeList PAL = getAttributes(Record[OpNum++]);
55580b57cec5SDimitry Andric       unsigned CCInfo = Record[OpNum++];
55590b57cec5SDimitry Andric       BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
55600b57cec5SDimitry Andric       BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
55610b57cec5SDimitry Andric 
556281ad6265SDimitry Andric       unsigned FTyID = InvalidTypeID;
55630b57cec5SDimitry Andric       FunctionType *FTy = nullptr;
55640b57cec5SDimitry Andric       if ((CCInfo >> 13) & 1) {
556581ad6265SDimitry Andric         FTyID = Record[OpNum++];
556681ad6265SDimitry Andric         FTy = dyn_cast<FunctionType>(getTypeByID(FTyID));
5567fe6060f1SDimitry Andric         if (!FTy)
55680b57cec5SDimitry Andric           return error("Explicit invoke type is not a function type");
55690b57cec5SDimitry Andric       }
55700b57cec5SDimitry Andric 
55710b57cec5SDimitry Andric       Value *Callee;
557281ad6265SDimitry Andric       unsigned CalleeTypeID;
557381ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
557481ad6265SDimitry Andric                            CurBB))
55750b57cec5SDimitry Andric         return error("Invalid record");
55760b57cec5SDimitry Andric 
55770b57cec5SDimitry Andric       PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
55780b57cec5SDimitry Andric       if (!CalleeTy)
55790b57cec5SDimitry Andric         return error("Callee is not a pointer");
55800b57cec5SDimitry Andric       if (!FTy) {
558181ad6265SDimitry Andric         FTyID = getContainedTypeID(CalleeTypeID);
558281ad6265SDimitry Andric         FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
5583fe6060f1SDimitry Andric         if (!FTy)
55840b57cec5SDimitry Andric           return error("Callee is not of pointer to function type");
5585fe013be4SDimitry Andric       }
55860b57cec5SDimitry Andric       if (Record.size() < FTy->getNumParams() + OpNum)
55870b57cec5SDimitry Andric         return error("Insufficient operands to call");
55880b57cec5SDimitry Andric 
55890b57cec5SDimitry Andric       SmallVector<Value*, 16> Ops;
559081ad6265SDimitry Andric       SmallVector<unsigned, 16> ArgTyIDs;
55910b57cec5SDimitry Andric       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
559281ad6265SDimitry Andric         unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
559381ad6265SDimitry Andric         Ops.push_back(getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
559481ad6265SDimitry Andric                                ArgTyID, CurBB));
559581ad6265SDimitry Andric         ArgTyIDs.push_back(ArgTyID);
55960b57cec5SDimitry Andric         if (!Ops.back())
55970b57cec5SDimitry Andric           return error("Invalid record");
55980b57cec5SDimitry Andric       }
55990b57cec5SDimitry Andric 
56000b57cec5SDimitry Andric       if (!FTy->isVarArg()) {
56010b57cec5SDimitry Andric         if (Record.size() != OpNum)
56020b57cec5SDimitry Andric           return error("Invalid record");
56030b57cec5SDimitry Andric       } else {
56040b57cec5SDimitry Andric         // Read type/value pairs for varargs params.
56050b57cec5SDimitry Andric         while (OpNum != Record.size()) {
56060b57cec5SDimitry Andric           Value *Op;
560781ad6265SDimitry Andric           unsigned OpTypeID;
560881ad6265SDimitry Andric           if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
56090b57cec5SDimitry Andric             return error("Invalid record");
56100b57cec5SDimitry Andric           Ops.push_back(Op);
561181ad6265SDimitry Andric           ArgTyIDs.push_back(OpTypeID);
56120b57cec5SDimitry Andric         }
56130b57cec5SDimitry Andric       }
56140b57cec5SDimitry Andric 
561581ad6265SDimitry Andric       // Upgrade the bundles if needed.
561681ad6265SDimitry Andric       if (!OperandBundles.empty())
561781ad6265SDimitry Andric         UpgradeOperandBundles(OperandBundles);
561881ad6265SDimitry Andric 
56190b57cec5SDimitry Andric       I = InvokeInst::Create(FTy, Callee, NormalBB, UnwindBB, Ops,
56200b57cec5SDimitry Andric                              OperandBundles);
562181ad6265SDimitry Andric       ResTypeID = getContainedTypeID(FTyID);
56220b57cec5SDimitry Andric       OperandBundles.clear();
56230b57cec5SDimitry Andric       InstructionList.push_back(I);
56240b57cec5SDimitry Andric       cast<InvokeInst>(I)->setCallingConv(
56250b57cec5SDimitry Andric           static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
56260b57cec5SDimitry Andric       cast<InvokeInst>(I)->setAttributes(PAL);
562781ad6265SDimitry Andric       if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) {
562881ad6265SDimitry Andric         I->deleteValue();
562981ad6265SDimitry Andric         return Err;
563081ad6265SDimitry Andric       }
56310b57cec5SDimitry Andric 
56320b57cec5SDimitry Andric       break;
56330b57cec5SDimitry Andric     }
56340b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
56350b57cec5SDimitry Andric       unsigned Idx = 0;
56360b57cec5SDimitry Andric       Value *Val = nullptr;
563781ad6265SDimitry Andric       unsigned ValTypeID;
563881ad6265SDimitry Andric       if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, CurBB))
56390b57cec5SDimitry Andric         return error("Invalid record");
56400b57cec5SDimitry Andric       I = ResumeInst::Create(Val);
56410b57cec5SDimitry Andric       InstructionList.push_back(I);
56420b57cec5SDimitry Andric       break;
56430b57cec5SDimitry Andric     }
56440b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CALLBR: {
56450b57cec5SDimitry Andric       // CALLBR: [attr, cc, norm, transfs, fty, fnid, args]
56460b57cec5SDimitry Andric       unsigned OpNum = 0;
56470b57cec5SDimitry Andric       AttributeList PAL = getAttributes(Record[OpNum++]);
56480b57cec5SDimitry Andric       unsigned CCInfo = Record[OpNum++];
56490b57cec5SDimitry Andric 
56500b57cec5SDimitry Andric       BasicBlock *DefaultDest = getBasicBlock(Record[OpNum++]);
56510b57cec5SDimitry Andric       unsigned NumIndirectDests = Record[OpNum++];
56520b57cec5SDimitry Andric       SmallVector<BasicBlock *, 16> IndirectDests;
56530b57cec5SDimitry Andric       for (unsigned i = 0, e = NumIndirectDests; i != e; ++i)
56540b57cec5SDimitry Andric         IndirectDests.push_back(getBasicBlock(Record[OpNum++]));
56550b57cec5SDimitry Andric 
565681ad6265SDimitry Andric       unsigned FTyID = InvalidTypeID;
56570b57cec5SDimitry Andric       FunctionType *FTy = nullptr;
56580b57cec5SDimitry Andric       if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) {
565981ad6265SDimitry Andric         FTyID = Record[OpNum++];
566081ad6265SDimitry Andric         FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
5661fe6060f1SDimitry Andric         if (!FTy)
56620b57cec5SDimitry Andric           return error("Explicit call type is not a function type");
56630b57cec5SDimitry Andric       }
56640b57cec5SDimitry Andric 
56650b57cec5SDimitry Andric       Value *Callee;
566681ad6265SDimitry Andric       unsigned CalleeTypeID;
566781ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
566881ad6265SDimitry Andric                            CurBB))
56690b57cec5SDimitry Andric         return error("Invalid record");
56700b57cec5SDimitry Andric 
56710b57cec5SDimitry Andric       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
56720b57cec5SDimitry Andric       if (!OpTy)
56730b57cec5SDimitry Andric         return error("Callee is not a pointer type");
56740b57cec5SDimitry Andric       if (!FTy) {
567581ad6265SDimitry Andric         FTyID = getContainedTypeID(CalleeTypeID);
567681ad6265SDimitry Andric         FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
5677fe6060f1SDimitry Andric         if (!FTy)
56780b57cec5SDimitry Andric           return error("Callee is not of pointer to function type");
5679fe013be4SDimitry Andric       }
56800b57cec5SDimitry Andric       if (Record.size() < FTy->getNumParams() + OpNum)
56810b57cec5SDimitry Andric         return error("Insufficient operands to call");
56820b57cec5SDimitry Andric 
56830b57cec5SDimitry Andric       SmallVector<Value*, 16> Args;
568481ad6265SDimitry Andric       SmallVector<unsigned, 16> ArgTyIDs;
56850b57cec5SDimitry Andric       // Read the fixed params.
56860b57cec5SDimitry Andric       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
568704eeddc0SDimitry Andric         Value *Arg;
568881ad6265SDimitry Andric         unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
56890b57cec5SDimitry Andric         if (FTy->getParamType(i)->isLabelTy())
569004eeddc0SDimitry Andric           Arg = getBasicBlock(Record[OpNum]);
56910b57cec5SDimitry Andric         else
569281ad6265SDimitry Andric           Arg = getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
569381ad6265SDimitry Andric                          ArgTyID, CurBB);
569404eeddc0SDimitry Andric         if (!Arg)
56950b57cec5SDimitry Andric           return error("Invalid record");
569604eeddc0SDimitry Andric         Args.push_back(Arg);
569781ad6265SDimitry Andric         ArgTyIDs.push_back(ArgTyID);
56980b57cec5SDimitry Andric       }
56990b57cec5SDimitry Andric 
57000b57cec5SDimitry Andric       // Read type/value pairs for varargs params.
57010b57cec5SDimitry Andric       if (!FTy->isVarArg()) {
57020b57cec5SDimitry Andric         if (OpNum != Record.size())
57030b57cec5SDimitry Andric           return error("Invalid record");
57040b57cec5SDimitry Andric       } else {
57050b57cec5SDimitry Andric         while (OpNum != Record.size()) {
57060b57cec5SDimitry Andric           Value *Op;
570781ad6265SDimitry Andric           unsigned OpTypeID;
570881ad6265SDimitry Andric           if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
57090b57cec5SDimitry Andric             return error("Invalid record");
57100b57cec5SDimitry Andric           Args.push_back(Op);
571181ad6265SDimitry Andric           ArgTyIDs.push_back(OpTypeID);
57120b57cec5SDimitry Andric         }
57130b57cec5SDimitry Andric       }
57140b57cec5SDimitry Andric 
571581ad6265SDimitry Andric       // Upgrade the bundles if needed.
571681ad6265SDimitry Andric       if (!OperandBundles.empty())
571781ad6265SDimitry Andric         UpgradeOperandBundles(OperandBundles);
571881ad6265SDimitry Andric 
5719fcaf7f86SDimitry Andric       if (auto *IA = dyn_cast<InlineAsm>(Callee)) {
5720fcaf7f86SDimitry Andric         InlineAsm::ConstraintInfoVector ConstraintInfo = IA->ParseConstraints();
5721fcaf7f86SDimitry Andric         auto IsLabelConstraint = [](const InlineAsm::ConstraintInfo &CI) {
5722fcaf7f86SDimitry Andric           return CI.Type == InlineAsm::isLabel;
5723fcaf7f86SDimitry Andric         };
5724fcaf7f86SDimitry Andric         if (none_of(ConstraintInfo, IsLabelConstraint)) {
5725fcaf7f86SDimitry Andric           // Upgrade explicit blockaddress arguments to label constraints.
5726fcaf7f86SDimitry Andric           // Verify that the last arguments are blockaddress arguments that
5727fcaf7f86SDimitry Andric           // match the indirect destinations. Clang always generates callbr
5728fcaf7f86SDimitry Andric           // in this form. We could support reordering with more effort.
5729fcaf7f86SDimitry Andric           unsigned FirstBlockArg = Args.size() - IndirectDests.size();
5730fcaf7f86SDimitry Andric           for (unsigned ArgNo = FirstBlockArg; ArgNo < Args.size(); ++ArgNo) {
5731fcaf7f86SDimitry Andric             unsigned LabelNo = ArgNo - FirstBlockArg;
5732fcaf7f86SDimitry Andric             auto *BA = dyn_cast<BlockAddress>(Args[ArgNo]);
5733fcaf7f86SDimitry Andric             if (!BA || BA->getFunction() != F ||
5734fcaf7f86SDimitry Andric                 LabelNo > IndirectDests.size() ||
5735fcaf7f86SDimitry Andric                 BA->getBasicBlock() != IndirectDests[LabelNo])
5736fcaf7f86SDimitry Andric               return error("callbr argument does not match indirect dest");
5737fcaf7f86SDimitry Andric           }
5738fcaf7f86SDimitry Andric 
5739fcaf7f86SDimitry Andric           // Remove blockaddress arguments.
5740fcaf7f86SDimitry Andric           Args.erase(Args.begin() + FirstBlockArg, Args.end());
5741fcaf7f86SDimitry Andric           ArgTyIDs.erase(ArgTyIDs.begin() + FirstBlockArg, ArgTyIDs.end());
5742fcaf7f86SDimitry Andric 
5743fcaf7f86SDimitry Andric           // Recreate the function type with less arguments.
5744fcaf7f86SDimitry Andric           SmallVector<Type *> ArgTys;
5745fcaf7f86SDimitry Andric           for (Value *Arg : Args)
5746fcaf7f86SDimitry Andric             ArgTys.push_back(Arg->getType());
5747fcaf7f86SDimitry Andric           FTy =
5748fcaf7f86SDimitry Andric               FunctionType::get(FTy->getReturnType(), ArgTys, FTy->isVarArg());
5749fcaf7f86SDimitry Andric 
5750fcaf7f86SDimitry Andric           // Update constraint string to use label constraints.
5751fcaf7f86SDimitry Andric           std::string Constraints = IA->getConstraintString();
5752fcaf7f86SDimitry Andric           unsigned ArgNo = 0;
5753fcaf7f86SDimitry Andric           size_t Pos = 0;
5754fcaf7f86SDimitry Andric           for (const auto &CI : ConstraintInfo) {
5755fcaf7f86SDimitry Andric             if (CI.hasArg()) {
5756fcaf7f86SDimitry Andric               if (ArgNo >= FirstBlockArg)
5757fcaf7f86SDimitry Andric                 Constraints.insert(Pos, "!");
5758fcaf7f86SDimitry Andric               ++ArgNo;
5759fcaf7f86SDimitry Andric             }
5760fcaf7f86SDimitry Andric 
5761fcaf7f86SDimitry Andric             // Go to next constraint in string.
5762fcaf7f86SDimitry Andric             Pos = Constraints.find(',', Pos);
5763fcaf7f86SDimitry Andric             if (Pos == std::string::npos)
5764fcaf7f86SDimitry Andric               break;
5765fcaf7f86SDimitry Andric             ++Pos;
5766fcaf7f86SDimitry Andric           }
5767fcaf7f86SDimitry Andric 
5768fcaf7f86SDimitry Andric           Callee = InlineAsm::get(FTy, IA->getAsmString(), Constraints,
5769fcaf7f86SDimitry Andric                                   IA->hasSideEffects(), IA->isAlignStack(),
5770fcaf7f86SDimitry Andric                                   IA->getDialect(), IA->canThrow());
5771fcaf7f86SDimitry Andric         }
5772fcaf7f86SDimitry Andric       }
5773fcaf7f86SDimitry Andric 
57740b57cec5SDimitry Andric       I = CallBrInst::Create(FTy, Callee, DefaultDest, IndirectDests, Args,
57750b57cec5SDimitry Andric                              OperandBundles);
577681ad6265SDimitry Andric       ResTypeID = getContainedTypeID(FTyID);
57770b57cec5SDimitry Andric       OperandBundles.clear();
57780b57cec5SDimitry Andric       InstructionList.push_back(I);
57790b57cec5SDimitry Andric       cast<CallBrInst>(I)->setCallingConv(
57800b57cec5SDimitry Andric           static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
57810b57cec5SDimitry Andric       cast<CallBrInst>(I)->setAttributes(PAL);
578281ad6265SDimitry Andric       if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) {
578381ad6265SDimitry Andric         I->deleteValue();
578481ad6265SDimitry Andric         return Err;
578581ad6265SDimitry Andric       }
57860b57cec5SDimitry Andric       break;
57870b57cec5SDimitry Andric     }
57880b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
57890b57cec5SDimitry Andric       I = new UnreachableInst(Context);
57900b57cec5SDimitry Andric       InstructionList.push_back(I);
57910b57cec5SDimitry Andric       break;
57920b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
5793e8d8bef9SDimitry Andric       if (Record.empty())
579481ad6265SDimitry Andric         return error("Invalid phi record");
57958bcb0991SDimitry Andric       // The first record specifies the type.
579681ad6265SDimitry Andric       unsigned TyID = Record[0];
579781ad6265SDimitry Andric       Type *Ty = getTypeByID(TyID);
57980b57cec5SDimitry Andric       if (!Ty)
579981ad6265SDimitry Andric         return error("Invalid phi record");
58000b57cec5SDimitry Andric 
58018bcb0991SDimitry Andric       // Phi arguments are pairs of records of [value, basic block].
58028bcb0991SDimitry Andric       // There is an optional final record for fast-math-flags if this phi has a
58038bcb0991SDimitry Andric       // floating-point type.
58048bcb0991SDimitry Andric       size_t NumArgs = (Record.size() - 1) / 2;
58058bcb0991SDimitry Andric       PHINode *PN = PHINode::Create(Ty, NumArgs);
580681ad6265SDimitry Andric       if ((Record.size() - 1) % 2 == 1 && !isa<FPMathOperator>(PN)) {
580781ad6265SDimitry Andric         PN->deleteValue();
580881ad6265SDimitry Andric         return error("Invalid phi record");
580981ad6265SDimitry Andric       }
58100b57cec5SDimitry Andric       InstructionList.push_back(PN);
58110b57cec5SDimitry Andric 
581281ad6265SDimitry Andric       SmallDenseMap<BasicBlock *, Value *> Args;
58138bcb0991SDimitry Andric       for (unsigned i = 0; i != NumArgs; i++) {
581481ad6265SDimitry Andric         BasicBlock *BB = getBasicBlock(Record[i * 2 + 2]);
581581ad6265SDimitry Andric         if (!BB) {
581681ad6265SDimitry Andric           PN->deleteValue();
581781ad6265SDimitry Andric           return error("Invalid phi BB");
581881ad6265SDimitry Andric         }
581981ad6265SDimitry Andric 
582081ad6265SDimitry Andric         // Phi nodes may contain the same predecessor multiple times, in which
582181ad6265SDimitry Andric         // case the incoming value must be identical. Directly reuse the already
582281ad6265SDimitry Andric         // seen value here, to avoid expanding a constant expression multiple
582381ad6265SDimitry Andric         // times.
582481ad6265SDimitry Andric         auto It = Args.find(BB);
582581ad6265SDimitry Andric         if (It != Args.end()) {
582681ad6265SDimitry Andric           PN->addIncoming(It->second, BB);
582781ad6265SDimitry Andric           continue;
582881ad6265SDimitry Andric         }
582981ad6265SDimitry Andric 
583081ad6265SDimitry Andric         // If there already is a block for this edge (from a different phi),
583181ad6265SDimitry Andric         // use it.
583281ad6265SDimitry Andric         BasicBlock *EdgeBB = ConstExprEdgeBBs.lookup({BB, CurBB});
583381ad6265SDimitry Andric         if (!EdgeBB) {
583481ad6265SDimitry Andric           // Otherwise, use a temporary block (that we will discard if it
583581ad6265SDimitry Andric           // turns out to be unnecessary).
583681ad6265SDimitry Andric           if (!PhiConstExprBB)
583781ad6265SDimitry Andric             PhiConstExprBB = BasicBlock::Create(Context, "phi.constexpr", F);
583881ad6265SDimitry Andric           EdgeBB = PhiConstExprBB;
583981ad6265SDimitry Andric         }
584081ad6265SDimitry Andric 
58410b57cec5SDimitry Andric         // With the new function encoding, it is possible that operands have
58420b57cec5SDimitry Andric         // negative IDs (for forward references).  Use a signed VBR
58430b57cec5SDimitry Andric         // representation to keep the encoding small.
584481ad6265SDimitry Andric         Value *V;
58450b57cec5SDimitry Andric         if (UseRelativeIDs)
584681ad6265SDimitry Andric           V = getValueSigned(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
58470b57cec5SDimitry Andric         else
584881ad6265SDimitry Andric           V = getValue(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
584981ad6265SDimitry Andric         if (!V) {
585081ad6265SDimitry Andric           PN->deleteValue();
585181ad6265SDimitry Andric           PhiConstExprBB->eraseFromParent();
585281ad6265SDimitry Andric           return error("Invalid phi record");
585381ad6265SDimitry Andric         }
585481ad6265SDimitry Andric 
585581ad6265SDimitry Andric         if (EdgeBB == PhiConstExprBB && !EdgeBB->empty()) {
585681ad6265SDimitry Andric           ConstExprEdgeBBs.insert({{BB, CurBB}, EdgeBB});
585781ad6265SDimitry Andric           PhiConstExprBB = nullptr;
585881ad6265SDimitry Andric         }
58590b57cec5SDimitry Andric         PN->addIncoming(V, BB);
586081ad6265SDimitry Andric         Args.insert({BB, V});
58610b57cec5SDimitry Andric       }
58620b57cec5SDimitry Andric       I = PN;
586381ad6265SDimitry Andric       ResTypeID = TyID;
58648bcb0991SDimitry Andric 
58658bcb0991SDimitry Andric       // If there are an even number of records, the final record must be FMF.
58668bcb0991SDimitry Andric       if (Record.size() % 2 == 0) {
58678bcb0991SDimitry Andric         assert(isa<FPMathOperator>(I) && "Unexpected phi type");
58688bcb0991SDimitry Andric         FastMathFlags FMF = getDecodedFastMathFlags(Record[Record.size() - 1]);
58698bcb0991SDimitry Andric         if (FMF.any())
58708bcb0991SDimitry Andric           I->setFastMathFlags(FMF);
58718bcb0991SDimitry Andric       }
58728bcb0991SDimitry Andric 
58730b57cec5SDimitry Andric       break;
58740b57cec5SDimitry Andric     }
58750b57cec5SDimitry Andric 
58760b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_LANDINGPAD:
58770b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
58780b57cec5SDimitry Andric       // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
58790b57cec5SDimitry Andric       unsigned Idx = 0;
58800b57cec5SDimitry Andric       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
58810b57cec5SDimitry Andric         if (Record.size() < 3)
58820b57cec5SDimitry Andric           return error("Invalid record");
58830b57cec5SDimitry Andric       } else {
58840b57cec5SDimitry Andric         assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
58850b57cec5SDimitry Andric         if (Record.size() < 4)
58860b57cec5SDimitry Andric           return error("Invalid record");
58870b57cec5SDimitry Andric       }
588881ad6265SDimitry Andric       ResTypeID = Record[Idx++];
588981ad6265SDimitry Andric       Type *Ty = getTypeByID(ResTypeID);
58900b57cec5SDimitry Andric       if (!Ty)
58910b57cec5SDimitry Andric         return error("Invalid record");
58920b57cec5SDimitry Andric       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
58930b57cec5SDimitry Andric         Value *PersFn = nullptr;
589481ad6265SDimitry Andric         unsigned PersFnTypeID;
589581ad6265SDimitry Andric         if (getValueTypePair(Record, Idx, NextValueNo, PersFn, PersFnTypeID,
589681ad6265SDimitry Andric                              nullptr))
58970b57cec5SDimitry Andric           return error("Invalid record");
58980b57cec5SDimitry Andric 
58990b57cec5SDimitry Andric         if (!F->hasPersonalityFn())
59000b57cec5SDimitry Andric           F->setPersonalityFn(cast<Constant>(PersFn));
59010b57cec5SDimitry Andric         else if (F->getPersonalityFn() != cast<Constant>(PersFn))
59020b57cec5SDimitry Andric           return error("Personality function mismatch");
59030b57cec5SDimitry Andric       }
59040b57cec5SDimitry Andric 
59050b57cec5SDimitry Andric       bool IsCleanup = !!Record[Idx++];
59060b57cec5SDimitry Andric       unsigned NumClauses = Record[Idx++];
59070b57cec5SDimitry Andric       LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
59080b57cec5SDimitry Andric       LP->setCleanup(IsCleanup);
59090b57cec5SDimitry Andric       for (unsigned J = 0; J != NumClauses; ++J) {
59100b57cec5SDimitry Andric         LandingPadInst::ClauseType CT =
59110b57cec5SDimitry Andric           LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
59120b57cec5SDimitry Andric         Value *Val;
591381ad6265SDimitry Andric         unsigned ValTypeID;
59140b57cec5SDimitry Andric 
591581ad6265SDimitry Andric         if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID,
591681ad6265SDimitry Andric                              nullptr)) {
59170b57cec5SDimitry Andric           delete LP;
59180b57cec5SDimitry Andric           return error("Invalid record");
59190b57cec5SDimitry Andric         }
59200b57cec5SDimitry Andric 
59210b57cec5SDimitry Andric         assert((CT != LandingPadInst::Catch ||
59220b57cec5SDimitry Andric                 !isa<ArrayType>(Val->getType())) &&
59230b57cec5SDimitry Andric                "Catch clause has a invalid type!");
59240b57cec5SDimitry Andric         assert((CT != LandingPadInst::Filter ||
59250b57cec5SDimitry Andric                 isa<ArrayType>(Val->getType())) &&
59260b57cec5SDimitry Andric                "Filter clause has invalid type!");
59270b57cec5SDimitry Andric         LP->addClause(cast<Constant>(Val));
59280b57cec5SDimitry Andric       }
59290b57cec5SDimitry Andric 
59300b57cec5SDimitry Andric       I = LP;
59310b57cec5SDimitry Andric       InstructionList.push_back(I);
59320b57cec5SDimitry Andric       break;
59330b57cec5SDimitry Andric     }
59340b57cec5SDimitry Andric 
59350b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
593681ad6265SDimitry Andric       if (Record.size() != 4 && Record.size() != 5)
59370b57cec5SDimitry Andric         return error("Invalid record");
5938e8d8bef9SDimitry Andric       using APV = AllocaPackedValues;
5939e8d8bef9SDimitry Andric       const uint64_t Rec = Record[3];
5940e8d8bef9SDimitry Andric       const bool InAlloca = Bitfield::get<APV::UsedWithInAlloca>(Rec);
5941e8d8bef9SDimitry Andric       const bool SwiftError = Bitfield::get<APV::SwiftError>(Rec);
594281ad6265SDimitry Andric       unsigned TyID = Record[0];
594381ad6265SDimitry Andric       Type *Ty = getTypeByID(TyID);
5944e8d8bef9SDimitry Andric       if (!Bitfield::get<APV::ExplicitType>(Rec)) {
594581ad6265SDimitry Andric         TyID = getContainedTypeID(TyID);
594681ad6265SDimitry Andric         Ty = getTypeByID(TyID);
594781ad6265SDimitry Andric         if (!Ty)
594881ad6265SDimitry Andric           return error("Missing element type for old-style alloca");
59490b57cec5SDimitry Andric       }
595081ad6265SDimitry Andric       unsigned OpTyID = Record[1];
595181ad6265SDimitry Andric       Type *OpTy = getTypeByID(OpTyID);
595281ad6265SDimitry Andric       Value *Size = getFnValueByID(Record[2], OpTy, OpTyID, CurBB);
59538bcb0991SDimitry Andric       MaybeAlign Align;
5954349cc55cSDimitry Andric       uint64_t AlignExp =
5955349cc55cSDimitry Andric           Bitfield::get<APV::AlignLower>(Rec) |
5956349cc55cSDimitry Andric           (Bitfield::get<APV::AlignUpper>(Rec) << APV::AlignLower::Bits);
5957349cc55cSDimitry Andric       if (Error Err = parseAlignmentValue(AlignExp, Align)) {
59580b57cec5SDimitry Andric         return Err;
59590b57cec5SDimitry Andric       }
59600b57cec5SDimitry Andric       if (!Ty || !Size)
59610b57cec5SDimitry Andric         return error("Invalid record");
59620b57cec5SDimitry Andric 
59630b57cec5SDimitry Andric       const DataLayout &DL = TheModule->getDataLayout();
596481ad6265SDimitry Andric       unsigned AS = Record.size() == 5 ? Record[4] : DL.getAllocaAddrSpace();
59650b57cec5SDimitry Andric 
59665ffd83dbSDimitry Andric       SmallPtrSet<Type *, 4> Visited;
59675ffd83dbSDimitry Andric       if (!Align && !Ty->isSized(&Visited))
59685ffd83dbSDimitry Andric         return error("alloca of unsized type");
59695ffd83dbSDimitry Andric       if (!Align)
59705ffd83dbSDimitry Andric         Align = DL.getPrefTypeAlign(Ty);
59715ffd83dbSDimitry Andric 
5972*c9157d92SDimitry Andric       if (!Size->getType()->isIntegerTy())
5973*c9157d92SDimitry Andric         return error("alloca element count must have integer type");
5974*c9157d92SDimitry Andric 
59755ffd83dbSDimitry Andric       AllocaInst *AI = new AllocaInst(Ty, AS, Size, *Align);
59760b57cec5SDimitry Andric       AI->setUsedWithInAlloca(InAlloca);
59770b57cec5SDimitry Andric       AI->setSwiftError(SwiftError);
59780b57cec5SDimitry Andric       I = AI;
597981ad6265SDimitry Andric       ResTypeID = getVirtualTypeID(AI->getType(), TyID);
59800b57cec5SDimitry Andric       InstructionList.push_back(I);
59810b57cec5SDimitry Andric       break;
59820b57cec5SDimitry Andric     }
59830b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
59840b57cec5SDimitry Andric       unsigned OpNum = 0;
59850b57cec5SDimitry Andric       Value *Op;
598681ad6265SDimitry Andric       unsigned OpTypeID;
598781ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) ||
59880b57cec5SDimitry Andric           (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
59890b57cec5SDimitry Andric         return error("Invalid record");
59900b57cec5SDimitry Andric 
59910b57cec5SDimitry Andric       if (!isa<PointerType>(Op->getType()))
59920b57cec5SDimitry Andric         return error("Load operand is not a pointer type");
59930b57cec5SDimitry Andric 
59940b57cec5SDimitry Andric       Type *Ty = nullptr;
59950b57cec5SDimitry Andric       if (OpNum + 3 == Record.size()) {
599681ad6265SDimitry Andric         ResTypeID = Record[OpNum++];
599781ad6265SDimitry Andric         Ty = getTypeByID(ResTypeID);
5998fe6060f1SDimitry Andric       } else {
599981ad6265SDimitry Andric         ResTypeID = getContainedTypeID(OpTypeID);
600081ad6265SDimitry Andric         Ty = getTypeByID(ResTypeID);
6001fe6060f1SDimitry Andric       }
60020b57cec5SDimitry Andric 
6003*c9157d92SDimitry Andric       if (!Ty)
6004*c9157d92SDimitry Andric         return error("Missing load type");
6005*c9157d92SDimitry Andric 
60060b57cec5SDimitry Andric       if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
60070b57cec5SDimitry Andric         return Err;
60080b57cec5SDimitry Andric 
60098bcb0991SDimitry Andric       MaybeAlign Align;
60100b57cec5SDimitry Andric       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
60110b57cec5SDimitry Andric         return Err;
60125ffd83dbSDimitry Andric       SmallPtrSet<Type *, 4> Visited;
60135ffd83dbSDimitry Andric       if (!Align && !Ty->isSized(&Visited))
60145ffd83dbSDimitry Andric         return error("load of unsized type");
60155ffd83dbSDimitry Andric       if (!Align)
60165ffd83dbSDimitry Andric         Align = TheModule->getDataLayout().getABITypeAlign(Ty);
60175ffd83dbSDimitry Andric       I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align);
60180b57cec5SDimitry Andric       InstructionList.push_back(I);
60190b57cec5SDimitry Andric       break;
60200b57cec5SDimitry Andric     }
60210b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_LOADATOMIC: {
60220b57cec5SDimitry Andric        // LOADATOMIC: [opty, op, align, vol, ordering, ssid]
60230b57cec5SDimitry Andric       unsigned OpNum = 0;
60240b57cec5SDimitry Andric       Value *Op;
602581ad6265SDimitry Andric       unsigned OpTypeID;
602681ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) ||
60270b57cec5SDimitry Andric           (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
60280b57cec5SDimitry Andric         return error("Invalid record");
60290b57cec5SDimitry Andric 
60300b57cec5SDimitry Andric       if (!isa<PointerType>(Op->getType()))
60310b57cec5SDimitry Andric         return error("Load operand is not a pointer type");
60320b57cec5SDimitry Andric 
60330b57cec5SDimitry Andric       Type *Ty = nullptr;
60340b57cec5SDimitry Andric       if (OpNum + 5 == Record.size()) {
603581ad6265SDimitry Andric         ResTypeID = Record[OpNum++];
603681ad6265SDimitry Andric         Ty = getTypeByID(ResTypeID);
6037fe6060f1SDimitry Andric       } else {
603881ad6265SDimitry Andric         ResTypeID = getContainedTypeID(OpTypeID);
603981ad6265SDimitry Andric         Ty = getTypeByID(ResTypeID);
6040fe6060f1SDimitry Andric       }
60410b57cec5SDimitry Andric 
6042*c9157d92SDimitry Andric       if (!Ty)
6043*c9157d92SDimitry Andric         return error("Missing atomic load type");
6044*c9157d92SDimitry Andric 
60450b57cec5SDimitry Andric       if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
60460b57cec5SDimitry Andric         return Err;
60470b57cec5SDimitry Andric 
60480b57cec5SDimitry Andric       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
60490b57cec5SDimitry Andric       if (Ordering == AtomicOrdering::NotAtomic ||
60500b57cec5SDimitry Andric           Ordering == AtomicOrdering::Release ||
60510b57cec5SDimitry Andric           Ordering == AtomicOrdering::AcquireRelease)
60520b57cec5SDimitry Andric         return error("Invalid record");
60530b57cec5SDimitry Andric       if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
60540b57cec5SDimitry Andric         return error("Invalid record");
60550b57cec5SDimitry Andric       SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
60560b57cec5SDimitry Andric 
60578bcb0991SDimitry Andric       MaybeAlign Align;
60580b57cec5SDimitry Andric       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
60590b57cec5SDimitry Andric         return Err;
60605ffd83dbSDimitry Andric       if (!Align)
60615ffd83dbSDimitry Andric         return error("Alignment missing from atomic load");
60625ffd83dbSDimitry Andric       I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align, Ordering, SSID);
60630b57cec5SDimitry Andric       InstructionList.push_back(I);
60640b57cec5SDimitry Andric       break;
60650b57cec5SDimitry Andric     }
60660b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_STORE:
60670b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
60680b57cec5SDimitry Andric       unsigned OpNum = 0;
60690b57cec5SDimitry Andric       Value *Val, *Ptr;
607081ad6265SDimitry Andric       unsigned PtrTypeID, ValTypeID;
607181ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
607281ad6265SDimitry Andric         return error("Invalid record");
607381ad6265SDimitry Andric 
607481ad6265SDimitry Andric       if (BitCode == bitc::FUNC_CODE_INST_STORE) {
607581ad6265SDimitry Andric         if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
607681ad6265SDimitry Andric           return error("Invalid record");
607781ad6265SDimitry Andric       } else {
607881ad6265SDimitry Andric         ValTypeID = getContainedTypeID(PtrTypeID);
607981ad6265SDimitry Andric         if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
608081ad6265SDimitry Andric                      ValTypeID, Val, CurBB))
608181ad6265SDimitry Andric           return error("Invalid record");
608281ad6265SDimitry Andric       }
608381ad6265SDimitry Andric 
608481ad6265SDimitry Andric       if (OpNum + 2 != Record.size())
60850b57cec5SDimitry Andric         return error("Invalid record");
60860b57cec5SDimitry Andric 
60870b57cec5SDimitry Andric       if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
60880b57cec5SDimitry Andric         return Err;
60898bcb0991SDimitry Andric       MaybeAlign Align;
60900b57cec5SDimitry Andric       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
60910b57cec5SDimitry Andric         return Err;
60925ffd83dbSDimitry Andric       SmallPtrSet<Type *, 4> Visited;
60935ffd83dbSDimitry Andric       if (!Align && !Val->getType()->isSized(&Visited))
60945ffd83dbSDimitry Andric         return error("store of unsized type");
60955ffd83dbSDimitry Andric       if (!Align)
60965ffd83dbSDimitry Andric         Align = TheModule->getDataLayout().getABITypeAlign(Val->getType());
60975ffd83dbSDimitry Andric       I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align);
60980b57cec5SDimitry Andric       InstructionList.push_back(I);
60990b57cec5SDimitry Andric       break;
61000b57cec5SDimitry Andric     }
61010b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_STOREATOMIC:
61020b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
61030b57cec5SDimitry Andric       // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid]
61040b57cec5SDimitry Andric       unsigned OpNum = 0;
61050b57cec5SDimitry Andric       Value *Val, *Ptr;
610681ad6265SDimitry Andric       unsigned PtrTypeID, ValTypeID;
610781ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB) ||
610881ad6265SDimitry Andric           !isa<PointerType>(Ptr->getType()))
610981ad6265SDimitry Andric         return error("Invalid record");
611081ad6265SDimitry Andric       if (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC) {
611181ad6265SDimitry Andric         if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
611281ad6265SDimitry Andric           return error("Invalid record");
611381ad6265SDimitry Andric       } else {
611481ad6265SDimitry Andric         ValTypeID = getContainedTypeID(PtrTypeID);
611581ad6265SDimitry Andric         if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
611681ad6265SDimitry Andric                      ValTypeID, Val, CurBB))
611781ad6265SDimitry Andric           return error("Invalid record");
611881ad6265SDimitry Andric       }
611981ad6265SDimitry Andric 
612081ad6265SDimitry Andric       if (OpNum + 4 != Record.size())
61210b57cec5SDimitry Andric         return error("Invalid record");
61220b57cec5SDimitry Andric 
61230b57cec5SDimitry Andric       if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
61240b57cec5SDimitry Andric         return Err;
61250b57cec5SDimitry Andric       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
61260b57cec5SDimitry Andric       if (Ordering == AtomicOrdering::NotAtomic ||
61270b57cec5SDimitry Andric           Ordering == AtomicOrdering::Acquire ||
61280b57cec5SDimitry Andric           Ordering == AtomicOrdering::AcquireRelease)
61290b57cec5SDimitry Andric         return error("Invalid record");
61300b57cec5SDimitry Andric       SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
61310b57cec5SDimitry Andric       if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
61320b57cec5SDimitry Andric         return error("Invalid record");
61330b57cec5SDimitry Andric 
61348bcb0991SDimitry Andric       MaybeAlign Align;
61350b57cec5SDimitry Andric       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
61360b57cec5SDimitry Andric         return Err;
61375ffd83dbSDimitry Andric       if (!Align)
61385ffd83dbSDimitry Andric         return error("Alignment missing from atomic store");
61395ffd83dbSDimitry Andric       I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align, Ordering, SSID);
61400b57cec5SDimitry Andric       InstructionList.push_back(I);
61410b57cec5SDimitry Andric       break;
61420b57cec5SDimitry Andric     }
6143e8d8bef9SDimitry Andric     case bitc::FUNC_CODE_INST_CMPXCHG_OLD: {
6144e8d8bef9SDimitry Andric       // CMPXCHG_OLD: [ptrty, ptr, cmp, val, vol, ordering, synchscope,
6145e8d8bef9SDimitry Andric       // failure_ordering?, weak?]
6146e8d8bef9SDimitry Andric       const size_t NumRecords = Record.size();
61470b57cec5SDimitry Andric       unsigned OpNum = 0;
6148e8d8bef9SDimitry Andric       Value *Ptr = nullptr;
614981ad6265SDimitry Andric       unsigned PtrTypeID;
615081ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
61510b57cec5SDimitry Andric         return error("Invalid record");
61520b57cec5SDimitry Andric 
61530b57cec5SDimitry Andric       if (!isa<PointerType>(Ptr->getType()))
61540b57cec5SDimitry Andric         return error("Cmpxchg operand is not a pointer type");
61550b57cec5SDimitry Andric 
6156e8d8bef9SDimitry Andric       Value *Cmp = nullptr;
615781ad6265SDimitry Andric       unsigned CmpTypeID = getContainedTypeID(PtrTypeID);
615881ad6265SDimitry Andric       if (popValue(Record, OpNum, NextValueNo, getTypeByID(CmpTypeID),
615981ad6265SDimitry Andric                    CmpTypeID, Cmp, CurBB))
61600b57cec5SDimitry Andric         return error("Invalid record");
6161e8d8bef9SDimitry Andric 
6162e8d8bef9SDimitry Andric       Value *New = nullptr;
616381ad6265SDimitry Andric       if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), CmpTypeID,
616481ad6265SDimitry Andric                    New, CurBB) ||
6165e8d8bef9SDimitry Andric           NumRecords < OpNum + 3 || NumRecords > OpNum + 5)
61660b57cec5SDimitry Andric         return error("Invalid record");
61670b57cec5SDimitry Andric 
6168e8d8bef9SDimitry Andric       const AtomicOrdering SuccessOrdering =
6169e8d8bef9SDimitry Andric           getDecodedOrdering(Record[OpNum + 1]);
61700b57cec5SDimitry Andric       if (SuccessOrdering == AtomicOrdering::NotAtomic ||
61710b57cec5SDimitry Andric           SuccessOrdering == AtomicOrdering::Unordered)
61720b57cec5SDimitry Andric         return error("Invalid record");
6173e8d8bef9SDimitry Andric 
6174e8d8bef9SDimitry Andric       const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
61750b57cec5SDimitry Andric 
61760b57cec5SDimitry Andric       if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
61770b57cec5SDimitry Andric         return Err;
61780b57cec5SDimitry Andric 
6179e8d8bef9SDimitry Andric       const AtomicOrdering FailureOrdering =
6180e8d8bef9SDimitry Andric           NumRecords < 7
6181e8d8bef9SDimitry Andric               ? AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering)
6182e8d8bef9SDimitry Andric               : getDecodedOrdering(Record[OpNum + 3]);
6183e8d8bef9SDimitry Andric 
6184fe6060f1SDimitry Andric       if (FailureOrdering == AtomicOrdering::NotAtomic ||
6185fe6060f1SDimitry Andric           FailureOrdering == AtomicOrdering::Unordered)
6186fe6060f1SDimitry Andric         return error("Invalid record");
6187fe6060f1SDimitry Andric 
6188e8d8bef9SDimitry Andric       const Align Alignment(
61895ffd83dbSDimitry Andric           TheModule->getDataLayout().getTypeStoreSize(Cmp->getType()));
6190e8d8bef9SDimitry Andric 
61915ffd83dbSDimitry Andric       I = new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment, SuccessOrdering,
61925ffd83dbSDimitry Andric                                 FailureOrdering, SSID);
61930b57cec5SDimitry Andric       cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
61940b57cec5SDimitry Andric 
6195e8d8bef9SDimitry Andric       if (NumRecords < 8) {
61960b57cec5SDimitry Andric         // Before weak cmpxchgs existed, the instruction simply returned the
61970b57cec5SDimitry Andric         // value loaded from memory, so bitcode files from that era will be
61980b57cec5SDimitry Andric         // expecting the first component of a modern cmpxchg.
6199bdd1243dSDimitry Andric         I->insertInto(CurBB, CurBB->end());
62000b57cec5SDimitry Andric         I = ExtractValueInst::Create(I, 0);
620181ad6265SDimitry Andric         ResTypeID = CmpTypeID;
62020b57cec5SDimitry Andric       } else {
62030b57cec5SDimitry Andric         cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum + 4]);
620481ad6265SDimitry Andric         unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(Context));
620581ad6265SDimitry Andric         ResTypeID = getVirtualTypeID(I->getType(), {CmpTypeID, I1TypeID});
62060b57cec5SDimitry Andric       }
62070b57cec5SDimitry Andric 
62080b57cec5SDimitry Andric       InstructionList.push_back(I);
62090b57cec5SDimitry Andric       break;
62100b57cec5SDimitry Andric     }
6211e8d8bef9SDimitry Andric     case bitc::FUNC_CODE_INST_CMPXCHG: {
6212e8d8bef9SDimitry Andric       // CMPXCHG: [ptrty, ptr, cmp, val, vol, success_ordering, synchscope,
6213fe6060f1SDimitry Andric       // failure_ordering, weak, align?]
6214e8d8bef9SDimitry Andric       const size_t NumRecords = Record.size();
6215e8d8bef9SDimitry Andric       unsigned OpNum = 0;
6216e8d8bef9SDimitry Andric       Value *Ptr = nullptr;
621781ad6265SDimitry Andric       unsigned PtrTypeID;
621881ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6219e8d8bef9SDimitry Andric         return error("Invalid record");
6220e8d8bef9SDimitry Andric 
6221e8d8bef9SDimitry Andric       if (!isa<PointerType>(Ptr->getType()))
6222e8d8bef9SDimitry Andric         return error("Cmpxchg operand is not a pointer type");
6223e8d8bef9SDimitry Andric 
6224e8d8bef9SDimitry Andric       Value *Cmp = nullptr;
622581ad6265SDimitry Andric       unsigned CmpTypeID;
622681ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Cmp, CmpTypeID, CurBB))
6227e8d8bef9SDimitry Andric         return error("Invalid record");
6228e8d8bef9SDimitry Andric 
6229e8d8bef9SDimitry Andric       Value *Val = nullptr;
623081ad6265SDimitry Andric       if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), CmpTypeID, Val,
623181ad6265SDimitry Andric                    CurBB))
6232e8d8bef9SDimitry Andric         return error("Invalid record");
6233e8d8bef9SDimitry Andric 
6234fe6060f1SDimitry Andric       if (NumRecords < OpNum + 3 || NumRecords > OpNum + 6)
6235fe6060f1SDimitry Andric         return error("Invalid record");
6236fe6060f1SDimitry Andric 
6237fe6060f1SDimitry Andric       const bool IsVol = Record[OpNum];
6238fe6060f1SDimitry Andric 
6239e8d8bef9SDimitry Andric       const AtomicOrdering SuccessOrdering =
6240e8d8bef9SDimitry Andric           getDecodedOrdering(Record[OpNum + 1]);
6241fe6060f1SDimitry Andric       if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
6242fe6060f1SDimitry Andric         return error("Invalid cmpxchg success ordering");
6243e8d8bef9SDimitry Andric 
6244e8d8bef9SDimitry Andric       const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
6245e8d8bef9SDimitry Andric 
6246e8d8bef9SDimitry Andric       if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
6247e8d8bef9SDimitry Andric         return Err;
6248e8d8bef9SDimitry Andric 
6249e8d8bef9SDimitry Andric       const AtomicOrdering FailureOrdering =
6250e8d8bef9SDimitry Andric           getDecodedOrdering(Record[OpNum + 3]);
6251fe6060f1SDimitry Andric       if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
6252fe6060f1SDimitry Andric         return error("Invalid cmpxchg failure ordering");
6253e8d8bef9SDimitry Andric 
6254fe6060f1SDimitry Andric       const bool IsWeak = Record[OpNum + 4];
6255e8d8bef9SDimitry Andric 
6256fe6060f1SDimitry Andric       MaybeAlign Alignment;
6257fe6060f1SDimitry Andric 
6258fe6060f1SDimitry Andric       if (NumRecords == (OpNum + 6)) {
6259fe6060f1SDimitry Andric         if (Error Err = parseAlignmentValue(Record[OpNum + 5], Alignment))
6260fe6060f1SDimitry Andric           return Err;
6261fe6060f1SDimitry Andric       }
6262fe6060f1SDimitry Andric       if (!Alignment)
6263fe6060f1SDimitry Andric         Alignment =
6264fe6060f1SDimitry Andric             Align(TheModule->getDataLayout().getTypeStoreSize(Cmp->getType()));
6265fe6060f1SDimitry Andric 
6266fe6060f1SDimitry Andric       I = new AtomicCmpXchgInst(Ptr, Cmp, Val, *Alignment, SuccessOrdering,
6267e8d8bef9SDimitry Andric                                 FailureOrdering, SSID);
6268fe6060f1SDimitry Andric       cast<AtomicCmpXchgInst>(I)->setVolatile(IsVol);
6269fe6060f1SDimitry Andric       cast<AtomicCmpXchgInst>(I)->setWeak(IsWeak);
6270e8d8bef9SDimitry Andric 
627181ad6265SDimitry Andric       unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(Context));
627281ad6265SDimitry Andric       ResTypeID = getVirtualTypeID(I->getType(), {CmpTypeID, I1TypeID});
627381ad6265SDimitry Andric 
6274e8d8bef9SDimitry Andric       InstructionList.push_back(I);
6275e8d8bef9SDimitry Andric       break;
6276e8d8bef9SDimitry Andric     }
6277fe6060f1SDimitry Andric     case bitc::FUNC_CODE_INST_ATOMICRMW_OLD:
62780b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_ATOMICRMW: {
6279fe6060f1SDimitry Andric       // ATOMICRMW_OLD: [ptrty, ptr, val, op, vol, ordering, ssid, align?]
6280fe6060f1SDimitry Andric       // ATOMICRMW: [ptrty, ptr, valty, val, op, vol, ordering, ssid, align?]
6281fe6060f1SDimitry Andric       const size_t NumRecords = Record.size();
62820b57cec5SDimitry Andric       unsigned OpNum = 0;
6283fe6060f1SDimitry Andric 
6284fe6060f1SDimitry Andric       Value *Ptr = nullptr;
628581ad6265SDimitry Andric       unsigned PtrTypeID;
628681ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
62870b57cec5SDimitry Andric         return error("Invalid record");
6288fe6060f1SDimitry Andric 
6289fe6060f1SDimitry Andric       if (!isa<PointerType>(Ptr->getType()))
6290fe6060f1SDimitry Andric         return error("Invalid record");
6291fe6060f1SDimitry Andric 
6292fe6060f1SDimitry Andric       Value *Val = nullptr;
629381ad6265SDimitry Andric       unsigned ValTypeID = InvalidTypeID;
6294fe6060f1SDimitry Andric       if (BitCode == bitc::FUNC_CODE_INST_ATOMICRMW_OLD) {
629581ad6265SDimitry Andric         ValTypeID = getContainedTypeID(PtrTypeID);
6296fe6060f1SDimitry Andric         if (popValue(Record, OpNum, NextValueNo,
629781ad6265SDimitry Andric                      getTypeByID(ValTypeID), ValTypeID, Val, CurBB))
6298fe6060f1SDimitry Andric           return error("Invalid record");
6299fe6060f1SDimitry Andric       } else {
630081ad6265SDimitry Andric         if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6301fe6060f1SDimitry Andric           return error("Invalid record");
6302fe6060f1SDimitry Andric       }
6303fe6060f1SDimitry Andric 
6304fe6060f1SDimitry Andric       if (!(NumRecords == (OpNum + 4) || NumRecords == (OpNum + 5)))
6305fe6060f1SDimitry Andric         return error("Invalid record");
6306fe6060f1SDimitry Andric 
6307fe6060f1SDimitry Andric       const AtomicRMWInst::BinOp Operation =
6308fe6060f1SDimitry Andric           getDecodedRMWOperation(Record[OpNum]);
63090b57cec5SDimitry Andric       if (Operation < AtomicRMWInst::FIRST_BINOP ||
63100b57cec5SDimitry Andric           Operation > AtomicRMWInst::LAST_BINOP)
63110b57cec5SDimitry Andric         return error("Invalid record");
6312fe6060f1SDimitry Andric 
6313fe6060f1SDimitry Andric       const bool IsVol = Record[OpNum + 1];
6314fe6060f1SDimitry Andric 
6315fe6060f1SDimitry Andric       const AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
63160b57cec5SDimitry Andric       if (Ordering == AtomicOrdering::NotAtomic ||
63170b57cec5SDimitry Andric           Ordering == AtomicOrdering::Unordered)
63180b57cec5SDimitry Andric         return error("Invalid record");
6319fe6060f1SDimitry Andric 
6320fe6060f1SDimitry Andric       const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6321fe6060f1SDimitry Andric 
6322fe6060f1SDimitry Andric       MaybeAlign Alignment;
6323fe6060f1SDimitry Andric 
6324fe6060f1SDimitry Andric       if (NumRecords == (OpNum + 5)) {
6325fe6060f1SDimitry Andric         if (Error Err = parseAlignmentValue(Record[OpNum + 4], Alignment))
6326fe6060f1SDimitry Andric           return Err;
6327fe6060f1SDimitry Andric       }
6328fe6060f1SDimitry Andric 
6329fe6060f1SDimitry Andric       if (!Alignment)
6330fe6060f1SDimitry Andric         Alignment =
6331fe6060f1SDimitry Andric             Align(TheModule->getDataLayout().getTypeStoreSize(Val->getType()));
6332fe6060f1SDimitry Andric 
6333fe6060f1SDimitry Andric       I = new AtomicRMWInst(Operation, Ptr, Val, *Alignment, Ordering, SSID);
633481ad6265SDimitry Andric       ResTypeID = ValTypeID;
6335fe6060f1SDimitry Andric       cast<AtomicRMWInst>(I)->setVolatile(IsVol);
6336fe6060f1SDimitry Andric 
63370b57cec5SDimitry Andric       InstructionList.push_back(I);
63380b57cec5SDimitry Andric       break;
63390b57cec5SDimitry Andric     }
63400b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid]
63410b57cec5SDimitry Andric       if (2 != Record.size())
63420b57cec5SDimitry Andric         return error("Invalid record");
63430b57cec5SDimitry Andric       AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
63440b57cec5SDimitry Andric       if (Ordering == AtomicOrdering::NotAtomic ||
63450b57cec5SDimitry Andric           Ordering == AtomicOrdering::Unordered ||
63460b57cec5SDimitry Andric           Ordering == AtomicOrdering::Monotonic)
63470b57cec5SDimitry Andric         return error("Invalid record");
63480b57cec5SDimitry Andric       SyncScope::ID SSID = getDecodedSyncScopeID(Record[1]);
63490b57cec5SDimitry Andric       I = new FenceInst(Context, Ordering, SSID);
63500b57cec5SDimitry Andric       InstructionList.push_back(I);
63510b57cec5SDimitry Andric       break;
63520b57cec5SDimitry Andric     }
63530b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CALL: {
63540b57cec5SDimitry Andric       // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
63550b57cec5SDimitry Andric       if (Record.size() < 3)
63560b57cec5SDimitry Andric         return error("Invalid record");
63570b57cec5SDimitry Andric 
63580b57cec5SDimitry Andric       unsigned OpNum = 0;
63590b57cec5SDimitry Andric       AttributeList PAL = getAttributes(Record[OpNum++]);
63600b57cec5SDimitry Andric       unsigned CCInfo = Record[OpNum++];
63610b57cec5SDimitry Andric 
63620b57cec5SDimitry Andric       FastMathFlags FMF;
63630b57cec5SDimitry Andric       if ((CCInfo >> bitc::CALL_FMF) & 1) {
63640b57cec5SDimitry Andric         FMF = getDecodedFastMathFlags(Record[OpNum++]);
63650b57cec5SDimitry Andric         if (!FMF.any())
63660b57cec5SDimitry Andric           return error("Fast math flags indicator set for call with no FMF");
63670b57cec5SDimitry Andric       }
63680b57cec5SDimitry Andric 
636981ad6265SDimitry Andric       unsigned FTyID = InvalidTypeID;
63700b57cec5SDimitry Andric       FunctionType *FTy = nullptr;
63710b57cec5SDimitry Andric       if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) {
637281ad6265SDimitry Andric         FTyID = Record[OpNum++];
637381ad6265SDimitry Andric         FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
6374fe6060f1SDimitry Andric         if (!FTy)
63750b57cec5SDimitry Andric           return error("Explicit call type is not a function type");
63760b57cec5SDimitry Andric       }
63770b57cec5SDimitry Andric 
63780b57cec5SDimitry Andric       Value *Callee;
637981ad6265SDimitry Andric       unsigned CalleeTypeID;
638081ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
638181ad6265SDimitry Andric                            CurBB))
63820b57cec5SDimitry Andric         return error("Invalid record");
63830b57cec5SDimitry Andric 
63840b57cec5SDimitry Andric       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
63850b57cec5SDimitry Andric       if (!OpTy)
63860b57cec5SDimitry Andric         return error("Callee is not a pointer type");
63870b57cec5SDimitry Andric       if (!FTy) {
638881ad6265SDimitry Andric         FTyID = getContainedTypeID(CalleeTypeID);
638981ad6265SDimitry Andric         FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
6390fe6060f1SDimitry Andric         if (!FTy)
63910b57cec5SDimitry Andric           return error("Callee is not of pointer to function type");
6392fe013be4SDimitry Andric       }
63930b57cec5SDimitry Andric       if (Record.size() < FTy->getNumParams() + OpNum)
63940b57cec5SDimitry Andric         return error("Insufficient operands to call");
63950b57cec5SDimitry Andric 
63960b57cec5SDimitry Andric       SmallVector<Value*, 16> Args;
639781ad6265SDimitry Andric       SmallVector<unsigned, 16> ArgTyIDs;
63980b57cec5SDimitry Andric       // Read the fixed params.
63990b57cec5SDimitry Andric       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
640081ad6265SDimitry Andric         unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
64010b57cec5SDimitry Andric         if (FTy->getParamType(i)->isLabelTy())
64020b57cec5SDimitry Andric           Args.push_back(getBasicBlock(Record[OpNum]));
64030b57cec5SDimitry Andric         else
64040b57cec5SDimitry Andric           Args.push_back(getValue(Record, OpNum, NextValueNo,
640581ad6265SDimitry Andric                                   FTy->getParamType(i), ArgTyID, CurBB));
640681ad6265SDimitry Andric         ArgTyIDs.push_back(ArgTyID);
64070b57cec5SDimitry Andric         if (!Args.back())
64080b57cec5SDimitry Andric           return error("Invalid record");
64090b57cec5SDimitry Andric       }
64100b57cec5SDimitry Andric 
64110b57cec5SDimitry Andric       // Read type/value pairs for varargs params.
64120b57cec5SDimitry Andric       if (!FTy->isVarArg()) {
64130b57cec5SDimitry Andric         if (OpNum != Record.size())
64140b57cec5SDimitry Andric           return error("Invalid record");
64150b57cec5SDimitry Andric       } else {
64160b57cec5SDimitry Andric         while (OpNum != Record.size()) {
64170b57cec5SDimitry Andric           Value *Op;
641881ad6265SDimitry Andric           unsigned OpTypeID;
641981ad6265SDimitry Andric           if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
64200b57cec5SDimitry Andric             return error("Invalid record");
64210b57cec5SDimitry Andric           Args.push_back(Op);
642281ad6265SDimitry Andric           ArgTyIDs.push_back(OpTypeID);
64230b57cec5SDimitry Andric         }
64240b57cec5SDimitry Andric       }
64250b57cec5SDimitry Andric 
642681ad6265SDimitry Andric       // Upgrade the bundles if needed.
642781ad6265SDimitry Andric       if (!OperandBundles.empty())
642881ad6265SDimitry Andric         UpgradeOperandBundles(OperandBundles);
642981ad6265SDimitry Andric 
64300b57cec5SDimitry Andric       I = CallInst::Create(FTy, Callee, Args, OperandBundles);
643181ad6265SDimitry Andric       ResTypeID = getContainedTypeID(FTyID);
64320b57cec5SDimitry Andric       OperandBundles.clear();
64330b57cec5SDimitry Andric       InstructionList.push_back(I);
64340b57cec5SDimitry Andric       cast<CallInst>(I)->setCallingConv(
64350b57cec5SDimitry Andric           static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
64360b57cec5SDimitry Andric       CallInst::TailCallKind TCK = CallInst::TCK_None;
6437*c9157d92SDimitry Andric       if (CCInfo & (1 << bitc::CALL_TAIL))
64380b57cec5SDimitry Andric         TCK = CallInst::TCK_Tail;
64390b57cec5SDimitry Andric       if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
64400b57cec5SDimitry Andric         TCK = CallInst::TCK_MustTail;
64410b57cec5SDimitry Andric       if (CCInfo & (1 << bitc::CALL_NOTAIL))
64420b57cec5SDimitry Andric         TCK = CallInst::TCK_NoTail;
64430b57cec5SDimitry Andric       cast<CallInst>(I)->setTailCallKind(TCK);
64440b57cec5SDimitry Andric       cast<CallInst>(I)->setAttributes(PAL);
644581ad6265SDimitry Andric       if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) {
644681ad6265SDimitry Andric         I->deleteValue();
644781ad6265SDimitry Andric         return Err;
644881ad6265SDimitry Andric       }
64490b57cec5SDimitry Andric       if (FMF.any()) {
64500b57cec5SDimitry Andric         if (!isa<FPMathOperator>(I))
64510b57cec5SDimitry Andric           return error("Fast-math-flags specified for call without "
64520b57cec5SDimitry Andric                        "floating-point scalar or vector return type");
64530b57cec5SDimitry Andric         I->setFastMathFlags(FMF);
64540b57cec5SDimitry Andric       }
64550b57cec5SDimitry Andric       break;
64560b57cec5SDimitry Andric     }
64570b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
64580b57cec5SDimitry Andric       if (Record.size() < 3)
64590b57cec5SDimitry Andric         return error("Invalid record");
646081ad6265SDimitry Andric       unsigned OpTyID = Record[0];
646181ad6265SDimitry Andric       Type *OpTy = getTypeByID(OpTyID);
646281ad6265SDimitry Andric       Value *Op = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
646381ad6265SDimitry Andric       ResTypeID = Record[2];
646481ad6265SDimitry Andric       Type *ResTy = getTypeByID(ResTypeID);
64650b57cec5SDimitry Andric       if (!OpTy || !Op || !ResTy)
64660b57cec5SDimitry Andric         return error("Invalid record");
64670b57cec5SDimitry Andric       I = new VAArgInst(Op, ResTy);
64680b57cec5SDimitry Andric       InstructionList.push_back(I);
64690b57cec5SDimitry Andric       break;
64700b57cec5SDimitry Andric     }
64710b57cec5SDimitry Andric 
64720b57cec5SDimitry Andric     case bitc::FUNC_CODE_OPERAND_BUNDLE: {
64730b57cec5SDimitry Andric       // A call or an invoke can be optionally prefixed with some variable
64740b57cec5SDimitry Andric       // number of operand bundle blocks.  These blocks are read into
64750b57cec5SDimitry Andric       // OperandBundles and consumed at the next call or invoke instruction.
64760b57cec5SDimitry Andric 
6477e8d8bef9SDimitry Andric       if (Record.empty() || Record[0] >= BundleTags.size())
64780b57cec5SDimitry Andric         return error("Invalid record");
64790b57cec5SDimitry Andric 
64800b57cec5SDimitry Andric       std::vector<Value *> Inputs;
64810b57cec5SDimitry Andric 
64820b57cec5SDimitry Andric       unsigned OpNum = 1;
64830b57cec5SDimitry Andric       while (OpNum != Record.size()) {
64840b57cec5SDimitry Andric         Value *Op;
648581ad6265SDimitry Andric         unsigned OpTypeID;
648681ad6265SDimitry Andric         if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
64870b57cec5SDimitry Andric           return error("Invalid record");
64880b57cec5SDimitry Andric         Inputs.push_back(Op);
64890b57cec5SDimitry Andric       }
64900b57cec5SDimitry Andric 
64910b57cec5SDimitry Andric       OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
64920b57cec5SDimitry Andric       continue;
64930b57cec5SDimitry Andric     }
6494480093f4SDimitry Andric 
6495480093f4SDimitry Andric     case bitc::FUNC_CODE_INST_FREEZE: { // FREEZE: [opty,opval]
6496480093f4SDimitry Andric       unsigned OpNum = 0;
6497480093f4SDimitry Andric       Value *Op = nullptr;
649881ad6265SDimitry Andric       unsigned OpTypeID;
649981ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
6500480093f4SDimitry Andric         return error("Invalid record");
6501480093f4SDimitry Andric       if (OpNum != Record.size())
6502480093f4SDimitry Andric         return error("Invalid record");
6503480093f4SDimitry Andric 
6504480093f4SDimitry Andric       I = new FreezeInst(Op);
650581ad6265SDimitry Andric       ResTypeID = OpTypeID;
6506480093f4SDimitry Andric       InstructionList.push_back(I);
6507480093f4SDimitry Andric       break;
6508480093f4SDimitry Andric     }
65090b57cec5SDimitry Andric     }
65100b57cec5SDimitry Andric 
65110b57cec5SDimitry Andric     // Add instruction to end of current BB.  If there is no current BB, reject
65120b57cec5SDimitry Andric     // this file.
65130b57cec5SDimitry Andric     if (!CurBB) {
65140b57cec5SDimitry Andric       I->deleteValue();
65150b57cec5SDimitry Andric       return error("Invalid instruction with no BB");
65160b57cec5SDimitry Andric     }
65170b57cec5SDimitry Andric     if (!OperandBundles.empty()) {
65180b57cec5SDimitry Andric       I->deleteValue();
65190b57cec5SDimitry Andric       return error("Operand bundles found with no consumer");
65200b57cec5SDimitry Andric     }
6521bdd1243dSDimitry Andric     I->insertInto(CurBB, CurBB->end());
65220b57cec5SDimitry Andric 
65230b57cec5SDimitry Andric     // If this was a terminator instruction, move to the next block.
65240b57cec5SDimitry Andric     if (I->isTerminator()) {
65250b57cec5SDimitry Andric       ++CurBBNo;
65260b57cec5SDimitry Andric       CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
65270b57cec5SDimitry Andric     }
65280b57cec5SDimitry Andric 
65290b57cec5SDimitry Andric     // Non-void values get registered in the value table for future use.
653081ad6265SDimitry Andric     if (!I->getType()->isVoidTy()) {
653181ad6265SDimitry Andric       assert(I->getType() == getTypeByID(ResTypeID) &&
653281ad6265SDimitry Andric              "Incorrect result type ID");
653381ad6265SDimitry Andric       if (Error Err = ValueList.assignValue(NextValueNo++, I, ResTypeID))
653481ad6265SDimitry Andric         return Err;
653581ad6265SDimitry Andric     }
65360b57cec5SDimitry Andric   }
65370b57cec5SDimitry Andric 
65380b57cec5SDimitry Andric OutOfRecordLoop:
65390b57cec5SDimitry Andric 
65400b57cec5SDimitry Andric   if (!OperandBundles.empty())
65410b57cec5SDimitry Andric     return error("Operand bundles found with no consumer");
65420b57cec5SDimitry Andric 
65430b57cec5SDimitry Andric   // Check the function list for unresolved values.
65440b57cec5SDimitry Andric   if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
65450b57cec5SDimitry Andric     if (!A->getParent()) {
65460b57cec5SDimitry Andric       // We found at least one unresolved value.  Nuke them all to avoid leaks.
65470b57cec5SDimitry Andric       for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
65480b57cec5SDimitry Andric         if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
6549bdd1243dSDimitry Andric           A->replaceAllUsesWith(PoisonValue::get(A->getType()));
65500b57cec5SDimitry Andric           delete A;
65510b57cec5SDimitry Andric         }
65520b57cec5SDimitry Andric       }
65530b57cec5SDimitry Andric       return error("Never resolved value found in function");
65540b57cec5SDimitry Andric     }
65550b57cec5SDimitry Andric   }
65560b57cec5SDimitry Andric 
65570b57cec5SDimitry Andric   // Unexpected unresolved metadata about to be dropped.
65580b57cec5SDimitry Andric   if (MDLoader->hasFwdRefs())
65590b57cec5SDimitry Andric     return error("Invalid function metadata: outgoing forward refs");
65600b57cec5SDimitry Andric 
656181ad6265SDimitry Andric   if (PhiConstExprBB)
656281ad6265SDimitry Andric     PhiConstExprBB->eraseFromParent();
656381ad6265SDimitry Andric 
656481ad6265SDimitry Andric   for (const auto &Pair : ConstExprEdgeBBs) {
656581ad6265SDimitry Andric     BasicBlock *From = Pair.first.first;
656681ad6265SDimitry Andric     BasicBlock *To = Pair.first.second;
656781ad6265SDimitry Andric     BasicBlock *EdgeBB = Pair.second;
656881ad6265SDimitry Andric     BranchInst::Create(To, EdgeBB);
656981ad6265SDimitry Andric     From->getTerminator()->replaceSuccessorWith(To, EdgeBB);
657081ad6265SDimitry Andric     To->replacePhiUsesWith(From, EdgeBB);
657181ad6265SDimitry Andric     EdgeBB->moveBefore(To);
657281ad6265SDimitry Andric   }
657381ad6265SDimitry Andric 
65740b57cec5SDimitry Andric   // Trim the value list down to the size it was before we parsed this function.
65750b57cec5SDimitry Andric   ValueList.shrinkTo(ModuleValueListSize);
65760b57cec5SDimitry Andric   MDLoader->shrinkTo(ModuleMDLoaderSize);
65770b57cec5SDimitry Andric   std::vector<BasicBlock*>().swap(FunctionBBs);
65780b57cec5SDimitry Andric   return Error::success();
65790b57cec5SDimitry Andric }
65800b57cec5SDimitry Andric 
65810b57cec5SDimitry Andric /// Find the function body in the bitcode stream
65820b57cec5SDimitry Andric Error BitcodeReader::findFunctionInStream(
65830b57cec5SDimitry Andric     Function *F,
65840b57cec5SDimitry Andric     DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
65850b57cec5SDimitry Andric   while (DeferredFunctionInfoIterator->second == 0) {
65860b57cec5SDimitry Andric     // This is the fallback handling for the old format bitcode that
65870b57cec5SDimitry Andric     // didn't contain the function index in the VST, or when we have
65880b57cec5SDimitry Andric     // an anonymous function which would not have a VST entry.
65890b57cec5SDimitry Andric     // Assert that we have one of those two cases.
65900b57cec5SDimitry Andric     assert(VSTOffset == 0 || !F->hasName());
65910b57cec5SDimitry Andric     // Parse the next body in the stream and set its position in the
65920b57cec5SDimitry Andric     // DeferredFunctionInfo map.
65930b57cec5SDimitry Andric     if (Error Err = rememberAndSkipFunctionBodies())
65940b57cec5SDimitry Andric       return Err;
65950b57cec5SDimitry Andric   }
65960b57cec5SDimitry Andric   return Error::success();
65970b57cec5SDimitry Andric }
65980b57cec5SDimitry Andric 
65990b57cec5SDimitry Andric SyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) {
66000b57cec5SDimitry Andric   if (Val == SyncScope::SingleThread || Val == SyncScope::System)
66010b57cec5SDimitry Andric     return SyncScope::ID(Val);
66020b57cec5SDimitry Andric   if (Val >= SSIDs.size())
66030b57cec5SDimitry Andric     return SyncScope::System; // Map unknown synchronization scopes to system.
66040b57cec5SDimitry Andric   return SSIDs[Val];
66050b57cec5SDimitry Andric }
66060b57cec5SDimitry Andric 
66070b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
66080b57cec5SDimitry Andric // GVMaterializer implementation
66090b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
66100b57cec5SDimitry Andric 
66110b57cec5SDimitry Andric Error BitcodeReader::materialize(GlobalValue *GV) {
66120b57cec5SDimitry Andric   Function *F = dyn_cast<Function>(GV);
66130b57cec5SDimitry Andric   // If it's not a function or is already material, ignore the request.
66140b57cec5SDimitry Andric   if (!F || !F->isMaterializable())
66150b57cec5SDimitry Andric     return Error::success();
66160b57cec5SDimitry Andric 
66170b57cec5SDimitry Andric   DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
66180b57cec5SDimitry Andric   assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
66190b57cec5SDimitry Andric   // If its position is recorded as 0, its body is somewhere in the stream
66200b57cec5SDimitry Andric   // but we haven't seen it yet.
66210b57cec5SDimitry Andric   if (DFII->second == 0)
66220b57cec5SDimitry Andric     if (Error Err = findFunctionInStream(F, DFII))
66230b57cec5SDimitry Andric       return Err;
66240b57cec5SDimitry Andric 
66250b57cec5SDimitry Andric   // Materialize metadata before parsing any function bodies.
66260b57cec5SDimitry Andric   if (Error Err = materializeMetadata())
66270b57cec5SDimitry Andric     return Err;
66280b57cec5SDimitry Andric 
66290b57cec5SDimitry Andric   // Move the bit stream to the saved position of the deferred function body.
66300b57cec5SDimitry Andric   if (Error JumpFailed = Stream.JumpToBit(DFII->second))
66310b57cec5SDimitry Andric     return JumpFailed;
66320b57cec5SDimitry Andric   if (Error Err = parseFunctionBody(F))
66330b57cec5SDimitry Andric     return Err;
66340b57cec5SDimitry Andric   F->setIsMaterializable(false);
66350b57cec5SDimitry Andric 
66360b57cec5SDimitry Andric   if (StripDebugInfo)
66370b57cec5SDimitry Andric     stripDebugInfo(*F);
66380b57cec5SDimitry Andric 
66390b57cec5SDimitry Andric   // Upgrade any old intrinsic calls in the function.
66400b57cec5SDimitry Andric   for (auto &I : UpgradedIntrinsics) {
6641349cc55cSDimitry Andric     for (User *U : llvm::make_early_inc_range(I.first->materialized_users()))
66420b57cec5SDimitry Andric       if (CallInst *CI = dyn_cast<CallInst>(U))
66430b57cec5SDimitry Andric         UpgradeIntrinsicCall(CI, I.second);
66440b57cec5SDimitry Andric   }
66450b57cec5SDimitry Andric 
66460b57cec5SDimitry Andric   // Finish fn->subprogram upgrade for materialized functions.
66470b57cec5SDimitry Andric   if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F))
66480b57cec5SDimitry Andric     F->setSubprogram(SP);
66490b57cec5SDimitry Andric 
66500b57cec5SDimitry Andric   // Check if the TBAA Metadata are valid, otherwise we will need to strip them.
66510b57cec5SDimitry Andric   if (!MDLoader->isStrippingTBAA()) {
66520b57cec5SDimitry Andric     for (auto &I : instructions(F)) {
66530b57cec5SDimitry Andric       MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa);
66540b57cec5SDimitry Andric       if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA))
66550b57cec5SDimitry Andric         continue;
66560b57cec5SDimitry Andric       MDLoader->setStripTBAA(true);
66570b57cec5SDimitry Andric       stripTBAA(F->getParent());
66580b57cec5SDimitry Andric     }
66590b57cec5SDimitry Andric   }
66600b57cec5SDimitry Andric 
6661e8d8bef9SDimitry Andric   for (auto &I : instructions(F)) {
6662fe6060f1SDimitry Andric     // "Upgrade" older incorrect branch weights by dropping them.
6663e8d8bef9SDimitry Andric     if (auto *MD = I.getMetadata(LLVMContext::MD_prof)) {
6664e8d8bef9SDimitry Andric       if (MD->getOperand(0) != nullptr && isa<MDString>(MD->getOperand(0))) {
6665e8d8bef9SDimitry Andric         MDString *MDS = cast<MDString>(MD->getOperand(0));
6666e8d8bef9SDimitry Andric         StringRef ProfName = MDS->getString();
6667e8d8bef9SDimitry Andric         // Check consistency of !prof branch_weights metadata.
6668e8d8bef9SDimitry Andric         if (!ProfName.equals("branch_weights"))
6669e8d8bef9SDimitry Andric           continue;
6670e8d8bef9SDimitry Andric         unsigned ExpectedNumOperands = 0;
6671e8d8bef9SDimitry Andric         if (BranchInst *BI = dyn_cast<BranchInst>(&I))
6672e8d8bef9SDimitry Andric           ExpectedNumOperands = BI->getNumSuccessors();
6673e8d8bef9SDimitry Andric         else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I))
6674e8d8bef9SDimitry Andric           ExpectedNumOperands = SI->getNumSuccessors();
6675e8d8bef9SDimitry Andric         else if (isa<CallInst>(&I))
6676e8d8bef9SDimitry Andric           ExpectedNumOperands = 1;
6677e8d8bef9SDimitry Andric         else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I))
6678e8d8bef9SDimitry Andric           ExpectedNumOperands = IBI->getNumDestinations();
6679e8d8bef9SDimitry Andric         else if (isa<SelectInst>(&I))
6680e8d8bef9SDimitry Andric           ExpectedNumOperands = 2;
6681e8d8bef9SDimitry Andric         else
6682e8d8bef9SDimitry Andric           continue; // ignore and continue.
6683e8d8bef9SDimitry Andric 
6684e8d8bef9SDimitry Andric         // If branch weight doesn't match, just strip branch weight.
6685e8d8bef9SDimitry Andric         if (MD->getNumOperands() != 1 + ExpectedNumOperands)
6686e8d8bef9SDimitry Andric           I.setMetadata(LLVMContext::MD_prof, nullptr);
6687e8d8bef9SDimitry Andric       }
6688e8d8bef9SDimitry Andric     }
6689fe6060f1SDimitry Andric 
6690fe6060f1SDimitry Andric     // Remove incompatible attributes on function calls.
6691fe6060f1SDimitry Andric     if (auto *CI = dyn_cast<CallBase>(&I)) {
6692349cc55cSDimitry Andric       CI->removeRetAttrs(AttributeFuncs::typeIncompatible(
6693fe6060f1SDimitry Andric           CI->getFunctionType()->getReturnType()));
6694fe6060f1SDimitry Andric 
6695fe6060f1SDimitry Andric       for (unsigned ArgNo = 0; ArgNo < CI->arg_size(); ++ArgNo)
6696fe6060f1SDimitry Andric         CI->removeParamAttrs(ArgNo, AttributeFuncs::typeIncompatible(
6697fe6060f1SDimitry Andric                                         CI->getArgOperand(ArgNo)->getType()));
6698fe6060f1SDimitry Andric     }
6699e8d8bef9SDimitry Andric   }
6700e8d8bef9SDimitry Andric 
67015ffd83dbSDimitry Andric   // Look for functions that rely on old function attribute behavior.
67025ffd83dbSDimitry Andric   UpgradeFunctionAttributes(*F);
67035ffd83dbSDimitry Andric 
67040b57cec5SDimitry Andric   // Bring in any functions that this function forward-referenced via
67050b57cec5SDimitry Andric   // blockaddresses.
67060b57cec5SDimitry Andric   return materializeForwardReferencedFunctions();
67070b57cec5SDimitry Andric }
67080b57cec5SDimitry Andric 
67090b57cec5SDimitry Andric Error BitcodeReader::materializeModule() {
67100b57cec5SDimitry Andric   if (Error Err = materializeMetadata())
67110b57cec5SDimitry Andric     return Err;
67120b57cec5SDimitry Andric 
67130b57cec5SDimitry Andric   // Promise to materialize all forward references.
67140b57cec5SDimitry Andric   WillMaterializeAllForwardRefs = true;
67150b57cec5SDimitry Andric 
67160b57cec5SDimitry Andric   // Iterate over the module, deserializing any functions that are still on
67170b57cec5SDimitry Andric   // disk.
67180b57cec5SDimitry Andric   for (Function &F : *TheModule) {
67190b57cec5SDimitry Andric     if (Error Err = materialize(&F))
67200b57cec5SDimitry Andric       return Err;
67210b57cec5SDimitry Andric   }
67220b57cec5SDimitry Andric   // At this point, if there are any function bodies, parse the rest of
67230b57cec5SDimitry Andric   // the bits in the module past the last function block we have recorded
67240b57cec5SDimitry Andric   // through either lazy scanning or the VST.
67250b57cec5SDimitry Andric   if (LastFunctionBlockBit || NextUnreadBit)
67260b57cec5SDimitry Andric     if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit
67270b57cec5SDimitry Andric                                     ? LastFunctionBlockBit
67280b57cec5SDimitry Andric                                     : NextUnreadBit))
67290b57cec5SDimitry Andric       return Err;
67300b57cec5SDimitry Andric 
67310b57cec5SDimitry Andric   // Check that all block address forward references got resolved (as we
67320b57cec5SDimitry Andric   // promised above).
67330b57cec5SDimitry Andric   if (!BasicBlockFwdRefs.empty())
67340b57cec5SDimitry Andric     return error("Never resolved function from blockaddress");
67350b57cec5SDimitry Andric 
67360b57cec5SDimitry Andric   // Upgrade any intrinsic calls that slipped through (should not happen!) and
67370b57cec5SDimitry Andric   // delete the old functions to clean up. We can't do this unless the entire
67380b57cec5SDimitry Andric   // module is materialized because there could always be another function body
67390b57cec5SDimitry Andric   // with calls to the old function.
67400b57cec5SDimitry Andric   for (auto &I : UpgradedIntrinsics) {
67410b57cec5SDimitry Andric     for (auto *U : I.first->users()) {
67420b57cec5SDimitry Andric       if (CallInst *CI = dyn_cast<CallInst>(U))
67430b57cec5SDimitry Andric         UpgradeIntrinsicCall(CI, I.second);
67440b57cec5SDimitry Andric     }
67450b57cec5SDimitry Andric     if (!I.first->use_empty())
67460b57cec5SDimitry Andric       I.first->replaceAllUsesWith(I.second);
67470b57cec5SDimitry Andric     I.first->eraseFromParent();
67480b57cec5SDimitry Andric   }
67490b57cec5SDimitry Andric   UpgradedIntrinsics.clear();
67500b57cec5SDimitry Andric 
67510b57cec5SDimitry Andric   UpgradeDebugInfo(*TheModule);
67520b57cec5SDimitry Andric 
67530b57cec5SDimitry Andric   UpgradeModuleFlags(*TheModule);
67540b57cec5SDimitry Andric 
67558bcb0991SDimitry Andric   UpgradeARCRuntime(*TheModule);
67560b57cec5SDimitry Andric 
67570b57cec5SDimitry Andric   return Error::success();
67580b57cec5SDimitry Andric }
67590b57cec5SDimitry Andric 
67600b57cec5SDimitry Andric std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
67610b57cec5SDimitry Andric   return IdentifiedStructTypes;
67620b57cec5SDimitry Andric }
67630b57cec5SDimitry Andric 
67640b57cec5SDimitry Andric ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
67650b57cec5SDimitry Andric     BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex,
6766*c9157d92SDimitry Andric     StringRef ModulePath, std::function<bool(GlobalValue::GUID)> IsPrevailing)
67670b57cec5SDimitry Andric     : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex),
6768*c9157d92SDimitry Andric       ModulePath(ModulePath), IsPrevailing(IsPrevailing) {}
67690b57cec5SDimitry Andric 
67700b57cec5SDimitry Andric void ModuleSummaryIndexBitcodeReader::addThisModule() {
6771*c9157d92SDimitry Andric   TheIndex.addModule(ModulePath);
67720b57cec5SDimitry Andric }
67730b57cec5SDimitry Andric 
67740b57cec5SDimitry Andric ModuleSummaryIndex::ModuleInfo *
67750b57cec5SDimitry Andric ModuleSummaryIndexBitcodeReader::getThisModule() {
67760b57cec5SDimitry Andric   return TheIndex.getModule(ModulePath);
67770b57cec5SDimitry Andric }
67780b57cec5SDimitry Andric 
6779bdd1243dSDimitry Andric template <bool AllowNullValueInfo>
6780bdd1243dSDimitry Andric std::tuple<ValueInfo, GlobalValue::GUID, GlobalValue::GUID>
67810b57cec5SDimitry Andric ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) {
67820b57cec5SDimitry Andric   auto VGI = ValueIdToValueInfoMap[ValueId];
6783bdd1243dSDimitry Andric   // We can have a null value info for memprof callsite info records in
6784bdd1243dSDimitry Andric   // distributed ThinLTO index files when the callee function summary is not
6785bdd1243dSDimitry Andric   // included in the index. The bitcode writer records 0 in that case,
6786bdd1243dSDimitry Andric   // and the caller of this helper will set AllowNullValueInfo to true.
6787bdd1243dSDimitry Andric   assert(AllowNullValueInfo || std::get<0>(VGI));
67880b57cec5SDimitry Andric   return VGI;
67890b57cec5SDimitry Andric }
67900b57cec5SDimitry Andric 
67910b57cec5SDimitry Andric void ModuleSummaryIndexBitcodeReader::setValueGUID(
67920b57cec5SDimitry Andric     uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage,
67930b57cec5SDimitry Andric     StringRef SourceFileName) {
67940b57cec5SDimitry Andric   std::string GlobalId =
67950b57cec5SDimitry Andric       GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
67960b57cec5SDimitry Andric   auto ValueGUID = GlobalValue::getGUID(GlobalId);
67970b57cec5SDimitry Andric   auto OriginalNameID = ValueGUID;
67980b57cec5SDimitry Andric   if (GlobalValue::isLocalLinkage(Linkage))
67990b57cec5SDimitry Andric     OriginalNameID = GlobalValue::getGUID(ValueName);
68000b57cec5SDimitry Andric   if (PrintSummaryGUIDs)
68010b57cec5SDimitry Andric     dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
68020b57cec5SDimitry Andric            << ValueName << "\n";
68030b57cec5SDimitry Andric 
68040b57cec5SDimitry Andric   // UseStrtab is false for legacy summary formats and value names are
68050b57cec5SDimitry Andric   // created on stack. In that case we save the name in a string saver in
68060b57cec5SDimitry Andric   // the index so that the value name can be recorded.
6807bdd1243dSDimitry Andric   ValueIdToValueInfoMap[ValueID] = std::make_tuple(
68080b57cec5SDimitry Andric       TheIndex.getOrInsertValueInfo(
6809bdd1243dSDimitry Andric           ValueGUID, UseStrtab ? ValueName : TheIndex.saveString(ValueName)),
6810bdd1243dSDimitry Andric       OriginalNameID, ValueGUID);
68110b57cec5SDimitry Andric }
68120b57cec5SDimitry Andric 
68130b57cec5SDimitry Andric // Specialized value symbol table parser used when reading module index
68140b57cec5SDimitry Andric // blocks where we don't actually create global values. The parsed information
68150b57cec5SDimitry Andric // is saved in the bitcode reader for use when later parsing summaries.
68160b57cec5SDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
68170b57cec5SDimitry Andric     uint64_t Offset,
68180b57cec5SDimitry Andric     DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
68190b57cec5SDimitry Andric   // With a strtab the VST is not required to parse the summary.
68200b57cec5SDimitry Andric   if (UseStrtab)
68210b57cec5SDimitry Andric     return Error::success();
68220b57cec5SDimitry Andric 
68230b57cec5SDimitry Andric   assert(Offset > 0 && "Expected non-zero VST offset");
68240b57cec5SDimitry Andric   Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream);
68250b57cec5SDimitry Andric   if (!MaybeCurrentBit)
68260b57cec5SDimitry Andric     return MaybeCurrentBit.takeError();
68270b57cec5SDimitry Andric   uint64_t CurrentBit = MaybeCurrentBit.get();
68280b57cec5SDimitry Andric 
68290b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
68300b57cec5SDimitry Andric     return Err;
68310b57cec5SDimitry Andric 
68320b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
68330b57cec5SDimitry Andric 
68340b57cec5SDimitry Andric   // Read all the records for this value table.
68350b57cec5SDimitry Andric   SmallString<128> ValueName;
68360b57cec5SDimitry Andric 
68370b57cec5SDimitry Andric   while (true) {
68380b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
68390b57cec5SDimitry Andric     if (!MaybeEntry)
68400b57cec5SDimitry Andric       return MaybeEntry.takeError();
68410b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
68420b57cec5SDimitry Andric 
68430b57cec5SDimitry Andric     switch (Entry.Kind) {
68440b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
68450b57cec5SDimitry Andric     case BitstreamEntry::Error:
68460b57cec5SDimitry Andric       return error("Malformed block");
68470b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
68480b57cec5SDimitry Andric       // Done parsing VST, jump back to wherever we came from.
68490b57cec5SDimitry Andric       if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
68500b57cec5SDimitry Andric         return JumpFailed;
68510b57cec5SDimitry Andric       return Error::success();
68520b57cec5SDimitry Andric     case BitstreamEntry::Record:
68530b57cec5SDimitry Andric       // The interesting case.
68540b57cec5SDimitry Andric       break;
68550b57cec5SDimitry Andric     }
68560b57cec5SDimitry Andric 
68570b57cec5SDimitry Andric     // Read a record.
68580b57cec5SDimitry Andric     Record.clear();
68590b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
68600b57cec5SDimitry Andric     if (!MaybeRecord)
68610b57cec5SDimitry Andric       return MaybeRecord.takeError();
68620b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
68630b57cec5SDimitry Andric     default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
68640b57cec5SDimitry Andric       break;
68650b57cec5SDimitry Andric     case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
68660b57cec5SDimitry Andric       if (convertToString(Record, 1, ValueName))
68670b57cec5SDimitry Andric         return error("Invalid record");
68680b57cec5SDimitry Andric       unsigned ValueID = Record[0];
68690b57cec5SDimitry Andric       assert(!SourceFileName.empty());
68700b57cec5SDimitry Andric       auto VLI = ValueIdToLinkageMap.find(ValueID);
68710b57cec5SDimitry Andric       assert(VLI != ValueIdToLinkageMap.end() &&
68720b57cec5SDimitry Andric              "No linkage found for VST entry?");
68730b57cec5SDimitry Andric       auto Linkage = VLI->second;
68740b57cec5SDimitry Andric       setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
68750b57cec5SDimitry Andric       ValueName.clear();
68760b57cec5SDimitry Andric       break;
68770b57cec5SDimitry Andric     }
68780b57cec5SDimitry Andric     case bitc::VST_CODE_FNENTRY: {
68790b57cec5SDimitry Andric       // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
68800b57cec5SDimitry Andric       if (convertToString(Record, 2, ValueName))
68810b57cec5SDimitry Andric         return error("Invalid record");
68820b57cec5SDimitry Andric       unsigned ValueID = Record[0];
68830b57cec5SDimitry Andric       assert(!SourceFileName.empty());
68840b57cec5SDimitry Andric       auto VLI = ValueIdToLinkageMap.find(ValueID);
68850b57cec5SDimitry Andric       assert(VLI != ValueIdToLinkageMap.end() &&
68860b57cec5SDimitry Andric              "No linkage found for VST entry?");
68870b57cec5SDimitry Andric       auto Linkage = VLI->second;
68880b57cec5SDimitry Andric       setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
68890b57cec5SDimitry Andric       ValueName.clear();
68900b57cec5SDimitry Andric       break;
68910b57cec5SDimitry Andric     }
68920b57cec5SDimitry Andric     case bitc::VST_CODE_COMBINED_ENTRY: {
68930b57cec5SDimitry Andric       // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
68940b57cec5SDimitry Andric       unsigned ValueID = Record[0];
68950b57cec5SDimitry Andric       GlobalValue::GUID RefGUID = Record[1];
68960b57cec5SDimitry Andric       // The "original name", which is the second value of the pair will be
68970b57cec5SDimitry Andric       // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
6898bdd1243dSDimitry Andric       ValueIdToValueInfoMap[ValueID] = std::make_tuple(
6899bdd1243dSDimitry Andric           TheIndex.getOrInsertValueInfo(RefGUID), RefGUID, RefGUID);
69000b57cec5SDimitry Andric       break;
69010b57cec5SDimitry Andric     }
69020b57cec5SDimitry Andric     }
69030b57cec5SDimitry Andric   }
69040b57cec5SDimitry Andric }
69050b57cec5SDimitry Andric 
69060b57cec5SDimitry Andric // Parse just the blocks needed for building the index out of the module.
69070b57cec5SDimitry Andric // At the end of this routine the module Index is populated with a map
69080b57cec5SDimitry Andric // from global value id to GlobalValueSummary objects.
69090b57cec5SDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseModule() {
69100b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
69110b57cec5SDimitry Andric     return Err;
69120b57cec5SDimitry Andric 
69130b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
69140b57cec5SDimitry Andric   DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
69150b57cec5SDimitry Andric   unsigned ValueId = 0;
69160b57cec5SDimitry Andric 
69170b57cec5SDimitry Andric   // Read the index for this module.
69180b57cec5SDimitry Andric   while (true) {
69190b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
69200b57cec5SDimitry Andric     if (!MaybeEntry)
69210b57cec5SDimitry Andric       return MaybeEntry.takeError();
69220b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
69230b57cec5SDimitry Andric 
69240b57cec5SDimitry Andric     switch (Entry.Kind) {
69250b57cec5SDimitry Andric     case BitstreamEntry::Error:
69260b57cec5SDimitry Andric       return error("Malformed block");
69270b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
69280b57cec5SDimitry Andric       return Error::success();
69290b57cec5SDimitry Andric 
69300b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
69310b57cec5SDimitry Andric       switch (Entry.ID) {
69320b57cec5SDimitry Andric       default: // Skip unknown content.
69330b57cec5SDimitry Andric         if (Error Err = Stream.SkipBlock())
69340b57cec5SDimitry Andric           return Err;
69350b57cec5SDimitry Andric         break;
69360b57cec5SDimitry Andric       case bitc::BLOCKINFO_BLOCK_ID:
69370b57cec5SDimitry Andric         // Need to parse these to get abbrev ids (e.g. for VST)
693881ad6265SDimitry Andric         if (Error Err = readBlockInfo())
693981ad6265SDimitry Andric           return Err;
69400b57cec5SDimitry Andric         break;
69410b57cec5SDimitry Andric       case bitc::VALUE_SYMTAB_BLOCK_ID:
69420b57cec5SDimitry Andric         // Should have been parsed earlier via VSTOffset, unless there
69430b57cec5SDimitry Andric         // is no summary section.
69440b57cec5SDimitry Andric         assert(((SeenValueSymbolTable && VSTOffset > 0) ||
69450b57cec5SDimitry Andric                 !SeenGlobalValSummary) &&
69460b57cec5SDimitry Andric                "Expected early VST parse via VSTOffset record");
69470b57cec5SDimitry Andric         if (Error Err = Stream.SkipBlock())
69480b57cec5SDimitry Andric           return Err;
69490b57cec5SDimitry Andric         break;
69500b57cec5SDimitry Andric       case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
69510b57cec5SDimitry Andric       case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID:
69520b57cec5SDimitry Andric         // Add the module if it is a per-module index (has a source file name).
69530b57cec5SDimitry Andric         if (!SourceFileName.empty())
69540b57cec5SDimitry Andric           addThisModule();
69550b57cec5SDimitry Andric         assert(!SeenValueSymbolTable &&
69560b57cec5SDimitry Andric                "Already read VST when parsing summary block?");
69570b57cec5SDimitry Andric         // We might not have a VST if there were no values in the
69580b57cec5SDimitry Andric         // summary. An empty summary block generated when we are
69590b57cec5SDimitry Andric         // performing ThinLTO compiles so we don't later invoke
69600b57cec5SDimitry Andric         // the regular LTO process on them.
69610b57cec5SDimitry Andric         if (VSTOffset > 0) {
69620b57cec5SDimitry Andric           if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
69630b57cec5SDimitry Andric             return Err;
69640b57cec5SDimitry Andric           SeenValueSymbolTable = true;
69650b57cec5SDimitry Andric         }
69660b57cec5SDimitry Andric         SeenGlobalValSummary = true;
69670b57cec5SDimitry Andric         if (Error Err = parseEntireSummary(Entry.ID))
69680b57cec5SDimitry Andric           return Err;
69690b57cec5SDimitry Andric         break;
69700b57cec5SDimitry Andric       case bitc::MODULE_STRTAB_BLOCK_ID:
69710b57cec5SDimitry Andric         if (Error Err = parseModuleStringTable())
69720b57cec5SDimitry Andric           return Err;
69730b57cec5SDimitry Andric         break;
69740b57cec5SDimitry Andric       }
69750b57cec5SDimitry Andric       continue;
69760b57cec5SDimitry Andric 
69770b57cec5SDimitry Andric     case BitstreamEntry::Record: {
69780b57cec5SDimitry Andric         Record.clear();
69790b57cec5SDimitry Andric         Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
69800b57cec5SDimitry Andric         if (!MaybeBitCode)
69810b57cec5SDimitry Andric           return MaybeBitCode.takeError();
69820b57cec5SDimitry Andric         switch (MaybeBitCode.get()) {
69830b57cec5SDimitry Andric         default:
69840b57cec5SDimitry Andric           break; // Default behavior, ignore unknown content.
69850b57cec5SDimitry Andric         case bitc::MODULE_CODE_VERSION: {
69860b57cec5SDimitry Andric           if (Error Err = parseVersionRecord(Record).takeError())
69870b57cec5SDimitry Andric             return Err;
69880b57cec5SDimitry Andric           break;
69890b57cec5SDimitry Andric         }
69900b57cec5SDimitry Andric         /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
69910b57cec5SDimitry Andric         case bitc::MODULE_CODE_SOURCE_FILENAME: {
69920b57cec5SDimitry Andric           SmallString<128> ValueName;
69930b57cec5SDimitry Andric           if (convertToString(Record, 0, ValueName))
69940b57cec5SDimitry Andric             return error("Invalid record");
69950b57cec5SDimitry Andric           SourceFileName = ValueName.c_str();
69960b57cec5SDimitry Andric           break;
69970b57cec5SDimitry Andric         }
69980b57cec5SDimitry Andric         /// MODULE_CODE_HASH: [5*i32]
69990b57cec5SDimitry Andric         case bitc::MODULE_CODE_HASH: {
70000b57cec5SDimitry Andric           if (Record.size() != 5)
70010b57cec5SDimitry Andric             return error("Invalid hash length " + Twine(Record.size()).str());
7002*c9157d92SDimitry Andric           auto &Hash = getThisModule()->second;
70030b57cec5SDimitry Andric           int Pos = 0;
70040b57cec5SDimitry Andric           for (auto &Val : Record) {
70050b57cec5SDimitry Andric             assert(!(Val >> 32) && "Unexpected high bits set");
70060b57cec5SDimitry Andric             Hash[Pos++] = Val;
70070b57cec5SDimitry Andric           }
70080b57cec5SDimitry Andric           break;
70090b57cec5SDimitry Andric         }
70100b57cec5SDimitry Andric         /// MODULE_CODE_VSTOFFSET: [offset]
70110b57cec5SDimitry Andric         case bitc::MODULE_CODE_VSTOFFSET:
7012e8d8bef9SDimitry Andric           if (Record.empty())
70130b57cec5SDimitry Andric             return error("Invalid record");
70140b57cec5SDimitry Andric           // Note that we subtract 1 here because the offset is relative to one
70150b57cec5SDimitry Andric           // word before the start of the identification or module block, which
70160b57cec5SDimitry Andric           // was historically always the start of the regular bitcode header.
70170b57cec5SDimitry Andric           VSTOffset = Record[0] - 1;
70180b57cec5SDimitry Andric           break;
70190b57cec5SDimitry Andric         // v1 GLOBALVAR: [pointer type, isconst,     initid,       linkage, ...]
70200b57cec5SDimitry Andric         // v1 FUNCTION:  [type,         callingconv, isproto,      linkage, ...]
70210b57cec5SDimitry Andric         // v1 ALIAS:     [alias type,   addrspace,   aliasee val#, linkage, ...]
70220b57cec5SDimitry Andric         // v2: [strtab offset, strtab size, v1]
70230b57cec5SDimitry Andric         case bitc::MODULE_CODE_GLOBALVAR:
70240b57cec5SDimitry Andric         case bitc::MODULE_CODE_FUNCTION:
70250b57cec5SDimitry Andric         case bitc::MODULE_CODE_ALIAS: {
70260b57cec5SDimitry Andric           StringRef Name;
70270b57cec5SDimitry Andric           ArrayRef<uint64_t> GVRecord;
70280b57cec5SDimitry Andric           std::tie(Name, GVRecord) = readNameFromStrtab(Record);
70290b57cec5SDimitry Andric           if (GVRecord.size() <= 3)
70300b57cec5SDimitry Andric             return error("Invalid record");
70310b57cec5SDimitry Andric           uint64_t RawLinkage = GVRecord[3];
70320b57cec5SDimitry Andric           GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
70330b57cec5SDimitry Andric           if (!UseStrtab) {
70340b57cec5SDimitry Andric             ValueIdToLinkageMap[ValueId++] = Linkage;
70350b57cec5SDimitry Andric             break;
70360b57cec5SDimitry Andric           }
70370b57cec5SDimitry Andric 
70380b57cec5SDimitry Andric           setValueGUID(ValueId++, Name, Linkage, SourceFileName);
70390b57cec5SDimitry Andric           break;
70400b57cec5SDimitry Andric         }
70410b57cec5SDimitry Andric         }
70420b57cec5SDimitry Andric       }
70430b57cec5SDimitry Andric       continue;
70440b57cec5SDimitry Andric     }
70450b57cec5SDimitry Andric   }
70460b57cec5SDimitry Andric }
70470b57cec5SDimitry Andric 
70480b57cec5SDimitry Andric std::vector<ValueInfo>
70490b57cec5SDimitry Andric ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
70500b57cec5SDimitry Andric   std::vector<ValueInfo> Ret;
70510b57cec5SDimitry Andric   Ret.reserve(Record.size());
70520b57cec5SDimitry Andric   for (uint64_t RefValueId : Record)
7053bdd1243dSDimitry Andric     Ret.push_back(std::get<0>(getValueInfoFromValueId(RefValueId)));
70540b57cec5SDimitry Andric   return Ret;
70550b57cec5SDimitry Andric }
70560b57cec5SDimitry Andric 
70570b57cec5SDimitry Andric std::vector<FunctionSummary::EdgeTy>
70580b57cec5SDimitry Andric ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record,
70590b57cec5SDimitry Andric                                               bool IsOldProfileFormat,
70600b57cec5SDimitry Andric                                               bool HasProfile, bool HasRelBF) {
70610b57cec5SDimitry Andric   std::vector<FunctionSummary::EdgeTy> Ret;
70620b57cec5SDimitry Andric   Ret.reserve(Record.size());
70630b57cec5SDimitry Andric   for (unsigned I = 0, E = Record.size(); I != E; ++I) {
70640b57cec5SDimitry Andric     CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
7065*c9157d92SDimitry Andric     bool HasTailCall = false;
70660b57cec5SDimitry Andric     uint64_t RelBF = 0;
7067bdd1243dSDimitry Andric     ValueInfo Callee = std::get<0>(getValueInfoFromValueId(Record[I]));
70680b57cec5SDimitry Andric     if (IsOldProfileFormat) {
70690b57cec5SDimitry Andric       I += 1; // Skip old callsitecount field
70700b57cec5SDimitry Andric       if (HasProfile)
70710b57cec5SDimitry Andric         I += 1; // Skip old profilecount field
70720b57cec5SDimitry Andric     } else if (HasProfile)
7073*c9157d92SDimitry Andric       std::tie(Hotness, HasTailCall) =
7074*c9157d92SDimitry Andric           getDecodedHotnessCallEdgeInfo(Record[++I]);
70750b57cec5SDimitry Andric     else if (HasRelBF)
7076*c9157d92SDimitry Andric       getDecodedRelBFCallEdgeInfo(Record[++I], RelBF, HasTailCall);
7077*c9157d92SDimitry Andric     Ret.push_back(FunctionSummary::EdgeTy{
7078*c9157d92SDimitry Andric         Callee, CalleeInfo(Hotness, HasTailCall, RelBF)});
70790b57cec5SDimitry Andric   }
70800b57cec5SDimitry Andric   return Ret;
70810b57cec5SDimitry Andric }
70820b57cec5SDimitry Andric 
70830b57cec5SDimitry Andric static void
70840b57cec5SDimitry Andric parseWholeProgramDevirtResolutionByArg(ArrayRef<uint64_t> Record, size_t &Slot,
70850b57cec5SDimitry Andric                                        WholeProgramDevirtResolution &Wpd) {
70860b57cec5SDimitry Andric   uint64_t ArgNum = Record[Slot++];
70870b57cec5SDimitry Andric   WholeProgramDevirtResolution::ByArg &B =
70880b57cec5SDimitry Andric       Wpd.ResByArg[{Record.begin() + Slot, Record.begin() + Slot + ArgNum}];
70890b57cec5SDimitry Andric   Slot += ArgNum;
70900b57cec5SDimitry Andric 
70910b57cec5SDimitry Andric   B.TheKind =
70920b57cec5SDimitry Andric       static_cast<WholeProgramDevirtResolution::ByArg::Kind>(Record[Slot++]);
70930b57cec5SDimitry Andric   B.Info = Record[Slot++];
70940b57cec5SDimitry Andric   B.Byte = Record[Slot++];
70950b57cec5SDimitry Andric   B.Bit = Record[Slot++];
70960b57cec5SDimitry Andric }
70970b57cec5SDimitry Andric 
70980b57cec5SDimitry Andric static void parseWholeProgramDevirtResolution(ArrayRef<uint64_t> Record,
70990b57cec5SDimitry Andric                                               StringRef Strtab, size_t &Slot,
71000b57cec5SDimitry Andric                                               TypeIdSummary &TypeId) {
71010b57cec5SDimitry Andric   uint64_t Id = Record[Slot++];
71020b57cec5SDimitry Andric   WholeProgramDevirtResolution &Wpd = TypeId.WPDRes[Id];
71030b57cec5SDimitry Andric 
71040b57cec5SDimitry Andric   Wpd.TheKind = static_cast<WholeProgramDevirtResolution::Kind>(Record[Slot++]);
71050b57cec5SDimitry Andric   Wpd.SingleImplName = {Strtab.data() + Record[Slot],
71060b57cec5SDimitry Andric                         static_cast<size_t>(Record[Slot + 1])};
71070b57cec5SDimitry Andric   Slot += 2;
71080b57cec5SDimitry Andric 
71090b57cec5SDimitry Andric   uint64_t ResByArgNum = Record[Slot++];
71100b57cec5SDimitry Andric   for (uint64_t I = 0; I != ResByArgNum; ++I)
71110b57cec5SDimitry Andric     parseWholeProgramDevirtResolutionByArg(Record, Slot, Wpd);
71120b57cec5SDimitry Andric }
71130b57cec5SDimitry Andric 
71140b57cec5SDimitry Andric static void parseTypeIdSummaryRecord(ArrayRef<uint64_t> Record,
71150b57cec5SDimitry Andric                                      StringRef Strtab,
71160b57cec5SDimitry Andric                                      ModuleSummaryIndex &TheIndex) {
71170b57cec5SDimitry Andric   size_t Slot = 0;
71180b57cec5SDimitry Andric   TypeIdSummary &TypeId = TheIndex.getOrInsertTypeIdSummary(
71190b57cec5SDimitry Andric       {Strtab.data() + Record[Slot], static_cast<size_t>(Record[Slot + 1])});
71200b57cec5SDimitry Andric   Slot += 2;
71210b57cec5SDimitry Andric 
71220b57cec5SDimitry Andric   TypeId.TTRes.TheKind = static_cast<TypeTestResolution::Kind>(Record[Slot++]);
71230b57cec5SDimitry Andric   TypeId.TTRes.SizeM1BitWidth = Record[Slot++];
71240b57cec5SDimitry Andric   TypeId.TTRes.AlignLog2 = Record[Slot++];
71250b57cec5SDimitry Andric   TypeId.TTRes.SizeM1 = Record[Slot++];
71260b57cec5SDimitry Andric   TypeId.TTRes.BitMask = Record[Slot++];
71270b57cec5SDimitry Andric   TypeId.TTRes.InlineBits = Record[Slot++];
71280b57cec5SDimitry Andric 
71290b57cec5SDimitry Andric   while (Slot < Record.size())
71300b57cec5SDimitry Andric     parseWholeProgramDevirtResolution(Record, Strtab, Slot, TypeId);
71310b57cec5SDimitry Andric }
71320b57cec5SDimitry Andric 
7133e8d8bef9SDimitry Andric std::vector<FunctionSummary::ParamAccess>
7134e8d8bef9SDimitry Andric ModuleSummaryIndexBitcodeReader::parseParamAccesses(ArrayRef<uint64_t> Record) {
71355ffd83dbSDimitry Andric   auto ReadRange = [&]() {
71365ffd83dbSDimitry Andric     APInt Lower(FunctionSummary::ParamAccess::RangeWidth,
71375ffd83dbSDimitry Andric                 BitcodeReader::decodeSignRotatedValue(Record.front()));
71385ffd83dbSDimitry Andric     Record = Record.drop_front();
71395ffd83dbSDimitry Andric     APInt Upper(FunctionSummary::ParamAccess::RangeWidth,
71405ffd83dbSDimitry Andric                 BitcodeReader::decodeSignRotatedValue(Record.front()));
71415ffd83dbSDimitry Andric     Record = Record.drop_front();
71425ffd83dbSDimitry Andric     ConstantRange Range{Lower, Upper};
71435ffd83dbSDimitry Andric     assert(!Range.isFullSet());
71445ffd83dbSDimitry Andric     assert(!Range.isUpperSignWrapped());
71455ffd83dbSDimitry Andric     return Range;
71465ffd83dbSDimitry Andric   };
71475ffd83dbSDimitry Andric 
71485ffd83dbSDimitry Andric   std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
71495ffd83dbSDimitry Andric   while (!Record.empty()) {
71505ffd83dbSDimitry Andric     PendingParamAccesses.emplace_back();
71515ffd83dbSDimitry Andric     FunctionSummary::ParamAccess &ParamAccess = PendingParamAccesses.back();
71525ffd83dbSDimitry Andric     ParamAccess.ParamNo = Record.front();
71535ffd83dbSDimitry Andric     Record = Record.drop_front();
71545ffd83dbSDimitry Andric     ParamAccess.Use = ReadRange();
71555ffd83dbSDimitry Andric     ParamAccess.Calls.resize(Record.front());
71565ffd83dbSDimitry Andric     Record = Record.drop_front();
71575ffd83dbSDimitry Andric     for (auto &Call : ParamAccess.Calls) {
71585ffd83dbSDimitry Andric       Call.ParamNo = Record.front();
71595ffd83dbSDimitry Andric       Record = Record.drop_front();
7160bdd1243dSDimitry Andric       Call.Callee = std::get<0>(getValueInfoFromValueId(Record.front()));
71615ffd83dbSDimitry Andric       Record = Record.drop_front();
71625ffd83dbSDimitry Andric       Call.Offsets = ReadRange();
71635ffd83dbSDimitry Andric     }
71645ffd83dbSDimitry Andric   }
71655ffd83dbSDimitry Andric   return PendingParamAccesses;
71665ffd83dbSDimitry Andric }
71675ffd83dbSDimitry Andric 
71680b57cec5SDimitry Andric void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo(
71690b57cec5SDimitry Andric     ArrayRef<uint64_t> Record, size_t &Slot,
71700b57cec5SDimitry Andric     TypeIdCompatibleVtableInfo &TypeId) {
71710b57cec5SDimitry Andric   uint64_t Offset = Record[Slot++];
7172bdd1243dSDimitry Andric   ValueInfo Callee = std::get<0>(getValueInfoFromValueId(Record[Slot++]));
71730b57cec5SDimitry Andric   TypeId.push_back({Offset, Callee});
71740b57cec5SDimitry Andric }
71750b57cec5SDimitry Andric 
71760b57cec5SDimitry Andric void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord(
71770b57cec5SDimitry Andric     ArrayRef<uint64_t> Record) {
71780b57cec5SDimitry Andric   size_t Slot = 0;
71790b57cec5SDimitry Andric   TypeIdCompatibleVtableInfo &TypeId =
71800b57cec5SDimitry Andric       TheIndex.getOrInsertTypeIdCompatibleVtableSummary(
71810b57cec5SDimitry Andric           {Strtab.data() + Record[Slot],
71820b57cec5SDimitry Andric            static_cast<size_t>(Record[Slot + 1])});
71830b57cec5SDimitry Andric   Slot += 2;
71840b57cec5SDimitry Andric 
71850b57cec5SDimitry Andric   while (Slot < Record.size())
71860b57cec5SDimitry Andric     parseTypeIdCompatibleVtableInfo(Record, Slot, TypeId);
71870b57cec5SDimitry Andric }
71880b57cec5SDimitry Andric 
71890b57cec5SDimitry Andric static void setSpecialRefs(std::vector<ValueInfo> &Refs, unsigned ROCnt,
71900b57cec5SDimitry Andric                            unsigned WOCnt) {
71910b57cec5SDimitry Andric   // Readonly and writeonly refs are in the end of the refs list.
71920b57cec5SDimitry Andric   assert(ROCnt + WOCnt <= Refs.size());
71930b57cec5SDimitry Andric   unsigned FirstWORef = Refs.size() - WOCnt;
71940b57cec5SDimitry Andric   unsigned RefNo = FirstWORef - ROCnt;
71950b57cec5SDimitry Andric   for (; RefNo < FirstWORef; ++RefNo)
71960b57cec5SDimitry Andric     Refs[RefNo].setReadOnly();
71970b57cec5SDimitry Andric   for (; RefNo < Refs.size(); ++RefNo)
71980b57cec5SDimitry Andric     Refs[RefNo].setWriteOnly();
71990b57cec5SDimitry Andric }
72000b57cec5SDimitry Andric 
72010b57cec5SDimitry Andric // Eagerly parse the entire summary block. This populates the GlobalValueSummary
72020b57cec5SDimitry Andric // objects in the index.
72030b57cec5SDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) {
72040b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(ID))
72050b57cec5SDimitry Andric     return Err;
72060b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
72070b57cec5SDimitry Andric 
72080b57cec5SDimitry Andric   // Parse version
72090b57cec5SDimitry Andric   {
72100b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
72110b57cec5SDimitry Andric     if (!MaybeEntry)
72120b57cec5SDimitry Andric       return MaybeEntry.takeError();
72130b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
72140b57cec5SDimitry Andric 
72150b57cec5SDimitry Andric     if (Entry.Kind != BitstreamEntry::Record)
72160b57cec5SDimitry Andric       return error("Invalid Summary Block: record for version expected");
72170b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
72180b57cec5SDimitry Andric     if (!MaybeRecord)
72190b57cec5SDimitry Andric       return MaybeRecord.takeError();
72200b57cec5SDimitry Andric     if (MaybeRecord.get() != bitc::FS_VERSION)
72210b57cec5SDimitry Andric       return error("Invalid Summary Block: version expected");
72220b57cec5SDimitry Andric   }
72230b57cec5SDimitry Andric   const uint64_t Version = Record[0];
72240b57cec5SDimitry Andric   const bool IsOldProfileFormat = Version == 1;
7225480093f4SDimitry Andric   if (Version < 1 || Version > ModuleSummaryIndex::BitcodeSummaryVersion)
72260b57cec5SDimitry Andric     return error("Invalid summary version " + Twine(Version) +
7227480093f4SDimitry Andric                  ". Version should be in the range [1-" +
7228480093f4SDimitry Andric                  Twine(ModuleSummaryIndex::BitcodeSummaryVersion) +
7229480093f4SDimitry Andric                  "].");
72300b57cec5SDimitry Andric   Record.clear();
72310b57cec5SDimitry Andric 
72320b57cec5SDimitry Andric   // Keep around the last seen summary to be used when we see an optional
72330b57cec5SDimitry Andric   // "OriginalName" attachement.
72340b57cec5SDimitry Andric   GlobalValueSummary *LastSeenSummary = nullptr;
72350b57cec5SDimitry Andric   GlobalValue::GUID LastSeenGUID = 0;
72360b57cec5SDimitry Andric 
72370b57cec5SDimitry Andric   // We can expect to see any number of type ID information records before
72380b57cec5SDimitry Andric   // each function summary records; these variables store the information
72390b57cec5SDimitry Andric   // collected so far so that it can be used to create the summary object.
72400b57cec5SDimitry Andric   std::vector<GlobalValue::GUID> PendingTypeTests;
72410b57cec5SDimitry Andric   std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
72420b57cec5SDimitry Andric       PendingTypeCheckedLoadVCalls;
72430b57cec5SDimitry Andric   std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
72440b57cec5SDimitry Andric       PendingTypeCheckedLoadConstVCalls;
72455ffd83dbSDimitry Andric   std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
72460b57cec5SDimitry Andric 
7247bdd1243dSDimitry Andric   std::vector<CallsiteInfo> PendingCallsites;
7248bdd1243dSDimitry Andric   std::vector<AllocInfo> PendingAllocs;
7249bdd1243dSDimitry Andric 
72500b57cec5SDimitry Andric   while (true) {
72510b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
72520b57cec5SDimitry Andric     if (!MaybeEntry)
72530b57cec5SDimitry Andric       return MaybeEntry.takeError();
72540b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
72550b57cec5SDimitry Andric 
72560b57cec5SDimitry Andric     switch (Entry.Kind) {
72570b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
72580b57cec5SDimitry Andric     case BitstreamEntry::Error:
72590b57cec5SDimitry Andric       return error("Malformed block");
72600b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
72610b57cec5SDimitry Andric       return Error::success();
72620b57cec5SDimitry Andric     case BitstreamEntry::Record:
72630b57cec5SDimitry Andric       // The interesting case.
72640b57cec5SDimitry Andric       break;
72650b57cec5SDimitry Andric     }
72660b57cec5SDimitry Andric 
72670b57cec5SDimitry Andric     // Read a record. The record format depends on whether this
72680b57cec5SDimitry Andric     // is a per-module index or a combined index file. In the per-module
72690b57cec5SDimitry Andric     // case the records contain the associated value's ID for correlation
72700b57cec5SDimitry Andric     // with VST entries. In the combined index the correlation is done
72710b57cec5SDimitry Andric     // via the bitcode offset of the summary records (which were saved
72720b57cec5SDimitry Andric     // in the combined index VST entries). The records also contain
72730b57cec5SDimitry Andric     // information used for ThinLTO renaming and importing.
72740b57cec5SDimitry Andric     Record.clear();
72750b57cec5SDimitry Andric     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
72760b57cec5SDimitry Andric     if (!MaybeBitCode)
72770b57cec5SDimitry Andric       return MaybeBitCode.takeError();
72780b57cec5SDimitry Andric     switch (unsigned BitCode = MaybeBitCode.get()) {
72790b57cec5SDimitry Andric     default: // Default behavior: ignore.
72800b57cec5SDimitry Andric       break;
72810b57cec5SDimitry Andric     case bitc::FS_FLAGS: {  // [flags]
72825ffd83dbSDimitry Andric       TheIndex.setFlags(Record[0]);
72830b57cec5SDimitry Andric       break;
72840b57cec5SDimitry Andric     }
72850b57cec5SDimitry Andric     case bitc::FS_VALUE_GUID: { // [valueid, refguid]
72860b57cec5SDimitry Andric       uint64_t ValueID = Record[0];
72870b57cec5SDimitry Andric       GlobalValue::GUID RefGUID = Record[1];
7288bdd1243dSDimitry Andric       ValueIdToValueInfoMap[ValueID] = std::make_tuple(
7289bdd1243dSDimitry Andric           TheIndex.getOrInsertValueInfo(RefGUID), RefGUID, RefGUID);
72900b57cec5SDimitry Andric       break;
72910b57cec5SDimitry Andric     }
7292*c9157d92SDimitry Andric     // FS_PERMODULE is legacy and does not have support for the tail call flag.
72930b57cec5SDimitry Andric     // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs,
72940b57cec5SDimitry Andric     //                numrefs x valueid, n x (valueid)]
72950b57cec5SDimitry Andric     // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs,
72960b57cec5SDimitry Andric     //                        numrefs x valueid,
7297*c9157d92SDimitry Andric     //                        n x (valueid, hotness+tailcall flags)]
72980b57cec5SDimitry Andric     // FS_PERMODULE_RELBF: [valueid, flags, instcount, fflags, numrefs,
72990b57cec5SDimitry Andric     //                      numrefs x valueid,
7300*c9157d92SDimitry Andric     //                      n x (valueid, relblockfreq+tailcall)]
73010b57cec5SDimitry Andric     case bitc::FS_PERMODULE:
73020b57cec5SDimitry Andric     case bitc::FS_PERMODULE_RELBF:
73030b57cec5SDimitry Andric     case bitc::FS_PERMODULE_PROFILE: {
73040b57cec5SDimitry Andric       unsigned ValueID = Record[0];
73050b57cec5SDimitry Andric       uint64_t RawFlags = Record[1];
73060b57cec5SDimitry Andric       unsigned InstCount = Record[2];
73070b57cec5SDimitry Andric       uint64_t RawFunFlags = 0;
73080b57cec5SDimitry Andric       unsigned NumRefs = Record[3];
73090b57cec5SDimitry Andric       unsigned NumRORefs = 0, NumWORefs = 0;
73100b57cec5SDimitry Andric       int RefListStartIndex = 4;
73110b57cec5SDimitry Andric       if (Version >= 4) {
73120b57cec5SDimitry Andric         RawFunFlags = Record[3];
73130b57cec5SDimitry Andric         NumRefs = Record[4];
73140b57cec5SDimitry Andric         RefListStartIndex = 5;
73150b57cec5SDimitry Andric         if (Version >= 5) {
73160b57cec5SDimitry Andric           NumRORefs = Record[5];
73170b57cec5SDimitry Andric           RefListStartIndex = 6;
73180b57cec5SDimitry Andric           if (Version >= 7) {
73190b57cec5SDimitry Andric             NumWORefs = Record[6];
73200b57cec5SDimitry Andric             RefListStartIndex = 7;
73210b57cec5SDimitry Andric           }
73220b57cec5SDimitry Andric         }
73230b57cec5SDimitry Andric       }
73240b57cec5SDimitry Andric 
73250b57cec5SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
73260b57cec5SDimitry Andric       // The module path string ref set in the summary must be owned by the
73270b57cec5SDimitry Andric       // index's module string table. Since we don't have a module path
73280b57cec5SDimitry Andric       // string table section in the per-module index, we create a single
73290b57cec5SDimitry Andric       // module path string table entry with an empty (0) ID to take
73300b57cec5SDimitry Andric       // ownership.
73310b57cec5SDimitry Andric       int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
73320b57cec5SDimitry Andric       assert(Record.size() >= RefListStartIndex + NumRefs &&
73330b57cec5SDimitry Andric              "Record size inconsistent with number of references");
73340b57cec5SDimitry Andric       std::vector<ValueInfo> Refs = makeRefList(
73350b57cec5SDimitry Andric           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
73360b57cec5SDimitry Andric       bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
73370b57cec5SDimitry Andric       bool HasRelBF = (BitCode == bitc::FS_PERMODULE_RELBF);
73380b57cec5SDimitry Andric       std::vector<FunctionSummary::EdgeTy> Calls = makeCallList(
73390b57cec5SDimitry Andric           ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
73400b57cec5SDimitry Andric           IsOldProfileFormat, HasProfile, HasRelBF);
73410b57cec5SDimitry Andric       setSpecialRefs(Refs, NumRORefs, NumWORefs);
7342bdd1243dSDimitry Andric       auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID);
7343bdd1243dSDimitry Andric       // In order to save memory, only record the memprof summaries if this is
7344bdd1243dSDimitry Andric       // the prevailing copy of a symbol. The linker doesn't resolve local
7345bdd1243dSDimitry Andric       // linkage values so don't check whether those are prevailing.
7346bdd1243dSDimitry Andric       auto LT = (GlobalValue::LinkageTypes)Flags.Linkage;
7347bdd1243dSDimitry Andric       if (IsPrevailing &&
7348bdd1243dSDimitry Andric           !GlobalValue::isLocalLinkage(LT) &&
7349bdd1243dSDimitry Andric           !IsPrevailing(std::get<2>(VIAndOriginalGUID))) {
7350bdd1243dSDimitry Andric         PendingCallsites.clear();
7351bdd1243dSDimitry Andric         PendingAllocs.clear();
7352bdd1243dSDimitry Andric       }
73538bcb0991SDimitry Andric       auto FS = std::make_unique<FunctionSummary>(
73540b57cec5SDimitry Andric           Flags, InstCount, getDecodedFFlags(RawFunFlags), /*EntryCount=*/0,
73550b57cec5SDimitry Andric           std::move(Refs), std::move(Calls), std::move(PendingTypeTests),
73560b57cec5SDimitry Andric           std::move(PendingTypeTestAssumeVCalls),
73570b57cec5SDimitry Andric           std::move(PendingTypeCheckedLoadVCalls),
73580b57cec5SDimitry Andric           std::move(PendingTypeTestAssumeConstVCalls),
73595ffd83dbSDimitry Andric           std::move(PendingTypeCheckedLoadConstVCalls),
7360bdd1243dSDimitry Andric           std::move(PendingParamAccesses), std::move(PendingCallsites),
7361bdd1243dSDimitry Andric           std::move(PendingAllocs));
73620b57cec5SDimitry Andric       FS->setModulePath(getThisModule()->first());
7363bdd1243dSDimitry Andric       FS->setOriginalName(std::get<1>(VIAndOriginalGUID));
7364bdd1243dSDimitry Andric       TheIndex.addGlobalValueSummary(std::get<0>(VIAndOriginalGUID),
7365bdd1243dSDimitry Andric                                      std::move(FS));
73660b57cec5SDimitry Andric       break;
73670b57cec5SDimitry Andric     }
73680b57cec5SDimitry Andric     // FS_ALIAS: [valueid, flags, valueid]
73690b57cec5SDimitry Andric     // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
73700b57cec5SDimitry Andric     // they expect all aliasee summaries to be available.
73710b57cec5SDimitry Andric     case bitc::FS_ALIAS: {
73720b57cec5SDimitry Andric       unsigned ValueID = Record[0];
73730b57cec5SDimitry Andric       uint64_t RawFlags = Record[1];
73740b57cec5SDimitry Andric       unsigned AliaseeID = Record[2];
73750b57cec5SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
73768bcb0991SDimitry Andric       auto AS = std::make_unique<AliasSummary>(Flags);
73770b57cec5SDimitry Andric       // The module path string ref set in the summary must be owned by the
73780b57cec5SDimitry Andric       // index's module string table. Since we don't have a module path
73790b57cec5SDimitry Andric       // string table section in the per-module index, we create a single
73800b57cec5SDimitry Andric       // module path string table entry with an empty (0) ID to take
73810b57cec5SDimitry Andric       // ownership.
73820b57cec5SDimitry Andric       AS->setModulePath(getThisModule()->first());
73830b57cec5SDimitry Andric 
7384bdd1243dSDimitry Andric       auto AliaseeVI = std::get<0>(getValueInfoFromValueId(AliaseeID));
73850b57cec5SDimitry Andric       auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, ModulePath);
73860b57cec5SDimitry Andric       if (!AliaseeInModule)
73870b57cec5SDimitry Andric         return error("Alias expects aliasee summary to be parsed");
73880b57cec5SDimitry Andric       AS->setAliasee(AliaseeVI, AliaseeInModule);
73890b57cec5SDimitry Andric 
73900b57cec5SDimitry Andric       auto GUID = getValueInfoFromValueId(ValueID);
7391bdd1243dSDimitry Andric       AS->setOriginalName(std::get<1>(GUID));
7392bdd1243dSDimitry Andric       TheIndex.addGlobalValueSummary(std::get<0>(GUID), std::move(AS));
73930b57cec5SDimitry Andric       break;
73940b57cec5SDimitry Andric     }
73950b57cec5SDimitry Andric     // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, n x valueid]
73960b57cec5SDimitry Andric     case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
73970b57cec5SDimitry Andric       unsigned ValueID = Record[0];
73980b57cec5SDimitry Andric       uint64_t RawFlags = Record[1];
73990b57cec5SDimitry Andric       unsigned RefArrayStart = 2;
74000b57cec5SDimitry Andric       GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false,
74015ffd83dbSDimitry Andric                                       /* WriteOnly */ false,
74025ffd83dbSDimitry Andric                                       /* Constant */ false,
74035ffd83dbSDimitry Andric                                       GlobalObject::VCallVisibilityPublic);
74040b57cec5SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
74050b57cec5SDimitry Andric       if (Version >= 5) {
74060b57cec5SDimitry Andric         GVF = getDecodedGVarFlags(Record[2]);
74070b57cec5SDimitry Andric         RefArrayStart = 3;
74080b57cec5SDimitry Andric       }
74090b57cec5SDimitry Andric       std::vector<ValueInfo> Refs =
74100b57cec5SDimitry Andric           makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
74110b57cec5SDimitry Andric       auto FS =
74128bcb0991SDimitry Andric           std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
74130b57cec5SDimitry Andric       FS->setModulePath(getThisModule()->first());
74140b57cec5SDimitry Andric       auto GUID = getValueInfoFromValueId(ValueID);
7415bdd1243dSDimitry Andric       FS->setOriginalName(std::get<1>(GUID));
7416bdd1243dSDimitry Andric       TheIndex.addGlobalValueSummary(std::get<0>(GUID), std::move(FS));
74170b57cec5SDimitry Andric       break;
74180b57cec5SDimitry Andric     }
74190b57cec5SDimitry Andric     // FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags,
74200b57cec5SDimitry Andric     //                        numrefs, numrefs x valueid,
74210b57cec5SDimitry Andric     //                        n x (valueid, offset)]
74220b57cec5SDimitry Andric     case bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: {
74230b57cec5SDimitry Andric       unsigned ValueID = Record[0];
74240b57cec5SDimitry Andric       uint64_t RawFlags = Record[1];
74250b57cec5SDimitry Andric       GlobalVarSummary::GVarFlags GVF = getDecodedGVarFlags(Record[2]);
74260b57cec5SDimitry Andric       unsigned NumRefs = Record[3];
74270b57cec5SDimitry Andric       unsigned RefListStartIndex = 4;
74280b57cec5SDimitry Andric       unsigned VTableListStartIndex = RefListStartIndex + NumRefs;
74290b57cec5SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
74300b57cec5SDimitry Andric       std::vector<ValueInfo> Refs = makeRefList(
74310b57cec5SDimitry Andric           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
74320b57cec5SDimitry Andric       VTableFuncList VTableFuncs;
74330b57cec5SDimitry Andric       for (unsigned I = VTableListStartIndex, E = Record.size(); I != E; ++I) {
7434bdd1243dSDimitry Andric         ValueInfo Callee = std::get<0>(getValueInfoFromValueId(Record[I]));
74350b57cec5SDimitry Andric         uint64_t Offset = Record[++I];
74360b57cec5SDimitry Andric         VTableFuncs.push_back({Callee, Offset});
74370b57cec5SDimitry Andric       }
74380b57cec5SDimitry Andric       auto VS =
74398bcb0991SDimitry Andric           std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
74400b57cec5SDimitry Andric       VS->setModulePath(getThisModule()->first());
74410b57cec5SDimitry Andric       VS->setVTableFuncs(VTableFuncs);
74420b57cec5SDimitry Andric       auto GUID = getValueInfoFromValueId(ValueID);
7443bdd1243dSDimitry Andric       VS->setOriginalName(std::get<1>(GUID));
7444bdd1243dSDimitry Andric       TheIndex.addGlobalValueSummary(std::get<0>(GUID), std::move(VS));
74450b57cec5SDimitry Andric       break;
74460b57cec5SDimitry Andric     }
7447*c9157d92SDimitry Andric     // FS_COMBINED is legacy and does not have support for the tail call flag.
74480b57cec5SDimitry Andric     // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs,
74490b57cec5SDimitry Andric     //               numrefs x valueid, n x (valueid)]
74500b57cec5SDimitry Andric     // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs,
7451*c9157d92SDimitry Andric     //                       numrefs x valueid,
7452*c9157d92SDimitry Andric     //                       n x (valueid, hotness+tailcall flags)]
74530b57cec5SDimitry Andric     case bitc::FS_COMBINED:
74540b57cec5SDimitry Andric     case bitc::FS_COMBINED_PROFILE: {
74550b57cec5SDimitry Andric       unsigned ValueID = Record[0];
74560b57cec5SDimitry Andric       uint64_t ModuleId = Record[1];
74570b57cec5SDimitry Andric       uint64_t RawFlags = Record[2];
74580b57cec5SDimitry Andric       unsigned InstCount = Record[3];
74590b57cec5SDimitry Andric       uint64_t RawFunFlags = 0;
74600b57cec5SDimitry Andric       uint64_t EntryCount = 0;
74610b57cec5SDimitry Andric       unsigned NumRefs = Record[4];
74620b57cec5SDimitry Andric       unsigned NumRORefs = 0, NumWORefs = 0;
74630b57cec5SDimitry Andric       int RefListStartIndex = 5;
74640b57cec5SDimitry Andric 
74650b57cec5SDimitry Andric       if (Version >= 4) {
74660b57cec5SDimitry Andric         RawFunFlags = Record[4];
74670b57cec5SDimitry Andric         RefListStartIndex = 6;
74680b57cec5SDimitry Andric         size_t NumRefsIndex = 5;
74690b57cec5SDimitry Andric         if (Version >= 5) {
74700b57cec5SDimitry Andric           unsigned NumRORefsOffset = 1;
74710b57cec5SDimitry Andric           RefListStartIndex = 7;
74720b57cec5SDimitry Andric           if (Version >= 6) {
74730b57cec5SDimitry Andric             NumRefsIndex = 6;
74740b57cec5SDimitry Andric             EntryCount = Record[5];
74750b57cec5SDimitry Andric             RefListStartIndex = 8;
74760b57cec5SDimitry Andric             if (Version >= 7) {
74770b57cec5SDimitry Andric               RefListStartIndex = 9;
74780b57cec5SDimitry Andric               NumWORefs = Record[8];
74790b57cec5SDimitry Andric               NumRORefsOffset = 2;
74800b57cec5SDimitry Andric             }
74810b57cec5SDimitry Andric           }
74820b57cec5SDimitry Andric           NumRORefs = Record[RefListStartIndex - NumRORefsOffset];
74830b57cec5SDimitry Andric         }
74840b57cec5SDimitry Andric         NumRefs = Record[NumRefsIndex];
74850b57cec5SDimitry Andric       }
74860b57cec5SDimitry Andric 
74870b57cec5SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
74880b57cec5SDimitry Andric       int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
74890b57cec5SDimitry Andric       assert(Record.size() >= RefListStartIndex + NumRefs &&
74900b57cec5SDimitry Andric              "Record size inconsistent with number of references");
74910b57cec5SDimitry Andric       std::vector<ValueInfo> Refs = makeRefList(
74920b57cec5SDimitry Andric           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
74930b57cec5SDimitry Andric       bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
74940b57cec5SDimitry Andric       std::vector<FunctionSummary::EdgeTy> Edges = makeCallList(
74950b57cec5SDimitry Andric           ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
74960b57cec5SDimitry Andric           IsOldProfileFormat, HasProfile, false);
7497bdd1243dSDimitry Andric       ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
74980b57cec5SDimitry Andric       setSpecialRefs(Refs, NumRORefs, NumWORefs);
74998bcb0991SDimitry Andric       auto FS = std::make_unique<FunctionSummary>(
75000b57cec5SDimitry Andric           Flags, InstCount, getDecodedFFlags(RawFunFlags), EntryCount,
75010b57cec5SDimitry Andric           std::move(Refs), std::move(Edges), std::move(PendingTypeTests),
75020b57cec5SDimitry Andric           std::move(PendingTypeTestAssumeVCalls),
75030b57cec5SDimitry Andric           std::move(PendingTypeCheckedLoadVCalls),
75040b57cec5SDimitry Andric           std::move(PendingTypeTestAssumeConstVCalls),
75055ffd83dbSDimitry Andric           std::move(PendingTypeCheckedLoadConstVCalls),
7506bdd1243dSDimitry Andric           std::move(PendingParamAccesses), std::move(PendingCallsites),
7507bdd1243dSDimitry Andric           std::move(PendingAllocs));
75080b57cec5SDimitry Andric       LastSeenSummary = FS.get();
75090b57cec5SDimitry Andric       LastSeenGUID = VI.getGUID();
75100b57cec5SDimitry Andric       FS->setModulePath(ModuleIdMap[ModuleId]);
75110b57cec5SDimitry Andric       TheIndex.addGlobalValueSummary(VI, std::move(FS));
75120b57cec5SDimitry Andric       break;
75130b57cec5SDimitry Andric     }
75140b57cec5SDimitry Andric     // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
75150b57cec5SDimitry Andric     // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
75160b57cec5SDimitry Andric     // they expect all aliasee summaries to be available.
75170b57cec5SDimitry Andric     case bitc::FS_COMBINED_ALIAS: {
75180b57cec5SDimitry Andric       unsigned ValueID = Record[0];
75190b57cec5SDimitry Andric       uint64_t ModuleId = Record[1];
75200b57cec5SDimitry Andric       uint64_t RawFlags = Record[2];
75210b57cec5SDimitry Andric       unsigned AliaseeValueId = Record[3];
75220b57cec5SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
75238bcb0991SDimitry Andric       auto AS = std::make_unique<AliasSummary>(Flags);
75240b57cec5SDimitry Andric       LastSeenSummary = AS.get();
75250b57cec5SDimitry Andric       AS->setModulePath(ModuleIdMap[ModuleId]);
75260b57cec5SDimitry Andric 
7527bdd1243dSDimitry Andric       auto AliaseeVI = std::get<0>(getValueInfoFromValueId(AliaseeValueId));
75280b57cec5SDimitry Andric       auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, AS->modulePath());
75290b57cec5SDimitry Andric       AS->setAliasee(AliaseeVI, AliaseeInModule);
75300b57cec5SDimitry Andric 
7531bdd1243dSDimitry Andric       ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
75320b57cec5SDimitry Andric       LastSeenGUID = VI.getGUID();
75330b57cec5SDimitry Andric       TheIndex.addGlobalValueSummary(VI, std::move(AS));
75340b57cec5SDimitry Andric       break;
75350b57cec5SDimitry Andric     }
75360b57cec5SDimitry Andric     // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
75370b57cec5SDimitry Andric     case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
75380b57cec5SDimitry Andric       unsigned ValueID = Record[0];
75390b57cec5SDimitry Andric       uint64_t ModuleId = Record[1];
75400b57cec5SDimitry Andric       uint64_t RawFlags = Record[2];
75410b57cec5SDimitry Andric       unsigned RefArrayStart = 3;
75420b57cec5SDimitry Andric       GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false,
75435ffd83dbSDimitry Andric                                       /* WriteOnly */ false,
75445ffd83dbSDimitry Andric                                       /* Constant */ false,
75455ffd83dbSDimitry Andric                                       GlobalObject::VCallVisibilityPublic);
75460b57cec5SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
75470b57cec5SDimitry Andric       if (Version >= 5) {
75480b57cec5SDimitry Andric         GVF = getDecodedGVarFlags(Record[3]);
75490b57cec5SDimitry Andric         RefArrayStart = 4;
75500b57cec5SDimitry Andric       }
75510b57cec5SDimitry Andric       std::vector<ValueInfo> Refs =
75520b57cec5SDimitry Andric           makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
75530b57cec5SDimitry Andric       auto FS =
75548bcb0991SDimitry Andric           std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
75550b57cec5SDimitry Andric       LastSeenSummary = FS.get();
75560b57cec5SDimitry Andric       FS->setModulePath(ModuleIdMap[ModuleId]);
7557bdd1243dSDimitry Andric       ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
75580b57cec5SDimitry Andric       LastSeenGUID = VI.getGUID();
75590b57cec5SDimitry Andric       TheIndex.addGlobalValueSummary(VI, std::move(FS));
75600b57cec5SDimitry Andric       break;
75610b57cec5SDimitry Andric     }
75620b57cec5SDimitry Andric     // FS_COMBINED_ORIGINAL_NAME: [original_name]
75630b57cec5SDimitry Andric     case bitc::FS_COMBINED_ORIGINAL_NAME: {
75640b57cec5SDimitry Andric       uint64_t OriginalName = Record[0];
75650b57cec5SDimitry Andric       if (!LastSeenSummary)
75660b57cec5SDimitry Andric         return error("Name attachment that does not follow a combined record");
75670b57cec5SDimitry Andric       LastSeenSummary->setOriginalName(OriginalName);
75680b57cec5SDimitry Andric       TheIndex.addOriginalName(LastSeenGUID, OriginalName);
75690b57cec5SDimitry Andric       // Reset the LastSeenSummary
75700b57cec5SDimitry Andric       LastSeenSummary = nullptr;
75710b57cec5SDimitry Andric       LastSeenGUID = 0;
75720b57cec5SDimitry Andric       break;
75730b57cec5SDimitry Andric     }
75740b57cec5SDimitry Andric     case bitc::FS_TYPE_TESTS:
75750b57cec5SDimitry Andric       assert(PendingTypeTests.empty());
7576e8d8bef9SDimitry Andric       llvm::append_range(PendingTypeTests, Record);
75770b57cec5SDimitry Andric       break;
75780b57cec5SDimitry Andric 
75790b57cec5SDimitry Andric     case bitc::FS_TYPE_TEST_ASSUME_VCALLS:
75800b57cec5SDimitry Andric       assert(PendingTypeTestAssumeVCalls.empty());
75810b57cec5SDimitry Andric       for (unsigned I = 0; I != Record.size(); I += 2)
75820b57cec5SDimitry Andric         PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
75830b57cec5SDimitry Andric       break;
75840b57cec5SDimitry Andric 
75850b57cec5SDimitry Andric     case bitc::FS_TYPE_CHECKED_LOAD_VCALLS:
75860b57cec5SDimitry Andric       assert(PendingTypeCheckedLoadVCalls.empty());
75870b57cec5SDimitry Andric       for (unsigned I = 0; I != Record.size(); I += 2)
75880b57cec5SDimitry Andric         PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
75890b57cec5SDimitry Andric       break;
75900b57cec5SDimitry Andric 
75910b57cec5SDimitry Andric     case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL:
75920b57cec5SDimitry Andric       PendingTypeTestAssumeConstVCalls.push_back(
75930b57cec5SDimitry Andric           {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
75940b57cec5SDimitry Andric       break;
75950b57cec5SDimitry Andric 
75960b57cec5SDimitry Andric     case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL:
75970b57cec5SDimitry Andric       PendingTypeCheckedLoadConstVCalls.push_back(
75980b57cec5SDimitry Andric           {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
75990b57cec5SDimitry Andric       break;
76000b57cec5SDimitry Andric 
76010b57cec5SDimitry Andric     case bitc::FS_CFI_FUNCTION_DEFS: {
76020b57cec5SDimitry Andric       std::set<std::string> &CfiFunctionDefs = TheIndex.cfiFunctionDefs();
76030b57cec5SDimitry Andric       for (unsigned I = 0; I != Record.size(); I += 2)
76040b57cec5SDimitry Andric         CfiFunctionDefs.insert(
76050b57cec5SDimitry Andric             {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
76060b57cec5SDimitry Andric       break;
76070b57cec5SDimitry Andric     }
76080b57cec5SDimitry Andric 
76090b57cec5SDimitry Andric     case bitc::FS_CFI_FUNCTION_DECLS: {
76100b57cec5SDimitry Andric       std::set<std::string> &CfiFunctionDecls = TheIndex.cfiFunctionDecls();
76110b57cec5SDimitry Andric       for (unsigned I = 0; I != Record.size(); I += 2)
76120b57cec5SDimitry Andric         CfiFunctionDecls.insert(
76130b57cec5SDimitry Andric             {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
76140b57cec5SDimitry Andric       break;
76150b57cec5SDimitry Andric     }
76160b57cec5SDimitry Andric 
76170b57cec5SDimitry Andric     case bitc::FS_TYPE_ID:
76180b57cec5SDimitry Andric       parseTypeIdSummaryRecord(Record, Strtab, TheIndex);
76190b57cec5SDimitry Andric       break;
76200b57cec5SDimitry Andric 
76210b57cec5SDimitry Andric     case bitc::FS_TYPE_ID_METADATA:
76220b57cec5SDimitry Andric       parseTypeIdCompatibleVtableSummaryRecord(Record);
76230b57cec5SDimitry Andric       break;
76245ffd83dbSDimitry Andric 
76255ffd83dbSDimitry Andric     case bitc::FS_BLOCK_COUNT:
76265ffd83dbSDimitry Andric       TheIndex.addBlockCount(Record[0]);
76275ffd83dbSDimitry Andric       break;
76285ffd83dbSDimitry Andric 
76295ffd83dbSDimitry Andric     case bitc::FS_PARAM_ACCESS: {
76305ffd83dbSDimitry Andric       PendingParamAccesses = parseParamAccesses(Record);
76315ffd83dbSDimitry Andric       break;
76325ffd83dbSDimitry Andric     }
7633bdd1243dSDimitry Andric 
7634bdd1243dSDimitry Andric     case bitc::FS_STACK_IDS: { // [n x stackid]
7635bdd1243dSDimitry Andric       // Save stack ids in the reader to consult when adding stack ids from the
7636bdd1243dSDimitry Andric       // lists in the stack node and alloc node entries.
7637bdd1243dSDimitry Andric       StackIds = ArrayRef<uint64_t>(Record);
7638bdd1243dSDimitry Andric       break;
7639bdd1243dSDimitry Andric     }
7640bdd1243dSDimitry Andric 
7641bdd1243dSDimitry Andric     case bitc::FS_PERMODULE_CALLSITE_INFO: {
7642bdd1243dSDimitry Andric       unsigned ValueID = Record[0];
7643bdd1243dSDimitry Andric       SmallVector<unsigned> StackIdList;
7644bdd1243dSDimitry Andric       for (auto R = Record.begin() + 1; R != Record.end(); R++) {
7645bdd1243dSDimitry Andric         assert(*R < StackIds.size());
7646bdd1243dSDimitry Andric         StackIdList.push_back(TheIndex.addOrGetStackIdIndex(StackIds[*R]));
7647bdd1243dSDimitry Andric       }
7648bdd1243dSDimitry Andric       ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
7649bdd1243dSDimitry Andric       PendingCallsites.push_back(CallsiteInfo({VI, std::move(StackIdList)}));
7650bdd1243dSDimitry Andric       break;
7651bdd1243dSDimitry Andric     }
7652bdd1243dSDimitry Andric 
7653bdd1243dSDimitry Andric     case bitc::FS_COMBINED_CALLSITE_INFO: {
7654bdd1243dSDimitry Andric       auto RecordIter = Record.begin();
7655bdd1243dSDimitry Andric       unsigned ValueID = *RecordIter++;
7656bdd1243dSDimitry Andric       unsigned NumStackIds = *RecordIter++;
7657bdd1243dSDimitry Andric       unsigned NumVersions = *RecordIter++;
7658bdd1243dSDimitry Andric       assert(Record.size() == 3 + NumStackIds + NumVersions);
7659bdd1243dSDimitry Andric       SmallVector<unsigned> StackIdList;
7660bdd1243dSDimitry Andric       for (unsigned J = 0; J < NumStackIds; J++) {
7661bdd1243dSDimitry Andric         assert(*RecordIter < StackIds.size());
7662bdd1243dSDimitry Andric         StackIdList.push_back(
7663bdd1243dSDimitry Andric             TheIndex.addOrGetStackIdIndex(StackIds[*RecordIter++]));
7664bdd1243dSDimitry Andric       }
7665bdd1243dSDimitry Andric       SmallVector<unsigned> Versions;
7666bdd1243dSDimitry Andric       for (unsigned J = 0; J < NumVersions; J++)
7667bdd1243dSDimitry Andric         Versions.push_back(*RecordIter++);
7668bdd1243dSDimitry Andric       ValueInfo VI = std::get<0>(
7669bdd1243dSDimitry Andric           getValueInfoFromValueId</*AllowNullValueInfo*/ true>(ValueID));
7670bdd1243dSDimitry Andric       PendingCallsites.push_back(
7671bdd1243dSDimitry Andric           CallsiteInfo({VI, std::move(Versions), std::move(StackIdList)}));
7672bdd1243dSDimitry Andric       break;
7673bdd1243dSDimitry Andric     }
7674bdd1243dSDimitry Andric 
7675bdd1243dSDimitry Andric     case bitc::FS_PERMODULE_ALLOC_INFO: {
7676bdd1243dSDimitry Andric       unsigned I = 0;
7677bdd1243dSDimitry Andric       std::vector<MIBInfo> MIBs;
7678bdd1243dSDimitry Andric       while (I < Record.size()) {
7679bdd1243dSDimitry Andric         assert(Record.size() - I >= 2);
7680bdd1243dSDimitry Andric         AllocationType AllocType = (AllocationType)Record[I++];
7681bdd1243dSDimitry Andric         unsigned NumStackEntries = Record[I++];
7682bdd1243dSDimitry Andric         assert(Record.size() - I >= NumStackEntries);
7683bdd1243dSDimitry Andric         SmallVector<unsigned> StackIdList;
7684bdd1243dSDimitry Andric         for (unsigned J = 0; J < NumStackEntries; J++) {
7685bdd1243dSDimitry Andric           assert(Record[I] < StackIds.size());
7686bdd1243dSDimitry Andric           StackIdList.push_back(
7687bdd1243dSDimitry Andric               TheIndex.addOrGetStackIdIndex(StackIds[Record[I++]]));
7688bdd1243dSDimitry Andric         }
7689bdd1243dSDimitry Andric         MIBs.push_back(MIBInfo(AllocType, std::move(StackIdList)));
7690bdd1243dSDimitry Andric       }
7691bdd1243dSDimitry Andric       PendingAllocs.push_back(AllocInfo(std::move(MIBs)));
7692bdd1243dSDimitry Andric       break;
7693bdd1243dSDimitry Andric     }
7694bdd1243dSDimitry Andric 
7695bdd1243dSDimitry Andric     case bitc::FS_COMBINED_ALLOC_INFO: {
7696bdd1243dSDimitry Andric       unsigned I = 0;
7697bdd1243dSDimitry Andric       std::vector<MIBInfo> MIBs;
7698bdd1243dSDimitry Andric       unsigned NumMIBs = Record[I++];
7699bdd1243dSDimitry Andric       unsigned NumVersions = Record[I++];
7700bdd1243dSDimitry Andric       unsigned MIBsRead = 0;
7701bdd1243dSDimitry Andric       while (MIBsRead++ < NumMIBs) {
7702bdd1243dSDimitry Andric         assert(Record.size() - I >= 2);
7703bdd1243dSDimitry Andric         AllocationType AllocType = (AllocationType)Record[I++];
7704bdd1243dSDimitry Andric         unsigned NumStackEntries = Record[I++];
7705bdd1243dSDimitry Andric         assert(Record.size() - I >= NumStackEntries);
7706bdd1243dSDimitry Andric         SmallVector<unsigned> StackIdList;
7707bdd1243dSDimitry Andric         for (unsigned J = 0; J < NumStackEntries; J++) {
7708bdd1243dSDimitry Andric           assert(Record[I] < StackIds.size());
7709bdd1243dSDimitry Andric           StackIdList.push_back(
7710bdd1243dSDimitry Andric               TheIndex.addOrGetStackIdIndex(StackIds[Record[I++]]));
7711bdd1243dSDimitry Andric         }
7712bdd1243dSDimitry Andric         MIBs.push_back(MIBInfo(AllocType, std::move(StackIdList)));
7713bdd1243dSDimitry Andric       }
7714bdd1243dSDimitry Andric       assert(Record.size() - I >= NumVersions);
7715bdd1243dSDimitry Andric       SmallVector<uint8_t> Versions;
7716bdd1243dSDimitry Andric       for (unsigned J = 0; J < NumVersions; J++)
7717bdd1243dSDimitry Andric         Versions.push_back(Record[I++]);
7718bdd1243dSDimitry Andric       PendingAllocs.push_back(
7719bdd1243dSDimitry Andric           AllocInfo(std::move(Versions), std::move(MIBs)));
7720bdd1243dSDimitry Andric       break;
7721bdd1243dSDimitry Andric     }
77220b57cec5SDimitry Andric     }
77230b57cec5SDimitry Andric   }
77240b57cec5SDimitry Andric   llvm_unreachable("Exit infinite loop");
77250b57cec5SDimitry Andric }
77260b57cec5SDimitry Andric 
77270b57cec5SDimitry Andric // Parse the  module string table block into the Index.
77280b57cec5SDimitry Andric // This populates the ModulePathStringTable map in the index.
77290b57cec5SDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
77300b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
77310b57cec5SDimitry Andric     return Err;
77320b57cec5SDimitry Andric 
77330b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
77340b57cec5SDimitry Andric 
77350b57cec5SDimitry Andric   SmallString<128> ModulePath;
77360b57cec5SDimitry Andric   ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr;
77370b57cec5SDimitry Andric 
77380b57cec5SDimitry Andric   while (true) {
77390b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
77400b57cec5SDimitry Andric     if (!MaybeEntry)
77410b57cec5SDimitry Andric       return MaybeEntry.takeError();
77420b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
77430b57cec5SDimitry Andric 
77440b57cec5SDimitry Andric     switch (Entry.Kind) {
77450b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
77460b57cec5SDimitry Andric     case BitstreamEntry::Error:
77470b57cec5SDimitry Andric       return error("Malformed block");
77480b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
77490b57cec5SDimitry Andric       return Error::success();
77500b57cec5SDimitry Andric     case BitstreamEntry::Record:
77510b57cec5SDimitry Andric       // The interesting case.
77520b57cec5SDimitry Andric       break;
77530b57cec5SDimitry Andric     }
77540b57cec5SDimitry Andric 
77550b57cec5SDimitry Andric     Record.clear();
77560b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
77570b57cec5SDimitry Andric     if (!MaybeRecord)
77580b57cec5SDimitry Andric       return MaybeRecord.takeError();
77590b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
77600b57cec5SDimitry Andric     default: // Default behavior: ignore.
77610b57cec5SDimitry Andric       break;
77620b57cec5SDimitry Andric     case bitc::MST_CODE_ENTRY: {
77630b57cec5SDimitry Andric       // MST_ENTRY: [modid, namechar x N]
77640b57cec5SDimitry Andric       uint64_t ModuleId = Record[0];
77650b57cec5SDimitry Andric 
77660b57cec5SDimitry Andric       if (convertToString(Record, 1, ModulePath))
77670b57cec5SDimitry Andric         return error("Invalid record");
77680b57cec5SDimitry Andric 
7769*c9157d92SDimitry Andric       LastSeenModule = TheIndex.addModule(ModulePath);
77700b57cec5SDimitry Andric       ModuleIdMap[ModuleId] = LastSeenModule->first();
77710b57cec5SDimitry Andric 
77720b57cec5SDimitry Andric       ModulePath.clear();
77730b57cec5SDimitry Andric       break;
77740b57cec5SDimitry Andric     }
77750b57cec5SDimitry Andric     /// MST_CODE_HASH: [5*i32]
77760b57cec5SDimitry Andric     case bitc::MST_CODE_HASH: {
77770b57cec5SDimitry Andric       if (Record.size() != 5)
77780b57cec5SDimitry Andric         return error("Invalid hash length " + Twine(Record.size()).str());
77790b57cec5SDimitry Andric       if (!LastSeenModule)
77800b57cec5SDimitry Andric         return error("Invalid hash that does not follow a module path");
77810b57cec5SDimitry Andric       int Pos = 0;
77820b57cec5SDimitry Andric       for (auto &Val : Record) {
77830b57cec5SDimitry Andric         assert(!(Val >> 32) && "Unexpected high bits set");
7784*c9157d92SDimitry Andric         LastSeenModule->second[Pos++] = Val;
77850b57cec5SDimitry Andric       }
77860b57cec5SDimitry Andric       // Reset LastSeenModule to avoid overriding the hash unexpectedly.
77870b57cec5SDimitry Andric       LastSeenModule = nullptr;
77880b57cec5SDimitry Andric       break;
77890b57cec5SDimitry Andric     }
77900b57cec5SDimitry Andric     }
77910b57cec5SDimitry Andric   }
77920b57cec5SDimitry Andric   llvm_unreachable("Exit infinite loop");
77930b57cec5SDimitry Andric }
77940b57cec5SDimitry Andric 
77950b57cec5SDimitry Andric namespace {
77960b57cec5SDimitry Andric 
77970b57cec5SDimitry Andric // FIXME: This class is only here to support the transition to llvm::Error. It
77980b57cec5SDimitry Andric // will be removed once this transition is complete. Clients should prefer to
77990b57cec5SDimitry Andric // deal with the Error value directly, rather than converting to error_code.
78000b57cec5SDimitry Andric class BitcodeErrorCategoryType : public std::error_category {
78010b57cec5SDimitry Andric   const char *name() const noexcept override {
78020b57cec5SDimitry Andric     return "llvm.bitcode";
78030b57cec5SDimitry Andric   }
78040b57cec5SDimitry Andric 
78050b57cec5SDimitry Andric   std::string message(int IE) const override {
78060b57cec5SDimitry Andric     BitcodeError E = static_cast<BitcodeError>(IE);
78070b57cec5SDimitry Andric     switch (E) {
78080b57cec5SDimitry Andric     case BitcodeError::CorruptedBitcode:
78090b57cec5SDimitry Andric       return "Corrupted bitcode";
78100b57cec5SDimitry Andric     }
78110b57cec5SDimitry Andric     llvm_unreachable("Unknown error type!");
78120b57cec5SDimitry Andric   }
78130b57cec5SDimitry Andric };
78140b57cec5SDimitry Andric 
78150b57cec5SDimitry Andric } // end anonymous namespace
78160b57cec5SDimitry Andric 
78170b57cec5SDimitry Andric const std::error_category &llvm::BitcodeErrorCategory() {
7818753f127fSDimitry Andric   static BitcodeErrorCategoryType ErrorCategory;
7819753f127fSDimitry Andric   return ErrorCategory;
78200b57cec5SDimitry Andric }
78210b57cec5SDimitry Andric 
78220b57cec5SDimitry Andric static Expected<StringRef> readBlobInRecord(BitstreamCursor &Stream,
78230b57cec5SDimitry Andric                                             unsigned Block, unsigned RecordID) {
78240b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(Block))
78250b57cec5SDimitry Andric     return std::move(Err);
78260b57cec5SDimitry Andric 
78270b57cec5SDimitry Andric   StringRef Strtab;
78280b57cec5SDimitry Andric   while (true) {
78290b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
78300b57cec5SDimitry Andric     if (!MaybeEntry)
78310b57cec5SDimitry Andric       return MaybeEntry.takeError();
78320b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
78330b57cec5SDimitry Andric 
78340b57cec5SDimitry Andric     switch (Entry.Kind) {
78350b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
78360b57cec5SDimitry Andric       return Strtab;
78370b57cec5SDimitry Andric 
78380b57cec5SDimitry Andric     case BitstreamEntry::Error:
78390b57cec5SDimitry Andric       return error("Malformed block");
78400b57cec5SDimitry Andric 
78410b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
78420b57cec5SDimitry Andric       if (Error Err = Stream.SkipBlock())
78430b57cec5SDimitry Andric         return std::move(Err);
78440b57cec5SDimitry Andric       break;
78450b57cec5SDimitry Andric 
78460b57cec5SDimitry Andric     case BitstreamEntry::Record:
78470b57cec5SDimitry Andric       StringRef Blob;
78480b57cec5SDimitry Andric       SmallVector<uint64_t, 1> Record;
78490b57cec5SDimitry Andric       Expected<unsigned> MaybeRecord =
78500b57cec5SDimitry Andric           Stream.readRecord(Entry.ID, Record, &Blob);
78510b57cec5SDimitry Andric       if (!MaybeRecord)
78520b57cec5SDimitry Andric         return MaybeRecord.takeError();
78530b57cec5SDimitry Andric       if (MaybeRecord.get() == RecordID)
78540b57cec5SDimitry Andric         Strtab = Blob;
78550b57cec5SDimitry Andric       break;
78560b57cec5SDimitry Andric     }
78570b57cec5SDimitry Andric   }
78580b57cec5SDimitry Andric }
78590b57cec5SDimitry Andric 
78600b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
78610b57cec5SDimitry Andric // External interface
78620b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
78630b57cec5SDimitry Andric 
78640b57cec5SDimitry Andric Expected<std::vector<BitcodeModule>>
78650b57cec5SDimitry Andric llvm::getBitcodeModuleList(MemoryBufferRef Buffer) {
78660b57cec5SDimitry Andric   auto FOrErr = getBitcodeFileContents(Buffer);
78670b57cec5SDimitry Andric   if (!FOrErr)
78680b57cec5SDimitry Andric     return FOrErr.takeError();
78690b57cec5SDimitry Andric   return std::move(FOrErr->Mods);
78700b57cec5SDimitry Andric }
78710b57cec5SDimitry Andric 
78720b57cec5SDimitry Andric Expected<BitcodeFileContents>
78730b57cec5SDimitry Andric llvm::getBitcodeFileContents(MemoryBufferRef Buffer) {
78740b57cec5SDimitry Andric   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
78750b57cec5SDimitry Andric   if (!StreamOrErr)
78760b57cec5SDimitry Andric     return StreamOrErr.takeError();
78770b57cec5SDimitry Andric   BitstreamCursor &Stream = *StreamOrErr;
78780b57cec5SDimitry Andric 
78790b57cec5SDimitry Andric   BitcodeFileContents F;
78800b57cec5SDimitry Andric   while (true) {
78810b57cec5SDimitry Andric     uint64_t BCBegin = Stream.getCurrentByteNo();
78820b57cec5SDimitry Andric 
78830b57cec5SDimitry Andric     // We may be consuming bitcode from a client that leaves garbage at the end
78840b57cec5SDimitry Andric     // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to
78850b57cec5SDimitry Andric     // the end that there cannot possibly be another module, stop looking.
78860b57cec5SDimitry Andric     if (BCBegin + 8 >= Stream.getBitcodeBytes().size())
78870b57cec5SDimitry Andric       return F;
78880b57cec5SDimitry Andric 
78890b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
78900b57cec5SDimitry Andric     if (!MaybeEntry)
78910b57cec5SDimitry Andric       return MaybeEntry.takeError();
78920b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
78930b57cec5SDimitry Andric 
78940b57cec5SDimitry Andric     switch (Entry.Kind) {
78950b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
78960b57cec5SDimitry Andric     case BitstreamEntry::Error:
78970b57cec5SDimitry Andric       return error("Malformed block");
78980b57cec5SDimitry Andric 
78990b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: {
79000b57cec5SDimitry Andric       uint64_t IdentificationBit = -1ull;
79010b57cec5SDimitry Andric       if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
79020b57cec5SDimitry Andric         IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8;
79030b57cec5SDimitry Andric         if (Error Err = Stream.SkipBlock())
79040b57cec5SDimitry Andric           return std::move(Err);
79050b57cec5SDimitry Andric 
79060b57cec5SDimitry Andric         {
79070b57cec5SDimitry Andric           Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
79080b57cec5SDimitry Andric           if (!MaybeEntry)
79090b57cec5SDimitry Andric             return MaybeEntry.takeError();
79100b57cec5SDimitry Andric           Entry = MaybeEntry.get();
79110b57cec5SDimitry Andric         }
79120b57cec5SDimitry Andric 
79130b57cec5SDimitry Andric         if (Entry.Kind != BitstreamEntry::SubBlock ||
79140b57cec5SDimitry Andric             Entry.ID != bitc::MODULE_BLOCK_ID)
79150b57cec5SDimitry Andric           return error("Malformed block");
79160b57cec5SDimitry Andric       }
79170b57cec5SDimitry Andric 
79180b57cec5SDimitry Andric       if (Entry.ID == bitc::MODULE_BLOCK_ID) {
79190b57cec5SDimitry Andric         uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8;
79200b57cec5SDimitry Andric         if (Error Err = Stream.SkipBlock())
79210b57cec5SDimitry Andric           return std::move(Err);
79220b57cec5SDimitry Andric 
79230b57cec5SDimitry Andric         F.Mods.push_back({Stream.getBitcodeBytes().slice(
79240b57cec5SDimitry Andric                               BCBegin, Stream.getCurrentByteNo() - BCBegin),
79250b57cec5SDimitry Andric                           Buffer.getBufferIdentifier(), IdentificationBit,
79260b57cec5SDimitry Andric                           ModuleBit});
79270b57cec5SDimitry Andric         continue;
79280b57cec5SDimitry Andric       }
79290b57cec5SDimitry Andric 
79300b57cec5SDimitry Andric       if (Entry.ID == bitc::STRTAB_BLOCK_ID) {
79310b57cec5SDimitry Andric         Expected<StringRef> Strtab =
79320b57cec5SDimitry Andric             readBlobInRecord(Stream, bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB);
79330b57cec5SDimitry Andric         if (!Strtab)
79340b57cec5SDimitry Andric           return Strtab.takeError();
79350b57cec5SDimitry Andric         // This string table is used by every preceding bitcode module that does
79360b57cec5SDimitry Andric         // not have its own string table. A bitcode file may have multiple
79370b57cec5SDimitry Andric         // string tables if it was created by binary concatenation, for example
79380b57cec5SDimitry Andric         // with "llvm-cat -b".
79390eae32dcSDimitry Andric         for (BitcodeModule &I : llvm::reverse(F.Mods)) {
79400eae32dcSDimitry Andric           if (!I.Strtab.empty())
79410b57cec5SDimitry Andric             break;
79420eae32dcSDimitry Andric           I.Strtab = *Strtab;
79430b57cec5SDimitry Andric         }
79440b57cec5SDimitry Andric         // Similarly, the string table is used by every preceding symbol table;
79450b57cec5SDimitry Andric         // normally there will be just one unless the bitcode file was created
79460b57cec5SDimitry Andric         // by binary concatenation.
79470b57cec5SDimitry Andric         if (!F.Symtab.empty() && F.StrtabForSymtab.empty())
79480b57cec5SDimitry Andric           F.StrtabForSymtab = *Strtab;
79490b57cec5SDimitry Andric         continue;
79500b57cec5SDimitry Andric       }
79510b57cec5SDimitry Andric 
79520b57cec5SDimitry Andric       if (Entry.ID == bitc::SYMTAB_BLOCK_ID) {
79530b57cec5SDimitry Andric         Expected<StringRef> SymtabOrErr =
79540b57cec5SDimitry Andric             readBlobInRecord(Stream, bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB);
79550b57cec5SDimitry Andric         if (!SymtabOrErr)
79560b57cec5SDimitry Andric           return SymtabOrErr.takeError();
79570b57cec5SDimitry Andric 
79580b57cec5SDimitry Andric         // We can expect the bitcode file to have multiple symbol tables if it
79590b57cec5SDimitry Andric         // was created by binary concatenation. In that case we silently
79600b57cec5SDimitry Andric         // ignore any subsequent symbol tables, which is fine because this is a
79610b57cec5SDimitry Andric         // low level function. The client is expected to notice that the number
79620b57cec5SDimitry Andric         // of modules in the symbol table does not match the number of modules
79630b57cec5SDimitry Andric         // in the input file and regenerate the symbol table.
79640b57cec5SDimitry Andric         if (F.Symtab.empty())
79650b57cec5SDimitry Andric           F.Symtab = *SymtabOrErr;
79660b57cec5SDimitry Andric         continue;
79670b57cec5SDimitry Andric       }
79680b57cec5SDimitry Andric 
79690b57cec5SDimitry Andric       if (Error Err = Stream.SkipBlock())
79700b57cec5SDimitry Andric         return std::move(Err);
79710b57cec5SDimitry Andric       continue;
79720b57cec5SDimitry Andric     }
79730b57cec5SDimitry Andric     case BitstreamEntry::Record:
7974349cc55cSDimitry Andric       if (Error E = Stream.skipRecord(Entry.ID).takeError())
7975349cc55cSDimitry Andric         return std::move(E);
79760b57cec5SDimitry Andric       continue;
79770b57cec5SDimitry Andric     }
79780b57cec5SDimitry Andric   }
79790b57cec5SDimitry Andric }
79800b57cec5SDimitry Andric 
79810b57cec5SDimitry Andric /// Get a lazy one-at-time loading module from bitcode.
79820b57cec5SDimitry Andric ///
79830b57cec5SDimitry Andric /// This isn't always used in a lazy context.  In particular, it's also used by
79840b57cec5SDimitry Andric /// \a parseModule().  If this is truly lazy, then we need to eagerly pull
79850b57cec5SDimitry Andric /// in forward-referenced functions from block address references.
79860b57cec5SDimitry Andric ///
79870b57cec5SDimitry Andric /// \param[in] MaterializeAll Set to \c true if we should materialize
79880b57cec5SDimitry Andric /// everything.
79890b57cec5SDimitry Andric Expected<std::unique_ptr<Module>>
79900b57cec5SDimitry Andric BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll,
79915ffd83dbSDimitry Andric                              bool ShouldLazyLoadMetadata, bool IsImporting,
7992bdd1243dSDimitry Andric                              ParserCallbacks Callbacks) {
79930b57cec5SDimitry Andric   BitstreamCursor Stream(Buffer);
79940b57cec5SDimitry Andric 
79950b57cec5SDimitry Andric   std::string ProducerIdentification;
79960b57cec5SDimitry Andric   if (IdentificationBit != -1ull) {
79970b57cec5SDimitry Andric     if (Error JumpFailed = Stream.JumpToBit(IdentificationBit))
79980b57cec5SDimitry Andric       return std::move(JumpFailed);
7999349cc55cSDimitry Andric     if (Error E =
8000349cc55cSDimitry Andric             readIdentificationBlock(Stream).moveInto(ProducerIdentification))
8001349cc55cSDimitry Andric       return std::move(E);
80020b57cec5SDimitry Andric   }
80030b57cec5SDimitry Andric 
80040b57cec5SDimitry Andric   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
80050b57cec5SDimitry Andric     return std::move(JumpFailed);
80060b57cec5SDimitry Andric   auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
80070b57cec5SDimitry Andric                               Context);
80080b57cec5SDimitry Andric 
80090b57cec5SDimitry Andric   std::unique_ptr<Module> M =
80108bcb0991SDimitry Andric       std::make_unique<Module>(ModuleIdentifier, Context);
80110b57cec5SDimitry Andric   M->setMaterializer(R);
80120b57cec5SDimitry Andric 
80130b57cec5SDimitry Andric   // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
80145ffd83dbSDimitry Andric   if (Error Err = R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata,
8015bdd1243dSDimitry Andric                                       IsImporting, Callbacks))
80160b57cec5SDimitry Andric     return std::move(Err);
80170b57cec5SDimitry Andric 
80180b57cec5SDimitry Andric   if (MaterializeAll) {
80190b57cec5SDimitry Andric     // Read in the entire module, and destroy the BitcodeReader.
80200b57cec5SDimitry Andric     if (Error Err = M->materializeAll())
80210b57cec5SDimitry Andric       return std::move(Err);
80220b57cec5SDimitry Andric   } else {
80230b57cec5SDimitry Andric     // Resolve forward references from blockaddresses.
80240b57cec5SDimitry Andric     if (Error Err = R->materializeForwardReferencedFunctions())
80250b57cec5SDimitry Andric       return std::move(Err);
80260b57cec5SDimitry Andric   }
80270b57cec5SDimitry Andric   return std::move(M);
80280b57cec5SDimitry Andric }
80290b57cec5SDimitry Andric 
80300b57cec5SDimitry Andric Expected<std::unique_ptr<Module>>
80310b57cec5SDimitry Andric BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata,
8032bdd1243dSDimitry Andric                              bool IsImporting, ParserCallbacks Callbacks) {
80335ffd83dbSDimitry Andric   return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting,
8034bdd1243dSDimitry Andric                        Callbacks);
80350b57cec5SDimitry Andric }
80360b57cec5SDimitry Andric 
80370b57cec5SDimitry Andric // Parse the specified bitcode buffer and merge the index into CombinedIndex.
80380b57cec5SDimitry Andric // We don't use ModuleIdentifier here because the client may need to control the
80390b57cec5SDimitry Andric // module path used in the combined summary (e.g. when reading summaries for
80400b57cec5SDimitry Andric // regular LTO modules).
8041bdd1243dSDimitry Andric Error BitcodeModule::readSummary(
8042*c9157d92SDimitry Andric     ModuleSummaryIndex &CombinedIndex, StringRef ModulePath,
8043bdd1243dSDimitry Andric     std::function<bool(GlobalValue::GUID)> IsPrevailing) {
80440b57cec5SDimitry Andric   BitstreamCursor Stream(Buffer);
80450b57cec5SDimitry Andric   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
80460b57cec5SDimitry Andric     return JumpFailed;
80470b57cec5SDimitry Andric 
80480b57cec5SDimitry Andric   ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
8049*c9157d92SDimitry Andric                                     ModulePath, IsPrevailing);
80500b57cec5SDimitry Andric   return R.parseModule();
80510b57cec5SDimitry Andric }
80520b57cec5SDimitry Andric 
80530b57cec5SDimitry Andric // Parse the specified bitcode buffer, returning the function info index.
80540b57cec5SDimitry Andric Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() {
80550b57cec5SDimitry Andric   BitstreamCursor Stream(Buffer);
80560b57cec5SDimitry Andric   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
80570b57cec5SDimitry Andric     return std::move(JumpFailed);
80580b57cec5SDimitry Andric 
80598bcb0991SDimitry Andric   auto Index = std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
80600b57cec5SDimitry Andric   ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,
80610b57cec5SDimitry Andric                                     ModuleIdentifier, 0);
80620b57cec5SDimitry Andric 
80630b57cec5SDimitry Andric   if (Error Err = R.parseModule())
80640b57cec5SDimitry Andric     return std::move(Err);
80650b57cec5SDimitry Andric 
80660b57cec5SDimitry Andric   return std::move(Index);
80670b57cec5SDimitry Andric }
80680b57cec5SDimitry Andric 
8069fe013be4SDimitry Andric static Expected<std::pair<bool, bool>>
8070fe013be4SDimitry Andric getEnableSplitLTOUnitAndUnifiedFlag(BitstreamCursor &Stream,
8071fe013be4SDimitry Andric                                                  unsigned ID,
8072fe013be4SDimitry Andric                                                  BitcodeLTOInfo &LTOInfo) {
80730b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(ID))
80740b57cec5SDimitry Andric     return std::move(Err);
80750b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
80760b57cec5SDimitry Andric 
80770b57cec5SDimitry Andric   while (true) {
8078349cc55cSDimitry Andric     BitstreamEntry Entry;
8079fe013be4SDimitry Andric     std::pair<bool, bool> Result = {false,false};
8080349cc55cSDimitry Andric     if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
8081349cc55cSDimitry Andric       return std::move(E);
80820b57cec5SDimitry Andric 
80830b57cec5SDimitry Andric     switch (Entry.Kind) {
80840b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
80850b57cec5SDimitry Andric     case BitstreamEntry::Error:
80860b57cec5SDimitry Andric       return error("Malformed block");
8087fe013be4SDimitry Andric     case BitstreamEntry::EndBlock: {
8088fe013be4SDimitry Andric       // If no flags record found, set both flags to false.
8089fe013be4SDimitry Andric       return Result;
8090fe013be4SDimitry Andric     }
80910b57cec5SDimitry Andric     case BitstreamEntry::Record:
80920b57cec5SDimitry Andric       // The interesting case.
80930b57cec5SDimitry Andric       break;
80940b57cec5SDimitry Andric     }
80950b57cec5SDimitry Andric 
80960b57cec5SDimitry Andric     // Look for the FS_FLAGS record.
80970b57cec5SDimitry Andric     Record.clear();
80980b57cec5SDimitry Andric     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
80990b57cec5SDimitry Andric     if (!MaybeBitCode)
81000b57cec5SDimitry Andric       return MaybeBitCode.takeError();
81010b57cec5SDimitry Andric     switch (MaybeBitCode.get()) {
81020b57cec5SDimitry Andric     default: // Default behavior: ignore.
81030b57cec5SDimitry Andric       break;
81040b57cec5SDimitry Andric     case bitc::FS_FLAGS: { // [flags]
81050b57cec5SDimitry Andric       uint64_t Flags = Record[0];
81060b57cec5SDimitry Andric       // Scan flags.
8107fe013be4SDimitry Andric       assert(Flags <= 0x2ff && "Unexpected bits in flag");
81080b57cec5SDimitry Andric 
8109fe013be4SDimitry Andric       bool EnableSplitLTOUnit = Flags & 0x8;
8110fe013be4SDimitry Andric       bool UnifiedLTO = Flags & 0x200;
8111fe013be4SDimitry Andric       Result = {EnableSplitLTOUnit, UnifiedLTO};
8112fe013be4SDimitry Andric 
8113fe013be4SDimitry Andric       return Result;
81140b57cec5SDimitry Andric     }
81150b57cec5SDimitry Andric     }
81160b57cec5SDimitry Andric   }
81170b57cec5SDimitry Andric   llvm_unreachable("Exit infinite loop");
81180b57cec5SDimitry Andric }
81190b57cec5SDimitry Andric 
81200b57cec5SDimitry Andric // Check if the given bitcode buffer contains a global value summary block.
81210b57cec5SDimitry Andric Expected<BitcodeLTOInfo> BitcodeModule::getLTOInfo() {
81220b57cec5SDimitry Andric   BitstreamCursor Stream(Buffer);
81230b57cec5SDimitry Andric   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
81240b57cec5SDimitry Andric     return std::move(JumpFailed);
81250b57cec5SDimitry Andric 
81260b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
81270b57cec5SDimitry Andric     return std::move(Err);
81280b57cec5SDimitry Andric 
81290b57cec5SDimitry Andric   while (true) {
8130349cc55cSDimitry Andric     llvm::BitstreamEntry Entry;
8131349cc55cSDimitry Andric     if (Error E = Stream.advance().moveInto(Entry))
8132349cc55cSDimitry Andric       return std::move(E);
81330b57cec5SDimitry Andric 
81340b57cec5SDimitry Andric     switch (Entry.Kind) {
81350b57cec5SDimitry Andric     case BitstreamEntry::Error:
81360b57cec5SDimitry Andric       return error("Malformed block");
81370b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
81380b57cec5SDimitry Andric       return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/false,
8139fe013be4SDimitry Andric                             /*EnableSplitLTOUnit=*/false, /*UnifiedLTO=*/false};
81400b57cec5SDimitry Andric 
81410b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
81420b57cec5SDimitry Andric       if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) {
8143fe013be4SDimitry Andric         BitcodeLTOInfo LTOInfo;
8144fe013be4SDimitry Andric         Expected<std::pair<bool, bool>> Flags =
8145fe013be4SDimitry Andric             getEnableSplitLTOUnitAndUnifiedFlag(Stream, Entry.ID, LTOInfo);
8146fe013be4SDimitry Andric         if (!Flags)
8147fe013be4SDimitry Andric           return Flags.takeError();
8148fe013be4SDimitry Andric         std::tie(LTOInfo.EnableSplitLTOUnit, LTOInfo.UnifiedLTO) = Flags.get();
8149fe013be4SDimitry Andric         LTOInfo.IsThinLTO = true;
8150fe013be4SDimitry Andric         LTOInfo.HasSummary = true;
8151fe013be4SDimitry Andric         return LTOInfo;
81520b57cec5SDimitry Andric       }
81530b57cec5SDimitry Andric 
81540b57cec5SDimitry Andric       if (Entry.ID == bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID) {
8155fe013be4SDimitry Andric         BitcodeLTOInfo LTOInfo;
8156fe013be4SDimitry Andric         Expected<std::pair<bool, bool>> Flags =
8157fe013be4SDimitry Andric             getEnableSplitLTOUnitAndUnifiedFlag(Stream, Entry.ID, LTOInfo);
8158fe013be4SDimitry Andric         if (!Flags)
8159fe013be4SDimitry Andric           return Flags.takeError();
8160fe013be4SDimitry Andric         std::tie(LTOInfo.EnableSplitLTOUnit, LTOInfo.UnifiedLTO) = Flags.get();
8161fe013be4SDimitry Andric         LTOInfo.IsThinLTO = false;
8162fe013be4SDimitry Andric         LTOInfo.HasSummary = true;
8163fe013be4SDimitry Andric         return LTOInfo;
81640b57cec5SDimitry Andric       }
81650b57cec5SDimitry Andric 
81660b57cec5SDimitry Andric       // Ignore other sub-blocks.
81670b57cec5SDimitry Andric       if (Error Err = Stream.SkipBlock())
81680b57cec5SDimitry Andric         return std::move(Err);
81690b57cec5SDimitry Andric       continue;
81700b57cec5SDimitry Andric 
81710b57cec5SDimitry Andric     case BitstreamEntry::Record:
81720b57cec5SDimitry Andric       if (Expected<unsigned> StreamFailed = Stream.skipRecord(Entry.ID))
81730b57cec5SDimitry Andric         continue;
81740b57cec5SDimitry Andric       else
81750b57cec5SDimitry Andric         return StreamFailed.takeError();
81760b57cec5SDimitry Andric     }
81770b57cec5SDimitry Andric   }
81780b57cec5SDimitry Andric }
81790b57cec5SDimitry Andric 
81800b57cec5SDimitry Andric static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) {
81810b57cec5SDimitry Andric   Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer);
81820b57cec5SDimitry Andric   if (!MsOrErr)
81830b57cec5SDimitry Andric     return MsOrErr.takeError();
81840b57cec5SDimitry Andric 
81850b57cec5SDimitry Andric   if (MsOrErr->size() != 1)
81860b57cec5SDimitry Andric     return error("Expected a single module");
81870b57cec5SDimitry Andric 
81880b57cec5SDimitry Andric   return (*MsOrErr)[0];
81890b57cec5SDimitry Andric }
81900b57cec5SDimitry Andric 
81910b57cec5SDimitry Andric Expected<std::unique_ptr<Module>>
81920b57cec5SDimitry Andric llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context,
8193bdd1243dSDimitry Andric                            bool ShouldLazyLoadMetadata, bool IsImporting,
8194bdd1243dSDimitry Andric                            ParserCallbacks Callbacks) {
81950b57cec5SDimitry Andric   Expected<BitcodeModule> BM = getSingleModule(Buffer);
81960b57cec5SDimitry Andric   if (!BM)
81970b57cec5SDimitry Andric     return BM.takeError();
81980b57cec5SDimitry Andric 
8199bdd1243dSDimitry Andric   return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting,
8200bdd1243dSDimitry Andric                            Callbacks);
82010b57cec5SDimitry Andric }
82020b57cec5SDimitry Andric 
82030b57cec5SDimitry Andric Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule(
82040b57cec5SDimitry Andric     std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
8205bdd1243dSDimitry Andric     bool ShouldLazyLoadMetadata, bool IsImporting, ParserCallbacks Callbacks) {
82060b57cec5SDimitry Andric   auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata,
8207bdd1243dSDimitry Andric                                      IsImporting, Callbacks);
82080b57cec5SDimitry Andric   if (MOrErr)
82090b57cec5SDimitry Andric     (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
82100b57cec5SDimitry Andric   return MOrErr;
82110b57cec5SDimitry Andric }
82120b57cec5SDimitry Andric 
82130b57cec5SDimitry Andric Expected<std::unique_ptr<Module>>
8214bdd1243dSDimitry Andric BitcodeModule::parseModule(LLVMContext &Context, ParserCallbacks Callbacks) {
8215bdd1243dSDimitry Andric   return getModuleImpl(Context, true, false, false, Callbacks);
82160b57cec5SDimitry Andric   // TODO: Restore the use-lists to the in-memory state when the bitcode was
82170b57cec5SDimitry Andric   // written.  We must defer until the Module has been fully materialized.
82180b57cec5SDimitry Andric }
82190b57cec5SDimitry Andric 
82205ffd83dbSDimitry Andric Expected<std::unique_ptr<Module>>
82215ffd83dbSDimitry Andric llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
8222bdd1243dSDimitry Andric                        ParserCallbacks Callbacks) {
82230b57cec5SDimitry Andric   Expected<BitcodeModule> BM = getSingleModule(Buffer);
82240b57cec5SDimitry Andric   if (!BM)
82250b57cec5SDimitry Andric     return BM.takeError();
82260b57cec5SDimitry Andric 
8227bdd1243dSDimitry Andric   return BM->parseModule(Context, Callbacks);
82280b57cec5SDimitry Andric }
82290b57cec5SDimitry Andric 
82300b57cec5SDimitry Andric Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) {
82310b57cec5SDimitry Andric   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
82320b57cec5SDimitry Andric   if (!StreamOrErr)
82330b57cec5SDimitry Andric     return StreamOrErr.takeError();
82340b57cec5SDimitry Andric 
82350b57cec5SDimitry Andric   return readTriple(*StreamOrErr);
82360b57cec5SDimitry Andric }
82370b57cec5SDimitry Andric 
82380b57cec5SDimitry Andric Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) {
82390b57cec5SDimitry Andric   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
82400b57cec5SDimitry Andric   if (!StreamOrErr)
82410b57cec5SDimitry Andric     return StreamOrErr.takeError();
82420b57cec5SDimitry Andric 
82430b57cec5SDimitry Andric   return hasObjCCategory(*StreamOrErr);
82440b57cec5SDimitry Andric }
82450b57cec5SDimitry Andric 
82460b57cec5SDimitry Andric Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) {
82470b57cec5SDimitry Andric   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
82480b57cec5SDimitry Andric   if (!StreamOrErr)
82490b57cec5SDimitry Andric     return StreamOrErr.takeError();
82500b57cec5SDimitry Andric 
82510b57cec5SDimitry Andric   return readIdentificationCode(*StreamOrErr);
82520b57cec5SDimitry Andric }
82530b57cec5SDimitry Andric 
82540b57cec5SDimitry Andric Error llvm::readModuleSummaryIndex(MemoryBufferRef Buffer,
8255*c9157d92SDimitry Andric                                    ModuleSummaryIndex &CombinedIndex) {
82560b57cec5SDimitry Andric   Expected<BitcodeModule> BM = getSingleModule(Buffer);
82570b57cec5SDimitry Andric   if (!BM)
82580b57cec5SDimitry Andric     return BM.takeError();
82590b57cec5SDimitry Andric 
8260*c9157d92SDimitry Andric   return BM->readSummary(CombinedIndex, BM->getModuleIdentifier());
82610b57cec5SDimitry Andric }
82620b57cec5SDimitry Andric 
82630b57cec5SDimitry Andric Expected<std::unique_ptr<ModuleSummaryIndex>>
82640b57cec5SDimitry Andric llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) {
82650b57cec5SDimitry Andric   Expected<BitcodeModule> BM = getSingleModule(Buffer);
82660b57cec5SDimitry Andric   if (!BM)
82670b57cec5SDimitry Andric     return BM.takeError();
82680b57cec5SDimitry Andric 
82690b57cec5SDimitry Andric   return BM->getSummary();
82700b57cec5SDimitry Andric }
82710b57cec5SDimitry Andric 
82720b57cec5SDimitry Andric Expected<BitcodeLTOInfo> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer) {
82730b57cec5SDimitry Andric   Expected<BitcodeModule> BM = getSingleModule(Buffer);
82740b57cec5SDimitry Andric   if (!BM)
82750b57cec5SDimitry Andric     return BM.takeError();
82760b57cec5SDimitry Andric 
82770b57cec5SDimitry Andric   return BM->getLTOInfo();
82780b57cec5SDimitry Andric }
82790b57cec5SDimitry Andric 
82800b57cec5SDimitry Andric Expected<std::unique_ptr<ModuleSummaryIndex>>
82810b57cec5SDimitry Andric llvm::getModuleSummaryIndexForFile(StringRef Path,
82820b57cec5SDimitry Andric                                    bool IgnoreEmptyThinLTOIndexFile) {
82830b57cec5SDimitry Andric   ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
82840b57cec5SDimitry Andric       MemoryBuffer::getFileOrSTDIN(Path);
82850b57cec5SDimitry Andric   if (!FileOrErr)
82860b57cec5SDimitry Andric     return errorCodeToError(FileOrErr.getError());
82870b57cec5SDimitry Andric   if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize())
82880b57cec5SDimitry Andric     return nullptr;
82890b57cec5SDimitry Andric   return getModuleSummaryIndex(**FileOrErr);
82900b57cec5SDimitry Andric }
8291