xref: /freebsd-src/contrib/llvm-project/llvm/lib/Bitcode/Reader/BitcodeReader.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
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"
2606c3fb27SDimitry 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"
33*0fca6ea1SDimitry Andric #include "llvm/IR/ConstantRangeList.h"
340b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
350b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
360b57cec5SDimitry Andric #include "llvm/IR/DebugInfo.h"
370b57cec5SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
380b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h"
390b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
400b57cec5SDimitry Andric #include "llvm/IR/Function.h"
410b57cec5SDimitry Andric #include "llvm/IR/GVMaterializer.h"
4281ad6265SDimitry Andric #include "llvm/IR/GetElementPtrTypeIterator.h"
430b57cec5SDimitry Andric #include "llvm/IR/GlobalAlias.h"
440b57cec5SDimitry Andric #include "llvm/IR/GlobalIFunc.h"
450b57cec5SDimitry Andric #include "llvm/IR/GlobalObject.h"
460b57cec5SDimitry Andric #include "llvm/IR/GlobalValue.h"
470b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h"
480b57cec5SDimitry Andric #include "llvm/IR/InlineAsm.h"
490b57cec5SDimitry Andric #include "llvm/IR/InstIterator.h"
500b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h"
510b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
520b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
530b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
5481ad6265SDimitry Andric #include "llvm/IR/IntrinsicsAArch64.h"
5581ad6265SDimitry Andric #include "llvm/IR/IntrinsicsARM.h"
560b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
570b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
580b57cec5SDimitry Andric #include "llvm/IR/Module.h"
590b57cec5SDimitry Andric #include "llvm/IR/ModuleSummaryIndex.h"
600b57cec5SDimitry Andric #include "llvm/IR/Operator.h"
61*0fca6ea1SDimitry Andric #include "llvm/IR/ProfDataUtils.h"
620b57cec5SDimitry Andric #include "llvm/IR/Type.h"
630b57cec5SDimitry Andric #include "llvm/IR/Value.h"
640b57cec5SDimitry Andric #include "llvm/IR/Verifier.h"
650b57cec5SDimitry Andric #include "llvm/Support/AtomicOrdering.h"
660b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
670b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
680b57cec5SDimitry Andric #include "llvm/Support/Compiler.h"
690b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
700b57cec5SDimitry Andric #include "llvm/Support/Error.h"
710b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
720b57cec5SDimitry Andric #include "llvm/Support/ErrorOr.h"
730b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
740b57cec5SDimitry Andric #include "llvm/Support/MemoryBuffer.h"
75bdd1243dSDimitry Andric #include "llvm/Support/ModRef.h"
760b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
7706c3fb27SDimitry Andric #include "llvm/TargetParser/Triple.h"
780b57cec5SDimitry Andric #include <algorithm>
790b57cec5SDimitry Andric #include <cassert>
800b57cec5SDimitry Andric #include <cstddef>
810b57cec5SDimitry Andric #include <cstdint>
820b57cec5SDimitry Andric #include <deque>
830b57cec5SDimitry Andric #include <map>
840b57cec5SDimitry Andric #include <memory>
85bdd1243dSDimitry Andric #include <optional>
860b57cec5SDimitry Andric #include <set>
870b57cec5SDimitry Andric #include <string>
880b57cec5SDimitry Andric #include <system_error>
890b57cec5SDimitry Andric #include <tuple>
900b57cec5SDimitry Andric #include <utility>
910b57cec5SDimitry Andric #include <vector>
920b57cec5SDimitry Andric 
930b57cec5SDimitry Andric using namespace llvm;
940b57cec5SDimitry Andric 
950b57cec5SDimitry Andric static cl::opt<bool> PrintSummaryGUIDs(
960b57cec5SDimitry Andric     "print-summary-global-ids", cl::init(false), cl::Hidden,
970b57cec5SDimitry Andric     cl::desc(
980b57cec5SDimitry Andric         "Print the global id for each value when reading the module summary"));
990b57cec5SDimitry Andric 
10081ad6265SDimitry Andric static cl::opt<bool> ExpandConstantExprs(
10181ad6265SDimitry Andric     "expand-constant-exprs", cl::Hidden,
10281ad6265SDimitry Andric     cl::desc(
10381ad6265SDimitry Andric         "Expand constant expressions to instructions for testing purposes"));
10481ad6265SDimitry Andric 
105*0fca6ea1SDimitry Andric /// Load bitcode directly into RemoveDIs format (use debug records instead
106*0fca6ea1SDimitry Andric /// of debug intrinsics). UNSET is treated as FALSE, so the default action
107*0fca6ea1SDimitry Andric /// is to do nothing. Individual tools can override this to incrementally add
108*0fca6ea1SDimitry Andric /// support for the RemoveDIs format.
109*0fca6ea1SDimitry Andric cl::opt<cl::boolOrDefault> LoadBitcodeIntoNewDbgInfoFormat(
110*0fca6ea1SDimitry Andric     "load-bitcode-into-experimental-debuginfo-iterators", cl::Hidden,
111*0fca6ea1SDimitry Andric     cl::desc("Load bitcode directly into the new debug info format (regardless "
112*0fca6ea1SDimitry Andric              "of input format)"));
113*0fca6ea1SDimitry Andric extern cl::opt<bool> UseNewDbgInfoFormat;
114*0fca6ea1SDimitry Andric extern cl::opt<cl::boolOrDefault> PreserveInputDbgFormat;
115*0fca6ea1SDimitry Andric extern bool WriteNewDbgInfoFormatToBitcode;
116*0fca6ea1SDimitry Andric extern cl::opt<bool> WriteNewDbgInfoFormat;
117*0fca6ea1SDimitry Andric 
1180b57cec5SDimitry Andric namespace {
1190b57cec5SDimitry Andric 
1200b57cec5SDimitry Andric enum {
1210b57cec5SDimitry Andric   SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
1220b57cec5SDimitry Andric };
1230b57cec5SDimitry Andric 
1240b57cec5SDimitry Andric } // end anonymous namespace
1250b57cec5SDimitry Andric 
1260b57cec5SDimitry Andric static Error error(const Twine &Message) {
1270b57cec5SDimitry Andric   return make_error<StringError>(
1280b57cec5SDimitry Andric       Message, make_error_code(BitcodeError::CorruptedBitcode));
1290b57cec5SDimitry Andric }
1300b57cec5SDimitry Andric 
1310b57cec5SDimitry Andric static Error hasInvalidBitcodeHeader(BitstreamCursor &Stream) {
1320b57cec5SDimitry Andric   if (!Stream.canSkipToPos(4))
1330b57cec5SDimitry Andric     return createStringError(std::errc::illegal_byte_sequence,
1340b57cec5SDimitry Andric                              "file too small to contain bitcode header");
1350b57cec5SDimitry Andric   for (unsigned C : {'B', 'C'})
1360b57cec5SDimitry Andric     if (Expected<SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
1370b57cec5SDimitry Andric       if (Res.get() != C)
1380b57cec5SDimitry Andric         return createStringError(std::errc::illegal_byte_sequence,
1390b57cec5SDimitry Andric                                  "file doesn't start with bitcode header");
1400b57cec5SDimitry Andric     } else
1410b57cec5SDimitry Andric       return Res.takeError();
1420b57cec5SDimitry Andric   for (unsigned C : {0x0, 0xC, 0xE, 0xD})
1430b57cec5SDimitry Andric     if (Expected<SimpleBitstreamCursor::word_t> Res = Stream.Read(4)) {
1440b57cec5SDimitry Andric       if (Res.get() != C)
1450b57cec5SDimitry Andric         return createStringError(std::errc::illegal_byte_sequence,
1460b57cec5SDimitry Andric                                  "file doesn't start with bitcode header");
1470b57cec5SDimitry Andric     } else
1480b57cec5SDimitry Andric       return Res.takeError();
1490b57cec5SDimitry Andric   return Error::success();
1500b57cec5SDimitry Andric }
1510b57cec5SDimitry Andric 
1520b57cec5SDimitry Andric static Expected<BitstreamCursor> initStream(MemoryBufferRef Buffer) {
1530b57cec5SDimitry Andric   const unsigned char *BufPtr = (const unsigned char *)Buffer.getBufferStart();
1540b57cec5SDimitry Andric   const unsigned char *BufEnd = BufPtr + Buffer.getBufferSize();
1550b57cec5SDimitry Andric 
1560b57cec5SDimitry Andric   if (Buffer.getBufferSize() & 3)
1570b57cec5SDimitry Andric     return error("Invalid bitcode signature");
1580b57cec5SDimitry Andric 
1590b57cec5SDimitry Andric   // If we have a wrapper header, parse it and ignore the non-bc file contents.
1600b57cec5SDimitry Andric   // The magic number is 0x0B17C0DE stored in little endian.
1610b57cec5SDimitry Andric   if (isBitcodeWrapper(BufPtr, BufEnd))
1620b57cec5SDimitry Andric     if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
1630b57cec5SDimitry Andric       return error("Invalid bitcode wrapper header");
1640b57cec5SDimitry Andric 
1650b57cec5SDimitry Andric   BitstreamCursor Stream(ArrayRef<uint8_t>(BufPtr, BufEnd));
1660b57cec5SDimitry Andric   if (Error Err = hasInvalidBitcodeHeader(Stream))
1670b57cec5SDimitry Andric     return std::move(Err);
1680b57cec5SDimitry Andric 
1690b57cec5SDimitry Andric   return std::move(Stream);
1700b57cec5SDimitry Andric }
1710b57cec5SDimitry Andric 
1720b57cec5SDimitry Andric /// Convert a string from a record into an std::string, return true on failure.
1730b57cec5SDimitry Andric template <typename StrTy>
1740b57cec5SDimitry Andric static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
1750b57cec5SDimitry Andric                             StrTy &Result) {
1760b57cec5SDimitry Andric   if (Idx > Record.size())
1770b57cec5SDimitry Andric     return true;
1780b57cec5SDimitry Andric 
1795ffd83dbSDimitry Andric   Result.append(Record.begin() + Idx, Record.end());
1800b57cec5SDimitry Andric   return false;
1810b57cec5SDimitry Andric }
1820b57cec5SDimitry Andric 
1830b57cec5SDimitry Andric // Strip all the TBAA attachment for the module.
1840b57cec5SDimitry Andric static void stripTBAA(Module *M) {
1850b57cec5SDimitry Andric   for (auto &F : *M) {
1860b57cec5SDimitry Andric     if (F.isMaterializable())
1870b57cec5SDimitry Andric       continue;
1880b57cec5SDimitry Andric     for (auto &I : instructions(F))
1890b57cec5SDimitry Andric       I.setMetadata(LLVMContext::MD_tbaa, nullptr);
1900b57cec5SDimitry Andric   }
1910b57cec5SDimitry Andric }
1920b57cec5SDimitry Andric 
1930b57cec5SDimitry Andric /// Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the
1940b57cec5SDimitry Andric /// "epoch" encoded in the bitcode, and return the producer name if any.
1950b57cec5SDimitry Andric static Expected<std::string> readIdentificationBlock(BitstreamCursor &Stream) {
1960b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
1970b57cec5SDimitry Andric     return std::move(Err);
1980b57cec5SDimitry Andric 
1990b57cec5SDimitry Andric   // Read all the records.
2000b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
2010b57cec5SDimitry Andric 
2020b57cec5SDimitry Andric   std::string ProducerIdentification;
2030b57cec5SDimitry Andric 
2040b57cec5SDimitry Andric   while (true) {
2050b57cec5SDimitry Andric     BitstreamEntry Entry;
206349cc55cSDimitry Andric     if (Error E = Stream.advance().moveInto(Entry))
207349cc55cSDimitry Andric       return std::move(E);
2080b57cec5SDimitry Andric 
2090b57cec5SDimitry Andric     switch (Entry.Kind) {
2100b57cec5SDimitry Andric     default:
2110b57cec5SDimitry Andric     case BitstreamEntry::Error:
2120b57cec5SDimitry Andric       return error("Malformed block");
2130b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
2140b57cec5SDimitry Andric       return ProducerIdentification;
2150b57cec5SDimitry Andric     case BitstreamEntry::Record:
2160b57cec5SDimitry Andric       // The interesting case.
2170b57cec5SDimitry Andric       break;
2180b57cec5SDimitry Andric     }
2190b57cec5SDimitry Andric 
2200b57cec5SDimitry Andric     // Read a record.
2210b57cec5SDimitry Andric     Record.clear();
2220b57cec5SDimitry Andric     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
2230b57cec5SDimitry Andric     if (!MaybeBitCode)
2240b57cec5SDimitry Andric       return MaybeBitCode.takeError();
2250b57cec5SDimitry Andric     switch (MaybeBitCode.get()) {
2260b57cec5SDimitry Andric     default: // Default behavior: reject
2270b57cec5SDimitry Andric       return error("Invalid value");
2280b57cec5SDimitry Andric     case bitc::IDENTIFICATION_CODE_STRING: // IDENTIFICATION: [strchr x N]
2290b57cec5SDimitry Andric       convertToString(Record, 0, ProducerIdentification);
2300b57cec5SDimitry Andric       break;
2310b57cec5SDimitry Andric     case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
2320b57cec5SDimitry Andric       unsigned epoch = (unsigned)Record[0];
2330b57cec5SDimitry Andric       if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
2340b57cec5SDimitry Andric         return error(
2350b57cec5SDimitry Andric           Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
2360b57cec5SDimitry Andric           "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
2370b57cec5SDimitry Andric       }
2380b57cec5SDimitry Andric     }
2390b57cec5SDimitry Andric     }
2400b57cec5SDimitry Andric   }
2410b57cec5SDimitry Andric }
2420b57cec5SDimitry Andric 
2430b57cec5SDimitry Andric static Expected<std::string> readIdentificationCode(BitstreamCursor &Stream) {
2440b57cec5SDimitry Andric   // We expect a number of well-defined blocks, though we don't necessarily
2450b57cec5SDimitry Andric   // need to understand them all.
2460b57cec5SDimitry Andric   while (true) {
2470b57cec5SDimitry Andric     if (Stream.AtEndOfStream())
2480b57cec5SDimitry Andric       return "";
2490b57cec5SDimitry Andric 
2500b57cec5SDimitry Andric     BitstreamEntry Entry;
251349cc55cSDimitry Andric     if (Error E = Stream.advance().moveInto(Entry))
252349cc55cSDimitry Andric       return std::move(E);
2530b57cec5SDimitry Andric 
2540b57cec5SDimitry Andric     switch (Entry.Kind) {
2550b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
2560b57cec5SDimitry Andric     case BitstreamEntry::Error:
2570b57cec5SDimitry Andric       return error("Malformed block");
2580b57cec5SDimitry Andric 
2590b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
2600b57cec5SDimitry Andric       if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID)
2610b57cec5SDimitry Andric         return readIdentificationBlock(Stream);
2620b57cec5SDimitry Andric 
2630b57cec5SDimitry Andric       // Ignore other sub-blocks.
2640b57cec5SDimitry Andric       if (Error Err = Stream.SkipBlock())
2650b57cec5SDimitry Andric         return std::move(Err);
2660b57cec5SDimitry Andric       continue;
2670b57cec5SDimitry Andric     case BitstreamEntry::Record:
268349cc55cSDimitry Andric       if (Error E = Stream.skipRecord(Entry.ID).takeError())
269349cc55cSDimitry Andric         return std::move(E);
2700b57cec5SDimitry Andric       continue;
2710b57cec5SDimitry Andric     }
2720b57cec5SDimitry Andric   }
2730b57cec5SDimitry Andric }
2740b57cec5SDimitry Andric 
2750b57cec5SDimitry Andric static Expected<bool> hasObjCCategoryInModule(BitstreamCursor &Stream) {
2760b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2770b57cec5SDimitry Andric     return std::move(Err);
2780b57cec5SDimitry Andric 
2790b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
2800b57cec5SDimitry Andric   // Read all the records for this module.
2810b57cec5SDimitry Andric 
2820b57cec5SDimitry Andric   while (true) {
2830b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2840b57cec5SDimitry Andric     if (!MaybeEntry)
2850b57cec5SDimitry Andric       return MaybeEntry.takeError();
2860b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
2870b57cec5SDimitry Andric 
2880b57cec5SDimitry Andric     switch (Entry.Kind) {
2890b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
2900b57cec5SDimitry Andric     case BitstreamEntry::Error:
2910b57cec5SDimitry Andric       return error("Malformed block");
2920b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
2930b57cec5SDimitry Andric       return false;
2940b57cec5SDimitry Andric     case BitstreamEntry::Record:
2950b57cec5SDimitry Andric       // The interesting case.
2960b57cec5SDimitry Andric       break;
2970b57cec5SDimitry Andric     }
2980b57cec5SDimitry Andric 
2990b57cec5SDimitry Andric     // Read a record.
3000b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
3010b57cec5SDimitry Andric     if (!MaybeRecord)
3020b57cec5SDimitry Andric       return MaybeRecord.takeError();
3030b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
3040b57cec5SDimitry Andric     default:
3050b57cec5SDimitry Andric       break; // Default behavior, ignore unknown content.
3060b57cec5SDimitry Andric     case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
3070b57cec5SDimitry Andric       std::string S;
3080b57cec5SDimitry Andric       if (convertToString(Record, 0, S))
30981ad6265SDimitry Andric         return error("Invalid section name record");
3100b57cec5SDimitry Andric       // Check for the i386 and other (x86_64, ARM) conventions
3110b57cec5SDimitry Andric       if (S.find("__DATA,__objc_catlist") != std::string::npos ||
312*0fca6ea1SDimitry Andric           S.find("__OBJC,__category") != std::string::npos ||
313*0fca6ea1SDimitry Andric           S.find("__TEXT,__swift") != std::string::npos)
3140b57cec5SDimitry Andric         return true;
3150b57cec5SDimitry Andric       break;
3160b57cec5SDimitry Andric     }
3170b57cec5SDimitry Andric     }
3180b57cec5SDimitry Andric     Record.clear();
3190b57cec5SDimitry Andric   }
3200b57cec5SDimitry Andric   llvm_unreachable("Exit infinite loop");
3210b57cec5SDimitry Andric }
3220b57cec5SDimitry Andric 
3230b57cec5SDimitry Andric static Expected<bool> hasObjCCategory(BitstreamCursor &Stream) {
3240b57cec5SDimitry Andric   // We expect a number of well-defined blocks, though we don't necessarily
3250b57cec5SDimitry Andric   // need to understand them all.
3260b57cec5SDimitry Andric   while (true) {
3270b57cec5SDimitry Andric     BitstreamEntry Entry;
328349cc55cSDimitry Andric     if (Error E = Stream.advance().moveInto(Entry))
329349cc55cSDimitry Andric       return std::move(E);
3300b57cec5SDimitry Andric 
3310b57cec5SDimitry Andric     switch (Entry.Kind) {
3320b57cec5SDimitry Andric     case BitstreamEntry::Error:
3330b57cec5SDimitry Andric       return error("Malformed block");
3340b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
3350b57cec5SDimitry Andric       return false;
3360b57cec5SDimitry Andric 
3370b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
3380b57cec5SDimitry Andric       if (Entry.ID == bitc::MODULE_BLOCK_ID)
3390b57cec5SDimitry Andric         return hasObjCCategoryInModule(Stream);
3400b57cec5SDimitry Andric 
3410b57cec5SDimitry Andric       // Ignore other sub-blocks.
3420b57cec5SDimitry Andric       if (Error Err = Stream.SkipBlock())
3430b57cec5SDimitry Andric         return std::move(Err);
3440b57cec5SDimitry Andric       continue;
3450b57cec5SDimitry Andric 
3460b57cec5SDimitry Andric     case BitstreamEntry::Record:
347349cc55cSDimitry Andric       if (Error E = Stream.skipRecord(Entry.ID).takeError())
348349cc55cSDimitry Andric         return std::move(E);
3490b57cec5SDimitry Andric       continue;
3500b57cec5SDimitry Andric     }
3510b57cec5SDimitry Andric   }
3520b57cec5SDimitry Andric }
3530b57cec5SDimitry Andric 
3540b57cec5SDimitry Andric static Expected<std::string> readModuleTriple(BitstreamCursor &Stream) {
3550b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3560b57cec5SDimitry Andric     return std::move(Err);
3570b57cec5SDimitry Andric 
3580b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
3590b57cec5SDimitry Andric 
3600b57cec5SDimitry Andric   std::string Triple;
3610b57cec5SDimitry Andric 
3620b57cec5SDimitry Andric   // Read all the records for this module.
3630b57cec5SDimitry Andric   while (true) {
3640b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
3650b57cec5SDimitry Andric     if (!MaybeEntry)
3660b57cec5SDimitry Andric       return MaybeEntry.takeError();
3670b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
3680b57cec5SDimitry Andric 
3690b57cec5SDimitry Andric     switch (Entry.Kind) {
3700b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
3710b57cec5SDimitry Andric     case BitstreamEntry::Error:
3720b57cec5SDimitry Andric       return error("Malformed block");
3730b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
3740b57cec5SDimitry Andric       return Triple;
3750b57cec5SDimitry Andric     case BitstreamEntry::Record:
3760b57cec5SDimitry Andric       // The interesting case.
3770b57cec5SDimitry Andric       break;
3780b57cec5SDimitry Andric     }
3790b57cec5SDimitry Andric 
3800b57cec5SDimitry Andric     // Read a record.
3810b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
3820b57cec5SDimitry Andric     if (!MaybeRecord)
3830b57cec5SDimitry Andric       return MaybeRecord.takeError();
3840b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
3850b57cec5SDimitry Andric     default: break;  // Default behavior, ignore unknown content.
3860b57cec5SDimitry Andric     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
3870b57cec5SDimitry Andric       std::string S;
3880b57cec5SDimitry Andric       if (convertToString(Record, 0, S))
38981ad6265SDimitry Andric         return error("Invalid triple record");
3900b57cec5SDimitry Andric       Triple = S;
3910b57cec5SDimitry Andric       break;
3920b57cec5SDimitry Andric     }
3930b57cec5SDimitry Andric     }
3940b57cec5SDimitry Andric     Record.clear();
3950b57cec5SDimitry Andric   }
3960b57cec5SDimitry Andric   llvm_unreachable("Exit infinite loop");
3970b57cec5SDimitry Andric }
3980b57cec5SDimitry Andric 
3990b57cec5SDimitry Andric static Expected<std::string> readTriple(BitstreamCursor &Stream) {
4000b57cec5SDimitry Andric   // We expect a number of well-defined blocks, though we don't necessarily
4010b57cec5SDimitry Andric   // need to understand them all.
4020b57cec5SDimitry Andric   while (true) {
4030b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advance();
4040b57cec5SDimitry Andric     if (!MaybeEntry)
4050b57cec5SDimitry Andric       return MaybeEntry.takeError();
4060b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
4070b57cec5SDimitry Andric 
4080b57cec5SDimitry Andric     switch (Entry.Kind) {
4090b57cec5SDimitry Andric     case BitstreamEntry::Error:
4100b57cec5SDimitry Andric       return error("Malformed block");
4110b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
4120b57cec5SDimitry Andric       return "";
4130b57cec5SDimitry Andric 
4140b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
4150b57cec5SDimitry Andric       if (Entry.ID == bitc::MODULE_BLOCK_ID)
4160b57cec5SDimitry Andric         return readModuleTriple(Stream);
4170b57cec5SDimitry Andric 
4180b57cec5SDimitry Andric       // Ignore other sub-blocks.
4190b57cec5SDimitry Andric       if (Error Err = Stream.SkipBlock())
4200b57cec5SDimitry Andric         return std::move(Err);
4210b57cec5SDimitry Andric       continue;
4220b57cec5SDimitry Andric 
4230b57cec5SDimitry Andric     case BitstreamEntry::Record:
4240b57cec5SDimitry Andric       if (llvm::Expected<unsigned> Skipped = Stream.skipRecord(Entry.ID))
4250b57cec5SDimitry Andric         continue;
4260b57cec5SDimitry Andric       else
4270b57cec5SDimitry Andric         return Skipped.takeError();
4280b57cec5SDimitry Andric     }
4290b57cec5SDimitry Andric   }
4300b57cec5SDimitry Andric }
4310b57cec5SDimitry Andric 
4320b57cec5SDimitry Andric namespace {
4330b57cec5SDimitry Andric 
4340b57cec5SDimitry Andric class BitcodeReaderBase {
4350b57cec5SDimitry Andric protected:
4360b57cec5SDimitry Andric   BitcodeReaderBase(BitstreamCursor Stream, StringRef Strtab)
4370b57cec5SDimitry Andric       : Stream(std::move(Stream)), Strtab(Strtab) {
4380b57cec5SDimitry Andric     this->Stream.setBlockInfo(&BlockInfo);
4390b57cec5SDimitry Andric   }
4400b57cec5SDimitry Andric 
4410b57cec5SDimitry Andric   BitstreamBlockInfo BlockInfo;
4420b57cec5SDimitry Andric   BitstreamCursor Stream;
4430b57cec5SDimitry Andric   StringRef Strtab;
4440b57cec5SDimitry Andric 
4450b57cec5SDimitry Andric   /// In version 2 of the bitcode we store names of global values and comdats in
4460b57cec5SDimitry Andric   /// a string table rather than in the VST.
4470b57cec5SDimitry Andric   bool UseStrtab = false;
4480b57cec5SDimitry Andric 
4490b57cec5SDimitry Andric   Expected<unsigned> parseVersionRecord(ArrayRef<uint64_t> Record);
4500b57cec5SDimitry Andric 
4510b57cec5SDimitry Andric   /// If this module uses a string table, pop the reference to the string table
4520b57cec5SDimitry Andric   /// and return the referenced string and the rest of the record. Otherwise
4530b57cec5SDimitry Andric   /// just return the record itself.
4540b57cec5SDimitry Andric   std::pair<StringRef, ArrayRef<uint64_t>>
4550b57cec5SDimitry Andric   readNameFromStrtab(ArrayRef<uint64_t> Record);
4560b57cec5SDimitry Andric 
45781ad6265SDimitry Andric   Error readBlockInfo();
4580b57cec5SDimitry Andric 
4590b57cec5SDimitry Andric   // Contains an arbitrary and optional string identifying the bitcode producer
4600b57cec5SDimitry Andric   std::string ProducerIdentification;
4610b57cec5SDimitry Andric 
4620b57cec5SDimitry Andric   Error error(const Twine &Message);
4630b57cec5SDimitry Andric };
4640b57cec5SDimitry Andric 
4650b57cec5SDimitry Andric } // end anonymous namespace
4660b57cec5SDimitry Andric 
4670b57cec5SDimitry Andric Error BitcodeReaderBase::error(const Twine &Message) {
4680b57cec5SDimitry Andric   std::string FullMsg = Message.str();
4690b57cec5SDimitry Andric   if (!ProducerIdentification.empty())
4700b57cec5SDimitry Andric     FullMsg += " (Producer: '" + ProducerIdentification + "' Reader: 'LLVM " +
4710b57cec5SDimitry Andric                LLVM_VERSION_STRING "')";
4720b57cec5SDimitry Andric   return ::error(FullMsg);
4730b57cec5SDimitry Andric }
4740b57cec5SDimitry Andric 
4750b57cec5SDimitry Andric Expected<unsigned>
4760b57cec5SDimitry Andric BitcodeReaderBase::parseVersionRecord(ArrayRef<uint64_t> Record) {
4770b57cec5SDimitry Andric   if (Record.empty())
47881ad6265SDimitry Andric     return error("Invalid version record");
4790b57cec5SDimitry Andric   unsigned ModuleVersion = Record[0];
4800b57cec5SDimitry Andric   if (ModuleVersion > 2)
4810b57cec5SDimitry Andric     return error("Invalid value");
4820b57cec5SDimitry Andric   UseStrtab = ModuleVersion >= 2;
4830b57cec5SDimitry Andric   return ModuleVersion;
4840b57cec5SDimitry Andric }
4850b57cec5SDimitry Andric 
4860b57cec5SDimitry Andric std::pair<StringRef, ArrayRef<uint64_t>>
4870b57cec5SDimitry Andric BitcodeReaderBase::readNameFromStrtab(ArrayRef<uint64_t> Record) {
4880b57cec5SDimitry Andric   if (!UseStrtab)
4890b57cec5SDimitry Andric     return {"", Record};
4900b57cec5SDimitry Andric   // Invalid reference. Let the caller complain about the record being empty.
4910b57cec5SDimitry Andric   if (Record[0] + Record[1] > Strtab.size())
4920b57cec5SDimitry Andric     return {"", {}};
4930b57cec5SDimitry Andric   return {StringRef(Strtab.data() + Record[0], Record[1]), Record.slice(2)};
4940b57cec5SDimitry Andric }
4950b57cec5SDimitry Andric 
4960b57cec5SDimitry Andric namespace {
4970b57cec5SDimitry Andric 
49881ad6265SDimitry Andric /// This represents a constant expression or constant aggregate using a custom
49981ad6265SDimitry Andric /// structure internal to the bitcode reader. Later, this structure will be
50081ad6265SDimitry Andric /// expanded by materializeValue() either into a constant expression/aggregate,
50181ad6265SDimitry Andric /// or into an instruction sequence at the point of use. This allows us to
50281ad6265SDimitry Andric /// upgrade bitcode using constant expressions even if this kind of constant
50381ad6265SDimitry Andric /// expression is no longer supported.
50481ad6265SDimitry Andric class BitcodeConstant final : public Value,
50581ad6265SDimitry Andric                               TrailingObjects<BitcodeConstant, unsigned> {
50681ad6265SDimitry Andric   friend TrailingObjects;
50781ad6265SDimitry Andric 
50881ad6265SDimitry Andric   // Value subclass ID: Pick largest possible value to avoid any clashes.
50981ad6265SDimitry Andric   static constexpr uint8_t SubclassID = 255;
51081ad6265SDimitry Andric 
51181ad6265SDimitry Andric public:
51281ad6265SDimitry Andric   // Opcodes used for non-expressions. This includes constant aggregates
51381ad6265SDimitry Andric   // (struct, array, vector) that might need expansion, as well as non-leaf
51481ad6265SDimitry Andric   // constants that don't need expansion (no_cfi, dso_local, blockaddress),
51581ad6265SDimitry Andric   // but still go through BitcodeConstant to avoid different uselist orders
51681ad6265SDimitry Andric   // between the two cases.
51781ad6265SDimitry Andric   static constexpr uint8_t ConstantStructOpcode = 255;
51881ad6265SDimitry Andric   static constexpr uint8_t ConstantArrayOpcode = 254;
51981ad6265SDimitry Andric   static constexpr uint8_t ConstantVectorOpcode = 253;
52081ad6265SDimitry Andric   static constexpr uint8_t NoCFIOpcode = 252;
52181ad6265SDimitry Andric   static constexpr uint8_t DSOLocalEquivalentOpcode = 251;
52281ad6265SDimitry Andric   static constexpr uint8_t BlockAddressOpcode = 250;
523*0fca6ea1SDimitry Andric   static constexpr uint8_t ConstantPtrAuthOpcode = 249;
524*0fca6ea1SDimitry Andric   static constexpr uint8_t FirstSpecialOpcode = ConstantPtrAuthOpcode;
52581ad6265SDimitry Andric 
52681ad6265SDimitry Andric   // Separate struct to make passing different number of parameters to
52781ad6265SDimitry Andric   // BitcodeConstant::create() more convenient.
52881ad6265SDimitry Andric   struct ExtraInfo {
52981ad6265SDimitry Andric     uint8_t Opcode;
53081ad6265SDimitry Andric     uint8_t Flags;
531*0fca6ea1SDimitry Andric     unsigned BlockAddressBB = 0;
532*0fca6ea1SDimitry Andric     Type *SrcElemTy = nullptr;
533*0fca6ea1SDimitry Andric     std::optional<ConstantRange> InRange;
53481ad6265SDimitry Andric 
535*0fca6ea1SDimitry Andric     ExtraInfo(uint8_t Opcode, uint8_t Flags = 0, Type *SrcElemTy = nullptr,
536*0fca6ea1SDimitry Andric               std::optional<ConstantRange> InRange = std::nullopt)
537*0fca6ea1SDimitry Andric         : Opcode(Opcode), Flags(Flags), SrcElemTy(SrcElemTy),
538*0fca6ea1SDimitry Andric           InRange(std::move(InRange)) {}
539*0fca6ea1SDimitry Andric 
540*0fca6ea1SDimitry Andric     ExtraInfo(uint8_t Opcode, uint8_t Flags, unsigned BlockAddressBB)
541*0fca6ea1SDimitry Andric         : Opcode(Opcode), Flags(Flags), BlockAddressBB(BlockAddressBB) {}
54281ad6265SDimitry Andric   };
54381ad6265SDimitry Andric 
54481ad6265SDimitry Andric   uint8_t Opcode;
54581ad6265SDimitry Andric   uint8_t Flags;
54681ad6265SDimitry Andric   unsigned NumOperands;
547*0fca6ea1SDimitry Andric   unsigned BlockAddressBB;
54881ad6265SDimitry Andric   Type *SrcElemTy; // GEP source element type.
549*0fca6ea1SDimitry Andric   std::optional<ConstantRange> InRange; // GEP inrange attribute.
55081ad6265SDimitry Andric 
55181ad6265SDimitry Andric private:
55281ad6265SDimitry Andric   BitcodeConstant(Type *Ty, const ExtraInfo &Info, ArrayRef<unsigned> OpIDs)
55381ad6265SDimitry Andric       : Value(Ty, SubclassID), Opcode(Info.Opcode), Flags(Info.Flags),
554*0fca6ea1SDimitry Andric         NumOperands(OpIDs.size()), BlockAddressBB(Info.BlockAddressBB),
555*0fca6ea1SDimitry Andric         SrcElemTy(Info.SrcElemTy), InRange(Info.InRange) {
55681ad6265SDimitry Andric     std::uninitialized_copy(OpIDs.begin(), OpIDs.end(),
55781ad6265SDimitry Andric                             getTrailingObjects<unsigned>());
55881ad6265SDimitry Andric   }
55981ad6265SDimitry Andric 
56081ad6265SDimitry Andric   BitcodeConstant &operator=(const BitcodeConstant &) = delete;
56181ad6265SDimitry Andric 
56281ad6265SDimitry Andric public:
56381ad6265SDimitry Andric   static BitcodeConstant *create(BumpPtrAllocator &A, Type *Ty,
56481ad6265SDimitry Andric                                  const ExtraInfo &Info,
56581ad6265SDimitry Andric                                  ArrayRef<unsigned> OpIDs) {
56681ad6265SDimitry Andric     void *Mem = A.Allocate(totalSizeToAlloc<unsigned>(OpIDs.size()),
56781ad6265SDimitry Andric                            alignof(BitcodeConstant));
56881ad6265SDimitry Andric     return new (Mem) BitcodeConstant(Ty, Info, OpIDs);
56981ad6265SDimitry Andric   }
57081ad6265SDimitry Andric 
57181ad6265SDimitry Andric   static bool classof(const Value *V) { return V->getValueID() == SubclassID; }
57281ad6265SDimitry Andric 
57381ad6265SDimitry Andric   ArrayRef<unsigned> getOperandIDs() const {
574bdd1243dSDimitry Andric     return ArrayRef(getTrailingObjects<unsigned>(), NumOperands);
57581ad6265SDimitry Andric   }
57681ad6265SDimitry Andric 
577*0fca6ea1SDimitry Andric   std::optional<ConstantRange> getInRange() const {
57881ad6265SDimitry Andric     assert(Opcode == Instruction::GetElementPtr);
579*0fca6ea1SDimitry Andric     return InRange;
58081ad6265SDimitry Andric   }
58181ad6265SDimitry Andric 
58281ad6265SDimitry Andric   const char *getOpcodeName() const {
58381ad6265SDimitry Andric     return Instruction::getOpcodeName(Opcode);
58481ad6265SDimitry Andric   }
58581ad6265SDimitry Andric };
58681ad6265SDimitry Andric 
5870b57cec5SDimitry Andric class BitcodeReader : public BitcodeReaderBase, public GVMaterializer {
5880b57cec5SDimitry Andric   LLVMContext &Context;
5890b57cec5SDimitry Andric   Module *TheModule = nullptr;
5900b57cec5SDimitry Andric   // Next offset to start scanning for lazy parsing of function bodies.
5910b57cec5SDimitry Andric   uint64_t NextUnreadBit = 0;
5920b57cec5SDimitry Andric   // Last function offset found in the VST.
5930b57cec5SDimitry Andric   uint64_t LastFunctionBlockBit = 0;
5940b57cec5SDimitry Andric   bool SeenValueSymbolTable = false;
5950b57cec5SDimitry Andric   uint64_t VSTOffset = 0;
5960b57cec5SDimitry Andric 
5970b57cec5SDimitry Andric   std::vector<std::string> SectionTable;
5980b57cec5SDimitry Andric   std::vector<std::string> GCTable;
5990b57cec5SDimitry Andric 
6000b57cec5SDimitry Andric   std::vector<Type *> TypeList;
60181ad6265SDimitry Andric   /// Track type IDs of contained types. Order is the same as the contained
60281ad6265SDimitry Andric   /// types of a Type*. This is used during upgrades of typed pointer IR in
60381ad6265SDimitry Andric   /// opaque pointer mode.
60481ad6265SDimitry Andric   DenseMap<unsigned, SmallVector<unsigned, 1>> ContainedTypeIDs;
60581ad6265SDimitry Andric   /// In some cases, we need to create a type ID for a type that was not
60681ad6265SDimitry Andric   /// explicitly encoded in the bitcode, or we don't know about at the current
60781ad6265SDimitry Andric   /// point. For example, a global may explicitly encode the value type ID, but
60881ad6265SDimitry Andric   /// not have a type ID for the pointer to value type, for which we create a
60981ad6265SDimitry Andric   /// virtual type ID instead. This map stores the new type ID that was created
61081ad6265SDimitry Andric   /// for the given pair of Type and contained type ID.
61181ad6265SDimitry Andric   DenseMap<std::pair<Type *, unsigned>, unsigned> VirtualTypeIDs;
61281ad6265SDimitry Andric   DenseMap<Function *, unsigned> FunctionTypeIDs;
61381ad6265SDimitry Andric   /// Allocator for BitcodeConstants. This should come before ValueList,
61481ad6265SDimitry Andric   /// because the ValueList might hold ValueHandles to these constants, so
61581ad6265SDimitry Andric   /// ValueList must be destroyed before Alloc.
61681ad6265SDimitry Andric   BumpPtrAllocator Alloc;
6170b57cec5SDimitry Andric   BitcodeReaderValueList ValueList;
618bdd1243dSDimitry Andric   std::optional<MetadataLoader> MDLoader;
6190b57cec5SDimitry Andric   std::vector<Comdat *> ComdatList;
6200eae32dcSDimitry Andric   DenseSet<GlobalObject *> ImplicitComdatObjects;
6210b57cec5SDimitry Andric   SmallVector<Instruction *, 64> InstructionList;
6220b57cec5SDimitry Andric 
6230b57cec5SDimitry Andric   std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInits;
624349cc55cSDimitry Andric   std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInits;
625349cc55cSDimitry Andric 
626349cc55cSDimitry Andric   struct FunctionOperandInfo {
627349cc55cSDimitry Andric     Function *F;
628349cc55cSDimitry Andric     unsigned PersonalityFn;
629349cc55cSDimitry Andric     unsigned Prefix;
630349cc55cSDimitry Andric     unsigned Prologue;
631349cc55cSDimitry Andric   };
632349cc55cSDimitry Andric   std::vector<FunctionOperandInfo> FunctionOperands;
6330b57cec5SDimitry Andric 
6340b57cec5SDimitry Andric   /// The set of attributes by index.  Index zero in the file is for null, and
6350b57cec5SDimitry Andric   /// is thus not represented here.  As such all indices are off by one.
6360b57cec5SDimitry Andric   std::vector<AttributeList> MAttributes;
6370b57cec5SDimitry Andric 
6380b57cec5SDimitry Andric   /// The set of attribute groups.
6390b57cec5SDimitry Andric   std::map<unsigned, AttributeList> MAttributeGroups;
6400b57cec5SDimitry Andric 
6410b57cec5SDimitry Andric   /// While parsing a function body, this is a list of the basic blocks for the
6420b57cec5SDimitry Andric   /// function.
6430b57cec5SDimitry Andric   std::vector<BasicBlock*> FunctionBBs;
6440b57cec5SDimitry Andric 
6450b57cec5SDimitry Andric   // When reading the module header, this list is populated with functions that
6460b57cec5SDimitry Andric   // have bodies later in the file.
6470b57cec5SDimitry Andric   std::vector<Function*> FunctionsWithBodies;
6480b57cec5SDimitry Andric 
6490b57cec5SDimitry Andric   // When intrinsic functions are encountered which require upgrading they are
6500b57cec5SDimitry Andric   // stored here with their replacement function.
6510b57cec5SDimitry Andric   using UpdatedIntrinsicMap = DenseMap<Function *, Function *>;
6520b57cec5SDimitry Andric   UpdatedIntrinsicMap UpgradedIntrinsics;
6530b57cec5SDimitry Andric 
6540b57cec5SDimitry Andric   // Several operations happen after the module header has been read, but
6550b57cec5SDimitry Andric   // before function bodies are processed. This keeps track of whether
6560b57cec5SDimitry Andric   // we've done this yet.
6570b57cec5SDimitry Andric   bool SeenFirstFunctionBody = false;
6580b57cec5SDimitry Andric 
6590b57cec5SDimitry Andric   /// When function bodies are initially scanned, this map contains info about
6600b57cec5SDimitry Andric   /// where to find deferred function body in the stream.
6610b57cec5SDimitry Andric   DenseMap<Function*, uint64_t> DeferredFunctionInfo;
6620b57cec5SDimitry Andric 
6630b57cec5SDimitry Andric   /// When Metadata block is initially scanned when parsing the module, we may
6640b57cec5SDimitry Andric   /// choose to defer parsing of the metadata. This vector contains info about
6650b57cec5SDimitry Andric   /// which Metadata blocks are deferred.
6660b57cec5SDimitry Andric   std::vector<uint64_t> DeferredMetadataInfo;
6670b57cec5SDimitry Andric 
6680b57cec5SDimitry Andric   /// These are basic blocks forward-referenced by block addresses.  They are
6690b57cec5SDimitry Andric   /// inserted lazily into functions when they're loaded.  The basic block ID is
6700b57cec5SDimitry Andric   /// its index into the vector.
6710b57cec5SDimitry Andric   DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
6720b57cec5SDimitry Andric   std::deque<Function *> BasicBlockFwdRefQueue;
6730b57cec5SDimitry Andric 
67481ad6265SDimitry Andric   /// These are Functions that contain BlockAddresses which refer a different
67581ad6265SDimitry Andric   /// Function. When parsing the different Function, queue Functions that refer
67681ad6265SDimitry Andric   /// to the different Function. Those Functions must be materialized in order
67781ad6265SDimitry Andric   /// to resolve their BlockAddress constants before the different Function
67881ad6265SDimitry Andric   /// gets moved into another Module.
67981ad6265SDimitry Andric   std::vector<Function *> BackwardRefFunctions;
68081ad6265SDimitry Andric 
6810b57cec5SDimitry Andric   /// Indicates that we are using a new encoding for instruction operands where
6820b57cec5SDimitry Andric   /// most operands in the current FUNCTION_BLOCK are encoded relative to the
6830b57cec5SDimitry Andric   /// instruction number, for a more compact encoding.  Some instruction
6840b57cec5SDimitry Andric   /// operands are not relative to the instruction ID: basic block numbers, and
6850b57cec5SDimitry Andric   /// types. Once the old style function blocks have been phased out, we would
6860b57cec5SDimitry Andric   /// not need this flag.
6870b57cec5SDimitry Andric   bool UseRelativeIDs = false;
6880b57cec5SDimitry Andric 
6890b57cec5SDimitry Andric   /// True if all functions will be materialized, negating the need to process
6900b57cec5SDimitry Andric   /// (e.g.) blockaddress forward references.
6910b57cec5SDimitry Andric   bool WillMaterializeAllForwardRefs = false;
6920b57cec5SDimitry Andric 
693*0fca6ea1SDimitry Andric   /// Tracks whether we have seen debug intrinsics or records in this bitcode;
694*0fca6ea1SDimitry Andric   /// seeing both in a single module is currently a fatal error.
695*0fca6ea1SDimitry Andric   bool SeenDebugIntrinsic = false;
696*0fca6ea1SDimitry Andric   bool SeenDebugRecord = false;
697*0fca6ea1SDimitry Andric 
6980b57cec5SDimitry Andric   bool StripDebugInfo = false;
6990b57cec5SDimitry Andric   TBAAVerifier TBAAVerifyHelper;
7000b57cec5SDimitry Andric 
7010b57cec5SDimitry Andric   std::vector<std::string> BundleTags;
7020b57cec5SDimitry Andric   SmallVector<SyncScope::ID, 8> SSIDs;
7030b57cec5SDimitry Andric 
704bdd1243dSDimitry Andric   std::optional<ValueTypeCallbackTy> ValueTypeCallback;
705bdd1243dSDimitry Andric 
7060b57cec5SDimitry Andric public:
7070b57cec5SDimitry Andric   BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
7080b57cec5SDimitry Andric                 StringRef ProducerIdentification, LLVMContext &Context);
7090b57cec5SDimitry Andric 
7100b57cec5SDimitry Andric   Error materializeForwardReferencedFunctions();
7110b57cec5SDimitry Andric 
7120b57cec5SDimitry Andric   Error materialize(GlobalValue *GV) override;
7130b57cec5SDimitry Andric   Error materializeModule() override;
7140b57cec5SDimitry Andric   std::vector<StructType *> getIdentifiedStructTypes() const override;
7150b57cec5SDimitry Andric 
7160b57cec5SDimitry Andric   /// Main interface to parsing a bitcode buffer.
7170b57cec5SDimitry Andric   /// \returns true if an error occurred.
718bdd1243dSDimitry Andric   Error parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata,
719bdd1243dSDimitry Andric                          bool IsImporting, ParserCallbacks Callbacks = {});
7200b57cec5SDimitry Andric 
7210b57cec5SDimitry Andric   static uint64_t decodeSignRotatedValue(uint64_t V);
7220b57cec5SDimitry Andric 
7230b57cec5SDimitry Andric   /// Materialize any deferred Metadata block.
7240b57cec5SDimitry Andric   Error materializeMetadata() override;
7250b57cec5SDimitry Andric 
7260b57cec5SDimitry Andric   void setStripDebugInfo() override;
7270b57cec5SDimitry Andric 
7280b57cec5SDimitry Andric private:
7290b57cec5SDimitry Andric   std::vector<StructType *> IdentifiedStructTypes;
7300b57cec5SDimitry Andric   StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
7310b57cec5SDimitry Andric   StructType *createIdentifiedStructType(LLVMContext &Context);
7320b57cec5SDimitry Andric 
73381ad6265SDimitry Andric   static constexpr unsigned InvalidTypeID = ~0u;
7340b57cec5SDimitry Andric 
73581ad6265SDimitry Andric   Type *getTypeByID(unsigned ID);
73681ad6265SDimitry Andric   Type *getPtrElementTypeByID(unsigned ID);
73781ad6265SDimitry Andric   unsigned getContainedTypeID(unsigned ID, unsigned Idx = 0);
73881ad6265SDimitry Andric   unsigned getVirtualTypeID(Type *Ty, ArrayRef<unsigned> ContainedTypeIDs = {});
73981ad6265SDimitry Andric 
740bdd1243dSDimitry Andric   void callValueTypeCallback(Value *F, unsigned TypeID);
74181ad6265SDimitry Andric   Expected<Value *> materializeValue(unsigned ValID, BasicBlock *InsertBB);
74281ad6265SDimitry Andric   Expected<Constant *> getValueForInitializer(unsigned ID);
74381ad6265SDimitry Andric 
74481ad6265SDimitry Andric   Value *getFnValueByID(unsigned ID, Type *Ty, unsigned TyID,
74581ad6265SDimitry Andric                         BasicBlock *ConstExprInsertBB) {
7460b57cec5SDimitry Andric     if (Ty && Ty->isMetadataTy())
7470b57cec5SDimitry Andric       return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
74881ad6265SDimitry Andric     return ValueList.getValueFwdRef(ID, Ty, TyID, ConstExprInsertBB);
7490b57cec5SDimitry Andric   }
7500b57cec5SDimitry Andric 
7510b57cec5SDimitry Andric   Metadata *getFnMetadataByID(unsigned ID) {
7520b57cec5SDimitry Andric     return MDLoader->getMetadataFwdRefOrLoad(ID);
7530b57cec5SDimitry Andric   }
7540b57cec5SDimitry Andric 
7550b57cec5SDimitry Andric   BasicBlock *getBasicBlock(unsigned ID) const {
7560b57cec5SDimitry Andric     if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
7570b57cec5SDimitry Andric     return FunctionBBs[ID];
7580b57cec5SDimitry Andric   }
7590b57cec5SDimitry Andric 
7600b57cec5SDimitry Andric   AttributeList getAttributes(unsigned i) const {
7610b57cec5SDimitry Andric     if (i-1 < MAttributes.size())
7620b57cec5SDimitry Andric       return MAttributes[i-1];
7630b57cec5SDimitry Andric     return AttributeList();
7640b57cec5SDimitry Andric   }
7650b57cec5SDimitry Andric 
7660b57cec5SDimitry Andric   /// Read a value/type pair out of the specified record from slot 'Slot'.
7670b57cec5SDimitry Andric   /// Increment Slot past the number of slots used in the record. Return true on
7680b57cec5SDimitry Andric   /// failure.
769e8d8bef9SDimitry Andric   bool getValueTypePair(const SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
77081ad6265SDimitry Andric                         unsigned InstNum, Value *&ResVal, unsigned &TypeID,
77181ad6265SDimitry Andric                         BasicBlock *ConstExprInsertBB) {
7720b57cec5SDimitry Andric     if (Slot == Record.size()) return true;
7730b57cec5SDimitry Andric     unsigned ValNo = (unsigned)Record[Slot++];
7740b57cec5SDimitry Andric     // Adjust the ValNo, if it was encoded relative to the InstNum.
7750b57cec5SDimitry Andric     if (UseRelativeIDs)
7760b57cec5SDimitry Andric       ValNo = InstNum - ValNo;
7770b57cec5SDimitry Andric     if (ValNo < InstNum) {
7780b57cec5SDimitry Andric       // If this is not a forward reference, just return the value we already
7790b57cec5SDimitry Andric       // have.
78081ad6265SDimitry Andric       TypeID = ValueList.getTypeID(ValNo);
78181ad6265SDimitry Andric       ResVal = getFnValueByID(ValNo, nullptr, TypeID, ConstExprInsertBB);
78281ad6265SDimitry Andric       assert((!ResVal || ResVal->getType() == getTypeByID(TypeID)) &&
78381ad6265SDimitry Andric              "Incorrect type ID stored for value");
7840b57cec5SDimitry Andric       return ResVal == nullptr;
7850b57cec5SDimitry Andric     }
7860b57cec5SDimitry Andric     if (Slot == Record.size())
7870b57cec5SDimitry Andric       return true;
7880b57cec5SDimitry Andric 
78981ad6265SDimitry Andric     TypeID = (unsigned)Record[Slot++];
79081ad6265SDimitry Andric     ResVal = getFnValueByID(ValNo, getTypeByID(TypeID), TypeID,
79181ad6265SDimitry Andric                             ConstExprInsertBB);
7920b57cec5SDimitry Andric     return ResVal == nullptr;
7930b57cec5SDimitry Andric   }
7940b57cec5SDimitry Andric 
7950b57cec5SDimitry Andric   /// Read a value out of the specified record from slot 'Slot'. Increment Slot
7960b57cec5SDimitry Andric   /// past the number of slots used by the value in the record. Return true if
7970b57cec5SDimitry Andric   /// there is an error.
798e8d8bef9SDimitry Andric   bool popValue(const SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
79981ad6265SDimitry Andric                 unsigned InstNum, Type *Ty, unsigned TyID, Value *&ResVal,
80081ad6265SDimitry Andric                 BasicBlock *ConstExprInsertBB) {
80181ad6265SDimitry Andric     if (getValue(Record, Slot, InstNum, Ty, TyID, ResVal, ConstExprInsertBB))
8020b57cec5SDimitry Andric       return true;
8030b57cec5SDimitry Andric     // All values currently take a single record slot.
8040b57cec5SDimitry Andric     ++Slot;
8050b57cec5SDimitry Andric     return false;
8060b57cec5SDimitry Andric   }
8070b57cec5SDimitry Andric 
8080b57cec5SDimitry Andric   /// Like popValue, but does not increment the Slot number.
809e8d8bef9SDimitry Andric   bool getValue(const SmallVectorImpl<uint64_t> &Record, unsigned Slot,
81081ad6265SDimitry Andric                 unsigned InstNum, Type *Ty, unsigned TyID, Value *&ResVal,
81181ad6265SDimitry Andric                 BasicBlock *ConstExprInsertBB) {
81281ad6265SDimitry Andric     ResVal = getValue(Record, Slot, InstNum, Ty, TyID, ConstExprInsertBB);
8130b57cec5SDimitry Andric     return ResVal == nullptr;
8140b57cec5SDimitry Andric   }
8150b57cec5SDimitry Andric 
8160b57cec5SDimitry Andric   /// Version of getValue that returns ResVal directly, or 0 if there is an
8170b57cec5SDimitry Andric   /// error.
818e8d8bef9SDimitry Andric   Value *getValue(const SmallVectorImpl<uint64_t> &Record, unsigned Slot,
81981ad6265SDimitry Andric                   unsigned InstNum, Type *Ty, unsigned TyID,
82081ad6265SDimitry Andric                   BasicBlock *ConstExprInsertBB) {
8210b57cec5SDimitry Andric     if (Slot == Record.size()) return nullptr;
8220b57cec5SDimitry Andric     unsigned ValNo = (unsigned)Record[Slot];
8230b57cec5SDimitry Andric     // Adjust the ValNo, if it was encoded relative to the InstNum.
8240b57cec5SDimitry Andric     if (UseRelativeIDs)
8250b57cec5SDimitry Andric       ValNo = InstNum - ValNo;
82681ad6265SDimitry Andric     return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB);
8270b57cec5SDimitry Andric   }
8280b57cec5SDimitry Andric 
8290b57cec5SDimitry Andric   /// Like getValue, but decodes signed VBRs.
830e8d8bef9SDimitry Andric   Value *getValueSigned(const SmallVectorImpl<uint64_t> &Record, unsigned Slot,
83181ad6265SDimitry Andric                         unsigned InstNum, Type *Ty, unsigned TyID,
83281ad6265SDimitry Andric                         BasicBlock *ConstExprInsertBB) {
8330b57cec5SDimitry Andric     if (Slot == Record.size()) return nullptr;
8340b57cec5SDimitry Andric     unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
8350b57cec5SDimitry Andric     // Adjust the ValNo, if it was encoded relative to the InstNum.
8360b57cec5SDimitry Andric     if (UseRelativeIDs)
8370b57cec5SDimitry Andric       ValNo = InstNum - ValNo;
83881ad6265SDimitry Andric     return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB);
8390b57cec5SDimitry Andric   }
8400b57cec5SDimitry Andric 
841*0fca6ea1SDimitry Andric   Expected<ConstantRange> readConstantRange(ArrayRef<uint64_t> Record,
842*0fca6ea1SDimitry Andric                                             unsigned &OpNum,
843*0fca6ea1SDimitry Andric                                             unsigned BitWidth) {
844*0fca6ea1SDimitry Andric     if (Record.size() - OpNum < 2)
845*0fca6ea1SDimitry Andric       return error("Too few records for range");
846*0fca6ea1SDimitry Andric     if (BitWidth > 64) {
847*0fca6ea1SDimitry Andric       unsigned LowerActiveWords = Record[OpNum];
848*0fca6ea1SDimitry Andric       unsigned UpperActiveWords = Record[OpNum++] >> 32;
849*0fca6ea1SDimitry Andric       if (Record.size() - OpNum < LowerActiveWords + UpperActiveWords)
850*0fca6ea1SDimitry Andric         return error("Too few records for range");
851*0fca6ea1SDimitry Andric       APInt Lower =
852*0fca6ea1SDimitry Andric           readWideAPInt(ArrayRef(&Record[OpNum], LowerActiveWords), BitWidth);
853*0fca6ea1SDimitry Andric       OpNum += LowerActiveWords;
854*0fca6ea1SDimitry Andric       APInt Upper =
855*0fca6ea1SDimitry Andric           readWideAPInt(ArrayRef(&Record[OpNum], UpperActiveWords), BitWidth);
856*0fca6ea1SDimitry Andric       OpNum += UpperActiveWords;
857*0fca6ea1SDimitry Andric       return ConstantRange(Lower, Upper);
858*0fca6ea1SDimitry Andric     } else {
859*0fca6ea1SDimitry Andric       int64_t Start = BitcodeReader::decodeSignRotatedValue(Record[OpNum++]);
860*0fca6ea1SDimitry Andric       int64_t End = BitcodeReader::decodeSignRotatedValue(Record[OpNum++]);
861*0fca6ea1SDimitry Andric       return ConstantRange(APInt(BitWidth, Start), APInt(BitWidth, End));
862*0fca6ea1SDimitry Andric     }
863*0fca6ea1SDimitry Andric   }
864*0fca6ea1SDimitry Andric 
865*0fca6ea1SDimitry Andric   Expected<ConstantRange>
866*0fca6ea1SDimitry Andric   readBitWidthAndConstantRange(ArrayRef<uint64_t> Record, unsigned &OpNum) {
867*0fca6ea1SDimitry Andric     if (Record.size() - OpNum < 1)
868*0fca6ea1SDimitry Andric       return error("Too few records for range");
869*0fca6ea1SDimitry Andric     unsigned BitWidth = Record[OpNum++];
870*0fca6ea1SDimitry Andric     return readConstantRange(Record, OpNum, BitWidth);
871*0fca6ea1SDimitry Andric   }
872*0fca6ea1SDimitry Andric 
873fe6060f1SDimitry Andric   /// Upgrades old-style typeless byval/sret/inalloca attributes by adding the
874fe6060f1SDimitry Andric   /// corresponding argument's pointee type. Also upgrades intrinsics that now
875fe6060f1SDimitry Andric   /// require an elementtype attribute.
87681ad6265SDimitry Andric   Error propagateAttributeTypes(CallBase *CB, ArrayRef<unsigned> ArgsTys);
8770b57cec5SDimitry Andric 
8780b57cec5SDimitry Andric   /// Converts alignment exponent (i.e. power of two (or zero)) to the
8790b57cec5SDimitry Andric   /// corresponding alignment to use. If alignment is too large, returns
8800b57cec5SDimitry Andric   /// a corresponding error code.
8818bcb0991SDimitry Andric   Error parseAlignmentValue(uint64_t Exponent, MaybeAlign &Alignment);
8820b57cec5SDimitry Andric   Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
883bdd1243dSDimitry Andric   Error parseModule(uint64_t ResumeBit, bool ShouldLazyLoadMetadata = false,
884bdd1243dSDimitry Andric                     ParserCallbacks Callbacks = {});
8850b57cec5SDimitry Andric 
8860b57cec5SDimitry Andric   Error parseComdatRecord(ArrayRef<uint64_t> Record);
8870b57cec5SDimitry Andric   Error parseGlobalVarRecord(ArrayRef<uint64_t> Record);
8880b57cec5SDimitry Andric   Error parseFunctionRecord(ArrayRef<uint64_t> Record);
8890b57cec5SDimitry Andric   Error parseGlobalIndirectSymbolRecord(unsigned BitCode,
8900b57cec5SDimitry Andric                                         ArrayRef<uint64_t> Record);
8910b57cec5SDimitry Andric 
8920b57cec5SDimitry Andric   Error parseAttributeBlock();
8930b57cec5SDimitry Andric   Error parseAttributeGroupBlock();
8940b57cec5SDimitry Andric   Error parseTypeTable();
8950b57cec5SDimitry Andric   Error parseTypeTableBody();
8960b57cec5SDimitry Andric   Error parseOperandBundleTags();
8970b57cec5SDimitry Andric   Error parseSyncScopeNames();
8980b57cec5SDimitry Andric 
8990b57cec5SDimitry Andric   Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
9000b57cec5SDimitry Andric                                 unsigned NameIndex, Triple &TT);
9010b57cec5SDimitry Andric   void setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, Function *F,
9020b57cec5SDimitry Andric                                ArrayRef<uint64_t> Record);
9030b57cec5SDimitry Andric   Error parseValueSymbolTable(uint64_t Offset = 0);
9040b57cec5SDimitry Andric   Error parseGlobalValueSymbolTable();
9050b57cec5SDimitry Andric   Error parseConstants();
9060b57cec5SDimitry Andric   Error rememberAndSkipFunctionBodies();
9070b57cec5SDimitry Andric   Error rememberAndSkipFunctionBody();
9080b57cec5SDimitry Andric   /// Save the positions of the Metadata blocks and skip parsing the blocks.
9090b57cec5SDimitry Andric   Error rememberAndSkipMetadata();
9100b57cec5SDimitry Andric   Error typeCheckLoadStoreInst(Type *ValType, Type *PtrType);
9110b57cec5SDimitry Andric   Error parseFunctionBody(Function *F);
9120b57cec5SDimitry Andric   Error globalCleanup();
9130b57cec5SDimitry Andric   Error resolveGlobalAndIndirectSymbolInits();
9140b57cec5SDimitry Andric   Error parseUseLists();
9150b57cec5SDimitry Andric   Error findFunctionInStream(
9160b57cec5SDimitry Andric       Function *F,
9170b57cec5SDimitry Andric       DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
9180b57cec5SDimitry Andric 
9190b57cec5SDimitry Andric   SyncScope::ID getDecodedSyncScopeID(unsigned Val);
9200b57cec5SDimitry Andric };
9210b57cec5SDimitry Andric 
9220b57cec5SDimitry Andric /// Class to manage reading and parsing function summary index bitcode
9230b57cec5SDimitry Andric /// files/sections.
9240b57cec5SDimitry Andric class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase {
9250b57cec5SDimitry Andric   /// The module index built during parsing.
9260b57cec5SDimitry Andric   ModuleSummaryIndex &TheIndex;
9270b57cec5SDimitry Andric 
9280b57cec5SDimitry Andric   /// Indicates whether we have encountered a global value summary section
9290b57cec5SDimitry Andric   /// yet during parsing.
9300b57cec5SDimitry Andric   bool SeenGlobalValSummary = false;
9310b57cec5SDimitry Andric 
9320b57cec5SDimitry Andric   /// Indicates whether we have already parsed the VST, used for error checking.
9330b57cec5SDimitry Andric   bool SeenValueSymbolTable = false;
9340b57cec5SDimitry Andric 
9350b57cec5SDimitry Andric   /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record.
9360b57cec5SDimitry Andric   /// Used to enable on-demand parsing of the VST.
9370b57cec5SDimitry Andric   uint64_t VSTOffset = 0;
9380b57cec5SDimitry Andric 
9390b57cec5SDimitry Andric   // Map to save ValueId to ValueInfo association that was recorded in the
9400b57cec5SDimitry Andric   // ValueSymbolTable. It is used after the VST is parsed to convert
9410b57cec5SDimitry Andric   // call graph edges read from the function summary from referencing
9420b57cec5SDimitry Andric   // callees by their ValueId to using the ValueInfo instead, which is how
9430b57cec5SDimitry Andric   // they are recorded in the summary index being built.
9440b57cec5SDimitry Andric   // We save a GUID which refers to the same global as the ValueInfo, but
9450b57cec5SDimitry Andric   // ignoring the linkage, i.e. for values other than local linkage they are
946bdd1243dSDimitry Andric   // identical (this is the second tuple member).
947bdd1243dSDimitry Andric   // The third tuple member is the real GUID of the ValueInfo.
948bdd1243dSDimitry Andric   DenseMap<unsigned,
949bdd1243dSDimitry Andric            std::tuple<ValueInfo, GlobalValue::GUID, GlobalValue::GUID>>
9500b57cec5SDimitry Andric       ValueIdToValueInfoMap;
9510b57cec5SDimitry Andric 
9520b57cec5SDimitry Andric   /// Map populated during module path string table parsing, from the
9530b57cec5SDimitry Andric   /// module ID to a string reference owned by the index's module
9540b57cec5SDimitry Andric   /// path string table, used to correlate with combined index
9550b57cec5SDimitry Andric   /// summary records.
9560b57cec5SDimitry Andric   DenseMap<uint64_t, StringRef> ModuleIdMap;
9570b57cec5SDimitry Andric 
9580b57cec5SDimitry Andric   /// Original source file name recorded in a bitcode record.
9590b57cec5SDimitry Andric   std::string SourceFileName;
9600b57cec5SDimitry Andric 
9610b57cec5SDimitry Andric   /// The string identifier given to this module by the client, normally the
9620b57cec5SDimitry Andric   /// path to the bitcode file.
9630b57cec5SDimitry Andric   StringRef ModulePath;
9640b57cec5SDimitry Andric 
965bdd1243dSDimitry Andric   /// Callback to ask whether a symbol is the prevailing copy when invoked
966bdd1243dSDimitry Andric   /// during combined index building.
967bdd1243dSDimitry Andric   std::function<bool(GlobalValue::GUID)> IsPrevailing;
968bdd1243dSDimitry Andric 
969bdd1243dSDimitry Andric   /// Saves the stack ids from the STACK_IDS record to consult when adding stack
970bdd1243dSDimitry Andric   /// ids from the lists in the callsite and alloc entries to the index.
971bdd1243dSDimitry Andric   std::vector<uint64_t> StackIds;
972bdd1243dSDimitry Andric 
9730b57cec5SDimitry Andric public:
974bdd1243dSDimitry Andric   ModuleSummaryIndexBitcodeReader(
975bdd1243dSDimitry Andric       BitstreamCursor Stream, StringRef Strtab, ModuleSummaryIndex &TheIndex,
9765f757f3fSDimitry Andric       StringRef ModulePath,
977bdd1243dSDimitry Andric       std::function<bool(GlobalValue::GUID)> IsPrevailing = nullptr);
9780b57cec5SDimitry Andric 
9790b57cec5SDimitry Andric   Error parseModule();
9800b57cec5SDimitry Andric 
9810b57cec5SDimitry Andric private:
9820b57cec5SDimitry Andric   void setValueGUID(uint64_t ValueID, StringRef ValueName,
9830b57cec5SDimitry Andric                     GlobalValue::LinkageTypes Linkage,
9840b57cec5SDimitry Andric                     StringRef SourceFileName);
9850b57cec5SDimitry Andric   Error parseValueSymbolTable(
9860b57cec5SDimitry Andric       uint64_t Offset,
9870b57cec5SDimitry Andric       DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
9880b57cec5SDimitry Andric   std::vector<ValueInfo> makeRefList(ArrayRef<uint64_t> Record);
9890b57cec5SDimitry Andric   std::vector<FunctionSummary::EdgeTy> makeCallList(ArrayRef<uint64_t> Record,
9900b57cec5SDimitry Andric                                                     bool IsOldProfileFormat,
9910b57cec5SDimitry Andric                                                     bool HasProfile,
9920b57cec5SDimitry Andric                                                     bool HasRelBF);
9930b57cec5SDimitry Andric   Error parseEntireSummary(unsigned ID);
9940b57cec5SDimitry Andric   Error parseModuleStringTable();
9950b57cec5SDimitry Andric   void parseTypeIdCompatibleVtableSummaryRecord(ArrayRef<uint64_t> Record);
9960b57cec5SDimitry Andric   void parseTypeIdCompatibleVtableInfo(ArrayRef<uint64_t> Record, size_t &Slot,
9970b57cec5SDimitry Andric                                        TypeIdCompatibleVtableInfo &TypeId);
998e8d8bef9SDimitry Andric   std::vector<FunctionSummary::ParamAccess>
999e8d8bef9SDimitry Andric   parseParamAccesses(ArrayRef<uint64_t> Record);
10000b57cec5SDimitry Andric 
1001bdd1243dSDimitry Andric   template <bool AllowNullValueInfo = false>
1002bdd1243dSDimitry Andric   std::tuple<ValueInfo, GlobalValue::GUID, GlobalValue::GUID>
10030b57cec5SDimitry Andric   getValueInfoFromValueId(unsigned ValueId);
10040b57cec5SDimitry Andric 
10050b57cec5SDimitry Andric   void addThisModule();
10060b57cec5SDimitry Andric   ModuleSummaryIndex::ModuleInfo *getThisModule();
10070b57cec5SDimitry Andric };
10080b57cec5SDimitry Andric 
10090b57cec5SDimitry Andric } // end anonymous namespace
10100b57cec5SDimitry Andric 
10110b57cec5SDimitry Andric std::error_code llvm::errorToErrorCodeAndEmitErrors(LLVMContext &Ctx,
10120b57cec5SDimitry Andric                                                     Error Err) {
10130b57cec5SDimitry Andric   if (Err) {
10140b57cec5SDimitry Andric     std::error_code EC;
10150b57cec5SDimitry Andric     handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) {
10160b57cec5SDimitry Andric       EC = EIB.convertToErrorCode();
10170b57cec5SDimitry Andric       Ctx.emitError(EIB.message());
10180b57cec5SDimitry Andric     });
10190b57cec5SDimitry Andric     return EC;
10200b57cec5SDimitry Andric   }
10210b57cec5SDimitry Andric   return std::error_code();
10220b57cec5SDimitry Andric }
10230b57cec5SDimitry Andric 
10240b57cec5SDimitry Andric BitcodeReader::BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
10250b57cec5SDimitry Andric                              StringRef ProducerIdentification,
10260b57cec5SDimitry Andric                              LLVMContext &Context)
10270b57cec5SDimitry Andric     : BitcodeReaderBase(std::move(Stream), Strtab), Context(Context),
102881ad6265SDimitry Andric       ValueList(this->Stream.SizeInBytes(),
102981ad6265SDimitry Andric                 [this](unsigned ValID, BasicBlock *InsertBB) {
103081ad6265SDimitry Andric                   return materializeValue(ValID, InsertBB);
103181ad6265SDimitry Andric                 }) {
10325ffd83dbSDimitry Andric   this->ProducerIdentification = std::string(ProducerIdentification);
10330b57cec5SDimitry Andric }
10340b57cec5SDimitry Andric 
10350b57cec5SDimitry Andric Error BitcodeReader::materializeForwardReferencedFunctions() {
10360b57cec5SDimitry Andric   if (WillMaterializeAllForwardRefs)
10370b57cec5SDimitry Andric     return Error::success();
10380b57cec5SDimitry Andric 
10390b57cec5SDimitry Andric   // Prevent recursion.
10400b57cec5SDimitry Andric   WillMaterializeAllForwardRefs = true;
10410b57cec5SDimitry Andric 
10420b57cec5SDimitry Andric   while (!BasicBlockFwdRefQueue.empty()) {
10430b57cec5SDimitry Andric     Function *F = BasicBlockFwdRefQueue.front();
10440b57cec5SDimitry Andric     BasicBlockFwdRefQueue.pop_front();
10450b57cec5SDimitry Andric     assert(F && "Expected valid function");
10460b57cec5SDimitry Andric     if (!BasicBlockFwdRefs.count(F))
10470b57cec5SDimitry Andric       // Already materialized.
10480b57cec5SDimitry Andric       continue;
10490b57cec5SDimitry Andric 
10500b57cec5SDimitry Andric     // Check for a function that isn't materializable to prevent an infinite
10510b57cec5SDimitry Andric     // loop.  When parsing a blockaddress stored in a global variable, there
10520b57cec5SDimitry Andric     // isn't a trivial way to check if a function will have a body without a
10530b57cec5SDimitry Andric     // linear search through FunctionsWithBodies, so just check it here.
10540b57cec5SDimitry Andric     if (!F->isMaterializable())
10550b57cec5SDimitry Andric       return error("Never resolved function from blockaddress");
10560b57cec5SDimitry Andric 
10570b57cec5SDimitry Andric     // Try to materialize F.
10580b57cec5SDimitry Andric     if (Error Err = materialize(F))
10590b57cec5SDimitry Andric       return Err;
10600b57cec5SDimitry Andric   }
10610b57cec5SDimitry Andric   assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
10620b57cec5SDimitry Andric 
106381ad6265SDimitry Andric   for (Function *F : BackwardRefFunctions)
106481ad6265SDimitry Andric     if (Error Err = materialize(F))
106581ad6265SDimitry Andric       return Err;
106681ad6265SDimitry Andric   BackwardRefFunctions.clear();
106781ad6265SDimitry Andric 
10680b57cec5SDimitry Andric   // Reset state.
10690b57cec5SDimitry Andric   WillMaterializeAllForwardRefs = false;
10700b57cec5SDimitry Andric   return Error::success();
10710b57cec5SDimitry Andric }
10720b57cec5SDimitry Andric 
10730b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
10740b57cec5SDimitry Andric //  Helper functions to implement forward reference resolution, etc.
10750b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
10760b57cec5SDimitry Andric 
10770b57cec5SDimitry Andric static bool hasImplicitComdat(size_t Val) {
10780b57cec5SDimitry Andric   switch (Val) {
10790b57cec5SDimitry Andric   default:
10800b57cec5SDimitry Andric     return false;
10810b57cec5SDimitry Andric   case 1:  // Old WeakAnyLinkage
10820b57cec5SDimitry Andric   case 4:  // Old LinkOnceAnyLinkage
10830b57cec5SDimitry Andric   case 10: // Old WeakODRLinkage
10840b57cec5SDimitry Andric   case 11: // Old LinkOnceODRLinkage
10850b57cec5SDimitry Andric     return true;
10860b57cec5SDimitry Andric   }
10870b57cec5SDimitry Andric }
10880b57cec5SDimitry Andric 
10890b57cec5SDimitry Andric static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
10900b57cec5SDimitry Andric   switch (Val) {
10910b57cec5SDimitry Andric   default: // Map unknown/new linkages to external
10920b57cec5SDimitry Andric   case 0:
10930b57cec5SDimitry Andric     return GlobalValue::ExternalLinkage;
10940b57cec5SDimitry Andric   case 2:
10950b57cec5SDimitry Andric     return GlobalValue::AppendingLinkage;
10960b57cec5SDimitry Andric   case 3:
10970b57cec5SDimitry Andric     return GlobalValue::InternalLinkage;
10980b57cec5SDimitry Andric   case 5:
10990b57cec5SDimitry Andric     return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
11000b57cec5SDimitry Andric   case 6:
11010b57cec5SDimitry Andric     return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
11020b57cec5SDimitry Andric   case 7:
11030b57cec5SDimitry Andric     return GlobalValue::ExternalWeakLinkage;
11040b57cec5SDimitry Andric   case 8:
11050b57cec5SDimitry Andric     return GlobalValue::CommonLinkage;
11060b57cec5SDimitry Andric   case 9:
11070b57cec5SDimitry Andric     return GlobalValue::PrivateLinkage;
11080b57cec5SDimitry Andric   case 12:
11090b57cec5SDimitry Andric     return GlobalValue::AvailableExternallyLinkage;
11100b57cec5SDimitry Andric   case 13:
11110b57cec5SDimitry Andric     return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
11120b57cec5SDimitry Andric   case 14:
11130b57cec5SDimitry Andric     return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
11140b57cec5SDimitry Andric   case 15:
11150b57cec5SDimitry Andric     return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
11160b57cec5SDimitry Andric   case 1: // Old value with implicit comdat.
11170b57cec5SDimitry Andric   case 16:
11180b57cec5SDimitry Andric     return GlobalValue::WeakAnyLinkage;
11190b57cec5SDimitry Andric   case 10: // Old value with implicit comdat.
11200b57cec5SDimitry Andric   case 17:
11210b57cec5SDimitry Andric     return GlobalValue::WeakODRLinkage;
11220b57cec5SDimitry Andric   case 4: // Old value with implicit comdat.
11230b57cec5SDimitry Andric   case 18:
11240b57cec5SDimitry Andric     return GlobalValue::LinkOnceAnyLinkage;
11250b57cec5SDimitry Andric   case 11: // Old value with implicit comdat.
11260b57cec5SDimitry Andric   case 19:
11270b57cec5SDimitry Andric     return GlobalValue::LinkOnceODRLinkage;
11280b57cec5SDimitry Andric   }
11290b57cec5SDimitry Andric }
11300b57cec5SDimitry Andric 
11310b57cec5SDimitry Andric static FunctionSummary::FFlags getDecodedFFlags(uint64_t RawFlags) {
11320b57cec5SDimitry Andric   FunctionSummary::FFlags Flags;
11330b57cec5SDimitry Andric   Flags.ReadNone = RawFlags & 0x1;
11340b57cec5SDimitry Andric   Flags.ReadOnly = (RawFlags >> 1) & 0x1;
11350b57cec5SDimitry Andric   Flags.NoRecurse = (RawFlags >> 2) & 0x1;
11360b57cec5SDimitry Andric   Flags.ReturnDoesNotAlias = (RawFlags >> 3) & 0x1;
11370b57cec5SDimitry Andric   Flags.NoInline = (RawFlags >> 4) & 0x1;
1138480093f4SDimitry Andric   Flags.AlwaysInline = (RawFlags >> 5) & 0x1;
1139349cc55cSDimitry Andric   Flags.NoUnwind = (RawFlags >> 6) & 0x1;
1140349cc55cSDimitry Andric   Flags.MayThrow = (RawFlags >> 7) & 0x1;
1141349cc55cSDimitry Andric   Flags.HasUnknownCall = (RawFlags >> 8) & 0x1;
11420eae32dcSDimitry Andric   Flags.MustBeUnreachable = (RawFlags >> 9) & 0x1;
11430b57cec5SDimitry Andric   return Flags;
11440b57cec5SDimitry Andric }
11450b57cec5SDimitry Andric 
1146fe6060f1SDimitry Andric // Decode the flags for GlobalValue in the summary. The bits for each attribute:
1147fe6060f1SDimitry Andric //
1148fe6060f1SDimitry Andric // linkage: [0,4), notEligibleToImport: 4, live: 5, local: 6, canAutoHide: 7,
1149fe6060f1SDimitry Andric // visibility: [8, 10).
11500b57cec5SDimitry Andric static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags,
11510b57cec5SDimitry Andric                                                             uint64_t Version) {
11520b57cec5SDimitry Andric   // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage
11530b57cec5SDimitry Andric   // like getDecodedLinkage() above. Any future change to the linkage enum and
11540b57cec5SDimitry Andric   // to getDecodedLinkage() will need to be taken into account here as above.
11550b57cec5SDimitry Andric   auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits
1156fe6060f1SDimitry Andric   auto Visibility = GlobalValue::VisibilityTypes((RawFlags >> 8) & 3); // 2 bits
1157*0fca6ea1SDimitry Andric   auto IK = GlobalValueSummary::ImportKind((RawFlags >> 10) & 1);      // 1 bit
11580b57cec5SDimitry Andric   RawFlags = RawFlags >> 4;
11590b57cec5SDimitry Andric   bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3;
11600b57cec5SDimitry Andric   // The Live flag wasn't introduced until version 3. For dead stripping
11610b57cec5SDimitry Andric   // to work correctly on earlier versions, we must conservatively treat all
11620b57cec5SDimitry Andric   // values as live.
11630b57cec5SDimitry Andric   bool Live = (RawFlags & 0x2) || Version < 3;
11640b57cec5SDimitry Andric   bool Local = (RawFlags & 0x4);
11650b57cec5SDimitry Andric   bool AutoHide = (RawFlags & 0x8);
11660b57cec5SDimitry Andric 
1167fe6060f1SDimitry Andric   return GlobalValueSummary::GVFlags(Linkage, Visibility, NotEligibleToImport,
1168*0fca6ea1SDimitry Andric                                      Live, Local, AutoHide, IK);
11690b57cec5SDimitry Andric }
11700b57cec5SDimitry Andric 
11710b57cec5SDimitry Andric // Decode the flags for GlobalVariable in the summary
11720b57cec5SDimitry Andric static GlobalVarSummary::GVarFlags getDecodedGVarFlags(uint64_t RawFlags) {
11735ffd83dbSDimitry Andric   return GlobalVarSummary::GVarFlags(
11745ffd83dbSDimitry Andric       (RawFlags & 0x1) ? true : false, (RawFlags & 0x2) ? true : false,
11755ffd83dbSDimitry Andric       (RawFlags & 0x4) ? true : false,
11765ffd83dbSDimitry Andric       (GlobalObject::VCallVisibility)(RawFlags >> 3));
11770b57cec5SDimitry Andric }
11780b57cec5SDimitry Andric 
11795f757f3fSDimitry Andric static std::pair<CalleeInfo::HotnessType, bool>
11805f757f3fSDimitry Andric getDecodedHotnessCallEdgeInfo(uint64_t RawFlags) {
11815f757f3fSDimitry Andric   CalleeInfo::HotnessType Hotness =
11825f757f3fSDimitry Andric       static_cast<CalleeInfo::HotnessType>(RawFlags & 0x7); // 3 bits
11835f757f3fSDimitry Andric   bool HasTailCall = (RawFlags & 0x8);                      // 1 bit
11845f757f3fSDimitry Andric   return {Hotness, HasTailCall};
11855f757f3fSDimitry Andric }
11865f757f3fSDimitry Andric 
11875f757f3fSDimitry Andric static void getDecodedRelBFCallEdgeInfo(uint64_t RawFlags, uint64_t &RelBF,
11885f757f3fSDimitry Andric                                         bool &HasTailCall) {
11895f757f3fSDimitry Andric   static constexpr uint64_t RelBlockFreqMask =
11905f757f3fSDimitry Andric       (1 << CalleeInfo::RelBlockFreqBits) - 1;
11915f757f3fSDimitry Andric   RelBF = RawFlags & RelBlockFreqMask; // RelBlockFreqBits bits
11925f757f3fSDimitry Andric   HasTailCall = (RawFlags & (1 << CalleeInfo::RelBlockFreqBits)); // 1 bit
11935f757f3fSDimitry Andric }
11945f757f3fSDimitry Andric 
11950b57cec5SDimitry Andric static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
11960b57cec5SDimitry Andric   switch (Val) {
11970b57cec5SDimitry Andric   default: // Map unknown visibilities to default.
11980b57cec5SDimitry Andric   case 0: return GlobalValue::DefaultVisibility;
11990b57cec5SDimitry Andric   case 1: return GlobalValue::HiddenVisibility;
12000b57cec5SDimitry Andric   case 2: return GlobalValue::ProtectedVisibility;
12010b57cec5SDimitry Andric   }
12020b57cec5SDimitry Andric }
12030b57cec5SDimitry Andric 
12040b57cec5SDimitry Andric static GlobalValue::DLLStorageClassTypes
12050b57cec5SDimitry Andric getDecodedDLLStorageClass(unsigned Val) {
12060b57cec5SDimitry Andric   switch (Val) {
12070b57cec5SDimitry Andric   default: // Map unknown values to default.
12080b57cec5SDimitry Andric   case 0: return GlobalValue::DefaultStorageClass;
12090b57cec5SDimitry Andric   case 1: return GlobalValue::DLLImportStorageClass;
12100b57cec5SDimitry Andric   case 2: return GlobalValue::DLLExportStorageClass;
12110b57cec5SDimitry Andric   }
12120b57cec5SDimitry Andric }
12130b57cec5SDimitry Andric 
12140b57cec5SDimitry Andric static bool getDecodedDSOLocal(unsigned Val) {
12150b57cec5SDimitry Andric   switch(Val) {
12160b57cec5SDimitry Andric   default: // Map unknown values to preemptable.
12170b57cec5SDimitry Andric   case 0:  return false;
12180b57cec5SDimitry Andric   case 1:  return true;
12190b57cec5SDimitry Andric   }
12200b57cec5SDimitry Andric }
12210b57cec5SDimitry Andric 
12225f757f3fSDimitry Andric static std::optional<CodeModel::Model> getDecodedCodeModel(unsigned Val) {
12235f757f3fSDimitry Andric   switch (Val) {
12245f757f3fSDimitry Andric   case 1:
12255f757f3fSDimitry Andric     return CodeModel::Tiny;
12265f757f3fSDimitry Andric   case 2:
12275f757f3fSDimitry Andric     return CodeModel::Small;
12285f757f3fSDimitry Andric   case 3:
12295f757f3fSDimitry Andric     return CodeModel::Kernel;
12305f757f3fSDimitry Andric   case 4:
12315f757f3fSDimitry Andric     return CodeModel::Medium;
12325f757f3fSDimitry Andric   case 5:
12335f757f3fSDimitry Andric     return CodeModel::Large;
12345f757f3fSDimitry Andric   }
12355f757f3fSDimitry Andric 
12365f757f3fSDimitry Andric   return {};
12375f757f3fSDimitry Andric }
12385f757f3fSDimitry Andric 
12390b57cec5SDimitry Andric static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
12400b57cec5SDimitry Andric   switch (Val) {
12410b57cec5SDimitry Andric     case 0: return GlobalVariable::NotThreadLocal;
12420b57cec5SDimitry Andric     default: // Map unknown non-zero value to general dynamic.
12430b57cec5SDimitry Andric     case 1: return GlobalVariable::GeneralDynamicTLSModel;
12440b57cec5SDimitry Andric     case 2: return GlobalVariable::LocalDynamicTLSModel;
12450b57cec5SDimitry Andric     case 3: return GlobalVariable::InitialExecTLSModel;
12460b57cec5SDimitry Andric     case 4: return GlobalVariable::LocalExecTLSModel;
12470b57cec5SDimitry Andric   }
12480b57cec5SDimitry Andric }
12490b57cec5SDimitry Andric 
12500b57cec5SDimitry Andric static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) {
12510b57cec5SDimitry Andric   switch (Val) {
12520b57cec5SDimitry Andric     default: // Map unknown to UnnamedAddr::None.
12530b57cec5SDimitry Andric     case 0: return GlobalVariable::UnnamedAddr::None;
12540b57cec5SDimitry Andric     case 1: return GlobalVariable::UnnamedAddr::Global;
12550b57cec5SDimitry Andric     case 2: return GlobalVariable::UnnamedAddr::Local;
12560b57cec5SDimitry Andric   }
12570b57cec5SDimitry Andric }
12580b57cec5SDimitry Andric 
12590b57cec5SDimitry Andric static int getDecodedCastOpcode(unsigned Val) {
12600b57cec5SDimitry Andric   switch (Val) {
12610b57cec5SDimitry Andric   default: return -1;
12620b57cec5SDimitry Andric   case bitc::CAST_TRUNC   : return Instruction::Trunc;
12630b57cec5SDimitry Andric   case bitc::CAST_ZEXT    : return Instruction::ZExt;
12640b57cec5SDimitry Andric   case bitc::CAST_SEXT    : return Instruction::SExt;
12650b57cec5SDimitry Andric   case bitc::CAST_FPTOUI  : return Instruction::FPToUI;
12660b57cec5SDimitry Andric   case bitc::CAST_FPTOSI  : return Instruction::FPToSI;
12670b57cec5SDimitry Andric   case bitc::CAST_UITOFP  : return Instruction::UIToFP;
12680b57cec5SDimitry Andric   case bitc::CAST_SITOFP  : return Instruction::SIToFP;
12690b57cec5SDimitry Andric   case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
12700b57cec5SDimitry Andric   case bitc::CAST_FPEXT   : return Instruction::FPExt;
12710b57cec5SDimitry Andric   case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
12720b57cec5SDimitry Andric   case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
12730b57cec5SDimitry Andric   case bitc::CAST_BITCAST : return Instruction::BitCast;
12740b57cec5SDimitry Andric   case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
12750b57cec5SDimitry Andric   }
12760b57cec5SDimitry Andric }
12770b57cec5SDimitry Andric 
12780b57cec5SDimitry Andric static int getDecodedUnaryOpcode(unsigned Val, Type *Ty) {
12790b57cec5SDimitry Andric   bool IsFP = Ty->isFPOrFPVectorTy();
12800b57cec5SDimitry Andric   // UnOps are only valid for int/fp or vector of int/fp types
12810b57cec5SDimitry Andric   if (!IsFP && !Ty->isIntOrIntVectorTy())
12820b57cec5SDimitry Andric     return -1;
12830b57cec5SDimitry Andric 
12840b57cec5SDimitry Andric   switch (Val) {
12850b57cec5SDimitry Andric   default:
12860b57cec5SDimitry Andric     return -1;
12878bcb0991SDimitry Andric   case bitc::UNOP_FNEG:
12880b57cec5SDimitry Andric     return IsFP ? Instruction::FNeg : -1;
12890b57cec5SDimitry Andric   }
12900b57cec5SDimitry Andric }
12910b57cec5SDimitry Andric 
12920b57cec5SDimitry Andric static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
12930b57cec5SDimitry Andric   bool IsFP = Ty->isFPOrFPVectorTy();
12940b57cec5SDimitry Andric   // BinOps are only valid for int/fp or vector of int/fp types
12950b57cec5SDimitry Andric   if (!IsFP && !Ty->isIntOrIntVectorTy())
12960b57cec5SDimitry Andric     return -1;
12970b57cec5SDimitry Andric 
12980b57cec5SDimitry Andric   switch (Val) {
12990b57cec5SDimitry Andric   default:
13000b57cec5SDimitry Andric     return -1;
13010b57cec5SDimitry Andric   case bitc::BINOP_ADD:
13020b57cec5SDimitry Andric     return IsFP ? Instruction::FAdd : Instruction::Add;
13030b57cec5SDimitry Andric   case bitc::BINOP_SUB:
13040b57cec5SDimitry Andric     return IsFP ? Instruction::FSub : Instruction::Sub;
13050b57cec5SDimitry Andric   case bitc::BINOP_MUL:
13060b57cec5SDimitry Andric     return IsFP ? Instruction::FMul : Instruction::Mul;
13070b57cec5SDimitry Andric   case bitc::BINOP_UDIV:
13080b57cec5SDimitry Andric     return IsFP ? -1 : Instruction::UDiv;
13090b57cec5SDimitry Andric   case bitc::BINOP_SDIV:
13100b57cec5SDimitry Andric     return IsFP ? Instruction::FDiv : Instruction::SDiv;
13110b57cec5SDimitry Andric   case bitc::BINOP_UREM:
13120b57cec5SDimitry Andric     return IsFP ? -1 : Instruction::URem;
13130b57cec5SDimitry Andric   case bitc::BINOP_SREM:
13140b57cec5SDimitry Andric     return IsFP ? Instruction::FRem : Instruction::SRem;
13150b57cec5SDimitry Andric   case bitc::BINOP_SHL:
13160b57cec5SDimitry Andric     return IsFP ? -1 : Instruction::Shl;
13170b57cec5SDimitry Andric   case bitc::BINOP_LSHR:
13180b57cec5SDimitry Andric     return IsFP ? -1 : Instruction::LShr;
13190b57cec5SDimitry Andric   case bitc::BINOP_ASHR:
13200b57cec5SDimitry Andric     return IsFP ? -1 : Instruction::AShr;
13210b57cec5SDimitry Andric   case bitc::BINOP_AND:
13220b57cec5SDimitry Andric     return IsFP ? -1 : Instruction::And;
13230b57cec5SDimitry Andric   case bitc::BINOP_OR:
13240b57cec5SDimitry Andric     return IsFP ? -1 : Instruction::Or;
13250b57cec5SDimitry Andric   case bitc::BINOP_XOR:
13260b57cec5SDimitry Andric     return IsFP ? -1 : Instruction::Xor;
13270b57cec5SDimitry Andric   }
13280b57cec5SDimitry Andric }
13290b57cec5SDimitry Andric 
13300b57cec5SDimitry Andric static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
13310b57cec5SDimitry Andric   switch (Val) {
13320b57cec5SDimitry Andric   default: return AtomicRMWInst::BAD_BINOP;
13330b57cec5SDimitry Andric   case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
13340b57cec5SDimitry Andric   case bitc::RMW_ADD: return AtomicRMWInst::Add;
13350b57cec5SDimitry Andric   case bitc::RMW_SUB: return AtomicRMWInst::Sub;
13360b57cec5SDimitry Andric   case bitc::RMW_AND: return AtomicRMWInst::And;
13370b57cec5SDimitry Andric   case bitc::RMW_NAND: return AtomicRMWInst::Nand;
13380b57cec5SDimitry Andric   case bitc::RMW_OR: return AtomicRMWInst::Or;
13390b57cec5SDimitry Andric   case bitc::RMW_XOR: return AtomicRMWInst::Xor;
13400b57cec5SDimitry Andric   case bitc::RMW_MAX: return AtomicRMWInst::Max;
13410b57cec5SDimitry Andric   case bitc::RMW_MIN: return AtomicRMWInst::Min;
13420b57cec5SDimitry Andric   case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
13430b57cec5SDimitry Andric   case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
13440b57cec5SDimitry Andric   case bitc::RMW_FADD: return AtomicRMWInst::FAdd;
13450b57cec5SDimitry Andric   case bitc::RMW_FSUB: return AtomicRMWInst::FSub;
1346753f127fSDimitry Andric   case bitc::RMW_FMAX: return AtomicRMWInst::FMax;
1347753f127fSDimitry Andric   case bitc::RMW_FMIN: return AtomicRMWInst::FMin;
1348bdd1243dSDimitry Andric   case bitc::RMW_UINC_WRAP:
1349bdd1243dSDimitry Andric     return AtomicRMWInst::UIncWrap;
1350bdd1243dSDimitry Andric   case bitc::RMW_UDEC_WRAP:
1351bdd1243dSDimitry Andric     return AtomicRMWInst::UDecWrap;
13520b57cec5SDimitry Andric   }
13530b57cec5SDimitry Andric }
13540b57cec5SDimitry Andric 
13550b57cec5SDimitry Andric static AtomicOrdering getDecodedOrdering(unsigned Val) {
13560b57cec5SDimitry Andric   switch (Val) {
13570b57cec5SDimitry Andric   case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic;
13580b57cec5SDimitry Andric   case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered;
13590b57cec5SDimitry Andric   case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic;
13600b57cec5SDimitry Andric   case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire;
13610b57cec5SDimitry Andric   case bitc::ORDERING_RELEASE: return AtomicOrdering::Release;
13620b57cec5SDimitry Andric   case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease;
13630b57cec5SDimitry Andric   default: // Map unknown orderings to sequentially-consistent.
13640b57cec5SDimitry Andric   case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent;
13650b57cec5SDimitry Andric   }
13660b57cec5SDimitry Andric }
13670b57cec5SDimitry Andric 
13680b57cec5SDimitry Andric static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
13690b57cec5SDimitry Andric   switch (Val) {
13700b57cec5SDimitry Andric   default: // Map unknown selection kinds to any.
13710b57cec5SDimitry Andric   case bitc::COMDAT_SELECTION_KIND_ANY:
13720b57cec5SDimitry Andric     return Comdat::Any;
13730b57cec5SDimitry Andric   case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
13740b57cec5SDimitry Andric     return Comdat::ExactMatch;
13750b57cec5SDimitry Andric   case bitc::COMDAT_SELECTION_KIND_LARGEST:
13760b57cec5SDimitry Andric     return Comdat::Largest;
13770b57cec5SDimitry Andric   case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
1378fe6060f1SDimitry Andric     return Comdat::NoDeduplicate;
13790b57cec5SDimitry Andric   case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
13800b57cec5SDimitry Andric     return Comdat::SameSize;
13810b57cec5SDimitry Andric   }
13820b57cec5SDimitry Andric }
13830b57cec5SDimitry Andric 
13840b57cec5SDimitry Andric static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
13850b57cec5SDimitry Andric   FastMathFlags FMF;
13860b57cec5SDimitry Andric   if (0 != (Val & bitc::UnsafeAlgebra))
13870b57cec5SDimitry Andric     FMF.setFast();
13880b57cec5SDimitry Andric   if (0 != (Val & bitc::AllowReassoc))
13890b57cec5SDimitry Andric     FMF.setAllowReassoc();
13900b57cec5SDimitry Andric   if (0 != (Val & bitc::NoNaNs))
13910b57cec5SDimitry Andric     FMF.setNoNaNs();
13920b57cec5SDimitry Andric   if (0 != (Val & bitc::NoInfs))
13930b57cec5SDimitry Andric     FMF.setNoInfs();
13940b57cec5SDimitry Andric   if (0 != (Val & bitc::NoSignedZeros))
13950b57cec5SDimitry Andric     FMF.setNoSignedZeros();
13960b57cec5SDimitry Andric   if (0 != (Val & bitc::AllowReciprocal))
13970b57cec5SDimitry Andric     FMF.setAllowReciprocal();
13980b57cec5SDimitry Andric   if (0 != (Val & bitc::AllowContract))
13990b57cec5SDimitry Andric     FMF.setAllowContract(true);
14000b57cec5SDimitry Andric   if (0 != (Val & bitc::ApproxFunc))
14010b57cec5SDimitry Andric     FMF.setApproxFunc();
14020b57cec5SDimitry Andric   return FMF;
14030b57cec5SDimitry Andric }
14040b57cec5SDimitry Andric 
14050b57cec5SDimitry Andric static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) {
1406bdd1243dSDimitry Andric   // A GlobalValue with local linkage cannot have a DLL storage class.
1407bdd1243dSDimitry Andric   if (GV->hasLocalLinkage())
1408bdd1243dSDimitry Andric     return;
14090b57cec5SDimitry Andric   switch (Val) {
14100b57cec5SDimitry Andric   case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
14110b57cec5SDimitry Andric   case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
14120b57cec5SDimitry Andric   }
14130b57cec5SDimitry Andric }
14140b57cec5SDimitry Andric 
1415fe6060f1SDimitry Andric Type *BitcodeReader::getTypeByID(unsigned ID) {
14160b57cec5SDimitry Andric   // The type table size is always specified correctly.
14170b57cec5SDimitry Andric   if (ID >= TypeList.size())
14180b57cec5SDimitry Andric     return nullptr;
14190b57cec5SDimitry Andric 
14200b57cec5SDimitry Andric   if (Type *Ty = TypeList[ID])
14210b57cec5SDimitry Andric     return Ty;
14220b57cec5SDimitry Andric 
14230b57cec5SDimitry Andric   // If we have a forward reference, the only possible case is when it is to a
14240b57cec5SDimitry Andric   // named struct.  Just create a placeholder for now.
14250b57cec5SDimitry Andric   return TypeList[ID] = createIdentifiedStructType(Context);
14260b57cec5SDimitry Andric }
14270b57cec5SDimitry Andric 
142881ad6265SDimitry Andric unsigned BitcodeReader::getContainedTypeID(unsigned ID, unsigned Idx) {
142981ad6265SDimitry Andric   auto It = ContainedTypeIDs.find(ID);
143081ad6265SDimitry Andric   if (It == ContainedTypeIDs.end())
143181ad6265SDimitry Andric     return InvalidTypeID;
143281ad6265SDimitry Andric 
143381ad6265SDimitry Andric   if (Idx >= It->second.size())
143481ad6265SDimitry Andric     return InvalidTypeID;
143581ad6265SDimitry Andric 
143681ad6265SDimitry Andric   return It->second[Idx];
143781ad6265SDimitry Andric }
143881ad6265SDimitry Andric 
143981ad6265SDimitry Andric Type *BitcodeReader::getPtrElementTypeByID(unsigned ID) {
144081ad6265SDimitry Andric   if (ID >= TypeList.size())
144181ad6265SDimitry Andric     return nullptr;
144281ad6265SDimitry Andric 
144381ad6265SDimitry Andric   Type *Ty = TypeList[ID];
144481ad6265SDimitry Andric   if (!Ty->isPointerTy())
144581ad6265SDimitry Andric     return nullptr;
144681ad6265SDimitry Andric 
144706c3fb27SDimitry Andric   return getTypeByID(getContainedTypeID(ID, 0));
144881ad6265SDimitry Andric }
144981ad6265SDimitry Andric 
145081ad6265SDimitry Andric unsigned BitcodeReader::getVirtualTypeID(Type *Ty,
145181ad6265SDimitry Andric                                          ArrayRef<unsigned> ChildTypeIDs) {
145281ad6265SDimitry Andric   unsigned ChildTypeID = ChildTypeIDs.empty() ? InvalidTypeID : ChildTypeIDs[0];
145381ad6265SDimitry Andric   auto CacheKey = std::make_pair(Ty, ChildTypeID);
145481ad6265SDimitry Andric   auto It = VirtualTypeIDs.find(CacheKey);
145581ad6265SDimitry Andric   if (It != VirtualTypeIDs.end()) {
145681ad6265SDimitry Andric     // The cmpxchg return value is the only place we need more than one
145781ad6265SDimitry Andric     // contained type ID, however the second one will always be the same (i1),
145881ad6265SDimitry Andric     // so we don't need to include it in the cache key. This asserts that the
145981ad6265SDimitry Andric     // contained types are indeed as expected and there are no collisions.
146081ad6265SDimitry Andric     assert((ChildTypeIDs.empty() ||
146181ad6265SDimitry Andric             ContainedTypeIDs[It->second] == ChildTypeIDs) &&
146281ad6265SDimitry Andric            "Incorrect cached contained type IDs");
146381ad6265SDimitry Andric     return It->second;
146481ad6265SDimitry Andric   }
146581ad6265SDimitry Andric 
146681ad6265SDimitry Andric   unsigned TypeID = TypeList.size();
146781ad6265SDimitry Andric   TypeList.push_back(Ty);
146881ad6265SDimitry Andric   if (!ChildTypeIDs.empty())
146981ad6265SDimitry Andric     append_range(ContainedTypeIDs[TypeID], ChildTypeIDs);
147081ad6265SDimitry Andric   VirtualTypeIDs.insert({CacheKey, TypeID});
147181ad6265SDimitry Andric   return TypeID;
147281ad6265SDimitry Andric }
147381ad6265SDimitry Andric 
1474*0fca6ea1SDimitry Andric static GEPNoWrapFlags toGEPNoWrapFlags(uint64_t Flags) {
1475*0fca6ea1SDimitry Andric   GEPNoWrapFlags NW;
1476*0fca6ea1SDimitry Andric   if (Flags & (1 << bitc::GEP_INBOUNDS))
1477*0fca6ea1SDimitry Andric     NW |= GEPNoWrapFlags::inBounds();
1478*0fca6ea1SDimitry Andric   if (Flags & (1 << bitc::GEP_NUSW))
1479*0fca6ea1SDimitry Andric     NW |= GEPNoWrapFlags::noUnsignedSignedWrap();
1480*0fca6ea1SDimitry Andric   if (Flags & (1 << bitc::GEP_NUW))
1481*0fca6ea1SDimitry Andric     NW |= GEPNoWrapFlags::noUnsignedWrap();
1482*0fca6ea1SDimitry Andric   return NW;
1483*0fca6ea1SDimitry Andric }
1484*0fca6ea1SDimitry Andric 
148506c3fb27SDimitry Andric static bool isConstExprSupported(const BitcodeConstant *BC) {
148606c3fb27SDimitry Andric   uint8_t Opcode = BC->Opcode;
148706c3fb27SDimitry Andric 
148881ad6265SDimitry Andric   // These are not real constant expressions, always consider them supported.
148981ad6265SDimitry Andric   if (Opcode >= BitcodeConstant::FirstSpecialOpcode)
149081ad6265SDimitry Andric     return true;
149181ad6265SDimitry Andric 
1492bdd1243dSDimitry Andric   // If -expand-constant-exprs is set, we want to consider all expressions
1493bdd1243dSDimitry Andric   // as unsupported.
1494bdd1243dSDimitry Andric   if (ExpandConstantExprs)
1495bdd1243dSDimitry Andric     return false;
1496bdd1243dSDimitry Andric 
1497753f127fSDimitry Andric   if (Instruction::isBinaryOp(Opcode))
1498753f127fSDimitry Andric     return ConstantExpr::isSupportedBinOp(Opcode);
1499753f127fSDimitry Andric 
15005f757f3fSDimitry Andric   if (Instruction::isCast(Opcode))
15015f757f3fSDimitry Andric     return ConstantExpr::isSupportedCastOp(Opcode);
15025f757f3fSDimitry Andric 
150306c3fb27SDimitry Andric   if (Opcode == Instruction::GetElementPtr)
150406c3fb27SDimitry Andric     return ConstantExpr::isSupportedGetElementPtr(BC->SrcElemTy);
150506c3fb27SDimitry Andric 
150606c3fb27SDimitry Andric   switch (Opcode) {
150706c3fb27SDimitry Andric   case Instruction::FNeg:
150806c3fb27SDimitry Andric   case Instruction::Select:
1509*0fca6ea1SDimitry Andric   case Instruction::ICmp:
1510*0fca6ea1SDimitry Andric   case Instruction::FCmp:
151106c3fb27SDimitry Andric     return false;
151206c3fb27SDimitry Andric   default:
151306c3fb27SDimitry Andric     return true;
151406c3fb27SDimitry Andric   }
151581ad6265SDimitry Andric }
151681ad6265SDimitry Andric 
151781ad6265SDimitry Andric Expected<Value *> BitcodeReader::materializeValue(unsigned StartValID,
151881ad6265SDimitry Andric                                                   BasicBlock *InsertBB) {
151981ad6265SDimitry Andric   // Quickly handle the case where there is no BitcodeConstant to resolve.
152081ad6265SDimitry Andric   if (StartValID < ValueList.size() && ValueList[StartValID] &&
152181ad6265SDimitry Andric       !isa<BitcodeConstant>(ValueList[StartValID]))
152281ad6265SDimitry Andric     return ValueList[StartValID];
152381ad6265SDimitry Andric 
152481ad6265SDimitry Andric   SmallDenseMap<unsigned, Value *> MaterializedValues;
152581ad6265SDimitry Andric   SmallVector<unsigned> Worklist;
152681ad6265SDimitry Andric   Worklist.push_back(StartValID);
152781ad6265SDimitry Andric   while (!Worklist.empty()) {
152881ad6265SDimitry Andric     unsigned ValID = Worklist.back();
152981ad6265SDimitry Andric     if (MaterializedValues.count(ValID)) {
153081ad6265SDimitry Andric       // Duplicate expression that was already handled.
153181ad6265SDimitry Andric       Worklist.pop_back();
153281ad6265SDimitry Andric       continue;
153381ad6265SDimitry Andric     }
153481ad6265SDimitry Andric 
153581ad6265SDimitry Andric     if (ValID >= ValueList.size() || !ValueList[ValID])
153681ad6265SDimitry Andric       return error("Invalid value ID");
153781ad6265SDimitry Andric 
153881ad6265SDimitry Andric     Value *V = ValueList[ValID];
153981ad6265SDimitry Andric     auto *BC = dyn_cast<BitcodeConstant>(V);
154081ad6265SDimitry Andric     if (!BC) {
154181ad6265SDimitry Andric       MaterializedValues.insert({ValID, V});
154281ad6265SDimitry Andric       Worklist.pop_back();
154381ad6265SDimitry Andric       continue;
154481ad6265SDimitry Andric     }
154581ad6265SDimitry Andric 
154681ad6265SDimitry Andric     // Iterate in reverse, so values will get popped from the worklist in
154781ad6265SDimitry Andric     // expected order.
154881ad6265SDimitry Andric     SmallVector<Value *> Ops;
154981ad6265SDimitry Andric     for (unsigned OpID : reverse(BC->getOperandIDs())) {
155081ad6265SDimitry Andric       auto It = MaterializedValues.find(OpID);
155181ad6265SDimitry Andric       if (It != MaterializedValues.end())
155281ad6265SDimitry Andric         Ops.push_back(It->second);
155381ad6265SDimitry Andric       else
155481ad6265SDimitry Andric         Worklist.push_back(OpID);
155581ad6265SDimitry Andric     }
155681ad6265SDimitry Andric 
155781ad6265SDimitry Andric     // Some expressions have not been resolved yet, handle them first and then
155881ad6265SDimitry Andric     // revisit this one.
155981ad6265SDimitry Andric     if (Ops.size() != BC->getOperandIDs().size())
156081ad6265SDimitry Andric       continue;
156181ad6265SDimitry Andric     std::reverse(Ops.begin(), Ops.end());
156281ad6265SDimitry Andric 
156381ad6265SDimitry Andric     SmallVector<Constant *> ConstOps;
156481ad6265SDimitry Andric     for (Value *Op : Ops)
156581ad6265SDimitry Andric       if (auto *C = dyn_cast<Constant>(Op))
156681ad6265SDimitry Andric         ConstOps.push_back(C);
156781ad6265SDimitry Andric 
156881ad6265SDimitry Andric     // Materialize as constant expression if possible.
156906c3fb27SDimitry Andric     if (isConstExprSupported(BC) && ConstOps.size() == Ops.size()) {
157081ad6265SDimitry Andric       Constant *C;
157181ad6265SDimitry Andric       if (Instruction::isCast(BC->Opcode)) {
157281ad6265SDimitry Andric         C = UpgradeBitCastExpr(BC->Opcode, ConstOps[0], BC->getType());
157381ad6265SDimitry Andric         if (!C)
157481ad6265SDimitry Andric           C = ConstantExpr::getCast(BC->Opcode, ConstOps[0], BC->getType());
157581ad6265SDimitry Andric       } else if (Instruction::isBinaryOp(BC->Opcode)) {
157681ad6265SDimitry Andric         C = ConstantExpr::get(BC->Opcode, ConstOps[0], ConstOps[1], BC->Flags);
157781ad6265SDimitry Andric       } else {
157881ad6265SDimitry Andric         switch (BC->Opcode) {
1579*0fca6ea1SDimitry Andric         case BitcodeConstant::ConstantPtrAuthOpcode: {
1580*0fca6ea1SDimitry Andric           auto *Key = dyn_cast<ConstantInt>(ConstOps[1]);
1581*0fca6ea1SDimitry Andric           if (!Key)
1582*0fca6ea1SDimitry Andric             return error("ptrauth key operand must be ConstantInt");
1583*0fca6ea1SDimitry Andric 
1584*0fca6ea1SDimitry Andric           auto *Disc = dyn_cast<ConstantInt>(ConstOps[2]);
1585*0fca6ea1SDimitry Andric           if (!Disc)
1586*0fca6ea1SDimitry Andric             return error("ptrauth disc operand must be ConstantInt");
1587*0fca6ea1SDimitry Andric 
1588*0fca6ea1SDimitry Andric           C = ConstantPtrAuth::get(ConstOps[0], Key, Disc, ConstOps[3]);
1589*0fca6ea1SDimitry Andric           break;
1590*0fca6ea1SDimitry Andric         }
159181ad6265SDimitry Andric         case BitcodeConstant::NoCFIOpcode: {
159281ad6265SDimitry Andric           auto *GV = dyn_cast<GlobalValue>(ConstOps[0]);
159381ad6265SDimitry Andric           if (!GV)
159481ad6265SDimitry Andric             return error("no_cfi operand must be GlobalValue");
159581ad6265SDimitry Andric           C = NoCFIValue::get(GV);
159681ad6265SDimitry Andric           break;
159781ad6265SDimitry Andric         }
159881ad6265SDimitry Andric         case BitcodeConstant::DSOLocalEquivalentOpcode: {
159981ad6265SDimitry Andric           auto *GV = dyn_cast<GlobalValue>(ConstOps[0]);
160081ad6265SDimitry Andric           if (!GV)
160181ad6265SDimitry Andric             return error("dso_local operand must be GlobalValue");
160281ad6265SDimitry Andric           C = DSOLocalEquivalent::get(GV);
160381ad6265SDimitry Andric           break;
160481ad6265SDimitry Andric         }
160581ad6265SDimitry Andric         case BitcodeConstant::BlockAddressOpcode: {
160681ad6265SDimitry Andric           Function *Fn = dyn_cast<Function>(ConstOps[0]);
160781ad6265SDimitry Andric           if (!Fn)
160881ad6265SDimitry Andric             return error("blockaddress operand must be a function");
160981ad6265SDimitry Andric 
161081ad6265SDimitry Andric           // If the function is already parsed we can insert the block address
161181ad6265SDimitry Andric           // right away.
161281ad6265SDimitry Andric           BasicBlock *BB;
1613*0fca6ea1SDimitry Andric           unsigned BBID = BC->BlockAddressBB;
161481ad6265SDimitry Andric           if (!BBID)
161581ad6265SDimitry Andric             // Invalid reference to entry block.
161681ad6265SDimitry Andric             return error("Invalid ID");
161781ad6265SDimitry Andric           if (!Fn->empty()) {
161881ad6265SDimitry Andric             Function::iterator BBI = Fn->begin(), BBE = Fn->end();
161981ad6265SDimitry Andric             for (size_t I = 0, E = BBID; I != E; ++I) {
162081ad6265SDimitry Andric               if (BBI == BBE)
162181ad6265SDimitry Andric                 return error("Invalid ID");
162281ad6265SDimitry Andric               ++BBI;
162381ad6265SDimitry Andric             }
162481ad6265SDimitry Andric             BB = &*BBI;
162581ad6265SDimitry Andric           } else {
162681ad6265SDimitry Andric             // Otherwise insert a placeholder and remember it so it can be
162781ad6265SDimitry Andric             // inserted when the function is parsed.
162881ad6265SDimitry Andric             auto &FwdBBs = BasicBlockFwdRefs[Fn];
162981ad6265SDimitry Andric             if (FwdBBs.empty())
163081ad6265SDimitry Andric               BasicBlockFwdRefQueue.push_back(Fn);
163181ad6265SDimitry Andric             if (FwdBBs.size() < BBID + 1)
163281ad6265SDimitry Andric               FwdBBs.resize(BBID + 1);
163381ad6265SDimitry Andric             if (!FwdBBs[BBID])
163481ad6265SDimitry Andric               FwdBBs[BBID] = BasicBlock::Create(Context);
163581ad6265SDimitry Andric             BB = FwdBBs[BBID];
163681ad6265SDimitry Andric           }
163781ad6265SDimitry Andric           C = BlockAddress::get(Fn, BB);
163881ad6265SDimitry Andric           break;
163981ad6265SDimitry Andric         }
164081ad6265SDimitry Andric         case BitcodeConstant::ConstantStructOpcode:
164181ad6265SDimitry Andric           C = ConstantStruct::get(cast<StructType>(BC->getType()), ConstOps);
164281ad6265SDimitry Andric           break;
164381ad6265SDimitry Andric         case BitcodeConstant::ConstantArrayOpcode:
164481ad6265SDimitry Andric           C = ConstantArray::get(cast<ArrayType>(BC->getType()), ConstOps);
164581ad6265SDimitry Andric           break;
164681ad6265SDimitry Andric         case BitcodeConstant::ConstantVectorOpcode:
164781ad6265SDimitry Andric           C = ConstantVector::get(ConstOps);
164881ad6265SDimitry Andric           break;
164981ad6265SDimitry Andric         case Instruction::GetElementPtr:
1650*0fca6ea1SDimitry Andric           C = ConstantExpr::getGetElementPtr(
1651*0fca6ea1SDimitry Andric               BC->SrcElemTy, ConstOps[0], ArrayRef(ConstOps).drop_front(),
1652*0fca6ea1SDimitry Andric               toGEPNoWrapFlags(BC->Flags), BC->getInRange());
165381ad6265SDimitry Andric           break;
165481ad6265SDimitry Andric         case Instruction::ExtractElement:
165581ad6265SDimitry Andric           C = ConstantExpr::getExtractElement(ConstOps[0], ConstOps[1]);
165681ad6265SDimitry Andric           break;
165781ad6265SDimitry Andric         case Instruction::InsertElement:
165881ad6265SDimitry Andric           C = ConstantExpr::getInsertElement(ConstOps[0], ConstOps[1],
165981ad6265SDimitry Andric                                              ConstOps[2]);
166081ad6265SDimitry Andric           break;
166181ad6265SDimitry Andric         case Instruction::ShuffleVector: {
166281ad6265SDimitry Andric           SmallVector<int, 16> Mask;
166381ad6265SDimitry Andric           ShuffleVectorInst::getShuffleMask(ConstOps[2], Mask);
166481ad6265SDimitry Andric           C = ConstantExpr::getShuffleVector(ConstOps[0], ConstOps[1], Mask);
166581ad6265SDimitry Andric           break;
166681ad6265SDimitry Andric         }
166781ad6265SDimitry Andric         default:
166881ad6265SDimitry Andric           llvm_unreachable("Unhandled bitcode constant");
166981ad6265SDimitry Andric         }
167081ad6265SDimitry Andric       }
167181ad6265SDimitry Andric 
167281ad6265SDimitry Andric       // Cache resolved constant.
167381ad6265SDimitry Andric       ValueList.replaceValueWithoutRAUW(ValID, C);
167481ad6265SDimitry Andric       MaterializedValues.insert({ValID, C});
167581ad6265SDimitry Andric       Worklist.pop_back();
167681ad6265SDimitry Andric       continue;
167781ad6265SDimitry Andric     }
167881ad6265SDimitry Andric 
167981ad6265SDimitry Andric     if (!InsertBB)
168081ad6265SDimitry Andric       return error(Twine("Value referenced by initializer is an unsupported "
168181ad6265SDimitry Andric                          "constant expression of type ") +
168281ad6265SDimitry Andric                    BC->getOpcodeName());
168381ad6265SDimitry Andric 
168481ad6265SDimitry Andric     // Materialize as instructions if necessary.
168581ad6265SDimitry Andric     Instruction *I;
168681ad6265SDimitry Andric     if (Instruction::isCast(BC->Opcode)) {
168781ad6265SDimitry Andric       I = CastInst::Create((Instruction::CastOps)BC->Opcode, Ops[0],
168881ad6265SDimitry Andric                            BC->getType(), "constexpr", InsertBB);
168981ad6265SDimitry Andric     } else if (Instruction::isUnaryOp(BC->Opcode)) {
169081ad6265SDimitry Andric       I = UnaryOperator::Create((Instruction::UnaryOps)BC->Opcode, Ops[0],
169181ad6265SDimitry Andric                                 "constexpr", InsertBB);
169281ad6265SDimitry Andric     } else if (Instruction::isBinaryOp(BC->Opcode)) {
169381ad6265SDimitry Andric       I = BinaryOperator::Create((Instruction::BinaryOps)BC->Opcode, Ops[0],
169481ad6265SDimitry Andric                                  Ops[1], "constexpr", InsertBB);
169581ad6265SDimitry Andric       if (isa<OverflowingBinaryOperator>(I)) {
169681ad6265SDimitry Andric         if (BC->Flags & OverflowingBinaryOperator::NoSignedWrap)
169781ad6265SDimitry Andric           I->setHasNoSignedWrap();
169881ad6265SDimitry Andric         if (BC->Flags & OverflowingBinaryOperator::NoUnsignedWrap)
169981ad6265SDimitry Andric           I->setHasNoUnsignedWrap();
170081ad6265SDimitry Andric       }
170181ad6265SDimitry Andric       if (isa<PossiblyExactOperator>(I) &&
170281ad6265SDimitry Andric           (BC->Flags & PossiblyExactOperator::IsExact))
170381ad6265SDimitry Andric         I->setIsExact();
170481ad6265SDimitry Andric     } else {
170581ad6265SDimitry Andric       switch (BC->Opcode) {
170681ad6265SDimitry Andric       case BitcodeConstant::ConstantVectorOpcode: {
170781ad6265SDimitry Andric         Type *IdxTy = Type::getInt32Ty(BC->getContext());
170881ad6265SDimitry Andric         Value *V = PoisonValue::get(BC->getType());
170981ad6265SDimitry Andric         for (auto Pair : enumerate(Ops)) {
171081ad6265SDimitry Andric           Value *Idx = ConstantInt::get(IdxTy, Pair.index());
171181ad6265SDimitry Andric           V = InsertElementInst::Create(V, Pair.value(), Idx, "constexpr.ins",
171281ad6265SDimitry Andric                                         InsertBB);
171381ad6265SDimitry Andric         }
171481ad6265SDimitry Andric         I = cast<Instruction>(V);
171581ad6265SDimitry Andric         break;
171681ad6265SDimitry Andric       }
1717bdd1243dSDimitry Andric       case BitcodeConstant::ConstantStructOpcode:
1718bdd1243dSDimitry Andric       case BitcodeConstant::ConstantArrayOpcode: {
1719bdd1243dSDimitry Andric         Value *V = PoisonValue::get(BC->getType());
1720bdd1243dSDimitry Andric         for (auto Pair : enumerate(Ops))
1721bdd1243dSDimitry Andric           V = InsertValueInst::Create(V, Pair.value(), Pair.index(),
1722bdd1243dSDimitry Andric                                       "constexpr.ins", InsertBB);
1723bdd1243dSDimitry Andric         I = cast<Instruction>(V);
1724bdd1243dSDimitry Andric         break;
1725bdd1243dSDimitry Andric       }
172681ad6265SDimitry Andric       case Instruction::ICmp:
172781ad6265SDimitry Andric       case Instruction::FCmp:
172881ad6265SDimitry Andric         I = CmpInst::Create((Instruction::OtherOps)BC->Opcode,
172981ad6265SDimitry Andric                             (CmpInst::Predicate)BC->Flags, Ops[0], Ops[1],
173081ad6265SDimitry Andric                             "constexpr", InsertBB);
173181ad6265SDimitry Andric         break;
173281ad6265SDimitry Andric       case Instruction::GetElementPtr:
173381ad6265SDimitry Andric         I = GetElementPtrInst::Create(BC->SrcElemTy, Ops[0],
1734bdd1243dSDimitry Andric                                       ArrayRef(Ops).drop_front(), "constexpr",
1735bdd1243dSDimitry Andric                                       InsertBB);
1736*0fca6ea1SDimitry Andric         cast<GetElementPtrInst>(I)->setNoWrapFlags(toGEPNoWrapFlags(BC->Flags));
173781ad6265SDimitry Andric         break;
173881ad6265SDimitry Andric       case Instruction::Select:
173981ad6265SDimitry Andric         I = SelectInst::Create(Ops[0], Ops[1], Ops[2], "constexpr", InsertBB);
174081ad6265SDimitry Andric         break;
174181ad6265SDimitry Andric       case Instruction::ExtractElement:
174281ad6265SDimitry Andric         I = ExtractElementInst::Create(Ops[0], Ops[1], "constexpr", InsertBB);
174381ad6265SDimitry Andric         break;
174481ad6265SDimitry Andric       case Instruction::InsertElement:
174581ad6265SDimitry Andric         I = InsertElementInst::Create(Ops[0], Ops[1], Ops[2], "constexpr",
174681ad6265SDimitry Andric                                       InsertBB);
174781ad6265SDimitry Andric         break;
174881ad6265SDimitry Andric       case Instruction::ShuffleVector:
174981ad6265SDimitry Andric         I = new ShuffleVectorInst(Ops[0], Ops[1], Ops[2], "constexpr",
175081ad6265SDimitry Andric                                   InsertBB);
175181ad6265SDimitry Andric         break;
175281ad6265SDimitry Andric       default:
175381ad6265SDimitry Andric         llvm_unreachable("Unhandled bitcode constant");
175481ad6265SDimitry Andric       }
175581ad6265SDimitry Andric     }
175681ad6265SDimitry Andric 
175781ad6265SDimitry Andric     MaterializedValues.insert({ValID, I});
175881ad6265SDimitry Andric     Worklist.pop_back();
175981ad6265SDimitry Andric   }
176081ad6265SDimitry Andric 
176181ad6265SDimitry Andric   return MaterializedValues[StartValID];
176281ad6265SDimitry Andric }
176381ad6265SDimitry Andric 
176481ad6265SDimitry Andric Expected<Constant *> BitcodeReader::getValueForInitializer(unsigned ID) {
176581ad6265SDimitry Andric   Expected<Value *> MaybeV = materializeValue(ID, /* InsertBB */ nullptr);
176681ad6265SDimitry Andric   if (!MaybeV)
176781ad6265SDimitry Andric     return MaybeV.takeError();
176881ad6265SDimitry Andric 
176981ad6265SDimitry Andric   // Result must be Constant if InsertBB is nullptr.
177081ad6265SDimitry Andric   return cast<Constant>(MaybeV.get());
177181ad6265SDimitry Andric }
177281ad6265SDimitry Andric 
17730b57cec5SDimitry Andric StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
17740b57cec5SDimitry Andric                                                       StringRef Name) {
17750b57cec5SDimitry Andric   auto *Ret = StructType::create(Context, Name);
17760b57cec5SDimitry Andric   IdentifiedStructTypes.push_back(Ret);
17770b57cec5SDimitry Andric   return Ret;
17780b57cec5SDimitry Andric }
17790b57cec5SDimitry Andric 
17800b57cec5SDimitry Andric StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
17810b57cec5SDimitry Andric   auto *Ret = StructType::create(Context);
17820b57cec5SDimitry Andric   IdentifiedStructTypes.push_back(Ret);
17830b57cec5SDimitry Andric   return Ret;
17840b57cec5SDimitry Andric }
17850b57cec5SDimitry Andric 
17860b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
17870b57cec5SDimitry Andric //  Functions for parsing blocks from the bitcode file
17880b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
17890b57cec5SDimitry Andric 
17900b57cec5SDimitry Andric static uint64_t getRawAttributeMask(Attribute::AttrKind Val) {
17910b57cec5SDimitry Andric   switch (Val) {
17920b57cec5SDimitry Andric   case Attribute::EndAttrKinds:
17935ffd83dbSDimitry Andric   case Attribute::EmptyKey:
17945ffd83dbSDimitry Andric   case Attribute::TombstoneKey:
17950b57cec5SDimitry Andric     llvm_unreachable("Synthetic enumerators which should never get here");
17960b57cec5SDimitry Andric 
17970b57cec5SDimitry Andric   case Attribute::None:            return 0;
17980b57cec5SDimitry Andric   case Attribute::ZExt:            return 1 << 0;
17990b57cec5SDimitry Andric   case Attribute::SExt:            return 1 << 1;
18000b57cec5SDimitry Andric   case Attribute::NoReturn:        return 1 << 2;
18010b57cec5SDimitry Andric   case Attribute::InReg:           return 1 << 3;
18020b57cec5SDimitry Andric   case Attribute::StructRet:       return 1 << 4;
18030b57cec5SDimitry Andric   case Attribute::NoUnwind:        return 1 << 5;
18040b57cec5SDimitry Andric   case Attribute::NoAlias:         return 1 << 6;
18050b57cec5SDimitry Andric   case Attribute::ByVal:           return 1 << 7;
18060b57cec5SDimitry Andric   case Attribute::Nest:            return 1 << 8;
18070b57cec5SDimitry Andric   case Attribute::ReadNone:        return 1 << 9;
18080b57cec5SDimitry Andric   case Attribute::ReadOnly:        return 1 << 10;
18090b57cec5SDimitry Andric   case Attribute::NoInline:        return 1 << 11;
18100b57cec5SDimitry Andric   case Attribute::AlwaysInline:    return 1 << 12;
18110b57cec5SDimitry Andric   case Attribute::OptimizeForSize: return 1 << 13;
18120b57cec5SDimitry Andric   case Attribute::StackProtect:    return 1 << 14;
18130b57cec5SDimitry Andric   case Attribute::StackProtectReq: return 1 << 15;
18140b57cec5SDimitry Andric   case Attribute::Alignment:       return 31 << 16;
18150b57cec5SDimitry Andric   case Attribute::NoCapture:       return 1 << 21;
18160b57cec5SDimitry Andric   case Attribute::NoRedZone:       return 1 << 22;
18170b57cec5SDimitry Andric   case Attribute::NoImplicitFloat: return 1 << 23;
18180b57cec5SDimitry Andric   case Attribute::Naked:           return 1 << 24;
18190b57cec5SDimitry Andric   case Attribute::InlineHint:      return 1 << 25;
18200b57cec5SDimitry Andric   case Attribute::StackAlignment:  return 7 << 26;
18210b57cec5SDimitry Andric   case Attribute::ReturnsTwice:    return 1 << 29;
18220b57cec5SDimitry Andric   case Attribute::UWTable:         return 1 << 30;
18230b57cec5SDimitry Andric   case Attribute::NonLazyBind:     return 1U << 31;
18240b57cec5SDimitry Andric   case Attribute::SanitizeAddress: return 1ULL << 32;
18250b57cec5SDimitry Andric   case Attribute::MinSize:         return 1ULL << 33;
18260b57cec5SDimitry Andric   case Attribute::NoDuplicate:     return 1ULL << 34;
18270b57cec5SDimitry Andric   case Attribute::StackProtectStrong: return 1ULL << 35;
18280b57cec5SDimitry Andric   case Attribute::SanitizeThread:  return 1ULL << 36;
18290b57cec5SDimitry Andric   case Attribute::SanitizeMemory:  return 1ULL << 37;
18300b57cec5SDimitry Andric   case Attribute::NoBuiltin:       return 1ULL << 38;
18310b57cec5SDimitry Andric   case Attribute::Returned:        return 1ULL << 39;
18320b57cec5SDimitry Andric   case Attribute::Cold:            return 1ULL << 40;
18330b57cec5SDimitry Andric   case Attribute::Builtin:         return 1ULL << 41;
18340b57cec5SDimitry Andric   case Attribute::OptimizeNone:    return 1ULL << 42;
18350b57cec5SDimitry Andric   case Attribute::InAlloca:        return 1ULL << 43;
18360b57cec5SDimitry Andric   case Attribute::NonNull:         return 1ULL << 44;
18370b57cec5SDimitry Andric   case Attribute::JumpTable:       return 1ULL << 45;
18380b57cec5SDimitry Andric   case Attribute::Convergent:      return 1ULL << 46;
18390b57cec5SDimitry Andric   case Attribute::SafeStack:       return 1ULL << 47;
18400b57cec5SDimitry Andric   case Attribute::NoRecurse:       return 1ULL << 48;
1841bdd1243dSDimitry Andric   // 1ULL << 49 is InaccessibleMemOnly, which is upgraded separately.
1842bdd1243dSDimitry Andric   // 1ULL << 50 is InaccessibleMemOrArgMemOnly, which is upgraded separately.
18430b57cec5SDimitry Andric   case Attribute::SwiftSelf:       return 1ULL << 51;
18440b57cec5SDimitry Andric   case Attribute::SwiftError:      return 1ULL << 52;
18450b57cec5SDimitry Andric   case Attribute::WriteOnly:       return 1ULL << 53;
18460b57cec5SDimitry Andric   case Attribute::Speculatable:    return 1ULL << 54;
18470b57cec5SDimitry Andric   case Attribute::StrictFP:        return 1ULL << 55;
18480b57cec5SDimitry Andric   case Attribute::SanitizeHWAddress: return 1ULL << 56;
18490b57cec5SDimitry Andric   case Attribute::NoCfCheck:       return 1ULL << 57;
18500b57cec5SDimitry Andric   case Attribute::OptForFuzzing:   return 1ULL << 58;
18510b57cec5SDimitry Andric   case Attribute::ShadowCallStack: return 1ULL << 59;
18520b57cec5SDimitry Andric   case Attribute::SpeculativeLoadHardening:
18530b57cec5SDimitry Andric     return 1ULL << 60;
18540b57cec5SDimitry Andric   case Attribute::ImmArg:
18550b57cec5SDimitry Andric     return 1ULL << 61;
18560b57cec5SDimitry Andric   case Attribute::WillReturn:
18570b57cec5SDimitry Andric     return 1ULL << 62;
18580b57cec5SDimitry Andric   case Attribute::NoFree:
18590b57cec5SDimitry Andric     return 1ULL << 63;
18605ffd83dbSDimitry Andric   default:
18615ffd83dbSDimitry Andric     // Other attributes are not supported in the raw format,
18625ffd83dbSDimitry Andric     // as we ran out of space.
18635ffd83dbSDimitry Andric     return 0;
18640b57cec5SDimitry Andric   }
18650b57cec5SDimitry Andric   llvm_unreachable("Unsupported attribute type");
18660b57cec5SDimitry Andric }
18670b57cec5SDimitry Andric 
18680b57cec5SDimitry Andric static void addRawAttributeValue(AttrBuilder &B, uint64_t Val) {
18690b57cec5SDimitry Andric   if (!Val) return;
18700b57cec5SDimitry Andric 
18710b57cec5SDimitry Andric   for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
18720b57cec5SDimitry Andric        I = Attribute::AttrKind(I + 1)) {
18730b57cec5SDimitry Andric     if (uint64_t A = (Val & getRawAttributeMask(I))) {
18740b57cec5SDimitry Andric       if (I == Attribute::Alignment)
18750b57cec5SDimitry Andric         B.addAlignmentAttr(1ULL << ((A >> 16) - 1));
18760b57cec5SDimitry Andric       else if (I == Attribute::StackAlignment)
18770b57cec5SDimitry Andric         B.addStackAlignmentAttr(1ULL << ((A >> 26)-1));
1878fe6060f1SDimitry Andric       else if (Attribute::isTypeAttrKind(I))
1879fe6060f1SDimitry Andric         B.addTypeAttr(I, nullptr); // Type will be auto-upgraded.
18800b57cec5SDimitry Andric       else
18810b57cec5SDimitry Andric         B.addAttribute(I);
18820b57cec5SDimitry Andric     }
18830b57cec5SDimitry Andric   }
18840b57cec5SDimitry Andric }
18850b57cec5SDimitry Andric 
18860b57cec5SDimitry Andric /// This fills an AttrBuilder object with the LLVM attributes that have
18870b57cec5SDimitry Andric /// been decoded from the given integer. This function must stay in sync with
18880b57cec5SDimitry Andric /// 'encodeLLVMAttributesForBitcode'.
18890b57cec5SDimitry Andric static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1890bdd1243dSDimitry Andric                                            uint64_t EncodedAttrs,
1891bdd1243dSDimitry Andric                                            uint64_t AttrIdx) {
18920b57cec5SDimitry Andric   // The alignment is stored as a 16-bit raw value from bits 31--16.  We shift
18930b57cec5SDimitry Andric   // the bits above 31 down by 11 bits.
18940b57cec5SDimitry Andric   unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
18950b57cec5SDimitry Andric   assert((!Alignment || isPowerOf2_32(Alignment)) &&
18960b57cec5SDimitry Andric          "Alignment must be a power of two.");
18970b57cec5SDimitry Andric 
18980b57cec5SDimitry Andric   if (Alignment)
18990b57cec5SDimitry Andric     B.addAlignmentAttr(Alignment);
1900bdd1243dSDimitry Andric 
1901bdd1243dSDimitry Andric   uint64_t Attrs = ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1902bdd1243dSDimitry Andric                    (EncodedAttrs & 0xffff);
1903bdd1243dSDimitry Andric 
1904bdd1243dSDimitry Andric   if (AttrIdx == AttributeList::FunctionIndex) {
1905bdd1243dSDimitry Andric     // Upgrade old memory attributes.
1906bdd1243dSDimitry Andric     MemoryEffects ME = MemoryEffects::unknown();
1907bdd1243dSDimitry Andric     if (Attrs & (1ULL << 9)) {
1908bdd1243dSDimitry Andric       // ReadNone
1909bdd1243dSDimitry Andric       Attrs &= ~(1ULL << 9);
1910bdd1243dSDimitry Andric       ME &= MemoryEffects::none();
1911bdd1243dSDimitry Andric     }
1912bdd1243dSDimitry Andric     if (Attrs & (1ULL << 10)) {
1913bdd1243dSDimitry Andric       // ReadOnly
1914bdd1243dSDimitry Andric       Attrs &= ~(1ULL << 10);
1915bdd1243dSDimitry Andric       ME &= MemoryEffects::readOnly();
1916bdd1243dSDimitry Andric     }
1917bdd1243dSDimitry Andric     if (Attrs & (1ULL << 49)) {
1918bdd1243dSDimitry Andric       // InaccessibleMemOnly
1919bdd1243dSDimitry Andric       Attrs &= ~(1ULL << 49);
1920bdd1243dSDimitry Andric       ME &= MemoryEffects::inaccessibleMemOnly();
1921bdd1243dSDimitry Andric     }
1922bdd1243dSDimitry Andric     if (Attrs & (1ULL << 50)) {
1923bdd1243dSDimitry Andric       // InaccessibleMemOrArgMemOnly
1924bdd1243dSDimitry Andric       Attrs &= ~(1ULL << 50);
1925bdd1243dSDimitry Andric       ME &= MemoryEffects::inaccessibleOrArgMemOnly();
1926bdd1243dSDimitry Andric     }
1927bdd1243dSDimitry Andric     if (Attrs & (1ULL << 53)) {
1928bdd1243dSDimitry Andric       // WriteOnly
1929bdd1243dSDimitry Andric       Attrs &= ~(1ULL << 53);
1930bdd1243dSDimitry Andric       ME &= MemoryEffects::writeOnly();
1931bdd1243dSDimitry Andric     }
1932bdd1243dSDimitry Andric     if (ME != MemoryEffects::unknown())
1933bdd1243dSDimitry Andric       B.addMemoryAttr(ME);
1934bdd1243dSDimitry Andric   }
1935bdd1243dSDimitry Andric 
1936bdd1243dSDimitry Andric   addRawAttributeValue(B, Attrs);
19370b57cec5SDimitry Andric }
19380b57cec5SDimitry Andric 
19390b57cec5SDimitry Andric Error BitcodeReader::parseAttributeBlock() {
19400b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
19410b57cec5SDimitry Andric     return Err;
19420b57cec5SDimitry Andric 
19430b57cec5SDimitry Andric   if (!MAttributes.empty())
19440b57cec5SDimitry Andric     return error("Invalid multiple blocks");
19450b57cec5SDimitry Andric 
19460b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
19470b57cec5SDimitry Andric 
19480b57cec5SDimitry Andric   SmallVector<AttributeList, 8> Attrs;
19490b57cec5SDimitry Andric 
19500b57cec5SDimitry Andric   // Read all the records.
19510b57cec5SDimitry Andric   while (true) {
19520b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
19530b57cec5SDimitry Andric     if (!MaybeEntry)
19540b57cec5SDimitry Andric       return MaybeEntry.takeError();
19550b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
19560b57cec5SDimitry Andric 
19570b57cec5SDimitry Andric     switch (Entry.Kind) {
19580b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
19590b57cec5SDimitry Andric     case BitstreamEntry::Error:
19600b57cec5SDimitry Andric       return error("Malformed block");
19610b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
19620b57cec5SDimitry Andric       return Error::success();
19630b57cec5SDimitry Andric     case BitstreamEntry::Record:
19640b57cec5SDimitry Andric       // The interesting case.
19650b57cec5SDimitry Andric       break;
19660b57cec5SDimitry Andric     }
19670b57cec5SDimitry Andric 
19680b57cec5SDimitry Andric     // Read a record.
19690b57cec5SDimitry Andric     Record.clear();
19700b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
19710b57cec5SDimitry Andric     if (!MaybeRecord)
19720b57cec5SDimitry Andric       return MaybeRecord.takeError();
19730b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
19740b57cec5SDimitry Andric     default:  // Default behavior: ignore.
19750b57cec5SDimitry Andric       break;
19760b57cec5SDimitry Andric     case bitc::PARAMATTR_CODE_ENTRY_OLD: // ENTRY: [paramidx0, attr0, ...]
19775ffd83dbSDimitry Andric       // Deprecated, but still needed to read old bitcode files.
19780b57cec5SDimitry Andric       if (Record.size() & 1)
197981ad6265SDimitry Andric         return error("Invalid parameter attribute record");
19800b57cec5SDimitry Andric 
19810b57cec5SDimitry Andric       for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
198204eeddc0SDimitry Andric         AttrBuilder B(Context);
1983bdd1243dSDimitry Andric         decodeLLVMAttributesForBitcode(B, Record[i+1], Record[i]);
19840b57cec5SDimitry Andric         Attrs.push_back(AttributeList::get(Context, Record[i], B));
19850b57cec5SDimitry Andric       }
19860b57cec5SDimitry Andric 
19870b57cec5SDimitry Andric       MAttributes.push_back(AttributeList::get(Context, Attrs));
19880b57cec5SDimitry Andric       Attrs.clear();
19890b57cec5SDimitry Andric       break;
19900b57cec5SDimitry Andric     case bitc::PARAMATTR_CODE_ENTRY: // ENTRY: [attrgrp0, attrgrp1, ...]
1991*0fca6ea1SDimitry Andric       for (uint64_t Val : Record)
1992*0fca6ea1SDimitry Andric         Attrs.push_back(MAttributeGroups[Val]);
19930b57cec5SDimitry Andric 
19940b57cec5SDimitry Andric       MAttributes.push_back(AttributeList::get(Context, Attrs));
19950b57cec5SDimitry Andric       Attrs.clear();
19960b57cec5SDimitry Andric       break;
19970b57cec5SDimitry Andric     }
19980b57cec5SDimitry Andric   }
19990b57cec5SDimitry Andric }
20000b57cec5SDimitry Andric 
20010b57cec5SDimitry Andric // Returns Attribute::None on unrecognized codes.
20020b57cec5SDimitry Andric static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
20030b57cec5SDimitry Andric   switch (Code) {
20040b57cec5SDimitry Andric   default:
20050b57cec5SDimitry Andric     return Attribute::None;
20060b57cec5SDimitry Andric   case bitc::ATTR_KIND_ALIGNMENT:
20070b57cec5SDimitry Andric     return Attribute::Alignment;
20080b57cec5SDimitry Andric   case bitc::ATTR_KIND_ALWAYS_INLINE:
20090b57cec5SDimitry Andric     return Attribute::AlwaysInline;
20100b57cec5SDimitry Andric   case bitc::ATTR_KIND_BUILTIN:
20110b57cec5SDimitry Andric     return Attribute::Builtin;
20120b57cec5SDimitry Andric   case bitc::ATTR_KIND_BY_VAL:
20130b57cec5SDimitry Andric     return Attribute::ByVal;
20140b57cec5SDimitry Andric   case bitc::ATTR_KIND_IN_ALLOCA:
20150b57cec5SDimitry Andric     return Attribute::InAlloca;
20160b57cec5SDimitry Andric   case bitc::ATTR_KIND_COLD:
20170b57cec5SDimitry Andric     return Attribute::Cold;
20180b57cec5SDimitry Andric   case bitc::ATTR_KIND_CONVERGENT:
20190b57cec5SDimitry Andric     return Attribute::Convergent;
2020349cc55cSDimitry Andric   case bitc::ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION:
2021349cc55cSDimitry Andric     return Attribute::DisableSanitizerInstrumentation;
2022fe6060f1SDimitry Andric   case bitc::ATTR_KIND_ELEMENTTYPE:
2023fe6060f1SDimitry Andric     return Attribute::ElementType;
2024753f127fSDimitry Andric   case bitc::ATTR_KIND_FNRETTHUNK_EXTERN:
2025753f127fSDimitry Andric     return Attribute::FnRetThunkExtern;
20260b57cec5SDimitry Andric   case bitc::ATTR_KIND_INLINE_HINT:
20270b57cec5SDimitry Andric     return Attribute::InlineHint;
20280b57cec5SDimitry Andric   case bitc::ATTR_KIND_IN_REG:
20290b57cec5SDimitry Andric     return Attribute::InReg;
20300b57cec5SDimitry Andric   case bitc::ATTR_KIND_JUMP_TABLE:
20310b57cec5SDimitry Andric     return Attribute::JumpTable;
2032bdd1243dSDimitry Andric   case bitc::ATTR_KIND_MEMORY:
2033bdd1243dSDimitry Andric     return Attribute::Memory;
203406c3fb27SDimitry Andric   case bitc::ATTR_KIND_NOFPCLASS:
203506c3fb27SDimitry Andric     return Attribute::NoFPClass;
20360b57cec5SDimitry Andric   case bitc::ATTR_KIND_MIN_SIZE:
20370b57cec5SDimitry Andric     return Attribute::MinSize;
20380b57cec5SDimitry Andric   case bitc::ATTR_KIND_NAKED:
20390b57cec5SDimitry Andric     return Attribute::Naked;
20400b57cec5SDimitry Andric   case bitc::ATTR_KIND_NEST:
20410b57cec5SDimitry Andric     return Attribute::Nest;
20420b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_ALIAS:
20430b57cec5SDimitry Andric     return Attribute::NoAlias;
20440b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_BUILTIN:
20450b57cec5SDimitry Andric     return Attribute::NoBuiltin;
2046e8d8bef9SDimitry Andric   case bitc::ATTR_KIND_NO_CALLBACK:
2047e8d8bef9SDimitry Andric     return Attribute::NoCallback;
20480b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_CAPTURE:
20490b57cec5SDimitry Andric     return Attribute::NoCapture;
20500b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_DUPLICATE:
20510b57cec5SDimitry Andric     return Attribute::NoDuplicate;
20520b57cec5SDimitry Andric   case bitc::ATTR_KIND_NOFREE:
20530b57cec5SDimitry Andric     return Attribute::NoFree;
20540b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
20550b57cec5SDimitry Andric     return Attribute::NoImplicitFloat;
20560b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_INLINE:
20570b57cec5SDimitry Andric     return Attribute::NoInline;
20580b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_RECURSE:
20590b57cec5SDimitry Andric     return Attribute::NoRecurse;
20605ffd83dbSDimitry Andric   case bitc::ATTR_KIND_NO_MERGE:
20615ffd83dbSDimitry Andric     return Attribute::NoMerge;
20620b57cec5SDimitry Andric   case bitc::ATTR_KIND_NON_LAZY_BIND:
20630b57cec5SDimitry Andric     return Attribute::NonLazyBind;
20640b57cec5SDimitry Andric   case bitc::ATTR_KIND_NON_NULL:
20650b57cec5SDimitry Andric     return Attribute::NonNull;
20660b57cec5SDimitry Andric   case bitc::ATTR_KIND_DEREFERENCEABLE:
20670b57cec5SDimitry Andric     return Attribute::Dereferenceable;
20680b57cec5SDimitry Andric   case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
20690b57cec5SDimitry Andric     return Attribute::DereferenceableOrNull;
207081ad6265SDimitry Andric   case bitc::ATTR_KIND_ALLOC_ALIGN:
207181ad6265SDimitry Andric     return Attribute::AllocAlign;
207281ad6265SDimitry Andric   case bitc::ATTR_KIND_ALLOC_KIND:
207381ad6265SDimitry Andric     return Attribute::AllocKind;
20740b57cec5SDimitry Andric   case bitc::ATTR_KIND_ALLOC_SIZE:
20750b57cec5SDimitry Andric     return Attribute::AllocSize;
207681ad6265SDimitry Andric   case bitc::ATTR_KIND_ALLOCATED_POINTER:
207781ad6265SDimitry Andric     return Attribute::AllocatedPointer;
20780b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_RED_ZONE:
20790b57cec5SDimitry Andric     return Attribute::NoRedZone;
20800b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_RETURN:
20810b57cec5SDimitry Andric     return Attribute::NoReturn;
20820b57cec5SDimitry Andric   case bitc::ATTR_KIND_NOSYNC:
20830b57cec5SDimitry Andric     return Attribute::NoSync;
20840b57cec5SDimitry Andric   case bitc::ATTR_KIND_NOCF_CHECK:
20850b57cec5SDimitry Andric     return Attribute::NoCfCheck;
2086fe6060f1SDimitry Andric   case bitc::ATTR_KIND_NO_PROFILE:
2087fe6060f1SDimitry Andric     return Attribute::NoProfile;
2088bdd1243dSDimitry Andric   case bitc::ATTR_KIND_SKIP_PROFILE:
2089bdd1243dSDimitry Andric     return Attribute::SkipProfile;
20900b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_UNWIND:
20910b57cec5SDimitry Andric     return Attribute::NoUnwind;
209281ad6265SDimitry Andric   case bitc::ATTR_KIND_NO_SANITIZE_BOUNDS:
209381ad6265SDimitry Andric     return Attribute::NoSanitizeBounds;
2094fe6060f1SDimitry Andric   case bitc::ATTR_KIND_NO_SANITIZE_COVERAGE:
2095fe6060f1SDimitry Andric     return Attribute::NoSanitizeCoverage;
20965ffd83dbSDimitry Andric   case bitc::ATTR_KIND_NULL_POINTER_IS_VALID:
20975ffd83dbSDimitry Andric     return Attribute::NullPointerIsValid;
20985f757f3fSDimitry Andric   case bitc::ATTR_KIND_OPTIMIZE_FOR_DEBUGGING:
20995f757f3fSDimitry Andric     return Attribute::OptimizeForDebugging;
21000b57cec5SDimitry Andric   case bitc::ATTR_KIND_OPT_FOR_FUZZING:
21010b57cec5SDimitry Andric     return Attribute::OptForFuzzing;
21020b57cec5SDimitry Andric   case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
21030b57cec5SDimitry Andric     return Attribute::OptimizeForSize;
21040b57cec5SDimitry Andric   case bitc::ATTR_KIND_OPTIMIZE_NONE:
21050b57cec5SDimitry Andric     return Attribute::OptimizeNone;
21060b57cec5SDimitry Andric   case bitc::ATTR_KIND_READ_NONE:
21070b57cec5SDimitry Andric     return Attribute::ReadNone;
21080b57cec5SDimitry Andric   case bitc::ATTR_KIND_READ_ONLY:
21090b57cec5SDimitry Andric     return Attribute::ReadOnly;
21100b57cec5SDimitry Andric   case bitc::ATTR_KIND_RETURNED:
21110b57cec5SDimitry Andric     return Attribute::Returned;
21120b57cec5SDimitry Andric   case bitc::ATTR_KIND_RETURNS_TWICE:
21130b57cec5SDimitry Andric     return Attribute::ReturnsTwice;
21140b57cec5SDimitry Andric   case bitc::ATTR_KIND_S_EXT:
21150b57cec5SDimitry Andric     return Attribute::SExt;
21160b57cec5SDimitry Andric   case bitc::ATTR_KIND_SPECULATABLE:
21170b57cec5SDimitry Andric     return Attribute::Speculatable;
21180b57cec5SDimitry Andric   case bitc::ATTR_KIND_STACK_ALIGNMENT:
21190b57cec5SDimitry Andric     return Attribute::StackAlignment;
21200b57cec5SDimitry Andric   case bitc::ATTR_KIND_STACK_PROTECT:
21210b57cec5SDimitry Andric     return Attribute::StackProtect;
21220b57cec5SDimitry Andric   case bitc::ATTR_KIND_STACK_PROTECT_REQ:
21230b57cec5SDimitry Andric     return Attribute::StackProtectReq;
21240b57cec5SDimitry Andric   case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
21250b57cec5SDimitry Andric     return Attribute::StackProtectStrong;
21260b57cec5SDimitry Andric   case bitc::ATTR_KIND_SAFESTACK:
21270b57cec5SDimitry Andric     return Attribute::SafeStack;
21280b57cec5SDimitry Andric   case bitc::ATTR_KIND_SHADOWCALLSTACK:
21290b57cec5SDimitry Andric     return Attribute::ShadowCallStack;
21300b57cec5SDimitry Andric   case bitc::ATTR_KIND_STRICT_FP:
21310b57cec5SDimitry Andric     return Attribute::StrictFP;
21320b57cec5SDimitry Andric   case bitc::ATTR_KIND_STRUCT_RET:
21330b57cec5SDimitry Andric     return Attribute::StructRet;
21340b57cec5SDimitry Andric   case bitc::ATTR_KIND_SANITIZE_ADDRESS:
21350b57cec5SDimitry Andric     return Attribute::SanitizeAddress;
21360b57cec5SDimitry Andric   case bitc::ATTR_KIND_SANITIZE_HWADDRESS:
21370b57cec5SDimitry Andric     return Attribute::SanitizeHWAddress;
21380b57cec5SDimitry Andric   case bitc::ATTR_KIND_SANITIZE_THREAD:
21390b57cec5SDimitry Andric     return Attribute::SanitizeThread;
21400b57cec5SDimitry Andric   case bitc::ATTR_KIND_SANITIZE_MEMORY:
21410b57cec5SDimitry Andric     return Attribute::SanitizeMemory;
2142*0fca6ea1SDimitry Andric   case bitc::ATTR_KIND_SANITIZE_NUMERICAL_STABILITY:
2143*0fca6ea1SDimitry Andric     return Attribute::SanitizeNumericalStability;
21440b57cec5SDimitry Andric   case bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING:
21450b57cec5SDimitry Andric     return Attribute::SpeculativeLoadHardening;
21460b57cec5SDimitry Andric   case bitc::ATTR_KIND_SWIFT_ERROR:
21470b57cec5SDimitry Andric     return Attribute::SwiftError;
21480b57cec5SDimitry Andric   case bitc::ATTR_KIND_SWIFT_SELF:
21490b57cec5SDimitry Andric     return Attribute::SwiftSelf;
2150fe6060f1SDimitry Andric   case bitc::ATTR_KIND_SWIFT_ASYNC:
2151fe6060f1SDimitry Andric     return Attribute::SwiftAsync;
21520b57cec5SDimitry Andric   case bitc::ATTR_KIND_UW_TABLE:
21530b57cec5SDimitry Andric     return Attribute::UWTable;
2154fe6060f1SDimitry Andric   case bitc::ATTR_KIND_VSCALE_RANGE:
2155fe6060f1SDimitry Andric     return Attribute::VScaleRange;
21560b57cec5SDimitry Andric   case bitc::ATTR_KIND_WILLRETURN:
21570b57cec5SDimitry Andric     return Attribute::WillReturn;
21580b57cec5SDimitry Andric   case bitc::ATTR_KIND_WRITEONLY:
21590b57cec5SDimitry Andric     return Attribute::WriteOnly;
21600b57cec5SDimitry Andric   case bitc::ATTR_KIND_Z_EXT:
21610b57cec5SDimitry Andric     return Attribute::ZExt;
21620b57cec5SDimitry Andric   case bitc::ATTR_KIND_IMMARG:
21630b57cec5SDimitry Andric     return Attribute::ImmArg;
21640b57cec5SDimitry Andric   case bitc::ATTR_KIND_SANITIZE_MEMTAG:
21650b57cec5SDimitry Andric     return Attribute::SanitizeMemTag;
21665ffd83dbSDimitry Andric   case bitc::ATTR_KIND_PREALLOCATED:
21675ffd83dbSDimitry Andric     return Attribute::Preallocated;
21685ffd83dbSDimitry Andric   case bitc::ATTR_KIND_NOUNDEF:
21695ffd83dbSDimitry Andric     return Attribute::NoUndef;
2170e8d8bef9SDimitry Andric   case bitc::ATTR_KIND_BYREF:
2171e8d8bef9SDimitry Andric     return Attribute::ByRef;
2172e8d8bef9SDimitry Andric   case bitc::ATTR_KIND_MUSTPROGRESS:
2173e8d8bef9SDimitry Andric     return Attribute::MustProgress;
2174e8d8bef9SDimitry Andric   case bitc::ATTR_KIND_HOT:
2175e8d8bef9SDimitry Andric     return Attribute::Hot;
217681ad6265SDimitry Andric   case bitc::ATTR_KIND_PRESPLIT_COROUTINE:
217781ad6265SDimitry Andric     return Attribute::PresplitCoroutine;
21785f757f3fSDimitry Andric   case bitc::ATTR_KIND_WRITABLE:
21795f757f3fSDimitry Andric     return Attribute::Writable;
21805f757f3fSDimitry Andric   case bitc::ATTR_KIND_CORO_ONLY_DESTROY_WHEN_COMPLETE:
21815f757f3fSDimitry Andric     return Attribute::CoroDestroyOnlyWhenComplete;
21825f757f3fSDimitry Andric   case bitc::ATTR_KIND_DEAD_ON_UNWIND:
21835f757f3fSDimitry Andric     return Attribute::DeadOnUnwind;
2184*0fca6ea1SDimitry Andric   case bitc::ATTR_KIND_RANGE:
2185*0fca6ea1SDimitry Andric     return Attribute::Range;
2186*0fca6ea1SDimitry Andric   case bitc::ATTR_KIND_INITIALIZES:
2187*0fca6ea1SDimitry Andric     return Attribute::Initializes;
21880b57cec5SDimitry Andric   }
21890b57cec5SDimitry Andric }
21900b57cec5SDimitry Andric 
21910b57cec5SDimitry Andric Error BitcodeReader::parseAlignmentValue(uint64_t Exponent,
21928bcb0991SDimitry Andric                                          MaybeAlign &Alignment) {
21930b57cec5SDimitry Andric   // Note: Alignment in bitcode files is incremented by 1, so that zero
21940b57cec5SDimitry Andric   // can be used for default alignment.
21950b57cec5SDimitry Andric   if (Exponent > Value::MaxAlignmentExponent + 1)
21960b57cec5SDimitry Andric     return error("Invalid alignment value");
21978bcb0991SDimitry Andric   Alignment = decodeMaybeAlign(Exponent);
21980b57cec5SDimitry Andric   return Error::success();
21990b57cec5SDimitry Andric }
22000b57cec5SDimitry Andric 
22010b57cec5SDimitry Andric Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) {
22020b57cec5SDimitry Andric   *Kind = getAttrFromCode(Code);
22030b57cec5SDimitry Andric   if (*Kind == Attribute::None)
22040b57cec5SDimitry Andric     return error("Unknown attribute kind (" + Twine(Code) + ")");
22050b57cec5SDimitry Andric   return Error::success();
22060b57cec5SDimitry Andric }
22070b57cec5SDimitry Andric 
2208bdd1243dSDimitry Andric static bool upgradeOldMemoryAttribute(MemoryEffects &ME, uint64_t EncodedKind) {
2209bdd1243dSDimitry Andric   switch (EncodedKind) {
2210bdd1243dSDimitry Andric   case bitc::ATTR_KIND_READ_NONE:
2211bdd1243dSDimitry Andric     ME &= MemoryEffects::none();
2212bdd1243dSDimitry Andric     return true;
2213bdd1243dSDimitry Andric   case bitc::ATTR_KIND_READ_ONLY:
2214bdd1243dSDimitry Andric     ME &= MemoryEffects::readOnly();
2215bdd1243dSDimitry Andric     return true;
2216bdd1243dSDimitry Andric   case bitc::ATTR_KIND_WRITEONLY:
2217bdd1243dSDimitry Andric     ME &= MemoryEffects::writeOnly();
2218bdd1243dSDimitry Andric     return true;
2219bdd1243dSDimitry Andric   case bitc::ATTR_KIND_ARGMEMONLY:
2220bdd1243dSDimitry Andric     ME &= MemoryEffects::argMemOnly();
2221bdd1243dSDimitry Andric     return true;
2222bdd1243dSDimitry Andric   case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY:
2223bdd1243dSDimitry Andric     ME &= MemoryEffects::inaccessibleMemOnly();
2224bdd1243dSDimitry Andric     return true;
2225bdd1243dSDimitry Andric   case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY:
2226bdd1243dSDimitry Andric     ME &= MemoryEffects::inaccessibleOrArgMemOnly();
2227bdd1243dSDimitry Andric     return true;
2228bdd1243dSDimitry Andric   default:
2229bdd1243dSDimitry Andric     return false;
2230bdd1243dSDimitry Andric   }
2231bdd1243dSDimitry Andric }
2232bdd1243dSDimitry Andric 
22330b57cec5SDimitry Andric Error BitcodeReader::parseAttributeGroupBlock() {
22340b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
22350b57cec5SDimitry Andric     return Err;
22360b57cec5SDimitry Andric 
22370b57cec5SDimitry Andric   if (!MAttributeGroups.empty())
22380b57cec5SDimitry Andric     return error("Invalid multiple blocks");
22390b57cec5SDimitry Andric 
22400b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
22410b57cec5SDimitry Andric 
22420b57cec5SDimitry Andric   // Read all the records.
22430b57cec5SDimitry Andric   while (true) {
22440b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
22450b57cec5SDimitry Andric     if (!MaybeEntry)
22460b57cec5SDimitry Andric       return MaybeEntry.takeError();
22470b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
22480b57cec5SDimitry Andric 
22490b57cec5SDimitry Andric     switch (Entry.Kind) {
22500b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
22510b57cec5SDimitry Andric     case BitstreamEntry::Error:
22520b57cec5SDimitry Andric       return error("Malformed block");
22530b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
22540b57cec5SDimitry Andric       return Error::success();
22550b57cec5SDimitry Andric     case BitstreamEntry::Record:
22560b57cec5SDimitry Andric       // The interesting case.
22570b57cec5SDimitry Andric       break;
22580b57cec5SDimitry Andric     }
22590b57cec5SDimitry Andric 
22600b57cec5SDimitry Andric     // Read a record.
22610b57cec5SDimitry Andric     Record.clear();
22620b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
22630b57cec5SDimitry Andric     if (!MaybeRecord)
22640b57cec5SDimitry Andric       return MaybeRecord.takeError();
22650b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
22660b57cec5SDimitry Andric     default:  // Default behavior: ignore.
22670b57cec5SDimitry Andric       break;
22680b57cec5SDimitry Andric     case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
22690b57cec5SDimitry Andric       if (Record.size() < 3)
227081ad6265SDimitry Andric         return error("Invalid grp record");
22710b57cec5SDimitry Andric 
22720b57cec5SDimitry Andric       uint64_t GrpID = Record[0];
22730b57cec5SDimitry Andric       uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
22740b57cec5SDimitry Andric 
227504eeddc0SDimitry Andric       AttrBuilder B(Context);
2276bdd1243dSDimitry Andric       MemoryEffects ME = MemoryEffects::unknown();
22770b57cec5SDimitry Andric       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
22780b57cec5SDimitry Andric         if (Record[i] == 0) {        // Enum attribute
22790b57cec5SDimitry Andric           Attribute::AttrKind Kind;
2280bdd1243dSDimitry Andric           uint64_t EncodedKind = Record[++i];
2281bdd1243dSDimitry Andric           if (Idx == AttributeList::FunctionIndex &&
2282bdd1243dSDimitry Andric               upgradeOldMemoryAttribute(ME, EncodedKind))
2283bdd1243dSDimitry Andric             continue;
2284bdd1243dSDimitry Andric 
2285bdd1243dSDimitry Andric           if (Error Err = parseAttrKind(EncodedKind, &Kind))
22860b57cec5SDimitry Andric             return Err;
22870b57cec5SDimitry Andric 
22880b57cec5SDimitry Andric           // Upgrade old-style byval attribute to one with a type, even if it's
22890b57cec5SDimitry Andric           // nullptr. We will have to insert the real type when we associate
22900b57cec5SDimitry Andric           // this AttributeList with a function.
22910b57cec5SDimitry Andric           if (Kind == Attribute::ByVal)
22920b57cec5SDimitry Andric             B.addByValAttr(nullptr);
2293e8d8bef9SDimitry Andric           else if (Kind == Attribute::StructRet)
2294e8d8bef9SDimitry Andric             B.addStructRetAttr(nullptr);
2295fe6060f1SDimitry Andric           else if (Kind == Attribute::InAlloca)
2296fe6060f1SDimitry Andric             B.addInAllocaAttr(nullptr);
229781ad6265SDimitry Andric           else if (Kind == Attribute::UWTable)
229881ad6265SDimitry Andric             B.addUWTableAttr(UWTableKind::Default);
2299fe6060f1SDimitry Andric           else if (Attribute::isEnumAttrKind(Kind))
23000b57cec5SDimitry Andric             B.addAttribute(Kind);
2301fe6060f1SDimitry Andric           else
2302fe6060f1SDimitry Andric             return error("Not an enum attribute");
23030b57cec5SDimitry Andric         } else if (Record[i] == 1) { // Integer attribute
23040b57cec5SDimitry Andric           Attribute::AttrKind Kind;
23050b57cec5SDimitry Andric           if (Error Err = parseAttrKind(Record[++i], &Kind))
23060b57cec5SDimitry Andric             return Err;
2307fe6060f1SDimitry Andric           if (!Attribute::isIntAttrKind(Kind))
2308fe6060f1SDimitry Andric             return error("Not an int attribute");
23090b57cec5SDimitry Andric           if (Kind == Attribute::Alignment)
23100b57cec5SDimitry Andric             B.addAlignmentAttr(Record[++i]);
23110b57cec5SDimitry Andric           else if (Kind == Attribute::StackAlignment)
23120b57cec5SDimitry Andric             B.addStackAlignmentAttr(Record[++i]);
23130b57cec5SDimitry Andric           else if (Kind == Attribute::Dereferenceable)
23140b57cec5SDimitry Andric             B.addDereferenceableAttr(Record[++i]);
23150b57cec5SDimitry Andric           else if (Kind == Attribute::DereferenceableOrNull)
23160b57cec5SDimitry Andric             B.addDereferenceableOrNullAttr(Record[++i]);
23170b57cec5SDimitry Andric           else if (Kind == Attribute::AllocSize)
23180b57cec5SDimitry Andric             B.addAllocSizeAttrFromRawRepr(Record[++i]);
2319fe6060f1SDimitry Andric           else if (Kind == Attribute::VScaleRange)
2320fe6060f1SDimitry Andric             B.addVScaleRangeAttrFromRawRepr(Record[++i]);
232181ad6265SDimitry Andric           else if (Kind == Attribute::UWTable)
232281ad6265SDimitry Andric             B.addUWTableAttr(UWTableKind(Record[++i]));
232381ad6265SDimitry Andric           else if (Kind == Attribute::AllocKind)
232481ad6265SDimitry Andric             B.addAllocKindAttr(static_cast<AllocFnKind>(Record[++i]));
2325bdd1243dSDimitry Andric           else if (Kind == Attribute::Memory)
2326bdd1243dSDimitry Andric             B.addMemoryAttr(MemoryEffects::createFromIntValue(Record[++i]));
232706c3fb27SDimitry Andric           else if (Kind == Attribute::NoFPClass)
232806c3fb27SDimitry Andric             B.addNoFPClassAttr(
232906c3fb27SDimitry Andric                 static_cast<FPClassTest>(Record[++i] & fcAllFlags));
23300b57cec5SDimitry Andric         } else if (Record[i] == 3 || Record[i] == 4) { // String attribute
23310b57cec5SDimitry Andric           bool HasValue = (Record[i++] == 4);
23320b57cec5SDimitry Andric           SmallString<64> KindStr;
23330b57cec5SDimitry Andric           SmallString<64> ValStr;
23340b57cec5SDimitry Andric 
23350b57cec5SDimitry Andric           while (Record[i] != 0 && i != e)
23360b57cec5SDimitry Andric             KindStr += Record[i++];
23370b57cec5SDimitry Andric           assert(Record[i] == 0 && "Kind string not null terminated");
23380b57cec5SDimitry Andric 
23390b57cec5SDimitry Andric           if (HasValue) {
23400b57cec5SDimitry Andric             // Has a value associated with it.
23410b57cec5SDimitry Andric             ++i; // Skip the '0' that terminates the "kind" string.
23420b57cec5SDimitry Andric             while (Record[i] != 0 && i != e)
23430b57cec5SDimitry Andric               ValStr += Record[i++];
23440b57cec5SDimitry Andric             assert(Record[i] == 0 && "Value string not null terminated");
23450b57cec5SDimitry Andric           }
23460b57cec5SDimitry Andric 
23470b57cec5SDimitry Andric           B.addAttribute(KindStr.str(), ValStr.str());
234881ad6265SDimitry Andric         } else if (Record[i] == 5 || Record[i] == 6) {
23490b57cec5SDimitry Andric           bool HasType = Record[i] == 6;
23500b57cec5SDimitry Andric           Attribute::AttrKind Kind;
23510b57cec5SDimitry Andric           if (Error Err = parseAttrKind(Record[++i], &Kind))
23520b57cec5SDimitry Andric             return Err;
2353fe6060f1SDimitry Andric           if (!Attribute::isTypeAttrKind(Kind))
2354fe6060f1SDimitry Andric             return error("Not a type attribute");
2355fe6060f1SDimitry Andric 
2356fe6060f1SDimitry Andric           B.addTypeAttr(Kind, HasType ? getTypeByID(Record[++i]) : nullptr);
2357*0fca6ea1SDimitry Andric         } else if (Record[i] == 7) {
2358*0fca6ea1SDimitry Andric           Attribute::AttrKind Kind;
2359*0fca6ea1SDimitry Andric 
2360*0fca6ea1SDimitry Andric           i++;
2361*0fca6ea1SDimitry Andric           if (Error Err = parseAttrKind(Record[i++], &Kind))
2362*0fca6ea1SDimitry Andric             return Err;
2363*0fca6ea1SDimitry Andric           if (!Attribute::isConstantRangeAttrKind(Kind))
2364*0fca6ea1SDimitry Andric             return error("Not a ConstantRange attribute");
2365*0fca6ea1SDimitry Andric 
2366*0fca6ea1SDimitry Andric           Expected<ConstantRange> MaybeCR =
2367*0fca6ea1SDimitry Andric               readBitWidthAndConstantRange(Record, i);
2368*0fca6ea1SDimitry Andric           if (!MaybeCR)
2369*0fca6ea1SDimitry Andric             return MaybeCR.takeError();
2370*0fca6ea1SDimitry Andric           i--;
2371*0fca6ea1SDimitry Andric 
2372*0fca6ea1SDimitry Andric           B.addConstantRangeAttr(Kind, MaybeCR.get());
2373*0fca6ea1SDimitry Andric         } else if (Record[i] == 8) {
2374*0fca6ea1SDimitry Andric           Attribute::AttrKind Kind;
2375*0fca6ea1SDimitry Andric 
2376*0fca6ea1SDimitry Andric           i++;
2377*0fca6ea1SDimitry Andric           if (Error Err = parseAttrKind(Record[i++], &Kind))
2378*0fca6ea1SDimitry Andric             return Err;
2379*0fca6ea1SDimitry Andric           if (!Attribute::isConstantRangeListAttrKind(Kind))
2380*0fca6ea1SDimitry Andric             return error("Not a constant range list attribute");
2381*0fca6ea1SDimitry Andric 
2382*0fca6ea1SDimitry Andric           SmallVector<ConstantRange, 2> Val;
2383*0fca6ea1SDimitry Andric           if (i + 2 > e)
2384*0fca6ea1SDimitry Andric             return error("Too few records for constant range list");
2385*0fca6ea1SDimitry Andric           unsigned RangeSize = Record[i++];
2386*0fca6ea1SDimitry Andric           unsigned BitWidth = Record[i++];
2387*0fca6ea1SDimitry Andric           for (unsigned Idx = 0; Idx < RangeSize; ++Idx) {
2388*0fca6ea1SDimitry Andric             Expected<ConstantRange> MaybeCR =
2389*0fca6ea1SDimitry Andric                 readConstantRange(Record, i, BitWidth);
2390*0fca6ea1SDimitry Andric             if (!MaybeCR)
2391*0fca6ea1SDimitry Andric               return MaybeCR.takeError();
2392*0fca6ea1SDimitry Andric             Val.push_back(MaybeCR.get());
2393*0fca6ea1SDimitry Andric           }
2394*0fca6ea1SDimitry Andric           i--;
2395*0fca6ea1SDimitry Andric 
2396*0fca6ea1SDimitry Andric           if (!ConstantRangeList::isOrderedRanges(Val))
2397*0fca6ea1SDimitry Andric             return error("Invalid (unordered or overlapping) range list");
2398*0fca6ea1SDimitry Andric           B.addConstantRangeListAttr(Kind, Val);
239981ad6265SDimitry Andric         } else {
240081ad6265SDimitry Andric           return error("Invalid attribute group entry");
24010b57cec5SDimitry Andric         }
24020b57cec5SDimitry Andric       }
24030b57cec5SDimitry Andric 
2404bdd1243dSDimitry Andric       if (ME != MemoryEffects::unknown())
2405bdd1243dSDimitry Andric         B.addMemoryAttr(ME);
2406bdd1243dSDimitry Andric 
24075ffd83dbSDimitry Andric       UpgradeAttributes(B);
24080b57cec5SDimitry Andric       MAttributeGroups[GrpID] = AttributeList::get(Context, Idx, B);
24090b57cec5SDimitry Andric       break;
24100b57cec5SDimitry Andric     }
24110b57cec5SDimitry Andric     }
24120b57cec5SDimitry Andric   }
24130b57cec5SDimitry Andric }
24140b57cec5SDimitry Andric 
24150b57cec5SDimitry Andric Error BitcodeReader::parseTypeTable() {
24160b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
24170b57cec5SDimitry Andric     return Err;
24180b57cec5SDimitry Andric 
24190b57cec5SDimitry Andric   return parseTypeTableBody();
24200b57cec5SDimitry Andric }
24210b57cec5SDimitry Andric 
24220b57cec5SDimitry Andric Error BitcodeReader::parseTypeTableBody() {
24230b57cec5SDimitry Andric   if (!TypeList.empty())
24240b57cec5SDimitry Andric     return error("Invalid multiple blocks");
24250b57cec5SDimitry Andric 
24260b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
24270b57cec5SDimitry Andric   unsigned NumRecords = 0;
24280b57cec5SDimitry Andric 
24290b57cec5SDimitry Andric   SmallString<64> TypeName;
24300b57cec5SDimitry Andric 
24310b57cec5SDimitry Andric   // Read all the records for this type table.
24320b57cec5SDimitry Andric   while (true) {
24330b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
24340b57cec5SDimitry Andric     if (!MaybeEntry)
24350b57cec5SDimitry Andric       return MaybeEntry.takeError();
24360b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
24370b57cec5SDimitry Andric 
24380b57cec5SDimitry Andric     switch (Entry.Kind) {
24390b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
24400b57cec5SDimitry Andric     case BitstreamEntry::Error:
24410b57cec5SDimitry Andric       return error("Malformed block");
24420b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
24430b57cec5SDimitry Andric       if (NumRecords != TypeList.size())
24440b57cec5SDimitry Andric         return error("Malformed block");
24450b57cec5SDimitry Andric       return Error::success();
24460b57cec5SDimitry Andric     case BitstreamEntry::Record:
24470b57cec5SDimitry Andric       // The interesting case.
24480b57cec5SDimitry Andric       break;
24490b57cec5SDimitry Andric     }
24500b57cec5SDimitry Andric 
24510b57cec5SDimitry Andric     // Read a record.
24520b57cec5SDimitry Andric     Record.clear();
24530b57cec5SDimitry Andric     Type *ResultTy = nullptr;
245481ad6265SDimitry Andric     SmallVector<unsigned> ContainedIDs;
24550b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
24560b57cec5SDimitry Andric     if (!MaybeRecord)
24570b57cec5SDimitry Andric       return MaybeRecord.takeError();
24580b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
24590b57cec5SDimitry Andric     default:
24600b57cec5SDimitry Andric       return error("Invalid value");
24610b57cec5SDimitry Andric     case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
24620b57cec5SDimitry Andric       // TYPE_CODE_NUMENTRY contains a count of the number of types in the
24630b57cec5SDimitry Andric       // type list.  This allows us to reserve space.
2464e8d8bef9SDimitry Andric       if (Record.empty())
246581ad6265SDimitry Andric         return error("Invalid numentry record");
24660b57cec5SDimitry Andric       TypeList.resize(Record[0]);
24670b57cec5SDimitry Andric       continue;
24680b57cec5SDimitry Andric     case bitc::TYPE_CODE_VOID:      // VOID
24690b57cec5SDimitry Andric       ResultTy = Type::getVoidTy(Context);
24700b57cec5SDimitry Andric       break;
24710b57cec5SDimitry Andric     case bitc::TYPE_CODE_HALF:     // HALF
24720b57cec5SDimitry Andric       ResultTy = Type::getHalfTy(Context);
24730b57cec5SDimitry Andric       break;
24745ffd83dbSDimitry Andric     case bitc::TYPE_CODE_BFLOAT:    // BFLOAT
24755ffd83dbSDimitry Andric       ResultTy = Type::getBFloatTy(Context);
24765ffd83dbSDimitry Andric       break;
24770b57cec5SDimitry Andric     case bitc::TYPE_CODE_FLOAT:     // FLOAT
24780b57cec5SDimitry Andric       ResultTy = Type::getFloatTy(Context);
24790b57cec5SDimitry Andric       break;
24800b57cec5SDimitry Andric     case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
24810b57cec5SDimitry Andric       ResultTy = Type::getDoubleTy(Context);
24820b57cec5SDimitry Andric       break;
24830b57cec5SDimitry Andric     case bitc::TYPE_CODE_X86_FP80:  // X86_FP80
24840b57cec5SDimitry Andric       ResultTy = Type::getX86_FP80Ty(Context);
24850b57cec5SDimitry Andric       break;
24860b57cec5SDimitry Andric     case bitc::TYPE_CODE_FP128:     // FP128
24870b57cec5SDimitry Andric       ResultTy = Type::getFP128Ty(Context);
24880b57cec5SDimitry Andric       break;
24890b57cec5SDimitry Andric     case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
24900b57cec5SDimitry Andric       ResultTy = Type::getPPC_FP128Ty(Context);
24910b57cec5SDimitry Andric       break;
24920b57cec5SDimitry Andric     case bitc::TYPE_CODE_LABEL:     // LABEL
24930b57cec5SDimitry Andric       ResultTy = Type::getLabelTy(Context);
24940b57cec5SDimitry Andric       break;
24950b57cec5SDimitry Andric     case bitc::TYPE_CODE_METADATA:  // METADATA
24960b57cec5SDimitry Andric       ResultTy = Type::getMetadataTy(Context);
24970b57cec5SDimitry Andric       break;
24980b57cec5SDimitry Andric     case bitc::TYPE_CODE_X86_MMX:   // X86_MMX
24990b57cec5SDimitry Andric       ResultTy = Type::getX86_MMXTy(Context);
25000b57cec5SDimitry Andric       break;
2501e8d8bef9SDimitry Andric     case bitc::TYPE_CODE_X86_AMX:   // X86_AMX
2502e8d8bef9SDimitry Andric       ResultTy = Type::getX86_AMXTy(Context);
2503e8d8bef9SDimitry Andric       break;
25040b57cec5SDimitry Andric     case bitc::TYPE_CODE_TOKEN:     // TOKEN
25050b57cec5SDimitry Andric       ResultTy = Type::getTokenTy(Context);
25060b57cec5SDimitry Andric       break;
25070b57cec5SDimitry Andric     case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
2508e8d8bef9SDimitry Andric       if (Record.empty())
250981ad6265SDimitry Andric         return error("Invalid integer record");
25100b57cec5SDimitry Andric 
25110b57cec5SDimitry Andric       uint64_t NumBits = Record[0];
25120b57cec5SDimitry Andric       if (NumBits < IntegerType::MIN_INT_BITS ||
25130b57cec5SDimitry Andric           NumBits > IntegerType::MAX_INT_BITS)
25140b57cec5SDimitry Andric         return error("Bitwidth for integer type out of range");
25150b57cec5SDimitry Andric       ResultTy = IntegerType::get(Context, NumBits);
25160b57cec5SDimitry Andric       break;
25170b57cec5SDimitry Andric     }
25180b57cec5SDimitry Andric     case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
25190b57cec5SDimitry Andric                                     //          [pointee type, address space]
2520e8d8bef9SDimitry Andric       if (Record.empty())
252181ad6265SDimitry Andric         return error("Invalid pointer record");
25220b57cec5SDimitry Andric       unsigned AddressSpace = 0;
25230b57cec5SDimitry Andric       if (Record.size() == 2)
25240b57cec5SDimitry Andric         AddressSpace = Record[1];
25250b57cec5SDimitry Andric       ResultTy = getTypeByID(Record[0]);
25260b57cec5SDimitry Andric       if (!ResultTy ||
25270b57cec5SDimitry Andric           !PointerType::isValidElementType(ResultTy))
25280b57cec5SDimitry Andric         return error("Invalid type");
252981ad6265SDimitry Andric       ContainedIDs.push_back(Record[0]);
25300b57cec5SDimitry Andric       ResultTy = PointerType::get(ResultTy, AddressSpace);
25310b57cec5SDimitry Andric       break;
25320b57cec5SDimitry Andric     }
2533fe6060f1SDimitry Andric     case bitc::TYPE_CODE_OPAQUE_POINTER: { // OPAQUE_POINTER: [addrspace]
2534fe6060f1SDimitry Andric       if (Record.size() != 1)
253581ad6265SDimitry Andric         return error("Invalid opaque pointer record");
2536fe6060f1SDimitry Andric       unsigned AddressSpace = Record[0];
2537fe6060f1SDimitry Andric       ResultTy = PointerType::get(Context, AddressSpace);
2538fe6060f1SDimitry Andric       break;
2539fe6060f1SDimitry Andric     }
25400b57cec5SDimitry Andric     case bitc::TYPE_CODE_FUNCTION_OLD: {
25415ffd83dbSDimitry Andric       // Deprecated, but still needed to read old bitcode files.
25420b57cec5SDimitry Andric       // FUNCTION: [vararg, attrid, retty, paramty x N]
25430b57cec5SDimitry Andric       if (Record.size() < 3)
254481ad6265SDimitry Andric         return error("Invalid function record");
25450b57cec5SDimitry Andric       SmallVector<Type*, 8> ArgTys;
25460b57cec5SDimitry Andric       for (unsigned i = 3, e = Record.size(); i != e; ++i) {
25470b57cec5SDimitry Andric         if (Type *T = getTypeByID(Record[i]))
25480b57cec5SDimitry Andric           ArgTys.push_back(T);
25490b57cec5SDimitry Andric         else
25500b57cec5SDimitry Andric           break;
25510b57cec5SDimitry Andric       }
25520b57cec5SDimitry Andric 
25530b57cec5SDimitry Andric       ResultTy = getTypeByID(Record[2]);
25540b57cec5SDimitry Andric       if (!ResultTy || ArgTys.size() < Record.size()-3)
25550b57cec5SDimitry Andric         return error("Invalid type");
25560b57cec5SDimitry Andric 
255781ad6265SDimitry Andric       ContainedIDs.append(Record.begin() + 2, Record.end());
25580b57cec5SDimitry Andric       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
25590b57cec5SDimitry Andric       break;
25600b57cec5SDimitry Andric     }
25610b57cec5SDimitry Andric     case bitc::TYPE_CODE_FUNCTION: {
25620b57cec5SDimitry Andric       // FUNCTION: [vararg, retty, paramty x N]
25630b57cec5SDimitry Andric       if (Record.size() < 2)
256481ad6265SDimitry Andric         return error("Invalid function record");
25650b57cec5SDimitry Andric       SmallVector<Type*, 8> ArgTys;
25660b57cec5SDimitry Andric       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
25670b57cec5SDimitry Andric         if (Type *T = getTypeByID(Record[i])) {
25680b57cec5SDimitry Andric           if (!FunctionType::isValidArgumentType(T))
25690b57cec5SDimitry Andric             return error("Invalid function argument type");
25700b57cec5SDimitry Andric           ArgTys.push_back(T);
25710b57cec5SDimitry Andric         }
25720b57cec5SDimitry Andric         else
25730b57cec5SDimitry Andric           break;
25740b57cec5SDimitry Andric       }
25750b57cec5SDimitry Andric 
25760b57cec5SDimitry Andric       ResultTy = getTypeByID(Record[1]);
25770b57cec5SDimitry Andric       if (!ResultTy || ArgTys.size() < Record.size()-2)
25780b57cec5SDimitry Andric         return error("Invalid type");
25790b57cec5SDimitry Andric 
258081ad6265SDimitry Andric       ContainedIDs.append(Record.begin() + 1, Record.end());
25810b57cec5SDimitry Andric       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
25820b57cec5SDimitry Andric       break;
25830b57cec5SDimitry Andric     }
25840b57cec5SDimitry Andric     case bitc::TYPE_CODE_STRUCT_ANON: {  // STRUCT: [ispacked, eltty x N]
2585e8d8bef9SDimitry Andric       if (Record.empty())
258681ad6265SDimitry Andric         return error("Invalid anon struct record");
25870b57cec5SDimitry Andric       SmallVector<Type*, 8> EltTys;
25880b57cec5SDimitry Andric       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
25890b57cec5SDimitry Andric         if (Type *T = getTypeByID(Record[i]))
25900b57cec5SDimitry Andric           EltTys.push_back(T);
25910b57cec5SDimitry Andric         else
25920b57cec5SDimitry Andric           break;
25930b57cec5SDimitry Andric       }
25940b57cec5SDimitry Andric       if (EltTys.size() != Record.size()-1)
25950b57cec5SDimitry Andric         return error("Invalid type");
259681ad6265SDimitry Andric       ContainedIDs.append(Record.begin() + 1, Record.end());
25970b57cec5SDimitry Andric       ResultTy = StructType::get(Context, EltTys, Record[0]);
25980b57cec5SDimitry Andric       break;
25990b57cec5SDimitry Andric     }
26000b57cec5SDimitry Andric     case bitc::TYPE_CODE_STRUCT_NAME:   // STRUCT_NAME: [strchr x N]
26010b57cec5SDimitry Andric       if (convertToString(Record, 0, TypeName))
260281ad6265SDimitry Andric         return error("Invalid struct name record");
26030b57cec5SDimitry Andric       continue;
26040b57cec5SDimitry Andric 
26050b57cec5SDimitry Andric     case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
2606e8d8bef9SDimitry Andric       if (Record.empty())
260781ad6265SDimitry Andric         return error("Invalid named struct record");
26080b57cec5SDimitry Andric 
26090b57cec5SDimitry Andric       if (NumRecords >= TypeList.size())
26100b57cec5SDimitry Andric         return error("Invalid TYPE table");
26110b57cec5SDimitry Andric 
26120b57cec5SDimitry Andric       // Check to see if this was forward referenced, if so fill in the temp.
26130b57cec5SDimitry Andric       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
26140b57cec5SDimitry Andric       if (Res) {
26150b57cec5SDimitry Andric         Res->setName(TypeName);
26160b57cec5SDimitry Andric         TypeList[NumRecords] = nullptr;
26170b57cec5SDimitry Andric       } else  // Otherwise, create a new struct.
26180b57cec5SDimitry Andric         Res = createIdentifiedStructType(Context, TypeName);
26190b57cec5SDimitry Andric       TypeName.clear();
26200b57cec5SDimitry Andric 
26210b57cec5SDimitry Andric       SmallVector<Type*, 8> EltTys;
26220b57cec5SDimitry Andric       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
26230b57cec5SDimitry Andric         if (Type *T = getTypeByID(Record[i]))
26240b57cec5SDimitry Andric           EltTys.push_back(T);
26250b57cec5SDimitry Andric         else
26260b57cec5SDimitry Andric           break;
26270b57cec5SDimitry Andric       }
26280b57cec5SDimitry Andric       if (EltTys.size() != Record.size()-1)
262981ad6265SDimitry Andric         return error("Invalid named struct record");
26300b57cec5SDimitry Andric       Res->setBody(EltTys, Record[0]);
263181ad6265SDimitry Andric       ContainedIDs.append(Record.begin() + 1, Record.end());
26320b57cec5SDimitry Andric       ResultTy = Res;
26330b57cec5SDimitry Andric       break;
26340b57cec5SDimitry Andric     }
26350b57cec5SDimitry Andric     case bitc::TYPE_CODE_OPAQUE: {       // OPAQUE: []
26360b57cec5SDimitry Andric       if (Record.size() != 1)
263781ad6265SDimitry Andric         return error("Invalid opaque type record");
26380b57cec5SDimitry Andric 
26390b57cec5SDimitry Andric       if (NumRecords >= TypeList.size())
26400b57cec5SDimitry Andric         return error("Invalid TYPE table");
26410b57cec5SDimitry Andric 
26420b57cec5SDimitry Andric       // Check to see if this was forward referenced, if so fill in the temp.
26430b57cec5SDimitry Andric       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
26440b57cec5SDimitry Andric       if (Res) {
26450b57cec5SDimitry Andric         Res->setName(TypeName);
26460b57cec5SDimitry Andric         TypeList[NumRecords] = nullptr;
26470b57cec5SDimitry Andric       } else  // Otherwise, create a new struct with no body.
26480b57cec5SDimitry Andric         Res = createIdentifiedStructType(Context, TypeName);
26490b57cec5SDimitry Andric       TypeName.clear();
26500b57cec5SDimitry Andric       ResultTy = Res;
26510b57cec5SDimitry Andric       break;
26520b57cec5SDimitry Andric     }
2653bdd1243dSDimitry Andric     case bitc::TYPE_CODE_TARGET_TYPE: { // TARGET_TYPE: [NumTy, Tys..., Ints...]
2654bdd1243dSDimitry Andric       if (Record.size() < 1)
2655bdd1243dSDimitry Andric         return error("Invalid target extension type record");
2656bdd1243dSDimitry Andric 
2657bdd1243dSDimitry Andric       if (NumRecords >= TypeList.size())
2658bdd1243dSDimitry Andric         return error("Invalid TYPE table");
2659bdd1243dSDimitry Andric 
2660bdd1243dSDimitry Andric       if (Record[0] >= Record.size())
2661bdd1243dSDimitry Andric         return error("Too many type parameters");
2662bdd1243dSDimitry Andric 
2663bdd1243dSDimitry Andric       unsigned NumTys = Record[0];
2664bdd1243dSDimitry Andric       SmallVector<Type *, 4> TypeParams;
2665bdd1243dSDimitry Andric       SmallVector<unsigned, 8> IntParams;
2666bdd1243dSDimitry Andric       for (unsigned i = 0; i < NumTys; i++) {
2667bdd1243dSDimitry Andric         if (Type *T = getTypeByID(Record[i + 1]))
2668bdd1243dSDimitry Andric           TypeParams.push_back(T);
2669bdd1243dSDimitry Andric         else
2670bdd1243dSDimitry Andric           return error("Invalid type");
2671bdd1243dSDimitry Andric       }
2672bdd1243dSDimitry Andric 
2673bdd1243dSDimitry Andric       for (unsigned i = NumTys + 1, e = Record.size(); i < e; i++) {
2674bdd1243dSDimitry Andric         if (Record[i] > UINT_MAX)
2675bdd1243dSDimitry Andric           return error("Integer parameter too large");
2676bdd1243dSDimitry Andric         IntParams.push_back(Record[i]);
2677bdd1243dSDimitry Andric       }
2678bdd1243dSDimitry Andric       ResultTy = TargetExtType::get(Context, TypeName, TypeParams, IntParams);
2679bdd1243dSDimitry Andric       TypeName.clear();
2680bdd1243dSDimitry Andric       break;
2681bdd1243dSDimitry Andric     }
26820b57cec5SDimitry Andric     case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
26830b57cec5SDimitry Andric       if (Record.size() < 2)
268481ad6265SDimitry Andric         return error("Invalid array type record");
26850b57cec5SDimitry Andric       ResultTy = getTypeByID(Record[1]);
26860b57cec5SDimitry Andric       if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
26870b57cec5SDimitry Andric         return error("Invalid type");
268881ad6265SDimitry Andric       ContainedIDs.push_back(Record[1]);
26890b57cec5SDimitry Andric       ResultTy = ArrayType::get(ResultTy, Record[0]);
26900b57cec5SDimitry Andric       break;
26910b57cec5SDimitry Andric     case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty] or
26920b57cec5SDimitry Andric                                     //         [numelts, eltty, scalable]
26930b57cec5SDimitry Andric       if (Record.size() < 2)
269481ad6265SDimitry Andric         return error("Invalid vector type record");
26950b57cec5SDimitry Andric       if (Record[0] == 0)
26960b57cec5SDimitry Andric         return error("Invalid vector length");
26970b57cec5SDimitry Andric       ResultTy = getTypeByID(Record[1]);
2698349cc55cSDimitry Andric       if (!ResultTy || !VectorType::isValidElementType(ResultTy))
26990b57cec5SDimitry Andric         return error("Invalid type");
27000b57cec5SDimitry Andric       bool Scalable = Record.size() > 2 ? Record[2] : false;
270181ad6265SDimitry Andric       ContainedIDs.push_back(Record[1]);
27020b57cec5SDimitry Andric       ResultTy = VectorType::get(ResultTy, Record[0], Scalable);
27030b57cec5SDimitry Andric       break;
27040b57cec5SDimitry Andric     }
27050b57cec5SDimitry Andric 
27060b57cec5SDimitry Andric     if (NumRecords >= TypeList.size())
27070b57cec5SDimitry Andric       return error("Invalid TYPE table");
27080b57cec5SDimitry Andric     if (TypeList[NumRecords])
27090b57cec5SDimitry Andric       return error(
27100b57cec5SDimitry Andric           "Invalid TYPE table: Only named structs can be forward referenced");
27110b57cec5SDimitry Andric     assert(ResultTy && "Didn't read a type?");
271281ad6265SDimitry Andric     TypeList[NumRecords] = ResultTy;
271381ad6265SDimitry Andric     if (!ContainedIDs.empty())
271481ad6265SDimitry Andric       ContainedTypeIDs[NumRecords] = std::move(ContainedIDs);
271581ad6265SDimitry Andric     ++NumRecords;
27160b57cec5SDimitry Andric   }
27170b57cec5SDimitry Andric }
27180b57cec5SDimitry Andric 
27190b57cec5SDimitry Andric Error BitcodeReader::parseOperandBundleTags() {
27200b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
27210b57cec5SDimitry Andric     return Err;
27220b57cec5SDimitry Andric 
27230b57cec5SDimitry Andric   if (!BundleTags.empty())
27240b57cec5SDimitry Andric     return error("Invalid multiple blocks");
27250b57cec5SDimitry Andric 
27260b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
27270b57cec5SDimitry Andric 
27280b57cec5SDimitry Andric   while (true) {
27290b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
27300b57cec5SDimitry Andric     if (!MaybeEntry)
27310b57cec5SDimitry Andric       return MaybeEntry.takeError();
27320b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
27330b57cec5SDimitry Andric 
27340b57cec5SDimitry Andric     switch (Entry.Kind) {
27350b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
27360b57cec5SDimitry Andric     case BitstreamEntry::Error:
27370b57cec5SDimitry Andric       return error("Malformed block");
27380b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
27390b57cec5SDimitry Andric       return Error::success();
27400b57cec5SDimitry Andric     case BitstreamEntry::Record:
27410b57cec5SDimitry Andric       // The interesting case.
27420b57cec5SDimitry Andric       break;
27430b57cec5SDimitry Andric     }
27440b57cec5SDimitry Andric 
27450b57cec5SDimitry Andric     // Tags are implicitly mapped to integers by their order.
27460b57cec5SDimitry Andric 
27470b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
27480b57cec5SDimitry Andric     if (!MaybeRecord)
27490b57cec5SDimitry Andric       return MaybeRecord.takeError();
27500b57cec5SDimitry Andric     if (MaybeRecord.get() != bitc::OPERAND_BUNDLE_TAG)
275181ad6265SDimitry Andric       return error("Invalid operand bundle record");
27520b57cec5SDimitry Andric 
27530b57cec5SDimitry Andric     // OPERAND_BUNDLE_TAG: [strchr x N]
27540b57cec5SDimitry Andric     BundleTags.emplace_back();
27550b57cec5SDimitry Andric     if (convertToString(Record, 0, BundleTags.back()))
275681ad6265SDimitry Andric       return error("Invalid operand bundle record");
27570b57cec5SDimitry Andric     Record.clear();
27580b57cec5SDimitry Andric   }
27590b57cec5SDimitry Andric }
27600b57cec5SDimitry Andric 
27610b57cec5SDimitry Andric Error BitcodeReader::parseSyncScopeNames() {
27620b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID))
27630b57cec5SDimitry Andric     return Err;
27640b57cec5SDimitry Andric 
27650b57cec5SDimitry Andric   if (!SSIDs.empty())
27660b57cec5SDimitry Andric     return error("Invalid multiple synchronization scope names blocks");
27670b57cec5SDimitry Andric 
27680b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
27690b57cec5SDimitry Andric   while (true) {
27700b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
27710b57cec5SDimitry Andric     if (!MaybeEntry)
27720b57cec5SDimitry Andric       return MaybeEntry.takeError();
27730b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
27740b57cec5SDimitry Andric 
27750b57cec5SDimitry Andric     switch (Entry.Kind) {
27760b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
27770b57cec5SDimitry Andric     case BitstreamEntry::Error:
27780b57cec5SDimitry Andric       return error("Malformed block");
27790b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
27800b57cec5SDimitry Andric       if (SSIDs.empty())
27810b57cec5SDimitry Andric         return error("Invalid empty synchronization scope names block");
27820b57cec5SDimitry Andric       return Error::success();
27830b57cec5SDimitry Andric     case BitstreamEntry::Record:
27840b57cec5SDimitry Andric       // The interesting case.
27850b57cec5SDimitry Andric       break;
27860b57cec5SDimitry Andric     }
27870b57cec5SDimitry Andric 
27880b57cec5SDimitry Andric     // Synchronization scope names are implicitly mapped to synchronization
27890b57cec5SDimitry Andric     // scope IDs by their order.
27900b57cec5SDimitry Andric 
27910b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
27920b57cec5SDimitry Andric     if (!MaybeRecord)
27930b57cec5SDimitry Andric       return MaybeRecord.takeError();
27940b57cec5SDimitry Andric     if (MaybeRecord.get() != bitc::SYNC_SCOPE_NAME)
279581ad6265SDimitry Andric       return error("Invalid sync scope record");
27960b57cec5SDimitry Andric 
27970b57cec5SDimitry Andric     SmallString<16> SSN;
27980b57cec5SDimitry Andric     if (convertToString(Record, 0, SSN))
279981ad6265SDimitry Andric       return error("Invalid sync scope record");
28000b57cec5SDimitry Andric 
28010b57cec5SDimitry Andric     SSIDs.push_back(Context.getOrInsertSyncScopeID(SSN));
28020b57cec5SDimitry Andric     Record.clear();
28030b57cec5SDimitry Andric   }
28040b57cec5SDimitry Andric }
28050b57cec5SDimitry Andric 
28060b57cec5SDimitry Andric /// Associate a value with its name from the given index in the provided record.
28070b57cec5SDimitry Andric Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
28080b57cec5SDimitry Andric                                              unsigned NameIndex, Triple &TT) {
28090b57cec5SDimitry Andric   SmallString<128> ValueName;
28100b57cec5SDimitry Andric   if (convertToString(Record, NameIndex, ValueName))
28110b57cec5SDimitry Andric     return error("Invalid record");
28120b57cec5SDimitry Andric   unsigned ValueID = Record[0];
28130b57cec5SDimitry Andric   if (ValueID >= ValueList.size() || !ValueList[ValueID])
28140b57cec5SDimitry Andric     return error("Invalid record");
28150b57cec5SDimitry Andric   Value *V = ValueList[ValueID];
28160b57cec5SDimitry Andric 
28170b57cec5SDimitry Andric   StringRef NameStr(ValueName.data(), ValueName.size());
28185f757f3fSDimitry Andric   if (NameStr.contains(0))
28190b57cec5SDimitry Andric     return error("Invalid value name");
28200b57cec5SDimitry Andric   V->setName(NameStr);
28210b57cec5SDimitry Andric   auto *GO = dyn_cast<GlobalObject>(V);
28220eae32dcSDimitry Andric   if (GO && ImplicitComdatObjects.contains(GO) && TT.supportsCOMDAT())
28230b57cec5SDimitry Andric     GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
28240b57cec5SDimitry Andric   return V;
28250b57cec5SDimitry Andric }
28260b57cec5SDimitry Andric 
28270b57cec5SDimitry Andric /// Helper to note and return the current location, and jump to the given
28280b57cec5SDimitry Andric /// offset.
28290b57cec5SDimitry Andric static Expected<uint64_t> jumpToValueSymbolTable(uint64_t Offset,
28300b57cec5SDimitry Andric                                                  BitstreamCursor &Stream) {
28310b57cec5SDimitry Andric   // Save the current parsing location so we can jump back at the end
28320b57cec5SDimitry Andric   // of the VST read.
28330b57cec5SDimitry Andric   uint64_t CurrentBit = Stream.GetCurrentBitNo();
28340b57cec5SDimitry Andric   if (Error JumpFailed = Stream.JumpToBit(Offset * 32))
28350b57cec5SDimitry Andric     return std::move(JumpFailed);
28360b57cec5SDimitry Andric   Expected<BitstreamEntry> MaybeEntry = Stream.advance();
28370b57cec5SDimitry Andric   if (!MaybeEntry)
28380b57cec5SDimitry Andric     return MaybeEntry.takeError();
283981ad6265SDimitry Andric   if (MaybeEntry.get().Kind != BitstreamEntry::SubBlock ||
284081ad6265SDimitry Andric       MaybeEntry.get().ID != bitc::VALUE_SYMTAB_BLOCK_ID)
284181ad6265SDimitry Andric     return error("Expected value symbol table subblock");
28420b57cec5SDimitry Andric   return CurrentBit;
28430b57cec5SDimitry Andric }
28440b57cec5SDimitry Andric 
28450b57cec5SDimitry Andric void BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta,
28460b57cec5SDimitry Andric                                             Function *F,
28470b57cec5SDimitry Andric                                             ArrayRef<uint64_t> Record) {
28480b57cec5SDimitry Andric   // Note that we subtract 1 here because the offset is relative to one word
28490b57cec5SDimitry Andric   // before the start of the identification or module block, which was
28500b57cec5SDimitry Andric   // historically always the start of the regular bitcode header.
28510b57cec5SDimitry Andric   uint64_t FuncWordOffset = Record[1] - 1;
28520b57cec5SDimitry Andric   uint64_t FuncBitOffset = FuncWordOffset * 32;
28530b57cec5SDimitry Andric   DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
28540b57cec5SDimitry Andric   // Set the LastFunctionBlockBit to point to the last function block.
28550b57cec5SDimitry Andric   // Later when parsing is resumed after function materialization,
28560b57cec5SDimitry Andric   // we can simply skip that last function block.
28570b57cec5SDimitry Andric   if (FuncBitOffset > LastFunctionBlockBit)
28580b57cec5SDimitry Andric     LastFunctionBlockBit = FuncBitOffset;
28590b57cec5SDimitry Andric }
28600b57cec5SDimitry Andric 
28610b57cec5SDimitry Andric /// Read a new-style GlobalValue symbol table.
28620b57cec5SDimitry Andric Error BitcodeReader::parseGlobalValueSymbolTable() {
28630b57cec5SDimitry Andric   unsigned FuncBitcodeOffsetDelta =
28640b57cec5SDimitry Andric       Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
28650b57cec5SDimitry Andric 
28660b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
28670b57cec5SDimitry Andric     return Err;
28680b57cec5SDimitry Andric 
28690b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
28700b57cec5SDimitry Andric   while (true) {
28710b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
28720b57cec5SDimitry Andric     if (!MaybeEntry)
28730b57cec5SDimitry Andric       return MaybeEntry.takeError();
28740b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
28750b57cec5SDimitry Andric 
28760b57cec5SDimitry Andric     switch (Entry.Kind) {
28770b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
28780b57cec5SDimitry Andric     case BitstreamEntry::Error:
28790b57cec5SDimitry Andric       return error("Malformed block");
28800b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
28810b57cec5SDimitry Andric       return Error::success();
28820b57cec5SDimitry Andric     case BitstreamEntry::Record:
28830b57cec5SDimitry Andric       break;
28840b57cec5SDimitry Andric     }
28850b57cec5SDimitry Andric 
28860b57cec5SDimitry Andric     Record.clear();
28870b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
28880b57cec5SDimitry Andric     if (!MaybeRecord)
28890b57cec5SDimitry Andric       return MaybeRecord.takeError();
28900b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
289181ad6265SDimitry Andric     case bitc::VST_CODE_FNENTRY: { // [valueid, offset]
289281ad6265SDimitry Andric       unsigned ValueID = Record[0];
289381ad6265SDimitry Andric       if (ValueID >= ValueList.size() || !ValueList[ValueID])
289481ad6265SDimitry Andric         return error("Invalid value reference in symbol table");
28950b57cec5SDimitry Andric       setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
289681ad6265SDimitry Andric                               cast<Function>(ValueList[ValueID]), Record);
28970b57cec5SDimitry Andric       break;
28980b57cec5SDimitry Andric     }
28990b57cec5SDimitry Andric     }
29000b57cec5SDimitry Andric   }
290181ad6265SDimitry Andric }
29020b57cec5SDimitry Andric 
29030b57cec5SDimitry Andric /// Parse the value symbol table at either the current parsing location or
29040b57cec5SDimitry Andric /// at the given bit offset if provided.
29050b57cec5SDimitry Andric Error BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
29060b57cec5SDimitry Andric   uint64_t CurrentBit;
29070b57cec5SDimitry Andric   // Pass in the Offset to distinguish between calling for the module-level
29080b57cec5SDimitry Andric   // VST (where we want to jump to the VST offset) and the function-level
29090b57cec5SDimitry Andric   // VST (where we don't).
29100b57cec5SDimitry Andric   if (Offset > 0) {
29110b57cec5SDimitry Andric     Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream);
29120b57cec5SDimitry Andric     if (!MaybeCurrentBit)
29130b57cec5SDimitry Andric       return MaybeCurrentBit.takeError();
29140b57cec5SDimitry Andric     CurrentBit = MaybeCurrentBit.get();
29150b57cec5SDimitry Andric     // If this module uses a string table, read this as a module-level VST.
29160b57cec5SDimitry Andric     if (UseStrtab) {
29170b57cec5SDimitry Andric       if (Error Err = parseGlobalValueSymbolTable())
29180b57cec5SDimitry Andric         return Err;
29190b57cec5SDimitry Andric       if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
29200b57cec5SDimitry Andric         return JumpFailed;
29210b57cec5SDimitry Andric       return Error::success();
29220b57cec5SDimitry Andric     }
29230b57cec5SDimitry Andric     // Otherwise, the VST will be in a similar format to a function-level VST,
29240b57cec5SDimitry Andric     // and will contain symbol names.
29250b57cec5SDimitry Andric   }
29260b57cec5SDimitry Andric 
29270b57cec5SDimitry Andric   // Compute the delta between the bitcode indices in the VST (the word offset
29280b57cec5SDimitry Andric   // to the word-aligned ENTER_SUBBLOCK for the function block, and that
29290b57cec5SDimitry Andric   // expected by the lazy reader. The reader's EnterSubBlock expects to have
29300b57cec5SDimitry Andric   // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
29310b57cec5SDimitry Andric   // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
29320b57cec5SDimitry Andric   // just before entering the VST subblock because: 1) the EnterSubBlock
29330b57cec5SDimitry Andric   // changes the AbbrevID width; 2) the VST block is nested within the same
29340b57cec5SDimitry Andric   // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
29350b57cec5SDimitry Andric   // AbbrevID width before calling EnterSubBlock; and 3) when we want to
29360b57cec5SDimitry Andric   // jump to the FUNCTION_BLOCK using this offset later, we don't want
29370b57cec5SDimitry Andric   // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
29380b57cec5SDimitry Andric   unsigned FuncBitcodeOffsetDelta =
29390b57cec5SDimitry Andric       Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
29400b57cec5SDimitry Andric 
29410b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
29420b57cec5SDimitry Andric     return Err;
29430b57cec5SDimitry Andric 
29440b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
29450b57cec5SDimitry Andric 
29460b57cec5SDimitry Andric   Triple TT(TheModule->getTargetTriple());
29470b57cec5SDimitry Andric 
29480b57cec5SDimitry Andric   // Read all the records for this value table.
29490b57cec5SDimitry Andric   SmallString<128> ValueName;
29500b57cec5SDimitry Andric 
29510b57cec5SDimitry Andric   while (true) {
29520b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
29530b57cec5SDimitry Andric     if (!MaybeEntry)
29540b57cec5SDimitry Andric       return MaybeEntry.takeError();
29550b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
29560b57cec5SDimitry Andric 
29570b57cec5SDimitry Andric     switch (Entry.Kind) {
29580b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
29590b57cec5SDimitry Andric     case BitstreamEntry::Error:
29600b57cec5SDimitry Andric       return error("Malformed block");
29610b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
29620b57cec5SDimitry Andric       if (Offset > 0)
29630b57cec5SDimitry Andric         if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
29640b57cec5SDimitry Andric           return JumpFailed;
29650b57cec5SDimitry Andric       return Error::success();
29660b57cec5SDimitry Andric     case BitstreamEntry::Record:
29670b57cec5SDimitry Andric       // The interesting case.
29680b57cec5SDimitry Andric       break;
29690b57cec5SDimitry Andric     }
29700b57cec5SDimitry Andric 
29710b57cec5SDimitry Andric     // Read a record.
29720b57cec5SDimitry Andric     Record.clear();
29730b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
29740b57cec5SDimitry Andric     if (!MaybeRecord)
29750b57cec5SDimitry Andric       return MaybeRecord.takeError();
29760b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
29770b57cec5SDimitry Andric     default:  // Default behavior: unknown type.
29780b57cec5SDimitry Andric       break;
29790b57cec5SDimitry Andric     case bitc::VST_CODE_ENTRY: {  // VST_CODE_ENTRY: [valueid, namechar x N]
29800b57cec5SDimitry Andric       Expected<Value *> ValOrErr = recordValue(Record, 1, TT);
29810b57cec5SDimitry Andric       if (Error Err = ValOrErr.takeError())
29820b57cec5SDimitry Andric         return Err;
29830b57cec5SDimitry Andric       ValOrErr.get();
29840b57cec5SDimitry Andric       break;
29850b57cec5SDimitry Andric     }
29860b57cec5SDimitry Andric     case bitc::VST_CODE_FNENTRY: {
29870b57cec5SDimitry Andric       // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
29880b57cec5SDimitry Andric       Expected<Value *> ValOrErr = recordValue(Record, 2, TT);
29890b57cec5SDimitry Andric       if (Error Err = ValOrErr.takeError())
29900b57cec5SDimitry Andric         return Err;
29910b57cec5SDimitry Andric       Value *V = ValOrErr.get();
29920b57cec5SDimitry Andric 
29930b57cec5SDimitry Andric       // Ignore function offsets emitted for aliases of functions in older
29940b57cec5SDimitry Andric       // versions of LLVM.
29950b57cec5SDimitry Andric       if (auto *F = dyn_cast<Function>(V))
29960b57cec5SDimitry Andric         setDeferredFunctionInfo(FuncBitcodeOffsetDelta, F, Record);
29970b57cec5SDimitry Andric       break;
29980b57cec5SDimitry Andric     }
29990b57cec5SDimitry Andric     case bitc::VST_CODE_BBENTRY: {
30000b57cec5SDimitry Andric       if (convertToString(Record, 1, ValueName))
300181ad6265SDimitry Andric         return error("Invalid bbentry record");
30020b57cec5SDimitry Andric       BasicBlock *BB = getBasicBlock(Record[0]);
30030b57cec5SDimitry Andric       if (!BB)
300481ad6265SDimitry Andric         return error("Invalid bbentry record");
30050b57cec5SDimitry Andric 
3006*0fca6ea1SDimitry Andric       BB->setName(ValueName.str());
30070b57cec5SDimitry Andric       ValueName.clear();
30080b57cec5SDimitry Andric       break;
30090b57cec5SDimitry Andric     }
30100b57cec5SDimitry Andric     }
30110b57cec5SDimitry Andric   }
30120b57cec5SDimitry Andric }
30130b57cec5SDimitry Andric 
30140b57cec5SDimitry Andric /// Decode a signed value stored with the sign bit in the LSB for dense VBR
30150b57cec5SDimitry Andric /// encoding.
30160b57cec5SDimitry Andric uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
30170b57cec5SDimitry Andric   if ((V & 1) == 0)
30180b57cec5SDimitry Andric     return V >> 1;
30190b57cec5SDimitry Andric   if (V != 1)
30200b57cec5SDimitry Andric     return -(V >> 1);
30210b57cec5SDimitry Andric   // There is no such thing as -0 with integers.  "-0" really means MININT.
30220b57cec5SDimitry Andric   return 1ULL << 63;
30230b57cec5SDimitry Andric }
30240b57cec5SDimitry Andric 
30250b57cec5SDimitry Andric /// Resolve all of the initializers for global values and aliases that we can.
30260b57cec5SDimitry Andric Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
30270b57cec5SDimitry Andric   std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist;
3028349cc55cSDimitry Andric   std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInitWorklist;
3029349cc55cSDimitry Andric   std::vector<FunctionOperandInfo> FunctionOperandWorklist;
30300b57cec5SDimitry Andric 
30310b57cec5SDimitry Andric   GlobalInitWorklist.swap(GlobalInits);
30320b57cec5SDimitry Andric   IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
3033349cc55cSDimitry Andric   FunctionOperandWorklist.swap(FunctionOperands);
30340b57cec5SDimitry Andric 
30350b57cec5SDimitry Andric   while (!GlobalInitWorklist.empty()) {
30360b57cec5SDimitry Andric     unsigned ValID = GlobalInitWorklist.back().second;
30370b57cec5SDimitry Andric     if (ValID >= ValueList.size()) {
30380b57cec5SDimitry Andric       // Not ready to resolve this yet, it requires something later in the file.
30390b57cec5SDimitry Andric       GlobalInits.push_back(GlobalInitWorklist.back());
30400b57cec5SDimitry Andric     } else {
304181ad6265SDimitry Andric       Expected<Constant *> MaybeC = getValueForInitializer(ValID);
304281ad6265SDimitry Andric       if (!MaybeC)
304381ad6265SDimitry Andric         return MaybeC.takeError();
304481ad6265SDimitry Andric       GlobalInitWorklist.back().first->setInitializer(MaybeC.get());
30450b57cec5SDimitry Andric     }
30460b57cec5SDimitry Andric     GlobalInitWorklist.pop_back();
30470b57cec5SDimitry Andric   }
30480b57cec5SDimitry Andric 
30490b57cec5SDimitry Andric   while (!IndirectSymbolInitWorklist.empty()) {
30500b57cec5SDimitry Andric     unsigned ValID = IndirectSymbolInitWorklist.back().second;
30510b57cec5SDimitry Andric     if (ValID >= ValueList.size()) {
30520b57cec5SDimitry Andric       IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
30530b57cec5SDimitry Andric     } else {
305481ad6265SDimitry Andric       Expected<Constant *> MaybeC = getValueForInitializer(ValID);
305581ad6265SDimitry Andric       if (!MaybeC)
305681ad6265SDimitry Andric         return MaybeC.takeError();
305781ad6265SDimitry Andric       Constant *C = MaybeC.get();
3058349cc55cSDimitry Andric       GlobalValue *GV = IndirectSymbolInitWorklist.back().first;
3059349cc55cSDimitry Andric       if (auto *GA = dyn_cast<GlobalAlias>(GV)) {
3060349cc55cSDimitry Andric         if (C->getType() != GV->getType())
30610b57cec5SDimitry Andric           return error("Alias and aliasee types don't match");
3062349cc55cSDimitry Andric         GA->setAliasee(C);
3063349cc55cSDimitry Andric       } else if (auto *GI = dyn_cast<GlobalIFunc>(GV)) {
30645f757f3fSDimitry Andric         GI->setResolver(C);
3065349cc55cSDimitry Andric       } else {
3066349cc55cSDimitry Andric         return error("Expected an alias or an ifunc");
3067349cc55cSDimitry Andric       }
30680b57cec5SDimitry Andric     }
30690b57cec5SDimitry Andric     IndirectSymbolInitWorklist.pop_back();
30700b57cec5SDimitry Andric   }
30710b57cec5SDimitry Andric 
3072349cc55cSDimitry Andric   while (!FunctionOperandWorklist.empty()) {
3073349cc55cSDimitry Andric     FunctionOperandInfo &Info = FunctionOperandWorklist.back();
3074349cc55cSDimitry Andric     if (Info.PersonalityFn) {
3075349cc55cSDimitry Andric       unsigned ValID = Info.PersonalityFn - 1;
3076349cc55cSDimitry Andric       if (ValID < ValueList.size()) {
307781ad6265SDimitry Andric         Expected<Constant *> MaybeC = getValueForInitializer(ValID);
307881ad6265SDimitry Andric         if (!MaybeC)
307981ad6265SDimitry Andric           return MaybeC.takeError();
308081ad6265SDimitry Andric         Info.F->setPersonalityFn(MaybeC.get());
3081349cc55cSDimitry Andric         Info.PersonalityFn = 0;
30820b57cec5SDimitry Andric       }
30830b57cec5SDimitry Andric     }
3084349cc55cSDimitry Andric     if (Info.Prefix) {
3085349cc55cSDimitry Andric       unsigned ValID = Info.Prefix - 1;
3086349cc55cSDimitry Andric       if (ValID < ValueList.size()) {
308781ad6265SDimitry Andric         Expected<Constant *> MaybeC = getValueForInitializer(ValID);
308881ad6265SDimitry Andric         if (!MaybeC)
308981ad6265SDimitry Andric           return MaybeC.takeError();
309081ad6265SDimitry Andric         Info.F->setPrefixData(MaybeC.get());
3091349cc55cSDimitry Andric         Info.Prefix = 0;
30920b57cec5SDimitry Andric       }
30930b57cec5SDimitry Andric     }
3094349cc55cSDimitry Andric     if (Info.Prologue) {
3095349cc55cSDimitry Andric       unsigned ValID = Info.Prologue - 1;
3096349cc55cSDimitry Andric       if (ValID < ValueList.size()) {
309781ad6265SDimitry Andric         Expected<Constant *> MaybeC = getValueForInitializer(ValID);
309881ad6265SDimitry Andric         if (!MaybeC)
309981ad6265SDimitry Andric           return MaybeC.takeError();
310081ad6265SDimitry Andric         Info.F->setPrologueData(MaybeC.get());
3101349cc55cSDimitry Andric         Info.Prologue = 0;
31020b57cec5SDimitry Andric       }
3103349cc55cSDimitry Andric     }
3104349cc55cSDimitry Andric     if (Info.PersonalityFn || Info.Prefix || Info.Prologue)
3105349cc55cSDimitry Andric       FunctionOperands.push_back(Info);
3106349cc55cSDimitry Andric     FunctionOperandWorklist.pop_back();
31070b57cec5SDimitry Andric   }
31080b57cec5SDimitry Andric 
31090b57cec5SDimitry Andric   return Error::success();
31100b57cec5SDimitry Andric }
31110b57cec5SDimitry Andric 
31125ffd83dbSDimitry Andric APInt llvm::readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
31130b57cec5SDimitry Andric   SmallVector<uint64_t, 8> Words(Vals.size());
31140b57cec5SDimitry Andric   transform(Vals, Words.begin(),
31150b57cec5SDimitry Andric                  BitcodeReader::decodeSignRotatedValue);
31160b57cec5SDimitry Andric 
31170b57cec5SDimitry Andric   return APInt(TypeBits, Words);
31180b57cec5SDimitry Andric }
31190b57cec5SDimitry Andric 
31200b57cec5SDimitry Andric Error BitcodeReader::parseConstants() {
31210b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
31220b57cec5SDimitry Andric     return Err;
31230b57cec5SDimitry Andric 
31240b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
31250b57cec5SDimitry Andric 
31260b57cec5SDimitry Andric   // Read all the records for this value table.
31270b57cec5SDimitry Andric   Type *CurTy = Type::getInt32Ty(Context);
312881ad6265SDimitry Andric   unsigned Int32TyID = getVirtualTypeID(CurTy);
312981ad6265SDimitry Andric   unsigned CurTyID = Int32TyID;
313081ad6265SDimitry Andric   Type *CurElemTy = nullptr;
31310b57cec5SDimitry Andric   unsigned NextCstNo = ValueList.size();
31320b57cec5SDimitry Andric 
31330b57cec5SDimitry Andric   while (true) {
31340b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
31350b57cec5SDimitry Andric     if (!MaybeEntry)
31360b57cec5SDimitry Andric       return MaybeEntry.takeError();
31370b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
31380b57cec5SDimitry Andric 
31390b57cec5SDimitry Andric     switch (Entry.Kind) {
31400b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
31410b57cec5SDimitry Andric     case BitstreamEntry::Error:
31420b57cec5SDimitry Andric       return error("Malformed block");
31430b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
31440b57cec5SDimitry Andric       if (NextCstNo != ValueList.size())
31450b57cec5SDimitry Andric         return error("Invalid constant reference");
31460b57cec5SDimitry Andric       return Error::success();
31470b57cec5SDimitry Andric     case BitstreamEntry::Record:
31480b57cec5SDimitry Andric       // The interesting case.
31490b57cec5SDimitry Andric       break;
31500b57cec5SDimitry Andric     }
31510b57cec5SDimitry Andric 
31520b57cec5SDimitry Andric     // Read a record.
31530b57cec5SDimitry Andric     Record.clear();
31540b57cec5SDimitry Andric     Type *VoidType = Type::getVoidTy(Context);
31550b57cec5SDimitry Andric     Value *V = nullptr;
31560b57cec5SDimitry Andric     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
31570b57cec5SDimitry Andric     if (!MaybeBitCode)
31580b57cec5SDimitry Andric       return MaybeBitCode.takeError();
31590b57cec5SDimitry Andric     switch (unsigned BitCode = MaybeBitCode.get()) {
31600b57cec5SDimitry Andric     default:  // Default behavior: unknown constant
31610b57cec5SDimitry Andric     case bitc::CST_CODE_UNDEF:     // UNDEF
31620b57cec5SDimitry Andric       V = UndefValue::get(CurTy);
31630b57cec5SDimitry Andric       break;
3164e8d8bef9SDimitry Andric     case bitc::CST_CODE_POISON:    // POISON
3165e8d8bef9SDimitry Andric       V = PoisonValue::get(CurTy);
3166e8d8bef9SDimitry Andric       break;
31670b57cec5SDimitry Andric     case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
31680b57cec5SDimitry Andric       if (Record.empty())
316981ad6265SDimitry Andric         return error("Invalid settype record");
31700b57cec5SDimitry Andric       if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
317181ad6265SDimitry Andric         return error("Invalid settype record");
31720b57cec5SDimitry Andric       if (TypeList[Record[0]] == VoidType)
31730b57cec5SDimitry Andric         return error("Invalid constant type");
317481ad6265SDimitry Andric       CurTyID = Record[0];
317581ad6265SDimitry Andric       CurTy = TypeList[CurTyID];
317681ad6265SDimitry Andric       CurElemTy = getPtrElementTypeByID(CurTyID);
31770b57cec5SDimitry Andric       continue;  // Skip the ValueList manipulation.
31780b57cec5SDimitry Andric     case bitc::CST_CODE_NULL:      // NULL
31798bcb0991SDimitry Andric       if (CurTy->isVoidTy() || CurTy->isFunctionTy() || CurTy->isLabelTy())
31808bcb0991SDimitry Andric         return error("Invalid type for a constant null value");
3181bdd1243dSDimitry Andric       if (auto *TETy = dyn_cast<TargetExtType>(CurTy))
3182bdd1243dSDimitry Andric         if (!TETy->hasProperty(TargetExtType::HasZeroInit))
3183bdd1243dSDimitry Andric           return error("Invalid type for a constant null value");
31840b57cec5SDimitry Andric       V = Constant::getNullValue(CurTy);
31850b57cec5SDimitry Andric       break;
31860b57cec5SDimitry Andric     case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
3187*0fca6ea1SDimitry Andric       if (!CurTy->isIntOrIntVectorTy() || Record.empty())
318881ad6265SDimitry Andric         return error("Invalid integer const record");
31890b57cec5SDimitry Andric       V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
31900b57cec5SDimitry Andric       break;
31910b57cec5SDimitry Andric     case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
3192*0fca6ea1SDimitry Andric       if (!CurTy->isIntOrIntVectorTy() || Record.empty())
319381ad6265SDimitry Andric         return error("Invalid wide integer const record");
31940b57cec5SDimitry Andric 
3195*0fca6ea1SDimitry Andric       auto *ScalarTy = cast<IntegerType>(CurTy->getScalarType());
3196*0fca6ea1SDimitry Andric       APInt VInt = readWideAPInt(Record, ScalarTy->getBitWidth());
3197*0fca6ea1SDimitry Andric       V = ConstantInt::get(CurTy, VInt);
31980b57cec5SDimitry Andric       break;
31990b57cec5SDimitry Andric     }
32000b57cec5SDimitry Andric     case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
32010b57cec5SDimitry Andric       if (Record.empty())
320281ad6265SDimitry Andric         return error("Invalid float const record");
3203*0fca6ea1SDimitry Andric 
3204*0fca6ea1SDimitry Andric       auto *ScalarTy = CurTy->getScalarType();
3205*0fca6ea1SDimitry Andric       if (ScalarTy->isHalfTy())
3206*0fca6ea1SDimitry Andric         V = ConstantFP::get(CurTy, APFloat(APFloat::IEEEhalf(),
32070b57cec5SDimitry Andric                                            APInt(16, (uint16_t)Record[0])));
3208*0fca6ea1SDimitry Andric       else if (ScalarTy->isBFloatTy())
3209*0fca6ea1SDimitry Andric         V = ConstantFP::get(
3210*0fca6ea1SDimitry Andric             CurTy, APFloat(APFloat::BFloat(), APInt(16, (uint32_t)Record[0])));
3211*0fca6ea1SDimitry Andric       else if (ScalarTy->isFloatTy())
3212*0fca6ea1SDimitry Andric         V = ConstantFP::get(CurTy, APFloat(APFloat::IEEEsingle(),
32130b57cec5SDimitry Andric                                            APInt(32, (uint32_t)Record[0])));
3214*0fca6ea1SDimitry Andric       else if (ScalarTy->isDoubleTy())
3215*0fca6ea1SDimitry Andric         V = ConstantFP::get(
3216*0fca6ea1SDimitry Andric             CurTy, APFloat(APFloat::IEEEdouble(), APInt(64, Record[0])));
3217*0fca6ea1SDimitry Andric       else if (ScalarTy->isX86_FP80Ty()) {
32180b57cec5SDimitry Andric         // Bits are not stored the same way as a normal i80 APInt, compensate.
32190b57cec5SDimitry Andric         uint64_t Rearrange[2];
32200b57cec5SDimitry Andric         Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
32210b57cec5SDimitry Andric         Rearrange[1] = Record[0] >> 48;
3222*0fca6ea1SDimitry Andric         V = ConstantFP::get(
3223*0fca6ea1SDimitry Andric             CurTy, APFloat(APFloat::x87DoubleExtended(), APInt(80, Rearrange)));
3224*0fca6ea1SDimitry Andric       } else if (ScalarTy->isFP128Ty())
3225*0fca6ea1SDimitry Andric         V = ConstantFP::get(CurTy,
3226*0fca6ea1SDimitry Andric                             APFloat(APFloat::IEEEquad(), APInt(128, Record)));
3227*0fca6ea1SDimitry Andric       else if (ScalarTy->isPPC_FP128Ty())
3228*0fca6ea1SDimitry Andric         V = ConstantFP::get(
3229*0fca6ea1SDimitry Andric             CurTy, APFloat(APFloat::PPCDoubleDouble(), APInt(128, Record)));
32300b57cec5SDimitry Andric       else
3231*0fca6ea1SDimitry Andric         V = PoisonValue::get(CurTy);
32320b57cec5SDimitry Andric       break;
32330b57cec5SDimitry Andric     }
32340b57cec5SDimitry Andric 
32350b57cec5SDimitry Andric     case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
32360b57cec5SDimitry Andric       if (Record.empty())
323781ad6265SDimitry Andric         return error("Invalid aggregate record");
32380b57cec5SDimitry Andric 
32390b57cec5SDimitry Andric       unsigned Size = Record.size();
324081ad6265SDimitry Andric       SmallVector<unsigned, 16> Elts;
324181ad6265SDimitry Andric       for (unsigned i = 0; i != Size; ++i)
324281ad6265SDimitry Andric         Elts.push_back(Record[i]);
32430b57cec5SDimitry Andric 
324481ad6265SDimitry Andric       if (isa<StructType>(CurTy)) {
324581ad6265SDimitry Andric         V = BitcodeConstant::create(
324681ad6265SDimitry Andric             Alloc, CurTy, BitcodeConstant::ConstantStructOpcode, Elts);
324781ad6265SDimitry Andric       } else if (isa<ArrayType>(CurTy)) {
324881ad6265SDimitry Andric         V = BitcodeConstant::create(Alloc, CurTy,
324981ad6265SDimitry Andric                                     BitcodeConstant::ConstantArrayOpcode, Elts);
325081ad6265SDimitry Andric       } else if (isa<VectorType>(CurTy)) {
325181ad6265SDimitry Andric         V = BitcodeConstant::create(
325281ad6265SDimitry Andric             Alloc, CurTy, BitcodeConstant::ConstantVectorOpcode, Elts);
32530b57cec5SDimitry Andric       } else {
3254*0fca6ea1SDimitry Andric         V = PoisonValue::get(CurTy);
32550b57cec5SDimitry Andric       }
32560b57cec5SDimitry Andric       break;
32570b57cec5SDimitry Andric     }
32580b57cec5SDimitry Andric     case bitc::CST_CODE_STRING:    // STRING: [values]
32590b57cec5SDimitry Andric     case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
32600b57cec5SDimitry Andric       if (Record.empty())
326181ad6265SDimitry Andric         return error("Invalid string record");
32620b57cec5SDimitry Andric 
32630b57cec5SDimitry Andric       SmallString<16> Elts(Record.begin(), Record.end());
32640b57cec5SDimitry Andric       V = ConstantDataArray::getString(Context, Elts,
32650b57cec5SDimitry Andric                                        BitCode == bitc::CST_CODE_CSTRING);
32660b57cec5SDimitry Andric       break;
32670b57cec5SDimitry Andric     }
32680b57cec5SDimitry Andric     case bitc::CST_CODE_DATA: {// DATA: [n x value]
32690b57cec5SDimitry Andric       if (Record.empty())
327081ad6265SDimitry Andric         return error("Invalid data record");
32710b57cec5SDimitry Andric 
32725ffd83dbSDimitry Andric       Type *EltTy;
32735ffd83dbSDimitry Andric       if (auto *Array = dyn_cast<ArrayType>(CurTy))
32745ffd83dbSDimitry Andric         EltTy = Array->getElementType();
32755ffd83dbSDimitry Andric       else
32765ffd83dbSDimitry Andric         EltTy = cast<VectorType>(CurTy)->getElementType();
32770b57cec5SDimitry Andric       if (EltTy->isIntegerTy(8)) {
32780b57cec5SDimitry Andric         SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
32790b57cec5SDimitry Andric         if (isa<VectorType>(CurTy))
32800b57cec5SDimitry Andric           V = ConstantDataVector::get(Context, Elts);
32810b57cec5SDimitry Andric         else
32820b57cec5SDimitry Andric           V = ConstantDataArray::get(Context, Elts);
32830b57cec5SDimitry Andric       } else if (EltTy->isIntegerTy(16)) {
32840b57cec5SDimitry Andric         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
32850b57cec5SDimitry Andric         if (isa<VectorType>(CurTy))
32860b57cec5SDimitry Andric           V = ConstantDataVector::get(Context, Elts);
32870b57cec5SDimitry Andric         else
32880b57cec5SDimitry Andric           V = ConstantDataArray::get(Context, Elts);
32890b57cec5SDimitry Andric       } else if (EltTy->isIntegerTy(32)) {
32900b57cec5SDimitry Andric         SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
32910b57cec5SDimitry Andric         if (isa<VectorType>(CurTy))
32920b57cec5SDimitry Andric           V = ConstantDataVector::get(Context, Elts);
32930b57cec5SDimitry Andric         else
32940b57cec5SDimitry Andric           V = ConstantDataArray::get(Context, Elts);
32950b57cec5SDimitry Andric       } else if (EltTy->isIntegerTy(64)) {
32960b57cec5SDimitry Andric         SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
32970b57cec5SDimitry Andric         if (isa<VectorType>(CurTy))
32980b57cec5SDimitry Andric           V = ConstantDataVector::get(Context, Elts);
32990b57cec5SDimitry Andric         else
33000b57cec5SDimitry Andric           V = ConstantDataArray::get(Context, Elts);
33010b57cec5SDimitry Andric       } else if (EltTy->isHalfTy()) {
33020b57cec5SDimitry Andric         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
33030b57cec5SDimitry Andric         if (isa<VectorType>(CurTy))
33045ffd83dbSDimitry Andric           V = ConstantDataVector::getFP(EltTy, Elts);
33050b57cec5SDimitry Andric         else
33065ffd83dbSDimitry Andric           V = ConstantDataArray::getFP(EltTy, Elts);
33075ffd83dbSDimitry Andric       } else if (EltTy->isBFloatTy()) {
33085ffd83dbSDimitry Andric         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
33095ffd83dbSDimitry Andric         if (isa<VectorType>(CurTy))
33105ffd83dbSDimitry Andric           V = ConstantDataVector::getFP(EltTy, Elts);
33115ffd83dbSDimitry Andric         else
33125ffd83dbSDimitry Andric           V = ConstantDataArray::getFP(EltTy, Elts);
33130b57cec5SDimitry Andric       } else if (EltTy->isFloatTy()) {
33140b57cec5SDimitry Andric         SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
33150b57cec5SDimitry Andric         if (isa<VectorType>(CurTy))
33165ffd83dbSDimitry Andric           V = ConstantDataVector::getFP(EltTy, Elts);
33170b57cec5SDimitry Andric         else
33185ffd83dbSDimitry Andric           V = ConstantDataArray::getFP(EltTy, Elts);
33190b57cec5SDimitry Andric       } else if (EltTy->isDoubleTy()) {
33200b57cec5SDimitry Andric         SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
33210b57cec5SDimitry Andric         if (isa<VectorType>(CurTy))
33225ffd83dbSDimitry Andric           V = ConstantDataVector::getFP(EltTy, Elts);
33230b57cec5SDimitry Andric         else
33245ffd83dbSDimitry Andric           V = ConstantDataArray::getFP(EltTy, Elts);
33250b57cec5SDimitry Andric       } else {
33260b57cec5SDimitry Andric         return error("Invalid type for value");
33270b57cec5SDimitry Andric       }
33280b57cec5SDimitry Andric       break;
33290b57cec5SDimitry Andric     }
33300b57cec5SDimitry Andric     case bitc::CST_CODE_CE_UNOP: {  // CE_UNOP: [opcode, opval]
33310b57cec5SDimitry Andric       if (Record.size() < 2)
333281ad6265SDimitry Andric         return error("Invalid unary op constexpr record");
33330b57cec5SDimitry Andric       int Opc = getDecodedUnaryOpcode(Record[0], CurTy);
33340b57cec5SDimitry Andric       if (Opc < 0) {
3335*0fca6ea1SDimitry Andric         V = PoisonValue::get(CurTy);  // Unknown unop.
33360b57cec5SDimitry Andric       } else {
333781ad6265SDimitry Andric         V = BitcodeConstant::create(Alloc, CurTy, Opc, (unsigned)Record[1]);
33380b57cec5SDimitry Andric       }
33390b57cec5SDimitry Andric       break;
33400b57cec5SDimitry Andric     }
33410b57cec5SDimitry Andric     case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
33420b57cec5SDimitry Andric       if (Record.size() < 3)
334381ad6265SDimitry Andric         return error("Invalid binary op constexpr record");
33440b57cec5SDimitry Andric       int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
33450b57cec5SDimitry Andric       if (Opc < 0) {
3346*0fca6ea1SDimitry Andric         V = PoisonValue::get(CurTy);  // Unknown binop.
33470b57cec5SDimitry Andric       } else {
334881ad6265SDimitry Andric         uint8_t Flags = 0;
33490b57cec5SDimitry Andric         if (Record.size() >= 4) {
33500b57cec5SDimitry Andric           if (Opc == Instruction::Add ||
33510b57cec5SDimitry Andric               Opc == Instruction::Sub ||
33520b57cec5SDimitry Andric               Opc == Instruction::Mul ||
33530b57cec5SDimitry Andric               Opc == Instruction::Shl) {
33540b57cec5SDimitry Andric             if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
33550b57cec5SDimitry Andric               Flags |= OverflowingBinaryOperator::NoSignedWrap;
33560b57cec5SDimitry Andric             if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
33570b57cec5SDimitry Andric               Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
33580b57cec5SDimitry Andric           } else if (Opc == Instruction::SDiv ||
33590b57cec5SDimitry Andric                      Opc == Instruction::UDiv ||
33600b57cec5SDimitry Andric                      Opc == Instruction::LShr ||
33610b57cec5SDimitry Andric                      Opc == Instruction::AShr) {
33620b57cec5SDimitry Andric             if (Record[3] & (1 << bitc::PEO_EXACT))
33635f757f3fSDimitry Andric               Flags |= PossiblyExactOperator::IsExact;
33640b57cec5SDimitry Andric           }
33650b57cec5SDimitry Andric         }
336681ad6265SDimitry Andric         V = BitcodeConstant::create(Alloc, CurTy, {(uint8_t)Opc, Flags},
336781ad6265SDimitry Andric                                     {(unsigned)Record[1], (unsigned)Record[2]});
33680b57cec5SDimitry Andric       }
33690b57cec5SDimitry Andric       break;
33700b57cec5SDimitry Andric     }
33710b57cec5SDimitry Andric     case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
33720b57cec5SDimitry Andric       if (Record.size() < 3)
337381ad6265SDimitry Andric         return error("Invalid cast constexpr record");
33740b57cec5SDimitry Andric       int Opc = getDecodedCastOpcode(Record[0]);
33750b57cec5SDimitry Andric       if (Opc < 0) {
3376*0fca6ea1SDimitry Andric         V = PoisonValue::get(CurTy);  // Unknown cast.
33770b57cec5SDimitry Andric       } else {
337881ad6265SDimitry Andric         unsigned OpTyID = Record[1];
337981ad6265SDimitry Andric         Type *OpTy = getTypeByID(OpTyID);
33800b57cec5SDimitry Andric         if (!OpTy)
338181ad6265SDimitry Andric           return error("Invalid cast constexpr record");
338281ad6265SDimitry Andric         V = BitcodeConstant::create(Alloc, CurTy, Opc, (unsigned)Record[2]);
33830b57cec5SDimitry Andric       }
33840b57cec5SDimitry Andric       break;
33850b57cec5SDimitry Andric     }
33860b57cec5SDimitry Andric     case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands]
3387*0fca6ea1SDimitry Andric     case bitc::CST_CODE_CE_GEP_OLD:      // [ty, n x operands]
3388*0fca6ea1SDimitry Andric     case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX_OLD: // [ty, flags, n x
3389*0fca6ea1SDimitry Andric                                                        // operands]
3390*0fca6ea1SDimitry Andric     case bitc::CST_CODE_CE_GEP:                // [ty, flags, n x operands]
3391*0fca6ea1SDimitry Andric     case bitc::CST_CODE_CE_GEP_WITH_INRANGE: { // [ty, flags, start, end, n x
33920b57cec5SDimitry Andric                                                // operands]
339381ad6265SDimitry Andric       if (Record.size() < 2)
339481ad6265SDimitry Andric         return error("Constant GEP record must have at least two elements");
33950b57cec5SDimitry Andric       unsigned OpNum = 0;
33960b57cec5SDimitry Andric       Type *PointeeType = nullptr;
3397*0fca6ea1SDimitry Andric       if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX_OLD ||
3398*0fca6ea1SDimitry Andric           BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE ||
3399*0fca6ea1SDimitry Andric           BitCode == bitc::CST_CODE_CE_GEP || Record.size() % 2)
34000b57cec5SDimitry Andric         PointeeType = getTypeByID(Record[OpNum++]);
34010b57cec5SDimitry Andric 
3402*0fca6ea1SDimitry Andric       uint64_t Flags = 0;
3403*0fca6ea1SDimitry Andric       std::optional<ConstantRange> InRange;
3404*0fca6ea1SDimitry Andric       if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX_OLD) {
34050b57cec5SDimitry Andric         uint64_t Op = Record[OpNum++];
3406*0fca6ea1SDimitry Andric         Flags = Op & 1; // inbounds
3407*0fca6ea1SDimitry Andric         unsigned InRangeIndex = Op >> 1;
3408*0fca6ea1SDimitry Andric         // "Upgrade" inrange by dropping it. The feature is too niche to
3409*0fca6ea1SDimitry Andric         // bother.
3410*0fca6ea1SDimitry Andric         (void)InRangeIndex;
3411*0fca6ea1SDimitry Andric       } else if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE) {
3412*0fca6ea1SDimitry Andric         Flags = Record[OpNum++];
3413*0fca6ea1SDimitry Andric         Expected<ConstantRange> MaybeInRange =
3414*0fca6ea1SDimitry Andric             readBitWidthAndConstantRange(Record, OpNum);
3415*0fca6ea1SDimitry Andric         if (!MaybeInRange)
3416*0fca6ea1SDimitry Andric           return MaybeInRange.takeError();
3417*0fca6ea1SDimitry Andric         InRange = MaybeInRange.get();
3418*0fca6ea1SDimitry Andric       } else if (BitCode == bitc::CST_CODE_CE_GEP) {
3419*0fca6ea1SDimitry Andric         Flags = Record[OpNum++];
34200b57cec5SDimitry Andric       } else if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
3421*0fca6ea1SDimitry Andric         Flags = (1 << bitc::GEP_INBOUNDS);
34220b57cec5SDimitry Andric 
342381ad6265SDimitry Andric       SmallVector<unsigned, 16> Elts;
342481ad6265SDimitry Andric       unsigned BaseTypeID = Record[OpNum];
34250b57cec5SDimitry Andric       while (OpNum != Record.size()) {
342681ad6265SDimitry Andric         unsigned ElTyID = Record[OpNum++];
342781ad6265SDimitry Andric         Type *ElTy = getTypeByID(ElTyID);
34280b57cec5SDimitry Andric         if (!ElTy)
342981ad6265SDimitry Andric           return error("Invalid getelementptr constexpr record");
343081ad6265SDimitry Andric         Elts.push_back(Record[OpNum++]);
34310b57cec5SDimitry Andric       }
34320b57cec5SDimitry Andric 
34330b57cec5SDimitry Andric       if (Elts.size() < 1)
34340b57cec5SDimitry Andric         return error("Invalid gep with no operands");
34350b57cec5SDimitry Andric 
343681ad6265SDimitry Andric       Type *BaseType = getTypeByID(BaseTypeID);
343781ad6265SDimitry Andric       if (isa<VectorType>(BaseType)) {
343881ad6265SDimitry Andric         BaseTypeID = getContainedTypeID(BaseTypeID, 0);
343981ad6265SDimitry Andric         BaseType = getTypeByID(BaseTypeID);
344081ad6265SDimitry Andric       }
344181ad6265SDimitry Andric 
344281ad6265SDimitry Andric       PointerType *OrigPtrTy = dyn_cast_or_null<PointerType>(BaseType);
344381ad6265SDimitry Andric       if (!OrigPtrTy)
344481ad6265SDimitry Andric         return error("GEP base operand must be pointer or vector of pointer");
344581ad6265SDimitry Andric 
344681ad6265SDimitry Andric       if (!PointeeType) {
344781ad6265SDimitry Andric         PointeeType = getPtrElementTypeByID(BaseTypeID);
34480b57cec5SDimitry Andric         if (!PointeeType)
344981ad6265SDimitry Andric           return error("Missing element type for old-style constant GEP");
345006c3fb27SDimitry Andric       }
34510b57cec5SDimitry Andric 
3452*0fca6ea1SDimitry Andric       V = BitcodeConstant::create(
3453*0fca6ea1SDimitry Andric           Alloc, CurTy,
3454*0fca6ea1SDimitry Andric           {Instruction::GetElementPtr, uint8_t(Flags), PointeeType, InRange},
345581ad6265SDimitry Andric           Elts);
34560b57cec5SDimitry Andric       break;
34570b57cec5SDimitry Andric     }
34580b57cec5SDimitry Andric     case bitc::CST_CODE_CE_SELECT: {  // CE_SELECT: [opval#, opval#, opval#]
34590b57cec5SDimitry Andric       if (Record.size() < 3)
346081ad6265SDimitry Andric         return error("Invalid select constexpr record");
34610b57cec5SDimitry Andric 
346281ad6265SDimitry Andric       V = BitcodeConstant::create(
346381ad6265SDimitry Andric           Alloc, CurTy, Instruction::Select,
346481ad6265SDimitry Andric           {(unsigned)Record[0], (unsigned)Record[1], (unsigned)Record[2]});
346581ad6265SDimitry Andric       break;
34660b57cec5SDimitry Andric     }
34670b57cec5SDimitry Andric     case bitc::CST_CODE_CE_EXTRACTELT
34680b57cec5SDimitry Andric         : { // CE_EXTRACTELT: [opty, opval, opty, opval]
34690b57cec5SDimitry Andric       if (Record.size() < 3)
347081ad6265SDimitry Andric         return error("Invalid extractelement constexpr record");
347181ad6265SDimitry Andric       unsigned OpTyID = Record[0];
34720b57cec5SDimitry Andric       VectorType *OpTy =
347381ad6265SDimitry Andric         dyn_cast_or_null<VectorType>(getTypeByID(OpTyID));
34740b57cec5SDimitry Andric       if (!OpTy)
347581ad6265SDimitry Andric         return error("Invalid extractelement constexpr record");
347681ad6265SDimitry Andric       unsigned IdxRecord;
34770b57cec5SDimitry Andric       if (Record.size() == 4) {
347881ad6265SDimitry Andric         unsigned IdxTyID = Record[2];
347981ad6265SDimitry Andric         Type *IdxTy = getTypeByID(IdxTyID);
34800b57cec5SDimitry Andric         if (!IdxTy)
348181ad6265SDimitry Andric           return error("Invalid extractelement constexpr record");
348281ad6265SDimitry Andric         IdxRecord = Record[3];
34835ffd83dbSDimitry Andric       } else {
34845ffd83dbSDimitry Andric         // Deprecated, but still needed to read old bitcode files.
348581ad6265SDimitry Andric         IdxRecord = Record[2];
34865ffd83dbSDimitry Andric       }
348781ad6265SDimitry Andric       V = BitcodeConstant::create(Alloc, CurTy, Instruction::ExtractElement,
348881ad6265SDimitry Andric                                   {(unsigned)Record[1], IdxRecord});
34890b57cec5SDimitry Andric       break;
34900b57cec5SDimitry Andric     }
34910b57cec5SDimitry Andric     case bitc::CST_CODE_CE_INSERTELT
34920b57cec5SDimitry Andric         : { // CE_INSERTELT: [opval, opval, opty, opval]
34930b57cec5SDimitry Andric       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
34940b57cec5SDimitry Andric       if (Record.size() < 3 || !OpTy)
349581ad6265SDimitry Andric         return error("Invalid insertelement constexpr record");
349681ad6265SDimitry Andric       unsigned IdxRecord;
34970b57cec5SDimitry Andric       if (Record.size() == 4) {
349881ad6265SDimitry Andric         unsigned IdxTyID = Record[2];
349981ad6265SDimitry Andric         Type *IdxTy = getTypeByID(IdxTyID);
35000b57cec5SDimitry Andric         if (!IdxTy)
350181ad6265SDimitry Andric           return error("Invalid insertelement constexpr record");
350281ad6265SDimitry Andric         IdxRecord = Record[3];
35035ffd83dbSDimitry Andric       } else {
35045ffd83dbSDimitry Andric         // Deprecated, but still needed to read old bitcode files.
350581ad6265SDimitry Andric         IdxRecord = Record[2];
35065ffd83dbSDimitry Andric       }
350781ad6265SDimitry Andric       V = BitcodeConstant::create(
350881ad6265SDimitry Andric           Alloc, CurTy, Instruction::InsertElement,
350981ad6265SDimitry Andric           {(unsigned)Record[0], (unsigned)Record[1], IdxRecord});
35100b57cec5SDimitry Andric       break;
35110b57cec5SDimitry Andric     }
35120b57cec5SDimitry Andric     case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
35130b57cec5SDimitry Andric       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
35140b57cec5SDimitry Andric       if (Record.size() < 3 || !OpTy)
351581ad6265SDimitry Andric         return error("Invalid shufflevector constexpr record");
351681ad6265SDimitry Andric       V = BitcodeConstant::create(
351781ad6265SDimitry Andric           Alloc, CurTy, Instruction::ShuffleVector,
351881ad6265SDimitry Andric           {(unsigned)Record[0], (unsigned)Record[1], (unsigned)Record[2]});
351981ad6265SDimitry Andric       break;
35200b57cec5SDimitry Andric     }
35210b57cec5SDimitry Andric     case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
35220b57cec5SDimitry Andric       VectorType *RTy = dyn_cast<VectorType>(CurTy);
35230b57cec5SDimitry Andric       VectorType *OpTy =
35240b57cec5SDimitry Andric         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
35250b57cec5SDimitry Andric       if (Record.size() < 4 || !RTy || !OpTy)
352681ad6265SDimitry Andric         return error("Invalid shufflevector constexpr record");
352781ad6265SDimitry Andric       V = BitcodeConstant::create(
352881ad6265SDimitry Andric           Alloc, CurTy, Instruction::ShuffleVector,
352981ad6265SDimitry Andric           {(unsigned)Record[1], (unsigned)Record[2], (unsigned)Record[3]});
353081ad6265SDimitry Andric       break;
35310b57cec5SDimitry Andric     }
35320b57cec5SDimitry Andric     case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
35330b57cec5SDimitry Andric       if (Record.size() < 4)
353481ad6265SDimitry Andric         return error("Invalid cmp constexpt record");
353581ad6265SDimitry Andric       unsigned OpTyID = Record[0];
353681ad6265SDimitry Andric       Type *OpTy = getTypeByID(OpTyID);
35370b57cec5SDimitry Andric       if (!OpTy)
353881ad6265SDimitry Andric         return error("Invalid cmp constexpr record");
353981ad6265SDimitry Andric       V = BitcodeConstant::create(
354081ad6265SDimitry Andric           Alloc, CurTy,
354181ad6265SDimitry Andric           {(uint8_t)(OpTy->isFPOrFPVectorTy() ? Instruction::FCmp
354281ad6265SDimitry Andric                                               : Instruction::ICmp),
354381ad6265SDimitry Andric            (uint8_t)Record[3]},
354481ad6265SDimitry Andric           {(unsigned)Record[1], (unsigned)Record[2]});
35450b57cec5SDimitry Andric       break;
35460b57cec5SDimitry Andric     }
35470b57cec5SDimitry Andric     // This maintains backward compatibility, pre-asm dialect keywords.
35485ffd83dbSDimitry Andric     // Deprecated, but still needed to read old bitcode files.
35490b57cec5SDimitry Andric     case bitc::CST_CODE_INLINEASM_OLD: {
35500b57cec5SDimitry Andric       if (Record.size() < 2)
355181ad6265SDimitry Andric         return error("Invalid inlineasm record");
35520b57cec5SDimitry Andric       std::string AsmStr, ConstrStr;
35530b57cec5SDimitry Andric       bool HasSideEffects = Record[0] & 1;
35540b57cec5SDimitry Andric       bool IsAlignStack = Record[0] >> 1;
35550b57cec5SDimitry Andric       unsigned AsmStrSize = Record[1];
35560b57cec5SDimitry Andric       if (2+AsmStrSize >= Record.size())
355781ad6265SDimitry Andric         return error("Invalid inlineasm record");
35580b57cec5SDimitry Andric       unsigned ConstStrSize = Record[2+AsmStrSize];
35590b57cec5SDimitry Andric       if (3+AsmStrSize+ConstStrSize > Record.size())
356081ad6265SDimitry Andric         return error("Invalid inlineasm record");
35610b57cec5SDimitry Andric 
35620b57cec5SDimitry Andric       for (unsigned i = 0; i != AsmStrSize; ++i)
35630b57cec5SDimitry Andric         AsmStr += (char)Record[2+i];
35640b57cec5SDimitry Andric       for (unsigned i = 0; i != ConstStrSize; ++i)
35650b57cec5SDimitry Andric         ConstrStr += (char)Record[3+AsmStrSize+i];
35660b57cec5SDimitry Andric       UpgradeInlineAsmString(&AsmStr);
356781ad6265SDimitry Andric       if (!CurElemTy)
356881ad6265SDimitry Andric         return error("Missing element type for old-style inlineasm");
356981ad6265SDimitry Andric       V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr,
357081ad6265SDimitry Andric                          HasSideEffects, IsAlignStack);
35710b57cec5SDimitry Andric       break;
35720b57cec5SDimitry Andric     }
35730b57cec5SDimitry Andric     // This version adds support for the asm dialect keywords (e.g.,
35740b57cec5SDimitry Andric     // inteldialect).
3575fe6060f1SDimitry Andric     case bitc::CST_CODE_INLINEASM_OLD2: {
35760b57cec5SDimitry Andric       if (Record.size() < 2)
357781ad6265SDimitry Andric         return error("Invalid inlineasm record");
35780b57cec5SDimitry Andric       std::string AsmStr, ConstrStr;
35790b57cec5SDimitry Andric       bool HasSideEffects = Record[0] & 1;
35800b57cec5SDimitry Andric       bool IsAlignStack = (Record[0] >> 1) & 1;
35810b57cec5SDimitry Andric       unsigned AsmDialect = Record[0] >> 2;
35820b57cec5SDimitry Andric       unsigned AsmStrSize = Record[1];
35830b57cec5SDimitry Andric       if (2+AsmStrSize >= Record.size())
358481ad6265SDimitry Andric         return error("Invalid inlineasm record");
35850b57cec5SDimitry Andric       unsigned ConstStrSize = Record[2+AsmStrSize];
35860b57cec5SDimitry Andric       if (3+AsmStrSize+ConstStrSize > Record.size())
358781ad6265SDimitry Andric         return error("Invalid inlineasm record");
35880b57cec5SDimitry Andric 
35890b57cec5SDimitry Andric       for (unsigned i = 0; i != AsmStrSize; ++i)
35900b57cec5SDimitry Andric         AsmStr += (char)Record[2+i];
35910b57cec5SDimitry Andric       for (unsigned i = 0; i != ConstStrSize; ++i)
35920b57cec5SDimitry Andric         ConstrStr += (char)Record[3+AsmStrSize+i];
35930b57cec5SDimitry Andric       UpgradeInlineAsmString(&AsmStr);
359481ad6265SDimitry Andric       if (!CurElemTy)
359581ad6265SDimitry Andric         return error("Missing element type for old-style inlineasm");
359681ad6265SDimitry Andric       V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr,
359781ad6265SDimitry Andric                          HasSideEffects, IsAlignStack,
35980b57cec5SDimitry Andric                          InlineAsm::AsmDialect(AsmDialect));
35990b57cec5SDimitry Andric       break;
36000b57cec5SDimitry Andric     }
3601fe6060f1SDimitry Andric     // This version adds support for the unwind keyword.
360204eeddc0SDimitry Andric     case bitc::CST_CODE_INLINEASM_OLD3: {
3603fe6060f1SDimitry Andric       if (Record.size() < 2)
360481ad6265SDimitry Andric         return error("Invalid inlineasm record");
360504eeddc0SDimitry Andric       unsigned OpNum = 0;
3606fe6060f1SDimitry Andric       std::string AsmStr, ConstrStr;
360704eeddc0SDimitry Andric       bool HasSideEffects = Record[OpNum] & 1;
360804eeddc0SDimitry Andric       bool IsAlignStack = (Record[OpNum] >> 1) & 1;
360904eeddc0SDimitry Andric       unsigned AsmDialect = (Record[OpNum] >> 2) & 1;
361004eeddc0SDimitry Andric       bool CanThrow = (Record[OpNum] >> 3) & 1;
361104eeddc0SDimitry Andric       ++OpNum;
361204eeddc0SDimitry Andric       unsigned AsmStrSize = Record[OpNum];
361304eeddc0SDimitry Andric       ++OpNum;
361404eeddc0SDimitry Andric       if (OpNum + AsmStrSize >= Record.size())
361581ad6265SDimitry Andric         return error("Invalid inlineasm record");
361604eeddc0SDimitry Andric       unsigned ConstStrSize = Record[OpNum + AsmStrSize];
361704eeddc0SDimitry Andric       if (OpNum + 1 + AsmStrSize + ConstStrSize > Record.size())
361881ad6265SDimitry Andric         return error("Invalid inlineasm record");
3619fe6060f1SDimitry Andric 
3620fe6060f1SDimitry Andric       for (unsigned i = 0; i != AsmStrSize; ++i)
362104eeddc0SDimitry Andric         AsmStr += (char)Record[OpNum + i];
362204eeddc0SDimitry Andric       ++OpNum;
3623fe6060f1SDimitry Andric       for (unsigned i = 0; i != ConstStrSize; ++i)
362404eeddc0SDimitry Andric         ConstrStr += (char)Record[OpNum + AsmStrSize + i];
3625fe6060f1SDimitry Andric       UpgradeInlineAsmString(&AsmStr);
362681ad6265SDimitry Andric       if (!CurElemTy)
362781ad6265SDimitry Andric         return error("Missing element type for old-style inlineasm");
362881ad6265SDimitry Andric       V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr,
362981ad6265SDimitry Andric                          HasSideEffects, IsAlignStack,
3630fe6060f1SDimitry Andric                          InlineAsm::AsmDialect(AsmDialect), CanThrow);
3631fe6060f1SDimitry Andric       break;
3632fe6060f1SDimitry Andric     }
363304eeddc0SDimitry Andric     // This version adds explicit function type.
363404eeddc0SDimitry Andric     case bitc::CST_CODE_INLINEASM: {
363504eeddc0SDimitry Andric       if (Record.size() < 3)
363681ad6265SDimitry Andric         return error("Invalid inlineasm record");
363704eeddc0SDimitry Andric       unsigned OpNum = 0;
363804eeddc0SDimitry Andric       auto *FnTy = dyn_cast_or_null<FunctionType>(getTypeByID(Record[OpNum]));
363904eeddc0SDimitry Andric       ++OpNum;
364004eeddc0SDimitry Andric       if (!FnTy)
364181ad6265SDimitry Andric         return error("Invalid inlineasm record");
364204eeddc0SDimitry Andric       std::string AsmStr, ConstrStr;
364304eeddc0SDimitry Andric       bool HasSideEffects = Record[OpNum] & 1;
364404eeddc0SDimitry Andric       bool IsAlignStack = (Record[OpNum] >> 1) & 1;
364504eeddc0SDimitry Andric       unsigned AsmDialect = (Record[OpNum] >> 2) & 1;
364604eeddc0SDimitry Andric       bool CanThrow = (Record[OpNum] >> 3) & 1;
364704eeddc0SDimitry Andric       ++OpNum;
364804eeddc0SDimitry Andric       unsigned AsmStrSize = Record[OpNum];
364904eeddc0SDimitry Andric       ++OpNum;
365004eeddc0SDimitry Andric       if (OpNum + AsmStrSize >= Record.size())
365181ad6265SDimitry Andric         return error("Invalid inlineasm record");
365204eeddc0SDimitry Andric       unsigned ConstStrSize = Record[OpNum + AsmStrSize];
365304eeddc0SDimitry Andric       if (OpNum + 1 + AsmStrSize + ConstStrSize > Record.size())
365481ad6265SDimitry Andric         return error("Invalid inlineasm record");
365504eeddc0SDimitry Andric 
365604eeddc0SDimitry Andric       for (unsigned i = 0; i != AsmStrSize; ++i)
365704eeddc0SDimitry Andric         AsmStr += (char)Record[OpNum + i];
365804eeddc0SDimitry Andric       ++OpNum;
365904eeddc0SDimitry Andric       for (unsigned i = 0; i != ConstStrSize; ++i)
366004eeddc0SDimitry Andric         ConstrStr += (char)Record[OpNum + AsmStrSize + i];
366104eeddc0SDimitry Andric       UpgradeInlineAsmString(&AsmStr);
366204eeddc0SDimitry Andric       V = InlineAsm::get(FnTy, AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
366304eeddc0SDimitry Andric                          InlineAsm::AsmDialect(AsmDialect), CanThrow);
366404eeddc0SDimitry Andric       break;
366504eeddc0SDimitry Andric     }
36660b57cec5SDimitry Andric     case bitc::CST_CODE_BLOCKADDRESS:{
36670b57cec5SDimitry Andric       if (Record.size() < 3)
366881ad6265SDimitry Andric         return error("Invalid blockaddress record");
366981ad6265SDimitry Andric       unsigned FnTyID = Record[0];
367081ad6265SDimitry Andric       Type *FnTy = getTypeByID(FnTyID);
36710b57cec5SDimitry Andric       if (!FnTy)
367281ad6265SDimitry Andric         return error("Invalid blockaddress record");
367381ad6265SDimitry Andric       V = BitcodeConstant::create(
367481ad6265SDimitry Andric           Alloc, CurTy,
367581ad6265SDimitry Andric           {BitcodeConstant::BlockAddressOpcode, 0, (unsigned)Record[2]},
367681ad6265SDimitry Andric           Record[1]);
36770b57cec5SDimitry Andric       break;
36780b57cec5SDimitry Andric     }
3679fe6060f1SDimitry Andric     case bitc::CST_CODE_DSO_LOCAL_EQUIVALENT: {
3680fe6060f1SDimitry Andric       if (Record.size() < 2)
368181ad6265SDimitry Andric         return error("Invalid dso_local record");
368281ad6265SDimitry Andric       unsigned GVTyID = Record[0];
368381ad6265SDimitry Andric       Type *GVTy = getTypeByID(GVTyID);
3684fe6060f1SDimitry Andric       if (!GVTy)
368581ad6265SDimitry Andric         return error("Invalid dso_local record");
368681ad6265SDimitry Andric       V = BitcodeConstant::create(
368781ad6265SDimitry Andric           Alloc, CurTy, BitcodeConstant::DSOLocalEquivalentOpcode, Record[1]);
3688fe6060f1SDimitry Andric       break;
3689fe6060f1SDimitry Andric     }
36900eae32dcSDimitry Andric     case bitc::CST_CODE_NO_CFI_VALUE: {
36910eae32dcSDimitry Andric       if (Record.size() < 2)
369281ad6265SDimitry Andric         return error("Invalid no_cfi record");
369381ad6265SDimitry Andric       unsigned GVTyID = Record[0];
369481ad6265SDimitry Andric       Type *GVTy = getTypeByID(GVTyID);
36950eae32dcSDimitry Andric       if (!GVTy)
369681ad6265SDimitry Andric         return error("Invalid no_cfi record");
369781ad6265SDimitry Andric       V = BitcodeConstant::create(Alloc, CurTy, BitcodeConstant::NoCFIOpcode,
369881ad6265SDimitry Andric                                   Record[1]);
36990eae32dcSDimitry Andric       break;
37000eae32dcSDimitry Andric     }
3701*0fca6ea1SDimitry Andric     case bitc::CST_CODE_PTRAUTH: {
3702*0fca6ea1SDimitry Andric       if (Record.size() < 4)
3703*0fca6ea1SDimitry Andric         return error("Invalid ptrauth record");
3704*0fca6ea1SDimitry Andric       // Ptr, Key, Disc, AddrDisc
3705*0fca6ea1SDimitry Andric       V = BitcodeConstant::create(Alloc, CurTy,
3706*0fca6ea1SDimitry Andric                                   BitcodeConstant::ConstantPtrAuthOpcode,
3707*0fca6ea1SDimitry Andric                                   {(unsigned)Record[0], (unsigned)Record[1],
3708*0fca6ea1SDimitry Andric                                    (unsigned)Record[2], (unsigned)Record[3]});
3709*0fca6ea1SDimitry Andric       break;
3710*0fca6ea1SDimitry Andric     }
37110b57cec5SDimitry Andric     }
37120b57cec5SDimitry Andric 
371381ad6265SDimitry Andric     assert(V->getType() == getTypeByID(CurTyID) && "Incorrect result type ID");
371481ad6265SDimitry Andric     if (Error Err = ValueList.assignValue(NextCstNo, V, CurTyID))
371581ad6265SDimitry Andric       return Err;
37160b57cec5SDimitry Andric     ++NextCstNo;
37170b57cec5SDimitry Andric   }
37180b57cec5SDimitry Andric }
37190b57cec5SDimitry Andric 
37200b57cec5SDimitry Andric Error BitcodeReader::parseUseLists() {
37210b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
37220b57cec5SDimitry Andric     return Err;
37230b57cec5SDimitry Andric 
37240b57cec5SDimitry Andric   // Read all the records.
37250b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
37260b57cec5SDimitry Andric 
37270b57cec5SDimitry Andric   while (true) {
37280b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
37290b57cec5SDimitry Andric     if (!MaybeEntry)
37300b57cec5SDimitry Andric       return MaybeEntry.takeError();
37310b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
37320b57cec5SDimitry Andric 
37330b57cec5SDimitry Andric     switch (Entry.Kind) {
37340b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
37350b57cec5SDimitry Andric     case BitstreamEntry::Error:
37360b57cec5SDimitry Andric       return error("Malformed block");
37370b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
37380b57cec5SDimitry Andric       return Error::success();
37390b57cec5SDimitry Andric     case BitstreamEntry::Record:
37400b57cec5SDimitry Andric       // The interesting case.
37410b57cec5SDimitry Andric       break;
37420b57cec5SDimitry Andric     }
37430b57cec5SDimitry Andric 
37440b57cec5SDimitry Andric     // Read a use list record.
37450b57cec5SDimitry Andric     Record.clear();
37460b57cec5SDimitry Andric     bool IsBB = false;
37470b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
37480b57cec5SDimitry Andric     if (!MaybeRecord)
37490b57cec5SDimitry Andric       return MaybeRecord.takeError();
37500b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
37510b57cec5SDimitry Andric     default:  // Default behavior: unknown type.
37520b57cec5SDimitry Andric       break;
37530b57cec5SDimitry Andric     case bitc::USELIST_CODE_BB:
37540b57cec5SDimitry Andric       IsBB = true;
3755bdd1243dSDimitry Andric       [[fallthrough]];
37560b57cec5SDimitry Andric     case bitc::USELIST_CODE_DEFAULT: {
37570b57cec5SDimitry Andric       unsigned RecordLength = Record.size();
37580b57cec5SDimitry Andric       if (RecordLength < 3)
37590b57cec5SDimitry Andric         // Records should have at least an ID and two indexes.
37600b57cec5SDimitry Andric         return error("Invalid record");
3761e8d8bef9SDimitry Andric       unsigned ID = Record.pop_back_val();
37620b57cec5SDimitry Andric 
37630b57cec5SDimitry Andric       Value *V;
37640b57cec5SDimitry Andric       if (IsBB) {
37650b57cec5SDimitry Andric         assert(ID < FunctionBBs.size() && "Basic block not found");
37660b57cec5SDimitry Andric         V = FunctionBBs[ID];
37670b57cec5SDimitry Andric       } else
37680b57cec5SDimitry Andric         V = ValueList[ID];
37690b57cec5SDimitry Andric       unsigned NumUses = 0;
37700b57cec5SDimitry Andric       SmallDenseMap<const Use *, unsigned, 16> Order;
37710b57cec5SDimitry Andric       for (const Use &U : V->materialized_uses()) {
37720b57cec5SDimitry Andric         if (++NumUses > Record.size())
37730b57cec5SDimitry Andric           break;
37740b57cec5SDimitry Andric         Order[&U] = Record[NumUses - 1];
37750b57cec5SDimitry Andric       }
37760b57cec5SDimitry Andric       if (Order.size() != Record.size() || NumUses > Record.size())
37770b57cec5SDimitry Andric         // Mismatches can happen if the functions are being materialized lazily
37780b57cec5SDimitry Andric         // (out-of-order), or a value has been upgraded.
37790b57cec5SDimitry Andric         break;
37800b57cec5SDimitry Andric 
37810b57cec5SDimitry Andric       V->sortUseList([&](const Use &L, const Use &R) {
37820b57cec5SDimitry Andric         return Order.lookup(&L) < Order.lookup(&R);
37830b57cec5SDimitry Andric       });
37840b57cec5SDimitry Andric       break;
37850b57cec5SDimitry Andric     }
37860b57cec5SDimitry Andric     }
37870b57cec5SDimitry Andric   }
37880b57cec5SDimitry Andric }
37890b57cec5SDimitry Andric 
37900b57cec5SDimitry Andric /// When we see the block for metadata, remember where it is and then skip it.
37910b57cec5SDimitry Andric /// This lets us lazily deserialize the metadata.
37920b57cec5SDimitry Andric Error BitcodeReader::rememberAndSkipMetadata() {
37930b57cec5SDimitry Andric   // Save the current stream state.
37940b57cec5SDimitry Andric   uint64_t CurBit = Stream.GetCurrentBitNo();
37950b57cec5SDimitry Andric   DeferredMetadataInfo.push_back(CurBit);
37960b57cec5SDimitry Andric 
37970b57cec5SDimitry Andric   // Skip over the block for now.
37980b57cec5SDimitry Andric   if (Error Err = Stream.SkipBlock())
37990b57cec5SDimitry Andric     return Err;
38000b57cec5SDimitry Andric   return Error::success();
38010b57cec5SDimitry Andric }
38020b57cec5SDimitry Andric 
38030b57cec5SDimitry Andric Error BitcodeReader::materializeMetadata() {
38040b57cec5SDimitry Andric   for (uint64_t BitPos : DeferredMetadataInfo) {
38050b57cec5SDimitry Andric     // Move the bit stream to the saved position.
38060b57cec5SDimitry Andric     if (Error JumpFailed = Stream.JumpToBit(BitPos))
38070b57cec5SDimitry Andric       return JumpFailed;
38080b57cec5SDimitry Andric     if (Error Err = MDLoader->parseModuleMetadata())
38090b57cec5SDimitry Andric       return Err;
38100b57cec5SDimitry Andric   }
38110b57cec5SDimitry Andric 
38120b57cec5SDimitry Andric   // Upgrade "Linker Options" module flag to "llvm.linker.options" module-level
3813e8d8bef9SDimitry Andric   // metadata. Only upgrade if the new option doesn't exist to avoid upgrade
3814e8d8bef9SDimitry Andric   // multiple times.
3815e8d8bef9SDimitry Andric   if (!TheModule->getNamedMetadata("llvm.linker.options")) {
38160b57cec5SDimitry Andric     if (Metadata *Val = TheModule->getModuleFlag("Linker Options")) {
38170b57cec5SDimitry Andric       NamedMDNode *LinkerOpts =
38180b57cec5SDimitry Andric           TheModule->getOrInsertNamedMetadata("llvm.linker.options");
38190b57cec5SDimitry Andric       for (const MDOperand &MDOptions : cast<MDNode>(Val)->operands())
38200b57cec5SDimitry Andric         LinkerOpts->addOperand(cast<MDNode>(MDOptions));
38210b57cec5SDimitry Andric     }
3822e8d8bef9SDimitry Andric   }
38230b57cec5SDimitry Andric 
38240b57cec5SDimitry Andric   DeferredMetadataInfo.clear();
38250b57cec5SDimitry Andric   return Error::success();
38260b57cec5SDimitry Andric }
38270b57cec5SDimitry Andric 
38280b57cec5SDimitry Andric void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
38290b57cec5SDimitry Andric 
38300b57cec5SDimitry Andric /// When we see the block for a function body, remember where it is and then
38310b57cec5SDimitry Andric /// skip it.  This lets us lazily deserialize the functions.
38320b57cec5SDimitry Andric Error BitcodeReader::rememberAndSkipFunctionBody() {
38330b57cec5SDimitry Andric   // Get the function we are talking about.
38340b57cec5SDimitry Andric   if (FunctionsWithBodies.empty())
38350b57cec5SDimitry Andric     return error("Insufficient function protos");
38360b57cec5SDimitry Andric 
38370b57cec5SDimitry Andric   Function *Fn = FunctionsWithBodies.back();
38380b57cec5SDimitry Andric   FunctionsWithBodies.pop_back();
38390b57cec5SDimitry Andric 
38400b57cec5SDimitry Andric   // Save the current stream state.
38410b57cec5SDimitry Andric   uint64_t CurBit = Stream.GetCurrentBitNo();
38420b57cec5SDimitry Andric   assert(
38430b57cec5SDimitry Andric       (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
38440b57cec5SDimitry Andric       "Mismatch between VST and scanned function offsets");
38450b57cec5SDimitry Andric   DeferredFunctionInfo[Fn] = CurBit;
38460b57cec5SDimitry Andric 
38470b57cec5SDimitry Andric   // Skip over the function block for now.
38480b57cec5SDimitry Andric   if (Error Err = Stream.SkipBlock())
38490b57cec5SDimitry Andric     return Err;
38500b57cec5SDimitry Andric   return Error::success();
38510b57cec5SDimitry Andric }
38520b57cec5SDimitry Andric 
38530b57cec5SDimitry Andric Error BitcodeReader::globalCleanup() {
38540b57cec5SDimitry Andric   // Patch the initializers for globals and aliases up.
38550b57cec5SDimitry Andric   if (Error Err = resolveGlobalAndIndirectSymbolInits())
38560b57cec5SDimitry Andric     return Err;
38570b57cec5SDimitry Andric   if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
38580b57cec5SDimitry Andric     return error("Malformed global initializer set");
38590b57cec5SDimitry Andric 
38600b57cec5SDimitry Andric   // Look for intrinsic functions which need to be upgraded at some point
38615ffd83dbSDimitry Andric   // and functions that need to have their function attributes upgraded.
38620b57cec5SDimitry Andric   for (Function &F : *TheModule) {
38630b57cec5SDimitry Andric     MDLoader->upgradeDebugIntrinsics(F);
38640b57cec5SDimitry Andric     Function *NewFn;
3865*0fca6ea1SDimitry Andric     // If PreserveInputDbgFormat=true, then we don't know whether we want
3866*0fca6ea1SDimitry Andric     // intrinsics or records, and we won't perform any conversions in either
3867*0fca6ea1SDimitry Andric     // case, so don't upgrade intrinsics to records.
3868*0fca6ea1SDimitry Andric     if (UpgradeIntrinsicFunction(
3869*0fca6ea1SDimitry Andric             &F, NewFn, PreserveInputDbgFormat != cl::boolOrDefault::BOU_TRUE))
38700b57cec5SDimitry Andric       UpgradedIntrinsics[&F] = NewFn;
38715ffd83dbSDimitry Andric     // Look for functions that rely on old function attribute behavior.
38725ffd83dbSDimitry Andric     UpgradeFunctionAttributes(F);
38730b57cec5SDimitry Andric   }
38740b57cec5SDimitry Andric 
38750b57cec5SDimitry Andric   // Look for global variables which need to be renamed.
38760b57cec5SDimitry Andric   std::vector<std::pair<GlobalVariable *, GlobalVariable *>> UpgradedVariables;
38770b57cec5SDimitry Andric   for (GlobalVariable &GV : TheModule->globals())
38780b57cec5SDimitry Andric     if (GlobalVariable *Upgraded = UpgradeGlobalVariable(&GV))
38790b57cec5SDimitry Andric       UpgradedVariables.emplace_back(&GV, Upgraded);
38800b57cec5SDimitry Andric   for (auto &Pair : UpgradedVariables) {
38810b57cec5SDimitry Andric     Pair.first->eraseFromParent();
388206c3fb27SDimitry Andric     TheModule->insertGlobalVariable(Pair.second);
38830b57cec5SDimitry Andric   }
38840b57cec5SDimitry Andric 
38850b57cec5SDimitry Andric   // Force deallocation of memory for these vectors to favor the client that
38860b57cec5SDimitry Andric   // want lazy deserialization.
38870b57cec5SDimitry Andric   std::vector<std::pair<GlobalVariable *, unsigned>>().swap(GlobalInits);
3888349cc55cSDimitry Andric   std::vector<std::pair<GlobalValue *, unsigned>>().swap(IndirectSymbolInits);
38890b57cec5SDimitry Andric   return Error::success();
38900b57cec5SDimitry Andric }
38910b57cec5SDimitry Andric 
38920b57cec5SDimitry Andric /// Support for lazy parsing of function bodies. This is required if we
38930b57cec5SDimitry Andric /// either have an old bitcode file without a VST forward declaration record,
38940b57cec5SDimitry Andric /// or if we have an anonymous function being materialized, since anonymous
38950b57cec5SDimitry Andric /// functions do not have a name and are therefore not in the VST.
38960b57cec5SDimitry Andric Error BitcodeReader::rememberAndSkipFunctionBodies() {
38970b57cec5SDimitry Andric   if (Error JumpFailed = Stream.JumpToBit(NextUnreadBit))
38980b57cec5SDimitry Andric     return JumpFailed;
38990b57cec5SDimitry Andric 
39000b57cec5SDimitry Andric   if (Stream.AtEndOfStream())
39010b57cec5SDimitry Andric     return error("Could not find function in stream");
39020b57cec5SDimitry Andric 
39030b57cec5SDimitry Andric   if (!SeenFirstFunctionBody)
39040b57cec5SDimitry Andric     return error("Trying to materialize functions before seeing function blocks");
39050b57cec5SDimitry Andric 
39060b57cec5SDimitry Andric   // An old bitcode file with the symbol table at the end would have
39070b57cec5SDimitry Andric   // finished the parse greedily.
39080b57cec5SDimitry Andric   assert(SeenValueSymbolTable);
39090b57cec5SDimitry Andric 
39100b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
39110b57cec5SDimitry Andric 
39120b57cec5SDimitry Andric   while (true) {
39130b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
39140b57cec5SDimitry Andric     if (!MaybeEntry)
39150b57cec5SDimitry Andric       return MaybeEntry.takeError();
39160b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
39170b57cec5SDimitry Andric 
39180b57cec5SDimitry Andric     switch (Entry.Kind) {
39190b57cec5SDimitry Andric     default:
39200b57cec5SDimitry Andric       return error("Expect SubBlock");
39210b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
39220b57cec5SDimitry Andric       switch (Entry.ID) {
39230b57cec5SDimitry Andric       default:
39240b57cec5SDimitry Andric         return error("Expect function block");
39250b57cec5SDimitry Andric       case bitc::FUNCTION_BLOCK_ID:
39260b57cec5SDimitry Andric         if (Error Err = rememberAndSkipFunctionBody())
39270b57cec5SDimitry Andric           return Err;
39280b57cec5SDimitry Andric         NextUnreadBit = Stream.GetCurrentBitNo();
39290b57cec5SDimitry Andric         return Error::success();
39300b57cec5SDimitry Andric       }
39310b57cec5SDimitry Andric     }
39320b57cec5SDimitry Andric   }
39330b57cec5SDimitry Andric }
39340b57cec5SDimitry Andric 
393581ad6265SDimitry Andric Error BitcodeReaderBase::readBlockInfo() {
3936bdd1243dSDimitry Andric   Expected<std::optional<BitstreamBlockInfo>> MaybeNewBlockInfo =
39370b57cec5SDimitry Andric       Stream.ReadBlockInfoBlock();
39380b57cec5SDimitry Andric   if (!MaybeNewBlockInfo)
393981ad6265SDimitry Andric     return MaybeNewBlockInfo.takeError();
3940bdd1243dSDimitry Andric   std::optional<BitstreamBlockInfo> NewBlockInfo =
39410b57cec5SDimitry Andric       std::move(MaybeNewBlockInfo.get());
39420b57cec5SDimitry Andric   if (!NewBlockInfo)
394381ad6265SDimitry Andric     return error("Malformed block");
39440b57cec5SDimitry Andric   BlockInfo = std::move(*NewBlockInfo);
394581ad6265SDimitry Andric   return Error::success();
39460b57cec5SDimitry Andric }
39470b57cec5SDimitry Andric 
39480b57cec5SDimitry Andric Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) {
39490b57cec5SDimitry Andric   // v1: [selection_kind, name]
39500b57cec5SDimitry Andric   // v2: [strtab_offset, strtab_size, selection_kind]
39510b57cec5SDimitry Andric   StringRef Name;
39520b57cec5SDimitry Andric   std::tie(Name, Record) = readNameFromStrtab(Record);
39530b57cec5SDimitry Andric 
39540b57cec5SDimitry Andric   if (Record.empty())
39550b57cec5SDimitry Andric     return error("Invalid record");
39560b57cec5SDimitry Andric   Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
39570b57cec5SDimitry Andric   std::string OldFormatName;
39580b57cec5SDimitry Andric   if (!UseStrtab) {
39590b57cec5SDimitry Andric     if (Record.size() < 2)
39600b57cec5SDimitry Andric       return error("Invalid record");
39610b57cec5SDimitry Andric     unsigned ComdatNameSize = Record[1];
396281ad6265SDimitry Andric     if (ComdatNameSize > Record.size() - 2)
396381ad6265SDimitry Andric       return error("Comdat name size too large");
39640b57cec5SDimitry Andric     OldFormatName.reserve(ComdatNameSize);
39650b57cec5SDimitry Andric     for (unsigned i = 0; i != ComdatNameSize; ++i)
39660b57cec5SDimitry Andric       OldFormatName += (char)Record[2 + i];
39670b57cec5SDimitry Andric     Name = OldFormatName;
39680b57cec5SDimitry Andric   }
39690b57cec5SDimitry Andric   Comdat *C = TheModule->getOrInsertComdat(Name);
39700b57cec5SDimitry Andric   C->setSelectionKind(SK);
39710b57cec5SDimitry Andric   ComdatList.push_back(C);
39720b57cec5SDimitry Andric   return Error::success();
39730b57cec5SDimitry Andric }
39740b57cec5SDimitry Andric 
39750b57cec5SDimitry Andric static void inferDSOLocal(GlobalValue *GV) {
39760b57cec5SDimitry Andric   // infer dso_local from linkage and visibility if it is not encoded.
39770b57cec5SDimitry Andric   if (GV->hasLocalLinkage() ||
39780b57cec5SDimitry Andric       (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage()))
39790b57cec5SDimitry Andric     GV->setDSOLocal(true);
39800b57cec5SDimitry Andric }
39810b57cec5SDimitry Andric 
398281ad6265SDimitry Andric GlobalValue::SanitizerMetadata deserializeSanitizerMetadata(unsigned V) {
398381ad6265SDimitry Andric   GlobalValue::SanitizerMetadata Meta;
398481ad6265SDimitry Andric   if (V & (1 << 0))
398581ad6265SDimitry Andric     Meta.NoAddress = true;
398681ad6265SDimitry Andric   if (V & (1 << 1))
398781ad6265SDimitry Andric     Meta.NoHWAddress = true;
398881ad6265SDimitry Andric   if (V & (1 << 2))
3989753f127fSDimitry Andric     Meta.Memtag = true;
399081ad6265SDimitry Andric   if (V & (1 << 3))
399181ad6265SDimitry Andric     Meta.IsDynInit = true;
399281ad6265SDimitry Andric   return Meta;
399381ad6265SDimitry Andric }
399481ad6265SDimitry Andric 
39950b57cec5SDimitry Andric Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) {
39960b57cec5SDimitry Andric   // v1: [pointer type, isconst, initid, linkage, alignment, section,
39970b57cec5SDimitry Andric   // visibility, threadlocal, unnamed_addr, externally_initialized,
39980b57cec5SDimitry Andric   // dllstorageclass, comdat, attributes, preemption specifier,
39990b57cec5SDimitry Andric   // partition strtab offset, partition strtab size] (name in VST)
40000b57cec5SDimitry Andric   // v2: [strtab_offset, strtab_size, v1]
40015f757f3fSDimitry Andric   // v3: [v2, code_model]
40020b57cec5SDimitry Andric   StringRef Name;
40030b57cec5SDimitry Andric   std::tie(Name, Record) = readNameFromStrtab(Record);
40040b57cec5SDimitry Andric 
40050b57cec5SDimitry Andric   if (Record.size() < 6)
40060b57cec5SDimitry Andric     return error("Invalid record");
400781ad6265SDimitry Andric   unsigned TyID = Record[0];
400881ad6265SDimitry Andric   Type *Ty = getTypeByID(TyID);
40090b57cec5SDimitry Andric   if (!Ty)
40100b57cec5SDimitry Andric     return error("Invalid record");
40110b57cec5SDimitry Andric   bool isConstant = Record[1] & 1;
40120b57cec5SDimitry Andric   bool explicitType = Record[1] & 2;
40130b57cec5SDimitry Andric   unsigned AddressSpace;
40140b57cec5SDimitry Andric   if (explicitType) {
40150b57cec5SDimitry Andric     AddressSpace = Record[1] >> 2;
40160b57cec5SDimitry Andric   } else {
40170b57cec5SDimitry Andric     if (!Ty->isPointerTy())
40180b57cec5SDimitry Andric       return error("Invalid type for value");
40190b57cec5SDimitry Andric     AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
402081ad6265SDimitry Andric     TyID = getContainedTypeID(TyID);
402181ad6265SDimitry Andric     Ty = getTypeByID(TyID);
402281ad6265SDimitry Andric     if (!Ty)
402381ad6265SDimitry Andric       return error("Missing element type for old-style global");
40240b57cec5SDimitry Andric   }
40250b57cec5SDimitry Andric 
40260b57cec5SDimitry Andric   uint64_t RawLinkage = Record[3];
40270b57cec5SDimitry Andric   GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
40288bcb0991SDimitry Andric   MaybeAlign Alignment;
40290b57cec5SDimitry Andric   if (Error Err = parseAlignmentValue(Record[4], Alignment))
40300b57cec5SDimitry Andric     return Err;
40310b57cec5SDimitry Andric   std::string Section;
40320b57cec5SDimitry Andric   if (Record[5]) {
40330b57cec5SDimitry Andric     if (Record[5] - 1 >= SectionTable.size())
40340b57cec5SDimitry Andric       return error("Invalid ID");
40350b57cec5SDimitry Andric     Section = SectionTable[Record[5] - 1];
40360b57cec5SDimitry Andric   }
40370b57cec5SDimitry Andric   GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
40380b57cec5SDimitry Andric   // Local linkage must have default visibility.
40395ffd83dbSDimitry Andric   // auto-upgrade `hidden` and `protected` for old bitcode.
40400b57cec5SDimitry Andric   if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
40410b57cec5SDimitry Andric     Visibility = getDecodedVisibility(Record[6]);
40420b57cec5SDimitry Andric 
40430b57cec5SDimitry Andric   GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
40440b57cec5SDimitry Andric   if (Record.size() > 7)
40450b57cec5SDimitry Andric     TLM = getDecodedThreadLocalMode(Record[7]);
40460b57cec5SDimitry Andric 
40470b57cec5SDimitry Andric   GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
40480b57cec5SDimitry Andric   if (Record.size() > 8)
40490b57cec5SDimitry Andric     UnnamedAddr = getDecodedUnnamedAddrType(Record[8]);
40500b57cec5SDimitry Andric 
40510b57cec5SDimitry Andric   bool ExternallyInitialized = false;
40520b57cec5SDimitry Andric   if (Record.size() > 9)
40530b57cec5SDimitry Andric     ExternallyInitialized = Record[9];
40540b57cec5SDimitry Andric 
40550b57cec5SDimitry Andric   GlobalVariable *NewGV =
40560b57cec5SDimitry Andric       new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, Name,
40570b57cec5SDimitry Andric                          nullptr, TLM, AddressSpace, ExternallyInitialized);
405806c3fb27SDimitry Andric   if (Alignment)
405906c3fb27SDimitry Andric     NewGV->setAlignment(*Alignment);
40600b57cec5SDimitry Andric   if (!Section.empty())
40610b57cec5SDimitry Andric     NewGV->setSection(Section);
40620b57cec5SDimitry Andric   NewGV->setVisibility(Visibility);
40630b57cec5SDimitry Andric   NewGV->setUnnamedAddr(UnnamedAddr);
40640b57cec5SDimitry Andric 
4065bdd1243dSDimitry Andric   if (Record.size() > 10) {
4066bdd1243dSDimitry Andric     // A GlobalValue with local linkage cannot have a DLL storage class.
4067bdd1243dSDimitry Andric     if (!NewGV->hasLocalLinkage()) {
40680b57cec5SDimitry Andric       NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
4069bdd1243dSDimitry Andric     }
4070bdd1243dSDimitry Andric   } else {
40710b57cec5SDimitry Andric     upgradeDLLImportExportLinkage(NewGV, RawLinkage);
4072bdd1243dSDimitry Andric   }
40730b57cec5SDimitry Andric 
407481ad6265SDimitry Andric   ValueList.push_back(NewGV, getVirtualTypeID(NewGV->getType(), TyID));
40750b57cec5SDimitry Andric 
40760b57cec5SDimitry Andric   // Remember which value to use for the global initializer.
40770b57cec5SDimitry Andric   if (unsigned InitID = Record[2])
40780b57cec5SDimitry Andric     GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));
40790b57cec5SDimitry Andric 
40800b57cec5SDimitry Andric   if (Record.size() > 11) {
40810b57cec5SDimitry Andric     if (unsigned ComdatID = Record[11]) {
40820b57cec5SDimitry Andric       if (ComdatID > ComdatList.size())
40830b57cec5SDimitry Andric         return error("Invalid global variable comdat ID");
40840b57cec5SDimitry Andric       NewGV->setComdat(ComdatList[ComdatID - 1]);
40850b57cec5SDimitry Andric     }
40860b57cec5SDimitry Andric   } else if (hasImplicitComdat(RawLinkage)) {
40870eae32dcSDimitry Andric     ImplicitComdatObjects.insert(NewGV);
40880b57cec5SDimitry Andric   }
40890b57cec5SDimitry Andric 
40900b57cec5SDimitry Andric   if (Record.size() > 12) {
4091349cc55cSDimitry Andric     auto AS = getAttributes(Record[12]).getFnAttrs();
40920b57cec5SDimitry Andric     NewGV->setAttributes(AS);
40930b57cec5SDimitry Andric   }
40940b57cec5SDimitry Andric 
40950b57cec5SDimitry Andric   if (Record.size() > 13) {
40960b57cec5SDimitry Andric     NewGV->setDSOLocal(getDecodedDSOLocal(Record[13]));
40970b57cec5SDimitry Andric   }
40980b57cec5SDimitry Andric   inferDSOLocal(NewGV);
40990b57cec5SDimitry Andric 
41000b57cec5SDimitry Andric   // Check whether we have enough values to read a partition name.
41010b57cec5SDimitry Andric   if (Record.size() > 15)
41020b57cec5SDimitry Andric     NewGV->setPartition(StringRef(Strtab.data() + Record[14], Record[15]));
41030b57cec5SDimitry Andric 
410481ad6265SDimitry Andric   if (Record.size() > 16 && Record[16]) {
410581ad6265SDimitry Andric     llvm::GlobalValue::SanitizerMetadata Meta =
410681ad6265SDimitry Andric         deserializeSanitizerMetadata(Record[16]);
410781ad6265SDimitry Andric     NewGV->setSanitizerMetadata(Meta);
410881ad6265SDimitry Andric   }
410981ad6265SDimitry Andric 
41105f757f3fSDimitry Andric   if (Record.size() > 17 && Record[17]) {
41115f757f3fSDimitry Andric     if (auto CM = getDecodedCodeModel(Record[17]))
41125f757f3fSDimitry Andric       NewGV->setCodeModel(*CM);
41135f757f3fSDimitry Andric     else
41145f757f3fSDimitry Andric       return error("Invalid global variable code model");
41155f757f3fSDimitry Andric   }
41165f757f3fSDimitry Andric 
41170b57cec5SDimitry Andric   return Error::success();
41180b57cec5SDimitry Andric }
41190b57cec5SDimitry Andric 
4120bdd1243dSDimitry Andric void BitcodeReader::callValueTypeCallback(Value *F, unsigned TypeID) {
4121bdd1243dSDimitry Andric   if (ValueTypeCallback) {
4122bdd1243dSDimitry Andric     (*ValueTypeCallback)(
4123bdd1243dSDimitry Andric         F, TypeID, [this](unsigned I) { return getTypeByID(I); },
4124bdd1243dSDimitry Andric         [this](unsigned I, unsigned J) { return getContainedTypeID(I, J); });
4125bdd1243dSDimitry Andric   }
4126bdd1243dSDimitry Andric }
4127bdd1243dSDimitry Andric 
41280b57cec5SDimitry Andric Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) {
41290b57cec5SDimitry Andric   // v1: [type, callingconv, isproto, linkage, paramattr, alignment, section,
41300b57cec5SDimitry Andric   // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat,
41310b57cec5SDimitry Andric   // prefixdata,  personalityfn, preemption specifier, addrspace] (name in VST)
41320b57cec5SDimitry Andric   // v2: [strtab_offset, strtab_size, v1]
41330b57cec5SDimitry Andric   StringRef Name;
41340b57cec5SDimitry Andric   std::tie(Name, Record) = readNameFromStrtab(Record);
41350b57cec5SDimitry Andric 
41360b57cec5SDimitry Andric   if (Record.size() < 8)
41370b57cec5SDimitry Andric     return error("Invalid record");
413881ad6265SDimitry Andric   unsigned FTyID = Record[0];
413981ad6265SDimitry Andric   Type *FTy = getTypeByID(FTyID);
41400b57cec5SDimitry Andric   if (!FTy)
41410b57cec5SDimitry Andric     return error("Invalid record");
414281ad6265SDimitry Andric   if (isa<PointerType>(FTy)) {
414381ad6265SDimitry Andric     FTyID = getContainedTypeID(FTyID, 0);
414481ad6265SDimitry Andric     FTy = getTypeByID(FTyID);
414581ad6265SDimitry Andric     if (!FTy)
414681ad6265SDimitry Andric       return error("Missing element type for old-style function");
414781ad6265SDimitry Andric   }
41480b57cec5SDimitry Andric 
41490b57cec5SDimitry Andric   if (!isa<FunctionType>(FTy))
41500b57cec5SDimitry Andric     return error("Invalid type for value");
41510b57cec5SDimitry Andric   auto CC = static_cast<CallingConv::ID>(Record[1]);
41520b57cec5SDimitry Andric   if (CC & ~CallingConv::MaxID)
41530b57cec5SDimitry Andric     return error("Invalid calling convention ID");
41540b57cec5SDimitry Andric 
41550b57cec5SDimitry Andric   unsigned AddrSpace = TheModule->getDataLayout().getProgramAddressSpace();
41560b57cec5SDimitry Andric   if (Record.size() > 16)
41570b57cec5SDimitry Andric     AddrSpace = Record[16];
41580b57cec5SDimitry Andric 
41590b57cec5SDimitry Andric   Function *Func =
41600b57cec5SDimitry Andric       Function::Create(cast<FunctionType>(FTy), GlobalValue::ExternalLinkage,
41610b57cec5SDimitry Andric                        AddrSpace, Name, TheModule);
41620b57cec5SDimitry Andric 
4163fe6060f1SDimitry Andric   assert(Func->getFunctionType() == FTy &&
41640b57cec5SDimitry Andric          "Incorrect fully specified type provided for function");
416581ad6265SDimitry Andric   FunctionTypeIDs[Func] = FTyID;
41660b57cec5SDimitry Andric 
41670b57cec5SDimitry Andric   Func->setCallingConv(CC);
41680b57cec5SDimitry Andric   bool isProto = Record[2];
41690b57cec5SDimitry Andric   uint64_t RawLinkage = Record[3];
41700b57cec5SDimitry Andric   Func->setLinkage(getDecodedLinkage(RawLinkage));
41710b57cec5SDimitry Andric   Func->setAttributes(getAttributes(Record[4]));
4172bdd1243dSDimitry Andric   callValueTypeCallback(Func, FTyID);
41730b57cec5SDimitry Andric 
4174e8d8bef9SDimitry Andric   // Upgrade any old-style byval or sret without a type by propagating the
4175e8d8bef9SDimitry Andric   // argument's pointee type. There should be no opaque pointers where the byval
4176e8d8bef9SDimitry Andric   // type is implicit.
41770b57cec5SDimitry Andric   for (unsigned i = 0; i != Func->arg_size(); ++i) {
4178fe6060f1SDimitry Andric     for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
4179fe6060f1SDimitry Andric                                      Attribute::InAlloca}) {
4180e8d8bef9SDimitry Andric       if (!Func->hasParamAttribute(i, Kind))
41810b57cec5SDimitry Andric         continue;
41820b57cec5SDimitry Andric 
4183fe6060f1SDimitry Andric       if (Func->getParamAttribute(i, Kind).getValueAsType())
4184fe6060f1SDimitry Andric         continue;
4185fe6060f1SDimitry Andric 
4186e8d8bef9SDimitry Andric       Func->removeParamAttr(i, Kind);
4187e8d8bef9SDimitry Andric 
418881ad6265SDimitry Andric       unsigned ParamTypeID = getContainedTypeID(FTyID, i + 1);
418981ad6265SDimitry Andric       Type *PtrEltTy = getPtrElementTypeByID(ParamTypeID);
419081ad6265SDimitry Andric       if (!PtrEltTy)
419181ad6265SDimitry Andric         return error("Missing param element type for attribute upgrade");
419281ad6265SDimitry Andric 
4193fe6060f1SDimitry Andric       Attribute NewAttr;
4194fe6060f1SDimitry Andric       switch (Kind) {
4195fe6060f1SDimitry Andric       case Attribute::ByVal:
4196fe6060f1SDimitry Andric         NewAttr = Attribute::getWithByValType(Context, PtrEltTy);
4197fe6060f1SDimitry Andric         break;
4198fe6060f1SDimitry Andric       case Attribute::StructRet:
4199fe6060f1SDimitry Andric         NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy);
4200fe6060f1SDimitry Andric         break;
4201fe6060f1SDimitry Andric       case Attribute::InAlloca:
4202fe6060f1SDimitry Andric         NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy);
4203fe6060f1SDimitry Andric         break;
4204fe6060f1SDimitry Andric       default:
4205fe6060f1SDimitry Andric         llvm_unreachable("not an upgraded type attribute");
4206fe6060f1SDimitry Andric       }
4207fe6060f1SDimitry Andric 
4208e8d8bef9SDimitry Andric       Func->addParamAttr(i, NewAttr);
4209e8d8bef9SDimitry Andric     }
42100b57cec5SDimitry Andric   }
42110b57cec5SDimitry Andric 
421281ad6265SDimitry Andric   if (Func->getCallingConv() == CallingConv::X86_INTR &&
421381ad6265SDimitry Andric       !Func->arg_empty() && !Func->hasParamAttribute(0, Attribute::ByVal)) {
421481ad6265SDimitry Andric     unsigned ParamTypeID = getContainedTypeID(FTyID, 1);
421581ad6265SDimitry Andric     Type *ByValTy = getPtrElementTypeByID(ParamTypeID);
421681ad6265SDimitry Andric     if (!ByValTy)
421781ad6265SDimitry Andric       return error("Missing param element type for x86_intrcc upgrade");
421881ad6265SDimitry Andric     Attribute NewAttr = Attribute::getWithByValType(Context, ByValTy);
421981ad6265SDimitry Andric     Func->addParamAttr(0, NewAttr);
422081ad6265SDimitry Andric   }
422181ad6265SDimitry Andric 
42228bcb0991SDimitry Andric   MaybeAlign Alignment;
42230b57cec5SDimitry Andric   if (Error Err = parseAlignmentValue(Record[5], Alignment))
42240b57cec5SDimitry Andric     return Err;
422506c3fb27SDimitry Andric   if (Alignment)
422606c3fb27SDimitry Andric     Func->setAlignment(*Alignment);
42270b57cec5SDimitry Andric   if (Record[6]) {
42280b57cec5SDimitry Andric     if (Record[6] - 1 >= SectionTable.size())
42290b57cec5SDimitry Andric       return error("Invalid ID");
42300b57cec5SDimitry Andric     Func->setSection(SectionTable[Record[6] - 1]);
42310b57cec5SDimitry Andric   }
42320b57cec5SDimitry Andric   // Local linkage must have default visibility.
42335ffd83dbSDimitry Andric   // auto-upgrade `hidden` and `protected` for old bitcode.
42340b57cec5SDimitry Andric   if (!Func->hasLocalLinkage())
42350b57cec5SDimitry Andric     Func->setVisibility(getDecodedVisibility(Record[7]));
42360b57cec5SDimitry Andric   if (Record.size() > 8 && Record[8]) {
42370b57cec5SDimitry Andric     if (Record[8] - 1 >= GCTable.size())
42380b57cec5SDimitry Andric       return error("Invalid ID");
42390b57cec5SDimitry Andric     Func->setGC(GCTable[Record[8] - 1]);
42400b57cec5SDimitry Andric   }
42410b57cec5SDimitry Andric   GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
42420b57cec5SDimitry Andric   if (Record.size() > 9)
42430b57cec5SDimitry Andric     UnnamedAddr = getDecodedUnnamedAddrType(Record[9]);
42440b57cec5SDimitry Andric   Func->setUnnamedAddr(UnnamedAddr);
4245349cc55cSDimitry Andric 
4246349cc55cSDimitry Andric   FunctionOperandInfo OperandInfo = {Func, 0, 0, 0};
4247349cc55cSDimitry Andric   if (Record.size() > 10)
4248349cc55cSDimitry Andric     OperandInfo.Prologue = Record[10];
42490b57cec5SDimitry Andric 
4250bdd1243dSDimitry Andric   if (Record.size() > 11) {
4251bdd1243dSDimitry Andric     // A GlobalValue with local linkage cannot have a DLL storage class.
4252bdd1243dSDimitry Andric     if (!Func->hasLocalLinkage()) {
42530b57cec5SDimitry Andric       Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
4254bdd1243dSDimitry Andric     }
4255bdd1243dSDimitry Andric   } else {
42560b57cec5SDimitry Andric     upgradeDLLImportExportLinkage(Func, RawLinkage);
4257bdd1243dSDimitry Andric   }
42580b57cec5SDimitry Andric 
42590b57cec5SDimitry Andric   if (Record.size() > 12) {
42600b57cec5SDimitry Andric     if (unsigned ComdatID = Record[12]) {
42610b57cec5SDimitry Andric       if (ComdatID > ComdatList.size())
42620b57cec5SDimitry Andric         return error("Invalid function comdat ID");
42630b57cec5SDimitry Andric       Func->setComdat(ComdatList[ComdatID - 1]);
42640b57cec5SDimitry Andric     }
42650b57cec5SDimitry Andric   } else if (hasImplicitComdat(RawLinkage)) {
42660eae32dcSDimitry Andric     ImplicitComdatObjects.insert(Func);
42670b57cec5SDimitry Andric   }
42680b57cec5SDimitry Andric 
4269349cc55cSDimitry Andric   if (Record.size() > 13)
4270349cc55cSDimitry Andric     OperandInfo.Prefix = Record[13];
42710b57cec5SDimitry Andric 
4272349cc55cSDimitry Andric   if (Record.size() > 14)
4273349cc55cSDimitry Andric     OperandInfo.PersonalityFn = Record[14];
42740b57cec5SDimitry Andric 
42750b57cec5SDimitry Andric   if (Record.size() > 15) {
42760b57cec5SDimitry Andric     Func->setDSOLocal(getDecodedDSOLocal(Record[15]));
42770b57cec5SDimitry Andric   }
42780b57cec5SDimitry Andric   inferDSOLocal(Func);
42790b57cec5SDimitry Andric 
42800b57cec5SDimitry Andric   // Record[16] is the address space number.
42810b57cec5SDimitry Andric 
4282fe6060f1SDimitry Andric   // Check whether we have enough values to read a partition name. Also make
4283fe6060f1SDimitry Andric   // sure Strtab has enough values.
4284fe6060f1SDimitry Andric   if (Record.size() > 18 && Strtab.data() &&
4285fe6060f1SDimitry Andric       Record[17] + Record[18] <= Strtab.size()) {
42860b57cec5SDimitry Andric     Func->setPartition(StringRef(Strtab.data() + Record[17], Record[18]));
4287fe6060f1SDimitry Andric   }
42880b57cec5SDimitry Andric 
428981ad6265SDimitry Andric   ValueList.push_back(Func, getVirtualTypeID(Func->getType(), FTyID));
42900b57cec5SDimitry Andric 
4291349cc55cSDimitry Andric   if (OperandInfo.PersonalityFn || OperandInfo.Prefix || OperandInfo.Prologue)
4292349cc55cSDimitry Andric     FunctionOperands.push_back(OperandInfo);
4293349cc55cSDimitry Andric 
42940b57cec5SDimitry Andric   // If this is a function with a body, remember the prototype we are
42950b57cec5SDimitry Andric   // creating now, so that we can match up the body with them later.
42960b57cec5SDimitry Andric   if (!isProto) {
42970b57cec5SDimitry Andric     Func->setIsMaterializable(true);
42980b57cec5SDimitry Andric     FunctionsWithBodies.push_back(Func);
42990b57cec5SDimitry Andric     DeferredFunctionInfo[Func] = 0;
43000b57cec5SDimitry Andric   }
43010b57cec5SDimitry Andric   return Error::success();
43020b57cec5SDimitry Andric }
43030b57cec5SDimitry Andric 
43040b57cec5SDimitry Andric Error BitcodeReader::parseGlobalIndirectSymbolRecord(
43050b57cec5SDimitry Andric     unsigned BitCode, ArrayRef<uint64_t> Record) {
43060b57cec5SDimitry Andric   // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST)
43070b57cec5SDimitry Andric   // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
43080b57cec5SDimitry Andric   // dllstorageclass, threadlocal, unnamed_addr,
43090b57cec5SDimitry Andric   // preemption specifier] (name in VST)
43100b57cec5SDimitry Andric   // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage,
43110b57cec5SDimitry Andric   // visibility, dllstorageclass, threadlocal, unnamed_addr,
43120b57cec5SDimitry Andric   // preemption specifier] (name in VST)
43130b57cec5SDimitry Andric   // v2: [strtab_offset, strtab_size, v1]
43140b57cec5SDimitry Andric   StringRef Name;
43150b57cec5SDimitry Andric   std::tie(Name, Record) = readNameFromStrtab(Record);
43160b57cec5SDimitry Andric 
43170b57cec5SDimitry Andric   bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
43180b57cec5SDimitry Andric   if (Record.size() < (3 + (unsigned)NewRecord))
43190b57cec5SDimitry Andric     return error("Invalid record");
43200b57cec5SDimitry Andric   unsigned OpNum = 0;
432181ad6265SDimitry Andric   unsigned TypeID = Record[OpNum++];
432281ad6265SDimitry Andric   Type *Ty = getTypeByID(TypeID);
43230b57cec5SDimitry Andric   if (!Ty)
43240b57cec5SDimitry Andric     return error("Invalid record");
43250b57cec5SDimitry Andric 
43260b57cec5SDimitry Andric   unsigned AddrSpace;
43270b57cec5SDimitry Andric   if (!NewRecord) {
43280b57cec5SDimitry Andric     auto *PTy = dyn_cast<PointerType>(Ty);
43290b57cec5SDimitry Andric     if (!PTy)
43300b57cec5SDimitry Andric       return error("Invalid type for value");
43310b57cec5SDimitry Andric     AddrSpace = PTy->getAddressSpace();
433281ad6265SDimitry Andric     TypeID = getContainedTypeID(TypeID);
433381ad6265SDimitry Andric     Ty = getTypeByID(TypeID);
433481ad6265SDimitry Andric     if (!Ty)
433581ad6265SDimitry Andric       return error("Missing element type for old-style indirect symbol");
43360b57cec5SDimitry Andric   } else {
43370b57cec5SDimitry Andric     AddrSpace = Record[OpNum++];
43380b57cec5SDimitry Andric   }
43390b57cec5SDimitry Andric 
43400b57cec5SDimitry Andric   auto Val = Record[OpNum++];
43410b57cec5SDimitry Andric   auto Linkage = Record[OpNum++];
4342349cc55cSDimitry Andric   GlobalValue *NewGA;
43430b57cec5SDimitry Andric   if (BitCode == bitc::MODULE_CODE_ALIAS ||
43440b57cec5SDimitry Andric       BitCode == bitc::MODULE_CODE_ALIAS_OLD)
43450b57cec5SDimitry Andric     NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
43460b57cec5SDimitry Andric                                 TheModule);
43470b57cec5SDimitry Andric   else
43480b57cec5SDimitry Andric     NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
43490b57cec5SDimitry Andric                                 nullptr, TheModule);
43500b57cec5SDimitry Andric 
43510b57cec5SDimitry Andric   // Local linkage must have default visibility.
43525ffd83dbSDimitry Andric   // auto-upgrade `hidden` and `protected` for old bitcode.
43530b57cec5SDimitry Andric   if (OpNum != Record.size()) {
43540b57cec5SDimitry Andric     auto VisInd = OpNum++;
43550b57cec5SDimitry Andric     if (!NewGA->hasLocalLinkage())
43560b57cec5SDimitry Andric       NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
43570b57cec5SDimitry Andric   }
43580b57cec5SDimitry Andric   if (BitCode == bitc::MODULE_CODE_ALIAS ||
43590b57cec5SDimitry Andric       BitCode == bitc::MODULE_CODE_ALIAS_OLD) {
4360bdd1243dSDimitry Andric     if (OpNum != Record.size()) {
4361bdd1243dSDimitry Andric       auto S = Record[OpNum++];
4362bdd1243dSDimitry Andric       // A GlobalValue with local linkage cannot have a DLL storage class.
4363bdd1243dSDimitry Andric       if (!NewGA->hasLocalLinkage())
4364bdd1243dSDimitry Andric         NewGA->setDLLStorageClass(getDecodedDLLStorageClass(S));
4365bdd1243dSDimitry Andric     }
43660b57cec5SDimitry Andric     else
43670b57cec5SDimitry Andric       upgradeDLLImportExportLinkage(NewGA, Linkage);
43680b57cec5SDimitry Andric     if (OpNum != Record.size())
43690b57cec5SDimitry Andric       NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
43700b57cec5SDimitry Andric     if (OpNum != Record.size())
43710b57cec5SDimitry Andric       NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++]));
43720b57cec5SDimitry Andric   }
43730b57cec5SDimitry Andric   if (OpNum != Record.size())
43740b57cec5SDimitry Andric     NewGA->setDSOLocal(getDecodedDSOLocal(Record[OpNum++]));
43750b57cec5SDimitry Andric   inferDSOLocal(NewGA);
43760b57cec5SDimitry Andric 
43770b57cec5SDimitry Andric   // Check whether we have enough values to read a partition name.
43780b57cec5SDimitry Andric   if (OpNum + 1 < Record.size()) {
4379647cbc5dSDimitry Andric     // Check Strtab has enough values for the partition.
4380647cbc5dSDimitry Andric     if (Record[OpNum] + Record[OpNum + 1] > Strtab.size())
4381647cbc5dSDimitry Andric       return error("Malformed partition, too large.");
43820b57cec5SDimitry Andric     NewGA->setPartition(
43830b57cec5SDimitry Andric         StringRef(Strtab.data() + Record[OpNum], Record[OpNum + 1]));
43840b57cec5SDimitry Andric   }
43850b57cec5SDimitry Andric 
438681ad6265SDimitry Andric   ValueList.push_back(NewGA, getVirtualTypeID(NewGA->getType(), TypeID));
43870b57cec5SDimitry Andric   IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
43880b57cec5SDimitry Andric   return Error::success();
43890b57cec5SDimitry Andric }
43900b57cec5SDimitry Andric 
43910b57cec5SDimitry Andric Error BitcodeReader::parseModule(uint64_t ResumeBit,
43925ffd83dbSDimitry Andric                                  bool ShouldLazyLoadMetadata,
4393bdd1243dSDimitry Andric                                  ParserCallbacks Callbacks) {
4394*0fca6ea1SDimitry Andric   // Load directly into RemoveDIs format if LoadBitcodeIntoNewDbgInfoFormat
4395*0fca6ea1SDimitry Andric   // has been set to true and we aren't attempting to preserve the existing
4396*0fca6ea1SDimitry Andric   // format in the bitcode (default action: load into the old debug format).
4397*0fca6ea1SDimitry Andric   if (PreserveInputDbgFormat != cl::boolOrDefault::BOU_TRUE) {
4398*0fca6ea1SDimitry Andric     TheModule->IsNewDbgInfoFormat =
4399*0fca6ea1SDimitry Andric         UseNewDbgInfoFormat &&
4400*0fca6ea1SDimitry Andric         LoadBitcodeIntoNewDbgInfoFormat != cl::boolOrDefault::BOU_FALSE;
4401*0fca6ea1SDimitry Andric   }
4402*0fca6ea1SDimitry Andric 
4403bdd1243dSDimitry Andric   this->ValueTypeCallback = std::move(Callbacks.ValueType);
44040b57cec5SDimitry Andric   if (ResumeBit) {
44050b57cec5SDimitry Andric     if (Error JumpFailed = Stream.JumpToBit(ResumeBit))
44060b57cec5SDimitry Andric       return JumpFailed;
44070b57cec5SDimitry Andric   } else if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
44080b57cec5SDimitry Andric     return Err;
44090b57cec5SDimitry Andric 
44100b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
44110b57cec5SDimitry Andric 
44125ffd83dbSDimitry Andric   // Parts of bitcode parsing depend on the datalayout.  Make sure we
44135ffd83dbSDimitry Andric   // finalize the datalayout before we run any of that code.
44145ffd83dbSDimitry Andric   bool ResolvedDataLayout = false;
4415bdd1243dSDimitry Andric   // In order to support importing modules with illegal data layout strings,
4416bdd1243dSDimitry Andric   // delay parsing the data layout string until after upgrades and overrides
4417bdd1243dSDimitry Andric   // have been applied, allowing to fix illegal data layout strings.
4418bdd1243dSDimitry Andric   // Initialize to the current module's layout string in case none is specified.
4419bdd1243dSDimitry Andric   std::string TentativeDataLayoutStr = TheModule->getDataLayoutStr();
44205ffd83dbSDimitry Andric 
4421bdd1243dSDimitry Andric   auto ResolveDataLayout = [&]() -> Error {
4422bdd1243dSDimitry Andric     if (ResolvedDataLayout)
4423bdd1243dSDimitry Andric       return Error::success();
4424bdd1243dSDimitry Andric 
4425bdd1243dSDimitry Andric     // Datalayout and triple can't be parsed after this point.
44265ffd83dbSDimitry Andric     ResolvedDataLayout = true;
44275ffd83dbSDimitry Andric 
4428bdd1243dSDimitry Andric     // Auto-upgrade the layout string
4429bdd1243dSDimitry Andric     TentativeDataLayoutStr = llvm::UpgradeDataLayoutString(
4430bdd1243dSDimitry Andric         TentativeDataLayoutStr, TheModule->getTargetTriple());
44315ffd83dbSDimitry Andric 
4432bdd1243dSDimitry Andric     // Apply override
4433bdd1243dSDimitry Andric     if (Callbacks.DataLayout) {
4434bdd1243dSDimitry Andric       if (auto LayoutOverride = (*Callbacks.DataLayout)(
4435bdd1243dSDimitry Andric               TheModule->getTargetTriple(), TentativeDataLayoutStr))
4436bdd1243dSDimitry Andric         TentativeDataLayoutStr = *LayoutOverride;
4437bdd1243dSDimitry Andric     }
4438bdd1243dSDimitry Andric 
4439bdd1243dSDimitry Andric     // Now the layout string is finalized in TentativeDataLayoutStr. Parse it.
4440bdd1243dSDimitry Andric     Expected<DataLayout> MaybeDL = DataLayout::parse(TentativeDataLayoutStr);
4441bdd1243dSDimitry Andric     if (!MaybeDL)
4442bdd1243dSDimitry Andric       return MaybeDL.takeError();
4443bdd1243dSDimitry Andric 
4444bdd1243dSDimitry Andric     TheModule->setDataLayout(MaybeDL.get());
4445bdd1243dSDimitry Andric     return Error::success();
44465ffd83dbSDimitry Andric   };
44475ffd83dbSDimitry Andric 
44480b57cec5SDimitry Andric   // Read all the records for this module.
44490b57cec5SDimitry Andric   while (true) {
44500b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
44510b57cec5SDimitry Andric     if (!MaybeEntry)
44520b57cec5SDimitry Andric       return MaybeEntry.takeError();
44530b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
44540b57cec5SDimitry Andric 
44550b57cec5SDimitry Andric     switch (Entry.Kind) {
44560b57cec5SDimitry Andric     case BitstreamEntry::Error:
44570b57cec5SDimitry Andric       return error("Malformed block");
44580b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
4459bdd1243dSDimitry Andric       if (Error Err = ResolveDataLayout())
4460bdd1243dSDimitry Andric         return Err;
44610b57cec5SDimitry Andric       return globalCleanup();
44620b57cec5SDimitry Andric 
44630b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
44640b57cec5SDimitry Andric       switch (Entry.ID) {
44650b57cec5SDimitry Andric       default:  // Skip unknown content.
44660b57cec5SDimitry Andric         if (Error Err = Stream.SkipBlock())
44670b57cec5SDimitry Andric           return Err;
44680b57cec5SDimitry Andric         break;
44690b57cec5SDimitry Andric       case bitc::BLOCKINFO_BLOCK_ID:
447081ad6265SDimitry Andric         if (Error Err = readBlockInfo())
447181ad6265SDimitry Andric           return Err;
44720b57cec5SDimitry Andric         break;
44730b57cec5SDimitry Andric       case bitc::PARAMATTR_BLOCK_ID:
44740b57cec5SDimitry Andric         if (Error Err = parseAttributeBlock())
44750b57cec5SDimitry Andric           return Err;
44760b57cec5SDimitry Andric         break;
44770b57cec5SDimitry Andric       case bitc::PARAMATTR_GROUP_BLOCK_ID:
44780b57cec5SDimitry Andric         if (Error Err = parseAttributeGroupBlock())
44790b57cec5SDimitry Andric           return Err;
44800b57cec5SDimitry Andric         break;
44810b57cec5SDimitry Andric       case bitc::TYPE_BLOCK_ID_NEW:
44820b57cec5SDimitry Andric         if (Error Err = parseTypeTable())
44830b57cec5SDimitry Andric           return Err;
44840b57cec5SDimitry Andric         break;
44850b57cec5SDimitry Andric       case bitc::VALUE_SYMTAB_BLOCK_ID:
44860b57cec5SDimitry Andric         if (!SeenValueSymbolTable) {
44870b57cec5SDimitry Andric           // Either this is an old form VST without function index and an
44880b57cec5SDimitry Andric           // associated VST forward declaration record (which would have caused
44890b57cec5SDimitry Andric           // the VST to be jumped to and parsed before it was encountered
44900b57cec5SDimitry Andric           // normally in the stream), or there were no function blocks to
44910b57cec5SDimitry Andric           // trigger an earlier parsing of the VST.
44920b57cec5SDimitry Andric           assert(VSTOffset == 0 || FunctionsWithBodies.empty());
44930b57cec5SDimitry Andric           if (Error Err = parseValueSymbolTable())
44940b57cec5SDimitry Andric             return Err;
44950b57cec5SDimitry Andric           SeenValueSymbolTable = true;
44960b57cec5SDimitry Andric         } else {
44970b57cec5SDimitry Andric           // We must have had a VST forward declaration record, which caused
44980b57cec5SDimitry Andric           // the parser to jump to and parse the VST earlier.
44990b57cec5SDimitry Andric           assert(VSTOffset > 0);
45000b57cec5SDimitry Andric           if (Error Err = Stream.SkipBlock())
45010b57cec5SDimitry Andric             return Err;
45020b57cec5SDimitry Andric         }
45030b57cec5SDimitry Andric         break;
45040b57cec5SDimitry Andric       case bitc::CONSTANTS_BLOCK_ID:
45050b57cec5SDimitry Andric         if (Error Err = parseConstants())
45060b57cec5SDimitry Andric           return Err;
45070b57cec5SDimitry Andric         if (Error Err = resolveGlobalAndIndirectSymbolInits())
45080b57cec5SDimitry Andric           return Err;
45090b57cec5SDimitry Andric         break;
45100b57cec5SDimitry Andric       case bitc::METADATA_BLOCK_ID:
45110b57cec5SDimitry Andric         if (ShouldLazyLoadMetadata) {
45120b57cec5SDimitry Andric           if (Error Err = rememberAndSkipMetadata())
45130b57cec5SDimitry Andric             return Err;
45140b57cec5SDimitry Andric           break;
45150b57cec5SDimitry Andric         }
45160b57cec5SDimitry Andric         assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
45170b57cec5SDimitry Andric         if (Error Err = MDLoader->parseModuleMetadata())
45180b57cec5SDimitry Andric           return Err;
45190b57cec5SDimitry Andric         break;
45200b57cec5SDimitry Andric       case bitc::METADATA_KIND_BLOCK_ID:
45210b57cec5SDimitry Andric         if (Error Err = MDLoader->parseMetadataKinds())
45220b57cec5SDimitry Andric           return Err;
45230b57cec5SDimitry Andric         break;
45240b57cec5SDimitry Andric       case bitc::FUNCTION_BLOCK_ID:
4525bdd1243dSDimitry Andric         if (Error Err = ResolveDataLayout())
4526bdd1243dSDimitry Andric           return Err;
45275ffd83dbSDimitry Andric 
45280b57cec5SDimitry Andric         // If this is the first function body we've seen, reverse the
45290b57cec5SDimitry Andric         // FunctionsWithBodies list.
45300b57cec5SDimitry Andric         if (!SeenFirstFunctionBody) {
45310b57cec5SDimitry Andric           std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
45320b57cec5SDimitry Andric           if (Error Err = globalCleanup())
45330b57cec5SDimitry Andric             return Err;
45340b57cec5SDimitry Andric           SeenFirstFunctionBody = true;
45350b57cec5SDimitry Andric         }
45360b57cec5SDimitry Andric 
45370b57cec5SDimitry Andric         if (VSTOffset > 0) {
45380b57cec5SDimitry Andric           // If we have a VST forward declaration record, make sure we
45390b57cec5SDimitry Andric           // parse the VST now if we haven't already. It is needed to
45400b57cec5SDimitry Andric           // set up the DeferredFunctionInfo vector for lazy reading.
45410b57cec5SDimitry Andric           if (!SeenValueSymbolTable) {
45420b57cec5SDimitry Andric             if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
45430b57cec5SDimitry Andric               return Err;
45440b57cec5SDimitry Andric             SeenValueSymbolTable = true;
45450b57cec5SDimitry Andric             // Fall through so that we record the NextUnreadBit below.
45460b57cec5SDimitry Andric             // This is necessary in case we have an anonymous function that
45470b57cec5SDimitry Andric             // is later materialized. Since it will not have a VST entry we
45480b57cec5SDimitry Andric             // need to fall back to the lazy parse to find its offset.
45490b57cec5SDimitry Andric           } else {
45500b57cec5SDimitry Andric             // If we have a VST forward declaration record, but have already
45510b57cec5SDimitry Andric             // parsed the VST (just above, when the first function body was
45520b57cec5SDimitry Andric             // encountered here), then we are resuming the parse after
45530b57cec5SDimitry Andric             // materializing functions. The ResumeBit points to the
45540b57cec5SDimitry Andric             // start of the last function block recorded in the
45550b57cec5SDimitry Andric             // DeferredFunctionInfo map. Skip it.
45560b57cec5SDimitry Andric             if (Error Err = Stream.SkipBlock())
45570b57cec5SDimitry Andric               return Err;
45580b57cec5SDimitry Andric             continue;
45590b57cec5SDimitry Andric           }
45600b57cec5SDimitry Andric         }
45610b57cec5SDimitry Andric 
45620b57cec5SDimitry Andric         // Support older bitcode files that did not have the function
45630b57cec5SDimitry Andric         // index in the VST, nor a VST forward declaration record, as
45640b57cec5SDimitry Andric         // well as anonymous functions that do not have VST entries.
45650b57cec5SDimitry Andric         // Build the DeferredFunctionInfo vector on the fly.
45660b57cec5SDimitry Andric         if (Error Err = rememberAndSkipFunctionBody())
45670b57cec5SDimitry Andric           return Err;
45680b57cec5SDimitry Andric 
45690b57cec5SDimitry Andric         // Suspend parsing when we reach the function bodies. Subsequent
45700b57cec5SDimitry Andric         // materialization calls will resume it when necessary. If the bitcode
45710b57cec5SDimitry Andric         // file is old, the symbol table will be at the end instead and will not
45720b57cec5SDimitry Andric         // have been seen yet. In this case, just finish the parse now.
45730b57cec5SDimitry Andric         if (SeenValueSymbolTable) {
45740b57cec5SDimitry Andric           NextUnreadBit = Stream.GetCurrentBitNo();
45750b57cec5SDimitry Andric           // After the VST has been parsed, we need to make sure intrinsic name
45760b57cec5SDimitry Andric           // are auto-upgraded.
45770b57cec5SDimitry Andric           return globalCleanup();
45780b57cec5SDimitry Andric         }
45790b57cec5SDimitry Andric         break;
45800b57cec5SDimitry Andric       case bitc::USELIST_BLOCK_ID:
45810b57cec5SDimitry Andric         if (Error Err = parseUseLists())
45820b57cec5SDimitry Andric           return Err;
45830b57cec5SDimitry Andric         break;
45840b57cec5SDimitry Andric       case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
45850b57cec5SDimitry Andric         if (Error Err = parseOperandBundleTags())
45860b57cec5SDimitry Andric           return Err;
45870b57cec5SDimitry Andric         break;
45880b57cec5SDimitry Andric       case bitc::SYNC_SCOPE_NAMES_BLOCK_ID:
45890b57cec5SDimitry Andric         if (Error Err = parseSyncScopeNames())
45900b57cec5SDimitry Andric           return Err;
45910b57cec5SDimitry Andric         break;
45920b57cec5SDimitry Andric       }
45930b57cec5SDimitry Andric       continue;
45940b57cec5SDimitry Andric 
45950b57cec5SDimitry Andric     case BitstreamEntry::Record:
45960b57cec5SDimitry Andric       // The interesting case.
45970b57cec5SDimitry Andric       break;
45980b57cec5SDimitry Andric     }
45990b57cec5SDimitry Andric 
46000b57cec5SDimitry Andric     // Read a record.
46010b57cec5SDimitry Andric     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
46020b57cec5SDimitry Andric     if (!MaybeBitCode)
46030b57cec5SDimitry Andric       return MaybeBitCode.takeError();
46040b57cec5SDimitry Andric     switch (unsigned BitCode = MaybeBitCode.get()) {
46050b57cec5SDimitry Andric     default: break;  // Default behavior, ignore unknown content.
46060b57cec5SDimitry Andric     case bitc::MODULE_CODE_VERSION: {
46070b57cec5SDimitry Andric       Expected<unsigned> VersionOrErr = parseVersionRecord(Record);
46080b57cec5SDimitry Andric       if (!VersionOrErr)
46090b57cec5SDimitry Andric         return VersionOrErr.takeError();
46100b57cec5SDimitry Andric       UseRelativeIDs = *VersionOrErr >= 1;
46110b57cec5SDimitry Andric       break;
46120b57cec5SDimitry Andric     }
46130b57cec5SDimitry Andric     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
46145ffd83dbSDimitry Andric       if (ResolvedDataLayout)
46155ffd83dbSDimitry Andric         return error("target triple too late in module");
46160b57cec5SDimitry Andric       std::string S;
46170b57cec5SDimitry Andric       if (convertToString(Record, 0, S))
46180b57cec5SDimitry Andric         return error("Invalid record");
46190b57cec5SDimitry Andric       TheModule->setTargetTriple(S);
46200b57cec5SDimitry Andric       break;
46210b57cec5SDimitry Andric     }
46220b57cec5SDimitry Andric     case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
46235ffd83dbSDimitry Andric       if (ResolvedDataLayout)
46245ffd83dbSDimitry Andric         return error("datalayout too late in module");
4625bdd1243dSDimitry Andric       if (convertToString(Record, 0, TentativeDataLayoutStr))
46260b57cec5SDimitry Andric         return error("Invalid record");
46270b57cec5SDimitry Andric       break;
46280b57cec5SDimitry Andric     }
46290b57cec5SDimitry Andric     case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
46300b57cec5SDimitry Andric       std::string S;
46310b57cec5SDimitry Andric       if (convertToString(Record, 0, S))
46320b57cec5SDimitry Andric         return error("Invalid record");
46330b57cec5SDimitry Andric       TheModule->setModuleInlineAsm(S);
46340b57cec5SDimitry Andric       break;
46350b57cec5SDimitry Andric     }
46360b57cec5SDimitry Andric     case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
46375ffd83dbSDimitry Andric       // Deprecated, but still needed to read old bitcode files.
46380b57cec5SDimitry Andric       std::string S;
46390b57cec5SDimitry Andric       if (convertToString(Record, 0, S))
46400b57cec5SDimitry Andric         return error("Invalid record");
46410b57cec5SDimitry Andric       // Ignore value.
46420b57cec5SDimitry Andric       break;
46430b57cec5SDimitry Andric     }
46440b57cec5SDimitry Andric     case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
46450b57cec5SDimitry Andric       std::string S;
46460b57cec5SDimitry Andric       if (convertToString(Record, 0, S))
46470b57cec5SDimitry Andric         return error("Invalid record");
46480b57cec5SDimitry Andric       SectionTable.push_back(S);
46490b57cec5SDimitry Andric       break;
46500b57cec5SDimitry Andric     }
46510b57cec5SDimitry Andric     case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
46520b57cec5SDimitry Andric       std::string S;
46530b57cec5SDimitry Andric       if (convertToString(Record, 0, S))
46540b57cec5SDimitry Andric         return error("Invalid record");
46550b57cec5SDimitry Andric       GCTable.push_back(S);
46560b57cec5SDimitry Andric       break;
46570b57cec5SDimitry Andric     }
46580b57cec5SDimitry Andric     case bitc::MODULE_CODE_COMDAT:
46590b57cec5SDimitry Andric       if (Error Err = parseComdatRecord(Record))
46600b57cec5SDimitry Andric         return Err;
46610b57cec5SDimitry Andric       break;
466204eeddc0SDimitry Andric     // FIXME: BitcodeReader should handle {GLOBALVAR, FUNCTION, ALIAS, IFUNC}
466304eeddc0SDimitry Andric     // written by ThinLinkBitcodeWriter. See
466404eeddc0SDimitry Andric     // `ThinLinkBitcodeWriter::writeSimplifiedModuleInfo` for the format of each
466504eeddc0SDimitry Andric     // record
466604eeddc0SDimitry Andric     // (https://github.com/llvm/llvm-project/blob/b6a93967d9c11e79802b5e75cec1584d6c8aa472/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp#L4714)
46670b57cec5SDimitry Andric     case bitc::MODULE_CODE_GLOBALVAR:
46680b57cec5SDimitry Andric       if (Error Err = parseGlobalVarRecord(Record))
46690b57cec5SDimitry Andric         return Err;
46700b57cec5SDimitry Andric       break;
46710b57cec5SDimitry Andric     case bitc::MODULE_CODE_FUNCTION:
4672bdd1243dSDimitry Andric       if (Error Err = ResolveDataLayout())
4673bdd1243dSDimitry Andric         return Err;
46740b57cec5SDimitry Andric       if (Error Err = parseFunctionRecord(Record))
46750b57cec5SDimitry Andric         return Err;
46760b57cec5SDimitry Andric       break;
46770b57cec5SDimitry Andric     case bitc::MODULE_CODE_IFUNC:
46780b57cec5SDimitry Andric     case bitc::MODULE_CODE_ALIAS:
46790b57cec5SDimitry Andric     case bitc::MODULE_CODE_ALIAS_OLD:
46800b57cec5SDimitry Andric       if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
46810b57cec5SDimitry Andric         return Err;
46820b57cec5SDimitry Andric       break;
46830b57cec5SDimitry Andric     /// MODULE_CODE_VSTOFFSET: [offset]
46840b57cec5SDimitry Andric     case bitc::MODULE_CODE_VSTOFFSET:
4685e8d8bef9SDimitry Andric       if (Record.empty())
46860b57cec5SDimitry Andric         return error("Invalid record");
46870b57cec5SDimitry Andric       // Note that we subtract 1 here because the offset is relative to one word
46880b57cec5SDimitry Andric       // before the start of the identification or module block, which was
46890b57cec5SDimitry Andric       // historically always the start of the regular bitcode header.
46900b57cec5SDimitry Andric       VSTOffset = Record[0] - 1;
46910b57cec5SDimitry Andric       break;
46920b57cec5SDimitry Andric     /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
46930b57cec5SDimitry Andric     case bitc::MODULE_CODE_SOURCE_FILENAME:
46940b57cec5SDimitry Andric       SmallString<128> ValueName;
46950b57cec5SDimitry Andric       if (convertToString(Record, 0, ValueName))
46960b57cec5SDimitry Andric         return error("Invalid record");
46970b57cec5SDimitry Andric       TheModule->setSourceFileName(ValueName);
46980b57cec5SDimitry Andric       break;
46990b57cec5SDimitry Andric     }
47000b57cec5SDimitry Andric     Record.clear();
47010b57cec5SDimitry Andric   }
4702bdd1243dSDimitry Andric   this->ValueTypeCallback = std::nullopt;
4703bdd1243dSDimitry Andric   return Error::success();
47040b57cec5SDimitry Andric }
47050b57cec5SDimitry Andric 
47060b57cec5SDimitry Andric Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata,
47075ffd83dbSDimitry Andric                                       bool IsImporting,
4708bdd1243dSDimitry Andric                                       ParserCallbacks Callbacks) {
47090b57cec5SDimitry Andric   TheModule = M;
4710bdd1243dSDimitry Andric   MetadataLoaderCallbacks MDCallbacks;
4711bdd1243dSDimitry Andric   MDCallbacks.GetTypeByID = [&](unsigned ID) { return getTypeByID(ID); };
4712bdd1243dSDimitry Andric   MDCallbacks.GetContainedTypeID = [&](unsigned I, unsigned J) {
4713bdd1243dSDimitry Andric     return getContainedTypeID(I, J);
4714bdd1243dSDimitry Andric   };
4715bdd1243dSDimitry Andric   MDCallbacks.MDType = Callbacks.MDType;
4716bdd1243dSDimitry Andric   MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting, MDCallbacks);
4717bdd1243dSDimitry Andric   return parseModule(0, ShouldLazyLoadMetadata, Callbacks);
47180b57cec5SDimitry Andric }
47190b57cec5SDimitry Andric 
47200b57cec5SDimitry Andric Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
47210b57cec5SDimitry Andric   if (!isa<PointerType>(PtrType))
47220b57cec5SDimitry Andric     return error("Load/Store operand is not a pointer type");
4723fe6060f1SDimitry Andric   if (!PointerType::isLoadableOrStorableType(ValType))
47240b57cec5SDimitry Andric     return error("Cannot load/store from pointer");
47250b57cec5SDimitry Andric   return Error::success();
47260b57cec5SDimitry Andric }
47270b57cec5SDimitry Andric 
472881ad6265SDimitry Andric Error BitcodeReader::propagateAttributeTypes(CallBase *CB,
472981ad6265SDimitry Andric                                              ArrayRef<unsigned> ArgTyIDs) {
473081ad6265SDimitry Andric   AttributeList Attrs = CB->getAttributes();
47310b57cec5SDimitry Andric   for (unsigned i = 0; i != CB->arg_size(); ++i) {
4732fe6060f1SDimitry Andric     for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
4733fe6060f1SDimitry Andric                                      Attribute::InAlloca}) {
473481ad6265SDimitry Andric       if (!Attrs.hasParamAttr(i, Kind) ||
473581ad6265SDimitry Andric           Attrs.getParamAttr(i, Kind).getValueAsType())
47360b57cec5SDimitry Andric         continue;
47370b57cec5SDimitry Andric 
473881ad6265SDimitry Andric       Type *PtrEltTy = getPtrElementTypeByID(ArgTyIDs[i]);
473981ad6265SDimitry Andric       if (!PtrEltTy)
474081ad6265SDimitry Andric         return error("Missing element type for typed attribute upgrade");
4741e8d8bef9SDimitry Andric 
4742fe6060f1SDimitry Andric       Attribute NewAttr;
4743fe6060f1SDimitry Andric       switch (Kind) {
4744fe6060f1SDimitry Andric       case Attribute::ByVal:
4745fe6060f1SDimitry Andric         NewAttr = Attribute::getWithByValType(Context, PtrEltTy);
4746fe6060f1SDimitry Andric         break;
4747fe6060f1SDimitry Andric       case Attribute::StructRet:
4748fe6060f1SDimitry Andric         NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy);
4749fe6060f1SDimitry Andric         break;
4750fe6060f1SDimitry Andric       case Attribute::InAlloca:
4751fe6060f1SDimitry Andric         NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy);
4752fe6060f1SDimitry Andric         break;
4753fe6060f1SDimitry Andric       default:
4754fe6060f1SDimitry Andric         llvm_unreachable("not an upgraded type attribute");
4755fe6060f1SDimitry Andric       }
4756fe6060f1SDimitry Andric 
475781ad6265SDimitry Andric       Attrs = Attrs.addParamAttribute(Context, i, NewAttr);
4758e8d8bef9SDimitry Andric     }
47590b57cec5SDimitry Andric   }
4760fe6060f1SDimitry Andric 
476104eeddc0SDimitry Andric   if (CB->isInlineAsm()) {
476204eeddc0SDimitry Andric     const InlineAsm *IA = cast<InlineAsm>(CB->getCalledOperand());
476304eeddc0SDimitry Andric     unsigned ArgNo = 0;
476404eeddc0SDimitry Andric     for (const InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
476504eeddc0SDimitry Andric       if (!CI.hasArg())
476604eeddc0SDimitry Andric         continue;
476704eeddc0SDimitry Andric 
476881ad6265SDimitry Andric       if (CI.isIndirect && !Attrs.getParamElementType(ArgNo)) {
476981ad6265SDimitry Andric         Type *ElemTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
477081ad6265SDimitry Andric         if (!ElemTy)
477181ad6265SDimitry Andric           return error("Missing element type for inline asm upgrade");
477281ad6265SDimitry Andric         Attrs = Attrs.addParamAttribute(
477381ad6265SDimitry Andric             Context, ArgNo,
477481ad6265SDimitry Andric             Attribute::get(Context, Attribute::ElementType, ElemTy));
477504eeddc0SDimitry Andric       }
477604eeddc0SDimitry Andric 
477704eeddc0SDimitry Andric       ArgNo++;
477804eeddc0SDimitry Andric     }
477904eeddc0SDimitry Andric   }
478004eeddc0SDimitry Andric 
4781fe6060f1SDimitry Andric   switch (CB->getIntrinsicID()) {
4782fe6060f1SDimitry Andric   case Intrinsic::preserve_array_access_index:
4783fe6060f1SDimitry Andric   case Intrinsic::preserve_struct_access_index:
478481ad6265SDimitry Andric   case Intrinsic::aarch64_ldaxr:
478581ad6265SDimitry Andric   case Intrinsic::aarch64_ldxr:
478681ad6265SDimitry Andric   case Intrinsic::aarch64_stlxr:
478781ad6265SDimitry Andric   case Intrinsic::aarch64_stxr:
478881ad6265SDimitry Andric   case Intrinsic::arm_ldaex:
478981ad6265SDimitry Andric   case Intrinsic::arm_ldrex:
479081ad6265SDimitry Andric   case Intrinsic::arm_stlex:
479181ad6265SDimitry Andric   case Intrinsic::arm_strex: {
479281ad6265SDimitry Andric     unsigned ArgNo;
479381ad6265SDimitry Andric     switch (CB->getIntrinsicID()) {
479481ad6265SDimitry Andric     case Intrinsic::aarch64_stlxr:
479581ad6265SDimitry Andric     case Intrinsic::aarch64_stxr:
479681ad6265SDimitry Andric     case Intrinsic::arm_stlex:
479781ad6265SDimitry Andric     case Intrinsic::arm_strex:
479881ad6265SDimitry Andric       ArgNo = 1;
479981ad6265SDimitry Andric       break;
480081ad6265SDimitry Andric     default:
480181ad6265SDimitry Andric       ArgNo = 0;
480281ad6265SDimitry Andric       break;
480381ad6265SDimitry Andric     }
480481ad6265SDimitry Andric     if (!Attrs.getParamElementType(ArgNo)) {
480581ad6265SDimitry Andric       Type *ElTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
480681ad6265SDimitry Andric       if (!ElTy)
480781ad6265SDimitry Andric         return error("Missing element type for elementtype upgrade");
4808fe6060f1SDimitry Andric       Attribute NewAttr = Attribute::get(Context, Attribute::ElementType, ElTy);
480981ad6265SDimitry Andric       Attrs = Attrs.addParamAttribute(Context, ArgNo, NewAttr);
4810fe6060f1SDimitry Andric     }
4811fe6060f1SDimitry Andric     break;
481281ad6265SDimitry Andric   }
4813fe6060f1SDimitry Andric   default:
4814fe6060f1SDimitry Andric     break;
4815fe6060f1SDimitry Andric   }
481681ad6265SDimitry Andric 
481781ad6265SDimitry Andric   CB->setAttributes(Attrs);
481881ad6265SDimitry Andric   return Error::success();
48190b57cec5SDimitry Andric }
48200b57cec5SDimitry Andric 
48210b57cec5SDimitry Andric /// Lazily parse the specified function body block.
48220b57cec5SDimitry Andric Error BitcodeReader::parseFunctionBody(Function *F) {
48230b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
48240b57cec5SDimitry Andric     return Err;
48250b57cec5SDimitry Andric 
48260b57cec5SDimitry Andric   // Unexpected unresolved metadata when parsing function.
48270b57cec5SDimitry Andric   if (MDLoader->hasFwdRefs())
48280b57cec5SDimitry Andric     return error("Invalid function metadata: incoming forward references");
48290b57cec5SDimitry Andric 
48300b57cec5SDimitry Andric   InstructionList.clear();
48310b57cec5SDimitry Andric   unsigned ModuleValueListSize = ValueList.size();
48320b57cec5SDimitry Andric   unsigned ModuleMDLoaderSize = MDLoader->size();
48330b57cec5SDimitry Andric 
48340b57cec5SDimitry Andric   // Add all the function arguments to the value table.
48350b57cec5SDimitry Andric   unsigned ArgNo = 0;
483681ad6265SDimitry Andric   unsigned FTyID = FunctionTypeIDs[F];
48370b57cec5SDimitry Andric   for (Argument &I : F->args()) {
483881ad6265SDimitry Andric     unsigned ArgTyID = getContainedTypeID(FTyID, ArgNo + 1);
483981ad6265SDimitry Andric     assert(I.getType() == getTypeByID(ArgTyID) &&
48400b57cec5SDimitry Andric            "Incorrect fully specified type for Function Argument");
484181ad6265SDimitry Andric     ValueList.push_back(&I, ArgTyID);
484281ad6265SDimitry Andric     ++ArgNo;
48430b57cec5SDimitry Andric   }
48440b57cec5SDimitry Andric   unsigned NextValueNo = ValueList.size();
48450b57cec5SDimitry Andric   BasicBlock *CurBB = nullptr;
48460b57cec5SDimitry Andric   unsigned CurBBNo = 0;
484781ad6265SDimitry Andric   // Block into which constant expressions from phi nodes are materialized.
484881ad6265SDimitry Andric   BasicBlock *PhiConstExprBB = nullptr;
484981ad6265SDimitry Andric   // Edge blocks for phi nodes into which constant expressions have been
485081ad6265SDimitry Andric   // expanded.
485181ad6265SDimitry Andric   SmallMapVector<std::pair<BasicBlock *, BasicBlock *>, BasicBlock *, 4>
485281ad6265SDimitry Andric     ConstExprEdgeBBs;
48530b57cec5SDimitry Andric 
48540b57cec5SDimitry Andric   DebugLoc LastLoc;
48550b57cec5SDimitry Andric   auto getLastInstruction = [&]() -> Instruction * {
48560b57cec5SDimitry Andric     if (CurBB && !CurBB->empty())
48570b57cec5SDimitry Andric       return &CurBB->back();
48580b57cec5SDimitry Andric     else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
48590b57cec5SDimitry Andric              !FunctionBBs[CurBBNo - 1]->empty())
48600b57cec5SDimitry Andric       return &FunctionBBs[CurBBNo - 1]->back();
48610b57cec5SDimitry Andric     return nullptr;
48620b57cec5SDimitry Andric   };
48630b57cec5SDimitry Andric 
48640b57cec5SDimitry Andric   std::vector<OperandBundleDef> OperandBundles;
48650b57cec5SDimitry Andric 
48660b57cec5SDimitry Andric   // Read all the records.
48670b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
48680b57cec5SDimitry Andric 
48690b57cec5SDimitry Andric   while (true) {
48700b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
48710b57cec5SDimitry Andric     if (!MaybeEntry)
48720b57cec5SDimitry Andric       return MaybeEntry.takeError();
48730b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
48740b57cec5SDimitry Andric 
48750b57cec5SDimitry Andric     switch (Entry.Kind) {
48760b57cec5SDimitry Andric     case BitstreamEntry::Error:
48770b57cec5SDimitry Andric       return error("Malformed block");
48780b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
48790b57cec5SDimitry Andric       goto OutOfRecordLoop;
48800b57cec5SDimitry Andric 
48810b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
48820b57cec5SDimitry Andric       switch (Entry.ID) {
48830b57cec5SDimitry Andric       default:  // Skip unknown content.
48840b57cec5SDimitry Andric         if (Error Err = Stream.SkipBlock())
48850b57cec5SDimitry Andric           return Err;
48860b57cec5SDimitry Andric         break;
48870b57cec5SDimitry Andric       case bitc::CONSTANTS_BLOCK_ID:
48880b57cec5SDimitry Andric         if (Error Err = parseConstants())
48890b57cec5SDimitry Andric           return Err;
48900b57cec5SDimitry Andric         NextValueNo = ValueList.size();
48910b57cec5SDimitry Andric         break;
48920b57cec5SDimitry Andric       case bitc::VALUE_SYMTAB_BLOCK_ID:
48930b57cec5SDimitry Andric         if (Error Err = parseValueSymbolTable())
48940b57cec5SDimitry Andric           return Err;
48950b57cec5SDimitry Andric         break;
48960b57cec5SDimitry Andric       case bitc::METADATA_ATTACHMENT_ID:
48970b57cec5SDimitry Andric         if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList))
48980b57cec5SDimitry Andric           return Err;
48990b57cec5SDimitry Andric         break;
49000b57cec5SDimitry Andric       case bitc::METADATA_BLOCK_ID:
49010b57cec5SDimitry Andric         assert(DeferredMetadataInfo.empty() &&
49020b57cec5SDimitry Andric                "Must read all module-level metadata before function-level");
49030b57cec5SDimitry Andric         if (Error Err = MDLoader->parseFunctionMetadata())
49040b57cec5SDimitry Andric           return Err;
49050b57cec5SDimitry Andric         break;
49060b57cec5SDimitry Andric       case bitc::USELIST_BLOCK_ID:
49070b57cec5SDimitry Andric         if (Error Err = parseUseLists())
49080b57cec5SDimitry Andric           return Err;
49090b57cec5SDimitry Andric         break;
49100b57cec5SDimitry Andric       }
49110b57cec5SDimitry Andric       continue;
49120b57cec5SDimitry Andric 
49130b57cec5SDimitry Andric     case BitstreamEntry::Record:
49140b57cec5SDimitry Andric       // The interesting case.
49150b57cec5SDimitry Andric       break;
49160b57cec5SDimitry Andric     }
49170b57cec5SDimitry Andric 
49180b57cec5SDimitry Andric     // Read a record.
49190b57cec5SDimitry Andric     Record.clear();
49200b57cec5SDimitry Andric     Instruction *I = nullptr;
492181ad6265SDimitry Andric     unsigned ResTypeID = InvalidTypeID;
49220b57cec5SDimitry Andric     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
49230b57cec5SDimitry Andric     if (!MaybeBitCode)
49240b57cec5SDimitry Andric       return MaybeBitCode.takeError();
49250b57cec5SDimitry Andric     switch (unsigned BitCode = MaybeBitCode.get()) {
49260b57cec5SDimitry Andric     default: // Default behavior: reject
49270b57cec5SDimitry Andric       return error("Invalid value");
49280b57cec5SDimitry Andric     case bitc::FUNC_CODE_DECLAREBLOCKS: {   // DECLAREBLOCKS: [nblocks]
4929e8d8bef9SDimitry Andric       if (Record.empty() || Record[0] == 0)
49300b57cec5SDimitry Andric         return error("Invalid record");
49310b57cec5SDimitry Andric       // Create all the basic blocks for the function.
49320b57cec5SDimitry Andric       FunctionBBs.resize(Record[0]);
49330b57cec5SDimitry Andric 
49340b57cec5SDimitry Andric       // See if anything took the address of blocks in this function.
49350b57cec5SDimitry Andric       auto BBFRI = BasicBlockFwdRefs.find(F);
49360b57cec5SDimitry Andric       if (BBFRI == BasicBlockFwdRefs.end()) {
49374824e7fdSDimitry Andric         for (BasicBlock *&BB : FunctionBBs)
49384824e7fdSDimitry Andric           BB = BasicBlock::Create(Context, "", F);
49390b57cec5SDimitry Andric       } else {
49400b57cec5SDimitry Andric         auto &BBRefs = BBFRI->second;
49410b57cec5SDimitry Andric         // Check for invalid basic block references.
49420b57cec5SDimitry Andric         if (BBRefs.size() > FunctionBBs.size())
49430b57cec5SDimitry Andric           return error("Invalid ID");
49440b57cec5SDimitry Andric         assert(!BBRefs.empty() && "Unexpected empty array");
49450b57cec5SDimitry Andric         assert(!BBRefs.front() && "Invalid reference to entry block");
49460b57cec5SDimitry Andric         for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
49470b57cec5SDimitry Andric              ++I)
49480b57cec5SDimitry Andric           if (I < RE && BBRefs[I]) {
49490b57cec5SDimitry Andric             BBRefs[I]->insertInto(F);
49500b57cec5SDimitry Andric             FunctionBBs[I] = BBRefs[I];
49510b57cec5SDimitry Andric           } else {
49520b57cec5SDimitry Andric             FunctionBBs[I] = BasicBlock::Create(Context, "", F);
49530b57cec5SDimitry Andric           }
49540b57cec5SDimitry Andric 
49550b57cec5SDimitry Andric         // Erase from the table.
49560b57cec5SDimitry Andric         BasicBlockFwdRefs.erase(BBFRI);
49570b57cec5SDimitry Andric       }
49580b57cec5SDimitry Andric 
49590b57cec5SDimitry Andric       CurBB = FunctionBBs[0];
49600b57cec5SDimitry Andric       continue;
49610b57cec5SDimitry Andric     }
49620b57cec5SDimitry Andric 
496381ad6265SDimitry Andric     case bitc::FUNC_CODE_BLOCKADDR_USERS: // BLOCKADDR_USERS: [vals...]
496481ad6265SDimitry Andric       // The record should not be emitted if it's an empty list.
496581ad6265SDimitry Andric       if (Record.empty())
496681ad6265SDimitry Andric         return error("Invalid record");
496781ad6265SDimitry Andric       // When we have the RARE case of a BlockAddress Constant that is not
496881ad6265SDimitry Andric       // scoped to the Function it refers to, we need to conservatively
496981ad6265SDimitry Andric       // materialize the referred to Function, regardless of whether or not
497081ad6265SDimitry Andric       // that Function will ultimately be linked, otherwise users of
497181ad6265SDimitry Andric       // BitcodeReader might start splicing out Function bodies such that we
497281ad6265SDimitry Andric       // might no longer be able to materialize the BlockAddress since the
497381ad6265SDimitry Andric       // BasicBlock (and entire body of the Function) the BlockAddress refers
497481ad6265SDimitry Andric       // to may have been moved. In the case that the user of BitcodeReader
497581ad6265SDimitry Andric       // decides ultimately not to link the Function body, materializing here
497681ad6265SDimitry Andric       // could be considered wasteful, but it's better than a deserialization
497781ad6265SDimitry Andric       // failure as described. This keeps BitcodeReader unaware of complex
497881ad6265SDimitry Andric       // linkage policy decisions such as those use by LTO, leaving those
497981ad6265SDimitry Andric       // decisions "one layer up."
498081ad6265SDimitry Andric       for (uint64_t ValID : Record)
498181ad6265SDimitry Andric         if (auto *F = dyn_cast<Function>(ValueList[ValID]))
498281ad6265SDimitry Andric           BackwardRefFunctions.push_back(F);
498381ad6265SDimitry Andric         else
498481ad6265SDimitry Andric           return error("Invalid record");
498581ad6265SDimitry Andric 
498681ad6265SDimitry Andric       continue;
498781ad6265SDimitry Andric 
49880b57cec5SDimitry Andric     case bitc::FUNC_CODE_DEBUG_LOC_AGAIN:  // DEBUG_LOC_AGAIN
49890b57cec5SDimitry Andric       // This record indicates that the last instruction is at the same
49900b57cec5SDimitry Andric       // location as the previous instruction with a location.
49910b57cec5SDimitry Andric       I = getLastInstruction();
49920b57cec5SDimitry Andric 
49930b57cec5SDimitry Andric       if (!I)
49940b57cec5SDimitry Andric         return error("Invalid record");
49950b57cec5SDimitry Andric       I->setDebugLoc(LastLoc);
49960b57cec5SDimitry Andric       I = nullptr;
49970b57cec5SDimitry Andric       continue;
49980b57cec5SDimitry Andric 
49990b57cec5SDimitry Andric     case bitc::FUNC_CODE_DEBUG_LOC: {      // DEBUG_LOC: [line, col, scope, ia]
50000b57cec5SDimitry Andric       I = getLastInstruction();
50010b57cec5SDimitry Andric       if (!I || Record.size() < 4)
50020b57cec5SDimitry Andric         return error("Invalid record");
50030b57cec5SDimitry Andric 
50040b57cec5SDimitry Andric       unsigned Line = Record[0], Col = Record[1];
50050b57cec5SDimitry Andric       unsigned ScopeID = Record[2], IAID = Record[3];
50060b57cec5SDimitry Andric       bool isImplicitCode = Record.size() == 5 && Record[4];
50070b57cec5SDimitry Andric 
50080b57cec5SDimitry Andric       MDNode *Scope = nullptr, *IA = nullptr;
50090b57cec5SDimitry Andric       if (ScopeID) {
50100b57cec5SDimitry Andric         Scope = dyn_cast_or_null<MDNode>(
50110b57cec5SDimitry Andric             MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1));
50120b57cec5SDimitry Andric         if (!Scope)
50130b57cec5SDimitry Andric           return error("Invalid record");
50140b57cec5SDimitry Andric       }
50150b57cec5SDimitry Andric       if (IAID) {
50160b57cec5SDimitry Andric         IA = dyn_cast_or_null<MDNode>(
50170b57cec5SDimitry Andric             MDLoader->getMetadataFwdRefOrLoad(IAID - 1));
50180b57cec5SDimitry Andric         if (!IA)
50190b57cec5SDimitry Andric           return error("Invalid record");
50200b57cec5SDimitry Andric       }
5021e8d8bef9SDimitry Andric       LastLoc = DILocation::get(Scope->getContext(), Line, Col, Scope, IA,
5022e8d8bef9SDimitry Andric                                 isImplicitCode);
50230b57cec5SDimitry Andric       I->setDebugLoc(LastLoc);
50240b57cec5SDimitry Andric       I = nullptr;
50250b57cec5SDimitry Andric       continue;
50260b57cec5SDimitry Andric     }
50270b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_UNOP: {    // UNOP: [opval, ty, opcode]
50280b57cec5SDimitry Andric       unsigned OpNum = 0;
50290b57cec5SDimitry Andric       Value *LHS;
503081ad6265SDimitry Andric       unsigned TypeID;
503181ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, LHS, TypeID, CurBB) ||
50320b57cec5SDimitry Andric           OpNum+1 > Record.size())
50330b57cec5SDimitry Andric         return error("Invalid record");
50340b57cec5SDimitry Andric 
50350b57cec5SDimitry Andric       int Opc = getDecodedUnaryOpcode(Record[OpNum++], LHS->getType());
50360b57cec5SDimitry Andric       if (Opc == -1)
50370b57cec5SDimitry Andric         return error("Invalid record");
50380b57cec5SDimitry Andric       I = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS);
503981ad6265SDimitry Andric       ResTypeID = TypeID;
50400b57cec5SDimitry Andric       InstructionList.push_back(I);
50410b57cec5SDimitry Andric       if (OpNum < Record.size()) {
50420b57cec5SDimitry Andric         if (isa<FPMathOperator>(I)) {
50430b57cec5SDimitry Andric           FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
50440b57cec5SDimitry Andric           if (FMF.any())
50450b57cec5SDimitry Andric             I->setFastMathFlags(FMF);
50460b57cec5SDimitry Andric         }
50470b57cec5SDimitry Andric       }
50480b57cec5SDimitry Andric       break;
50490b57cec5SDimitry Andric     }
50500b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
50510b57cec5SDimitry Andric       unsigned OpNum = 0;
50520b57cec5SDimitry Andric       Value *LHS, *RHS;
505381ad6265SDimitry Andric       unsigned TypeID;
505481ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, LHS, TypeID, CurBB) ||
505581ad6265SDimitry Andric           popValue(Record, OpNum, NextValueNo, LHS->getType(), TypeID, RHS,
505681ad6265SDimitry Andric                    CurBB) ||
50570b57cec5SDimitry Andric           OpNum+1 > Record.size())
50580b57cec5SDimitry Andric         return error("Invalid record");
50590b57cec5SDimitry Andric 
50600b57cec5SDimitry Andric       int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
50610b57cec5SDimitry Andric       if (Opc == -1)
50620b57cec5SDimitry Andric         return error("Invalid record");
50630b57cec5SDimitry Andric       I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
506481ad6265SDimitry Andric       ResTypeID = TypeID;
50650b57cec5SDimitry Andric       InstructionList.push_back(I);
50660b57cec5SDimitry Andric       if (OpNum < Record.size()) {
50670b57cec5SDimitry Andric         if (Opc == Instruction::Add ||
50680b57cec5SDimitry Andric             Opc == Instruction::Sub ||
50690b57cec5SDimitry Andric             Opc == Instruction::Mul ||
50700b57cec5SDimitry Andric             Opc == Instruction::Shl) {
50710b57cec5SDimitry Andric           if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
50720b57cec5SDimitry Andric             cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
50730b57cec5SDimitry Andric           if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
50740b57cec5SDimitry Andric             cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
50750b57cec5SDimitry Andric         } else if (Opc == Instruction::SDiv ||
50760b57cec5SDimitry Andric                    Opc == Instruction::UDiv ||
50770b57cec5SDimitry Andric                    Opc == Instruction::LShr ||
50780b57cec5SDimitry Andric                    Opc == Instruction::AShr) {
50790b57cec5SDimitry Andric           if (Record[OpNum] & (1 << bitc::PEO_EXACT))
50800b57cec5SDimitry Andric             cast<BinaryOperator>(I)->setIsExact(true);
50815f757f3fSDimitry Andric         } else if (Opc == Instruction::Or) {
50825f757f3fSDimitry Andric           if (Record[OpNum] & (1 << bitc::PDI_DISJOINT))
50835f757f3fSDimitry Andric             cast<PossiblyDisjointInst>(I)->setIsDisjoint(true);
50840b57cec5SDimitry Andric         } else if (isa<FPMathOperator>(I)) {
50850b57cec5SDimitry Andric           FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
50860b57cec5SDimitry Andric           if (FMF.any())
50870b57cec5SDimitry Andric             I->setFastMathFlags(FMF);
50880b57cec5SDimitry Andric         }
50890b57cec5SDimitry Andric       }
50900b57cec5SDimitry Andric       break;
50910b57cec5SDimitry Andric     }
50920b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
50930b57cec5SDimitry Andric       unsigned OpNum = 0;
50940b57cec5SDimitry Andric       Value *Op;
509581ad6265SDimitry Andric       unsigned OpTypeID;
509681ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) ||
50975f757f3fSDimitry Andric           OpNum + 1 > Record.size())
50980b57cec5SDimitry Andric         return error("Invalid record");
50990b57cec5SDimitry Andric 
51005f757f3fSDimitry Andric       ResTypeID = Record[OpNum++];
510181ad6265SDimitry Andric       Type *ResTy = getTypeByID(ResTypeID);
51025f757f3fSDimitry Andric       int Opc = getDecodedCastOpcode(Record[OpNum++]);
51035f757f3fSDimitry Andric 
51040b57cec5SDimitry Andric       if (Opc == -1 || !ResTy)
51050b57cec5SDimitry Andric         return error("Invalid record");
51060b57cec5SDimitry Andric       Instruction *Temp = nullptr;
51070b57cec5SDimitry Andric       if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
51080b57cec5SDimitry Andric         if (Temp) {
51090b57cec5SDimitry Andric           InstructionList.push_back(Temp);
5110480093f4SDimitry Andric           assert(CurBB && "No current BB?");
5111bdd1243dSDimitry Andric           Temp->insertInto(CurBB, CurBB->end());
51120b57cec5SDimitry Andric         }
51130b57cec5SDimitry Andric       } else {
51140b57cec5SDimitry Andric         auto CastOp = (Instruction::CastOps)Opc;
51150b57cec5SDimitry Andric         if (!CastInst::castIsValid(CastOp, Op, ResTy))
51160b57cec5SDimitry Andric           return error("Invalid cast");
51170b57cec5SDimitry Andric         I = CastInst::Create(CastOp, Op, ResTy);
51180b57cec5SDimitry Andric       }
5119*0fca6ea1SDimitry Andric 
5120*0fca6ea1SDimitry Andric       if (OpNum < Record.size()) {
5121*0fca6ea1SDimitry Andric         if (Opc == Instruction::ZExt || Opc == Instruction::UIToFP) {
5122*0fca6ea1SDimitry Andric           if (Record[OpNum] & (1 << bitc::PNNI_NON_NEG))
5123*0fca6ea1SDimitry Andric             cast<PossiblyNonNegInst>(I)->setNonNeg(true);
5124*0fca6ea1SDimitry Andric         } else if (Opc == Instruction::Trunc) {
5125*0fca6ea1SDimitry Andric           if (Record[OpNum] & (1 << bitc::TIO_NO_UNSIGNED_WRAP))
5126*0fca6ea1SDimitry Andric             cast<TruncInst>(I)->setHasNoUnsignedWrap(true);
5127*0fca6ea1SDimitry Andric           if (Record[OpNum] & (1 << bitc::TIO_NO_SIGNED_WRAP))
5128*0fca6ea1SDimitry Andric             cast<TruncInst>(I)->setHasNoSignedWrap(true);
5129*0fca6ea1SDimitry Andric         }
5130*0fca6ea1SDimitry Andric       }
5131*0fca6ea1SDimitry Andric 
51320b57cec5SDimitry Andric       InstructionList.push_back(I);
51330b57cec5SDimitry Andric       break;
51340b57cec5SDimitry Andric     }
51350b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
51360b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_GEP_OLD:
51370b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
51380b57cec5SDimitry Andric       unsigned OpNum = 0;
51390b57cec5SDimitry Andric 
514081ad6265SDimitry Andric       unsigned TyID;
51410b57cec5SDimitry Andric       Type *Ty;
5142*0fca6ea1SDimitry Andric       GEPNoWrapFlags NW;
51430b57cec5SDimitry Andric 
51440b57cec5SDimitry Andric       if (BitCode == bitc::FUNC_CODE_INST_GEP) {
5145*0fca6ea1SDimitry Andric         NW = toGEPNoWrapFlags(Record[OpNum++]);
514681ad6265SDimitry Andric         TyID = Record[OpNum++];
514781ad6265SDimitry Andric         Ty = getTypeByID(TyID);
51480b57cec5SDimitry Andric       } else {
5149*0fca6ea1SDimitry Andric         if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD)
5150*0fca6ea1SDimitry Andric           NW = GEPNoWrapFlags::inBounds();
515181ad6265SDimitry Andric         TyID = InvalidTypeID;
51520b57cec5SDimitry Andric         Ty = nullptr;
51530b57cec5SDimitry Andric       }
51540b57cec5SDimitry Andric 
51550b57cec5SDimitry Andric       Value *BasePtr;
515681ad6265SDimitry Andric       unsigned BasePtrTypeID;
515781ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr, BasePtrTypeID,
515881ad6265SDimitry Andric                            CurBB))
51590b57cec5SDimitry Andric         return error("Invalid record");
51600b57cec5SDimitry Andric 
51610b57cec5SDimitry Andric       if (!Ty) {
516281ad6265SDimitry Andric         TyID = getContainedTypeID(BasePtrTypeID);
516381ad6265SDimitry Andric         if (BasePtr->getType()->isVectorTy())
516481ad6265SDimitry Andric           TyID = getContainedTypeID(TyID);
516581ad6265SDimitry Andric         Ty = getTypeByID(TyID);
5166fe6060f1SDimitry Andric       }
51670b57cec5SDimitry Andric 
51680b57cec5SDimitry Andric       SmallVector<Value*, 16> GEPIdx;
51690b57cec5SDimitry Andric       while (OpNum != Record.size()) {
51700b57cec5SDimitry Andric         Value *Op;
517181ad6265SDimitry Andric         unsigned OpTypeID;
517281ad6265SDimitry Andric         if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
51730b57cec5SDimitry Andric           return error("Invalid record");
51740b57cec5SDimitry Andric         GEPIdx.push_back(Op);
51750b57cec5SDimitry Andric       }
51760b57cec5SDimitry Andric 
5177*0fca6ea1SDimitry Andric       auto *GEP = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
5178*0fca6ea1SDimitry Andric       I = GEP;
51790b57cec5SDimitry Andric 
518081ad6265SDimitry Andric       ResTypeID = TyID;
518181ad6265SDimitry Andric       if (cast<GEPOperator>(I)->getNumIndices() != 0) {
518281ad6265SDimitry Andric         auto GTI = std::next(gep_type_begin(I));
518381ad6265SDimitry Andric         for (Value *Idx : drop_begin(cast<GEPOperator>(I)->indices())) {
518481ad6265SDimitry Andric           unsigned SubType = 0;
518581ad6265SDimitry Andric           if (GTI.isStruct()) {
518681ad6265SDimitry Andric             ConstantInt *IdxC =
518781ad6265SDimitry Andric                 Idx->getType()->isVectorTy()
518881ad6265SDimitry Andric                     ? cast<ConstantInt>(cast<Constant>(Idx)->getSplatValue())
518981ad6265SDimitry Andric                     : cast<ConstantInt>(Idx);
519081ad6265SDimitry Andric             SubType = IdxC->getZExtValue();
519181ad6265SDimitry Andric           }
519281ad6265SDimitry Andric           ResTypeID = getContainedTypeID(ResTypeID, SubType);
519381ad6265SDimitry Andric           ++GTI;
519481ad6265SDimitry Andric         }
519581ad6265SDimitry Andric       }
519681ad6265SDimitry Andric 
519781ad6265SDimitry Andric       // At this point ResTypeID is the result element type. We need a pointer
519881ad6265SDimitry Andric       // or vector of pointer to it.
519981ad6265SDimitry Andric       ResTypeID = getVirtualTypeID(I->getType()->getScalarType(), ResTypeID);
520081ad6265SDimitry Andric       if (I->getType()->isVectorTy())
520181ad6265SDimitry Andric         ResTypeID = getVirtualTypeID(I->getType(), ResTypeID);
520281ad6265SDimitry Andric 
52030b57cec5SDimitry Andric       InstructionList.push_back(I);
5204*0fca6ea1SDimitry Andric       GEP->setNoWrapFlags(NW);
52050b57cec5SDimitry Andric       break;
52060b57cec5SDimitry Andric     }
52070b57cec5SDimitry Andric 
52080b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_EXTRACTVAL: {
52090b57cec5SDimitry Andric                                        // EXTRACTVAL: [opty, opval, n x indices]
52100b57cec5SDimitry Andric       unsigned OpNum = 0;
52110b57cec5SDimitry Andric       Value *Agg;
521281ad6265SDimitry Andric       unsigned AggTypeID;
521381ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
52140b57cec5SDimitry Andric         return error("Invalid record");
5215fe6060f1SDimitry Andric       Type *Ty = Agg->getType();
52160b57cec5SDimitry Andric 
52170b57cec5SDimitry Andric       unsigned RecSize = Record.size();
52180b57cec5SDimitry Andric       if (OpNum == RecSize)
52190b57cec5SDimitry Andric         return error("EXTRACTVAL: Invalid instruction with 0 indices");
52200b57cec5SDimitry Andric 
52210b57cec5SDimitry Andric       SmallVector<unsigned, 4> EXTRACTVALIdx;
522281ad6265SDimitry Andric       ResTypeID = AggTypeID;
52230b57cec5SDimitry Andric       for (; OpNum != RecSize; ++OpNum) {
5224fe6060f1SDimitry Andric         bool IsArray = Ty->isArrayTy();
5225fe6060f1SDimitry Andric         bool IsStruct = Ty->isStructTy();
52260b57cec5SDimitry Andric         uint64_t Index = Record[OpNum];
52270b57cec5SDimitry Andric 
52280b57cec5SDimitry Andric         if (!IsStruct && !IsArray)
52290b57cec5SDimitry Andric           return error("EXTRACTVAL: Invalid type");
52300b57cec5SDimitry Andric         if ((unsigned)Index != Index)
52310b57cec5SDimitry Andric           return error("Invalid value");
5232fe6060f1SDimitry Andric         if (IsStruct && Index >= Ty->getStructNumElements())
52330b57cec5SDimitry Andric           return error("EXTRACTVAL: Invalid struct index");
5234fe6060f1SDimitry Andric         if (IsArray && Index >= Ty->getArrayNumElements())
52350b57cec5SDimitry Andric           return error("EXTRACTVAL: Invalid array index");
52360b57cec5SDimitry Andric         EXTRACTVALIdx.push_back((unsigned)Index);
52370b57cec5SDimitry Andric 
523881ad6265SDimitry Andric         if (IsStruct) {
5239fe6060f1SDimitry Andric           Ty = Ty->getStructElementType(Index);
524081ad6265SDimitry Andric           ResTypeID = getContainedTypeID(ResTypeID, Index);
524181ad6265SDimitry Andric         } else {
5242fe6060f1SDimitry Andric           Ty = Ty->getArrayElementType();
524381ad6265SDimitry Andric           ResTypeID = getContainedTypeID(ResTypeID);
524481ad6265SDimitry Andric         }
52450b57cec5SDimitry Andric       }
52460b57cec5SDimitry Andric 
52470b57cec5SDimitry Andric       I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
52480b57cec5SDimitry Andric       InstructionList.push_back(I);
52490b57cec5SDimitry Andric       break;
52500b57cec5SDimitry Andric     }
52510b57cec5SDimitry Andric 
52520b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_INSERTVAL: {
52530b57cec5SDimitry Andric                            // INSERTVAL: [opty, opval, opty, opval, n x indices]
52540b57cec5SDimitry Andric       unsigned OpNum = 0;
52550b57cec5SDimitry Andric       Value *Agg;
525681ad6265SDimitry Andric       unsigned AggTypeID;
525781ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
52580b57cec5SDimitry Andric         return error("Invalid record");
52590b57cec5SDimitry Andric       Value *Val;
526081ad6265SDimitry Andric       unsigned ValTypeID;
526181ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
52620b57cec5SDimitry Andric         return error("Invalid record");
52630b57cec5SDimitry Andric 
52640b57cec5SDimitry Andric       unsigned RecSize = Record.size();
52650b57cec5SDimitry Andric       if (OpNum == RecSize)
52660b57cec5SDimitry Andric         return error("INSERTVAL: Invalid instruction with 0 indices");
52670b57cec5SDimitry Andric 
52680b57cec5SDimitry Andric       SmallVector<unsigned, 4> INSERTVALIdx;
52690b57cec5SDimitry Andric       Type *CurTy = Agg->getType();
52700b57cec5SDimitry Andric       for (; OpNum != RecSize; ++OpNum) {
52710b57cec5SDimitry Andric         bool IsArray = CurTy->isArrayTy();
52720b57cec5SDimitry Andric         bool IsStruct = CurTy->isStructTy();
52730b57cec5SDimitry Andric         uint64_t Index = Record[OpNum];
52740b57cec5SDimitry Andric 
52750b57cec5SDimitry Andric         if (!IsStruct && !IsArray)
52760b57cec5SDimitry Andric           return error("INSERTVAL: Invalid type");
52770b57cec5SDimitry Andric         if ((unsigned)Index != Index)
52780b57cec5SDimitry Andric           return error("Invalid value");
52790b57cec5SDimitry Andric         if (IsStruct && Index >= CurTy->getStructNumElements())
52800b57cec5SDimitry Andric           return error("INSERTVAL: Invalid struct index");
52810b57cec5SDimitry Andric         if (IsArray && Index >= CurTy->getArrayNumElements())
52820b57cec5SDimitry Andric           return error("INSERTVAL: Invalid array index");
52830b57cec5SDimitry Andric 
52840b57cec5SDimitry Andric         INSERTVALIdx.push_back((unsigned)Index);
52850b57cec5SDimitry Andric         if (IsStruct)
52860b57cec5SDimitry Andric           CurTy = CurTy->getStructElementType(Index);
52870b57cec5SDimitry Andric         else
52880b57cec5SDimitry Andric           CurTy = CurTy->getArrayElementType();
52890b57cec5SDimitry Andric       }
52900b57cec5SDimitry Andric 
52910b57cec5SDimitry Andric       if (CurTy != Val->getType())
52920b57cec5SDimitry Andric         return error("Inserted value type doesn't match aggregate type");
52930b57cec5SDimitry Andric 
52940b57cec5SDimitry Andric       I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
529581ad6265SDimitry Andric       ResTypeID = AggTypeID;
52960b57cec5SDimitry Andric       InstructionList.push_back(I);
52970b57cec5SDimitry Andric       break;
52980b57cec5SDimitry Andric     }
52990b57cec5SDimitry Andric 
53000b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
53010b57cec5SDimitry Andric       // obsolete form of select
53020b57cec5SDimitry Andric       // handles select i1 ... in old bitcode
53030b57cec5SDimitry Andric       unsigned OpNum = 0;
53040b57cec5SDimitry Andric       Value *TrueVal, *FalseVal, *Cond;
530581ad6265SDimitry Andric       unsigned TypeID;
530681ad6265SDimitry Andric       Type *CondType = Type::getInt1Ty(Context);
530781ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, TypeID,
530881ad6265SDimitry Andric                            CurBB) ||
530981ad6265SDimitry Andric           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), TypeID,
531081ad6265SDimitry Andric                    FalseVal, CurBB) ||
531181ad6265SDimitry Andric           popValue(Record, OpNum, NextValueNo, CondType,
531281ad6265SDimitry Andric                    getVirtualTypeID(CondType), Cond, CurBB))
53130b57cec5SDimitry Andric         return error("Invalid record");
53140b57cec5SDimitry Andric 
53150b57cec5SDimitry Andric       I = SelectInst::Create(Cond, TrueVal, FalseVal);
531681ad6265SDimitry Andric       ResTypeID = TypeID;
53170b57cec5SDimitry Andric       InstructionList.push_back(I);
53180b57cec5SDimitry Andric       break;
53190b57cec5SDimitry Andric     }
53200b57cec5SDimitry Andric 
53210b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
53220b57cec5SDimitry Andric       // new form of select
53230b57cec5SDimitry Andric       // handles select i1 or select [N x i1]
53240b57cec5SDimitry Andric       unsigned OpNum = 0;
53250b57cec5SDimitry Andric       Value *TrueVal, *FalseVal, *Cond;
532681ad6265SDimitry Andric       unsigned ValTypeID, CondTypeID;
532781ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, ValTypeID,
532881ad6265SDimitry Andric                            CurBB) ||
532981ad6265SDimitry Andric           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), ValTypeID,
533081ad6265SDimitry Andric                    FalseVal, CurBB) ||
533181ad6265SDimitry Andric           getValueTypePair(Record, OpNum, NextValueNo, Cond, CondTypeID, CurBB))
53320b57cec5SDimitry Andric         return error("Invalid record");
53330b57cec5SDimitry Andric 
53340b57cec5SDimitry Andric       // select condition can be either i1 or [N x i1]
53350b57cec5SDimitry Andric       if (VectorType* vector_type =
53360b57cec5SDimitry Andric           dyn_cast<VectorType>(Cond->getType())) {
53370b57cec5SDimitry Andric         // expect <n x i1>
53380b57cec5SDimitry Andric         if (vector_type->getElementType() != Type::getInt1Ty(Context))
53390b57cec5SDimitry Andric           return error("Invalid type for value");
53400b57cec5SDimitry Andric       } else {
53410b57cec5SDimitry Andric         // expect i1
53420b57cec5SDimitry Andric         if (Cond->getType() != Type::getInt1Ty(Context))
53430b57cec5SDimitry Andric           return error("Invalid type for value");
53440b57cec5SDimitry Andric       }
53450b57cec5SDimitry Andric 
53460b57cec5SDimitry Andric       I = SelectInst::Create(Cond, TrueVal, FalseVal);
534781ad6265SDimitry Andric       ResTypeID = ValTypeID;
53480b57cec5SDimitry Andric       InstructionList.push_back(I);
53490b57cec5SDimitry Andric       if (OpNum < Record.size() && isa<FPMathOperator>(I)) {
53500b57cec5SDimitry Andric         FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
53510b57cec5SDimitry Andric         if (FMF.any())
53520b57cec5SDimitry Andric           I->setFastMathFlags(FMF);
53530b57cec5SDimitry Andric       }
53540b57cec5SDimitry Andric       break;
53550b57cec5SDimitry Andric     }
53560b57cec5SDimitry Andric 
53570b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
53580b57cec5SDimitry Andric       unsigned OpNum = 0;
53590b57cec5SDimitry Andric       Value *Vec, *Idx;
536081ad6265SDimitry Andric       unsigned VecTypeID, IdxTypeID;
536181ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB) ||
536281ad6265SDimitry Andric           getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB))
53630b57cec5SDimitry Andric         return error("Invalid record");
53640b57cec5SDimitry Andric       if (!Vec->getType()->isVectorTy())
53650b57cec5SDimitry Andric         return error("Invalid type for value");
53660b57cec5SDimitry Andric       I = ExtractElementInst::Create(Vec, Idx);
536781ad6265SDimitry Andric       ResTypeID = getContainedTypeID(VecTypeID);
53680b57cec5SDimitry Andric       InstructionList.push_back(I);
53690b57cec5SDimitry Andric       break;
53700b57cec5SDimitry Andric     }
53710b57cec5SDimitry Andric 
53720b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
53730b57cec5SDimitry Andric       unsigned OpNum = 0;
53740b57cec5SDimitry Andric       Value *Vec, *Elt, *Idx;
537581ad6265SDimitry Andric       unsigned VecTypeID, IdxTypeID;
537681ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB))
53770b57cec5SDimitry Andric         return error("Invalid record");
53780b57cec5SDimitry Andric       if (!Vec->getType()->isVectorTy())
53790b57cec5SDimitry Andric         return error("Invalid type for value");
53800b57cec5SDimitry Andric       if (popValue(Record, OpNum, NextValueNo,
538181ad6265SDimitry Andric                    cast<VectorType>(Vec->getType())->getElementType(),
538281ad6265SDimitry Andric                    getContainedTypeID(VecTypeID), Elt, CurBB) ||
538381ad6265SDimitry Andric           getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB))
53840b57cec5SDimitry Andric         return error("Invalid record");
53850b57cec5SDimitry Andric       I = InsertElementInst::Create(Vec, Elt, Idx);
538681ad6265SDimitry Andric       ResTypeID = VecTypeID;
53870b57cec5SDimitry Andric       InstructionList.push_back(I);
53880b57cec5SDimitry Andric       break;
53890b57cec5SDimitry Andric     }
53900b57cec5SDimitry Andric 
53910b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
53920b57cec5SDimitry Andric       unsigned OpNum = 0;
53930b57cec5SDimitry Andric       Value *Vec1, *Vec2, *Mask;
539481ad6265SDimitry Andric       unsigned Vec1TypeID;
539581ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Vec1, Vec1TypeID,
539681ad6265SDimitry Andric                            CurBB) ||
539781ad6265SDimitry Andric           popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec1TypeID,
539881ad6265SDimitry Andric                    Vec2, CurBB))
53990b57cec5SDimitry Andric         return error("Invalid record");
54000b57cec5SDimitry Andric 
540181ad6265SDimitry Andric       unsigned MaskTypeID;
540281ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Mask, MaskTypeID, CurBB))
54030b57cec5SDimitry Andric         return error("Invalid record");
54040b57cec5SDimitry Andric       if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
54050b57cec5SDimitry Andric         return error("Invalid type for value");
54065ffd83dbSDimitry Andric 
54070b57cec5SDimitry Andric       I = new ShuffleVectorInst(Vec1, Vec2, Mask);
540881ad6265SDimitry Andric       ResTypeID =
540981ad6265SDimitry Andric           getVirtualTypeID(I->getType(), getContainedTypeID(Vec1TypeID));
54100b57cec5SDimitry Andric       InstructionList.push_back(I);
54110b57cec5SDimitry Andric       break;
54120b57cec5SDimitry Andric     }
54130b57cec5SDimitry Andric 
54140b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
54150b57cec5SDimitry Andric       // Old form of ICmp/FCmp returning bool
54160b57cec5SDimitry Andric       // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
54170b57cec5SDimitry Andric       // both legal on vectors but had different behaviour.
54180b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
54190b57cec5SDimitry Andric       // FCmp/ICmp returning bool or vector of bool
54200b57cec5SDimitry Andric 
54210b57cec5SDimitry Andric       unsigned OpNum = 0;
54220b57cec5SDimitry Andric       Value *LHS, *RHS;
542381ad6265SDimitry Andric       unsigned LHSTypeID;
542481ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, LHS, LHSTypeID, CurBB) ||
542581ad6265SDimitry Andric           popValue(Record, OpNum, NextValueNo, LHS->getType(), LHSTypeID, RHS,
542681ad6265SDimitry Andric                    CurBB))
54270b57cec5SDimitry Andric         return error("Invalid record");
54280b57cec5SDimitry Andric 
54290b57cec5SDimitry Andric       if (OpNum >= Record.size())
54300b57cec5SDimitry Andric         return error(
54310b57cec5SDimitry Andric             "Invalid record: operand number exceeded available operands");
54320b57cec5SDimitry Andric 
54335f757f3fSDimitry Andric       CmpInst::Predicate PredVal = CmpInst::Predicate(Record[OpNum]);
54340b57cec5SDimitry Andric       bool IsFP = LHS->getType()->isFPOrFPVectorTy();
54350b57cec5SDimitry Andric       FastMathFlags FMF;
54360b57cec5SDimitry Andric       if (IsFP && Record.size() > OpNum+1)
54370b57cec5SDimitry Andric         FMF = getDecodedFastMathFlags(Record[++OpNum]);
54380b57cec5SDimitry Andric 
54390b57cec5SDimitry Andric       if (OpNum+1 != Record.size())
54400b57cec5SDimitry Andric         return error("Invalid record");
54410b57cec5SDimitry Andric 
54425f757f3fSDimitry Andric       if (IsFP) {
54435f757f3fSDimitry Andric         if (!CmpInst::isFPPredicate(PredVal))
54445f757f3fSDimitry Andric           return error("Invalid fcmp predicate");
54455f757f3fSDimitry Andric         I = new FCmpInst(PredVal, LHS, RHS);
54465f757f3fSDimitry Andric       } else {
54475f757f3fSDimitry Andric         if (!CmpInst::isIntPredicate(PredVal))
54485f757f3fSDimitry Andric           return error("Invalid icmp predicate");
54495f757f3fSDimitry Andric         I = new ICmpInst(PredVal, LHS, RHS);
54505f757f3fSDimitry Andric       }
54510b57cec5SDimitry Andric 
545281ad6265SDimitry Andric       ResTypeID = getVirtualTypeID(I->getType()->getScalarType());
545381ad6265SDimitry Andric       if (LHS->getType()->isVectorTy())
545481ad6265SDimitry Andric         ResTypeID = getVirtualTypeID(I->getType(), ResTypeID);
545581ad6265SDimitry Andric 
54560b57cec5SDimitry Andric       if (FMF.any())
54570b57cec5SDimitry Andric         I->setFastMathFlags(FMF);
54580b57cec5SDimitry Andric       InstructionList.push_back(I);
54590b57cec5SDimitry Andric       break;
54600b57cec5SDimitry Andric     }
54610b57cec5SDimitry Andric 
54620b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
54630b57cec5SDimitry Andric       {
54640b57cec5SDimitry Andric         unsigned Size = Record.size();
54650b57cec5SDimitry Andric         if (Size == 0) {
54660b57cec5SDimitry Andric           I = ReturnInst::Create(Context);
54670b57cec5SDimitry Andric           InstructionList.push_back(I);
54680b57cec5SDimitry Andric           break;
54690b57cec5SDimitry Andric         }
54700b57cec5SDimitry Andric 
54710b57cec5SDimitry Andric         unsigned OpNum = 0;
54720b57cec5SDimitry Andric         Value *Op = nullptr;
547381ad6265SDimitry Andric         unsigned OpTypeID;
547481ad6265SDimitry Andric         if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
54750b57cec5SDimitry Andric           return error("Invalid record");
54760b57cec5SDimitry Andric         if (OpNum != Record.size())
54770b57cec5SDimitry Andric           return error("Invalid record");
54780b57cec5SDimitry Andric 
54790b57cec5SDimitry Andric         I = ReturnInst::Create(Context, Op);
54800b57cec5SDimitry Andric         InstructionList.push_back(I);
54810b57cec5SDimitry Andric         break;
54820b57cec5SDimitry Andric       }
54830b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
54840b57cec5SDimitry Andric       if (Record.size() != 1 && Record.size() != 3)
54850b57cec5SDimitry Andric         return error("Invalid record");
54860b57cec5SDimitry Andric       BasicBlock *TrueDest = getBasicBlock(Record[0]);
54870b57cec5SDimitry Andric       if (!TrueDest)
54880b57cec5SDimitry Andric         return error("Invalid record");
54890b57cec5SDimitry Andric 
54900b57cec5SDimitry Andric       if (Record.size() == 1) {
54910b57cec5SDimitry Andric         I = BranchInst::Create(TrueDest);
54920b57cec5SDimitry Andric         InstructionList.push_back(I);
54930b57cec5SDimitry Andric       }
54940b57cec5SDimitry Andric       else {
54950b57cec5SDimitry Andric         BasicBlock *FalseDest = getBasicBlock(Record[1]);
549681ad6265SDimitry Andric         Type *CondType = Type::getInt1Ty(Context);
549781ad6265SDimitry Andric         Value *Cond = getValue(Record, 2, NextValueNo, CondType,
549881ad6265SDimitry Andric                                getVirtualTypeID(CondType), CurBB);
54990b57cec5SDimitry Andric         if (!FalseDest || !Cond)
55000b57cec5SDimitry Andric           return error("Invalid record");
55010b57cec5SDimitry Andric         I = BranchInst::Create(TrueDest, FalseDest, Cond);
55020b57cec5SDimitry Andric         InstructionList.push_back(I);
55030b57cec5SDimitry Andric       }
55040b57cec5SDimitry Andric       break;
55050b57cec5SDimitry Andric     }
55060b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
55070b57cec5SDimitry Andric       if (Record.size() != 1 && Record.size() != 2)
55080b57cec5SDimitry Andric         return error("Invalid record");
55090b57cec5SDimitry Andric       unsigned Idx = 0;
551081ad6265SDimitry Andric       Type *TokenTy = Type::getTokenTy(Context);
551181ad6265SDimitry Andric       Value *CleanupPad = getValue(Record, Idx++, NextValueNo, TokenTy,
551281ad6265SDimitry Andric                                    getVirtualTypeID(TokenTy), CurBB);
55130b57cec5SDimitry Andric       if (!CleanupPad)
55140b57cec5SDimitry Andric         return error("Invalid record");
55150b57cec5SDimitry Andric       BasicBlock *UnwindDest = nullptr;
55160b57cec5SDimitry Andric       if (Record.size() == 2) {
55170b57cec5SDimitry Andric         UnwindDest = getBasicBlock(Record[Idx++]);
55180b57cec5SDimitry Andric         if (!UnwindDest)
55190b57cec5SDimitry Andric           return error("Invalid record");
55200b57cec5SDimitry Andric       }
55210b57cec5SDimitry Andric 
55220b57cec5SDimitry Andric       I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
55230b57cec5SDimitry Andric       InstructionList.push_back(I);
55240b57cec5SDimitry Andric       break;
55250b57cec5SDimitry Andric     }
55260b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
55270b57cec5SDimitry Andric       if (Record.size() != 2)
55280b57cec5SDimitry Andric         return error("Invalid record");
55290b57cec5SDimitry Andric       unsigned Idx = 0;
553081ad6265SDimitry Andric       Type *TokenTy = Type::getTokenTy(Context);
553181ad6265SDimitry Andric       Value *CatchPad = getValue(Record, Idx++, NextValueNo, TokenTy,
553281ad6265SDimitry Andric                                  getVirtualTypeID(TokenTy), CurBB);
55330b57cec5SDimitry Andric       if (!CatchPad)
55340b57cec5SDimitry Andric         return error("Invalid record");
55350b57cec5SDimitry Andric       BasicBlock *BB = getBasicBlock(Record[Idx++]);
55360b57cec5SDimitry Andric       if (!BB)
55370b57cec5SDimitry Andric         return error("Invalid record");
55380b57cec5SDimitry Andric 
55390b57cec5SDimitry Andric       I = CatchReturnInst::Create(CatchPad, BB);
55400b57cec5SDimitry Andric       InstructionList.push_back(I);
55410b57cec5SDimitry Andric       break;
55420b57cec5SDimitry Andric     }
55430b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
55440b57cec5SDimitry Andric       // We must have, at minimum, the outer scope and the number of arguments.
55450b57cec5SDimitry Andric       if (Record.size() < 2)
55460b57cec5SDimitry Andric         return error("Invalid record");
55470b57cec5SDimitry Andric 
55480b57cec5SDimitry Andric       unsigned Idx = 0;
55490b57cec5SDimitry Andric 
555081ad6265SDimitry Andric       Type *TokenTy = Type::getTokenTy(Context);
555181ad6265SDimitry Andric       Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy,
555281ad6265SDimitry Andric                                   getVirtualTypeID(TokenTy), CurBB);
55535f757f3fSDimitry Andric       if (!ParentPad)
55545f757f3fSDimitry Andric         return error("Invalid record");
55550b57cec5SDimitry Andric 
55560b57cec5SDimitry Andric       unsigned NumHandlers = Record[Idx++];
55570b57cec5SDimitry Andric 
55580b57cec5SDimitry Andric       SmallVector<BasicBlock *, 2> Handlers;
55590b57cec5SDimitry Andric       for (unsigned Op = 0; Op != NumHandlers; ++Op) {
55600b57cec5SDimitry Andric         BasicBlock *BB = getBasicBlock(Record[Idx++]);
55610b57cec5SDimitry Andric         if (!BB)
55620b57cec5SDimitry Andric           return error("Invalid record");
55630b57cec5SDimitry Andric         Handlers.push_back(BB);
55640b57cec5SDimitry Andric       }
55650b57cec5SDimitry Andric 
55660b57cec5SDimitry Andric       BasicBlock *UnwindDest = nullptr;
55670b57cec5SDimitry Andric       if (Idx + 1 == Record.size()) {
55680b57cec5SDimitry Andric         UnwindDest = getBasicBlock(Record[Idx++]);
55690b57cec5SDimitry Andric         if (!UnwindDest)
55700b57cec5SDimitry Andric           return error("Invalid record");
55710b57cec5SDimitry Andric       }
55720b57cec5SDimitry Andric 
55730b57cec5SDimitry Andric       if (Record.size() != Idx)
55740b57cec5SDimitry Andric         return error("Invalid record");
55750b57cec5SDimitry Andric 
55760b57cec5SDimitry Andric       auto *CatchSwitch =
55770b57cec5SDimitry Andric           CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
55780b57cec5SDimitry Andric       for (BasicBlock *Handler : Handlers)
55790b57cec5SDimitry Andric         CatchSwitch->addHandler(Handler);
55800b57cec5SDimitry Andric       I = CatchSwitch;
558181ad6265SDimitry Andric       ResTypeID = getVirtualTypeID(I->getType());
55820b57cec5SDimitry Andric       InstructionList.push_back(I);
55830b57cec5SDimitry Andric       break;
55840b57cec5SDimitry Andric     }
55850b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CATCHPAD:
55860b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
55870b57cec5SDimitry Andric       // We must have, at minimum, the outer scope and the number of arguments.
55880b57cec5SDimitry Andric       if (Record.size() < 2)
55890b57cec5SDimitry Andric         return error("Invalid record");
55900b57cec5SDimitry Andric 
55910b57cec5SDimitry Andric       unsigned Idx = 0;
55920b57cec5SDimitry Andric 
559381ad6265SDimitry Andric       Type *TokenTy = Type::getTokenTy(Context);
559481ad6265SDimitry Andric       Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy,
559581ad6265SDimitry Andric                                   getVirtualTypeID(TokenTy), CurBB);
55965f757f3fSDimitry Andric       if (!ParentPad)
55975f757f3fSDimitry Andric         return error("Invald record");
55980b57cec5SDimitry Andric 
55990b57cec5SDimitry Andric       unsigned NumArgOperands = Record[Idx++];
56000b57cec5SDimitry Andric 
56010b57cec5SDimitry Andric       SmallVector<Value *, 2> Args;
56020b57cec5SDimitry Andric       for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
56030b57cec5SDimitry Andric         Value *Val;
560481ad6265SDimitry Andric         unsigned ValTypeID;
560581ad6265SDimitry Andric         if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, nullptr))
56060b57cec5SDimitry Andric           return error("Invalid record");
56070b57cec5SDimitry Andric         Args.push_back(Val);
56080b57cec5SDimitry Andric       }
56090b57cec5SDimitry Andric 
56100b57cec5SDimitry Andric       if (Record.size() != Idx)
56110b57cec5SDimitry Andric         return error("Invalid record");
56120b57cec5SDimitry Andric 
56130b57cec5SDimitry Andric       if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
56140b57cec5SDimitry Andric         I = CleanupPadInst::Create(ParentPad, Args);
56150b57cec5SDimitry Andric       else
56160b57cec5SDimitry Andric         I = CatchPadInst::Create(ParentPad, Args);
561781ad6265SDimitry Andric       ResTypeID = getVirtualTypeID(I->getType());
56180b57cec5SDimitry Andric       InstructionList.push_back(I);
56190b57cec5SDimitry Andric       break;
56200b57cec5SDimitry Andric     }
56210b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
56220b57cec5SDimitry Andric       // Check magic
56230b57cec5SDimitry Andric       if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
56240b57cec5SDimitry Andric         // "New" SwitchInst format with case ranges. The changes to write this
56250b57cec5SDimitry Andric         // format were reverted but we still recognize bitcode that uses it.
56260b57cec5SDimitry Andric         // Hopefully someday we will have support for case ranges and can use
56270b57cec5SDimitry Andric         // this format again.
56280b57cec5SDimitry Andric 
562981ad6265SDimitry Andric         unsigned OpTyID = Record[1];
563081ad6265SDimitry Andric         Type *OpTy = getTypeByID(OpTyID);
56310b57cec5SDimitry Andric         unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
56320b57cec5SDimitry Andric 
563381ad6265SDimitry Andric         Value *Cond = getValue(Record, 2, NextValueNo, OpTy, OpTyID, CurBB);
56340b57cec5SDimitry Andric         BasicBlock *Default = getBasicBlock(Record[3]);
56350b57cec5SDimitry Andric         if (!OpTy || !Cond || !Default)
56360b57cec5SDimitry Andric           return error("Invalid record");
56370b57cec5SDimitry Andric 
56380b57cec5SDimitry Andric         unsigned NumCases = Record[4];
56390b57cec5SDimitry Andric 
56400b57cec5SDimitry Andric         SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
56410b57cec5SDimitry Andric         InstructionList.push_back(SI);
56420b57cec5SDimitry Andric 
56430b57cec5SDimitry Andric         unsigned CurIdx = 5;
56440b57cec5SDimitry Andric         for (unsigned i = 0; i != NumCases; ++i) {
56450b57cec5SDimitry Andric           SmallVector<ConstantInt*, 1> CaseVals;
56460b57cec5SDimitry Andric           unsigned NumItems = Record[CurIdx++];
56470b57cec5SDimitry Andric           for (unsigned ci = 0; ci != NumItems; ++ci) {
56480b57cec5SDimitry Andric             bool isSingleNumber = Record[CurIdx++];
56490b57cec5SDimitry Andric 
56500b57cec5SDimitry Andric             APInt Low;
56510b57cec5SDimitry Andric             unsigned ActiveWords = 1;
56520b57cec5SDimitry Andric             if (ValueBitWidth > 64)
56530b57cec5SDimitry Andric               ActiveWords = Record[CurIdx++];
5654bdd1243dSDimitry Andric             Low = readWideAPInt(ArrayRef(&Record[CurIdx], ActiveWords),
56550b57cec5SDimitry Andric                                 ValueBitWidth);
56560b57cec5SDimitry Andric             CurIdx += ActiveWords;
56570b57cec5SDimitry Andric 
56580b57cec5SDimitry Andric             if (!isSingleNumber) {
56590b57cec5SDimitry Andric               ActiveWords = 1;
56600b57cec5SDimitry Andric               if (ValueBitWidth > 64)
56610b57cec5SDimitry Andric                 ActiveWords = Record[CurIdx++];
5662bdd1243dSDimitry Andric               APInt High = readWideAPInt(ArrayRef(&Record[CurIdx], ActiveWords),
5663bdd1243dSDimitry Andric                                          ValueBitWidth);
56640b57cec5SDimitry Andric               CurIdx += ActiveWords;
56650b57cec5SDimitry Andric 
56660b57cec5SDimitry Andric               // FIXME: It is not clear whether values in the range should be
56670b57cec5SDimitry Andric               // compared as signed or unsigned values. The partially
56680b57cec5SDimitry Andric               // implemented changes that used this format in the past used
56690b57cec5SDimitry Andric               // unsigned comparisons.
56700b57cec5SDimitry Andric               for ( ; Low.ule(High); ++Low)
56710b57cec5SDimitry Andric                 CaseVals.push_back(ConstantInt::get(Context, Low));
56720b57cec5SDimitry Andric             } else
56730b57cec5SDimitry Andric               CaseVals.push_back(ConstantInt::get(Context, Low));
56740b57cec5SDimitry Andric           }
56750b57cec5SDimitry Andric           BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
56764824e7fdSDimitry Andric           for (ConstantInt *Cst : CaseVals)
56774824e7fdSDimitry Andric             SI->addCase(Cst, DestBB);
56780b57cec5SDimitry Andric         }
56790b57cec5SDimitry Andric         I = SI;
56800b57cec5SDimitry Andric         break;
56810b57cec5SDimitry Andric       }
56820b57cec5SDimitry Andric 
56830b57cec5SDimitry Andric       // Old SwitchInst format without case ranges.
56840b57cec5SDimitry Andric 
56850b57cec5SDimitry Andric       if (Record.size() < 3 || (Record.size() & 1) == 0)
56860b57cec5SDimitry Andric         return error("Invalid record");
568781ad6265SDimitry Andric       unsigned OpTyID = Record[0];
568881ad6265SDimitry Andric       Type *OpTy = getTypeByID(OpTyID);
568981ad6265SDimitry Andric       Value *Cond = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
56900b57cec5SDimitry Andric       BasicBlock *Default = getBasicBlock(Record[2]);
56910b57cec5SDimitry Andric       if (!OpTy || !Cond || !Default)
56920b57cec5SDimitry Andric         return error("Invalid record");
56930b57cec5SDimitry Andric       unsigned NumCases = (Record.size()-3)/2;
56940b57cec5SDimitry Andric       SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
56950b57cec5SDimitry Andric       InstructionList.push_back(SI);
56960b57cec5SDimitry Andric       for (unsigned i = 0, e = NumCases; i != e; ++i) {
569781ad6265SDimitry Andric         ConstantInt *CaseVal = dyn_cast_or_null<ConstantInt>(
569881ad6265SDimitry Andric             getFnValueByID(Record[3+i*2], OpTy, OpTyID, nullptr));
56990b57cec5SDimitry Andric         BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
57000b57cec5SDimitry Andric         if (!CaseVal || !DestBB) {
57010b57cec5SDimitry Andric           delete SI;
57020b57cec5SDimitry Andric           return error("Invalid record");
57030b57cec5SDimitry Andric         }
57040b57cec5SDimitry Andric         SI->addCase(CaseVal, DestBB);
57050b57cec5SDimitry Andric       }
57060b57cec5SDimitry Andric       I = SI;
57070b57cec5SDimitry Andric       break;
57080b57cec5SDimitry Andric     }
57090b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
57100b57cec5SDimitry Andric       if (Record.size() < 2)
57110b57cec5SDimitry Andric         return error("Invalid record");
571281ad6265SDimitry Andric       unsigned OpTyID = Record[0];
571381ad6265SDimitry Andric       Type *OpTy = getTypeByID(OpTyID);
571481ad6265SDimitry Andric       Value *Address = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
57150b57cec5SDimitry Andric       if (!OpTy || !Address)
57160b57cec5SDimitry Andric         return error("Invalid record");
57170b57cec5SDimitry Andric       unsigned NumDests = Record.size()-2;
57180b57cec5SDimitry Andric       IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
57190b57cec5SDimitry Andric       InstructionList.push_back(IBI);
57200b57cec5SDimitry Andric       for (unsigned i = 0, e = NumDests; i != e; ++i) {
57210b57cec5SDimitry Andric         if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
57220b57cec5SDimitry Andric           IBI->addDestination(DestBB);
57230b57cec5SDimitry Andric         } else {
57240b57cec5SDimitry Andric           delete IBI;
57250b57cec5SDimitry Andric           return error("Invalid record");
57260b57cec5SDimitry Andric         }
57270b57cec5SDimitry Andric       }
57280b57cec5SDimitry Andric       I = IBI;
57290b57cec5SDimitry Andric       break;
57300b57cec5SDimitry Andric     }
57310b57cec5SDimitry Andric 
57320b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_INVOKE: {
57330b57cec5SDimitry Andric       // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
57340b57cec5SDimitry Andric       if (Record.size() < 4)
57350b57cec5SDimitry Andric         return error("Invalid record");
57360b57cec5SDimitry Andric       unsigned OpNum = 0;
57370b57cec5SDimitry Andric       AttributeList PAL = getAttributes(Record[OpNum++]);
57380b57cec5SDimitry Andric       unsigned CCInfo = Record[OpNum++];
57390b57cec5SDimitry Andric       BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
57400b57cec5SDimitry Andric       BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
57410b57cec5SDimitry Andric 
574281ad6265SDimitry Andric       unsigned FTyID = InvalidTypeID;
57430b57cec5SDimitry Andric       FunctionType *FTy = nullptr;
57440b57cec5SDimitry Andric       if ((CCInfo >> 13) & 1) {
574581ad6265SDimitry Andric         FTyID = Record[OpNum++];
574681ad6265SDimitry Andric         FTy = dyn_cast<FunctionType>(getTypeByID(FTyID));
5747fe6060f1SDimitry Andric         if (!FTy)
57480b57cec5SDimitry Andric           return error("Explicit invoke type is not a function type");
57490b57cec5SDimitry Andric       }
57500b57cec5SDimitry Andric 
57510b57cec5SDimitry Andric       Value *Callee;
575281ad6265SDimitry Andric       unsigned CalleeTypeID;
575381ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
575481ad6265SDimitry Andric                            CurBB))
57550b57cec5SDimitry Andric         return error("Invalid record");
57560b57cec5SDimitry Andric 
57570b57cec5SDimitry Andric       PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
57580b57cec5SDimitry Andric       if (!CalleeTy)
57590b57cec5SDimitry Andric         return error("Callee is not a pointer");
57600b57cec5SDimitry Andric       if (!FTy) {
576181ad6265SDimitry Andric         FTyID = getContainedTypeID(CalleeTypeID);
576281ad6265SDimitry Andric         FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
5763fe6060f1SDimitry Andric         if (!FTy)
57640b57cec5SDimitry Andric           return error("Callee is not of pointer to function type");
576506c3fb27SDimitry Andric       }
57660b57cec5SDimitry Andric       if (Record.size() < FTy->getNumParams() + OpNum)
57670b57cec5SDimitry Andric         return error("Insufficient operands to call");
57680b57cec5SDimitry Andric 
57690b57cec5SDimitry Andric       SmallVector<Value*, 16> Ops;
577081ad6265SDimitry Andric       SmallVector<unsigned, 16> ArgTyIDs;
57710b57cec5SDimitry Andric       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
577281ad6265SDimitry Andric         unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
577381ad6265SDimitry Andric         Ops.push_back(getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
577481ad6265SDimitry Andric                                ArgTyID, CurBB));
577581ad6265SDimitry Andric         ArgTyIDs.push_back(ArgTyID);
57760b57cec5SDimitry Andric         if (!Ops.back())
57770b57cec5SDimitry Andric           return error("Invalid record");
57780b57cec5SDimitry Andric       }
57790b57cec5SDimitry Andric 
57800b57cec5SDimitry Andric       if (!FTy->isVarArg()) {
57810b57cec5SDimitry Andric         if (Record.size() != OpNum)
57820b57cec5SDimitry Andric           return error("Invalid record");
57830b57cec5SDimitry Andric       } else {
57840b57cec5SDimitry Andric         // Read type/value pairs for varargs params.
57850b57cec5SDimitry Andric         while (OpNum != Record.size()) {
57860b57cec5SDimitry Andric           Value *Op;
578781ad6265SDimitry Andric           unsigned OpTypeID;
578881ad6265SDimitry Andric           if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
57890b57cec5SDimitry Andric             return error("Invalid record");
57900b57cec5SDimitry Andric           Ops.push_back(Op);
579181ad6265SDimitry Andric           ArgTyIDs.push_back(OpTypeID);
57920b57cec5SDimitry Andric         }
57930b57cec5SDimitry Andric       }
57940b57cec5SDimitry Andric 
579581ad6265SDimitry Andric       // Upgrade the bundles if needed.
579681ad6265SDimitry Andric       if (!OperandBundles.empty())
579781ad6265SDimitry Andric         UpgradeOperandBundles(OperandBundles);
579881ad6265SDimitry Andric 
57990b57cec5SDimitry Andric       I = InvokeInst::Create(FTy, Callee, NormalBB, UnwindBB, Ops,
58000b57cec5SDimitry Andric                              OperandBundles);
580181ad6265SDimitry Andric       ResTypeID = getContainedTypeID(FTyID);
58020b57cec5SDimitry Andric       OperandBundles.clear();
58030b57cec5SDimitry Andric       InstructionList.push_back(I);
58040b57cec5SDimitry Andric       cast<InvokeInst>(I)->setCallingConv(
58050b57cec5SDimitry Andric           static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
58060b57cec5SDimitry Andric       cast<InvokeInst>(I)->setAttributes(PAL);
580781ad6265SDimitry Andric       if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) {
580881ad6265SDimitry Andric         I->deleteValue();
580981ad6265SDimitry Andric         return Err;
581081ad6265SDimitry Andric       }
58110b57cec5SDimitry Andric 
58120b57cec5SDimitry Andric       break;
58130b57cec5SDimitry Andric     }
58140b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
58150b57cec5SDimitry Andric       unsigned Idx = 0;
58160b57cec5SDimitry Andric       Value *Val = nullptr;
581781ad6265SDimitry Andric       unsigned ValTypeID;
581881ad6265SDimitry Andric       if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, CurBB))
58190b57cec5SDimitry Andric         return error("Invalid record");
58200b57cec5SDimitry Andric       I = ResumeInst::Create(Val);
58210b57cec5SDimitry Andric       InstructionList.push_back(I);
58220b57cec5SDimitry Andric       break;
58230b57cec5SDimitry Andric     }
58240b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CALLBR: {
58250b57cec5SDimitry Andric       // CALLBR: [attr, cc, norm, transfs, fty, fnid, args]
58260b57cec5SDimitry Andric       unsigned OpNum = 0;
58270b57cec5SDimitry Andric       AttributeList PAL = getAttributes(Record[OpNum++]);
58280b57cec5SDimitry Andric       unsigned CCInfo = Record[OpNum++];
58290b57cec5SDimitry Andric 
58300b57cec5SDimitry Andric       BasicBlock *DefaultDest = getBasicBlock(Record[OpNum++]);
58310b57cec5SDimitry Andric       unsigned NumIndirectDests = Record[OpNum++];
58320b57cec5SDimitry Andric       SmallVector<BasicBlock *, 16> IndirectDests;
58330b57cec5SDimitry Andric       for (unsigned i = 0, e = NumIndirectDests; i != e; ++i)
58340b57cec5SDimitry Andric         IndirectDests.push_back(getBasicBlock(Record[OpNum++]));
58350b57cec5SDimitry Andric 
583681ad6265SDimitry Andric       unsigned FTyID = InvalidTypeID;
58370b57cec5SDimitry Andric       FunctionType *FTy = nullptr;
58380b57cec5SDimitry Andric       if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) {
583981ad6265SDimitry Andric         FTyID = Record[OpNum++];
584081ad6265SDimitry Andric         FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
5841fe6060f1SDimitry Andric         if (!FTy)
58420b57cec5SDimitry Andric           return error("Explicit call type is not a function type");
58430b57cec5SDimitry Andric       }
58440b57cec5SDimitry Andric 
58450b57cec5SDimitry Andric       Value *Callee;
584681ad6265SDimitry Andric       unsigned CalleeTypeID;
584781ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
584881ad6265SDimitry Andric                            CurBB))
58490b57cec5SDimitry Andric         return error("Invalid record");
58500b57cec5SDimitry Andric 
58510b57cec5SDimitry Andric       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
58520b57cec5SDimitry Andric       if (!OpTy)
58530b57cec5SDimitry Andric         return error("Callee is not a pointer type");
58540b57cec5SDimitry Andric       if (!FTy) {
585581ad6265SDimitry Andric         FTyID = getContainedTypeID(CalleeTypeID);
585681ad6265SDimitry Andric         FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
5857fe6060f1SDimitry Andric         if (!FTy)
58580b57cec5SDimitry Andric           return error("Callee is not of pointer to function type");
585906c3fb27SDimitry Andric       }
58600b57cec5SDimitry Andric       if (Record.size() < FTy->getNumParams() + OpNum)
58610b57cec5SDimitry Andric         return error("Insufficient operands to call");
58620b57cec5SDimitry Andric 
58630b57cec5SDimitry Andric       SmallVector<Value*, 16> Args;
586481ad6265SDimitry Andric       SmallVector<unsigned, 16> ArgTyIDs;
58650b57cec5SDimitry Andric       // Read the fixed params.
58660b57cec5SDimitry Andric       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
586704eeddc0SDimitry Andric         Value *Arg;
586881ad6265SDimitry Andric         unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
58690b57cec5SDimitry Andric         if (FTy->getParamType(i)->isLabelTy())
587004eeddc0SDimitry Andric           Arg = getBasicBlock(Record[OpNum]);
58710b57cec5SDimitry Andric         else
587281ad6265SDimitry Andric           Arg = getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
587381ad6265SDimitry Andric                          ArgTyID, CurBB);
587404eeddc0SDimitry Andric         if (!Arg)
58750b57cec5SDimitry Andric           return error("Invalid record");
587604eeddc0SDimitry Andric         Args.push_back(Arg);
587781ad6265SDimitry Andric         ArgTyIDs.push_back(ArgTyID);
58780b57cec5SDimitry Andric       }
58790b57cec5SDimitry Andric 
58800b57cec5SDimitry Andric       // Read type/value pairs for varargs params.
58810b57cec5SDimitry Andric       if (!FTy->isVarArg()) {
58820b57cec5SDimitry Andric         if (OpNum != Record.size())
58830b57cec5SDimitry Andric           return error("Invalid record");
58840b57cec5SDimitry Andric       } else {
58850b57cec5SDimitry Andric         while (OpNum != Record.size()) {
58860b57cec5SDimitry Andric           Value *Op;
588781ad6265SDimitry Andric           unsigned OpTypeID;
588881ad6265SDimitry Andric           if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
58890b57cec5SDimitry Andric             return error("Invalid record");
58900b57cec5SDimitry Andric           Args.push_back(Op);
589181ad6265SDimitry Andric           ArgTyIDs.push_back(OpTypeID);
58920b57cec5SDimitry Andric         }
58930b57cec5SDimitry Andric       }
58940b57cec5SDimitry Andric 
589581ad6265SDimitry Andric       // Upgrade the bundles if needed.
589681ad6265SDimitry Andric       if (!OperandBundles.empty())
589781ad6265SDimitry Andric         UpgradeOperandBundles(OperandBundles);
589881ad6265SDimitry Andric 
5899fcaf7f86SDimitry Andric       if (auto *IA = dyn_cast<InlineAsm>(Callee)) {
5900fcaf7f86SDimitry Andric         InlineAsm::ConstraintInfoVector ConstraintInfo = IA->ParseConstraints();
5901fcaf7f86SDimitry Andric         auto IsLabelConstraint = [](const InlineAsm::ConstraintInfo &CI) {
5902fcaf7f86SDimitry Andric           return CI.Type == InlineAsm::isLabel;
5903fcaf7f86SDimitry Andric         };
5904fcaf7f86SDimitry Andric         if (none_of(ConstraintInfo, IsLabelConstraint)) {
5905fcaf7f86SDimitry Andric           // Upgrade explicit blockaddress arguments to label constraints.
5906fcaf7f86SDimitry Andric           // Verify that the last arguments are blockaddress arguments that
5907fcaf7f86SDimitry Andric           // match the indirect destinations. Clang always generates callbr
5908fcaf7f86SDimitry Andric           // in this form. We could support reordering with more effort.
5909fcaf7f86SDimitry Andric           unsigned FirstBlockArg = Args.size() - IndirectDests.size();
5910fcaf7f86SDimitry Andric           for (unsigned ArgNo = FirstBlockArg; ArgNo < Args.size(); ++ArgNo) {
5911fcaf7f86SDimitry Andric             unsigned LabelNo = ArgNo - FirstBlockArg;
5912fcaf7f86SDimitry Andric             auto *BA = dyn_cast<BlockAddress>(Args[ArgNo]);
5913fcaf7f86SDimitry Andric             if (!BA || BA->getFunction() != F ||
5914fcaf7f86SDimitry Andric                 LabelNo > IndirectDests.size() ||
5915fcaf7f86SDimitry Andric                 BA->getBasicBlock() != IndirectDests[LabelNo])
5916fcaf7f86SDimitry Andric               return error("callbr argument does not match indirect dest");
5917fcaf7f86SDimitry Andric           }
5918fcaf7f86SDimitry Andric 
5919fcaf7f86SDimitry Andric           // Remove blockaddress arguments.
5920fcaf7f86SDimitry Andric           Args.erase(Args.begin() + FirstBlockArg, Args.end());
5921fcaf7f86SDimitry Andric           ArgTyIDs.erase(ArgTyIDs.begin() + FirstBlockArg, ArgTyIDs.end());
5922fcaf7f86SDimitry Andric 
5923fcaf7f86SDimitry Andric           // Recreate the function type with less arguments.
5924fcaf7f86SDimitry Andric           SmallVector<Type *> ArgTys;
5925fcaf7f86SDimitry Andric           for (Value *Arg : Args)
5926fcaf7f86SDimitry Andric             ArgTys.push_back(Arg->getType());
5927fcaf7f86SDimitry Andric           FTy =
5928fcaf7f86SDimitry Andric               FunctionType::get(FTy->getReturnType(), ArgTys, FTy->isVarArg());
5929fcaf7f86SDimitry Andric 
5930fcaf7f86SDimitry Andric           // Update constraint string to use label constraints.
5931fcaf7f86SDimitry Andric           std::string Constraints = IA->getConstraintString();
5932fcaf7f86SDimitry Andric           unsigned ArgNo = 0;
5933fcaf7f86SDimitry Andric           size_t Pos = 0;
5934fcaf7f86SDimitry Andric           for (const auto &CI : ConstraintInfo) {
5935fcaf7f86SDimitry Andric             if (CI.hasArg()) {
5936fcaf7f86SDimitry Andric               if (ArgNo >= FirstBlockArg)
5937fcaf7f86SDimitry Andric                 Constraints.insert(Pos, "!");
5938fcaf7f86SDimitry Andric               ++ArgNo;
5939fcaf7f86SDimitry Andric             }
5940fcaf7f86SDimitry Andric 
5941fcaf7f86SDimitry Andric             // Go to next constraint in string.
5942fcaf7f86SDimitry Andric             Pos = Constraints.find(',', Pos);
5943fcaf7f86SDimitry Andric             if (Pos == std::string::npos)
5944fcaf7f86SDimitry Andric               break;
5945fcaf7f86SDimitry Andric             ++Pos;
5946fcaf7f86SDimitry Andric           }
5947fcaf7f86SDimitry Andric 
5948fcaf7f86SDimitry Andric           Callee = InlineAsm::get(FTy, IA->getAsmString(), Constraints,
5949fcaf7f86SDimitry Andric                                   IA->hasSideEffects(), IA->isAlignStack(),
5950fcaf7f86SDimitry Andric                                   IA->getDialect(), IA->canThrow());
5951fcaf7f86SDimitry Andric         }
5952fcaf7f86SDimitry Andric       }
5953fcaf7f86SDimitry Andric 
59540b57cec5SDimitry Andric       I = CallBrInst::Create(FTy, Callee, DefaultDest, IndirectDests, Args,
59550b57cec5SDimitry Andric                              OperandBundles);
595681ad6265SDimitry Andric       ResTypeID = getContainedTypeID(FTyID);
59570b57cec5SDimitry Andric       OperandBundles.clear();
59580b57cec5SDimitry Andric       InstructionList.push_back(I);
59590b57cec5SDimitry Andric       cast<CallBrInst>(I)->setCallingConv(
59600b57cec5SDimitry Andric           static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
59610b57cec5SDimitry Andric       cast<CallBrInst>(I)->setAttributes(PAL);
596281ad6265SDimitry Andric       if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) {
596381ad6265SDimitry Andric         I->deleteValue();
596481ad6265SDimitry Andric         return Err;
596581ad6265SDimitry Andric       }
59660b57cec5SDimitry Andric       break;
59670b57cec5SDimitry Andric     }
59680b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
59690b57cec5SDimitry Andric       I = new UnreachableInst(Context);
59700b57cec5SDimitry Andric       InstructionList.push_back(I);
59710b57cec5SDimitry Andric       break;
59720b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
5973e8d8bef9SDimitry Andric       if (Record.empty())
597481ad6265SDimitry Andric         return error("Invalid phi record");
59758bcb0991SDimitry Andric       // The first record specifies the type.
597681ad6265SDimitry Andric       unsigned TyID = Record[0];
597781ad6265SDimitry Andric       Type *Ty = getTypeByID(TyID);
59780b57cec5SDimitry Andric       if (!Ty)
597981ad6265SDimitry Andric         return error("Invalid phi record");
59800b57cec5SDimitry Andric 
59818bcb0991SDimitry Andric       // Phi arguments are pairs of records of [value, basic block].
59828bcb0991SDimitry Andric       // There is an optional final record for fast-math-flags if this phi has a
59838bcb0991SDimitry Andric       // floating-point type.
59848bcb0991SDimitry Andric       size_t NumArgs = (Record.size() - 1) / 2;
59858bcb0991SDimitry Andric       PHINode *PN = PHINode::Create(Ty, NumArgs);
598681ad6265SDimitry Andric       if ((Record.size() - 1) % 2 == 1 && !isa<FPMathOperator>(PN)) {
598781ad6265SDimitry Andric         PN->deleteValue();
598881ad6265SDimitry Andric         return error("Invalid phi record");
598981ad6265SDimitry Andric       }
59900b57cec5SDimitry Andric       InstructionList.push_back(PN);
59910b57cec5SDimitry Andric 
599281ad6265SDimitry Andric       SmallDenseMap<BasicBlock *, Value *> Args;
59938bcb0991SDimitry Andric       for (unsigned i = 0; i != NumArgs; i++) {
599481ad6265SDimitry Andric         BasicBlock *BB = getBasicBlock(Record[i * 2 + 2]);
599581ad6265SDimitry Andric         if (!BB) {
599681ad6265SDimitry Andric           PN->deleteValue();
599781ad6265SDimitry Andric           return error("Invalid phi BB");
599881ad6265SDimitry Andric         }
599981ad6265SDimitry Andric 
600081ad6265SDimitry Andric         // Phi nodes may contain the same predecessor multiple times, in which
600181ad6265SDimitry Andric         // case the incoming value must be identical. Directly reuse the already
600281ad6265SDimitry Andric         // seen value here, to avoid expanding a constant expression multiple
600381ad6265SDimitry Andric         // times.
600481ad6265SDimitry Andric         auto It = Args.find(BB);
600581ad6265SDimitry Andric         if (It != Args.end()) {
600681ad6265SDimitry Andric           PN->addIncoming(It->second, BB);
600781ad6265SDimitry Andric           continue;
600881ad6265SDimitry Andric         }
600981ad6265SDimitry Andric 
601081ad6265SDimitry Andric         // If there already is a block for this edge (from a different phi),
601181ad6265SDimitry Andric         // use it.
601281ad6265SDimitry Andric         BasicBlock *EdgeBB = ConstExprEdgeBBs.lookup({BB, CurBB});
601381ad6265SDimitry Andric         if (!EdgeBB) {
601481ad6265SDimitry Andric           // Otherwise, use a temporary block (that we will discard if it
601581ad6265SDimitry Andric           // turns out to be unnecessary).
601681ad6265SDimitry Andric           if (!PhiConstExprBB)
601781ad6265SDimitry Andric             PhiConstExprBB = BasicBlock::Create(Context, "phi.constexpr", F);
601881ad6265SDimitry Andric           EdgeBB = PhiConstExprBB;
601981ad6265SDimitry Andric         }
602081ad6265SDimitry Andric 
60210b57cec5SDimitry Andric         // With the new function encoding, it is possible that operands have
60220b57cec5SDimitry Andric         // negative IDs (for forward references).  Use a signed VBR
60230b57cec5SDimitry Andric         // representation to keep the encoding small.
602481ad6265SDimitry Andric         Value *V;
60250b57cec5SDimitry Andric         if (UseRelativeIDs)
602681ad6265SDimitry Andric           V = getValueSigned(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
60270b57cec5SDimitry Andric         else
602881ad6265SDimitry Andric           V = getValue(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
602981ad6265SDimitry Andric         if (!V) {
603081ad6265SDimitry Andric           PN->deleteValue();
603181ad6265SDimitry Andric           PhiConstExprBB->eraseFromParent();
603281ad6265SDimitry Andric           return error("Invalid phi record");
603381ad6265SDimitry Andric         }
603481ad6265SDimitry Andric 
603581ad6265SDimitry Andric         if (EdgeBB == PhiConstExprBB && !EdgeBB->empty()) {
603681ad6265SDimitry Andric           ConstExprEdgeBBs.insert({{BB, CurBB}, EdgeBB});
603781ad6265SDimitry Andric           PhiConstExprBB = nullptr;
603881ad6265SDimitry Andric         }
60390b57cec5SDimitry Andric         PN->addIncoming(V, BB);
604081ad6265SDimitry Andric         Args.insert({BB, V});
60410b57cec5SDimitry Andric       }
60420b57cec5SDimitry Andric       I = PN;
604381ad6265SDimitry Andric       ResTypeID = TyID;
60448bcb0991SDimitry Andric 
60458bcb0991SDimitry Andric       // If there are an even number of records, the final record must be FMF.
60468bcb0991SDimitry Andric       if (Record.size() % 2 == 0) {
60478bcb0991SDimitry Andric         assert(isa<FPMathOperator>(I) && "Unexpected phi type");
60488bcb0991SDimitry Andric         FastMathFlags FMF = getDecodedFastMathFlags(Record[Record.size() - 1]);
60498bcb0991SDimitry Andric         if (FMF.any())
60508bcb0991SDimitry Andric           I->setFastMathFlags(FMF);
60518bcb0991SDimitry Andric       }
60528bcb0991SDimitry Andric 
60530b57cec5SDimitry Andric       break;
60540b57cec5SDimitry Andric     }
60550b57cec5SDimitry Andric 
60560b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_LANDINGPAD:
60570b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
60580b57cec5SDimitry Andric       // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
60590b57cec5SDimitry Andric       unsigned Idx = 0;
60600b57cec5SDimitry Andric       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
60610b57cec5SDimitry Andric         if (Record.size() < 3)
60620b57cec5SDimitry Andric           return error("Invalid record");
60630b57cec5SDimitry Andric       } else {
60640b57cec5SDimitry Andric         assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
60650b57cec5SDimitry Andric         if (Record.size() < 4)
60660b57cec5SDimitry Andric           return error("Invalid record");
60670b57cec5SDimitry Andric       }
606881ad6265SDimitry Andric       ResTypeID = Record[Idx++];
606981ad6265SDimitry Andric       Type *Ty = getTypeByID(ResTypeID);
60700b57cec5SDimitry Andric       if (!Ty)
60710b57cec5SDimitry Andric         return error("Invalid record");
60720b57cec5SDimitry Andric       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
60730b57cec5SDimitry Andric         Value *PersFn = nullptr;
607481ad6265SDimitry Andric         unsigned PersFnTypeID;
607581ad6265SDimitry Andric         if (getValueTypePair(Record, Idx, NextValueNo, PersFn, PersFnTypeID,
607681ad6265SDimitry Andric                              nullptr))
60770b57cec5SDimitry Andric           return error("Invalid record");
60780b57cec5SDimitry Andric 
60790b57cec5SDimitry Andric         if (!F->hasPersonalityFn())
60800b57cec5SDimitry Andric           F->setPersonalityFn(cast<Constant>(PersFn));
60810b57cec5SDimitry Andric         else if (F->getPersonalityFn() != cast<Constant>(PersFn))
60820b57cec5SDimitry Andric           return error("Personality function mismatch");
60830b57cec5SDimitry Andric       }
60840b57cec5SDimitry Andric 
60850b57cec5SDimitry Andric       bool IsCleanup = !!Record[Idx++];
60860b57cec5SDimitry Andric       unsigned NumClauses = Record[Idx++];
60870b57cec5SDimitry Andric       LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
60880b57cec5SDimitry Andric       LP->setCleanup(IsCleanup);
60890b57cec5SDimitry Andric       for (unsigned J = 0; J != NumClauses; ++J) {
60900b57cec5SDimitry Andric         LandingPadInst::ClauseType CT =
60910b57cec5SDimitry Andric           LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
60920b57cec5SDimitry Andric         Value *Val;
609381ad6265SDimitry Andric         unsigned ValTypeID;
60940b57cec5SDimitry Andric 
609581ad6265SDimitry Andric         if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID,
609681ad6265SDimitry Andric                              nullptr)) {
60970b57cec5SDimitry Andric           delete LP;
60980b57cec5SDimitry Andric           return error("Invalid record");
60990b57cec5SDimitry Andric         }
61000b57cec5SDimitry Andric 
61010b57cec5SDimitry Andric         assert((CT != LandingPadInst::Catch ||
61020b57cec5SDimitry Andric                 !isa<ArrayType>(Val->getType())) &&
61030b57cec5SDimitry Andric                "Catch clause has a invalid type!");
61040b57cec5SDimitry Andric         assert((CT != LandingPadInst::Filter ||
61050b57cec5SDimitry Andric                 isa<ArrayType>(Val->getType())) &&
61060b57cec5SDimitry Andric                "Filter clause has invalid type!");
61070b57cec5SDimitry Andric         LP->addClause(cast<Constant>(Val));
61080b57cec5SDimitry Andric       }
61090b57cec5SDimitry Andric 
61100b57cec5SDimitry Andric       I = LP;
61110b57cec5SDimitry Andric       InstructionList.push_back(I);
61120b57cec5SDimitry Andric       break;
61130b57cec5SDimitry Andric     }
61140b57cec5SDimitry Andric 
61150b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
611681ad6265SDimitry Andric       if (Record.size() != 4 && Record.size() != 5)
61170b57cec5SDimitry Andric         return error("Invalid record");
6118e8d8bef9SDimitry Andric       using APV = AllocaPackedValues;
6119e8d8bef9SDimitry Andric       const uint64_t Rec = Record[3];
6120e8d8bef9SDimitry Andric       const bool InAlloca = Bitfield::get<APV::UsedWithInAlloca>(Rec);
6121e8d8bef9SDimitry Andric       const bool SwiftError = Bitfield::get<APV::SwiftError>(Rec);
612281ad6265SDimitry Andric       unsigned TyID = Record[0];
612381ad6265SDimitry Andric       Type *Ty = getTypeByID(TyID);
6124e8d8bef9SDimitry Andric       if (!Bitfield::get<APV::ExplicitType>(Rec)) {
612581ad6265SDimitry Andric         TyID = getContainedTypeID(TyID);
612681ad6265SDimitry Andric         Ty = getTypeByID(TyID);
612781ad6265SDimitry Andric         if (!Ty)
612881ad6265SDimitry Andric           return error("Missing element type for old-style alloca");
61290b57cec5SDimitry Andric       }
613081ad6265SDimitry Andric       unsigned OpTyID = Record[1];
613181ad6265SDimitry Andric       Type *OpTy = getTypeByID(OpTyID);
613281ad6265SDimitry Andric       Value *Size = getFnValueByID(Record[2], OpTy, OpTyID, CurBB);
61338bcb0991SDimitry Andric       MaybeAlign Align;
6134349cc55cSDimitry Andric       uint64_t AlignExp =
6135349cc55cSDimitry Andric           Bitfield::get<APV::AlignLower>(Rec) |
6136349cc55cSDimitry Andric           (Bitfield::get<APV::AlignUpper>(Rec) << APV::AlignLower::Bits);
6137349cc55cSDimitry Andric       if (Error Err = parseAlignmentValue(AlignExp, Align)) {
61380b57cec5SDimitry Andric         return Err;
61390b57cec5SDimitry Andric       }
61400b57cec5SDimitry Andric       if (!Ty || !Size)
61410b57cec5SDimitry Andric         return error("Invalid record");
61420b57cec5SDimitry Andric 
61430b57cec5SDimitry Andric       const DataLayout &DL = TheModule->getDataLayout();
614481ad6265SDimitry Andric       unsigned AS = Record.size() == 5 ? Record[4] : DL.getAllocaAddrSpace();
61450b57cec5SDimitry Andric 
61465ffd83dbSDimitry Andric       SmallPtrSet<Type *, 4> Visited;
61475ffd83dbSDimitry Andric       if (!Align && !Ty->isSized(&Visited))
61485ffd83dbSDimitry Andric         return error("alloca of unsized type");
61495ffd83dbSDimitry Andric       if (!Align)
61505ffd83dbSDimitry Andric         Align = DL.getPrefTypeAlign(Ty);
61515ffd83dbSDimitry Andric 
61525f757f3fSDimitry Andric       if (!Size->getType()->isIntegerTy())
61535f757f3fSDimitry Andric         return error("alloca element count must have integer type");
61545f757f3fSDimitry Andric 
61555ffd83dbSDimitry Andric       AllocaInst *AI = new AllocaInst(Ty, AS, Size, *Align);
61560b57cec5SDimitry Andric       AI->setUsedWithInAlloca(InAlloca);
61570b57cec5SDimitry Andric       AI->setSwiftError(SwiftError);
61580b57cec5SDimitry Andric       I = AI;
615981ad6265SDimitry Andric       ResTypeID = getVirtualTypeID(AI->getType(), TyID);
61600b57cec5SDimitry Andric       InstructionList.push_back(I);
61610b57cec5SDimitry Andric       break;
61620b57cec5SDimitry Andric     }
61630b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
61640b57cec5SDimitry Andric       unsigned OpNum = 0;
61650b57cec5SDimitry Andric       Value *Op;
616681ad6265SDimitry Andric       unsigned OpTypeID;
616781ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) ||
61680b57cec5SDimitry Andric           (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
61690b57cec5SDimitry Andric         return error("Invalid record");
61700b57cec5SDimitry Andric 
61710b57cec5SDimitry Andric       if (!isa<PointerType>(Op->getType()))
61720b57cec5SDimitry Andric         return error("Load operand is not a pointer type");
61730b57cec5SDimitry Andric 
61740b57cec5SDimitry Andric       Type *Ty = nullptr;
61750b57cec5SDimitry Andric       if (OpNum + 3 == Record.size()) {
617681ad6265SDimitry Andric         ResTypeID = Record[OpNum++];
617781ad6265SDimitry Andric         Ty = getTypeByID(ResTypeID);
6178fe6060f1SDimitry Andric       } else {
617981ad6265SDimitry Andric         ResTypeID = getContainedTypeID(OpTypeID);
618081ad6265SDimitry Andric         Ty = getTypeByID(ResTypeID);
6181fe6060f1SDimitry Andric       }
61820b57cec5SDimitry Andric 
61835f757f3fSDimitry Andric       if (!Ty)
61845f757f3fSDimitry Andric         return error("Missing load type");
61855f757f3fSDimitry Andric 
61860b57cec5SDimitry Andric       if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
61870b57cec5SDimitry Andric         return Err;
61880b57cec5SDimitry Andric 
61898bcb0991SDimitry Andric       MaybeAlign Align;
61900b57cec5SDimitry Andric       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
61910b57cec5SDimitry Andric         return Err;
61925ffd83dbSDimitry Andric       SmallPtrSet<Type *, 4> Visited;
61935ffd83dbSDimitry Andric       if (!Align && !Ty->isSized(&Visited))
61945ffd83dbSDimitry Andric         return error("load of unsized type");
61955ffd83dbSDimitry Andric       if (!Align)
61965ffd83dbSDimitry Andric         Align = TheModule->getDataLayout().getABITypeAlign(Ty);
61975ffd83dbSDimitry Andric       I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align);
61980b57cec5SDimitry Andric       InstructionList.push_back(I);
61990b57cec5SDimitry Andric       break;
62000b57cec5SDimitry Andric     }
62010b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_LOADATOMIC: {
62020b57cec5SDimitry Andric        // LOADATOMIC: [opty, op, align, vol, ordering, ssid]
62030b57cec5SDimitry Andric       unsigned OpNum = 0;
62040b57cec5SDimitry Andric       Value *Op;
620581ad6265SDimitry Andric       unsigned OpTypeID;
620681ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) ||
62070b57cec5SDimitry Andric           (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
62080b57cec5SDimitry Andric         return error("Invalid record");
62090b57cec5SDimitry Andric 
62100b57cec5SDimitry Andric       if (!isa<PointerType>(Op->getType()))
62110b57cec5SDimitry Andric         return error("Load operand is not a pointer type");
62120b57cec5SDimitry Andric 
62130b57cec5SDimitry Andric       Type *Ty = nullptr;
62140b57cec5SDimitry Andric       if (OpNum + 5 == Record.size()) {
621581ad6265SDimitry Andric         ResTypeID = Record[OpNum++];
621681ad6265SDimitry Andric         Ty = getTypeByID(ResTypeID);
6217fe6060f1SDimitry Andric       } else {
621881ad6265SDimitry Andric         ResTypeID = getContainedTypeID(OpTypeID);
621981ad6265SDimitry Andric         Ty = getTypeByID(ResTypeID);
6220fe6060f1SDimitry Andric       }
62210b57cec5SDimitry Andric 
62225f757f3fSDimitry Andric       if (!Ty)
62235f757f3fSDimitry Andric         return error("Missing atomic load type");
62245f757f3fSDimitry Andric 
62250b57cec5SDimitry Andric       if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
62260b57cec5SDimitry Andric         return Err;
62270b57cec5SDimitry Andric 
62280b57cec5SDimitry Andric       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
62290b57cec5SDimitry Andric       if (Ordering == AtomicOrdering::NotAtomic ||
62300b57cec5SDimitry Andric           Ordering == AtomicOrdering::Release ||
62310b57cec5SDimitry Andric           Ordering == AtomicOrdering::AcquireRelease)
62320b57cec5SDimitry Andric         return error("Invalid record");
62330b57cec5SDimitry Andric       if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
62340b57cec5SDimitry Andric         return error("Invalid record");
62350b57cec5SDimitry Andric       SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
62360b57cec5SDimitry Andric 
62378bcb0991SDimitry Andric       MaybeAlign Align;
62380b57cec5SDimitry Andric       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
62390b57cec5SDimitry Andric         return Err;
62405ffd83dbSDimitry Andric       if (!Align)
62415ffd83dbSDimitry Andric         return error("Alignment missing from atomic load");
62425ffd83dbSDimitry Andric       I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align, Ordering, SSID);
62430b57cec5SDimitry Andric       InstructionList.push_back(I);
62440b57cec5SDimitry Andric       break;
62450b57cec5SDimitry Andric     }
62460b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_STORE:
62470b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
62480b57cec5SDimitry Andric       unsigned OpNum = 0;
62490b57cec5SDimitry Andric       Value *Val, *Ptr;
625081ad6265SDimitry Andric       unsigned PtrTypeID, ValTypeID;
625181ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
625281ad6265SDimitry Andric         return error("Invalid record");
625381ad6265SDimitry Andric 
625481ad6265SDimitry Andric       if (BitCode == bitc::FUNC_CODE_INST_STORE) {
625581ad6265SDimitry Andric         if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
625681ad6265SDimitry Andric           return error("Invalid record");
625781ad6265SDimitry Andric       } else {
625881ad6265SDimitry Andric         ValTypeID = getContainedTypeID(PtrTypeID);
625981ad6265SDimitry Andric         if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
626081ad6265SDimitry Andric                      ValTypeID, Val, CurBB))
626181ad6265SDimitry Andric           return error("Invalid record");
626281ad6265SDimitry Andric       }
626381ad6265SDimitry Andric 
626481ad6265SDimitry Andric       if (OpNum + 2 != Record.size())
62650b57cec5SDimitry Andric         return error("Invalid record");
62660b57cec5SDimitry Andric 
62670b57cec5SDimitry Andric       if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
62680b57cec5SDimitry Andric         return Err;
62698bcb0991SDimitry Andric       MaybeAlign Align;
62700b57cec5SDimitry Andric       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
62710b57cec5SDimitry Andric         return Err;
62725ffd83dbSDimitry Andric       SmallPtrSet<Type *, 4> Visited;
62735ffd83dbSDimitry Andric       if (!Align && !Val->getType()->isSized(&Visited))
62745ffd83dbSDimitry Andric         return error("store of unsized type");
62755ffd83dbSDimitry Andric       if (!Align)
62765ffd83dbSDimitry Andric         Align = TheModule->getDataLayout().getABITypeAlign(Val->getType());
62775ffd83dbSDimitry Andric       I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align);
62780b57cec5SDimitry Andric       InstructionList.push_back(I);
62790b57cec5SDimitry Andric       break;
62800b57cec5SDimitry Andric     }
62810b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_STOREATOMIC:
62820b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
62830b57cec5SDimitry Andric       // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid]
62840b57cec5SDimitry Andric       unsigned OpNum = 0;
62850b57cec5SDimitry Andric       Value *Val, *Ptr;
628681ad6265SDimitry Andric       unsigned PtrTypeID, ValTypeID;
628781ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB) ||
628881ad6265SDimitry Andric           !isa<PointerType>(Ptr->getType()))
628981ad6265SDimitry Andric         return error("Invalid record");
629081ad6265SDimitry Andric       if (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC) {
629181ad6265SDimitry Andric         if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
629281ad6265SDimitry Andric           return error("Invalid record");
629381ad6265SDimitry Andric       } else {
629481ad6265SDimitry Andric         ValTypeID = getContainedTypeID(PtrTypeID);
629581ad6265SDimitry Andric         if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
629681ad6265SDimitry Andric                      ValTypeID, Val, CurBB))
629781ad6265SDimitry Andric           return error("Invalid record");
629881ad6265SDimitry Andric       }
629981ad6265SDimitry Andric 
630081ad6265SDimitry Andric       if (OpNum + 4 != Record.size())
63010b57cec5SDimitry Andric         return error("Invalid record");
63020b57cec5SDimitry Andric 
63030b57cec5SDimitry Andric       if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
63040b57cec5SDimitry Andric         return Err;
63050b57cec5SDimitry Andric       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
63060b57cec5SDimitry Andric       if (Ordering == AtomicOrdering::NotAtomic ||
63070b57cec5SDimitry Andric           Ordering == AtomicOrdering::Acquire ||
63080b57cec5SDimitry Andric           Ordering == AtomicOrdering::AcquireRelease)
63090b57cec5SDimitry Andric         return error("Invalid record");
63100b57cec5SDimitry Andric       SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
63110b57cec5SDimitry Andric       if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
63120b57cec5SDimitry Andric         return error("Invalid record");
63130b57cec5SDimitry Andric 
63148bcb0991SDimitry Andric       MaybeAlign Align;
63150b57cec5SDimitry Andric       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
63160b57cec5SDimitry Andric         return Err;
63175ffd83dbSDimitry Andric       if (!Align)
63185ffd83dbSDimitry Andric         return error("Alignment missing from atomic store");
63195ffd83dbSDimitry Andric       I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align, Ordering, SSID);
63200b57cec5SDimitry Andric       InstructionList.push_back(I);
63210b57cec5SDimitry Andric       break;
63220b57cec5SDimitry Andric     }
6323e8d8bef9SDimitry Andric     case bitc::FUNC_CODE_INST_CMPXCHG_OLD: {
6324e8d8bef9SDimitry Andric       // CMPXCHG_OLD: [ptrty, ptr, cmp, val, vol, ordering, synchscope,
6325e8d8bef9SDimitry Andric       // failure_ordering?, weak?]
6326e8d8bef9SDimitry Andric       const size_t NumRecords = Record.size();
63270b57cec5SDimitry Andric       unsigned OpNum = 0;
6328e8d8bef9SDimitry Andric       Value *Ptr = nullptr;
632981ad6265SDimitry Andric       unsigned PtrTypeID;
633081ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
63310b57cec5SDimitry Andric         return error("Invalid record");
63320b57cec5SDimitry Andric 
63330b57cec5SDimitry Andric       if (!isa<PointerType>(Ptr->getType()))
63340b57cec5SDimitry Andric         return error("Cmpxchg operand is not a pointer type");
63350b57cec5SDimitry Andric 
6336e8d8bef9SDimitry Andric       Value *Cmp = nullptr;
633781ad6265SDimitry Andric       unsigned CmpTypeID = getContainedTypeID(PtrTypeID);
633881ad6265SDimitry Andric       if (popValue(Record, OpNum, NextValueNo, getTypeByID(CmpTypeID),
633981ad6265SDimitry Andric                    CmpTypeID, Cmp, CurBB))
63400b57cec5SDimitry Andric         return error("Invalid record");
6341e8d8bef9SDimitry Andric 
6342e8d8bef9SDimitry Andric       Value *New = nullptr;
634381ad6265SDimitry Andric       if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), CmpTypeID,
634481ad6265SDimitry Andric                    New, CurBB) ||
6345e8d8bef9SDimitry Andric           NumRecords < OpNum + 3 || NumRecords > OpNum + 5)
63460b57cec5SDimitry Andric         return error("Invalid record");
63470b57cec5SDimitry Andric 
6348e8d8bef9SDimitry Andric       const AtomicOrdering SuccessOrdering =
6349e8d8bef9SDimitry Andric           getDecodedOrdering(Record[OpNum + 1]);
63500b57cec5SDimitry Andric       if (SuccessOrdering == AtomicOrdering::NotAtomic ||
63510b57cec5SDimitry Andric           SuccessOrdering == AtomicOrdering::Unordered)
63520b57cec5SDimitry Andric         return error("Invalid record");
6353e8d8bef9SDimitry Andric 
6354e8d8bef9SDimitry Andric       const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
63550b57cec5SDimitry Andric 
63560b57cec5SDimitry Andric       if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
63570b57cec5SDimitry Andric         return Err;
63580b57cec5SDimitry Andric 
6359e8d8bef9SDimitry Andric       const AtomicOrdering FailureOrdering =
6360e8d8bef9SDimitry Andric           NumRecords < 7
6361e8d8bef9SDimitry Andric               ? AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering)
6362e8d8bef9SDimitry Andric               : getDecodedOrdering(Record[OpNum + 3]);
6363e8d8bef9SDimitry Andric 
6364fe6060f1SDimitry Andric       if (FailureOrdering == AtomicOrdering::NotAtomic ||
6365fe6060f1SDimitry Andric           FailureOrdering == AtomicOrdering::Unordered)
6366fe6060f1SDimitry Andric         return error("Invalid record");
6367fe6060f1SDimitry Andric 
6368e8d8bef9SDimitry Andric       const Align Alignment(
63695ffd83dbSDimitry Andric           TheModule->getDataLayout().getTypeStoreSize(Cmp->getType()));
6370e8d8bef9SDimitry Andric 
63715ffd83dbSDimitry Andric       I = new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment, SuccessOrdering,
63725ffd83dbSDimitry Andric                                 FailureOrdering, SSID);
63730b57cec5SDimitry Andric       cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
63740b57cec5SDimitry Andric 
6375e8d8bef9SDimitry Andric       if (NumRecords < 8) {
63760b57cec5SDimitry Andric         // Before weak cmpxchgs existed, the instruction simply returned the
63770b57cec5SDimitry Andric         // value loaded from memory, so bitcode files from that era will be
63780b57cec5SDimitry Andric         // expecting the first component of a modern cmpxchg.
6379bdd1243dSDimitry Andric         I->insertInto(CurBB, CurBB->end());
63800b57cec5SDimitry Andric         I = ExtractValueInst::Create(I, 0);
638181ad6265SDimitry Andric         ResTypeID = CmpTypeID;
63820b57cec5SDimitry Andric       } else {
63830b57cec5SDimitry Andric         cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum + 4]);
638481ad6265SDimitry Andric         unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(Context));
638581ad6265SDimitry Andric         ResTypeID = getVirtualTypeID(I->getType(), {CmpTypeID, I1TypeID});
63860b57cec5SDimitry Andric       }
63870b57cec5SDimitry Andric 
63880b57cec5SDimitry Andric       InstructionList.push_back(I);
63890b57cec5SDimitry Andric       break;
63900b57cec5SDimitry Andric     }
6391e8d8bef9SDimitry Andric     case bitc::FUNC_CODE_INST_CMPXCHG: {
6392e8d8bef9SDimitry Andric       // CMPXCHG: [ptrty, ptr, cmp, val, vol, success_ordering, synchscope,
6393fe6060f1SDimitry Andric       // failure_ordering, weak, align?]
6394e8d8bef9SDimitry Andric       const size_t NumRecords = Record.size();
6395e8d8bef9SDimitry Andric       unsigned OpNum = 0;
6396e8d8bef9SDimitry Andric       Value *Ptr = nullptr;
639781ad6265SDimitry Andric       unsigned PtrTypeID;
639881ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6399e8d8bef9SDimitry Andric         return error("Invalid record");
6400e8d8bef9SDimitry Andric 
6401e8d8bef9SDimitry Andric       if (!isa<PointerType>(Ptr->getType()))
6402e8d8bef9SDimitry Andric         return error("Cmpxchg operand is not a pointer type");
6403e8d8bef9SDimitry Andric 
6404e8d8bef9SDimitry Andric       Value *Cmp = nullptr;
640581ad6265SDimitry Andric       unsigned CmpTypeID;
640681ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Cmp, CmpTypeID, CurBB))
6407e8d8bef9SDimitry Andric         return error("Invalid record");
6408e8d8bef9SDimitry Andric 
6409e8d8bef9SDimitry Andric       Value *Val = nullptr;
641081ad6265SDimitry Andric       if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), CmpTypeID, Val,
641181ad6265SDimitry Andric                    CurBB))
6412e8d8bef9SDimitry Andric         return error("Invalid record");
6413e8d8bef9SDimitry Andric 
6414fe6060f1SDimitry Andric       if (NumRecords < OpNum + 3 || NumRecords > OpNum + 6)
6415fe6060f1SDimitry Andric         return error("Invalid record");
6416fe6060f1SDimitry Andric 
6417fe6060f1SDimitry Andric       const bool IsVol = Record[OpNum];
6418fe6060f1SDimitry Andric 
6419e8d8bef9SDimitry Andric       const AtomicOrdering SuccessOrdering =
6420e8d8bef9SDimitry Andric           getDecodedOrdering(Record[OpNum + 1]);
6421fe6060f1SDimitry Andric       if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
6422fe6060f1SDimitry Andric         return error("Invalid cmpxchg success ordering");
6423e8d8bef9SDimitry Andric 
6424e8d8bef9SDimitry Andric       const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
6425e8d8bef9SDimitry Andric 
6426e8d8bef9SDimitry Andric       if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
6427e8d8bef9SDimitry Andric         return Err;
6428e8d8bef9SDimitry Andric 
6429e8d8bef9SDimitry Andric       const AtomicOrdering FailureOrdering =
6430e8d8bef9SDimitry Andric           getDecodedOrdering(Record[OpNum + 3]);
6431fe6060f1SDimitry Andric       if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
6432fe6060f1SDimitry Andric         return error("Invalid cmpxchg failure ordering");
6433e8d8bef9SDimitry Andric 
6434fe6060f1SDimitry Andric       const bool IsWeak = Record[OpNum + 4];
6435e8d8bef9SDimitry Andric 
6436fe6060f1SDimitry Andric       MaybeAlign Alignment;
6437fe6060f1SDimitry Andric 
6438fe6060f1SDimitry Andric       if (NumRecords == (OpNum + 6)) {
6439fe6060f1SDimitry Andric         if (Error Err = parseAlignmentValue(Record[OpNum + 5], Alignment))
6440fe6060f1SDimitry Andric           return Err;
6441fe6060f1SDimitry Andric       }
6442fe6060f1SDimitry Andric       if (!Alignment)
6443fe6060f1SDimitry Andric         Alignment =
6444fe6060f1SDimitry Andric             Align(TheModule->getDataLayout().getTypeStoreSize(Cmp->getType()));
6445fe6060f1SDimitry Andric 
6446fe6060f1SDimitry Andric       I = new AtomicCmpXchgInst(Ptr, Cmp, Val, *Alignment, SuccessOrdering,
6447e8d8bef9SDimitry Andric                                 FailureOrdering, SSID);
6448fe6060f1SDimitry Andric       cast<AtomicCmpXchgInst>(I)->setVolatile(IsVol);
6449fe6060f1SDimitry Andric       cast<AtomicCmpXchgInst>(I)->setWeak(IsWeak);
6450e8d8bef9SDimitry Andric 
645181ad6265SDimitry Andric       unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(Context));
645281ad6265SDimitry Andric       ResTypeID = getVirtualTypeID(I->getType(), {CmpTypeID, I1TypeID});
645381ad6265SDimitry Andric 
6454e8d8bef9SDimitry Andric       InstructionList.push_back(I);
6455e8d8bef9SDimitry Andric       break;
6456e8d8bef9SDimitry Andric     }
6457fe6060f1SDimitry Andric     case bitc::FUNC_CODE_INST_ATOMICRMW_OLD:
64580b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_ATOMICRMW: {
6459fe6060f1SDimitry Andric       // ATOMICRMW_OLD: [ptrty, ptr, val, op, vol, ordering, ssid, align?]
6460fe6060f1SDimitry Andric       // ATOMICRMW: [ptrty, ptr, valty, val, op, vol, ordering, ssid, align?]
6461fe6060f1SDimitry Andric       const size_t NumRecords = Record.size();
64620b57cec5SDimitry Andric       unsigned OpNum = 0;
6463fe6060f1SDimitry Andric 
6464fe6060f1SDimitry Andric       Value *Ptr = nullptr;
646581ad6265SDimitry Andric       unsigned PtrTypeID;
646681ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
64670b57cec5SDimitry Andric         return error("Invalid record");
6468fe6060f1SDimitry Andric 
6469fe6060f1SDimitry Andric       if (!isa<PointerType>(Ptr->getType()))
6470fe6060f1SDimitry Andric         return error("Invalid record");
6471fe6060f1SDimitry Andric 
6472fe6060f1SDimitry Andric       Value *Val = nullptr;
647381ad6265SDimitry Andric       unsigned ValTypeID = InvalidTypeID;
6474fe6060f1SDimitry Andric       if (BitCode == bitc::FUNC_CODE_INST_ATOMICRMW_OLD) {
647581ad6265SDimitry Andric         ValTypeID = getContainedTypeID(PtrTypeID);
6476fe6060f1SDimitry Andric         if (popValue(Record, OpNum, NextValueNo,
647781ad6265SDimitry Andric                      getTypeByID(ValTypeID), ValTypeID, Val, CurBB))
6478fe6060f1SDimitry Andric           return error("Invalid record");
6479fe6060f1SDimitry Andric       } else {
648081ad6265SDimitry Andric         if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6481fe6060f1SDimitry Andric           return error("Invalid record");
6482fe6060f1SDimitry Andric       }
6483fe6060f1SDimitry Andric 
6484fe6060f1SDimitry Andric       if (!(NumRecords == (OpNum + 4) || NumRecords == (OpNum + 5)))
6485fe6060f1SDimitry Andric         return error("Invalid record");
6486fe6060f1SDimitry Andric 
6487fe6060f1SDimitry Andric       const AtomicRMWInst::BinOp Operation =
6488fe6060f1SDimitry Andric           getDecodedRMWOperation(Record[OpNum]);
64890b57cec5SDimitry Andric       if (Operation < AtomicRMWInst::FIRST_BINOP ||
64900b57cec5SDimitry Andric           Operation > AtomicRMWInst::LAST_BINOP)
64910b57cec5SDimitry Andric         return error("Invalid record");
6492fe6060f1SDimitry Andric 
6493fe6060f1SDimitry Andric       const bool IsVol = Record[OpNum + 1];
6494fe6060f1SDimitry Andric 
6495fe6060f1SDimitry Andric       const AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
64960b57cec5SDimitry Andric       if (Ordering == AtomicOrdering::NotAtomic ||
64970b57cec5SDimitry Andric           Ordering == AtomicOrdering::Unordered)
64980b57cec5SDimitry Andric         return error("Invalid record");
6499fe6060f1SDimitry Andric 
6500fe6060f1SDimitry Andric       const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6501fe6060f1SDimitry Andric 
6502fe6060f1SDimitry Andric       MaybeAlign Alignment;
6503fe6060f1SDimitry Andric 
6504fe6060f1SDimitry Andric       if (NumRecords == (OpNum + 5)) {
6505fe6060f1SDimitry Andric         if (Error Err = parseAlignmentValue(Record[OpNum + 4], Alignment))
6506fe6060f1SDimitry Andric           return Err;
6507fe6060f1SDimitry Andric       }
6508fe6060f1SDimitry Andric 
6509fe6060f1SDimitry Andric       if (!Alignment)
6510fe6060f1SDimitry Andric         Alignment =
6511fe6060f1SDimitry Andric             Align(TheModule->getDataLayout().getTypeStoreSize(Val->getType()));
6512fe6060f1SDimitry Andric 
6513fe6060f1SDimitry Andric       I = new AtomicRMWInst(Operation, Ptr, Val, *Alignment, Ordering, SSID);
651481ad6265SDimitry Andric       ResTypeID = ValTypeID;
6515fe6060f1SDimitry Andric       cast<AtomicRMWInst>(I)->setVolatile(IsVol);
6516fe6060f1SDimitry Andric 
65170b57cec5SDimitry Andric       InstructionList.push_back(I);
65180b57cec5SDimitry Andric       break;
65190b57cec5SDimitry Andric     }
65200b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid]
65210b57cec5SDimitry Andric       if (2 != Record.size())
65220b57cec5SDimitry Andric         return error("Invalid record");
65230b57cec5SDimitry Andric       AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
65240b57cec5SDimitry Andric       if (Ordering == AtomicOrdering::NotAtomic ||
65250b57cec5SDimitry Andric           Ordering == AtomicOrdering::Unordered ||
65260b57cec5SDimitry Andric           Ordering == AtomicOrdering::Monotonic)
65270b57cec5SDimitry Andric         return error("Invalid record");
65280b57cec5SDimitry Andric       SyncScope::ID SSID = getDecodedSyncScopeID(Record[1]);
65290b57cec5SDimitry Andric       I = new FenceInst(Context, Ordering, SSID);
65300b57cec5SDimitry Andric       InstructionList.push_back(I);
65310b57cec5SDimitry Andric       break;
65320b57cec5SDimitry Andric     }
6533*0fca6ea1SDimitry Andric     case bitc::FUNC_CODE_DEBUG_RECORD_LABEL: {
6534*0fca6ea1SDimitry Andric       // DbgLabelRecords are placed after the Instructions that they are
6535*0fca6ea1SDimitry Andric       // attached to.
6536*0fca6ea1SDimitry Andric       SeenDebugRecord = true;
6537*0fca6ea1SDimitry Andric       Instruction *Inst = getLastInstruction();
6538*0fca6ea1SDimitry Andric       if (!Inst)
6539*0fca6ea1SDimitry Andric         return error("Invalid dbg record: missing instruction");
6540*0fca6ea1SDimitry Andric       DILocation *DIL = cast<DILocation>(getFnMetadataByID(Record[0]));
6541*0fca6ea1SDimitry Andric       DILabel *Label = cast<DILabel>(getFnMetadataByID(Record[1]));
6542*0fca6ea1SDimitry Andric       Inst->getParent()->insertDbgRecordBefore(
6543*0fca6ea1SDimitry Andric           new DbgLabelRecord(Label, DebugLoc(DIL)), Inst->getIterator());
6544*0fca6ea1SDimitry Andric       continue; // This isn't an instruction.
6545*0fca6ea1SDimitry Andric     }
6546*0fca6ea1SDimitry Andric     case bitc::FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE:
6547*0fca6ea1SDimitry Andric     case bitc::FUNC_CODE_DEBUG_RECORD_VALUE:
6548*0fca6ea1SDimitry Andric     case bitc::FUNC_CODE_DEBUG_RECORD_DECLARE:
6549*0fca6ea1SDimitry Andric     case bitc::FUNC_CODE_DEBUG_RECORD_ASSIGN: {
6550*0fca6ea1SDimitry Andric       // DbgVariableRecords are placed after the Instructions that they are
6551*0fca6ea1SDimitry Andric       // attached to.
6552*0fca6ea1SDimitry Andric       SeenDebugRecord = true;
6553*0fca6ea1SDimitry Andric       Instruction *Inst = getLastInstruction();
6554*0fca6ea1SDimitry Andric       if (!Inst)
6555*0fca6ea1SDimitry Andric         return error("Invalid dbg record: missing instruction");
6556*0fca6ea1SDimitry Andric 
6557*0fca6ea1SDimitry Andric       // First 3 fields are common to all kinds:
6558*0fca6ea1SDimitry Andric       //   DILocation, DILocalVariable, DIExpression
6559*0fca6ea1SDimitry Andric       // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE)
6560*0fca6ea1SDimitry Andric       //   ..., LocationMetadata
6561*0fca6ea1SDimitry Andric       // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE - abbrev'd)
6562*0fca6ea1SDimitry Andric       //   ..., Value
6563*0fca6ea1SDimitry Andric       // dbg_declare (FUNC_CODE_DEBUG_RECORD_DECLARE)
6564*0fca6ea1SDimitry Andric       //   ..., LocationMetadata
6565*0fca6ea1SDimitry Andric       // dbg_assign (FUNC_CODE_DEBUG_RECORD_ASSIGN)
6566*0fca6ea1SDimitry Andric       //   ..., LocationMetadata, DIAssignID, DIExpression, LocationMetadata
6567*0fca6ea1SDimitry Andric       unsigned Slot = 0;
6568*0fca6ea1SDimitry Andric       // Common fields (0-2).
6569*0fca6ea1SDimitry Andric       DILocation *DIL = cast<DILocation>(getFnMetadataByID(Record[Slot++]));
6570*0fca6ea1SDimitry Andric       DILocalVariable *Var =
6571*0fca6ea1SDimitry Andric           cast<DILocalVariable>(getFnMetadataByID(Record[Slot++]));
6572*0fca6ea1SDimitry Andric       DIExpression *Expr =
6573*0fca6ea1SDimitry Andric           cast<DIExpression>(getFnMetadataByID(Record[Slot++]));
6574*0fca6ea1SDimitry Andric 
6575*0fca6ea1SDimitry Andric       // Union field (3: LocationMetadata | Value).
6576*0fca6ea1SDimitry Andric       Metadata *RawLocation = nullptr;
6577*0fca6ea1SDimitry Andric       if (BitCode == bitc::FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE) {
6578*0fca6ea1SDimitry Andric         Value *V = nullptr;
6579*0fca6ea1SDimitry Andric         unsigned TyID = 0;
6580*0fca6ea1SDimitry Andric         // We never expect to see a fwd reference value here because
6581*0fca6ea1SDimitry Andric         // use-before-defs are encoded with the standard non-abbrev record
6582*0fca6ea1SDimitry Andric         // type (they'd require encoding the type too, and they're rare). As a
6583*0fca6ea1SDimitry Andric         // result, getValueTypePair only ever increments Slot by one here (once
6584*0fca6ea1SDimitry Andric         // for the value, never twice for value and type).
6585*0fca6ea1SDimitry Andric         unsigned SlotBefore = Slot;
6586*0fca6ea1SDimitry Andric         if (getValueTypePair(Record, Slot, NextValueNo, V, TyID, CurBB))
6587*0fca6ea1SDimitry Andric           return error("Invalid dbg record: invalid value");
6588*0fca6ea1SDimitry Andric         (void)SlotBefore;
6589*0fca6ea1SDimitry Andric         assert((SlotBefore == Slot - 1) && "unexpected fwd ref");
6590*0fca6ea1SDimitry Andric         RawLocation = ValueAsMetadata::get(V);
6591*0fca6ea1SDimitry Andric       } else {
6592*0fca6ea1SDimitry Andric         RawLocation = getFnMetadataByID(Record[Slot++]);
6593*0fca6ea1SDimitry Andric       }
6594*0fca6ea1SDimitry Andric 
6595*0fca6ea1SDimitry Andric       DbgVariableRecord *DVR = nullptr;
6596*0fca6ea1SDimitry Andric       switch (BitCode) {
6597*0fca6ea1SDimitry Andric       case bitc::FUNC_CODE_DEBUG_RECORD_VALUE:
6598*0fca6ea1SDimitry Andric       case bitc::FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE:
6599*0fca6ea1SDimitry Andric         DVR = new DbgVariableRecord(RawLocation, Var, Expr, DIL,
6600*0fca6ea1SDimitry Andric                                     DbgVariableRecord::LocationType::Value);
6601*0fca6ea1SDimitry Andric         break;
6602*0fca6ea1SDimitry Andric       case bitc::FUNC_CODE_DEBUG_RECORD_DECLARE:
6603*0fca6ea1SDimitry Andric         DVR = new DbgVariableRecord(RawLocation, Var, Expr, DIL,
6604*0fca6ea1SDimitry Andric                                     DbgVariableRecord::LocationType::Declare);
6605*0fca6ea1SDimitry Andric         break;
6606*0fca6ea1SDimitry Andric       case bitc::FUNC_CODE_DEBUG_RECORD_ASSIGN: {
6607*0fca6ea1SDimitry Andric         DIAssignID *ID = cast<DIAssignID>(getFnMetadataByID(Record[Slot++]));
6608*0fca6ea1SDimitry Andric         DIExpression *AddrExpr =
6609*0fca6ea1SDimitry Andric             cast<DIExpression>(getFnMetadataByID(Record[Slot++]));
6610*0fca6ea1SDimitry Andric         Metadata *Addr = getFnMetadataByID(Record[Slot++]);
6611*0fca6ea1SDimitry Andric         DVR = new DbgVariableRecord(RawLocation, Var, Expr, ID, Addr, AddrExpr,
6612*0fca6ea1SDimitry Andric                                     DIL);
6613*0fca6ea1SDimitry Andric         break;
6614*0fca6ea1SDimitry Andric       }
6615*0fca6ea1SDimitry Andric       default:
6616*0fca6ea1SDimitry Andric         llvm_unreachable("Unknown DbgVariableRecord bitcode");
6617*0fca6ea1SDimitry Andric       }
6618*0fca6ea1SDimitry Andric       Inst->getParent()->insertDbgRecordBefore(DVR, Inst->getIterator());
6619*0fca6ea1SDimitry Andric       continue; // This isn't an instruction.
6620*0fca6ea1SDimitry Andric     }
66210b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CALL: {
66220b57cec5SDimitry Andric       // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
66230b57cec5SDimitry Andric       if (Record.size() < 3)
66240b57cec5SDimitry Andric         return error("Invalid record");
66250b57cec5SDimitry Andric 
66260b57cec5SDimitry Andric       unsigned OpNum = 0;
66270b57cec5SDimitry Andric       AttributeList PAL = getAttributes(Record[OpNum++]);
66280b57cec5SDimitry Andric       unsigned CCInfo = Record[OpNum++];
66290b57cec5SDimitry Andric 
66300b57cec5SDimitry Andric       FastMathFlags FMF;
66310b57cec5SDimitry Andric       if ((CCInfo >> bitc::CALL_FMF) & 1) {
66320b57cec5SDimitry Andric         FMF = getDecodedFastMathFlags(Record[OpNum++]);
66330b57cec5SDimitry Andric         if (!FMF.any())
66340b57cec5SDimitry Andric           return error("Fast math flags indicator set for call with no FMF");
66350b57cec5SDimitry Andric       }
66360b57cec5SDimitry Andric 
663781ad6265SDimitry Andric       unsigned FTyID = InvalidTypeID;
66380b57cec5SDimitry Andric       FunctionType *FTy = nullptr;
66390b57cec5SDimitry Andric       if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) {
664081ad6265SDimitry Andric         FTyID = Record[OpNum++];
664181ad6265SDimitry Andric         FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
6642fe6060f1SDimitry Andric         if (!FTy)
66430b57cec5SDimitry Andric           return error("Explicit call type is not a function type");
66440b57cec5SDimitry Andric       }
66450b57cec5SDimitry Andric 
66460b57cec5SDimitry Andric       Value *Callee;
664781ad6265SDimitry Andric       unsigned CalleeTypeID;
664881ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
664981ad6265SDimitry Andric                            CurBB))
66500b57cec5SDimitry Andric         return error("Invalid record");
66510b57cec5SDimitry Andric 
66520b57cec5SDimitry Andric       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
66530b57cec5SDimitry Andric       if (!OpTy)
66540b57cec5SDimitry Andric         return error("Callee is not a pointer type");
66550b57cec5SDimitry Andric       if (!FTy) {
665681ad6265SDimitry Andric         FTyID = getContainedTypeID(CalleeTypeID);
665781ad6265SDimitry Andric         FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
6658fe6060f1SDimitry Andric         if (!FTy)
66590b57cec5SDimitry Andric           return error("Callee is not of pointer to function type");
666006c3fb27SDimitry Andric       }
66610b57cec5SDimitry Andric       if (Record.size() < FTy->getNumParams() + OpNum)
66620b57cec5SDimitry Andric         return error("Insufficient operands to call");
66630b57cec5SDimitry Andric 
66640b57cec5SDimitry Andric       SmallVector<Value*, 16> Args;
666581ad6265SDimitry Andric       SmallVector<unsigned, 16> ArgTyIDs;
66660b57cec5SDimitry Andric       // Read the fixed params.
66670b57cec5SDimitry Andric       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
666881ad6265SDimitry Andric         unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
66690b57cec5SDimitry Andric         if (FTy->getParamType(i)->isLabelTy())
66700b57cec5SDimitry Andric           Args.push_back(getBasicBlock(Record[OpNum]));
66710b57cec5SDimitry Andric         else
66720b57cec5SDimitry Andric           Args.push_back(getValue(Record, OpNum, NextValueNo,
667381ad6265SDimitry Andric                                   FTy->getParamType(i), ArgTyID, CurBB));
667481ad6265SDimitry Andric         ArgTyIDs.push_back(ArgTyID);
66750b57cec5SDimitry Andric         if (!Args.back())
66760b57cec5SDimitry Andric           return error("Invalid record");
66770b57cec5SDimitry Andric       }
66780b57cec5SDimitry Andric 
66790b57cec5SDimitry Andric       // Read type/value pairs for varargs params.
66800b57cec5SDimitry Andric       if (!FTy->isVarArg()) {
66810b57cec5SDimitry Andric         if (OpNum != Record.size())
66820b57cec5SDimitry Andric           return error("Invalid record");
66830b57cec5SDimitry Andric       } else {
66840b57cec5SDimitry Andric         while (OpNum != Record.size()) {
66850b57cec5SDimitry Andric           Value *Op;
668681ad6265SDimitry Andric           unsigned OpTypeID;
668781ad6265SDimitry Andric           if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
66880b57cec5SDimitry Andric             return error("Invalid record");
66890b57cec5SDimitry Andric           Args.push_back(Op);
669081ad6265SDimitry Andric           ArgTyIDs.push_back(OpTypeID);
66910b57cec5SDimitry Andric         }
66920b57cec5SDimitry Andric       }
66930b57cec5SDimitry Andric 
669481ad6265SDimitry Andric       // Upgrade the bundles if needed.
669581ad6265SDimitry Andric       if (!OperandBundles.empty())
669681ad6265SDimitry Andric         UpgradeOperandBundles(OperandBundles);
669781ad6265SDimitry Andric 
66980b57cec5SDimitry Andric       I = CallInst::Create(FTy, Callee, Args, OperandBundles);
669981ad6265SDimitry Andric       ResTypeID = getContainedTypeID(FTyID);
67000b57cec5SDimitry Andric       OperandBundles.clear();
67010b57cec5SDimitry Andric       InstructionList.push_back(I);
67020b57cec5SDimitry Andric       cast<CallInst>(I)->setCallingConv(
67030b57cec5SDimitry Andric           static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
67040b57cec5SDimitry Andric       CallInst::TailCallKind TCK = CallInst::TCK_None;
67055f757f3fSDimitry Andric       if (CCInfo & (1 << bitc::CALL_TAIL))
67060b57cec5SDimitry Andric         TCK = CallInst::TCK_Tail;
67070b57cec5SDimitry Andric       if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
67080b57cec5SDimitry Andric         TCK = CallInst::TCK_MustTail;
67090b57cec5SDimitry Andric       if (CCInfo & (1 << bitc::CALL_NOTAIL))
67100b57cec5SDimitry Andric         TCK = CallInst::TCK_NoTail;
67110b57cec5SDimitry Andric       cast<CallInst>(I)->setTailCallKind(TCK);
67120b57cec5SDimitry Andric       cast<CallInst>(I)->setAttributes(PAL);
6713*0fca6ea1SDimitry Andric       if (isa<DbgInfoIntrinsic>(I))
6714*0fca6ea1SDimitry Andric         SeenDebugIntrinsic = true;
671581ad6265SDimitry Andric       if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) {
671681ad6265SDimitry Andric         I->deleteValue();
671781ad6265SDimitry Andric         return Err;
671881ad6265SDimitry Andric       }
67190b57cec5SDimitry Andric       if (FMF.any()) {
67200b57cec5SDimitry Andric         if (!isa<FPMathOperator>(I))
67210b57cec5SDimitry Andric           return error("Fast-math-flags specified for call without "
67220b57cec5SDimitry Andric                        "floating-point scalar or vector return type");
67230b57cec5SDimitry Andric         I->setFastMathFlags(FMF);
67240b57cec5SDimitry Andric       }
67250b57cec5SDimitry Andric       break;
67260b57cec5SDimitry Andric     }
67270b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
67280b57cec5SDimitry Andric       if (Record.size() < 3)
67290b57cec5SDimitry Andric         return error("Invalid record");
673081ad6265SDimitry Andric       unsigned OpTyID = Record[0];
673181ad6265SDimitry Andric       Type *OpTy = getTypeByID(OpTyID);
673281ad6265SDimitry Andric       Value *Op = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
673381ad6265SDimitry Andric       ResTypeID = Record[2];
673481ad6265SDimitry Andric       Type *ResTy = getTypeByID(ResTypeID);
67350b57cec5SDimitry Andric       if (!OpTy || !Op || !ResTy)
67360b57cec5SDimitry Andric         return error("Invalid record");
67370b57cec5SDimitry Andric       I = new VAArgInst(Op, ResTy);
67380b57cec5SDimitry Andric       InstructionList.push_back(I);
67390b57cec5SDimitry Andric       break;
67400b57cec5SDimitry Andric     }
67410b57cec5SDimitry Andric 
67420b57cec5SDimitry Andric     case bitc::FUNC_CODE_OPERAND_BUNDLE: {
67430b57cec5SDimitry Andric       // A call or an invoke can be optionally prefixed with some variable
67440b57cec5SDimitry Andric       // number of operand bundle blocks.  These blocks are read into
67450b57cec5SDimitry Andric       // OperandBundles and consumed at the next call or invoke instruction.
67460b57cec5SDimitry Andric 
6747e8d8bef9SDimitry Andric       if (Record.empty() || Record[0] >= BundleTags.size())
67480b57cec5SDimitry Andric         return error("Invalid record");
67490b57cec5SDimitry Andric 
67500b57cec5SDimitry Andric       std::vector<Value *> Inputs;
67510b57cec5SDimitry Andric 
67520b57cec5SDimitry Andric       unsigned OpNum = 1;
67530b57cec5SDimitry Andric       while (OpNum != Record.size()) {
67540b57cec5SDimitry Andric         Value *Op;
675581ad6265SDimitry Andric         unsigned OpTypeID;
675681ad6265SDimitry Andric         if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
67570b57cec5SDimitry Andric           return error("Invalid record");
67580b57cec5SDimitry Andric         Inputs.push_back(Op);
67590b57cec5SDimitry Andric       }
67600b57cec5SDimitry Andric 
67610b57cec5SDimitry Andric       OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
67620b57cec5SDimitry Andric       continue;
67630b57cec5SDimitry Andric     }
6764480093f4SDimitry Andric 
6765480093f4SDimitry Andric     case bitc::FUNC_CODE_INST_FREEZE: { // FREEZE: [opty,opval]
6766480093f4SDimitry Andric       unsigned OpNum = 0;
6767480093f4SDimitry Andric       Value *Op = nullptr;
676881ad6265SDimitry Andric       unsigned OpTypeID;
676981ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
6770480093f4SDimitry Andric         return error("Invalid record");
6771480093f4SDimitry Andric       if (OpNum != Record.size())
6772480093f4SDimitry Andric         return error("Invalid record");
6773480093f4SDimitry Andric 
6774480093f4SDimitry Andric       I = new FreezeInst(Op);
677581ad6265SDimitry Andric       ResTypeID = OpTypeID;
6776480093f4SDimitry Andric       InstructionList.push_back(I);
6777480093f4SDimitry Andric       break;
6778480093f4SDimitry Andric     }
67790b57cec5SDimitry Andric     }
67800b57cec5SDimitry Andric 
67810b57cec5SDimitry Andric     // Add instruction to end of current BB.  If there is no current BB, reject
67820b57cec5SDimitry Andric     // this file.
67830b57cec5SDimitry Andric     if (!CurBB) {
67840b57cec5SDimitry Andric       I->deleteValue();
67850b57cec5SDimitry Andric       return error("Invalid instruction with no BB");
67860b57cec5SDimitry Andric     }
67870b57cec5SDimitry Andric     if (!OperandBundles.empty()) {
67880b57cec5SDimitry Andric       I->deleteValue();
67890b57cec5SDimitry Andric       return error("Operand bundles found with no consumer");
67900b57cec5SDimitry Andric     }
6791bdd1243dSDimitry Andric     I->insertInto(CurBB, CurBB->end());
67920b57cec5SDimitry Andric 
67930b57cec5SDimitry Andric     // If this was a terminator instruction, move to the next block.
67940b57cec5SDimitry Andric     if (I->isTerminator()) {
67950b57cec5SDimitry Andric       ++CurBBNo;
67960b57cec5SDimitry Andric       CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
67970b57cec5SDimitry Andric     }
67980b57cec5SDimitry Andric 
67990b57cec5SDimitry Andric     // Non-void values get registered in the value table for future use.
680081ad6265SDimitry Andric     if (!I->getType()->isVoidTy()) {
680181ad6265SDimitry Andric       assert(I->getType() == getTypeByID(ResTypeID) &&
680281ad6265SDimitry Andric              "Incorrect result type ID");
680381ad6265SDimitry Andric       if (Error Err = ValueList.assignValue(NextValueNo++, I, ResTypeID))
680481ad6265SDimitry Andric         return Err;
680581ad6265SDimitry Andric     }
68060b57cec5SDimitry Andric   }
68070b57cec5SDimitry Andric 
68080b57cec5SDimitry Andric OutOfRecordLoop:
68090b57cec5SDimitry Andric 
68100b57cec5SDimitry Andric   if (!OperandBundles.empty())
68110b57cec5SDimitry Andric     return error("Operand bundles found with no consumer");
68120b57cec5SDimitry Andric 
68130b57cec5SDimitry Andric   // Check the function list for unresolved values.
68140b57cec5SDimitry Andric   if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
68150b57cec5SDimitry Andric     if (!A->getParent()) {
68160b57cec5SDimitry Andric       // We found at least one unresolved value.  Nuke them all to avoid leaks.
68170b57cec5SDimitry Andric       for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
68180b57cec5SDimitry Andric         if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
6819bdd1243dSDimitry Andric           A->replaceAllUsesWith(PoisonValue::get(A->getType()));
68200b57cec5SDimitry Andric           delete A;
68210b57cec5SDimitry Andric         }
68220b57cec5SDimitry Andric       }
68230b57cec5SDimitry Andric       return error("Never resolved value found in function");
68240b57cec5SDimitry Andric     }
68250b57cec5SDimitry Andric   }
68260b57cec5SDimitry Andric 
68270b57cec5SDimitry Andric   // Unexpected unresolved metadata about to be dropped.
68280b57cec5SDimitry Andric   if (MDLoader->hasFwdRefs())
68290b57cec5SDimitry Andric     return error("Invalid function metadata: outgoing forward refs");
68300b57cec5SDimitry Andric 
683181ad6265SDimitry Andric   if (PhiConstExprBB)
683281ad6265SDimitry Andric     PhiConstExprBB->eraseFromParent();
683381ad6265SDimitry Andric 
683481ad6265SDimitry Andric   for (const auto &Pair : ConstExprEdgeBBs) {
683581ad6265SDimitry Andric     BasicBlock *From = Pair.first.first;
683681ad6265SDimitry Andric     BasicBlock *To = Pair.first.second;
683781ad6265SDimitry Andric     BasicBlock *EdgeBB = Pair.second;
683881ad6265SDimitry Andric     BranchInst::Create(To, EdgeBB);
683981ad6265SDimitry Andric     From->getTerminator()->replaceSuccessorWith(To, EdgeBB);
684081ad6265SDimitry Andric     To->replacePhiUsesWith(From, EdgeBB);
684181ad6265SDimitry Andric     EdgeBB->moveBefore(To);
684281ad6265SDimitry Andric   }
684381ad6265SDimitry Andric 
68440b57cec5SDimitry Andric   // Trim the value list down to the size it was before we parsed this function.
68450b57cec5SDimitry Andric   ValueList.shrinkTo(ModuleValueListSize);
68460b57cec5SDimitry Andric   MDLoader->shrinkTo(ModuleMDLoaderSize);
68470b57cec5SDimitry Andric   std::vector<BasicBlock*>().swap(FunctionBBs);
68480b57cec5SDimitry Andric   return Error::success();
68490b57cec5SDimitry Andric }
68500b57cec5SDimitry Andric 
68510b57cec5SDimitry Andric /// Find the function body in the bitcode stream
68520b57cec5SDimitry Andric Error BitcodeReader::findFunctionInStream(
68530b57cec5SDimitry Andric     Function *F,
68540b57cec5SDimitry Andric     DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
68550b57cec5SDimitry Andric   while (DeferredFunctionInfoIterator->second == 0) {
68560b57cec5SDimitry Andric     // This is the fallback handling for the old format bitcode that
68570b57cec5SDimitry Andric     // didn't contain the function index in the VST, or when we have
68580b57cec5SDimitry Andric     // an anonymous function which would not have a VST entry.
68590b57cec5SDimitry Andric     // Assert that we have one of those two cases.
68600b57cec5SDimitry Andric     assert(VSTOffset == 0 || !F->hasName());
68610b57cec5SDimitry Andric     // Parse the next body in the stream and set its position in the
68620b57cec5SDimitry Andric     // DeferredFunctionInfo map.
68630b57cec5SDimitry Andric     if (Error Err = rememberAndSkipFunctionBodies())
68640b57cec5SDimitry Andric       return Err;
68650b57cec5SDimitry Andric   }
68660b57cec5SDimitry Andric   return Error::success();
68670b57cec5SDimitry Andric }
68680b57cec5SDimitry Andric 
68690b57cec5SDimitry Andric SyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) {
68700b57cec5SDimitry Andric   if (Val == SyncScope::SingleThread || Val == SyncScope::System)
68710b57cec5SDimitry Andric     return SyncScope::ID(Val);
68720b57cec5SDimitry Andric   if (Val >= SSIDs.size())
68730b57cec5SDimitry Andric     return SyncScope::System; // Map unknown synchronization scopes to system.
68740b57cec5SDimitry Andric   return SSIDs[Val];
68750b57cec5SDimitry Andric }
68760b57cec5SDimitry Andric 
68770b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
68780b57cec5SDimitry Andric // GVMaterializer implementation
68790b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
68800b57cec5SDimitry Andric 
68810b57cec5SDimitry Andric Error BitcodeReader::materialize(GlobalValue *GV) {
68820b57cec5SDimitry Andric   Function *F = dyn_cast<Function>(GV);
68830b57cec5SDimitry Andric   // If it's not a function or is already material, ignore the request.
68840b57cec5SDimitry Andric   if (!F || !F->isMaterializable())
68850b57cec5SDimitry Andric     return Error::success();
68860b57cec5SDimitry Andric 
68870b57cec5SDimitry Andric   DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
68880b57cec5SDimitry Andric   assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
68890b57cec5SDimitry Andric   // If its position is recorded as 0, its body is somewhere in the stream
68900b57cec5SDimitry Andric   // but we haven't seen it yet.
68910b57cec5SDimitry Andric   if (DFII->second == 0)
68920b57cec5SDimitry Andric     if (Error Err = findFunctionInStream(F, DFII))
68930b57cec5SDimitry Andric       return Err;
68940b57cec5SDimitry Andric 
68950b57cec5SDimitry Andric   // Materialize metadata before parsing any function bodies.
68960b57cec5SDimitry Andric   if (Error Err = materializeMetadata())
68970b57cec5SDimitry Andric     return Err;
68980b57cec5SDimitry Andric 
68990b57cec5SDimitry Andric   // Move the bit stream to the saved position of the deferred function body.
69000b57cec5SDimitry Andric   if (Error JumpFailed = Stream.JumpToBit(DFII->second))
69010b57cec5SDimitry Andric     return JumpFailed;
6902*0fca6ea1SDimitry Andric 
6903*0fca6ea1SDimitry Andric   // Regardless of the debug info format we want to end up in, we need
6904*0fca6ea1SDimitry Andric   // IsNewDbgInfoFormat=true to construct any debug records seen in the bitcode.
6905*0fca6ea1SDimitry Andric   F->IsNewDbgInfoFormat = true;
6906*0fca6ea1SDimitry Andric 
69070b57cec5SDimitry Andric   if (Error Err = parseFunctionBody(F))
69080b57cec5SDimitry Andric     return Err;
69090b57cec5SDimitry Andric   F->setIsMaterializable(false);
69100b57cec5SDimitry Andric 
6911*0fca6ea1SDimitry Andric   // All parsed Functions should load into the debug info format dictated by the
6912*0fca6ea1SDimitry Andric   // Module, unless we're attempting to preserve the input debug info format.
6913*0fca6ea1SDimitry Andric   if (SeenDebugIntrinsic && SeenDebugRecord)
6914*0fca6ea1SDimitry Andric     return error("Mixed debug intrinsics and debug records in bitcode module!");
6915*0fca6ea1SDimitry Andric   if (PreserveInputDbgFormat == cl::boolOrDefault::BOU_TRUE) {
6916*0fca6ea1SDimitry Andric     bool SeenAnyDebugInfo = SeenDebugIntrinsic || SeenDebugRecord;
6917*0fca6ea1SDimitry Andric     bool NewDbgInfoFormatDesired =
6918*0fca6ea1SDimitry Andric         SeenAnyDebugInfo ? SeenDebugRecord : F->getParent()->IsNewDbgInfoFormat;
6919*0fca6ea1SDimitry Andric     if (SeenAnyDebugInfo) {
6920*0fca6ea1SDimitry Andric       UseNewDbgInfoFormat = SeenDebugRecord;
6921*0fca6ea1SDimitry Andric       WriteNewDbgInfoFormatToBitcode = SeenDebugRecord;
6922*0fca6ea1SDimitry Andric       WriteNewDbgInfoFormat = SeenDebugRecord;
6923*0fca6ea1SDimitry Andric     }
6924*0fca6ea1SDimitry Andric     // If the module's debug info format doesn't match the observed input
6925*0fca6ea1SDimitry Andric     // format, then set its format now; we don't need to call the conversion
6926*0fca6ea1SDimitry Andric     // function because there must be no existing intrinsics to convert.
6927*0fca6ea1SDimitry Andric     // Otherwise, just set the format on this function now.
6928*0fca6ea1SDimitry Andric     if (NewDbgInfoFormatDesired != F->getParent()->IsNewDbgInfoFormat)
6929*0fca6ea1SDimitry Andric       F->getParent()->setNewDbgInfoFormatFlag(NewDbgInfoFormatDesired);
6930*0fca6ea1SDimitry Andric     else
6931*0fca6ea1SDimitry Andric       F->setNewDbgInfoFormatFlag(NewDbgInfoFormatDesired);
6932*0fca6ea1SDimitry Andric   } else {
6933*0fca6ea1SDimitry Andric     // If we aren't preserving formats, we use the Module flag to get our
6934*0fca6ea1SDimitry Andric     // desired format instead of reading flags, in case we are lazy-loading and
6935*0fca6ea1SDimitry Andric     // the format of the module has been changed since it was set by the flags.
6936*0fca6ea1SDimitry Andric     // We only need to convert debug info here if we have debug records but
6937*0fca6ea1SDimitry Andric     // desire the intrinsic format; everything else is a no-op or handled by the
6938*0fca6ea1SDimitry Andric     // autoupgrader.
6939*0fca6ea1SDimitry Andric     bool ModuleIsNewDbgInfoFormat = F->getParent()->IsNewDbgInfoFormat;
6940*0fca6ea1SDimitry Andric     if (ModuleIsNewDbgInfoFormat || !SeenDebugRecord)
6941*0fca6ea1SDimitry Andric       F->setNewDbgInfoFormatFlag(ModuleIsNewDbgInfoFormat);
6942*0fca6ea1SDimitry Andric     else
6943*0fca6ea1SDimitry Andric       F->setIsNewDbgInfoFormat(ModuleIsNewDbgInfoFormat);
6944*0fca6ea1SDimitry Andric   }
6945*0fca6ea1SDimitry Andric 
69460b57cec5SDimitry Andric   if (StripDebugInfo)
69470b57cec5SDimitry Andric     stripDebugInfo(*F);
69480b57cec5SDimitry Andric 
69490b57cec5SDimitry Andric   // Upgrade any old intrinsic calls in the function.
69500b57cec5SDimitry Andric   for (auto &I : UpgradedIntrinsics) {
6951349cc55cSDimitry Andric     for (User *U : llvm::make_early_inc_range(I.first->materialized_users()))
69520b57cec5SDimitry Andric       if (CallInst *CI = dyn_cast<CallInst>(U))
69530b57cec5SDimitry Andric         UpgradeIntrinsicCall(CI, I.second);
69540b57cec5SDimitry Andric   }
69550b57cec5SDimitry Andric 
69560b57cec5SDimitry Andric   // Finish fn->subprogram upgrade for materialized functions.
69570b57cec5SDimitry Andric   if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F))
69580b57cec5SDimitry Andric     F->setSubprogram(SP);
69590b57cec5SDimitry Andric 
69600b57cec5SDimitry Andric   // Check if the TBAA Metadata are valid, otherwise we will need to strip them.
69610b57cec5SDimitry Andric   if (!MDLoader->isStrippingTBAA()) {
69620b57cec5SDimitry Andric     for (auto &I : instructions(F)) {
69630b57cec5SDimitry Andric       MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa);
69640b57cec5SDimitry Andric       if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA))
69650b57cec5SDimitry Andric         continue;
69660b57cec5SDimitry Andric       MDLoader->setStripTBAA(true);
69670b57cec5SDimitry Andric       stripTBAA(F->getParent());
69680b57cec5SDimitry Andric     }
69690b57cec5SDimitry Andric   }
69700b57cec5SDimitry Andric 
6971e8d8bef9SDimitry Andric   for (auto &I : instructions(F)) {
6972fe6060f1SDimitry Andric     // "Upgrade" older incorrect branch weights by dropping them.
6973e8d8bef9SDimitry Andric     if (auto *MD = I.getMetadata(LLVMContext::MD_prof)) {
6974e8d8bef9SDimitry Andric       if (MD->getOperand(0) != nullptr && isa<MDString>(MD->getOperand(0))) {
6975e8d8bef9SDimitry Andric         MDString *MDS = cast<MDString>(MD->getOperand(0));
6976e8d8bef9SDimitry Andric         StringRef ProfName = MDS->getString();
6977e8d8bef9SDimitry Andric         // Check consistency of !prof branch_weights metadata.
6978*0fca6ea1SDimitry Andric         if (ProfName != "branch_weights")
6979e8d8bef9SDimitry Andric           continue;
6980e8d8bef9SDimitry Andric         unsigned ExpectedNumOperands = 0;
6981e8d8bef9SDimitry Andric         if (BranchInst *BI = dyn_cast<BranchInst>(&I))
6982e8d8bef9SDimitry Andric           ExpectedNumOperands = BI->getNumSuccessors();
6983e8d8bef9SDimitry Andric         else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I))
6984e8d8bef9SDimitry Andric           ExpectedNumOperands = SI->getNumSuccessors();
6985e8d8bef9SDimitry Andric         else if (isa<CallInst>(&I))
6986e8d8bef9SDimitry Andric           ExpectedNumOperands = 1;
6987e8d8bef9SDimitry Andric         else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I))
6988e8d8bef9SDimitry Andric           ExpectedNumOperands = IBI->getNumDestinations();
6989e8d8bef9SDimitry Andric         else if (isa<SelectInst>(&I))
6990e8d8bef9SDimitry Andric           ExpectedNumOperands = 2;
6991e8d8bef9SDimitry Andric         else
6992e8d8bef9SDimitry Andric           continue; // ignore and continue.
6993e8d8bef9SDimitry Andric 
6994*0fca6ea1SDimitry Andric         unsigned Offset = getBranchWeightOffset(MD);
6995*0fca6ea1SDimitry Andric 
6996e8d8bef9SDimitry Andric         // If branch weight doesn't match, just strip branch weight.
6997*0fca6ea1SDimitry Andric         if (MD->getNumOperands() != Offset + ExpectedNumOperands)
6998e8d8bef9SDimitry Andric           I.setMetadata(LLVMContext::MD_prof, nullptr);
6999e8d8bef9SDimitry Andric       }
7000e8d8bef9SDimitry Andric     }
7001fe6060f1SDimitry Andric 
7002fe6060f1SDimitry Andric     // Remove incompatible attributes on function calls.
7003fe6060f1SDimitry Andric     if (auto *CI = dyn_cast<CallBase>(&I)) {
7004349cc55cSDimitry Andric       CI->removeRetAttrs(AttributeFuncs::typeIncompatible(
7005fe6060f1SDimitry Andric           CI->getFunctionType()->getReturnType()));
7006fe6060f1SDimitry Andric 
7007fe6060f1SDimitry Andric       for (unsigned ArgNo = 0; ArgNo < CI->arg_size(); ++ArgNo)
7008fe6060f1SDimitry Andric         CI->removeParamAttrs(ArgNo, AttributeFuncs::typeIncompatible(
7009fe6060f1SDimitry Andric                                         CI->getArgOperand(ArgNo)->getType()));
7010fe6060f1SDimitry Andric     }
7011e8d8bef9SDimitry Andric   }
7012e8d8bef9SDimitry Andric 
70135ffd83dbSDimitry Andric   // Look for functions that rely on old function attribute behavior.
70145ffd83dbSDimitry Andric   UpgradeFunctionAttributes(*F);
70155ffd83dbSDimitry Andric 
70160b57cec5SDimitry Andric   // Bring in any functions that this function forward-referenced via
70170b57cec5SDimitry Andric   // blockaddresses.
70180b57cec5SDimitry Andric   return materializeForwardReferencedFunctions();
70190b57cec5SDimitry Andric }
70200b57cec5SDimitry Andric 
70210b57cec5SDimitry Andric Error BitcodeReader::materializeModule() {
70220b57cec5SDimitry Andric   if (Error Err = materializeMetadata())
70230b57cec5SDimitry Andric     return Err;
70240b57cec5SDimitry Andric 
70250b57cec5SDimitry Andric   // Promise to materialize all forward references.
70260b57cec5SDimitry Andric   WillMaterializeAllForwardRefs = true;
70270b57cec5SDimitry Andric 
70280b57cec5SDimitry Andric   // Iterate over the module, deserializing any functions that are still on
70290b57cec5SDimitry Andric   // disk.
70300b57cec5SDimitry Andric   for (Function &F : *TheModule) {
70310b57cec5SDimitry Andric     if (Error Err = materialize(&F))
70320b57cec5SDimitry Andric       return Err;
70330b57cec5SDimitry Andric   }
70340b57cec5SDimitry Andric   // At this point, if there are any function bodies, parse the rest of
70350b57cec5SDimitry Andric   // the bits in the module past the last function block we have recorded
70360b57cec5SDimitry Andric   // through either lazy scanning or the VST.
70370b57cec5SDimitry Andric   if (LastFunctionBlockBit || NextUnreadBit)
70380b57cec5SDimitry Andric     if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit
70390b57cec5SDimitry Andric                                     ? LastFunctionBlockBit
70400b57cec5SDimitry Andric                                     : NextUnreadBit))
70410b57cec5SDimitry Andric       return Err;
70420b57cec5SDimitry Andric 
70430b57cec5SDimitry Andric   // Check that all block address forward references got resolved (as we
70440b57cec5SDimitry Andric   // promised above).
70450b57cec5SDimitry Andric   if (!BasicBlockFwdRefs.empty())
70460b57cec5SDimitry Andric     return error("Never resolved function from blockaddress");
70470b57cec5SDimitry Andric 
70480b57cec5SDimitry Andric   // Upgrade any intrinsic calls that slipped through (should not happen!) and
70490b57cec5SDimitry Andric   // delete the old functions to clean up. We can't do this unless the entire
70500b57cec5SDimitry Andric   // module is materialized because there could always be another function body
70510b57cec5SDimitry Andric   // with calls to the old function.
70520b57cec5SDimitry Andric   for (auto &I : UpgradedIntrinsics) {
70530b57cec5SDimitry Andric     for (auto *U : I.first->users()) {
70540b57cec5SDimitry Andric       if (CallInst *CI = dyn_cast<CallInst>(U))
70550b57cec5SDimitry Andric         UpgradeIntrinsicCall(CI, I.second);
70560b57cec5SDimitry Andric     }
70570b57cec5SDimitry Andric     if (!I.first->use_empty())
70580b57cec5SDimitry Andric       I.first->replaceAllUsesWith(I.second);
70590b57cec5SDimitry Andric     I.first->eraseFromParent();
70600b57cec5SDimitry Andric   }
70610b57cec5SDimitry Andric   UpgradedIntrinsics.clear();
70620b57cec5SDimitry Andric 
70630b57cec5SDimitry Andric   UpgradeDebugInfo(*TheModule);
70640b57cec5SDimitry Andric 
70650b57cec5SDimitry Andric   UpgradeModuleFlags(*TheModule);
70660b57cec5SDimitry Andric 
70678bcb0991SDimitry Andric   UpgradeARCRuntime(*TheModule);
70680b57cec5SDimitry Andric 
70690b57cec5SDimitry Andric   return Error::success();
70700b57cec5SDimitry Andric }
70710b57cec5SDimitry Andric 
70720b57cec5SDimitry Andric std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
70730b57cec5SDimitry Andric   return IdentifiedStructTypes;
70740b57cec5SDimitry Andric }
70750b57cec5SDimitry Andric 
70760b57cec5SDimitry Andric ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
70770b57cec5SDimitry Andric     BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex,
70785f757f3fSDimitry Andric     StringRef ModulePath, std::function<bool(GlobalValue::GUID)> IsPrevailing)
70790b57cec5SDimitry Andric     : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex),
70805f757f3fSDimitry Andric       ModulePath(ModulePath), IsPrevailing(IsPrevailing) {}
70810b57cec5SDimitry Andric 
70820b57cec5SDimitry Andric void ModuleSummaryIndexBitcodeReader::addThisModule() {
70835f757f3fSDimitry Andric   TheIndex.addModule(ModulePath);
70840b57cec5SDimitry Andric }
70850b57cec5SDimitry Andric 
70860b57cec5SDimitry Andric ModuleSummaryIndex::ModuleInfo *
70870b57cec5SDimitry Andric ModuleSummaryIndexBitcodeReader::getThisModule() {
70880b57cec5SDimitry Andric   return TheIndex.getModule(ModulePath);
70890b57cec5SDimitry Andric }
70900b57cec5SDimitry Andric 
7091bdd1243dSDimitry Andric template <bool AllowNullValueInfo>
7092bdd1243dSDimitry Andric std::tuple<ValueInfo, GlobalValue::GUID, GlobalValue::GUID>
70930b57cec5SDimitry Andric ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) {
70940b57cec5SDimitry Andric   auto VGI = ValueIdToValueInfoMap[ValueId];
7095bdd1243dSDimitry Andric   // We can have a null value info for memprof callsite info records in
7096bdd1243dSDimitry Andric   // distributed ThinLTO index files when the callee function summary is not
7097bdd1243dSDimitry Andric   // included in the index. The bitcode writer records 0 in that case,
7098bdd1243dSDimitry Andric   // and the caller of this helper will set AllowNullValueInfo to true.
7099bdd1243dSDimitry Andric   assert(AllowNullValueInfo || std::get<0>(VGI));
71000b57cec5SDimitry Andric   return VGI;
71010b57cec5SDimitry Andric }
71020b57cec5SDimitry Andric 
71030b57cec5SDimitry Andric void ModuleSummaryIndexBitcodeReader::setValueGUID(
71040b57cec5SDimitry Andric     uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage,
71050b57cec5SDimitry Andric     StringRef SourceFileName) {
71060b57cec5SDimitry Andric   std::string GlobalId =
71070b57cec5SDimitry Andric       GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
71080b57cec5SDimitry Andric   auto ValueGUID = GlobalValue::getGUID(GlobalId);
71090b57cec5SDimitry Andric   auto OriginalNameID = ValueGUID;
71100b57cec5SDimitry Andric   if (GlobalValue::isLocalLinkage(Linkage))
71110b57cec5SDimitry Andric     OriginalNameID = GlobalValue::getGUID(ValueName);
71120b57cec5SDimitry Andric   if (PrintSummaryGUIDs)
71130b57cec5SDimitry Andric     dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
71140b57cec5SDimitry Andric            << ValueName << "\n";
71150b57cec5SDimitry Andric 
71160b57cec5SDimitry Andric   // UseStrtab is false for legacy summary formats and value names are
71170b57cec5SDimitry Andric   // created on stack. In that case we save the name in a string saver in
71180b57cec5SDimitry Andric   // the index so that the value name can be recorded.
7119bdd1243dSDimitry Andric   ValueIdToValueInfoMap[ValueID] = std::make_tuple(
71200b57cec5SDimitry Andric       TheIndex.getOrInsertValueInfo(
7121bdd1243dSDimitry Andric           ValueGUID, UseStrtab ? ValueName : TheIndex.saveString(ValueName)),
7122bdd1243dSDimitry Andric       OriginalNameID, ValueGUID);
71230b57cec5SDimitry Andric }
71240b57cec5SDimitry Andric 
71250b57cec5SDimitry Andric // Specialized value symbol table parser used when reading module index
71260b57cec5SDimitry Andric // blocks where we don't actually create global values. The parsed information
71270b57cec5SDimitry Andric // is saved in the bitcode reader for use when later parsing summaries.
71280b57cec5SDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
71290b57cec5SDimitry Andric     uint64_t Offset,
71300b57cec5SDimitry Andric     DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
71310b57cec5SDimitry Andric   // With a strtab the VST is not required to parse the summary.
71320b57cec5SDimitry Andric   if (UseStrtab)
71330b57cec5SDimitry Andric     return Error::success();
71340b57cec5SDimitry Andric 
71350b57cec5SDimitry Andric   assert(Offset > 0 && "Expected non-zero VST offset");
71360b57cec5SDimitry Andric   Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream);
71370b57cec5SDimitry Andric   if (!MaybeCurrentBit)
71380b57cec5SDimitry Andric     return MaybeCurrentBit.takeError();
71390b57cec5SDimitry Andric   uint64_t CurrentBit = MaybeCurrentBit.get();
71400b57cec5SDimitry Andric 
71410b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
71420b57cec5SDimitry Andric     return Err;
71430b57cec5SDimitry Andric 
71440b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
71450b57cec5SDimitry Andric 
71460b57cec5SDimitry Andric   // Read all the records for this value table.
71470b57cec5SDimitry Andric   SmallString<128> ValueName;
71480b57cec5SDimitry Andric 
71490b57cec5SDimitry Andric   while (true) {
71500b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
71510b57cec5SDimitry Andric     if (!MaybeEntry)
71520b57cec5SDimitry Andric       return MaybeEntry.takeError();
71530b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
71540b57cec5SDimitry Andric 
71550b57cec5SDimitry Andric     switch (Entry.Kind) {
71560b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
71570b57cec5SDimitry Andric     case BitstreamEntry::Error:
71580b57cec5SDimitry Andric       return error("Malformed block");
71590b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
71600b57cec5SDimitry Andric       // Done parsing VST, jump back to wherever we came from.
71610b57cec5SDimitry Andric       if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
71620b57cec5SDimitry Andric         return JumpFailed;
71630b57cec5SDimitry Andric       return Error::success();
71640b57cec5SDimitry Andric     case BitstreamEntry::Record:
71650b57cec5SDimitry Andric       // The interesting case.
71660b57cec5SDimitry Andric       break;
71670b57cec5SDimitry Andric     }
71680b57cec5SDimitry Andric 
71690b57cec5SDimitry Andric     // Read a record.
71700b57cec5SDimitry Andric     Record.clear();
71710b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
71720b57cec5SDimitry Andric     if (!MaybeRecord)
71730b57cec5SDimitry Andric       return MaybeRecord.takeError();
71740b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
71750b57cec5SDimitry Andric     default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
71760b57cec5SDimitry Andric       break;
71770b57cec5SDimitry Andric     case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
71780b57cec5SDimitry Andric       if (convertToString(Record, 1, ValueName))
71790b57cec5SDimitry Andric         return error("Invalid record");
71800b57cec5SDimitry Andric       unsigned ValueID = Record[0];
71810b57cec5SDimitry Andric       assert(!SourceFileName.empty());
71820b57cec5SDimitry Andric       auto VLI = ValueIdToLinkageMap.find(ValueID);
71830b57cec5SDimitry Andric       assert(VLI != ValueIdToLinkageMap.end() &&
71840b57cec5SDimitry Andric              "No linkage found for VST entry?");
71850b57cec5SDimitry Andric       auto Linkage = VLI->second;
71860b57cec5SDimitry Andric       setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
71870b57cec5SDimitry Andric       ValueName.clear();
71880b57cec5SDimitry Andric       break;
71890b57cec5SDimitry Andric     }
71900b57cec5SDimitry Andric     case bitc::VST_CODE_FNENTRY: {
71910b57cec5SDimitry Andric       // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
71920b57cec5SDimitry Andric       if (convertToString(Record, 2, ValueName))
71930b57cec5SDimitry Andric         return error("Invalid record");
71940b57cec5SDimitry Andric       unsigned ValueID = Record[0];
71950b57cec5SDimitry Andric       assert(!SourceFileName.empty());
71960b57cec5SDimitry Andric       auto VLI = ValueIdToLinkageMap.find(ValueID);
71970b57cec5SDimitry Andric       assert(VLI != ValueIdToLinkageMap.end() &&
71980b57cec5SDimitry Andric              "No linkage found for VST entry?");
71990b57cec5SDimitry Andric       auto Linkage = VLI->second;
72000b57cec5SDimitry Andric       setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
72010b57cec5SDimitry Andric       ValueName.clear();
72020b57cec5SDimitry Andric       break;
72030b57cec5SDimitry Andric     }
72040b57cec5SDimitry Andric     case bitc::VST_CODE_COMBINED_ENTRY: {
72050b57cec5SDimitry Andric       // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
72060b57cec5SDimitry Andric       unsigned ValueID = Record[0];
72070b57cec5SDimitry Andric       GlobalValue::GUID RefGUID = Record[1];
72080b57cec5SDimitry Andric       // The "original name", which is the second value of the pair will be
72090b57cec5SDimitry Andric       // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
7210bdd1243dSDimitry Andric       ValueIdToValueInfoMap[ValueID] = std::make_tuple(
7211bdd1243dSDimitry Andric           TheIndex.getOrInsertValueInfo(RefGUID), RefGUID, RefGUID);
72120b57cec5SDimitry Andric       break;
72130b57cec5SDimitry Andric     }
72140b57cec5SDimitry Andric     }
72150b57cec5SDimitry Andric   }
72160b57cec5SDimitry Andric }
72170b57cec5SDimitry Andric 
72180b57cec5SDimitry Andric // Parse just the blocks needed for building the index out of the module.
72190b57cec5SDimitry Andric // At the end of this routine the module Index is populated with a map
72200b57cec5SDimitry Andric // from global value id to GlobalValueSummary objects.
72210b57cec5SDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseModule() {
72220b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
72230b57cec5SDimitry Andric     return Err;
72240b57cec5SDimitry Andric 
72250b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
72260b57cec5SDimitry Andric   DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
72270b57cec5SDimitry Andric   unsigned ValueId = 0;
72280b57cec5SDimitry Andric 
72290b57cec5SDimitry Andric   // Read the index for this module.
72300b57cec5SDimitry Andric   while (true) {
72310b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
72320b57cec5SDimitry Andric     if (!MaybeEntry)
72330b57cec5SDimitry Andric       return MaybeEntry.takeError();
72340b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
72350b57cec5SDimitry Andric 
72360b57cec5SDimitry Andric     switch (Entry.Kind) {
72370b57cec5SDimitry Andric     case BitstreamEntry::Error:
72380b57cec5SDimitry Andric       return error("Malformed block");
72390b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
72400b57cec5SDimitry Andric       return Error::success();
72410b57cec5SDimitry Andric 
72420b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
72430b57cec5SDimitry Andric       switch (Entry.ID) {
72440b57cec5SDimitry Andric       default: // Skip unknown content.
72450b57cec5SDimitry Andric         if (Error Err = Stream.SkipBlock())
72460b57cec5SDimitry Andric           return Err;
72470b57cec5SDimitry Andric         break;
72480b57cec5SDimitry Andric       case bitc::BLOCKINFO_BLOCK_ID:
72490b57cec5SDimitry Andric         // Need to parse these to get abbrev ids (e.g. for VST)
725081ad6265SDimitry Andric         if (Error Err = readBlockInfo())
725181ad6265SDimitry Andric           return Err;
72520b57cec5SDimitry Andric         break;
72530b57cec5SDimitry Andric       case bitc::VALUE_SYMTAB_BLOCK_ID:
72540b57cec5SDimitry Andric         // Should have been parsed earlier via VSTOffset, unless there
72550b57cec5SDimitry Andric         // is no summary section.
72560b57cec5SDimitry Andric         assert(((SeenValueSymbolTable && VSTOffset > 0) ||
72570b57cec5SDimitry Andric                 !SeenGlobalValSummary) &&
72580b57cec5SDimitry Andric                "Expected early VST parse via VSTOffset record");
72590b57cec5SDimitry Andric         if (Error Err = Stream.SkipBlock())
72600b57cec5SDimitry Andric           return Err;
72610b57cec5SDimitry Andric         break;
72620b57cec5SDimitry Andric       case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
72630b57cec5SDimitry Andric       case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID:
72640b57cec5SDimitry Andric         // Add the module if it is a per-module index (has a source file name).
72650b57cec5SDimitry Andric         if (!SourceFileName.empty())
72660b57cec5SDimitry Andric           addThisModule();
72670b57cec5SDimitry Andric         assert(!SeenValueSymbolTable &&
72680b57cec5SDimitry Andric                "Already read VST when parsing summary block?");
72690b57cec5SDimitry Andric         // We might not have a VST if there were no values in the
72700b57cec5SDimitry Andric         // summary. An empty summary block generated when we are
72710b57cec5SDimitry Andric         // performing ThinLTO compiles so we don't later invoke
72720b57cec5SDimitry Andric         // the regular LTO process on them.
72730b57cec5SDimitry Andric         if (VSTOffset > 0) {
72740b57cec5SDimitry Andric           if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
72750b57cec5SDimitry Andric             return Err;
72760b57cec5SDimitry Andric           SeenValueSymbolTable = true;
72770b57cec5SDimitry Andric         }
72780b57cec5SDimitry Andric         SeenGlobalValSummary = true;
72790b57cec5SDimitry Andric         if (Error Err = parseEntireSummary(Entry.ID))
72800b57cec5SDimitry Andric           return Err;
72810b57cec5SDimitry Andric         break;
72820b57cec5SDimitry Andric       case bitc::MODULE_STRTAB_BLOCK_ID:
72830b57cec5SDimitry Andric         if (Error Err = parseModuleStringTable())
72840b57cec5SDimitry Andric           return Err;
72850b57cec5SDimitry Andric         break;
72860b57cec5SDimitry Andric       }
72870b57cec5SDimitry Andric       continue;
72880b57cec5SDimitry Andric 
72890b57cec5SDimitry Andric     case BitstreamEntry::Record: {
72900b57cec5SDimitry Andric         Record.clear();
72910b57cec5SDimitry Andric         Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
72920b57cec5SDimitry Andric         if (!MaybeBitCode)
72930b57cec5SDimitry Andric           return MaybeBitCode.takeError();
72940b57cec5SDimitry Andric         switch (MaybeBitCode.get()) {
72950b57cec5SDimitry Andric         default:
72960b57cec5SDimitry Andric           break; // Default behavior, ignore unknown content.
72970b57cec5SDimitry Andric         case bitc::MODULE_CODE_VERSION: {
72980b57cec5SDimitry Andric           if (Error Err = parseVersionRecord(Record).takeError())
72990b57cec5SDimitry Andric             return Err;
73000b57cec5SDimitry Andric           break;
73010b57cec5SDimitry Andric         }
73020b57cec5SDimitry Andric         /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
73030b57cec5SDimitry Andric         case bitc::MODULE_CODE_SOURCE_FILENAME: {
73040b57cec5SDimitry Andric           SmallString<128> ValueName;
73050b57cec5SDimitry Andric           if (convertToString(Record, 0, ValueName))
73060b57cec5SDimitry Andric             return error("Invalid record");
73070b57cec5SDimitry Andric           SourceFileName = ValueName.c_str();
73080b57cec5SDimitry Andric           break;
73090b57cec5SDimitry Andric         }
73100b57cec5SDimitry Andric         /// MODULE_CODE_HASH: [5*i32]
73110b57cec5SDimitry Andric         case bitc::MODULE_CODE_HASH: {
73120b57cec5SDimitry Andric           if (Record.size() != 5)
73130b57cec5SDimitry Andric             return error("Invalid hash length " + Twine(Record.size()).str());
73145f757f3fSDimitry Andric           auto &Hash = getThisModule()->second;
73150b57cec5SDimitry Andric           int Pos = 0;
73160b57cec5SDimitry Andric           for (auto &Val : Record) {
73170b57cec5SDimitry Andric             assert(!(Val >> 32) && "Unexpected high bits set");
73180b57cec5SDimitry Andric             Hash[Pos++] = Val;
73190b57cec5SDimitry Andric           }
73200b57cec5SDimitry Andric           break;
73210b57cec5SDimitry Andric         }
73220b57cec5SDimitry Andric         /// MODULE_CODE_VSTOFFSET: [offset]
73230b57cec5SDimitry Andric         case bitc::MODULE_CODE_VSTOFFSET:
7324e8d8bef9SDimitry Andric           if (Record.empty())
73250b57cec5SDimitry Andric             return error("Invalid record");
73260b57cec5SDimitry Andric           // Note that we subtract 1 here because the offset is relative to one
73270b57cec5SDimitry Andric           // word before the start of the identification or module block, which
73280b57cec5SDimitry Andric           // was historically always the start of the regular bitcode header.
73290b57cec5SDimitry Andric           VSTOffset = Record[0] - 1;
73300b57cec5SDimitry Andric           break;
73310b57cec5SDimitry Andric         // v1 GLOBALVAR: [pointer type, isconst,     initid,       linkage, ...]
73320b57cec5SDimitry Andric         // v1 FUNCTION:  [type,         callingconv, isproto,      linkage, ...]
73330b57cec5SDimitry Andric         // v1 ALIAS:     [alias type,   addrspace,   aliasee val#, linkage, ...]
73340b57cec5SDimitry Andric         // v2: [strtab offset, strtab size, v1]
73350b57cec5SDimitry Andric         case bitc::MODULE_CODE_GLOBALVAR:
73360b57cec5SDimitry Andric         case bitc::MODULE_CODE_FUNCTION:
73370b57cec5SDimitry Andric         case bitc::MODULE_CODE_ALIAS: {
73380b57cec5SDimitry Andric           StringRef Name;
73390b57cec5SDimitry Andric           ArrayRef<uint64_t> GVRecord;
73400b57cec5SDimitry Andric           std::tie(Name, GVRecord) = readNameFromStrtab(Record);
73410b57cec5SDimitry Andric           if (GVRecord.size() <= 3)
73420b57cec5SDimitry Andric             return error("Invalid record");
73430b57cec5SDimitry Andric           uint64_t RawLinkage = GVRecord[3];
73440b57cec5SDimitry Andric           GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
73450b57cec5SDimitry Andric           if (!UseStrtab) {
73460b57cec5SDimitry Andric             ValueIdToLinkageMap[ValueId++] = Linkage;
73470b57cec5SDimitry Andric             break;
73480b57cec5SDimitry Andric           }
73490b57cec5SDimitry Andric 
73500b57cec5SDimitry Andric           setValueGUID(ValueId++, Name, Linkage, SourceFileName);
73510b57cec5SDimitry Andric           break;
73520b57cec5SDimitry Andric         }
73530b57cec5SDimitry Andric         }
73540b57cec5SDimitry Andric       }
73550b57cec5SDimitry Andric       continue;
73560b57cec5SDimitry Andric     }
73570b57cec5SDimitry Andric   }
73580b57cec5SDimitry Andric }
73590b57cec5SDimitry Andric 
73600b57cec5SDimitry Andric std::vector<ValueInfo>
73610b57cec5SDimitry Andric ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
73620b57cec5SDimitry Andric   std::vector<ValueInfo> Ret;
73630b57cec5SDimitry Andric   Ret.reserve(Record.size());
73640b57cec5SDimitry Andric   for (uint64_t RefValueId : Record)
7365bdd1243dSDimitry Andric     Ret.push_back(std::get<0>(getValueInfoFromValueId(RefValueId)));
73660b57cec5SDimitry Andric   return Ret;
73670b57cec5SDimitry Andric }
73680b57cec5SDimitry Andric 
73690b57cec5SDimitry Andric std::vector<FunctionSummary::EdgeTy>
73700b57cec5SDimitry Andric ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record,
73710b57cec5SDimitry Andric                                               bool IsOldProfileFormat,
73720b57cec5SDimitry Andric                                               bool HasProfile, bool HasRelBF) {
73730b57cec5SDimitry Andric   std::vector<FunctionSummary::EdgeTy> Ret;
7374*0fca6ea1SDimitry Andric   // In the case of new profile formats, there are two Record entries per
7375*0fca6ea1SDimitry Andric   // Edge. Otherwise, conservatively reserve up to Record.size.
7376*0fca6ea1SDimitry Andric   if (!IsOldProfileFormat && (HasProfile || HasRelBF))
7377*0fca6ea1SDimitry Andric     Ret.reserve(Record.size() / 2);
7378*0fca6ea1SDimitry Andric   else
73790b57cec5SDimitry Andric     Ret.reserve(Record.size());
7380*0fca6ea1SDimitry Andric 
73810b57cec5SDimitry Andric   for (unsigned I = 0, E = Record.size(); I != E; ++I) {
73820b57cec5SDimitry Andric     CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
73835f757f3fSDimitry Andric     bool HasTailCall = false;
73840b57cec5SDimitry Andric     uint64_t RelBF = 0;
7385bdd1243dSDimitry Andric     ValueInfo Callee = std::get<0>(getValueInfoFromValueId(Record[I]));
73860b57cec5SDimitry Andric     if (IsOldProfileFormat) {
73870b57cec5SDimitry Andric       I += 1; // Skip old callsitecount field
73880b57cec5SDimitry Andric       if (HasProfile)
73890b57cec5SDimitry Andric         I += 1; // Skip old profilecount field
73900b57cec5SDimitry Andric     } else if (HasProfile)
73915f757f3fSDimitry Andric       std::tie(Hotness, HasTailCall) =
73925f757f3fSDimitry Andric           getDecodedHotnessCallEdgeInfo(Record[++I]);
73930b57cec5SDimitry Andric     else if (HasRelBF)
73945f757f3fSDimitry Andric       getDecodedRelBFCallEdgeInfo(Record[++I], RelBF, HasTailCall);
73955f757f3fSDimitry Andric     Ret.push_back(FunctionSummary::EdgeTy{
73965f757f3fSDimitry Andric         Callee, CalleeInfo(Hotness, HasTailCall, RelBF)});
73970b57cec5SDimitry Andric   }
73980b57cec5SDimitry Andric   return Ret;
73990b57cec5SDimitry Andric }
74000b57cec5SDimitry Andric 
74010b57cec5SDimitry Andric static void
74020b57cec5SDimitry Andric parseWholeProgramDevirtResolutionByArg(ArrayRef<uint64_t> Record, size_t &Slot,
74030b57cec5SDimitry Andric                                        WholeProgramDevirtResolution &Wpd) {
74040b57cec5SDimitry Andric   uint64_t ArgNum = Record[Slot++];
74050b57cec5SDimitry Andric   WholeProgramDevirtResolution::ByArg &B =
74060b57cec5SDimitry Andric       Wpd.ResByArg[{Record.begin() + Slot, Record.begin() + Slot + ArgNum}];
74070b57cec5SDimitry Andric   Slot += ArgNum;
74080b57cec5SDimitry Andric 
74090b57cec5SDimitry Andric   B.TheKind =
74100b57cec5SDimitry Andric       static_cast<WholeProgramDevirtResolution::ByArg::Kind>(Record[Slot++]);
74110b57cec5SDimitry Andric   B.Info = Record[Slot++];
74120b57cec5SDimitry Andric   B.Byte = Record[Slot++];
74130b57cec5SDimitry Andric   B.Bit = Record[Slot++];
74140b57cec5SDimitry Andric }
74150b57cec5SDimitry Andric 
74160b57cec5SDimitry Andric static void parseWholeProgramDevirtResolution(ArrayRef<uint64_t> Record,
74170b57cec5SDimitry Andric                                               StringRef Strtab, size_t &Slot,
74180b57cec5SDimitry Andric                                               TypeIdSummary &TypeId) {
74190b57cec5SDimitry Andric   uint64_t Id = Record[Slot++];
74200b57cec5SDimitry Andric   WholeProgramDevirtResolution &Wpd = TypeId.WPDRes[Id];
74210b57cec5SDimitry Andric 
74220b57cec5SDimitry Andric   Wpd.TheKind = static_cast<WholeProgramDevirtResolution::Kind>(Record[Slot++]);
74230b57cec5SDimitry Andric   Wpd.SingleImplName = {Strtab.data() + Record[Slot],
74240b57cec5SDimitry Andric                         static_cast<size_t>(Record[Slot + 1])};
74250b57cec5SDimitry Andric   Slot += 2;
74260b57cec5SDimitry Andric 
74270b57cec5SDimitry Andric   uint64_t ResByArgNum = Record[Slot++];
74280b57cec5SDimitry Andric   for (uint64_t I = 0; I != ResByArgNum; ++I)
74290b57cec5SDimitry Andric     parseWholeProgramDevirtResolutionByArg(Record, Slot, Wpd);
74300b57cec5SDimitry Andric }
74310b57cec5SDimitry Andric 
74320b57cec5SDimitry Andric static void parseTypeIdSummaryRecord(ArrayRef<uint64_t> Record,
74330b57cec5SDimitry Andric                                      StringRef Strtab,
74340b57cec5SDimitry Andric                                      ModuleSummaryIndex &TheIndex) {
74350b57cec5SDimitry Andric   size_t Slot = 0;
74360b57cec5SDimitry Andric   TypeIdSummary &TypeId = TheIndex.getOrInsertTypeIdSummary(
74370b57cec5SDimitry Andric       {Strtab.data() + Record[Slot], static_cast<size_t>(Record[Slot + 1])});
74380b57cec5SDimitry Andric   Slot += 2;
74390b57cec5SDimitry Andric 
74400b57cec5SDimitry Andric   TypeId.TTRes.TheKind = static_cast<TypeTestResolution::Kind>(Record[Slot++]);
74410b57cec5SDimitry Andric   TypeId.TTRes.SizeM1BitWidth = Record[Slot++];
74420b57cec5SDimitry Andric   TypeId.TTRes.AlignLog2 = Record[Slot++];
74430b57cec5SDimitry Andric   TypeId.TTRes.SizeM1 = Record[Slot++];
74440b57cec5SDimitry Andric   TypeId.TTRes.BitMask = Record[Slot++];
74450b57cec5SDimitry Andric   TypeId.TTRes.InlineBits = Record[Slot++];
74460b57cec5SDimitry Andric 
74470b57cec5SDimitry Andric   while (Slot < Record.size())
74480b57cec5SDimitry Andric     parseWholeProgramDevirtResolution(Record, Strtab, Slot, TypeId);
74490b57cec5SDimitry Andric }
74500b57cec5SDimitry Andric 
7451e8d8bef9SDimitry Andric std::vector<FunctionSummary::ParamAccess>
7452e8d8bef9SDimitry Andric ModuleSummaryIndexBitcodeReader::parseParamAccesses(ArrayRef<uint64_t> Record) {
74535ffd83dbSDimitry Andric   auto ReadRange = [&]() {
74545ffd83dbSDimitry Andric     APInt Lower(FunctionSummary::ParamAccess::RangeWidth,
74555ffd83dbSDimitry Andric                 BitcodeReader::decodeSignRotatedValue(Record.front()));
74565ffd83dbSDimitry Andric     Record = Record.drop_front();
74575ffd83dbSDimitry Andric     APInt Upper(FunctionSummary::ParamAccess::RangeWidth,
74585ffd83dbSDimitry Andric                 BitcodeReader::decodeSignRotatedValue(Record.front()));
74595ffd83dbSDimitry Andric     Record = Record.drop_front();
74605ffd83dbSDimitry Andric     ConstantRange Range{Lower, Upper};
74615ffd83dbSDimitry Andric     assert(!Range.isFullSet());
74625ffd83dbSDimitry Andric     assert(!Range.isUpperSignWrapped());
74635ffd83dbSDimitry Andric     return Range;
74645ffd83dbSDimitry Andric   };
74655ffd83dbSDimitry Andric 
74665ffd83dbSDimitry Andric   std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
74675ffd83dbSDimitry Andric   while (!Record.empty()) {
74685ffd83dbSDimitry Andric     PendingParamAccesses.emplace_back();
74695ffd83dbSDimitry Andric     FunctionSummary::ParamAccess &ParamAccess = PendingParamAccesses.back();
74705ffd83dbSDimitry Andric     ParamAccess.ParamNo = Record.front();
74715ffd83dbSDimitry Andric     Record = Record.drop_front();
74725ffd83dbSDimitry Andric     ParamAccess.Use = ReadRange();
74735ffd83dbSDimitry Andric     ParamAccess.Calls.resize(Record.front());
74745ffd83dbSDimitry Andric     Record = Record.drop_front();
74755ffd83dbSDimitry Andric     for (auto &Call : ParamAccess.Calls) {
74765ffd83dbSDimitry Andric       Call.ParamNo = Record.front();
74775ffd83dbSDimitry Andric       Record = Record.drop_front();
7478bdd1243dSDimitry Andric       Call.Callee = std::get<0>(getValueInfoFromValueId(Record.front()));
74795ffd83dbSDimitry Andric       Record = Record.drop_front();
74805ffd83dbSDimitry Andric       Call.Offsets = ReadRange();
74815ffd83dbSDimitry Andric     }
74825ffd83dbSDimitry Andric   }
74835ffd83dbSDimitry Andric   return PendingParamAccesses;
74845ffd83dbSDimitry Andric }
74855ffd83dbSDimitry Andric 
74860b57cec5SDimitry Andric void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo(
74870b57cec5SDimitry Andric     ArrayRef<uint64_t> Record, size_t &Slot,
74880b57cec5SDimitry Andric     TypeIdCompatibleVtableInfo &TypeId) {
74890b57cec5SDimitry Andric   uint64_t Offset = Record[Slot++];
7490bdd1243dSDimitry Andric   ValueInfo Callee = std::get<0>(getValueInfoFromValueId(Record[Slot++]));
74910b57cec5SDimitry Andric   TypeId.push_back({Offset, Callee});
74920b57cec5SDimitry Andric }
74930b57cec5SDimitry Andric 
74940b57cec5SDimitry Andric void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord(
74950b57cec5SDimitry Andric     ArrayRef<uint64_t> Record) {
74960b57cec5SDimitry Andric   size_t Slot = 0;
74970b57cec5SDimitry Andric   TypeIdCompatibleVtableInfo &TypeId =
74980b57cec5SDimitry Andric       TheIndex.getOrInsertTypeIdCompatibleVtableSummary(
74990b57cec5SDimitry Andric           {Strtab.data() + Record[Slot],
75000b57cec5SDimitry Andric            static_cast<size_t>(Record[Slot + 1])});
75010b57cec5SDimitry Andric   Slot += 2;
75020b57cec5SDimitry Andric 
75030b57cec5SDimitry Andric   while (Slot < Record.size())
75040b57cec5SDimitry Andric     parseTypeIdCompatibleVtableInfo(Record, Slot, TypeId);
75050b57cec5SDimitry Andric }
75060b57cec5SDimitry Andric 
75070b57cec5SDimitry Andric static void setSpecialRefs(std::vector<ValueInfo> &Refs, unsigned ROCnt,
75080b57cec5SDimitry Andric                            unsigned WOCnt) {
75090b57cec5SDimitry Andric   // Readonly and writeonly refs are in the end of the refs list.
75100b57cec5SDimitry Andric   assert(ROCnt + WOCnt <= Refs.size());
75110b57cec5SDimitry Andric   unsigned FirstWORef = Refs.size() - WOCnt;
75120b57cec5SDimitry Andric   unsigned RefNo = FirstWORef - ROCnt;
75130b57cec5SDimitry Andric   for (; RefNo < FirstWORef; ++RefNo)
75140b57cec5SDimitry Andric     Refs[RefNo].setReadOnly();
75150b57cec5SDimitry Andric   for (; RefNo < Refs.size(); ++RefNo)
75160b57cec5SDimitry Andric     Refs[RefNo].setWriteOnly();
75170b57cec5SDimitry Andric }
75180b57cec5SDimitry Andric 
75190b57cec5SDimitry Andric // Eagerly parse the entire summary block. This populates the GlobalValueSummary
75200b57cec5SDimitry Andric // objects in the index.
75210b57cec5SDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) {
75220b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(ID))
75230b57cec5SDimitry Andric     return Err;
75240b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
75250b57cec5SDimitry Andric 
75260b57cec5SDimitry Andric   // Parse version
75270b57cec5SDimitry Andric   {
75280b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
75290b57cec5SDimitry Andric     if (!MaybeEntry)
75300b57cec5SDimitry Andric       return MaybeEntry.takeError();
75310b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
75320b57cec5SDimitry Andric 
75330b57cec5SDimitry Andric     if (Entry.Kind != BitstreamEntry::Record)
75340b57cec5SDimitry Andric       return error("Invalid Summary Block: record for version expected");
75350b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
75360b57cec5SDimitry Andric     if (!MaybeRecord)
75370b57cec5SDimitry Andric       return MaybeRecord.takeError();
75380b57cec5SDimitry Andric     if (MaybeRecord.get() != bitc::FS_VERSION)
75390b57cec5SDimitry Andric       return error("Invalid Summary Block: version expected");
75400b57cec5SDimitry Andric   }
75410b57cec5SDimitry Andric   const uint64_t Version = Record[0];
75420b57cec5SDimitry Andric   const bool IsOldProfileFormat = Version == 1;
7543480093f4SDimitry Andric   if (Version < 1 || Version > ModuleSummaryIndex::BitcodeSummaryVersion)
75440b57cec5SDimitry Andric     return error("Invalid summary version " + Twine(Version) +
7545480093f4SDimitry Andric                  ". Version should be in the range [1-" +
7546480093f4SDimitry Andric                  Twine(ModuleSummaryIndex::BitcodeSummaryVersion) +
7547480093f4SDimitry Andric                  "].");
75480b57cec5SDimitry Andric   Record.clear();
75490b57cec5SDimitry Andric 
75500b57cec5SDimitry Andric   // Keep around the last seen summary to be used when we see an optional
75510b57cec5SDimitry Andric   // "OriginalName" attachement.
75520b57cec5SDimitry Andric   GlobalValueSummary *LastSeenSummary = nullptr;
75530b57cec5SDimitry Andric   GlobalValue::GUID LastSeenGUID = 0;
75540b57cec5SDimitry Andric 
75550b57cec5SDimitry Andric   // We can expect to see any number of type ID information records before
75560b57cec5SDimitry Andric   // each function summary records; these variables store the information
75570b57cec5SDimitry Andric   // collected so far so that it can be used to create the summary object.
75580b57cec5SDimitry Andric   std::vector<GlobalValue::GUID> PendingTypeTests;
75590b57cec5SDimitry Andric   std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
75600b57cec5SDimitry Andric       PendingTypeCheckedLoadVCalls;
75610b57cec5SDimitry Andric   std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
75620b57cec5SDimitry Andric       PendingTypeCheckedLoadConstVCalls;
75635ffd83dbSDimitry Andric   std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
75640b57cec5SDimitry Andric 
7565bdd1243dSDimitry Andric   std::vector<CallsiteInfo> PendingCallsites;
7566bdd1243dSDimitry Andric   std::vector<AllocInfo> PendingAllocs;
7567bdd1243dSDimitry Andric 
75680b57cec5SDimitry Andric   while (true) {
75690b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
75700b57cec5SDimitry Andric     if (!MaybeEntry)
75710b57cec5SDimitry Andric       return MaybeEntry.takeError();
75720b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
75730b57cec5SDimitry Andric 
75740b57cec5SDimitry Andric     switch (Entry.Kind) {
75750b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
75760b57cec5SDimitry Andric     case BitstreamEntry::Error:
75770b57cec5SDimitry Andric       return error("Malformed block");
75780b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
75790b57cec5SDimitry Andric       return Error::success();
75800b57cec5SDimitry Andric     case BitstreamEntry::Record:
75810b57cec5SDimitry Andric       // The interesting case.
75820b57cec5SDimitry Andric       break;
75830b57cec5SDimitry Andric     }
75840b57cec5SDimitry Andric 
75850b57cec5SDimitry Andric     // Read a record. The record format depends on whether this
75860b57cec5SDimitry Andric     // is a per-module index or a combined index file. In the per-module
75870b57cec5SDimitry Andric     // case the records contain the associated value's ID for correlation
75880b57cec5SDimitry Andric     // with VST entries. In the combined index the correlation is done
75890b57cec5SDimitry Andric     // via the bitcode offset of the summary records (which were saved
75900b57cec5SDimitry Andric     // in the combined index VST entries). The records also contain
75910b57cec5SDimitry Andric     // information used for ThinLTO renaming and importing.
75920b57cec5SDimitry Andric     Record.clear();
75930b57cec5SDimitry Andric     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
75940b57cec5SDimitry Andric     if (!MaybeBitCode)
75950b57cec5SDimitry Andric       return MaybeBitCode.takeError();
75960b57cec5SDimitry Andric     switch (unsigned BitCode = MaybeBitCode.get()) {
75970b57cec5SDimitry Andric     default: // Default behavior: ignore.
75980b57cec5SDimitry Andric       break;
75990b57cec5SDimitry Andric     case bitc::FS_FLAGS: {  // [flags]
76005ffd83dbSDimitry Andric       TheIndex.setFlags(Record[0]);
76010b57cec5SDimitry Andric       break;
76020b57cec5SDimitry Andric     }
76030b57cec5SDimitry Andric     case bitc::FS_VALUE_GUID: { // [valueid, refguid]
76040b57cec5SDimitry Andric       uint64_t ValueID = Record[0];
76050b57cec5SDimitry Andric       GlobalValue::GUID RefGUID = Record[1];
7606bdd1243dSDimitry Andric       ValueIdToValueInfoMap[ValueID] = std::make_tuple(
7607bdd1243dSDimitry Andric           TheIndex.getOrInsertValueInfo(RefGUID), RefGUID, RefGUID);
76080b57cec5SDimitry Andric       break;
76090b57cec5SDimitry Andric     }
76105f757f3fSDimitry Andric     // FS_PERMODULE is legacy and does not have support for the tail call flag.
76110b57cec5SDimitry Andric     // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs,
76120b57cec5SDimitry Andric     //                numrefs x valueid, n x (valueid)]
76130b57cec5SDimitry Andric     // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs,
76140b57cec5SDimitry Andric     //                        numrefs x valueid,
76155f757f3fSDimitry Andric     //                        n x (valueid, hotness+tailcall flags)]
76160b57cec5SDimitry Andric     // FS_PERMODULE_RELBF: [valueid, flags, instcount, fflags, numrefs,
76170b57cec5SDimitry Andric     //                      numrefs x valueid,
76185f757f3fSDimitry Andric     //                      n x (valueid, relblockfreq+tailcall)]
76190b57cec5SDimitry Andric     case bitc::FS_PERMODULE:
76200b57cec5SDimitry Andric     case bitc::FS_PERMODULE_RELBF:
76210b57cec5SDimitry Andric     case bitc::FS_PERMODULE_PROFILE: {
76220b57cec5SDimitry Andric       unsigned ValueID = Record[0];
76230b57cec5SDimitry Andric       uint64_t RawFlags = Record[1];
76240b57cec5SDimitry Andric       unsigned InstCount = Record[2];
76250b57cec5SDimitry Andric       uint64_t RawFunFlags = 0;
76260b57cec5SDimitry Andric       unsigned NumRefs = Record[3];
76270b57cec5SDimitry Andric       unsigned NumRORefs = 0, NumWORefs = 0;
76280b57cec5SDimitry Andric       int RefListStartIndex = 4;
76290b57cec5SDimitry Andric       if (Version >= 4) {
76300b57cec5SDimitry Andric         RawFunFlags = Record[3];
76310b57cec5SDimitry Andric         NumRefs = Record[4];
76320b57cec5SDimitry Andric         RefListStartIndex = 5;
76330b57cec5SDimitry Andric         if (Version >= 5) {
76340b57cec5SDimitry Andric           NumRORefs = Record[5];
76350b57cec5SDimitry Andric           RefListStartIndex = 6;
76360b57cec5SDimitry Andric           if (Version >= 7) {
76370b57cec5SDimitry Andric             NumWORefs = Record[6];
76380b57cec5SDimitry Andric             RefListStartIndex = 7;
76390b57cec5SDimitry Andric           }
76400b57cec5SDimitry Andric         }
76410b57cec5SDimitry Andric       }
76420b57cec5SDimitry Andric 
76430b57cec5SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
76440b57cec5SDimitry Andric       // The module path string ref set in the summary must be owned by the
76450b57cec5SDimitry Andric       // index's module string table. Since we don't have a module path
76460b57cec5SDimitry Andric       // string table section in the per-module index, we create a single
76470b57cec5SDimitry Andric       // module path string table entry with an empty (0) ID to take
76480b57cec5SDimitry Andric       // ownership.
76490b57cec5SDimitry Andric       int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
76500b57cec5SDimitry Andric       assert(Record.size() >= RefListStartIndex + NumRefs &&
76510b57cec5SDimitry Andric              "Record size inconsistent with number of references");
76520b57cec5SDimitry Andric       std::vector<ValueInfo> Refs = makeRefList(
76530b57cec5SDimitry Andric           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
76540b57cec5SDimitry Andric       bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
76550b57cec5SDimitry Andric       bool HasRelBF = (BitCode == bitc::FS_PERMODULE_RELBF);
76560b57cec5SDimitry Andric       std::vector<FunctionSummary::EdgeTy> Calls = makeCallList(
76570b57cec5SDimitry Andric           ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
76580b57cec5SDimitry Andric           IsOldProfileFormat, HasProfile, HasRelBF);
76590b57cec5SDimitry Andric       setSpecialRefs(Refs, NumRORefs, NumWORefs);
7660bdd1243dSDimitry Andric       auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID);
7661bdd1243dSDimitry Andric       // In order to save memory, only record the memprof summaries if this is
7662bdd1243dSDimitry Andric       // the prevailing copy of a symbol. The linker doesn't resolve local
7663bdd1243dSDimitry Andric       // linkage values so don't check whether those are prevailing.
7664bdd1243dSDimitry Andric       auto LT = (GlobalValue::LinkageTypes)Flags.Linkage;
7665bdd1243dSDimitry Andric       if (IsPrevailing &&
7666bdd1243dSDimitry Andric           !GlobalValue::isLocalLinkage(LT) &&
7667bdd1243dSDimitry Andric           !IsPrevailing(std::get<2>(VIAndOriginalGUID))) {
7668bdd1243dSDimitry Andric         PendingCallsites.clear();
7669bdd1243dSDimitry Andric         PendingAllocs.clear();
7670bdd1243dSDimitry Andric       }
76718bcb0991SDimitry Andric       auto FS = std::make_unique<FunctionSummary>(
76720b57cec5SDimitry Andric           Flags, InstCount, getDecodedFFlags(RawFunFlags), /*EntryCount=*/0,
76730b57cec5SDimitry Andric           std::move(Refs), std::move(Calls), std::move(PendingTypeTests),
76740b57cec5SDimitry Andric           std::move(PendingTypeTestAssumeVCalls),
76750b57cec5SDimitry Andric           std::move(PendingTypeCheckedLoadVCalls),
76760b57cec5SDimitry Andric           std::move(PendingTypeTestAssumeConstVCalls),
76775ffd83dbSDimitry Andric           std::move(PendingTypeCheckedLoadConstVCalls),
7678bdd1243dSDimitry Andric           std::move(PendingParamAccesses), std::move(PendingCallsites),
7679bdd1243dSDimitry Andric           std::move(PendingAllocs));
76800b57cec5SDimitry Andric       FS->setModulePath(getThisModule()->first());
7681bdd1243dSDimitry Andric       FS->setOriginalName(std::get<1>(VIAndOriginalGUID));
7682bdd1243dSDimitry Andric       TheIndex.addGlobalValueSummary(std::get<0>(VIAndOriginalGUID),
7683bdd1243dSDimitry Andric                                      std::move(FS));
76840b57cec5SDimitry Andric       break;
76850b57cec5SDimitry Andric     }
76860b57cec5SDimitry Andric     // FS_ALIAS: [valueid, flags, valueid]
76870b57cec5SDimitry Andric     // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
76880b57cec5SDimitry Andric     // they expect all aliasee summaries to be available.
76890b57cec5SDimitry Andric     case bitc::FS_ALIAS: {
76900b57cec5SDimitry Andric       unsigned ValueID = Record[0];
76910b57cec5SDimitry Andric       uint64_t RawFlags = Record[1];
76920b57cec5SDimitry Andric       unsigned AliaseeID = Record[2];
76930b57cec5SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
76948bcb0991SDimitry Andric       auto AS = std::make_unique<AliasSummary>(Flags);
76950b57cec5SDimitry Andric       // The module path string ref set in the summary must be owned by the
76960b57cec5SDimitry Andric       // index's module string table. Since we don't have a module path
76970b57cec5SDimitry Andric       // string table section in the per-module index, we create a single
76980b57cec5SDimitry Andric       // module path string table entry with an empty (0) ID to take
76990b57cec5SDimitry Andric       // ownership.
77000b57cec5SDimitry Andric       AS->setModulePath(getThisModule()->first());
77010b57cec5SDimitry Andric 
7702bdd1243dSDimitry Andric       auto AliaseeVI = std::get<0>(getValueInfoFromValueId(AliaseeID));
77030b57cec5SDimitry Andric       auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, ModulePath);
77040b57cec5SDimitry Andric       if (!AliaseeInModule)
77050b57cec5SDimitry Andric         return error("Alias expects aliasee summary to be parsed");
77060b57cec5SDimitry Andric       AS->setAliasee(AliaseeVI, AliaseeInModule);
77070b57cec5SDimitry Andric 
77080b57cec5SDimitry Andric       auto GUID = getValueInfoFromValueId(ValueID);
7709bdd1243dSDimitry Andric       AS->setOriginalName(std::get<1>(GUID));
7710bdd1243dSDimitry Andric       TheIndex.addGlobalValueSummary(std::get<0>(GUID), std::move(AS));
77110b57cec5SDimitry Andric       break;
77120b57cec5SDimitry Andric     }
77130b57cec5SDimitry Andric     // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, n x valueid]
77140b57cec5SDimitry Andric     case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
77150b57cec5SDimitry Andric       unsigned ValueID = Record[0];
77160b57cec5SDimitry Andric       uint64_t RawFlags = Record[1];
77170b57cec5SDimitry Andric       unsigned RefArrayStart = 2;
77180b57cec5SDimitry Andric       GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false,
77195ffd83dbSDimitry Andric                                       /* WriteOnly */ false,
77205ffd83dbSDimitry Andric                                       /* Constant */ false,
77215ffd83dbSDimitry Andric                                       GlobalObject::VCallVisibilityPublic);
77220b57cec5SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
77230b57cec5SDimitry Andric       if (Version >= 5) {
77240b57cec5SDimitry Andric         GVF = getDecodedGVarFlags(Record[2]);
77250b57cec5SDimitry Andric         RefArrayStart = 3;
77260b57cec5SDimitry Andric       }
77270b57cec5SDimitry Andric       std::vector<ValueInfo> Refs =
77280b57cec5SDimitry Andric           makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
77290b57cec5SDimitry Andric       auto FS =
77308bcb0991SDimitry Andric           std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
77310b57cec5SDimitry Andric       FS->setModulePath(getThisModule()->first());
77320b57cec5SDimitry Andric       auto GUID = getValueInfoFromValueId(ValueID);
7733bdd1243dSDimitry Andric       FS->setOriginalName(std::get<1>(GUID));
7734bdd1243dSDimitry Andric       TheIndex.addGlobalValueSummary(std::get<0>(GUID), std::move(FS));
77350b57cec5SDimitry Andric       break;
77360b57cec5SDimitry Andric     }
77370b57cec5SDimitry Andric     // FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags,
77380b57cec5SDimitry Andric     //                        numrefs, numrefs x valueid,
77390b57cec5SDimitry Andric     //                        n x (valueid, offset)]
77400b57cec5SDimitry Andric     case bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: {
77410b57cec5SDimitry Andric       unsigned ValueID = Record[0];
77420b57cec5SDimitry Andric       uint64_t RawFlags = Record[1];
77430b57cec5SDimitry Andric       GlobalVarSummary::GVarFlags GVF = getDecodedGVarFlags(Record[2]);
77440b57cec5SDimitry Andric       unsigned NumRefs = Record[3];
77450b57cec5SDimitry Andric       unsigned RefListStartIndex = 4;
77460b57cec5SDimitry Andric       unsigned VTableListStartIndex = RefListStartIndex + NumRefs;
77470b57cec5SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
77480b57cec5SDimitry Andric       std::vector<ValueInfo> Refs = makeRefList(
77490b57cec5SDimitry Andric           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
77500b57cec5SDimitry Andric       VTableFuncList VTableFuncs;
77510b57cec5SDimitry Andric       for (unsigned I = VTableListStartIndex, E = Record.size(); I != E; ++I) {
7752bdd1243dSDimitry Andric         ValueInfo Callee = std::get<0>(getValueInfoFromValueId(Record[I]));
77530b57cec5SDimitry Andric         uint64_t Offset = Record[++I];
77540b57cec5SDimitry Andric         VTableFuncs.push_back({Callee, Offset});
77550b57cec5SDimitry Andric       }
77560b57cec5SDimitry Andric       auto VS =
77578bcb0991SDimitry Andric           std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
77580b57cec5SDimitry Andric       VS->setModulePath(getThisModule()->first());
77590b57cec5SDimitry Andric       VS->setVTableFuncs(VTableFuncs);
77600b57cec5SDimitry Andric       auto GUID = getValueInfoFromValueId(ValueID);
7761bdd1243dSDimitry Andric       VS->setOriginalName(std::get<1>(GUID));
7762bdd1243dSDimitry Andric       TheIndex.addGlobalValueSummary(std::get<0>(GUID), std::move(VS));
77630b57cec5SDimitry Andric       break;
77640b57cec5SDimitry Andric     }
77655f757f3fSDimitry Andric     // FS_COMBINED is legacy and does not have support for the tail call flag.
77660b57cec5SDimitry Andric     // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs,
77670b57cec5SDimitry Andric     //               numrefs x valueid, n x (valueid)]
77680b57cec5SDimitry Andric     // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs,
77695f757f3fSDimitry Andric     //                       numrefs x valueid,
77705f757f3fSDimitry Andric     //                       n x (valueid, hotness+tailcall flags)]
77710b57cec5SDimitry Andric     case bitc::FS_COMBINED:
77720b57cec5SDimitry Andric     case bitc::FS_COMBINED_PROFILE: {
77730b57cec5SDimitry Andric       unsigned ValueID = Record[0];
77740b57cec5SDimitry Andric       uint64_t ModuleId = Record[1];
77750b57cec5SDimitry Andric       uint64_t RawFlags = Record[2];
77760b57cec5SDimitry Andric       unsigned InstCount = Record[3];
77770b57cec5SDimitry Andric       uint64_t RawFunFlags = 0;
77780b57cec5SDimitry Andric       uint64_t EntryCount = 0;
77790b57cec5SDimitry Andric       unsigned NumRefs = Record[4];
77800b57cec5SDimitry Andric       unsigned NumRORefs = 0, NumWORefs = 0;
77810b57cec5SDimitry Andric       int RefListStartIndex = 5;
77820b57cec5SDimitry Andric 
77830b57cec5SDimitry Andric       if (Version >= 4) {
77840b57cec5SDimitry Andric         RawFunFlags = Record[4];
77850b57cec5SDimitry Andric         RefListStartIndex = 6;
77860b57cec5SDimitry Andric         size_t NumRefsIndex = 5;
77870b57cec5SDimitry Andric         if (Version >= 5) {
77880b57cec5SDimitry Andric           unsigned NumRORefsOffset = 1;
77890b57cec5SDimitry Andric           RefListStartIndex = 7;
77900b57cec5SDimitry Andric           if (Version >= 6) {
77910b57cec5SDimitry Andric             NumRefsIndex = 6;
77920b57cec5SDimitry Andric             EntryCount = Record[5];
77930b57cec5SDimitry Andric             RefListStartIndex = 8;
77940b57cec5SDimitry Andric             if (Version >= 7) {
77950b57cec5SDimitry Andric               RefListStartIndex = 9;
77960b57cec5SDimitry Andric               NumWORefs = Record[8];
77970b57cec5SDimitry Andric               NumRORefsOffset = 2;
77980b57cec5SDimitry Andric             }
77990b57cec5SDimitry Andric           }
78000b57cec5SDimitry Andric           NumRORefs = Record[RefListStartIndex - NumRORefsOffset];
78010b57cec5SDimitry Andric         }
78020b57cec5SDimitry Andric         NumRefs = Record[NumRefsIndex];
78030b57cec5SDimitry Andric       }
78040b57cec5SDimitry Andric 
78050b57cec5SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
78060b57cec5SDimitry Andric       int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
78070b57cec5SDimitry Andric       assert(Record.size() >= RefListStartIndex + NumRefs &&
78080b57cec5SDimitry Andric              "Record size inconsistent with number of references");
78090b57cec5SDimitry Andric       std::vector<ValueInfo> Refs = makeRefList(
78100b57cec5SDimitry Andric           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
78110b57cec5SDimitry Andric       bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
78120b57cec5SDimitry Andric       std::vector<FunctionSummary::EdgeTy> Edges = makeCallList(
78130b57cec5SDimitry Andric           ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
78140b57cec5SDimitry Andric           IsOldProfileFormat, HasProfile, false);
7815bdd1243dSDimitry Andric       ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
78160b57cec5SDimitry Andric       setSpecialRefs(Refs, NumRORefs, NumWORefs);
78178bcb0991SDimitry Andric       auto FS = std::make_unique<FunctionSummary>(
78180b57cec5SDimitry Andric           Flags, InstCount, getDecodedFFlags(RawFunFlags), EntryCount,
78190b57cec5SDimitry Andric           std::move(Refs), std::move(Edges), std::move(PendingTypeTests),
78200b57cec5SDimitry Andric           std::move(PendingTypeTestAssumeVCalls),
78210b57cec5SDimitry Andric           std::move(PendingTypeCheckedLoadVCalls),
78220b57cec5SDimitry Andric           std::move(PendingTypeTestAssumeConstVCalls),
78235ffd83dbSDimitry Andric           std::move(PendingTypeCheckedLoadConstVCalls),
7824bdd1243dSDimitry Andric           std::move(PendingParamAccesses), std::move(PendingCallsites),
7825bdd1243dSDimitry Andric           std::move(PendingAllocs));
78260b57cec5SDimitry Andric       LastSeenSummary = FS.get();
78270b57cec5SDimitry Andric       LastSeenGUID = VI.getGUID();
78280b57cec5SDimitry Andric       FS->setModulePath(ModuleIdMap[ModuleId]);
78290b57cec5SDimitry Andric       TheIndex.addGlobalValueSummary(VI, std::move(FS));
78300b57cec5SDimitry Andric       break;
78310b57cec5SDimitry Andric     }
78320b57cec5SDimitry Andric     // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
78330b57cec5SDimitry Andric     // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
78340b57cec5SDimitry Andric     // they expect all aliasee summaries to be available.
78350b57cec5SDimitry Andric     case bitc::FS_COMBINED_ALIAS: {
78360b57cec5SDimitry Andric       unsigned ValueID = Record[0];
78370b57cec5SDimitry Andric       uint64_t ModuleId = Record[1];
78380b57cec5SDimitry Andric       uint64_t RawFlags = Record[2];
78390b57cec5SDimitry Andric       unsigned AliaseeValueId = Record[3];
78400b57cec5SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
78418bcb0991SDimitry Andric       auto AS = std::make_unique<AliasSummary>(Flags);
78420b57cec5SDimitry Andric       LastSeenSummary = AS.get();
78430b57cec5SDimitry Andric       AS->setModulePath(ModuleIdMap[ModuleId]);
78440b57cec5SDimitry Andric 
7845bdd1243dSDimitry Andric       auto AliaseeVI = std::get<0>(getValueInfoFromValueId(AliaseeValueId));
78460b57cec5SDimitry Andric       auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, AS->modulePath());
78470b57cec5SDimitry Andric       AS->setAliasee(AliaseeVI, AliaseeInModule);
78480b57cec5SDimitry Andric 
7849bdd1243dSDimitry Andric       ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
78500b57cec5SDimitry Andric       LastSeenGUID = VI.getGUID();
78510b57cec5SDimitry Andric       TheIndex.addGlobalValueSummary(VI, std::move(AS));
78520b57cec5SDimitry Andric       break;
78530b57cec5SDimitry Andric     }
78540b57cec5SDimitry Andric     // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
78550b57cec5SDimitry Andric     case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
78560b57cec5SDimitry Andric       unsigned ValueID = Record[0];
78570b57cec5SDimitry Andric       uint64_t ModuleId = Record[1];
78580b57cec5SDimitry Andric       uint64_t RawFlags = Record[2];
78590b57cec5SDimitry Andric       unsigned RefArrayStart = 3;
78600b57cec5SDimitry Andric       GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false,
78615ffd83dbSDimitry Andric                                       /* WriteOnly */ false,
78625ffd83dbSDimitry Andric                                       /* Constant */ false,
78635ffd83dbSDimitry Andric                                       GlobalObject::VCallVisibilityPublic);
78640b57cec5SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
78650b57cec5SDimitry Andric       if (Version >= 5) {
78660b57cec5SDimitry Andric         GVF = getDecodedGVarFlags(Record[3]);
78670b57cec5SDimitry Andric         RefArrayStart = 4;
78680b57cec5SDimitry Andric       }
78690b57cec5SDimitry Andric       std::vector<ValueInfo> Refs =
78700b57cec5SDimitry Andric           makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
78710b57cec5SDimitry Andric       auto FS =
78728bcb0991SDimitry Andric           std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
78730b57cec5SDimitry Andric       LastSeenSummary = FS.get();
78740b57cec5SDimitry Andric       FS->setModulePath(ModuleIdMap[ModuleId]);
7875bdd1243dSDimitry Andric       ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
78760b57cec5SDimitry Andric       LastSeenGUID = VI.getGUID();
78770b57cec5SDimitry Andric       TheIndex.addGlobalValueSummary(VI, std::move(FS));
78780b57cec5SDimitry Andric       break;
78790b57cec5SDimitry Andric     }
78800b57cec5SDimitry Andric     // FS_COMBINED_ORIGINAL_NAME: [original_name]
78810b57cec5SDimitry Andric     case bitc::FS_COMBINED_ORIGINAL_NAME: {
78820b57cec5SDimitry Andric       uint64_t OriginalName = Record[0];
78830b57cec5SDimitry Andric       if (!LastSeenSummary)
78840b57cec5SDimitry Andric         return error("Name attachment that does not follow a combined record");
78850b57cec5SDimitry Andric       LastSeenSummary->setOriginalName(OriginalName);
78860b57cec5SDimitry Andric       TheIndex.addOriginalName(LastSeenGUID, OriginalName);
78870b57cec5SDimitry Andric       // Reset the LastSeenSummary
78880b57cec5SDimitry Andric       LastSeenSummary = nullptr;
78890b57cec5SDimitry Andric       LastSeenGUID = 0;
78900b57cec5SDimitry Andric       break;
78910b57cec5SDimitry Andric     }
78920b57cec5SDimitry Andric     case bitc::FS_TYPE_TESTS:
78930b57cec5SDimitry Andric       assert(PendingTypeTests.empty());
7894e8d8bef9SDimitry Andric       llvm::append_range(PendingTypeTests, Record);
78950b57cec5SDimitry Andric       break;
78960b57cec5SDimitry Andric 
78970b57cec5SDimitry Andric     case bitc::FS_TYPE_TEST_ASSUME_VCALLS:
78980b57cec5SDimitry Andric       assert(PendingTypeTestAssumeVCalls.empty());
78990b57cec5SDimitry Andric       for (unsigned I = 0; I != Record.size(); I += 2)
79000b57cec5SDimitry Andric         PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
79010b57cec5SDimitry Andric       break;
79020b57cec5SDimitry Andric 
79030b57cec5SDimitry Andric     case bitc::FS_TYPE_CHECKED_LOAD_VCALLS:
79040b57cec5SDimitry Andric       assert(PendingTypeCheckedLoadVCalls.empty());
79050b57cec5SDimitry Andric       for (unsigned I = 0; I != Record.size(); I += 2)
79060b57cec5SDimitry Andric         PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
79070b57cec5SDimitry Andric       break;
79080b57cec5SDimitry Andric 
79090b57cec5SDimitry Andric     case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL:
79100b57cec5SDimitry Andric       PendingTypeTestAssumeConstVCalls.push_back(
79110b57cec5SDimitry Andric           {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
79120b57cec5SDimitry Andric       break;
79130b57cec5SDimitry Andric 
79140b57cec5SDimitry Andric     case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL:
79150b57cec5SDimitry Andric       PendingTypeCheckedLoadConstVCalls.push_back(
79160b57cec5SDimitry Andric           {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
79170b57cec5SDimitry Andric       break;
79180b57cec5SDimitry Andric 
79190b57cec5SDimitry Andric     case bitc::FS_CFI_FUNCTION_DEFS: {
79200b57cec5SDimitry Andric       std::set<std::string> &CfiFunctionDefs = TheIndex.cfiFunctionDefs();
79210b57cec5SDimitry Andric       for (unsigned I = 0; I != Record.size(); I += 2)
79220b57cec5SDimitry Andric         CfiFunctionDefs.insert(
79230b57cec5SDimitry Andric             {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
79240b57cec5SDimitry Andric       break;
79250b57cec5SDimitry Andric     }
79260b57cec5SDimitry Andric 
79270b57cec5SDimitry Andric     case bitc::FS_CFI_FUNCTION_DECLS: {
79280b57cec5SDimitry Andric       std::set<std::string> &CfiFunctionDecls = TheIndex.cfiFunctionDecls();
79290b57cec5SDimitry Andric       for (unsigned I = 0; I != Record.size(); I += 2)
79300b57cec5SDimitry Andric         CfiFunctionDecls.insert(
79310b57cec5SDimitry Andric             {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
79320b57cec5SDimitry Andric       break;
79330b57cec5SDimitry Andric     }
79340b57cec5SDimitry Andric 
79350b57cec5SDimitry Andric     case bitc::FS_TYPE_ID:
79360b57cec5SDimitry Andric       parseTypeIdSummaryRecord(Record, Strtab, TheIndex);
79370b57cec5SDimitry Andric       break;
79380b57cec5SDimitry Andric 
79390b57cec5SDimitry Andric     case bitc::FS_TYPE_ID_METADATA:
79400b57cec5SDimitry Andric       parseTypeIdCompatibleVtableSummaryRecord(Record);
79410b57cec5SDimitry Andric       break;
79425ffd83dbSDimitry Andric 
79435ffd83dbSDimitry Andric     case bitc::FS_BLOCK_COUNT:
79445ffd83dbSDimitry Andric       TheIndex.addBlockCount(Record[0]);
79455ffd83dbSDimitry Andric       break;
79465ffd83dbSDimitry Andric 
79475ffd83dbSDimitry Andric     case bitc::FS_PARAM_ACCESS: {
79485ffd83dbSDimitry Andric       PendingParamAccesses = parseParamAccesses(Record);
79495ffd83dbSDimitry Andric       break;
79505ffd83dbSDimitry Andric     }
7951bdd1243dSDimitry Andric 
7952bdd1243dSDimitry Andric     case bitc::FS_STACK_IDS: { // [n x stackid]
7953bdd1243dSDimitry Andric       // Save stack ids in the reader to consult when adding stack ids from the
7954bdd1243dSDimitry Andric       // lists in the stack node and alloc node entries.
7955bdd1243dSDimitry Andric       StackIds = ArrayRef<uint64_t>(Record);
7956bdd1243dSDimitry Andric       break;
7957bdd1243dSDimitry Andric     }
7958bdd1243dSDimitry Andric 
7959bdd1243dSDimitry Andric     case bitc::FS_PERMODULE_CALLSITE_INFO: {
7960bdd1243dSDimitry Andric       unsigned ValueID = Record[0];
7961bdd1243dSDimitry Andric       SmallVector<unsigned> StackIdList;
7962bdd1243dSDimitry Andric       for (auto R = Record.begin() + 1; R != Record.end(); R++) {
7963bdd1243dSDimitry Andric         assert(*R < StackIds.size());
7964bdd1243dSDimitry Andric         StackIdList.push_back(TheIndex.addOrGetStackIdIndex(StackIds[*R]));
7965bdd1243dSDimitry Andric       }
7966bdd1243dSDimitry Andric       ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
7967bdd1243dSDimitry Andric       PendingCallsites.push_back(CallsiteInfo({VI, std::move(StackIdList)}));
7968bdd1243dSDimitry Andric       break;
7969bdd1243dSDimitry Andric     }
7970bdd1243dSDimitry Andric 
7971bdd1243dSDimitry Andric     case bitc::FS_COMBINED_CALLSITE_INFO: {
7972bdd1243dSDimitry Andric       auto RecordIter = Record.begin();
7973bdd1243dSDimitry Andric       unsigned ValueID = *RecordIter++;
7974bdd1243dSDimitry Andric       unsigned NumStackIds = *RecordIter++;
7975bdd1243dSDimitry Andric       unsigned NumVersions = *RecordIter++;
7976bdd1243dSDimitry Andric       assert(Record.size() == 3 + NumStackIds + NumVersions);
7977bdd1243dSDimitry Andric       SmallVector<unsigned> StackIdList;
7978bdd1243dSDimitry Andric       for (unsigned J = 0; J < NumStackIds; J++) {
7979bdd1243dSDimitry Andric         assert(*RecordIter < StackIds.size());
7980bdd1243dSDimitry Andric         StackIdList.push_back(
7981bdd1243dSDimitry Andric             TheIndex.addOrGetStackIdIndex(StackIds[*RecordIter++]));
7982bdd1243dSDimitry Andric       }
7983bdd1243dSDimitry Andric       SmallVector<unsigned> Versions;
7984bdd1243dSDimitry Andric       for (unsigned J = 0; J < NumVersions; J++)
7985bdd1243dSDimitry Andric         Versions.push_back(*RecordIter++);
7986bdd1243dSDimitry Andric       ValueInfo VI = std::get<0>(
7987bdd1243dSDimitry Andric           getValueInfoFromValueId</*AllowNullValueInfo*/ true>(ValueID));
7988bdd1243dSDimitry Andric       PendingCallsites.push_back(
7989bdd1243dSDimitry Andric           CallsiteInfo({VI, std::move(Versions), std::move(StackIdList)}));
7990bdd1243dSDimitry Andric       break;
7991bdd1243dSDimitry Andric     }
7992bdd1243dSDimitry Andric 
7993bdd1243dSDimitry Andric     case bitc::FS_PERMODULE_ALLOC_INFO: {
7994bdd1243dSDimitry Andric       unsigned I = 0;
7995bdd1243dSDimitry Andric       std::vector<MIBInfo> MIBs;
7996*0fca6ea1SDimitry Andric       unsigned NumMIBs = 0;
7997*0fca6ea1SDimitry Andric       if (Version >= 10)
7998*0fca6ea1SDimitry Andric         NumMIBs = Record[I++];
7999*0fca6ea1SDimitry Andric       unsigned MIBsRead = 0;
8000*0fca6ea1SDimitry Andric       while ((Version >= 10 && MIBsRead++ < NumMIBs) ||
8001*0fca6ea1SDimitry Andric              (Version < 10 && I < Record.size())) {
8002bdd1243dSDimitry Andric         assert(Record.size() - I >= 2);
8003bdd1243dSDimitry Andric         AllocationType AllocType = (AllocationType)Record[I++];
8004bdd1243dSDimitry Andric         unsigned NumStackEntries = Record[I++];
8005bdd1243dSDimitry Andric         assert(Record.size() - I >= NumStackEntries);
8006bdd1243dSDimitry Andric         SmallVector<unsigned> StackIdList;
8007bdd1243dSDimitry Andric         for (unsigned J = 0; J < NumStackEntries; J++) {
8008bdd1243dSDimitry Andric           assert(Record[I] < StackIds.size());
8009bdd1243dSDimitry Andric           StackIdList.push_back(
8010bdd1243dSDimitry Andric               TheIndex.addOrGetStackIdIndex(StackIds[Record[I++]]));
8011bdd1243dSDimitry Andric         }
8012bdd1243dSDimitry Andric         MIBs.push_back(MIBInfo(AllocType, std::move(StackIdList)));
8013bdd1243dSDimitry Andric       }
8014*0fca6ea1SDimitry Andric       std::vector<uint64_t> TotalSizes;
8015*0fca6ea1SDimitry Andric       // We either have no sizes or NumMIBs of them.
8016*0fca6ea1SDimitry Andric       assert(I == Record.size() || Record.size() - I == NumMIBs);
8017*0fca6ea1SDimitry Andric       if (I < Record.size()) {
8018*0fca6ea1SDimitry Andric         MIBsRead = 0;
8019*0fca6ea1SDimitry Andric         while (MIBsRead++ < NumMIBs)
8020*0fca6ea1SDimitry Andric           TotalSizes.push_back(Record[I++]);
8021*0fca6ea1SDimitry Andric       }
8022bdd1243dSDimitry Andric       PendingAllocs.push_back(AllocInfo(std::move(MIBs)));
8023*0fca6ea1SDimitry Andric       if (!TotalSizes.empty()) {
8024*0fca6ea1SDimitry Andric         assert(PendingAllocs.back().MIBs.size() == TotalSizes.size());
8025*0fca6ea1SDimitry Andric         PendingAllocs.back().TotalSizes = std::move(TotalSizes);
8026*0fca6ea1SDimitry Andric       }
8027bdd1243dSDimitry Andric       break;
8028bdd1243dSDimitry Andric     }
8029bdd1243dSDimitry Andric 
8030bdd1243dSDimitry Andric     case bitc::FS_COMBINED_ALLOC_INFO: {
8031bdd1243dSDimitry Andric       unsigned I = 0;
8032bdd1243dSDimitry Andric       std::vector<MIBInfo> MIBs;
8033bdd1243dSDimitry Andric       unsigned NumMIBs = Record[I++];
8034bdd1243dSDimitry Andric       unsigned NumVersions = Record[I++];
8035bdd1243dSDimitry Andric       unsigned MIBsRead = 0;
8036bdd1243dSDimitry Andric       while (MIBsRead++ < NumMIBs) {
8037bdd1243dSDimitry Andric         assert(Record.size() - I >= 2);
8038bdd1243dSDimitry Andric         AllocationType AllocType = (AllocationType)Record[I++];
8039bdd1243dSDimitry Andric         unsigned NumStackEntries = Record[I++];
8040bdd1243dSDimitry Andric         assert(Record.size() - I >= NumStackEntries);
8041bdd1243dSDimitry Andric         SmallVector<unsigned> StackIdList;
8042bdd1243dSDimitry Andric         for (unsigned J = 0; J < NumStackEntries; J++) {
8043bdd1243dSDimitry Andric           assert(Record[I] < StackIds.size());
8044bdd1243dSDimitry Andric           StackIdList.push_back(
8045bdd1243dSDimitry Andric               TheIndex.addOrGetStackIdIndex(StackIds[Record[I++]]));
8046bdd1243dSDimitry Andric         }
8047bdd1243dSDimitry Andric         MIBs.push_back(MIBInfo(AllocType, std::move(StackIdList)));
8048bdd1243dSDimitry Andric       }
8049bdd1243dSDimitry Andric       assert(Record.size() - I >= NumVersions);
8050bdd1243dSDimitry Andric       SmallVector<uint8_t> Versions;
8051bdd1243dSDimitry Andric       for (unsigned J = 0; J < NumVersions; J++)
8052bdd1243dSDimitry Andric         Versions.push_back(Record[I++]);
8053*0fca6ea1SDimitry Andric       std::vector<uint64_t> TotalSizes;
8054*0fca6ea1SDimitry Andric       // We either have no sizes or NumMIBs of them.
8055*0fca6ea1SDimitry Andric       assert(I == Record.size() || Record.size() - I == NumMIBs);
8056*0fca6ea1SDimitry Andric       if (I < Record.size()) {
8057*0fca6ea1SDimitry Andric         MIBsRead = 0;
8058*0fca6ea1SDimitry Andric         while (MIBsRead++ < NumMIBs) {
8059*0fca6ea1SDimitry Andric           TotalSizes.push_back(Record[I++]);
8060*0fca6ea1SDimitry Andric         }
8061*0fca6ea1SDimitry Andric       }
8062bdd1243dSDimitry Andric       PendingAllocs.push_back(
8063bdd1243dSDimitry Andric           AllocInfo(std::move(Versions), std::move(MIBs)));
8064*0fca6ea1SDimitry Andric       if (!TotalSizes.empty()) {
8065*0fca6ea1SDimitry Andric         assert(PendingAllocs.back().MIBs.size() == TotalSizes.size());
8066*0fca6ea1SDimitry Andric         PendingAllocs.back().TotalSizes = std::move(TotalSizes);
8067*0fca6ea1SDimitry Andric       }
8068bdd1243dSDimitry Andric       break;
8069bdd1243dSDimitry Andric     }
80700b57cec5SDimitry Andric     }
80710b57cec5SDimitry Andric   }
80720b57cec5SDimitry Andric   llvm_unreachable("Exit infinite loop");
80730b57cec5SDimitry Andric }
80740b57cec5SDimitry Andric 
80750b57cec5SDimitry Andric // Parse the  module string table block into the Index.
80760b57cec5SDimitry Andric // This populates the ModulePathStringTable map in the index.
80770b57cec5SDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
80780b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
80790b57cec5SDimitry Andric     return Err;
80800b57cec5SDimitry Andric 
80810b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
80820b57cec5SDimitry Andric 
80830b57cec5SDimitry Andric   SmallString<128> ModulePath;
80840b57cec5SDimitry Andric   ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr;
80850b57cec5SDimitry Andric 
80860b57cec5SDimitry Andric   while (true) {
80870b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
80880b57cec5SDimitry Andric     if (!MaybeEntry)
80890b57cec5SDimitry Andric       return MaybeEntry.takeError();
80900b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
80910b57cec5SDimitry Andric 
80920b57cec5SDimitry Andric     switch (Entry.Kind) {
80930b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
80940b57cec5SDimitry Andric     case BitstreamEntry::Error:
80950b57cec5SDimitry Andric       return error("Malformed block");
80960b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
80970b57cec5SDimitry Andric       return Error::success();
80980b57cec5SDimitry Andric     case BitstreamEntry::Record:
80990b57cec5SDimitry Andric       // The interesting case.
81000b57cec5SDimitry Andric       break;
81010b57cec5SDimitry Andric     }
81020b57cec5SDimitry Andric 
81030b57cec5SDimitry Andric     Record.clear();
81040b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
81050b57cec5SDimitry Andric     if (!MaybeRecord)
81060b57cec5SDimitry Andric       return MaybeRecord.takeError();
81070b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
81080b57cec5SDimitry Andric     default: // Default behavior: ignore.
81090b57cec5SDimitry Andric       break;
81100b57cec5SDimitry Andric     case bitc::MST_CODE_ENTRY: {
81110b57cec5SDimitry Andric       // MST_ENTRY: [modid, namechar x N]
81120b57cec5SDimitry Andric       uint64_t ModuleId = Record[0];
81130b57cec5SDimitry Andric 
81140b57cec5SDimitry Andric       if (convertToString(Record, 1, ModulePath))
81150b57cec5SDimitry Andric         return error("Invalid record");
81160b57cec5SDimitry Andric 
81175f757f3fSDimitry Andric       LastSeenModule = TheIndex.addModule(ModulePath);
81180b57cec5SDimitry Andric       ModuleIdMap[ModuleId] = LastSeenModule->first();
81190b57cec5SDimitry Andric 
81200b57cec5SDimitry Andric       ModulePath.clear();
81210b57cec5SDimitry Andric       break;
81220b57cec5SDimitry Andric     }
81230b57cec5SDimitry Andric     /// MST_CODE_HASH: [5*i32]
81240b57cec5SDimitry Andric     case bitc::MST_CODE_HASH: {
81250b57cec5SDimitry Andric       if (Record.size() != 5)
81260b57cec5SDimitry Andric         return error("Invalid hash length " + Twine(Record.size()).str());
81270b57cec5SDimitry Andric       if (!LastSeenModule)
81280b57cec5SDimitry Andric         return error("Invalid hash that does not follow a module path");
81290b57cec5SDimitry Andric       int Pos = 0;
81300b57cec5SDimitry Andric       for (auto &Val : Record) {
81310b57cec5SDimitry Andric         assert(!(Val >> 32) && "Unexpected high bits set");
81325f757f3fSDimitry Andric         LastSeenModule->second[Pos++] = Val;
81330b57cec5SDimitry Andric       }
81340b57cec5SDimitry Andric       // Reset LastSeenModule to avoid overriding the hash unexpectedly.
81350b57cec5SDimitry Andric       LastSeenModule = nullptr;
81360b57cec5SDimitry Andric       break;
81370b57cec5SDimitry Andric     }
81380b57cec5SDimitry Andric     }
81390b57cec5SDimitry Andric   }
81400b57cec5SDimitry Andric   llvm_unreachable("Exit infinite loop");
81410b57cec5SDimitry Andric }
81420b57cec5SDimitry Andric 
81430b57cec5SDimitry Andric namespace {
81440b57cec5SDimitry Andric 
81450b57cec5SDimitry Andric // FIXME: This class is only here to support the transition to llvm::Error. It
81460b57cec5SDimitry Andric // will be removed once this transition is complete. Clients should prefer to
81470b57cec5SDimitry Andric // deal with the Error value directly, rather than converting to error_code.
81480b57cec5SDimitry Andric class BitcodeErrorCategoryType : public std::error_category {
81490b57cec5SDimitry Andric   const char *name() const noexcept override {
81500b57cec5SDimitry Andric     return "llvm.bitcode";
81510b57cec5SDimitry Andric   }
81520b57cec5SDimitry Andric 
81530b57cec5SDimitry Andric   std::string message(int IE) const override {
81540b57cec5SDimitry Andric     BitcodeError E = static_cast<BitcodeError>(IE);
81550b57cec5SDimitry Andric     switch (E) {
81560b57cec5SDimitry Andric     case BitcodeError::CorruptedBitcode:
81570b57cec5SDimitry Andric       return "Corrupted bitcode";
81580b57cec5SDimitry Andric     }
81590b57cec5SDimitry Andric     llvm_unreachable("Unknown error type!");
81600b57cec5SDimitry Andric   }
81610b57cec5SDimitry Andric };
81620b57cec5SDimitry Andric 
81630b57cec5SDimitry Andric } // end anonymous namespace
81640b57cec5SDimitry Andric 
81650b57cec5SDimitry Andric const std::error_category &llvm::BitcodeErrorCategory() {
8166753f127fSDimitry Andric   static BitcodeErrorCategoryType ErrorCategory;
8167753f127fSDimitry Andric   return ErrorCategory;
81680b57cec5SDimitry Andric }
81690b57cec5SDimitry Andric 
81700b57cec5SDimitry Andric static Expected<StringRef> readBlobInRecord(BitstreamCursor &Stream,
81710b57cec5SDimitry Andric                                             unsigned Block, unsigned RecordID) {
81720b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(Block))
81730b57cec5SDimitry Andric     return std::move(Err);
81740b57cec5SDimitry Andric 
81750b57cec5SDimitry Andric   StringRef Strtab;
81760b57cec5SDimitry Andric   while (true) {
81770b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
81780b57cec5SDimitry Andric     if (!MaybeEntry)
81790b57cec5SDimitry Andric       return MaybeEntry.takeError();
81800b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
81810b57cec5SDimitry Andric 
81820b57cec5SDimitry Andric     switch (Entry.Kind) {
81830b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
81840b57cec5SDimitry Andric       return Strtab;
81850b57cec5SDimitry Andric 
81860b57cec5SDimitry Andric     case BitstreamEntry::Error:
81870b57cec5SDimitry Andric       return error("Malformed block");
81880b57cec5SDimitry Andric 
81890b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
81900b57cec5SDimitry Andric       if (Error Err = Stream.SkipBlock())
81910b57cec5SDimitry Andric         return std::move(Err);
81920b57cec5SDimitry Andric       break;
81930b57cec5SDimitry Andric 
81940b57cec5SDimitry Andric     case BitstreamEntry::Record:
81950b57cec5SDimitry Andric       StringRef Blob;
81960b57cec5SDimitry Andric       SmallVector<uint64_t, 1> Record;
81970b57cec5SDimitry Andric       Expected<unsigned> MaybeRecord =
81980b57cec5SDimitry Andric           Stream.readRecord(Entry.ID, Record, &Blob);
81990b57cec5SDimitry Andric       if (!MaybeRecord)
82000b57cec5SDimitry Andric         return MaybeRecord.takeError();
82010b57cec5SDimitry Andric       if (MaybeRecord.get() == RecordID)
82020b57cec5SDimitry Andric         Strtab = Blob;
82030b57cec5SDimitry Andric       break;
82040b57cec5SDimitry Andric     }
82050b57cec5SDimitry Andric   }
82060b57cec5SDimitry Andric }
82070b57cec5SDimitry Andric 
82080b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
82090b57cec5SDimitry Andric // External interface
82100b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
82110b57cec5SDimitry Andric 
82120b57cec5SDimitry Andric Expected<std::vector<BitcodeModule>>
82130b57cec5SDimitry Andric llvm::getBitcodeModuleList(MemoryBufferRef Buffer) {
82140b57cec5SDimitry Andric   auto FOrErr = getBitcodeFileContents(Buffer);
82150b57cec5SDimitry Andric   if (!FOrErr)
82160b57cec5SDimitry Andric     return FOrErr.takeError();
82170b57cec5SDimitry Andric   return std::move(FOrErr->Mods);
82180b57cec5SDimitry Andric }
82190b57cec5SDimitry Andric 
82200b57cec5SDimitry Andric Expected<BitcodeFileContents>
82210b57cec5SDimitry Andric llvm::getBitcodeFileContents(MemoryBufferRef Buffer) {
82220b57cec5SDimitry Andric   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
82230b57cec5SDimitry Andric   if (!StreamOrErr)
82240b57cec5SDimitry Andric     return StreamOrErr.takeError();
82250b57cec5SDimitry Andric   BitstreamCursor &Stream = *StreamOrErr;
82260b57cec5SDimitry Andric 
82270b57cec5SDimitry Andric   BitcodeFileContents F;
82280b57cec5SDimitry Andric   while (true) {
82290b57cec5SDimitry Andric     uint64_t BCBegin = Stream.getCurrentByteNo();
82300b57cec5SDimitry Andric 
82310b57cec5SDimitry Andric     // We may be consuming bitcode from a client that leaves garbage at the end
82320b57cec5SDimitry Andric     // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to
82330b57cec5SDimitry Andric     // the end that there cannot possibly be another module, stop looking.
82340b57cec5SDimitry Andric     if (BCBegin + 8 >= Stream.getBitcodeBytes().size())
82350b57cec5SDimitry Andric       return F;
82360b57cec5SDimitry Andric 
82370b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
82380b57cec5SDimitry Andric     if (!MaybeEntry)
82390b57cec5SDimitry Andric       return MaybeEntry.takeError();
82400b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
82410b57cec5SDimitry Andric 
82420b57cec5SDimitry Andric     switch (Entry.Kind) {
82430b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
82440b57cec5SDimitry Andric     case BitstreamEntry::Error:
82450b57cec5SDimitry Andric       return error("Malformed block");
82460b57cec5SDimitry Andric 
82470b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: {
82480b57cec5SDimitry Andric       uint64_t IdentificationBit = -1ull;
82490b57cec5SDimitry Andric       if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
82500b57cec5SDimitry Andric         IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8;
82510b57cec5SDimitry Andric         if (Error Err = Stream.SkipBlock())
82520b57cec5SDimitry Andric           return std::move(Err);
82530b57cec5SDimitry Andric 
82540b57cec5SDimitry Andric         {
82550b57cec5SDimitry Andric           Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
82560b57cec5SDimitry Andric           if (!MaybeEntry)
82570b57cec5SDimitry Andric             return MaybeEntry.takeError();
82580b57cec5SDimitry Andric           Entry = MaybeEntry.get();
82590b57cec5SDimitry Andric         }
82600b57cec5SDimitry Andric 
82610b57cec5SDimitry Andric         if (Entry.Kind != BitstreamEntry::SubBlock ||
82620b57cec5SDimitry Andric             Entry.ID != bitc::MODULE_BLOCK_ID)
82630b57cec5SDimitry Andric           return error("Malformed block");
82640b57cec5SDimitry Andric       }
82650b57cec5SDimitry Andric 
82660b57cec5SDimitry Andric       if (Entry.ID == bitc::MODULE_BLOCK_ID) {
82670b57cec5SDimitry Andric         uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8;
82680b57cec5SDimitry Andric         if (Error Err = Stream.SkipBlock())
82690b57cec5SDimitry Andric           return std::move(Err);
82700b57cec5SDimitry Andric 
82710b57cec5SDimitry Andric         F.Mods.push_back({Stream.getBitcodeBytes().slice(
82720b57cec5SDimitry Andric                               BCBegin, Stream.getCurrentByteNo() - BCBegin),
82730b57cec5SDimitry Andric                           Buffer.getBufferIdentifier(), IdentificationBit,
82740b57cec5SDimitry Andric                           ModuleBit});
82750b57cec5SDimitry Andric         continue;
82760b57cec5SDimitry Andric       }
82770b57cec5SDimitry Andric 
82780b57cec5SDimitry Andric       if (Entry.ID == bitc::STRTAB_BLOCK_ID) {
82790b57cec5SDimitry Andric         Expected<StringRef> Strtab =
82800b57cec5SDimitry Andric             readBlobInRecord(Stream, bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB);
82810b57cec5SDimitry Andric         if (!Strtab)
82820b57cec5SDimitry Andric           return Strtab.takeError();
82830b57cec5SDimitry Andric         // This string table is used by every preceding bitcode module that does
82840b57cec5SDimitry Andric         // not have its own string table. A bitcode file may have multiple
82850b57cec5SDimitry Andric         // string tables if it was created by binary concatenation, for example
82860b57cec5SDimitry Andric         // with "llvm-cat -b".
82870eae32dcSDimitry Andric         for (BitcodeModule &I : llvm::reverse(F.Mods)) {
82880eae32dcSDimitry Andric           if (!I.Strtab.empty())
82890b57cec5SDimitry Andric             break;
82900eae32dcSDimitry Andric           I.Strtab = *Strtab;
82910b57cec5SDimitry Andric         }
82920b57cec5SDimitry Andric         // Similarly, the string table is used by every preceding symbol table;
82930b57cec5SDimitry Andric         // normally there will be just one unless the bitcode file was created
82940b57cec5SDimitry Andric         // by binary concatenation.
82950b57cec5SDimitry Andric         if (!F.Symtab.empty() && F.StrtabForSymtab.empty())
82960b57cec5SDimitry Andric           F.StrtabForSymtab = *Strtab;
82970b57cec5SDimitry Andric         continue;
82980b57cec5SDimitry Andric       }
82990b57cec5SDimitry Andric 
83000b57cec5SDimitry Andric       if (Entry.ID == bitc::SYMTAB_BLOCK_ID) {
83010b57cec5SDimitry Andric         Expected<StringRef> SymtabOrErr =
83020b57cec5SDimitry Andric             readBlobInRecord(Stream, bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB);
83030b57cec5SDimitry Andric         if (!SymtabOrErr)
83040b57cec5SDimitry Andric           return SymtabOrErr.takeError();
83050b57cec5SDimitry Andric 
83060b57cec5SDimitry Andric         // We can expect the bitcode file to have multiple symbol tables if it
83070b57cec5SDimitry Andric         // was created by binary concatenation. In that case we silently
83080b57cec5SDimitry Andric         // ignore any subsequent symbol tables, which is fine because this is a
83090b57cec5SDimitry Andric         // low level function. The client is expected to notice that the number
83100b57cec5SDimitry Andric         // of modules in the symbol table does not match the number of modules
83110b57cec5SDimitry Andric         // in the input file and regenerate the symbol table.
83120b57cec5SDimitry Andric         if (F.Symtab.empty())
83130b57cec5SDimitry Andric           F.Symtab = *SymtabOrErr;
83140b57cec5SDimitry Andric         continue;
83150b57cec5SDimitry Andric       }
83160b57cec5SDimitry Andric 
83170b57cec5SDimitry Andric       if (Error Err = Stream.SkipBlock())
83180b57cec5SDimitry Andric         return std::move(Err);
83190b57cec5SDimitry Andric       continue;
83200b57cec5SDimitry Andric     }
83210b57cec5SDimitry Andric     case BitstreamEntry::Record:
8322349cc55cSDimitry Andric       if (Error E = Stream.skipRecord(Entry.ID).takeError())
8323349cc55cSDimitry Andric         return std::move(E);
83240b57cec5SDimitry Andric       continue;
83250b57cec5SDimitry Andric     }
83260b57cec5SDimitry Andric   }
83270b57cec5SDimitry Andric }
83280b57cec5SDimitry Andric 
83290b57cec5SDimitry Andric /// Get a lazy one-at-time loading module from bitcode.
83300b57cec5SDimitry Andric ///
83310b57cec5SDimitry Andric /// This isn't always used in a lazy context.  In particular, it's also used by
83320b57cec5SDimitry Andric /// \a parseModule().  If this is truly lazy, then we need to eagerly pull
83330b57cec5SDimitry Andric /// in forward-referenced functions from block address references.
83340b57cec5SDimitry Andric ///
83350b57cec5SDimitry Andric /// \param[in] MaterializeAll Set to \c true if we should materialize
83360b57cec5SDimitry Andric /// everything.
83370b57cec5SDimitry Andric Expected<std::unique_ptr<Module>>
83380b57cec5SDimitry Andric BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll,
83395ffd83dbSDimitry Andric                              bool ShouldLazyLoadMetadata, bool IsImporting,
8340bdd1243dSDimitry Andric                              ParserCallbacks Callbacks) {
83410b57cec5SDimitry Andric   BitstreamCursor Stream(Buffer);
83420b57cec5SDimitry Andric 
83430b57cec5SDimitry Andric   std::string ProducerIdentification;
83440b57cec5SDimitry Andric   if (IdentificationBit != -1ull) {
83450b57cec5SDimitry Andric     if (Error JumpFailed = Stream.JumpToBit(IdentificationBit))
83460b57cec5SDimitry Andric       return std::move(JumpFailed);
8347349cc55cSDimitry Andric     if (Error E =
8348349cc55cSDimitry Andric             readIdentificationBlock(Stream).moveInto(ProducerIdentification))
8349349cc55cSDimitry Andric       return std::move(E);
83500b57cec5SDimitry Andric   }
83510b57cec5SDimitry Andric 
83520b57cec5SDimitry Andric   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
83530b57cec5SDimitry Andric     return std::move(JumpFailed);
83540b57cec5SDimitry Andric   auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
83550b57cec5SDimitry Andric                               Context);
83560b57cec5SDimitry Andric 
83570b57cec5SDimitry Andric   std::unique_ptr<Module> M =
83588bcb0991SDimitry Andric       std::make_unique<Module>(ModuleIdentifier, Context);
83590b57cec5SDimitry Andric   M->setMaterializer(R);
83600b57cec5SDimitry Andric 
83610b57cec5SDimitry Andric   // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
83625ffd83dbSDimitry Andric   if (Error Err = R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata,
8363bdd1243dSDimitry Andric                                       IsImporting, Callbacks))
83640b57cec5SDimitry Andric     return std::move(Err);
83650b57cec5SDimitry Andric 
83660b57cec5SDimitry Andric   if (MaterializeAll) {
83670b57cec5SDimitry Andric     // Read in the entire module, and destroy the BitcodeReader.
83680b57cec5SDimitry Andric     if (Error Err = M->materializeAll())
83690b57cec5SDimitry Andric       return std::move(Err);
83700b57cec5SDimitry Andric   } else {
83710b57cec5SDimitry Andric     // Resolve forward references from blockaddresses.
83720b57cec5SDimitry Andric     if (Error Err = R->materializeForwardReferencedFunctions())
83730b57cec5SDimitry Andric       return std::move(Err);
83740b57cec5SDimitry Andric   }
8375*0fca6ea1SDimitry Andric 
83760b57cec5SDimitry Andric   return std::move(M);
83770b57cec5SDimitry Andric }
83780b57cec5SDimitry Andric 
83790b57cec5SDimitry Andric Expected<std::unique_ptr<Module>>
83800b57cec5SDimitry Andric BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata,
8381bdd1243dSDimitry Andric                              bool IsImporting, ParserCallbacks Callbacks) {
83825ffd83dbSDimitry Andric   return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting,
8383bdd1243dSDimitry Andric                        Callbacks);
83840b57cec5SDimitry Andric }
83850b57cec5SDimitry Andric 
83860b57cec5SDimitry Andric // Parse the specified bitcode buffer and merge the index into CombinedIndex.
83870b57cec5SDimitry Andric // We don't use ModuleIdentifier here because the client may need to control the
83880b57cec5SDimitry Andric // module path used in the combined summary (e.g. when reading summaries for
83890b57cec5SDimitry Andric // regular LTO modules).
8390bdd1243dSDimitry Andric Error BitcodeModule::readSummary(
83915f757f3fSDimitry Andric     ModuleSummaryIndex &CombinedIndex, StringRef ModulePath,
8392bdd1243dSDimitry Andric     std::function<bool(GlobalValue::GUID)> IsPrevailing) {
83930b57cec5SDimitry Andric   BitstreamCursor Stream(Buffer);
83940b57cec5SDimitry Andric   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
83950b57cec5SDimitry Andric     return JumpFailed;
83960b57cec5SDimitry Andric 
83970b57cec5SDimitry Andric   ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
83985f757f3fSDimitry Andric                                     ModulePath, IsPrevailing);
83990b57cec5SDimitry Andric   return R.parseModule();
84000b57cec5SDimitry Andric }
84010b57cec5SDimitry Andric 
84020b57cec5SDimitry Andric // Parse the specified bitcode buffer, returning the function info index.
84030b57cec5SDimitry Andric Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() {
84040b57cec5SDimitry Andric   BitstreamCursor Stream(Buffer);
84050b57cec5SDimitry Andric   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
84060b57cec5SDimitry Andric     return std::move(JumpFailed);
84070b57cec5SDimitry Andric 
84088bcb0991SDimitry Andric   auto Index = std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
84090b57cec5SDimitry Andric   ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,
84100b57cec5SDimitry Andric                                     ModuleIdentifier, 0);
84110b57cec5SDimitry Andric 
84120b57cec5SDimitry Andric   if (Error Err = R.parseModule())
84130b57cec5SDimitry Andric     return std::move(Err);
84140b57cec5SDimitry Andric 
84150b57cec5SDimitry Andric   return std::move(Index);
84160b57cec5SDimitry Andric }
84170b57cec5SDimitry Andric 
841806c3fb27SDimitry Andric static Expected<std::pair<bool, bool>>
841906c3fb27SDimitry Andric getEnableSplitLTOUnitAndUnifiedFlag(BitstreamCursor &Stream,
842006c3fb27SDimitry Andric                                                  unsigned ID,
842106c3fb27SDimitry Andric                                                  BitcodeLTOInfo &LTOInfo) {
84220b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(ID))
84230b57cec5SDimitry Andric     return std::move(Err);
84240b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
84250b57cec5SDimitry Andric 
84260b57cec5SDimitry Andric   while (true) {
8427349cc55cSDimitry Andric     BitstreamEntry Entry;
842806c3fb27SDimitry Andric     std::pair<bool, bool> Result = {false,false};
8429349cc55cSDimitry Andric     if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
8430349cc55cSDimitry Andric       return std::move(E);
84310b57cec5SDimitry Andric 
84320b57cec5SDimitry Andric     switch (Entry.Kind) {
84330b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
84340b57cec5SDimitry Andric     case BitstreamEntry::Error:
84350b57cec5SDimitry Andric       return error("Malformed block");
843606c3fb27SDimitry Andric     case BitstreamEntry::EndBlock: {
843706c3fb27SDimitry Andric       // If no flags record found, set both flags to false.
843806c3fb27SDimitry Andric       return Result;
843906c3fb27SDimitry Andric     }
84400b57cec5SDimitry Andric     case BitstreamEntry::Record:
84410b57cec5SDimitry Andric       // The interesting case.
84420b57cec5SDimitry Andric       break;
84430b57cec5SDimitry Andric     }
84440b57cec5SDimitry Andric 
84450b57cec5SDimitry Andric     // Look for the FS_FLAGS record.
84460b57cec5SDimitry Andric     Record.clear();
84470b57cec5SDimitry Andric     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
84480b57cec5SDimitry Andric     if (!MaybeBitCode)
84490b57cec5SDimitry Andric       return MaybeBitCode.takeError();
84500b57cec5SDimitry Andric     switch (MaybeBitCode.get()) {
84510b57cec5SDimitry Andric     default: // Default behavior: ignore.
84520b57cec5SDimitry Andric       break;
84530b57cec5SDimitry Andric     case bitc::FS_FLAGS: { // [flags]
84540b57cec5SDimitry Andric       uint64_t Flags = Record[0];
84550b57cec5SDimitry Andric       // Scan flags.
845606c3fb27SDimitry Andric       assert(Flags <= 0x2ff && "Unexpected bits in flag");
84570b57cec5SDimitry Andric 
845806c3fb27SDimitry Andric       bool EnableSplitLTOUnit = Flags & 0x8;
845906c3fb27SDimitry Andric       bool UnifiedLTO = Flags & 0x200;
846006c3fb27SDimitry Andric       Result = {EnableSplitLTOUnit, UnifiedLTO};
846106c3fb27SDimitry Andric 
846206c3fb27SDimitry Andric       return Result;
84630b57cec5SDimitry Andric     }
84640b57cec5SDimitry Andric     }
84650b57cec5SDimitry Andric   }
84660b57cec5SDimitry Andric   llvm_unreachable("Exit infinite loop");
84670b57cec5SDimitry Andric }
84680b57cec5SDimitry Andric 
84690b57cec5SDimitry Andric // Check if the given bitcode buffer contains a global value summary block.
84700b57cec5SDimitry Andric Expected<BitcodeLTOInfo> BitcodeModule::getLTOInfo() {
84710b57cec5SDimitry Andric   BitstreamCursor Stream(Buffer);
84720b57cec5SDimitry Andric   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
84730b57cec5SDimitry Andric     return std::move(JumpFailed);
84740b57cec5SDimitry Andric 
84750b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
84760b57cec5SDimitry Andric     return std::move(Err);
84770b57cec5SDimitry Andric 
84780b57cec5SDimitry Andric   while (true) {
8479349cc55cSDimitry Andric     llvm::BitstreamEntry Entry;
8480349cc55cSDimitry Andric     if (Error E = Stream.advance().moveInto(Entry))
8481349cc55cSDimitry Andric       return std::move(E);
84820b57cec5SDimitry Andric 
84830b57cec5SDimitry Andric     switch (Entry.Kind) {
84840b57cec5SDimitry Andric     case BitstreamEntry::Error:
84850b57cec5SDimitry Andric       return error("Malformed block");
84860b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
84870b57cec5SDimitry Andric       return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/false,
848806c3fb27SDimitry Andric                             /*EnableSplitLTOUnit=*/false, /*UnifiedLTO=*/false};
84890b57cec5SDimitry Andric 
84900b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
84910b57cec5SDimitry Andric       if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) {
849206c3fb27SDimitry Andric         BitcodeLTOInfo LTOInfo;
849306c3fb27SDimitry Andric         Expected<std::pair<bool, bool>> Flags =
849406c3fb27SDimitry Andric             getEnableSplitLTOUnitAndUnifiedFlag(Stream, Entry.ID, LTOInfo);
849506c3fb27SDimitry Andric         if (!Flags)
849606c3fb27SDimitry Andric           return Flags.takeError();
849706c3fb27SDimitry Andric         std::tie(LTOInfo.EnableSplitLTOUnit, LTOInfo.UnifiedLTO) = Flags.get();
849806c3fb27SDimitry Andric         LTOInfo.IsThinLTO = true;
849906c3fb27SDimitry Andric         LTOInfo.HasSummary = true;
850006c3fb27SDimitry Andric         return LTOInfo;
85010b57cec5SDimitry Andric       }
85020b57cec5SDimitry Andric 
85030b57cec5SDimitry Andric       if (Entry.ID == bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID) {
850406c3fb27SDimitry Andric         BitcodeLTOInfo LTOInfo;
850506c3fb27SDimitry Andric         Expected<std::pair<bool, bool>> Flags =
850606c3fb27SDimitry Andric             getEnableSplitLTOUnitAndUnifiedFlag(Stream, Entry.ID, LTOInfo);
850706c3fb27SDimitry Andric         if (!Flags)
850806c3fb27SDimitry Andric           return Flags.takeError();
850906c3fb27SDimitry Andric         std::tie(LTOInfo.EnableSplitLTOUnit, LTOInfo.UnifiedLTO) = Flags.get();
851006c3fb27SDimitry Andric         LTOInfo.IsThinLTO = false;
851106c3fb27SDimitry Andric         LTOInfo.HasSummary = true;
851206c3fb27SDimitry Andric         return LTOInfo;
85130b57cec5SDimitry Andric       }
85140b57cec5SDimitry Andric 
85150b57cec5SDimitry Andric       // Ignore other sub-blocks.
85160b57cec5SDimitry Andric       if (Error Err = Stream.SkipBlock())
85170b57cec5SDimitry Andric         return std::move(Err);
85180b57cec5SDimitry Andric       continue;
85190b57cec5SDimitry Andric 
85200b57cec5SDimitry Andric     case BitstreamEntry::Record:
85210b57cec5SDimitry Andric       if (Expected<unsigned> StreamFailed = Stream.skipRecord(Entry.ID))
85220b57cec5SDimitry Andric         continue;
85230b57cec5SDimitry Andric       else
85240b57cec5SDimitry Andric         return StreamFailed.takeError();
85250b57cec5SDimitry Andric     }
85260b57cec5SDimitry Andric   }
85270b57cec5SDimitry Andric }
85280b57cec5SDimitry Andric 
85290b57cec5SDimitry Andric static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) {
85300b57cec5SDimitry Andric   Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer);
85310b57cec5SDimitry Andric   if (!MsOrErr)
85320b57cec5SDimitry Andric     return MsOrErr.takeError();
85330b57cec5SDimitry Andric 
85340b57cec5SDimitry Andric   if (MsOrErr->size() != 1)
85350b57cec5SDimitry Andric     return error("Expected a single module");
85360b57cec5SDimitry Andric 
85370b57cec5SDimitry Andric   return (*MsOrErr)[0];
85380b57cec5SDimitry Andric }
85390b57cec5SDimitry Andric 
85400b57cec5SDimitry Andric Expected<std::unique_ptr<Module>>
85410b57cec5SDimitry Andric llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context,
8542bdd1243dSDimitry Andric                            bool ShouldLazyLoadMetadata, bool IsImporting,
8543bdd1243dSDimitry Andric                            ParserCallbacks Callbacks) {
85440b57cec5SDimitry Andric   Expected<BitcodeModule> BM = getSingleModule(Buffer);
85450b57cec5SDimitry Andric   if (!BM)
85460b57cec5SDimitry Andric     return BM.takeError();
85470b57cec5SDimitry Andric 
8548bdd1243dSDimitry Andric   return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting,
8549bdd1243dSDimitry Andric                            Callbacks);
85500b57cec5SDimitry Andric }
85510b57cec5SDimitry Andric 
85520b57cec5SDimitry Andric Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule(
85530b57cec5SDimitry Andric     std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
8554bdd1243dSDimitry Andric     bool ShouldLazyLoadMetadata, bool IsImporting, ParserCallbacks Callbacks) {
85550b57cec5SDimitry Andric   auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata,
8556bdd1243dSDimitry Andric                                      IsImporting, Callbacks);
85570b57cec5SDimitry Andric   if (MOrErr)
85580b57cec5SDimitry Andric     (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
85590b57cec5SDimitry Andric   return MOrErr;
85600b57cec5SDimitry Andric }
85610b57cec5SDimitry Andric 
85620b57cec5SDimitry Andric Expected<std::unique_ptr<Module>>
8563bdd1243dSDimitry Andric BitcodeModule::parseModule(LLVMContext &Context, ParserCallbacks Callbacks) {
8564bdd1243dSDimitry Andric   return getModuleImpl(Context, true, false, false, Callbacks);
85650b57cec5SDimitry Andric   // TODO: Restore the use-lists to the in-memory state when the bitcode was
85660b57cec5SDimitry Andric   // written.  We must defer until the Module has been fully materialized.
85670b57cec5SDimitry Andric }
85680b57cec5SDimitry Andric 
85695ffd83dbSDimitry Andric Expected<std::unique_ptr<Module>>
85705ffd83dbSDimitry Andric llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
8571bdd1243dSDimitry Andric                        ParserCallbacks Callbacks) {
85720b57cec5SDimitry Andric   Expected<BitcodeModule> BM = getSingleModule(Buffer);
85730b57cec5SDimitry Andric   if (!BM)
85740b57cec5SDimitry Andric     return BM.takeError();
85750b57cec5SDimitry Andric 
8576bdd1243dSDimitry Andric   return BM->parseModule(Context, Callbacks);
85770b57cec5SDimitry Andric }
85780b57cec5SDimitry Andric 
85790b57cec5SDimitry Andric Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) {
85800b57cec5SDimitry Andric   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
85810b57cec5SDimitry Andric   if (!StreamOrErr)
85820b57cec5SDimitry Andric     return StreamOrErr.takeError();
85830b57cec5SDimitry Andric 
85840b57cec5SDimitry Andric   return readTriple(*StreamOrErr);
85850b57cec5SDimitry Andric }
85860b57cec5SDimitry Andric 
85870b57cec5SDimitry Andric Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) {
85880b57cec5SDimitry Andric   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
85890b57cec5SDimitry Andric   if (!StreamOrErr)
85900b57cec5SDimitry Andric     return StreamOrErr.takeError();
85910b57cec5SDimitry Andric 
85920b57cec5SDimitry Andric   return hasObjCCategory(*StreamOrErr);
85930b57cec5SDimitry Andric }
85940b57cec5SDimitry Andric 
85950b57cec5SDimitry Andric Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) {
85960b57cec5SDimitry Andric   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
85970b57cec5SDimitry Andric   if (!StreamOrErr)
85980b57cec5SDimitry Andric     return StreamOrErr.takeError();
85990b57cec5SDimitry Andric 
86000b57cec5SDimitry Andric   return readIdentificationCode(*StreamOrErr);
86010b57cec5SDimitry Andric }
86020b57cec5SDimitry Andric 
86030b57cec5SDimitry Andric Error llvm::readModuleSummaryIndex(MemoryBufferRef Buffer,
86045f757f3fSDimitry Andric                                    ModuleSummaryIndex &CombinedIndex) {
86050b57cec5SDimitry Andric   Expected<BitcodeModule> BM = getSingleModule(Buffer);
86060b57cec5SDimitry Andric   if (!BM)
86070b57cec5SDimitry Andric     return BM.takeError();
86080b57cec5SDimitry Andric 
86095f757f3fSDimitry Andric   return BM->readSummary(CombinedIndex, BM->getModuleIdentifier());
86100b57cec5SDimitry Andric }
86110b57cec5SDimitry Andric 
86120b57cec5SDimitry Andric Expected<std::unique_ptr<ModuleSummaryIndex>>
86130b57cec5SDimitry Andric llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) {
86140b57cec5SDimitry Andric   Expected<BitcodeModule> BM = getSingleModule(Buffer);
86150b57cec5SDimitry Andric   if (!BM)
86160b57cec5SDimitry Andric     return BM.takeError();
86170b57cec5SDimitry Andric 
86180b57cec5SDimitry Andric   return BM->getSummary();
86190b57cec5SDimitry Andric }
86200b57cec5SDimitry Andric 
86210b57cec5SDimitry Andric Expected<BitcodeLTOInfo> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer) {
86220b57cec5SDimitry Andric   Expected<BitcodeModule> BM = getSingleModule(Buffer);
86230b57cec5SDimitry Andric   if (!BM)
86240b57cec5SDimitry Andric     return BM.takeError();
86250b57cec5SDimitry Andric 
86260b57cec5SDimitry Andric   return BM->getLTOInfo();
86270b57cec5SDimitry Andric }
86280b57cec5SDimitry Andric 
86290b57cec5SDimitry Andric Expected<std::unique_ptr<ModuleSummaryIndex>>
86300b57cec5SDimitry Andric llvm::getModuleSummaryIndexForFile(StringRef Path,
86310b57cec5SDimitry Andric                                    bool IgnoreEmptyThinLTOIndexFile) {
86320b57cec5SDimitry Andric   ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
86330b57cec5SDimitry Andric       MemoryBuffer::getFileOrSTDIN(Path);
86340b57cec5SDimitry Andric   if (!FileOrErr)
86350b57cec5SDimitry Andric     return errorCodeToError(FileOrErr.getError());
86360b57cec5SDimitry Andric   if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize())
86370b57cec5SDimitry Andric     return nullptr;
86380b57cec5SDimitry Andric   return getModuleSummaryIndex(**FileOrErr);
86390b57cec5SDimitry Andric }
8640