Path: blob/main/contrib/llvm-project/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
35291 views
//===- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// Bitcode writer implementation.9//10//===----------------------------------------------------------------------===//1112#include "llvm/Bitcode/BitcodeWriter.h"13#include "ValueEnumerator.h"14#include "llvm/ADT/APFloat.h"15#include "llvm/ADT/APInt.h"16#include "llvm/ADT/ArrayRef.h"17#include "llvm/ADT/DenseMap.h"18#include "llvm/ADT/STLExtras.h"19#include "llvm/ADT/SetVector.h"20#include "llvm/ADT/SmallPtrSet.h"21#include "llvm/ADT/SmallString.h"22#include "llvm/ADT/SmallVector.h"23#include "llvm/ADT/StringMap.h"24#include "llvm/ADT/StringRef.h"25#include "llvm/Bitcode/BitcodeCommon.h"26#include "llvm/Bitcode/BitcodeReader.h"27#include "llvm/Bitcode/LLVMBitCodes.h"28#include "llvm/Bitstream/BitCodes.h"29#include "llvm/Bitstream/BitstreamWriter.h"30#include "llvm/Config/llvm-config.h"31#include "llvm/IR/Attributes.h"32#include "llvm/IR/BasicBlock.h"33#include "llvm/IR/Comdat.h"34#include "llvm/IR/Constant.h"35#include "llvm/IR/ConstantRangeList.h"36#include "llvm/IR/Constants.h"37#include "llvm/IR/DebugInfoMetadata.h"38#include "llvm/IR/DebugLoc.h"39#include "llvm/IR/DerivedTypes.h"40#include "llvm/IR/Function.h"41#include "llvm/IR/GlobalAlias.h"42#include "llvm/IR/GlobalIFunc.h"43#include "llvm/IR/GlobalObject.h"44#include "llvm/IR/GlobalValue.h"45#include "llvm/IR/GlobalVariable.h"46#include "llvm/IR/InlineAsm.h"47#include "llvm/IR/InstrTypes.h"48#include "llvm/IR/Instruction.h"49#include "llvm/IR/Instructions.h"50#include "llvm/IR/LLVMContext.h"51#include "llvm/IR/Metadata.h"52#include "llvm/IR/Module.h"53#include "llvm/IR/ModuleSummaryIndex.h"54#include "llvm/IR/Operator.h"55#include "llvm/IR/Type.h"56#include "llvm/IR/UseListOrder.h"57#include "llvm/IR/Value.h"58#include "llvm/IR/ValueSymbolTable.h"59#include "llvm/MC/StringTableBuilder.h"60#include "llvm/MC/TargetRegistry.h"61#include "llvm/Object/IRSymtab.h"62#include "llvm/Support/AtomicOrdering.h"63#include "llvm/Support/Casting.h"64#include "llvm/Support/CommandLine.h"65#include "llvm/Support/Endian.h"66#include "llvm/Support/Error.h"67#include "llvm/Support/ErrorHandling.h"68#include "llvm/Support/MathExtras.h"69#include "llvm/Support/SHA1.h"70#include "llvm/Support/raw_ostream.h"71#include "llvm/TargetParser/Triple.h"72#include <algorithm>73#include <cassert>74#include <cstddef>75#include <cstdint>76#include <iterator>77#include <map>78#include <memory>79#include <optional>80#include <string>81#include <utility>82#include <vector>8384using namespace llvm;8586static cl::opt<unsigned>87IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25),88cl::desc("Number of metadatas above which we emit an index "89"to enable lazy-loading"));90static cl::opt<uint32_t> FlushThreshold(91"bitcode-flush-threshold", cl::Hidden, cl::init(512),92cl::desc("The threshold (unit M) for flushing LLVM bitcode."));9394static cl::opt<bool> WriteRelBFToSummary(95"write-relbf-to-summary", cl::Hidden, cl::init(false),96cl::desc("Write relative block frequency to function summary "));9798namespace llvm {99extern FunctionSummary::ForceSummaryHotnessType ForceSummaryEdgesCold;100}101102extern bool WriteNewDbgInfoFormatToBitcode;103extern llvm::cl::opt<bool> UseNewDbgInfoFormat;104105namespace {106107/// These are manifest constants used by the bitcode writer. They do not need to108/// be kept in sync with the reader, but need to be consistent within this file.109enum {110// VALUE_SYMTAB_BLOCK abbrev id's.111VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,112VST_ENTRY_7_ABBREV,113VST_ENTRY_6_ABBREV,114VST_BBENTRY_6_ABBREV,115116// CONSTANTS_BLOCK abbrev id's.117CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,118CONSTANTS_INTEGER_ABBREV,119CONSTANTS_CE_CAST_Abbrev,120CONSTANTS_NULL_Abbrev,121122// FUNCTION_BLOCK abbrev id's.123FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,124FUNCTION_INST_UNOP_ABBREV,125FUNCTION_INST_UNOP_FLAGS_ABBREV,126FUNCTION_INST_BINOP_ABBREV,127FUNCTION_INST_BINOP_FLAGS_ABBREV,128FUNCTION_INST_CAST_ABBREV,129FUNCTION_INST_CAST_FLAGS_ABBREV,130FUNCTION_INST_RET_VOID_ABBREV,131FUNCTION_INST_RET_VAL_ABBREV,132FUNCTION_INST_UNREACHABLE_ABBREV,133FUNCTION_INST_GEP_ABBREV,134FUNCTION_DEBUG_RECORD_VALUE_ABBREV,135};136137/// Abstract class to manage the bitcode writing, subclassed for each bitcode138/// file type.139class BitcodeWriterBase {140protected:141/// The stream created and owned by the client.142BitstreamWriter &Stream;143144StringTableBuilder &StrtabBuilder;145146public:147/// Constructs a BitcodeWriterBase object that writes to the provided148/// \p Stream.149BitcodeWriterBase(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder)150: Stream(Stream), StrtabBuilder(StrtabBuilder) {}151152protected:153void writeModuleVersion();154};155156void BitcodeWriterBase::writeModuleVersion() {157// VERSION: [version#]158Stream.EmitRecord(bitc::MODULE_CODE_VERSION, ArrayRef<uint64_t>{2});159}160161/// Base class to manage the module bitcode writing, currently subclassed for162/// ModuleBitcodeWriter and ThinLinkBitcodeWriter.163class ModuleBitcodeWriterBase : public BitcodeWriterBase {164protected:165/// The Module to write to bitcode.166const Module &M;167168/// Enumerates ids for all values in the module.169ValueEnumerator VE;170171/// Optional per-module index to write for ThinLTO.172const ModuleSummaryIndex *Index;173174/// Map that holds the correspondence between GUIDs in the summary index,175/// that came from indirect call profiles, and a value id generated by this176/// class to use in the VST and summary block records.177std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;178179/// Tracks the last value id recorded in the GUIDToValueMap.180unsigned GlobalValueId;181182/// Saves the offset of the VSTOffset record that must eventually be183/// backpatched with the offset of the actual VST.184uint64_t VSTOffsetPlaceholder = 0;185186public:187/// Constructs a ModuleBitcodeWriterBase object for the given Module,188/// writing to the provided \p Buffer.189ModuleBitcodeWriterBase(const Module &M, StringTableBuilder &StrtabBuilder,190BitstreamWriter &Stream,191bool ShouldPreserveUseListOrder,192const ModuleSummaryIndex *Index)193: BitcodeWriterBase(Stream, StrtabBuilder), M(M),194VE(M, ShouldPreserveUseListOrder), Index(Index) {195// Assign ValueIds to any callee values in the index that came from196// indirect call profiles and were recorded as a GUID not a Value*197// (which would have been assigned an ID by the ValueEnumerator).198// The starting ValueId is just after the number of values in the199// ValueEnumerator, so that they can be emitted in the VST.200GlobalValueId = VE.getValues().size();201if (!Index)202return;203for (const auto &GUIDSummaryLists : *Index)204// Examine all summaries for this GUID.205for (auto &Summary : GUIDSummaryLists.second.SummaryList)206if (auto FS = dyn_cast<FunctionSummary>(Summary.get())) {207// For each call in the function summary, see if the call208// is to a GUID (which means it is for an indirect call,209// otherwise we would have a Value for it). If so, synthesize210// a value id.211for (auto &CallEdge : FS->calls())212if (!CallEdge.first.haveGVs() || !CallEdge.first.getValue())213assignValueId(CallEdge.first.getGUID());214215// For each referenced variables in the function summary, see if the216// variable is represented by a GUID (as opposed to a symbol to217// declarations or definitions in the module). If so, synthesize a218// value id.219for (auto &RefEdge : FS->refs())220if (!RefEdge.haveGVs() || !RefEdge.getValue())221assignValueId(RefEdge.getGUID());222}223}224225protected:226void writePerModuleGlobalValueSummary();227228private:229void writePerModuleFunctionSummaryRecord(230SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,231unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,232unsigned CallsiteAbbrev, unsigned AllocAbbrev, const Function &F);233void writeModuleLevelReferences(const GlobalVariable &V,234SmallVector<uint64_t, 64> &NameVals,235unsigned FSModRefsAbbrev,236unsigned FSModVTableRefsAbbrev);237238void assignValueId(GlobalValue::GUID ValGUID) {239GUIDToValueIdMap[ValGUID] = ++GlobalValueId;240}241242unsigned getValueId(GlobalValue::GUID ValGUID) {243const auto &VMI = GUIDToValueIdMap.find(ValGUID);244// Expect that any GUID value had a value Id assigned by an245// earlier call to assignValueId.246assert(VMI != GUIDToValueIdMap.end() &&247"GUID does not have assigned value Id");248return VMI->second;249}250251// Helper to get the valueId for the type of value recorded in VI.252unsigned getValueId(ValueInfo VI) {253if (!VI.haveGVs() || !VI.getValue())254return getValueId(VI.getGUID());255return VE.getValueID(VI.getValue());256}257258std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }259};260261/// Class to manage the bitcode writing for a module.262class ModuleBitcodeWriter : public ModuleBitcodeWriterBase {263/// True if a module hash record should be written.264bool GenerateHash;265266/// If non-null, when GenerateHash is true, the resulting hash is written267/// into ModHash.268ModuleHash *ModHash;269270SHA1 Hasher;271272/// The start bit of the identification block.273uint64_t BitcodeStartBit;274275public:276/// Constructs a ModuleBitcodeWriter object for the given Module,277/// writing to the provided \p Buffer.278ModuleBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder,279BitstreamWriter &Stream, bool ShouldPreserveUseListOrder,280const ModuleSummaryIndex *Index, bool GenerateHash,281ModuleHash *ModHash = nullptr)282: ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,283ShouldPreserveUseListOrder, Index),284GenerateHash(GenerateHash), ModHash(ModHash),285BitcodeStartBit(Stream.GetCurrentBitNo()) {}286287/// Emit the current module to the bitstream.288void write();289290private:291uint64_t bitcodeStartBit() { return BitcodeStartBit; }292293size_t addToStrtab(StringRef Str);294295void writeAttributeGroupTable();296void writeAttributeTable();297void writeTypeTable();298void writeComdats();299void writeValueSymbolTableForwardDecl();300void writeModuleInfo();301void writeValueAsMetadata(const ValueAsMetadata *MD,302SmallVectorImpl<uint64_t> &Record);303void writeMDTuple(const MDTuple *N, SmallVectorImpl<uint64_t> &Record,304unsigned Abbrev);305unsigned createDILocationAbbrev();306void writeDILocation(const DILocation *N, SmallVectorImpl<uint64_t> &Record,307unsigned &Abbrev);308unsigned createGenericDINodeAbbrev();309void writeGenericDINode(const GenericDINode *N,310SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev);311void writeDISubrange(const DISubrange *N, SmallVectorImpl<uint64_t> &Record,312unsigned Abbrev);313void writeDIGenericSubrange(const DIGenericSubrange *N,314SmallVectorImpl<uint64_t> &Record,315unsigned Abbrev);316void writeDIEnumerator(const DIEnumerator *N,317SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);318void writeDIBasicType(const DIBasicType *N, SmallVectorImpl<uint64_t> &Record,319unsigned Abbrev);320void writeDIStringType(const DIStringType *N,321SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);322void writeDIDerivedType(const DIDerivedType *N,323SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);324void writeDICompositeType(const DICompositeType *N,325SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);326void writeDISubroutineType(const DISubroutineType *N,327SmallVectorImpl<uint64_t> &Record,328unsigned Abbrev);329void writeDIFile(const DIFile *N, SmallVectorImpl<uint64_t> &Record,330unsigned Abbrev);331void writeDICompileUnit(const DICompileUnit *N,332SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);333void writeDISubprogram(const DISubprogram *N,334SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);335void writeDILexicalBlock(const DILexicalBlock *N,336SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);337void writeDILexicalBlockFile(const DILexicalBlockFile *N,338SmallVectorImpl<uint64_t> &Record,339unsigned Abbrev);340void writeDICommonBlock(const DICommonBlock *N,341SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);342void writeDINamespace(const DINamespace *N, SmallVectorImpl<uint64_t> &Record,343unsigned Abbrev);344void writeDIMacro(const DIMacro *N, SmallVectorImpl<uint64_t> &Record,345unsigned Abbrev);346void writeDIMacroFile(const DIMacroFile *N, SmallVectorImpl<uint64_t> &Record,347unsigned Abbrev);348void writeDIArgList(const DIArgList *N, SmallVectorImpl<uint64_t> &Record);349void writeDIModule(const DIModule *N, SmallVectorImpl<uint64_t> &Record,350unsigned Abbrev);351void writeDIAssignID(const DIAssignID *N, SmallVectorImpl<uint64_t> &Record,352unsigned Abbrev);353void writeDITemplateTypeParameter(const DITemplateTypeParameter *N,354SmallVectorImpl<uint64_t> &Record,355unsigned Abbrev);356void writeDITemplateValueParameter(const DITemplateValueParameter *N,357SmallVectorImpl<uint64_t> &Record,358unsigned Abbrev);359void writeDIGlobalVariable(const DIGlobalVariable *N,360SmallVectorImpl<uint64_t> &Record,361unsigned Abbrev);362void writeDILocalVariable(const DILocalVariable *N,363SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);364void writeDILabel(const DILabel *N,365SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);366void writeDIExpression(const DIExpression *N,367SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);368void writeDIGlobalVariableExpression(const DIGlobalVariableExpression *N,369SmallVectorImpl<uint64_t> &Record,370unsigned Abbrev);371void writeDIObjCProperty(const DIObjCProperty *N,372SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);373void writeDIImportedEntity(const DIImportedEntity *N,374SmallVectorImpl<uint64_t> &Record,375unsigned Abbrev);376unsigned createNamedMetadataAbbrev();377void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);378unsigned createMetadataStringsAbbrev();379void writeMetadataStrings(ArrayRef<const Metadata *> Strings,380SmallVectorImpl<uint64_t> &Record);381void writeMetadataRecords(ArrayRef<const Metadata *> MDs,382SmallVectorImpl<uint64_t> &Record,383std::vector<unsigned> *MDAbbrevs = nullptr,384std::vector<uint64_t> *IndexPos = nullptr);385void writeModuleMetadata();386void writeFunctionMetadata(const Function &F);387void writeFunctionMetadataAttachment(const Function &F);388void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,389const GlobalObject &GO);390void writeModuleMetadataKinds();391void writeOperandBundleTags();392void writeSyncScopeNames();393void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal);394void writeModuleConstants();395bool pushValueAndType(const Value *V, unsigned InstID,396SmallVectorImpl<unsigned> &Vals);397void writeOperandBundles(const CallBase &CB, unsigned InstID);398void pushValue(const Value *V, unsigned InstID,399SmallVectorImpl<unsigned> &Vals);400void pushValueSigned(const Value *V, unsigned InstID,401SmallVectorImpl<uint64_t> &Vals);402void writeInstruction(const Instruction &I, unsigned InstID,403SmallVectorImpl<unsigned> &Vals);404void writeFunctionLevelValueSymbolTable(const ValueSymbolTable &VST);405void writeGlobalValueSymbolTable(406DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);407void writeUseList(UseListOrder &&Order);408void writeUseListBlock(const Function *F);409void410writeFunction(const Function &F,411DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);412void writeBlockInfo();413void writeModuleHash(StringRef View);414415unsigned getEncodedSyncScopeID(SyncScope::ID SSID) {416return unsigned(SSID);417}418419unsigned getEncodedAlign(MaybeAlign Alignment) { return encode(Alignment); }420};421422/// Class to manage the bitcode writing for a combined index.423class IndexBitcodeWriter : public BitcodeWriterBase {424/// The combined index to write to bitcode.425const ModuleSummaryIndex &Index;426427/// When writing combined summaries, provides the set of global value428/// summaries for which the value (function, function alias, etc) should be429/// imported as a declaration.430const GVSummaryPtrSet *DecSummaries = nullptr;431432/// When writing a subset of the index for distributed backends, client433/// provides a map of modules to the corresponding GUIDs/summaries to write.434const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex;435436/// Map that holds the correspondence between the GUID used in the combined437/// index and a value id generated by this class to use in references.438std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;439440// The stack ids used by this index, which will be a subset of those in441// the full index in the case of distributed indexes.442std::vector<uint64_t> StackIds;443444// Keep a map of the stack id indices used by records being written for this445// index to the index of the corresponding stack id in the above StackIds446// vector. Ensures we write each referenced stack id once.447DenseMap<unsigned, unsigned> StackIdIndicesToIndex;448449/// Tracks the last value id recorded in the GUIDToValueMap.450unsigned GlobalValueId = 0;451452/// Tracks the assignment of module paths in the module path string table to453/// an id assigned for use in summary references to the module path.454DenseMap<StringRef, uint64_t> ModuleIdMap;455456public:457/// Constructs a IndexBitcodeWriter object for the given combined index,458/// writing to the provided \p Buffer. When writing a subset of the index459/// for a distributed backend, provide a \p ModuleToSummariesForIndex map.460/// If provided, \p DecSummaries specifies the set of summaries for which461/// the corresponding functions or aliased functions should be imported as a462/// declaration (but not definition) for each module.463IndexBitcodeWriter(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder,464const ModuleSummaryIndex &Index,465const GVSummaryPtrSet *DecSummaries = nullptr,466const std::map<std::string, GVSummaryMapTy>467*ModuleToSummariesForIndex = nullptr)468: BitcodeWriterBase(Stream, StrtabBuilder), Index(Index),469DecSummaries(DecSummaries),470ModuleToSummariesForIndex(ModuleToSummariesForIndex) {471472// See if the StackIdIndex was already added to the StackId map and473// vector. If not, record it.474auto RecordStackIdReference = [&](unsigned StackIdIndex) {475// If the StackIdIndex is not yet in the map, the below insert ensures476// that it will point to the new StackIds vector entry we push to just477// below.478auto Inserted =479StackIdIndicesToIndex.insert({StackIdIndex, StackIds.size()});480if (Inserted.second)481StackIds.push_back(Index.getStackIdAtIndex(StackIdIndex));482};483484// Assign unique value ids to all summaries to be written, for use485// in writing out the call graph edges. Save the mapping from GUID486// to the new global value id to use when writing those edges, which487// are currently saved in the index in terms of GUID.488forEachSummary([&](GVInfo I, bool IsAliasee) {489GUIDToValueIdMap[I.first] = ++GlobalValueId;490if (IsAliasee)491return;492auto *FS = dyn_cast<FunctionSummary>(I.second);493if (!FS)494return;495// Record all stack id indices actually used in the summary entries being496// written, so that we can compact them in the case of distributed ThinLTO497// indexes.498for (auto &CI : FS->callsites()) {499// If the stack id list is empty, this callsite info was synthesized for500// a missing tail call frame. Ensure that the callee's GUID gets a value501// id. Normally we only generate these for defined summaries, which in502// the case of distributed ThinLTO is only the functions already defined503// in the module or that we want to import. We don't bother to include504// all the callee symbols as they aren't normally needed in the backend.505// However, for the synthesized callsite infos we do need the callee506// GUID in the backend so that we can correlate the identified callee507// with this callsite info (which for non-tail calls is done by the508// ordering of the callsite infos and verified via stack ids).509if (CI.StackIdIndices.empty()) {510GUIDToValueIdMap[CI.Callee.getGUID()] = ++GlobalValueId;511continue;512}513for (auto Idx : CI.StackIdIndices)514RecordStackIdReference(Idx);515}516for (auto &AI : FS->allocs())517for (auto &MIB : AI.MIBs)518for (auto Idx : MIB.StackIdIndices)519RecordStackIdReference(Idx);520});521}522523/// The below iterator returns the GUID and associated summary.524using GVInfo = std::pair<GlobalValue::GUID, GlobalValueSummary *>;525526/// Calls the callback for each value GUID and summary to be written to527/// bitcode. This hides the details of whether they are being pulled from the528/// entire index or just those in a provided ModuleToSummariesForIndex map.529template<typename Functor>530void forEachSummary(Functor Callback) {531if (ModuleToSummariesForIndex) {532for (auto &M : *ModuleToSummariesForIndex)533for (auto &Summary : M.second) {534Callback(Summary, false);535// Ensure aliasee is handled, e.g. for assigning a valueId,536// even if we are not importing the aliasee directly (the537// imported alias will contain a copy of aliasee).538if (auto *AS = dyn_cast<AliasSummary>(Summary.getSecond()))539Callback({AS->getAliaseeGUID(), &AS->getAliasee()}, true);540}541} else {542for (auto &Summaries : Index)543for (auto &Summary : Summaries.second.SummaryList)544Callback({Summaries.first, Summary.get()}, false);545}546}547548/// Calls the callback for each entry in the modulePaths StringMap that549/// should be written to the module path string table. This hides the details550/// of whether they are being pulled from the entire index or just those in a551/// provided ModuleToSummariesForIndex map.552template <typename Functor> void forEachModule(Functor Callback) {553if (ModuleToSummariesForIndex) {554for (const auto &M : *ModuleToSummariesForIndex) {555const auto &MPI = Index.modulePaths().find(M.first);556if (MPI == Index.modulePaths().end()) {557// This should only happen if the bitcode file was empty, in which558// case we shouldn't be importing (the ModuleToSummariesForIndex559// would only include the module we are writing and index for).560assert(ModuleToSummariesForIndex->size() == 1);561continue;562}563Callback(*MPI);564}565} else {566// Since StringMap iteration order isn't guaranteed, order by path string567// first.568// FIXME: Make this a vector of StringMapEntry instead to avoid the later569// map lookup.570std::vector<StringRef> ModulePaths;571for (auto &[ModPath, _] : Index.modulePaths())572ModulePaths.push_back(ModPath);573llvm::sort(ModulePaths.begin(), ModulePaths.end());574for (auto &ModPath : ModulePaths)575Callback(*Index.modulePaths().find(ModPath));576}577}578579/// Main entry point for writing a combined index to bitcode.580void write();581582private:583void writeModStrings();584void writeCombinedGlobalValueSummary();585586std::optional<unsigned> getValueId(GlobalValue::GUID ValGUID) {587auto VMI = GUIDToValueIdMap.find(ValGUID);588if (VMI == GUIDToValueIdMap.end())589return std::nullopt;590return VMI->second;591}592593std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }594};595596} // end anonymous namespace597598static unsigned getEncodedCastOpcode(unsigned Opcode) {599switch (Opcode) {600default: llvm_unreachable("Unknown cast instruction!");601case Instruction::Trunc : return bitc::CAST_TRUNC;602case Instruction::ZExt : return bitc::CAST_ZEXT;603case Instruction::SExt : return bitc::CAST_SEXT;604case Instruction::FPToUI : return bitc::CAST_FPTOUI;605case Instruction::FPToSI : return bitc::CAST_FPTOSI;606case Instruction::UIToFP : return bitc::CAST_UITOFP;607case Instruction::SIToFP : return bitc::CAST_SITOFP;608case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;609case Instruction::FPExt : return bitc::CAST_FPEXT;610case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;611case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;612case Instruction::BitCast : return bitc::CAST_BITCAST;613case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;614}615}616617static unsigned getEncodedUnaryOpcode(unsigned Opcode) {618switch (Opcode) {619default: llvm_unreachable("Unknown binary instruction!");620case Instruction::FNeg: return bitc::UNOP_FNEG;621}622}623624static unsigned getEncodedBinaryOpcode(unsigned Opcode) {625switch (Opcode) {626default: llvm_unreachable("Unknown binary instruction!");627case Instruction::Add:628case Instruction::FAdd: return bitc::BINOP_ADD;629case Instruction::Sub:630case Instruction::FSub: return bitc::BINOP_SUB;631case Instruction::Mul:632case Instruction::FMul: return bitc::BINOP_MUL;633case Instruction::UDiv: return bitc::BINOP_UDIV;634case Instruction::FDiv:635case Instruction::SDiv: return bitc::BINOP_SDIV;636case Instruction::URem: return bitc::BINOP_UREM;637case Instruction::FRem:638case Instruction::SRem: return bitc::BINOP_SREM;639case Instruction::Shl: return bitc::BINOP_SHL;640case Instruction::LShr: return bitc::BINOP_LSHR;641case Instruction::AShr: return bitc::BINOP_ASHR;642case Instruction::And: return bitc::BINOP_AND;643case Instruction::Or: return bitc::BINOP_OR;644case Instruction::Xor: return bitc::BINOP_XOR;645}646}647648static unsigned getEncodedRMWOperation(AtomicRMWInst::BinOp Op) {649switch (Op) {650default: llvm_unreachable("Unknown RMW operation!");651case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;652case AtomicRMWInst::Add: return bitc::RMW_ADD;653case AtomicRMWInst::Sub: return bitc::RMW_SUB;654case AtomicRMWInst::And: return bitc::RMW_AND;655case AtomicRMWInst::Nand: return bitc::RMW_NAND;656case AtomicRMWInst::Or: return bitc::RMW_OR;657case AtomicRMWInst::Xor: return bitc::RMW_XOR;658case AtomicRMWInst::Max: return bitc::RMW_MAX;659case AtomicRMWInst::Min: return bitc::RMW_MIN;660case AtomicRMWInst::UMax: return bitc::RMW_UMAX;661case AtomicRMWInst::UMin: return bitc::RMW_UMIN;662case AtomicRMWInst::FAdd: return bitc::RMW_FADD;663case AtomicRMWInst::FSub: return bitc::RMW_FSUB;664case AtomicRMWInst::FMax: return bitc::RMW_FMAX;665case AtomicRMWInst::FMin: return bitc::RMW_FMIN;666case AtomicRMWInst::UIncWrap:667return bitc::RMW_UINC_WRAP;668case AtomicRMWInst::UDecWrap:669return bitc::RMW_UDEC_WRAP;670}671}672673static unsigned getEncodedOrdering(AtomicOrdering Ordering) {674switch (Ordering) {675case AtomicOrdering::NotAtomic: return bitc::ORDERING_NOTATOMIC;676case AtomicOrdering::Unordered: return bitc::ORDERING_UNORDERED;677case AtomicOrdering::Monotonic: return bitc::ORDERING_MONOTONIC;678case AtomicOrdering::Acquire: return bitc::ORDERING_ACQUIRE;679case AtomicOrdering::Release: return bitc::ORDERING_RELEASE;680case AtomicOrdering::AcquireRelease: return bitc::ORDERING_ACQREL;681case AtomicOrdering::SequentiallyConsistent: return bitc::ORDERING_SEQCST;682}683llvm_unreachable("Invalid ordering");684}685686static void writeStringRecord(BitstreamWriter &Stream, unsigned Code,687StringRef Str, unsigned AbbrevToUse) {688SmallVector<unsigned, 64> Vals;689690// Code: [strchar x N]691for (char C : Str) {692if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(C))693AbbrevToUse = 0;694Vals.push_back(C);695}696697// Emit the finished record.698Stream.EmitRecord(Code, Vals, AbbrevToUse);699}700701static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {702switch (Kind) {703case Attribute::Alignment:704return bitc::ATTR_KIND_ALIGNMENT;705case Attribute::AllocAlign:706return bitc::ATTR_KIND_ALLOC_ALIGN;707case Attribute::AllocSize:708return bitc::ATTR_KIND_ALLOC_SIZE;709case Attribute::AlwaysInline:710return bitc::ATTR_KIND_ALWAYS_INLINE;711case Attribute::Builtin:712return bitc::ATTR_KIND_BUILTIN;713case Attribute::ByVal:714return bitc::ATTR_KIND_BY_VAL;715case Attribute::Convergent:716return bitc::ATTR_KIND_CONVERGENT;717case Attribute::InAlloca:718return bitc::ATTR_KIND_IN_ALLOCA;719case Attribute::Cold:720return bitc::ATTR_KIND_COLD;721case Attribute::DisableSanitizerInstrumentation:722return bitc::ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION;723case Attribute::FnRetThunkExtern:724return bitc::ATTR_KIND_FNRETTHUNK_EXTERN;725case Attribute::Hot:726return bitc::ATTR_KIND_HOT;727case Attribute::ElementType:728return bitc::ATTR_KIND_ELEMENTTYPE;729case Attribute::HybridPatchable:730return bitc::ATTR_KIND_HYBRID_PATCHABLE;731case Attribute::InlineHint:732return bitc::ATTR_KIND_INLINE_HINT;733case Attribute::InReg:734return bitc::ATTR_KIND_IN_REG;735case Attribute::JumpTable:736return bitc::ATTR_KIND_JUMP_TABLE;737case Attribute::MinSize:738return bitc::ATTR_KIND_MIN_SIZE;739case Attribute::AllocatedPointer:740return bitc::ATTR_KIND_ALLOCATED_POINTER;741case Attribute::AllocKind:742return bitc::ATTR_KIND_ALLOC_KIND;743case Attribute::Memory:744return bitc::ATTR_KIND_MEMORY;745case Attribute::NoFPClass:746return bitc::ATTR_KIND_NOFPCLASS;747case Attribute::Naked:748return bitc::ATTR_KIND_NAKED;749case Attribute::Nest:750return bitc::ATTR_KIND_NEST;751case Attribute::NoAlias:752return bitc::ATTR_KIND_NO_ALIAS;753case Attribute::NoBuiltin:754return bitc::ATTR_KIND_NO_BUILTIN;755case Attribute::NoCallback:756return bitc::ATTR_KIND_NO_CALLBACK;757case Attribute::NoCapture:758return bitc::ATTR_KIND_NO_CAPTURE;759case Attribute::NoDuplicate:760return bitc::ATTR_KIND_NO_DUPLICATE;761case Attribute::NoFree:762return bitc::ATTR_KIND_NOFREE;763case Attribute::NoImplicitFloat:764return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;765case Attribute::NoInline:766return bitc::ATTR_KIND_NO_INLINE;767case Attribute::NoRecurse:768return bitc::ATTR_KIND_NO_RECURSE;769case Attribute::NoMerge:770return bitc::ATTR_KIND_NO_MERGE;771case Attribute::NonLazyBind:772return bitc::ATTR_KIND_NON_LAZY_BIND;773case Attribute::NonNull:774return bitc::ATTR_KIND_NON_NULL;775case Attribute::Dereferenceable:776return bitc::ATTR_KIND_DEREFERENCEABLE;777case Attribute::DereferenceableOrNull:778return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL;779case Attribute::NoRedZone:780return bitc::ATTR_KIND_NO_RED_ZONE;781case Attribute::NoReturn:782return bitc::ATTR_KIND_NO_RETURN;783case Attribute::NoSync:784return bitc::ATTR_KIND_NOSYNC;785case Attribute::NoCfCheck:786return bitc::ATTR_KIND_NOCF_CHECK;787case Attribute::NoProfile:788return bitc::ATTR_KIND_NO_PROFILE;789case Attribute::SkipProfile:790return bitc::ATTR_KIND_SKIP_PROFILE;791case Attribute::NoUnwind:792return bitc::ATTR_KIND_NO_UNWIND;793case Attribute::NoSanitizeBounds:794return bitc::ATTR_KIND_NO_SANITIZE_BOUNDS;795case Attribute::NoSanitizeCoverage:796return bitc::ATTR_KIND_NO_SANITIZE_COVERAGE;797case Attribute::NullPointerIsValid:798return bitc::ATTR_KIND_NULL_POINTER_IS_VALID;799case Attribute::OptimizeForDebugging:800return bitc::ATTR_KIND_OPTIMIZE_FOR_DEBUGGING;801case Attribute::OptForFuzzing:802return bitc::ATTR_KIND_OPT_FOR_FUZZING;803case Attribute::OptimizeForSize:804return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;805case Attribute::OptimizeNone:806return bitc::ATTR_KIND_OPTIMIZE_NONE;807case Attribute::ReadNone:808return bitc::ATTR_KIND_READ_NONE;809case Attribute::ReadOnly:810return bitc::ATTR_KIND_READ_ONLY;811case Attribute::Returned:812return bitc::ATTR_KIND_RETURNED;813case Attribute::ReturnsTwice:814return bitc::ATTR_KIND_RETURNS_TWICE;815case Attribute::SExt:816return bitc::ATTR_KIND_S_EXT;817case Attribute::Speculatable:818return bitc::ATTR_KIND_SPECULATABLE;819case Attribute::StackAlignment:820return bitc::ATTR_KIND_STACK_ALIGNMENT;821case Attribute::StackProtect:822return bitc::ATTR_KIND_STACK_PROTECT;823case Attribute::StackProtectReq:824return bitc::ATTR_KIND_STACK_PROTECT_REQ;825case Attribute::StackProtectStrong:826return bitc::ATTR_KIND_STACK_PROTECT_STRONG;827case Attribute::SafeStack:828return bitc::ATTR_KIND_SAFESTACK;829case Attribute::ShadowCallStack:830return bitc::ATTR_KIND_SHADOWCALLSTACK;831case Attribute::StrictFP:832return bitc::ATTR_KIND_STRICT_FP;833case Attribute::StructRet:834return bitc::ATTR_KIND_STRUCT_RET;835case Attribute::SanitizeAddress:836return bitc::ATTR_KIND_SANITIZE_ADDRESS;837case Attribute::SanitizeHWAddress:838return bitc::ATTR_KIND_SANITIZE_HWADDRESS;839case Attribute::SanitizeThread:840return bitc::ATTR_KIND_SANITIZE_THREAD;841case Attribute::SanitizeMemory:842return bitc::ATTR_KIND_SANITIZE_MEMORY;843case Attribute::SanitizeNumericalStability:844return bitc::ATTR_KIND_SANITIZE_NUMERICAL_STABILITY;845case Attribute::SpeculativeLoadHardening:846return bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING;847case Attribute::SwiftError:848return bitc::ATTR_KIND_SWIFT_ERROR;849case Attribute::SwiftSelf:850return bitc::ATTR_KIND_SWIFT_SELF;851case Attribute::SwiftAsync:852return bitc::ATTR_KIND_SWIFT_ASYNC;853case Attribute::UWTable:854return bitc::ATTR_KIND_UW_TABLE;855case Attribute::VScaleRange:856return bitc::ATTR_KIND_VSCALE_RANGE;857case Attribute::WillReturn:858return bitc::ATTR_KIND_WILLRETURN;859case Attribute::WriteOnly:860return bitc::ATTR_KIND_WRITEONLY;861case Attribute::ZExt:862return bitc::ATTR_KIND_Z_EXT;863case Attribute::ImmArg:864return bitc::ATTR_KIND_IMMARG;865case Attribute::SanitizeMemTag:866return bitc::ATTR_KIND_SANITIZE_MEMTAG;867case Attribute::Preallocated:868return bitc::ATTR_KIND_PREALLOCATED;869case Attribute::NoUndef:870return bitc::ATTR_KIND_NOUNDEF;871case Attribute::ByRef:872return bitc::ATTR_KIND_BYREF;873case Attribute::MustProgress:874return bitc::ATTR_KIND_MUSTPROGRESS;875case Attribute::PresplitCoroutine:876return bitc::ATTR_KIND_PRESPLIT_COROUTINE;877case Attribute::Writable:878return bitc::ATTR_KIND_WRITABLE;879case Attribute::CoroDestroyOnlyWhenComplete:880return bitc::ATTR_KIND_CORO_ONLY_DESTROY_WHEN_COMPLETE;881case Attribute::DeadOnUnwind:882return bitc::ATTR_KIND_DEAD_ON_UNWIND;883case Attribute::Range:884return bitc::ATTR_KIND_RANGE;885case Attribute::Initializes:886return bitc::ATTR_KIND_INITIALIZES;887case Attribute::EndAttrKinds:888llvm_unreachable("Can not encode end-attribute kinds marker.");889case Attribute::None:890llvm_unreachable("Can not encode none-attribute.");891case Attribute::EmptyKey:892case Attribute::TombstoneKey:893llvm_unreachable("Trying to encode EmptyKey/TombstoneKey");894}895896llvm_unreachable("Trying to encode unknown attribute");897}898899static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {900if ((int64_t)V >= 0)901Vals.push_back(V << 1);902else903Vals.push_back((-V << 1) | 1);904}905906static void emitWideAPInt(SmallVectorImpl<uint64_t> &Vals, const APInt &A) {907// We have an arbitrary precision integer value to write whose908// bit width is > 64. However, in canonical unsigned integer909// format it is likely that the high bits are going to be zero.910// So, we only write the number of active words.911unsigned NumWords = A.getActiveWords();912const uint64_t *RawData = A.getRawData();913for (unsigned i = 0; i < NumWords; i++)914emitSignedInt64(Vals, RawData[i]);915}916917static void emitConstantRange(SmallVectorImpl<uint64_t> &Record,918const ConstantRange &CR, bool EmitBitWidth) {919unsigned BitWidth = CR.getBitWidth();920if (EmitBitWidth)921Record.push_back(BitWidth);922if (BitWidth > 64) {923Record.push_back(CR.getLower().getActiveWords() |924(uint64_t(CR.getUpper().getActiveWords()) << 32));925emitWideAPInt(Record, CR.getLower());926emitWideAPInt(Record, CR.getUpper());927} else {928emitSignedInt64(Record, CR.getLower().getSExtValue());929emitSignedInt64(Record, CR.getUpper().getSExtValue());930}931}932933void ModuleBitcodeWriter::writeAttributeGroupTable() {934const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =935VE.getAttributeGroups();936if (AttrGrps.empty()) return;937938Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);939940SmallVector<uint64_t, 64> Record;941for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) {942unsigned AttrListIndex = Pair.first;943AttributeSet AS = Pair.second;944Record.push_back(VE.getAttributeGroupID(Pair));945Record.push_back(AttrListIndex);946947for (Attribute Attr : AS) {948if (Attr.isEnumAttribute()) {949Record.push_back(0);950Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));951} else if (Attr.isIntAttribute()) {952Record.push_back(1);953Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));954Record.push_back(Attr.getValueAsInt());955} else if (Attr.isStringAttribute()) {956StringRef Kind = Attr.getKindAsString();957StringRef Val = Attr.getValueAsString();958959Record.push_back(Val.empty() ? 3 : 4);960Record.append(Kind.begin(), Kind.end());961Record.push_back(0);962if (!Val.empty()) {963Record.append(Val.begin(), Val.end());964Record.push_back(0);965}966} else if (Attr.isTypeAttribute()) {967Type *Ty = Attr.getValueAsType();968Record.push_back(Ty ? 6 : 5);969Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));970if (Ty)971Record.push_back(VE.getTypeID(Attr.getValueAsType()));972} else if (Attr.isConstantRangeAttribute()) {973Record.push_back(7);974Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));975emitConstantRange(Record, Attr.getValueAsConstantRange(),976/*EmitBitWidth=*/true);977} else {978assert(Attr.isConstantRangeListAttribute());979Record.push_back(8);980Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));981ArrayRef<ConstantRange> Val = Attr.getValueAsConstantRangeList();982Record.push_back(Val.size());983Record.push_back(Val[0].getBitWidth());984for (auto &CR : Val)985emitConstantRange(Record, CR, /*EmitBitWidth=*/false);986}987}988989Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);990Record.clear();991}992993Stream.ExitBlock();994}995996void ModuleBitcodeWriter::writeAttributeTable() {997const std::vector<AttributeList> &Attrs = VE.getAttributeLists();998if (Attrs.empty()) return;9991000Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);10011002SmallVector<uint64_t, 64> Record;1003for (const AttributeList &AL : Attrs) {1004for (unsigned i : AL.indexes()) {1005AttributeSet AS = AL.getAttributes(i);1006if (AS.hasAttributes())1007Record.push_back(VE.getAttributeGroupID({i, AS}));1008}10091010Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);1011Record.clear();1012}10131014Stream.ExitBlock();1015}10161017/// WriteTypeTable - Write out the type table for a module.1018void ModuleBitcodeWriter::writeTypeTable() {1019const ValueEnumerator::TypeList &TypeList = VE.getTypes();10201021Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);1022SmallVector<uint64_t, 64> TypeVals;10231024uint64_t NumBits = VE.computeBitsRequiredForTypeIndices();10251026// Abbrev for TYPE_CODE_OPAQUE_POINTER.1027auto Abbv = std::make_shared<BitCodeAbbrev>();1028Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_OPAQUE_POINTER));1029Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 01030unsigned OpaquePtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));10311032// Abbrev for TYPE_CODE_FUNCTION.1033Abbv = std::make_shared<BitCodeAbbrev>();1034Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));1035Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg1036Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));1037Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));1038unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));10391040// Abbrev for TYPE_CODE_STRUCT_ANON.1041Abbv = std::make_shared<BitCodeAbbrev>();1042Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));1043Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked1044Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));1045Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));1046unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));10471048// Abbrev for TYPE_CODE_STRUCT_NAME.1049Abbv = std::make_shared<BitCodeAbbrev>();1050Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));1051Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));1052Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));1053unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));10541055// Abbrev for TYPE_CODE_STRUCT_NAMED.1056Abbv = std::make_shared<BitCodeAbbrev>();1057Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));1058Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked1059Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));1060Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));1061unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));10621063// Abbrev for TYPE_CODE_ARRAY.1064Abbv = std::make_shared<BitCodeAbbrev>();1065Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));1066Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size1067Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));1068unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));10691070// Emit an entry count so the reader can reserve space.1071TypeVals.push_back(TypeList.size());1072Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);1073TypeVals.clear();10741075// Loop over all of the types, emitting each in turn.1076for (Type *T : TypeList) {1077int AbbrevToUse = 0;1078unsigned Code = 0;10791080switch (T->getTypeID()) {1081case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;1082case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break;1083case Type::BFloatTyID: Code = bitc::TYPE_CODE_BFLOAT; break;1084case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;1085case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;1086case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;1087case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;1088case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;1089case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;1090case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;1091case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break;1092case Type::X86_AMXTyID: Code = bitc::TYPE_CODE_X86_AMX; break;1093case Type::TokenTyID: Code = bitc::TYPE_CODE_TOKEN; break;1094case Type::IntegerTyID:1095// INTEGER: [width]1096Code = bitc::TYPE_CODE_INTEGER;1097TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());1098break;1099case Type::PointerTyID: {1100PointerType *PTy = cast<PointerType>(T);1101unsigned AddressSpace = PTy->getAddressSpace();1102// OPAQUE_POINTER: [address space]1103Code = bitc::TYPE_CODE_OPAQUE_POINTER;1104TypeVals.push_back(AddressSpace);1105if (AddressSpace == 0)1106AbbrevToUse = OpaquePtrAbbrev;1107break;1108}1109case Type::FunctionTyID: {1110FunctionType *FT = cast<FunctionType>(T);1111// FUNCTION: [isvararg, retty, paramty x N]1112Code = bitc::TYPE_CODE_FUNCTION;1113TypeVals.push_back(FT->isVarArg());1114TypeVals.push_back(VE.getTypeID(FT->getReturnType()));1115for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)1116TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));1117AbbrevToUse = FunctionAbbrev;1118break;1119}1120case Type::StructTyID: {1121StructType *ST = cast<StructType>(T);1122// STRUCT: [ispacked, eltty x N]1123TypeVals.push_back(ST->isPacked());1124// Output all of the element types.1125for (Type *ET : ST->elements())1126TypeVals.push_back(VE.getTypeID(ET));11271128if (ST->isLiteral()) {1129Code = bitc::TYPE_CODE_STRUCT_ANON;1130AbbrevToUse = StructAnonAbbrev;1131} else {1132if (ST->isOpaque()) {1133Code = bitc::TYPE_CODE_OPAQUE;1134} else {1135Code = bitc::TYPE_CODE_STRUCT_NAMED;1136AbbrevToUse = StructNamedAbbrev;1137}11381139// Emit the name if it is present.1140if (!ST->getName().empty())1141writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),1142StructNameAbbrev);1143}1144break;1145}1146case Type::ArrayTyID: {1147ArrayType *AT = cast<ArrayType>(T);1148// ARRAY: [numelts, eltty]1149Code = bitc::TYPE_CODE_ARRAY;1150TypeVals.push_back(AT->getNumElements());1151TypeVals.push_back(VE.getTypeID(AT->getElementType()));1152AbbrevToUse = ArrayAbbrev;1153break;1154}1155case Type::FixedVectorTyID:1156case Type::ScalableVectorTyID: {1157VectorType *VT = cast<VectorType>(T);1158// VECTOR [numelts, eltty] or1159// [numelts, eltty, scalable]1160Code = bitc::TYPE_CODE_VECTOR;1161TypeVals.push_back(VT->getElementCount().getKnownMinValue());1162TypeVals.push_back(VE.getTypeID(VT->getElementType()));1163if (isa<ScalableVectorType>(VT))1164TypeVals.push_back(true);1165break;1166}1167case Type::TargetExtTyID: {1168TargetExtType *TET = cast<TargetExtType>(T);1169Code = bitc::TYPE_CODE_TARGET_TYPE;1170writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, TET->getName(),1171StructNameAbbrev);1172TypeVals.push_back(TET->getNumTypeParameters());1173for (Type *InnerTy : TET->type_params())1174TypeVals.push_back(VE.getTypeID(InnerTy));1175for (unsigned IntParam : TET->int_params())1176TypeVals.push_back(IntParam);1177break;1178}1179case Type::TypedPointerTyID:1180llvm_unreachable("Typed pointers cannot be added to IR modules");1181}11821183// Emit the finished record.1184Stream.EmitRecord(Code, TypeVals, AbbrevToUse);1185TypeVals.clear();1186}11871188Stream.ExitBlock();1189}11901191static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {1192switch (Linkage) {1193case GlobalValue::ExternalLinkage:1194return 0;1195case GlobalValue::WeakAnyLinkage:1196return 16;1197case GlobalValue::AppendingLinkage:1198return 2;1199case GlobalValue::InternalLinkage:1200return 3;1201case GlobalValue::LinkOnceAnyLinkage:1202return 18;1203case GlobalValue::ExternalWeakLinkage:1204return 7;1205case GlobalValue::CommonLinkage:1206return 8;1207case GlobalValue::PrivateLinkage:1208return 9;1209case GlobalValue::WeakODRLinkage:1210return 17;1211case GlobalValue::LinkOnceODRLinkage:1212return 19;1213case GlobalValue::AvailableExternallyLinkage:1214return 12;1215}1216llvm_unreachable("Invalid linkage");1217}12181219static unsigned getEncodedLinkage(const GlobalValue &GV) {1220return getEncodedLinkage(GV.getLinkage());1221}12221223static uint64_t getEncodedFFlags(FunctionSummary::FFlags Flags) {1224uint64_t RawFlags = 0;1225RawFlags |= Flags.ReadNone;1226RawFlags |= (Flags.ReadOnly << 1);1227RawFlags |= (Flags.NoRecurse << 2);1228RawFlags |= (Flags.ReturnDoesNotAlias << 3);1229RawFlags |= (Flags.NoInline << 4);1230RawFlags |= (Flags.AlwaysInline << 5);1231RawFlags |= (Flags.NoUnwind << 6);1232RawFlags |= (Flags.MayThrow << 7);1233RawFlags |= (Flags.HasUnknownCall << 8);1234RawFlags |= (Flags.MustBeUnreachable << 9);1235return RawFlags;1236}12371238// Decode the flags for GlobalValue in the summary. See getDecodedGVSummaryFlags1239// in BitcodeReader.cpp.1240static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags,1241bool ImportAsDecl = false) {1242uint64_t RawFlags = 0;12431244RawFlags |= Flags.NotEligibleToImport; // bool1245RawFlags |= (Flags.Live << 1);1246RawFlags |= (Flags.DSOLocal << 2);1247RawFlags |= (Flags.CanAutoHide << 3);12481249// Linkage don't need to be remapped at that time for the summary. Any future1250// change to the getEncodedLinkage() function will need to be taken into1251// account here as well.1252RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits12531254RawFlags |= (Flags.Visibility << 8); // 2 bits12551256unsigned ImportType = Flags.ImportType | ImportAsDecl;1257RawFlags |= (ImportType << 10); // 1 bit12581259return RawFlags;1260}12611262static uint64_t getEncodedGVarFlags(GlobalVarSummary::GVarFlags Flags) {1263uint64_t RawFlags = Flags.MaybeReadOnly | (Flags.MaybeWriteOnly << 1) |1264(Flags.Constant << 2) | Flags.VCallVisibility << 3;1265return RawFlags;1266}12671268static uint64_t getEncodedHotnessCallEdgeInfo(const CalleeInfo &CI) {1269uint64_t RawFlags = 0;12701271RawFlags |= CI.Hotness; // 3 bits1272RawFlags |= (CI.HasTailCall << 3); // 1 bit12731274return RawFlags;1275}12761277static uint64_t getEncodedRelBFCallEdgeInfo(const CalleeInfo &CI) {1278uint64_t RawFlags = 0;12791280RawFlags |= CI.RelBlockFreq; // CalleeInfo::RelBlockFreqBits bits1281RawFlags |= (CI.HasTailCall << CalleeInfo::RelBlockFreqBits); // 1 bit12821283return RawFlags;1284}12851286static unsigned getEncodedVisibility(const GlobalValue &GV) {1287switch (GV.getVisibility()) {1288case GlobalValue::DefaultVisibility: return 0;1289case GlobalValue::HiddenVisibility: return 1;1290case GlobalValue::ProtectedVisibility: return 2;1291}1292llvm_unreachable("Invalid visibility");1293}12941295static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {1296switch (GV.getDLLStorageClass()) {1297case GlobalValue::DefaultStorageClass: return 0;1298case GlobalValue::DLLImportStorageClass: return 1;1299case GlobalValue::DLLExportStorageClass: return 2;1300}1301llvm_unreachable("Invalid DLL storage class");1302}13031304static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {1305switch (GV.getThreadLocalMode()) {1306case GlobalVariable::NotThreadLocal: return 0;1307case GlobalVariable::GeneralDynamicTLSModel: return 1;1308case GlobalVariable::LocalDynamicTLSModel: return 2;1309case GlobalVariable::InitialExecTLSModel: return 3;1310case GlobalVariable::LocalExecTLSModel: return 4;1311}1312llvm_unreachable("Invalid TLS model");1313}13141315static unsigned getEncodedComdatSelectionKind(const Comdat &C) {1316switch (C.getSelectionKind()) {1317case Comdat::Any:1318return bitc::COMDAT_SELECTION_KIND_ANY;1319case Comdat::ExactMatch:1320return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;1321case Comdat::Largest:1322return bitc::COMDAT_SELECTION_KIND_LARGEST;1323case Comdat::NoDeduplicate:1324return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;1325case Comdat::SameSize:1326return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;1327}1328llvm_unreachable("Invalid selection kind");1329}13301331static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) {1332switch (GV.getUnnamedAddr()) {1333case GlobalValue::UnnamedAddr::None: return 0;1334case GlobalValue::UnnamedAddr::Local: return 2;1335case GlobalValue::UnnamedAddr::Global: return 1;1336}1337llvm_unreachable("Invalid unnamed_addr");1338}13391340size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) {1341if (GenerateHash)1342Hasher.update(Str);1343return StrtabBuilder.add(Str);1344}13451346void ModuleBitcodeWriter::writeComdats() {1347SmallVector<unsigned, 64> Vals;1348for (const Comdat *C : VE.getComdats()) {1349// COMDAT: [strtab offset, strtab size, selection_kind]1350Vals.push_back(addToStrtab(C->getName()));1351Vals.push_back(C->getName().size());1352Vals.push_back(getEncodedComdatSelectionKind(*C));1353Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);1354Vals.clear();1355}1356}13571358/// Write a record that will eventually hold the word offset of the1359/// module-level VST. For now the offset is 0, which will be backpatched1360/// after the real VST is written. Saves the bit offset to backpatch.1361void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {1362// Write a placeholder value in for the offset of the real VST,1363// which is written after the function blocks so that it can include1364// the offset of each function. The placeholder offset will be1365// updated when the real VST is written.1366auto Abbv = std::make_shared<BitCodeAbbrev>();1367Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET));1368// Blocks are 32-bit aligned, so we can use a 32-bit word offset to1369// hold the real VST offset. Must use fixed instead of VBR as we don't1370// know how many VBR chunks to reserve ahead of time.1371Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));1372unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));13731374// Emit the placeholder1375uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0};1376Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);13771378// Compute and save the bit offset to the placeholder, which will be1379// patched when the real VST is written. We can simply subtract the 32-bit1380// fixed size from the current bit number to get the location to backpatch.1381VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32;1382}13831384enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 };13851386/// Determine the encoding to use for the given string name and length.1387static StringEncoding getStringEncoding(StringRef Str) {1388bool isChar6 = true;1389for (char C : Str) {1390if (isChar6)1391isChar6 = BitCodeAbbrevOp::isChar6(C);1392if ((unsigned char)C & 128)1393// don't bother scanning the rest.1394return SE_Fixed8;1395}1396if (isChar6)1397return SE_Char6;1398return SE_Fixed7;1399}14001401static_assert(sizeof(GlobalValue::SanitizerMetadata) <= sizeof(unsigned),1402"Sanitizer Metadata is too large for naive serialization.");1403static unsigned1404serializeSanitizerMetadata(const GlobalValue::SanitizerMetadata &Meta) {1405return Meta.NoAddress | (Meta.NoHWAddress << 1) |1406(Meta.Memtag << 2) | (Meta.IsDynInit << 3);1407}14081409/// Emit top-level description of module, including target triple, inline asm,1410/// descriptors for global variables, and function prototype info.1411/// Returns the bit offset to backpatch with the location of the real VST.1412void ModuleBitcodeWriter::writeModuleInfo() {1413// Emit various pieces of data attached to a module.1414if (!M.getTargetTriple().empty())1415writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(),14160 /*TODO*/);1417const std::string &DL = M.getDataLayoutStr();1418if (!DL.empty())1419writeStringRecord(Stream, bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/);1420if (!M.getModuleInlineAsm().empty())1421writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(),14220 /*TODO*/);14231424// Emit information about sections and GC, computing how many there are. Also1425// compute the maximum alignment value.1426std::map<std::string, unsigned> SectionMap;1427std::map<std::string, unsigned> GCMap;1428MaybeAlign MaxAlignment;1429unsigned MaxGlobalType = 0;1430const auto UpdateMaxAlignment = [&MaxAlignment](const MaybeAlign A) {1431if (A)1432MaxAlignment = !MaxAlignment ? *A : std::max(*MaxAlignment, *A);1433};1434for (const GlobalVariable &GV : M.globals()) {1435UpdateMaxAlignment(GV.getAlign());1436MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));1437if (GV.hasSection()) {1438// Give section names unique ID's.1439unsigned &Entry = SectionMap[std::string(GV.getSection())];1440if (!Entry) {1441writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),14420 /*TODO*/);1443Entry = SectionMap.size();1444}1445}1446}1447for (const Function &F : M) {1448UpdateMaxAlignment(F.getAlign());1449if (F.hasSection()) {1450// Give section names unique ID's.1451unsigned &Entry = SectionMap[std::string(F.getSection())];1452if (!Entry) {1453writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, F.getSection(),14540 /*TODO*/);1455Entry = SectionMap.size();1456}1457}1458if (F.hasGC()) {1459// Same for GC names.1460unsigned &Entry = GCMap[F.getGC()];1461if (!Entry) {1462writeStringRecord(Stream, bitc::MODULE_CODE_GCNAME, F.getGC(),14630 /*TODO*/);1464Entry = GCMap.size();1465}1466}1467}14681469// Emit abbrev for globals, now that we know # sections and max alignment.1470unsigned SimpleGVarAbbrev = 0;1471if (!M.global_empty()) {1472// Add an abbrev for common globals with no visibility or thread localness.1473auto Abbv = std::make_shared<BitCodeAbbrev>();1474Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));1475Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));1476Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));1477Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,1478Log2_32_Ceil(MaxGlobalType+1)));1479Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 21480//| explicitType << 11481//| constant1482Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.1483Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.1484if (!MaxAlignment) // Alignment.1485Abbv->Add(BitCodeAbbrevOp(0));1486else {1487unsigned MaxEncAlignment = getEncodedAlign(MaxAlignment);1488Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,1489Log2_32_Ceil(MaxEncAlignment+1)));1490}1491if (SectionMap.empty()) // Section.1492Abbv->Add(BitCodeAbbrevOp(0));1493else1494Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,1495Log2_32_Ceil(SectionMap.size()+1)));1496// Don't bother emitting vis + thread local.1497SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv));1498}14991500SmallVector<unsigned, 64> Vals;1501// Emit the module's source file name.1502{1503StringEncoding Bits = getStringEncoding(M.getSourceFileName());1504BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);1505if (Bits == SE_Char6)1506AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);1507else if (Bits == SE_Fixed7)1508AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);15091510// MODULE_CODE_SOURCE_FILENAME: [namechar x N]1511auto Abbv = std::make_shared<BitCodeAbbrev>();1512Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));1513Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));1514Abbv->Add(AbbrevOpToUse);1515unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));15161517for (const auto P : M.getSourceFileName())1518Vals.push_back((unsigned char)P);15191520// Emit the finished record.1521Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);1522Vals.clear();1523}15241525// Emit the global variable information.1526for (const GlobalVariable &GV : M.globals()) {1527unsigned AbbrevToUse = 0;15281529// GLOBALVAR: [strtab offset, strtab size, type, isconst, initid,1530// linkage, alignment, section, visibility, threadlocal,1531// unnamed_addr, externally_initialized, dllstorageclass,1532// comdat, attributes, DSO_Local, GlobalSanitizer, code_model]1533Vals.push_back(addToStrtab(GV.getName()));1534Vals.push_back(GV.getName().size());1535Vals.push_back(VE.getTypeID(GV.getValueType()));1536Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());1537Vals.push_back(GV.isDeclaration() ? 0 :1538(VE.getValueID(GV.getInitializer()) + 1));1539Vals.push_back(getEncodedLinkage(GV));1540Vals.push_back(getEncodedAlign(GV.getAlign()));1541Vals.push_back(GV.hasSection() ? SectionMap[std::string(GV.getSection())]1542: 0);1543if (GV.isThreadLocal() ||1544GV.getVisibility() != GlobalValue::DefaultVisibility ||1545GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||1546GV.isExternallyInitialized() ||1547GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||1548GV.hasComdat() || GV.hasAttributes() || GV.isDSOLocal() ||1549GV.hasPartition() || GV.hasSanitizerMetadata() || GV.getCodeModel()) {1550Vals.push_back(getEncodedVisibility(GV));1551Vals.push_back(getEncodedThreadLocalMode(GV));1552Vals.push_back(getEncodedUnnamedAddr(GV));1553Vals.push_back(GV.isExternallyInitialized());1554Vals.push_back(getEncodedDLLStorageClass(GV));1555Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);15561557auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);1558Vals.push_back(VE.getAttributeListID(AL));15591560Vals.push_back(GV.isDSOLocal());1561Vals.push_back(addToStrtab(GV.getPartition()));1562Vals.push_back(GV.getPartition().size());15631564Vals.push_back((GV.hasSanitizerMetadata() ? serializeSanitizerMetadata(1565GV.getSanitizerMetadata())1566: 0));1567Vals.push_back(GV.getCodeModelRaw());1568} else {1569AbbrevToUse = SimpleGVarAbbrev;1570}15711572Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);1573Vals.clear();1574}15751576// Emit the function proto information.1577for (const Function &F : M) {1578// FUNCTION: [strtab offset, strtab size, type, callingconv, isproto,1579// linkage, paramattrs, alignment, section, visibility, gc,1580// unnamed_addr, prologuedata, dllstorageclass, comdat,1581// prefixdata, personalityfn, DSO_Local, addrspace]1582Vals.push_back(addToStrtab(F.getName()));1583Vals.push_back(F.getName().size());1584Vals.push_back(VE.getTypeID(F.getFunctionType()));1585Vals.push_back(F.getCallingConv());1586Vals.push_back(F.isDeclaration());1587Vals.push_back(getEncodedLinkage(F));1588Vals.push_back(VE.getAttributeListID(F.getAttributes()));1589Vals.push_back(getEncodedAlign(F.getAlign()));1590Vals.push_back(F.hasSection() ? SectionMap[std::string(F.getSection())]1591: 0);1592Vals.push_back(getEncodedVisibility(F));1593Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);1594Vals.push_back(getEncodedUnnamedAddr(F));1595Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)1596: 0);1597Vals.push_back(getEncodedDLLStorageClass(F));1598Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);1599Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)1600: 0);1601Vals.push_back(1602F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);16031604Vals.push_back(F.isDSOLocal());1605Vals.push_back(F.getAddressSpace());1606Vals.push_back(addToStrtab(F.getPartition()));1607Vals.push_back(F.getPartition().size());16081609unsigned AbbrevToUse = 0;1610Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);1611Vals.clear();1612}16131614// Emit the alias information.1615for (const GlobalAlias &A : M.aliases()) {1616// ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage,1617// visibility, dllstorageclass, threadlocal, unnamed_addr,1618// DSO_Local]1619Vals.push_back(addToStrtab(A.getName()));1620Vals.push_back(A.getName().size());1621Vals.push_back(VE.getTypeID(A.getValueType()));1622Vals.push_back(A.getType()->getAddressSpace());1623Vals.push_back(VE.getValueID(A.getAliasee()));1624Vals.push_back(getEncodedLinkage(A));1625Vals.push_back(getEncodedVisibility(A));1626Vals.push_back(getEncodedDLLStorageClass(A));1627Vals.push_back(getEncodedThreadLocalMode(A));1628Vals.push_back(getEncodedUnnamedAddr(A));1629Vals.push_back(A.isDSOLocal());1630Vals.push_back(addToStrtab(A.getPartition()));1631Vals.push_back(A.getPartition().size());16321633unsigned AbbrevToUse = 0;1634Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);1635Vals.clear();1636}16371638// Emit the ifunc information.1639for (const GlobalIFunc &I : M.ifuncs()) {1640// IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver1641// val#, linkage, visibility, DSO_Local]1642Vals.push_back(addToStrtab(I.getName()));1643Vals.push_back(I.getName().size());1644Vals.push_back(VE.getTypeID(I.getValueType()));1645Vals.push_back(I.getType()->getAddressSpace());1646Vals.push_back(VE.getValueID(I.getResolver()));1647Vals.push_back(getEncodedLinkage(I));1648Vals.push_back(getEncodedVisibility(I));1649Vals.push_back(I.isDSOLocal());1650Vals.push_back(addToStrtab(I.getPartition()));1651Vals.push_back(I.getPartition().size());1652Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);1653Vals.clear();1654}16551656writeValueSymbolTableForwardDecl();1657}16581659static uint64_t getOptimizationFlags(const Value *V) {1660uint64_t Flags = 0;16611662if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {1663if (OBO->hasNoSignedWrap())1664Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;1665if (OBO->hasNoUnsignedWrap())1666Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;1667} else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {1668if (PEO->isExact())1669Flags |= 1 << bitc::PEO_EXACT;1670} else if (const auto *PDI = dyn_cast<PossiblyDisjointInst>(V)) {1671if (PDI->isDisjoint())1672Flags |= 1 << bitc::PDI_DISJOINT;1673} else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {1674if (FPMO->hasAllowReassoc())1675Flags |= bitc::AllowReassoc;1676if (FPMO->hasNoNaNs())1677Flags |= bitc::NoNaNs;1678if (FPMO->hasNoInfs())1679Flags |= bitc::NoInfs;1680if (FPMO->hasNoSignedZeros())1681Flags |= bitc::NoSignedZeros;1682if (FPMO->hasAllowReciprocal())1683Flags |= bitc::AllowReciprocal;1684if (FPMO->hasAllowContract())1685Flags |= bitc::AllowContract;1686if (FPMO->hasApproxFunc())1687Flags |= bitc::ApproxFunc;1688} else if (const auto *NNI = dyn_cast<PossiblyNonNegInst>(V)) {1689if (NNI->hasNonNeg())1690Flags |= 1 << bitc::PNNI_NON_NEG;1691} else if (const auto *TI = dyn_cast<TruncInst>(V)) {1692if (TI->hasNoSignedWrap())1693Flags |= 1 << bitc::TIO_NO_SIGNED_WRAP;1694if (TI->hasNoUnsignedWrap())1695Flags |= 1 << bitc::TIO_NO_UNSIGNED_WRAP;1696} else if (const auto *GEP = dyn_cast<GEPOperator>(V)) {1697if (GEP->isInBounds())1698Flags |= 1 << bitc::GEP_INBOUNDS;1699if (GEP->hasNoUnsignedSignedWrap())1700Flags |= 1 << bitc::GEP_NUSW;1701if (GEP->hasNoUnsignedWrap())1702Flags |= 1 << bitc::GEP_NUW;1703}17041705return Flags;1706}17071708void ModuleBitcodeWriter::writeValueAsMetadata(1709const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {1710// Mimic an MDNode with a value as one operand.1711Value *V = MD->getValue();1712Record.push_back(VE.getTypeID(V->getType()));1713Record.push_back(VE.getValueID(V));1714Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);1715Record.clear();1716}17171718void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N,1719SmallVectorImpl<uint64_t> &Record,1720unsigned Abbrev) {1721for (const MDOperand &MDO : N->operands()) {1722Metadata *MD = MDO;1723assert(!(MD && isa<LocalAsMetadata>(MD)) &&1724"Unexpected function-local metadata");1725Record.push_back(VE.getMetadataOrNullID(MD));1726}1727Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE1728: bitc::METADATA_NODE,1729Record, Abbrev);1730Record.clear();1731}17321733unsigned ModuleBitcodeWriter::createDILocationAbbrev() {1734// Assume the column is usually under 128, and always output the inlined-at1735// location (it's never more expensive than building an array size 1).1736auto Abbv = std::make_shared<BitCodeAbbrev>();1737Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));1738Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));1739Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));1740Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));1741Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));1742Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));1743Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));1744return Stream.EmitAbbrev(std::move(Abbv));1745}17461747void ModuleBitcodeWriter::writeDILocation(const DILocation *N,1748SmallVectorImpl<uint64_t> &Record,1749unsigned &Abbrev) {1750if (!Abbrev)1751Abbrev = createDILocationAbbrev();17521753Record.push_back(N->isDistinct());1754Record.push_back(N->getLine());1755Record.push_back(N->getColumn());1756Record.push_back(VE.getMetadataID(N->getScope()));1757Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));1758Record.push_back(N->isImplicitCode());17591760Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);1761Record.clear();1762}17631764unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {1765// Assume the column is usually under 128, and always output the inlined-at1766// location (it's never more expensive than building an array size 1).1767auto Abbv = std::make_shared<BitCodeAbbrev>();1768Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));1769Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));1770Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));1771Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));1772Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));1773Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));1774Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));1775return Stream.EmitAbbrev(std::move(Abbv));1776}17771778void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N,1779SmallVectorImpl<uint64_t> &Record,1780unsigned &Abbrev) {1781if (!Abbrev)1782Abbrev = createGenericDINodeAbbrev();17831784Record.push_back(N->isDistinct());1785Record.push_back(N->getTag());1786Record.push_back(0); // Per-tag version field; unused for now.17871788for (auto &I : N->operands())1789Record.push_back(VE.getMetadataOrNullID(I));17901791Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);1792Record.clear();1793}17941795void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N,1796SmallVectorImpl<uint64_t> &Record,1797unsigned Abbrev) {1798const uint64_t Version = 2 << 1;1799Record.push_back((uint64_t)N->isDistinct() | Version);1800Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));1801Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));1802Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));1803Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));18041805Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);1806Record.clear();1807}18081809void ModuleBitcodeWriter::writeDIGenericSubrange(1810const DIGenericSubrange *N, SmallVectorImpl<uint64_t> &Record,1811unsigned Abbrev) {1812Record.push_back((uint64_t)N->isDistinct());1813Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));1814Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));1815Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));1816Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));18171818Stream.EmitRecord(bitc::METADATA_GENERIC_SUBRANGE, Record, Abbrev);1819Record.clear();1820}18211822void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,1823SmallVectorImpl<uint64_t> &Record,1824unsigned Abbrev) {1825const uint64_t IsBigInt = 1 << 2;1826Record.push_back(IsBigInt | (N->isUnsigned() << 1) | N->isDistinct());1827Record.push_back(N->getValue().getBitWidth());1828Record.push_back(VE.getMetadataOrNullID(N->getRawName()));1829emitWideAPInt(Record, N->getValue());18301831Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);1832Record.clear();1833}18341835void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N,1836SmallVectorImpl<uint64_t> &Record,1837unsigned Abbrev) {1838Record.push_back(N->isDistinct());1839Record.push_back(N->getTag());1840Record.push_back(VE.getMetadataOrNullID(N->getRawName()));1841Record.push_back(N->getSizeInBits());1842Record.push_back(N->getAlignInBits());1843Record.push_back(N->getEncoding());1844Record.push_back(N->getFlags());18451846Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);1847Record.clear();1848}18491850void ModuleBitcodeWriter::writeDIStringType(const DIStringType *N,1851SmallVectorImpl<uint64_t> &Record,1852unsigned Abbrev) {1853Record.push_back(N->isDistinct());1854Record.push_back(N->getTag());1855Record.push_back(VE.getMetadataOrNullID(N->getRawName()));1856Record.push_back(VE.getMetadataOrNullID(N->getStringLength()));1857Record.push_back(VE.getMetadataOrNullID(N->getStringLengthExp()));1858Record.push_back(VE.getMetadataOrNullID(N->getStringLocationExp()));1859Record.push_back(N->getSizeInBits());1860Record.push_back(N->getAlignInBits());1861Record.push_back(N->getEncoding());18621863Stream.EmitRecord(bitc::METADATA_STRING_TYPE, Record, Abbrev);1864Record.clear();1865}18661867void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,1868SmallVectorImpl<uint64_t> &Record,1869unsigned Abbrev) {1870Record.push_back(N->isDistinct());1871Record.push_back(N->getTag());1872Record.push_back(VE.getMetadataOrNullID(N->getRawName()));1873Record.push_back(VE.getMetadataOrNullID(N->getFile()));1874Record.push_back(N->getLine());1875Record.push_back(VE.getMetadataOrNullID(N->getScope()));1876Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));1877Record.push_back(N->getSizeInBits());1878Record.push_back(N->getAlignInBits());1879Record.push_back(N->getOffsetInBits());1880Record.push_back(N->getFlags());1881Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));18821883// DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means1884// that there is no DWARF address space associated with DIDerivedType.1885if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())1886Record.push_back(*DWARFAddressSpace + 1);1887else1888Record.push_back(0);18891890Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));18911892if (auto PtrAuthData = N->getPtrAuthData())1893Record.push_back(PtrAuthData->RawData);1894else1895Record.push_back(0);18961897Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);1898Record.clear();1899}19001901void ModuleBitcodeWriter::writeDICompositeType(1902const DICompositeType *N, SmallVectorImpl<uint64_t> &Record,1903unsigned Abbrev) {1904const unsigned IsNotUsedInOldTypeRef = 0x2;1905Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct());1906Record.push_back(N->getTag());1907Record.push_back(VE.getMetadataOrNullID(N->getRawName()));1908Record.push_back(VE.getMetadataOrNullID(N->getFile()));1909Record.push_back(N->getLine());1910Record.push_back(VE.getMetadataOrNullID(N->getScope()));1911Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));1912Record.push_back(N->getSizeInBits());1913Record.push_back(N->getAlignInBits());1914Record.push_back(N->getOffsetInBits());1915Record.push_back(N->getFlags());1916Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));1917Record.push_back(N->getRuntimeLang());1918Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));1919Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));1920Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));1921Record.push_back(VE.getMetadataOrNullID(N->getDiscriminator()));1922Record.push_back(VE.getMetadataOrNullID(N->getRawDataLocation()));1923Record.push_back(VE.getMetadataOrNullID(N->getRawAssociated()));1924Record.push_back(VE.getMetadataOrNullID(N->getRawAllocated()));1925Record.push_back(VE.getMetadataOrNullID(N->getRawRank()));1926Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));19271928Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);1929Record.clear();1930}19311932void ModuleBitcodeWriter::writeDISubroutineType(1933const DISubroutineType *N, SmallVectorImpl<uint64_t> &Record,1934unsigned Abbrev) {1935const unsigned HasNoOldTypeRefs = 0x2;1936Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());1937Record.push_back(N->getFlags());1938Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));1939Record.push_back(N->getCC());19401941Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);1942Record.clear();1943}19441945void ModuleBitcodeWriter::writeDIFile(const DIFile *N,1946SmallVectorImpl<uint64_t> &Record,1947unsigned Abbrev) {1948Record.push_back(N->isDistinct());1949Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));1950Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));1951if (N->getRawChecksum()) {1952Record.push_back(N->getRawChecksum()->Kind);1953Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()->Value));1954} else {1955// Maintain backwards compatibility with the old internal representation of1956// CSK_None in ChecksumKind by writing nulls here when Checksum is None.1957Record.push_back(0);1958Record.push_back(VE.getMetadataOrNullID(nullptr));1959}1960auto Source = N->getRawSource();1961if (Source)1962Record.push_back(VE.getMetadataOrNullID(Source));19631964Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);1965Record.clear();1966}19671968void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,1969SmallVectorImpl<uint64_t> &Record,1970unsigned Abbrev) {1971assert(N->isDistinct() && "Expected distinct compile units");1972Record.push_back(/* IsDistinct */ true);1973Record.push_back(N->getSourceLanguage());1974Record.push_back(VE.getMetadataOrNullID(N->getFile()));1975Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));1976Record.push_back(N->isOptimized());1977Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));1978Record.push_back(N->getRuntimeVersion());1979Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));1980Record.push_back(N->getEmissionKind());1981Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));1982Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));1983Record.push_back(/* subprograms */ 0);1984Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));1985Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));1986Record.push_back(N->getDWOId());1987Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));1988Record.push_back(N->getSplitDebugInlining());1989Record.push_back(N->getDebugInfoForProfiling());1990Record.push_back((unsigned)N->getNameTableKind());1991Record.push_back(N->getRangesBaseAddress());1992Record.push_back(VE.getMetadataOrNullID(N->getRawSysRoot()));1993Record.push_back(VE.getMetadataOrNullID(N->getRawSDK()));19941995Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);1996Record.clear();1997}19981999void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,2000SmallVectorImpl<uint64_t> &Record,2001unsigned Abbrev) {2002const uint64_t HasUnitFlag = 1 << 1;2003const uint64_t HasSPFlagsFlag = 1 << 2;2004Record.push_back(uint64_t(N->isDistinct()) | HasUnitFlag | HasSPFlagsFlag);2005Record.push_back(VE.getMetadataOrNullID(N->getScope()));2006Record.push_back(VE.getMetadataOrNullID(N->getRawName()));2007Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));2008Record.push_back(VE.getMetadataOrNullID(N->getFile()));2009Record.push_back(N->getLine());2010Record.push_back(VE.getMetadataOrNullID(N->getType()));2011Record.push_back(N->getScopeLine());2012Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));2013Record.push_back(N->getSPFlags());2014Record.push_back(N->getVirtualIndex());2015Record.push_back(N->getFlags());2016Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));2017Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));2018Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));2019Record.push_back(VE.getMetadataOrNullID(N->getRetainedNodes().get()));2020Record.push_back(N->getThisAdjustment());2021Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get()));2022Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));2023Record.push_back(VE.getMetadataOrNullID(N->getRawTargetFuncName()));20242025Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);2026Record.clear();2027}20282029void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,2030SmallVectorImpl<uint64_t> &Record,2031unsigned Abbrev) {2032Record.push_back(N->isDistinct());2033Record.push_back(VE.getMetadataOrNullID(N->getScope()));2034Record.push_back(VE.getMetadataOrNullID(N->getFile()));2035Record.push_back(N->getLine());2036Record.push_back(N->getColumn());20372038Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);2039Record.clear();2040}20412042void ModuleBitcodeWriter::writeDILexicalBlockFile(2043const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record,2044unsigned Abbrev) {2045Record.push_back(N->isDistinct());2046Record.push_back(VE.getMetadataOrNullID(N->getScope()));2047Record.push_back(VE.getMetadataOrNullID(N->getFile()));2048Record.push_back(N->getDiscriminator());20492050Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);2051Record.clear();2052}20532054void ModuleBitcodeWriter::writeDICommonBlock(const DICommonBlock *N,2055SmallVectorImpl<uint64_t> &Record,2056unsigned Abbrev) {2057Record.push_back(N->isDistinct());2058Record.push_back(VE.getMetadataOrNullID(N->getScope()));2059Record.push_back(VE.getMetadataOrNullID(N->getDecl()));2060Record.push_back(VE.getMetadataOrNullID(N->getRawName()));2061Record.push_back(VE.getMetadataOrNullID(N->getFile()));2062Record.push_back(N->getLineNo());20632064Stream.EmitRecord(bitc::METADATA_COMMON_BLOCK, Record, Abbrev);2065Record.clear();2066}20672068void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,2069SmallVectorImpl<uint64_t> &Record,2070unsigned Abbrev) {2071Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);2072Record.push_back(VE.getMetadataOrNullID(N->getScope()));2073Record.push_back(VE.getMetadataOrNullID(N->getRawName()));20742075Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);2076Record.clear();2077}20782079void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,2080SmallVectorImpl<uint64_t> &Record,2081unsigned Abbrev) {2082Record.push_back(N->isDistinct());2083Record.push_back(N->getMacinfoType());2084Record.push_back(N->getLine());2085Record.push_back(VE.getMetadataOrNullID(N->getRawName()));2086Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));20872088Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);2089Record.clear();2090}20912092void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,2093SmallVectorImpl<uint64_t> &Record,2094unsigned Abbrev) {2095Record.push_back(N->isDistinct());2096Record.push_back(N->getMacinfoType());2097Record.push_back(N->getLine());2098Record.push_back(VE.getMetadataOrNullID(N->getFile()));2099Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));21002101Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);2102Record.clear();2103}21042105void ModuleBitcodeWriter::writeDIArgList(const DIArgList *N,2106SmallVectorImpl<uint64_t> &Record) {2107Record.reserve(N->getArgs().size());2108for (ValueAsMetadata *MD : N->getArgs())2109Record.push_back(VE.getMetadataID(MD));21102111Stream.EmitRecord(bitc::METADATA_ARG_LIST, Record);2112Record.clear();2113}21142115void ModuleBitcodeWriter::writeDIModule(const DIModule *N,2116SmallVectorImpl<uint64_t> &Record,2117unsigned Abbrev) {2118Record.push_back(N->isDistinct());2119for (auto &I : N->operands())2120Record.push_back(VE.getMetadataOrNullID(I));2121Record.push_back(N->getLineNo());2122Record.push_back(N->getIsDecl());21232124Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);2125Record.clear();2126}21272128void ModuleBitcodeWriter::writeDIAssignID(const DIAssignID *N,2129SmallVectorImpl<uint64_t> &Record,2130unsigned Abbrev) {2131// There are no arguments for this metadata type.2132Record.push_back(N->isDistinct());2133Stream.EmitRecord(bitc::METADATA_ASSIGN_ID, Record, Abbrev);2134Record.clear();2135}21362137void ModuleBitcodeWriter::writeDITemplateTypeParameter(2138const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record,2139unsigned Abbrev) {2140Record.push_back(N->isDistinct());2141Record.push_back(VE.getMetadataOrNullID(N->getRawName()));2142Record.push_back(VE.getMetadataOrNullID(N->getType()));2143Record.push_back(N->isDefault());21442145Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);2146Record.clear();2147}21482149void ModuleBitcodeWriter::writeDITemplateValueParameter(2150const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record,2151unsigned Abbrev) {2152Record.push_back(N->isDistinct());2153Record.push_back(N->getTag());2154Record.push_back(VE.getMetadataOrNullID(N->getRawName()));2155Record.push_back(VE.getMetadataOrNullID(N->getType()));2156Record.push_back(N->isDefault());2157Record.push_back(VE.getMetadataOrNullID(N->getValue()));21582159Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);2160Record.clear();2161}21622163void ModuleBitcodeWriter::writeDIGlobalVariable(2164const DIGlobalVariable *N, SmallVectorImpl<uint64_t> &Record,2165unsigned Abbrev) {2166const uint64_t Version = 2 << 1;2167Record.push_back((uint64_t)N->isDistinct() | Version);2168Record.push_back(VE.getMetadataOrNullID(N->getScope()));2169Record.push_back(VE.getMetadataOrNullID(N->getRawName()));2170Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));2171Record.push_back(VE.getMetadataOrNullID(N->getFile()));2172Record.push_back(N->getLine());2173Record.push_back(VE.getMetadataOrNullID(N->getType()));2174Record.push_back(N->isLocalToUnit());2175Record.push_back(N->isDefinition());2176Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));2177Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams()));2178Record.push_back(N->getAlignInBits());2179Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));21802181Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);2182Record.clear();2183}21842185void ModuleBitcodeWriter::writeDILocalVariable(2186const DILocalVariable *N, SmallVectorImpl<uint64_t> &Record,2187unsigned Abbrev) {2188// In order to support all possible bitcode formats in BitcodeReader we need2189// to distinguish the following cases:2190// 1) Record has no artificial tag (Record[1]),2191// has no obsolete inlinedAt field (Record[9]).2192// In this case Record size will be 8, HasAlignment flag is false.2193// 2) Record has artificial tag (Record[1]),2194// has no obsolete inlignedAt field (Record[9]).2195// In this case Record size will be 9, HasAlignment flag is false.2196// 3) Record has both artificial tag (Record[1]) and2197// obsolete inlignedAt field (Record[9]).2198// In this case Record size will be 10, HasAlignment flag is false.2199// 4) Record has neither artificial tag, nor inlignedAt field, but2200// HasAlignment flag is true and Record[8] contains alignment value.2201const uint64_t HasAlignmentFlag = 1 << 1;2202Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);2203Record.push_back(VE.getMetadataOrNullID(N->getScope()));2204Record.push_back(VE.getMetadataOrNullID(N->getRawName()));2205Record.push_back(VE.getMetadataOrNullID(N->getFile()));2206Record.push_back(N->getLine());2207Record.push_back(VE.getMetadataOrNullID(N->getType()));2208Record.push_back(N->getArg());2209Record.push_back(N->getFlags());2210Record.push_back(N->getAlignInBits());2211Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));22122213Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);2214Record.clear();2215}22162217void ModuleBitcodeWriter::writeDILabel(2218const DILabel *N, SmallVectorImpl<uint64_t> &Record,2219unsigned Abbrev) {2220Record.push_back((uint64_t)N->isDistinct());2221Record.push_back(VE.getMetadataOrNullID(N->getScope()));2222Record.push_back(VE.getMetadataOrNullID(N->getRawName()));2223Record.push_back(VE.getMetadataOrNullID(N->getFile()));2224Record.push_back(N->getLine());22252226Stream.EmitRecord(bitc::METADATA_LABEL, Record, Abbrev);2227Record.clear();2228}22292230void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,2231SmallVectorImpl<uint64_t> &Record,2232unsigned Abbrev) {2233Record.reserve(N->getElements().size() + 1);2234const uint64_t Version = 3 << 1;2235Record.push_back((uint64_t)N->isDistinct() | Version);2236Record.append(N->elements_begin(), N->elements_end());22372238Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);2239Record.clear();2240}22412242void ModuleBitcodeWriter::writeDIGlobalVariableExpression(2243const DIGlobalVariableExpression *N, SmallVectorImpl<uint64_t> &Record,2244unsigned Abbrev) {2245Record.push_back(N->isDistinct());2246Record.push_back(VE.getMetadataOrNullID(N->getVariable()));2247Record.push_back(VE.getMetadataOrNullID(N->getExpression()));22482249Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR, Record, Abbrev);2250Record.clear();2251}22522253void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,2254SmallVectorImpl<uint64_t> &Record,2255unsigned Abbrev) {2256Record.push_back(N->isDistinct());2257Record.push_back(VE.getMetadataOrNullID(N->getRawName()));2258Record.push_back(VE.getMetadataOrNullID(N->getFile()));2259Record.push_back(N->getLine());2260Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));2261Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));2262Record.push_back(N->getAttributes());2263Record.push_back(VE.getMetadataOrNullID(N->getType()));22642265Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);2266Record.clear();2267}22682269void ModuleBitcodeWriter::writeDIImportedEntity(2270const DIImportedEntity *N, SmallVectorImpl<uint64_t> &Record,2271unsigned Abbrev) {2272Record.push_back(N->isDistinct());2273Record.push_back(N->getTag());2274Record.push_back(VE.getMetadataOrNullID(N->getScope()));2275Record.push_back(VE.getMetadataOrNullID(N->getEntity()));2276Record.push_back(N->getLine());2277Record.push_back(VE.getMetadataOrNullID(N->getRawName()));2278Record.push_back(VE.getMetadataOrNullID(N->getRawFile()));2279Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));22802281Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);2282Record.clear();2283}22842285unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {2286auto Abbv = std::make_shared<BitCodeAbbrev>();2287Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));2288Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));2289Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));2290return Stream.EmitAbbrev(std::move(Abbv));2291}22922293void ModuleBitcodeWriter::writeNamedMetadata(2294SmallVectorImpl<uint64_t> &Record) {2295if (M.named_metadata_empty())2296return;22972298unsigned Abbrev = createNamedMetadataAbbrev();2299for (const NamedMDNode &NMD : M.named_metadata()) {2300// Write name.2301StringRef Str = NMD.getName();2302Record.append(Str.bytes_begin(), Str.bytes_end());2303Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);2304Record.clear();23052306// Write named metadata operands.2307for (const MDNode *N : NMD.operands())2308Record.push_back(VE.getMetadataID(N));2309Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);2310Record.clear();2311}2312}23132314unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {2315auto Abbv = std::make_shared<BitCodeAbbrev>();2316Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS));2317Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings2318Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars2319Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));2320return Stream.EmitAbbrev(std::move(Abbv));2321}23222323/// Write out a record for MDString.2324///2325/// All the metadata strings in a metadata block are emitted in a single2326/// record. The sizes and strings themselves are shoved into a blob.2327void ModuleBitcodeWriter::writeMetadataStrings(2328ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) {2329if (Strings.empty())2330return;23312332// Start the record with the number of strings.2333Record.push_back(bitc::METADATA_STRINGS);2334Record.push_back(Strings.size());23352336// Emit the sizes of the strings in the blob.2337SmallString<256> Blob;2338{2339BitstreamWriter W(Blob);2340for (const Metadata *MD : Strings)2341W.EmitVBR(cast<MDString>(MD)->getLength(), 6);2342W.FlushToWord();2343}23442345// Add the offset to the strings to the record.2346Record.push_back(Blob.size());23472348// Add the strings to the blob.2349for (const Metadata *MD : Strings)2350Blob.append(cast<MDString>(MD)->getString());23512352// Emit the final record.2353Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);2354Record.clear();2355}23562357// Generates an enum to use as an index in the Abbrev array of Metadata record.2358enum MetadataAbbrev : unsigned {2359#define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,2360#include "llvm/IR/Metadata.def"2361LastPlusOne2362};23632364void ModuleBitcodeWriter::writeMetadataRecords(2365ArrayRef<const Metadata *> MDs, SmallVectorImpl<uint64_t> &Record,2366std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {2367if (MDs.empty())2368return;23692370// Initialize MDNode abbreviations.2371#define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;2372#include "llvm/IR/Metadata.def"23732374for (const Metadata *MD : MDs) {2375if (IndexPos)2376IndexPos->push_back(Stream.GetCurrentBitNo());2377if (const MDNode *N = dyn_cast<MDNode>(MD)) {2378assert(N->isResolved() && "Expected forward references to be resolved");23792380switch (N->getMetadataID()) {2381default:2382llvm_unreachable("Invalid MDNode subclass");2383#define HANDLE_MDNODE_LEAF(CLASS) \2384case Metadata::CLASS##Kind: \2385if (MDAbbrevs) \2386write##CLASS(cast<CLASS>(N), Record, \2387(*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \2388else \2389write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \2390continue;2391#include "llvm/IR/Metadata.def"2392}2393}2394if (auto *AL = dyn_cast<DIArgList>(MD)) {2395writeDIArgList(AL, Record);2396continue;2397}2398writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);2399}2400}24012402void ModuleBitcodeWriter::writeModuleMetadata() {2403if (!VE.hasMDs() && M.named_metadata_empty())2404return;24052406Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 4);2407SmallVector<uint64_t, 64> Record;24082409// Emit all abbrevs upfront, so that the reader can jump in the middle of the2410// block and load any metadata.2411std::vector<unsigned> MDAbbrevs;24122413MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);2414MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();2415MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =2416createGenericDINodeAbbrev();24172418auto Abbv = std::make_shared<BitCodeAbbrev>();2419Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX_OFFSET));2420Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));2421Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));2422unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));24232424Abbv = std::make_shared<BitCodeAbbrev>();2425Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX));2426Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));2427Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));2428unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));24292430// Emit MDStrings together upfront.2431writeMetadataStrings(VE.getMDStrings(), Record);24322433// We only emit an index for the metadata record if we have more than a given2434// (naive) threshold of metadatas, otherwise it is not worth it.2435if (VE.getNonMDStrings().size() > IndexThreshold) {2436// Write a placeholder value in for the offset of the metadata index,2437// which is written after the records, so that it can include2438// the offset of each entry. The placeholder offset will be2439// updated after all records are emitted.2440uint64_t Vals[] = {0, 0};2441Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);2442}24432444// Compute and save the bit offset to the current position, which will be2445// patched when we emit the index later. We can simply subtract the 64-bit2446// fixed size from the current bit number to get the location to backpatch.2447uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();24482449// This index will contain the bitpos for each individual record.2450std::vector<uint64_t> IndexPos;2451IndexPos.reserve(VE.getNonMDStrings().size());24522453// Write all the records2454writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);24552456if (VE.getNonMDStrings().size() > IndexThreshold) {2457// Now that we have emitted all the records we will emit the index. But2458// first2459// backpatch the forward reference so that the reader can skip the records2460// efficiently.2461Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,2462Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);24632464// Delta encode the index.2465uint64_t PreviousValue = IndexOffsetRecordBitPos;2466for (auto &Elt : IndexPos) {2467auto EltDelta = Elt - PreviousValue;2468PreviousValue = Elt;2469Elt = EltDelta;2470}2471// Emit the index record.2472Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);2473IndexPos.clear();2474}24752476// Write the named metadata now.2477writeNamedMetadata(Record);24782479auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {2480SmallVector<uint64_t, 4> Record;2481Record.push_back(VE.getValueID(&GO));2482pushGlobalMetadataAttachment(Record, GO);2483Stream.EmitRecord(bitc::METADATA_GLOBAL_DECL_ATTACHMENT, Record);2484};2485for (const Function &F : M)2486if (F.isDeclaration() && F.hasMetadata())2487AddDeclAttachedMetadata(F);2488// FIXME: Only store metadata for declarations here, and move data for global2489// variable definitions to a separate block (PR28134).2490for (const GlobalVariable &GV : M.globals())2491if (GV.hasMetadata())2492AddDeclAttachedMetadata(GV);24932494Stream.ExitBlock();2495}24962497void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {2498if (!VE.hasMDs())2499return;25002501Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);2502SmallVector<uint64_t, 64> Record;2503writeMetadataStrings(VE.getMDStrings(), Record);2504writeMetadataRecords(VE.getNonMDStrings(), Record);2505Stream.ExitBlock();2506}25072508void ModuleBitcodeWriter::pushGlobalMetadataAttachment(2509SmallVectorImpl<uint64_t> &Record, const GlobalObject &GO) {2510// [n x [id, mdnode]]2511SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;2512GO.getAllMetadata(MDs);2513for (const auto &I : MDs) {2514Record.push_back(I.first);2515Record.push_back(VE.getMetadataID(I.second));2516}2517}25182519void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {2520Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);25212522SmallVector<uint64_t, 64> Record;25232524if (F.hasMetadata()) {2525pushGlobalMetadataAttachment(Record, F);2526Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);2527Record.clear();2528}25292530// Write metadata attachments2531// METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]2532SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;2533for (const BasicBlock &BB : F)2534for (const Instruction &I : BB) {2535MDs.clear();2536I.getAllMetadataOtherThanDebugLoc(MDs);25372538// If no metadata, ignore instruction.2539if (MDs.empty()) continue;25402541Record.push_back(VE.getInstructionID(&I));25422543for (unsigned i = 0, e = MDs.size(); i != e; ++i) {2544Record.push_back(MDs[i].first);2545Record.push_back(VE.getMetadataID(MDs[i].second));2546}2547Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);2548Record.clear();2549}25502551Stream.ExitBlock();2552}25532554void ModuleBitcodeWriter::writeModuleMetadataKinds() {2555SmallVector<uint64_t, 64> Record;25562557// Write metadata kinds2558// METADATA_KIND - [n x [id, name]]2559SmallVector<StringRef, 8> Names;2560M.getMDKindNames(Names);25612562if (Names.empty()) return;25632564Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3);25652566for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {2567Record.push_back(MDKindID);2568StringRef KName = Names[MDKindID];2569Record.append(KName.begin(), KName.end());25702571Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);2572Record.clear();2573}25742575Stream.ExitBlock();2576}25772578void ModuleBitcodeWriter::writeOperandBundleTags() {2579// Write metadata kinds2580//2581// OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG2582//2583// OPERAND_BUNDLE_TAG - [strchr x N]25842585SmallVector<StringRef, 8> Tags;2586M.getOperandBundleTags(Tags);25872588if (Tags.empty())2589return;25902591Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3);25922593SmallVector<uint64_t, 64> Record;25942595for (auto Tag : Tags) {2596Record.append(Tag.begin(), Tag.end());25972598Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);2599Record.clear();2600}26012602Stream.ExitBlock();2603}26042605void ModuleBitcodeWriter::writeSyncScopeNames() {2606SmallVector<StringRef, 8> SSNs;2607M.getContext().getSyncScopeNames(SSNs);2608if (SSNs.empty())2609return;26102611Stream.EnterSubblock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID, 2);26122613SmallVector<uint64_t, 64> Record;2614for (auto SSN : SSNs) {2615Record.append(SSN.begin(), SSN.end());2616Stream.EmitRecord(bitc::SYNC_SCOPE_NAME, Record, 0);2617Record.clear();2618}26192620Stream.ExitBlock();2621}26222623void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,2624bool isGlobal) {2625if (FirstVal == LastVal) return;26262627Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);26282629unsigned AggregateAbbrev = 0;2630unsigned String8Abbrev = 0;2631unsigned CString7Abbrev = 0;2632unsigned CString6Abbrev = 0;2633// If this is a constant pool for the module, emit module-specific abbrevs.2634if (isGlobal) {2635// Abbrev for CST_CODE_AGGREGATE.2636auto Abbv = std::make_shared<BitCodeAbbrev>();2637Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));2638Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));2639Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));2640AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));26412642// Abbrev for CST_CODE_STRING.2643Abbv = std::make_shared<BitCodeAbbrev>();2644Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));2645Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));2646Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));2647String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));2648// Abbrev for CST_CODE_CSTRING.2649Abbv = std::make_shared<BitCodeAbbrev>();2650Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));2651Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));2652Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));2653CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));2654// Abbrev for CST_CODE_CSTRING.2655Abbv = std::make_shared<BitCodeAbbrev>();2656Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));2657Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));2658Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));2659CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));2660}26612662SmallVector<uint64_t, 64> Record;26632664const ValueEnumerator::ValueList &Vals = VE.getValues();2665Type *LastTy = nullptr;2666for (unsigned i = FirstVal; i != LastVal; ++i) {2667const Value *V = Vals[i].first;2668// If we need to switch types, do so now.2669if (V->getType() != LastTy) {2670LastTy = V->getType();2671Record.push_back(VE.getTypeID(LastTy));2672Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,2673CONSTANTS_SETTYPE_ABBREV);2674Record.clear();2675}26762677if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {2678Record.push_back(VE.getTypeID(IA->getFunctionType()));2679Record.push_back(2680unsigned(IA->hasSideEffects()) | unsigned(IA->isAlignStack()) << 1 |2681unsigned(IA->getDialect() & 1) << 2 | unsigned(IA->canThrow()) << 3);26822683// Add the asm string.2684const std::string &AsmStr = IA->getAsmString();2685Record.push_back(AsmStr.size());2686Record.append(AsmStr.begin(), AsmStr.end());26872688// Add the constraint string.2689const std::string &ConstraintStr = IA->getConstraintString();2690Record.push_back(ConstraintStr.size());2691Record.append(ConstraintStr.begin(), ConstraintStr.end());2692Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);2693Record.clear();2694continue;2695}2696const Constant *C = cast<Constant>(V);2697unsigned Code = -1U;2698unsigned AbbrevToUse = 0;2699if (C->isNullValue()) {2700Code = bitc::CST_CODE_NULL;2701} else if (isa<PoisonValue>(C)) {2702Code = bitc::CST_CODE_POISON;2703} else if (isa<UndefValue>(C)) {2704Code = bitc::CST_CODE_UNDEF;2705} else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {2706if (IV->getBitWidth() <= 64) {2707uint64_t V = IV->getSExtValue();2708emitSignedInt64(Record, V);2709Code = bitc::CST_CODE_INTEGER;2710AbbrevToUse = CONSTANTS_INTEGER_ABBREV;2711} else { // Wide integers, > 64 bits in size.2712emitWideAPInt(Record, IV->getValue());2713Code = bitc::CST_CODE_WIDE_INTEGER;2714}2715} else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {2716Code = bitc::CST_CODE_FLOAT;2717Type *Ty = CFP->getType()->getScalarType();2718if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() ||2719Ty->isDoubleTy()) {2720Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());2721} else if (Ty->isX86_FP80Ty()) {2722// api needed to prevent premature destruction2723// bits are not in the same order as a normal i80 APInt, compensate.2724APInt api = CFP->getValueAPF().bitcastToAPInt();2725const uint64_t *p = api.getRawData();2726Record.push_back((p[1] << 48) | (p[0] >> 16));2727Record.push_back(p[0] & 0xffffLL);2728} else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {2729APInt api = CFP->getValueAPF().bitcastToAPInt();2730const uint64_t *p = api.getRawData();2731Record.push_back(p[0]);2732Record.push_back(p[1]);2733} else {2734assert(0 && "Unknown FP type!");2735}2736} else if (isa<ConstantDataSequential>(C) &&2737cast<ConstantDataSequential>(C)->isString()) {2738const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);2739// Emit constant strings specially.2740unsigned NumElts = Str->getNumElements();2741// If this is a null-terminated string, use the denser CSTRING encoding.2742if (Str->isCString()) {2743Code = bitc::CST_CODE_CSTRING;2744--NumElts; // Don't encode the null, which isn't allowed by char6.2745} else {2746Code = bitc::CST_CODE_STRING;2747AbbrevToUse = String8Abbrev;2748}2749bool isCStr7 = Code == bitc::CST_CODE_CSTRING;2750bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;2751for (unsigned i = 0; i != NumElts; ++i) {2752unsigned char V = Str->getElementAsInteger(i);2753Record.push_back(V);2754isCStr7 &= (V & 128) == 0;2755if (isCStrChar6)2756isCStrChar6 = BitCodeAbbrevOp::isChar6(V);2757}27582759if (isCStrChar6)2760AbbrevToUse = CString6Abbrev;2761else if (isCStr7)2762AbbrevToUse = CString7Abbrev;2763} else if (const ConstantDataSequential *CDS =2764dyn_cast<ConstantDataSequential>(C)) {2765Code = bitc::CST_CODE_DATA;2766Type *EltTy = CDS->getElementType();2767if (isa<IntegerType>(EltTy)) {2768for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)2769Record.push_back(CDS->getElementAsInteger(i));2770} else {2771for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)2772Record.push_back(2773CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());2774}2775} else if (isa<ConstantAggregate>(C)) {2776Code = bitc::CST_CODE_AGGREGATE;2777for (const Value *Op : C->operands())2778Record.push_back(VE.getValueID(Op));2779AbbrevToUse = AggregateAbbrev;2780} else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {2781switch (CE->getOpcode()) {2782default:2783if (Instruction::isCast(CE->getOpcode())) {2784Code = bitc::CST_CODE_CE_CAST;2785Record.push_back(getEncodedCastOpcode(CE->getOpcode()));2786Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));2787Record.push_back(VE.getValueID(C->getOperand(0)));2788AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;2789} else {2790assert(CE->getNumOperands() == 2 && "Unknown constant expr!");2791Code = bitc::CST_CODE_CE_BINOP;2792Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));2793Record.push_back(VE.getValueID(C->getOperand(0)));2794Record.push_back(VE.getValueID(C->getOperand(1)));2795uint64_t Flags = getOptimizationFlags(CE);2796if (Flags != 0)2797Record.push_back(Flags);2798}2799break;2800case Instruction::FNeg: {2801assert(CE->getNumOperands() == 1 && "Unknown constant expr!");2802Code = bitc::CST_CODE_CE_UNOP;2803Record.push_back(getEncodedUnaryOpcode(CE->getOpcode()));2804Record.push_back(VE.getValueID(C->getOperand(0)));2805uint64_t Flags = getOptimizationFlags(CE);2806if (Flags != 0)2807Record.push_back(Flags);2808break;2809}2810case Instruction::GetElementPtr: {2811Code = bitc::CST_CODE_CE_GEP;2812const auto *GO = cast<GEPOperator>(C);2813Record.push_back(VE.getTypeID(GO->getSourceElementType()));2814Record.push_back(getOptimizationFlags(GO));2815if (std::optional<ConstantRange> Range = GO->getInRange()) {2816Code = bitc::CST_CODE_CE_GEP_WITH_INRANGE;2817emitConstantRange(Record, *Range, /*EmitBitWidth=*/true);2818}2819for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {2820Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));2821Record.push_back(VE.getValueID(C->getOperand(i)));2822}2823break;2824}2825case Instruction::ExtractElement:2826Code = bitc::CST_CODE_CE_EXTRACTELT;2827Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));2828Record.push_back(VE.getValueID(C->getOperand(0)));2829Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));2830Record.push_back(VE.getValueID(C->getOperand(1)));2831break;2832case Instruction::InsertElement:2833Code = bitc::CST_CODE_CE_INSERTELT;2834Record.push_back(VE.getValueID(C->getOperand(0)));2835Record.push_back(VE.getValueID(C->getOperand(1)));2836Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));2837Record.push_back(VE.getValueID(C->getOperand(2)));2838break;2839case Instruction::ShuffleVector:2840// If the return type and argument types are the same, this is a2841// standard shufflevector instruction. If the types are different,2842// then the shuffle is widening or truncating the input vectors, and2843// the argument type must also be encoded.2844if (C->getType() == C->getOperand(0)->getType()) {2845Code = bitc::CST_CODE_CE_SHUFFLEVEC;2846} else {2847Code = bitc::CST_CODE_CE_SHUFVEC_EX;2848Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));2849}2850Record.push_back(VE.getValueID(C->getOperand(0)));2851Record.push_back(VE.getValueID(C->getOperand(1)));2852Record.push_back(VE.getValueID(CE->getShuffleMaskForBitcode()));2853break;2854}2855} else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {2856Code = bitc::CST_CODE_BLOCKADDRESS;2857Record.push_back(VE.getTypeID(BA->getFunction()->getType()));2858Record.push_back(VE.getValueID(BA->getFunction()));2859Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));2860} else if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) {2861Code = bitc::CST_CODE_DSO_LOCAL_EQUIVALENT;2862Record.push_back(VE.getTypeID(Equiv->getGlobalValue()->getType()));2863Record.push_back(VE.getValueID(Equiv->getGlobalValue()));2864} else if (const auto *NC = dyn_cast<NoCFIValue>(C)) {2865Code = bitc::CST_CODE_NO_CFI_VALUE;2866Record.push_back(VE.getTypeID(NC->getGlobalValue()->getType()));2867Record.push_back(VE.getValueID(NC->getGlobalValue()));2868} else if (const auto *CPA = dyn_cast<ConstantPtrAuth>(C)) {2869Code = bitc::CST_CODE_PTRAUTH;2870Record.push_back(VE.getValueID(CPA->getPointer()));2871Record.push_back(VE.getValueID(CPA->getKey()));2872Record.push_back(VE.getValueID(CPA->getDiscriminator()));2873Record.push_back(VE.getValueID(CPA->getAddrDiscriminator()));2874} else {2875#ifndef NDEBUG2876C->dump();2877#endif2878llvm_unreachable("Unknown constant!");2879}2880Stream.EmitRecord(Code, Record, AbbrevToUse);2881Record.clear();2882}28832884Stream.ExitBlock();2885}28862887void ModuleBitcodeWriter::writeModuleConstants() {2888const ValueEnumerator::ValueList &Vals = VE.getValues();28892890// Find the first constant to emit, which is the first non-globalvalue value.2891// We know globalvalues have been emitted by WriteModuleInfo.2892for (unsigned i = 0, e = Vals.size(); i != e; ++i) {2893if (!isa<GlobalValue>(Vals[i].first)) {2894writeConstants(i, Vals.size(), true);2895return;2896}2897}2898}28992900/// pushValueAndType - The file has to encode both the value and type id for2901/// many values, because we need to know what type to create for forward2902/// references. However, most operands are not forward references, so this type2903/// field is not needed.2904///2905/// This function adds V's value ID to Vals. If the value ID is higher than the2906/// instruction ID, then it is a forward reference, and it also includes the2907/// type ID. The value ID that is written is encoded relative to the InstID.2908bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,2909SmallVectorImpl<unsigned> &Vals) {2910unsigned ValID = VE.getValueID(V);2911// Make encoding relative to the InstID.2912Vals.push_back(InstID - ValID);2913if (ValID >= InstID) {2914Vals.push_back(VE.getTypeID(V->getType()));2915return true;2916}2917return false;2918}29192920void ModuleBitcodeWriter::writeOperandBundles(const CallBase &CS,2921unsigned InstID) {2922SmallVector<unsigned, 64> Record;2923LLVMContext &C = CS.getContext();29242925for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {2926const auto &Bundle = CS.getOperandBundleAt(i);2927Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));29282929for (auto &Input : Bundle.Inputs)2930pushValueAndType(Input, InstID, Record);29312932Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record);2933Record.clear();2934}2935}29362937/// pushValue - Like pushValueAndType, but where the type of the value is2938/// omitted (perhaps it was already encoded in an earlier operand).2939void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,2940SmallVectorImpl<unsigned> &Vals) {2941unsigned ValID = VE.getValueID(V);2942Vals.push_back(InstID - ValID);2943}29442945void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,2946SmallVectorImpl<uint64_t> &Vals) {2947unsigned ValID = VE.getValueID(V);2948int64_t diff = ((int32_t)InstID - (int32_t)ValID);2949emitSignedInt64(Vals, diff);2950}29512952/// WriteInstruction - Emit an instruction to the specified stream.2953void ModuleBitcodeWriter::writeInstruction(const Instruction &I,2954unsigned InstID,2955SmallVectorImpl<unsigned> &Vals) {2956unsigned Code = 0;2957unsigned AbbrevToUse = 0;2958VE.setInstructionID(&I);2959switch (I.getOpcode()) {2960default:2961if (Instruction::isCast(I.getOpcode())) {2962Code = bitc::FUNC_CODE_INST_CAST;2963if (!pushValueAndType(I.getOperand(0), InstID, Vals))2964AbbrevToUse = FUNCTION_INST_CAST_ABBREV;2965Vals.push_back(VE.getTypeID(I.getType()));2966Vals.push_back(getEncodedCastOpcode(I.getOpcode()));2967uint64_t Flags = getOptimizationFlags(&I);2968if (Flags != 0) {2969if (AbbrevToUse == FUNCTION_INST_CAST_ABBREV)2970AbbrevToUse = FUNCTION_INST_CAST_FLAGS_ABBREV;2971Vals.push_back(Flags);2972}2973} else {2974assert(isa<BinaryOperator>(I) && "Unknown instruction!");2975Code = bitc::FUNC_CODE_INST_BINOP;2976if (!pushValueAndType(I.getOperand(0), InstID, Vals))2977AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;2978pushValue(I.getOperand(1), InstID, Vals);2979Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));2980uint64_t Flags = getOptimizationFlags(&I);2981if (Flags != 0) {2982if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)2983AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;2984Vals.push_back(Flags);2985}2986}2987break;2988case Instruction::FNeg: {2989Code = bitc::FUNC_CODE_INST_UNOP;2990if (!pushValueAndType(I.getOperand(0), InstID, Vals))2991AbbrevToUse = FUNCTION_INST_UNOP_ABBREV;2992Vals.push_back(getEncodedUnaryOpcode(I.getOpcode()));2993uint64_t Flags = getOptimizationFlags(&I);2994if (Flags != 0) {2995if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV)2996AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV;2997Vals.push_back(Flags);2998}2999break;3000}3001case Instruction::GetElementPtr: {3002Code = bitc::FUNC_CODE_INST_GEP;3003AbbrevToUse = FUNCTION_INST_GEP_ABBREV;3004auto &GEPInst = cast<GetElementPtrInst>(I);3005Vals.push_back(getOptimizationFlags(&I));3006Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));3007for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)3008pushValueAndType(I.getOperand(i), InstID, Vals);3009break;3010}3011case Instruction::ExtractValue: {3012Code = bitc::FUNC_CODE_INST_EXTRACTVAL;3013pushValueAndType(I.getOperand(0), InstID, Vals);3014const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);3015Vals.append(EVI->idx_begin(), EVI->idx_end());3016break;3017}3018case Instruction::InsertValue: {3019Code = bitc::FUNC_CODE_INST_INSERTVAL;3020pushValueAndType(I.getOperand(0), InstID, Vals);3021pushValueAndType(I.getOperand(1), InstID, Vals);3022const InsertValueInst *IVI = cast<InsertValueInst>(&I);3023Vals.append(IVI->idx_begin(), IVI->idx_end());3024break;3025}3026case Instruction::Select: {3027Code = bitc::FUNC_CODE_INST_VSELECT;3028pushValueAndType(I.getOperand(1), InstID, Vals);3029pushValue(I.getOperand(2), InstID, Vals);3030pushValueAndType(I.getOperand(0), InstID, Vals);3031uint64_t Flags = getOptimizationFlags(&I);3032if (Flags != 0)3033Vals.push_back(Flags);3034break;3035}3036case Instruction::ExtractElement:3037Code = bitc::FUNC_CODE_INST_EXTRACTELT;3038pushValueAndType(I.getOperand(0), InstID, Vals);3039pushValueAndType(I.getOperand(1), InstID, Vals);3040break;3041case Instruction::InsertElement:3042Code = bitc::FUNC_CODE_INST_INSERTELT;3043pushValueAndType(I.getOperand(0), InstID, Vals);3044pushValue(I.getOperand(1), InstID, Vals);3045pushValueAndType(I.getOperand(2), InstID, Vals);3046break;3047case Instruction::ShuffleVector:3048Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;3049pushValueAndType(I.getOperand(0), InstID, Vals);3050pushValue(I.getOperand(1), InstID, Vals);3051pushValue(cast<ShuffleVectorInst>(I).getShuffleMaskForBitcode(), InstID,3052Vals);3053break;3054case Instruction::ICmp:3055case Instruction::FCmp: {3056// compare returning Int1Ty or vector of Int1Ty3057Code = bitc::FUNC_CODE_INST_CMP2;3058pushValueAndType(I.getOperand(0), InstID, Vals);3059pushValue(I.getOperand(1), InstID, Vals);3060Vals.push_back(cast<CmpInst>(I).getPredicate());3061uint64_t Flags = getOptimizationFlags(&I);3062if (Flags != 0)3063Vals.push_back(Flags);3064break;3065}30663067case Instruction::Ret:3068{3069Code = bitc::FUNC_CODE_INST_RET;3070unsigned NumOperands = I.getNumOperands();3071if (NumOperands == 0)3072AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;3073else if (NumOperands == 1) {3074if (!pushValueAndType(I.getOperand(0), InstID, Vals))3075AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;3076} else {3077for (unsigned i = 0, e = NumOperands; i != e; ++i)3078pushValueAndType(I.getOperand(i), InstID, Vals);3079}3080}3081break;3082case Instruction::Br:3083{3084Code = bitc::FUNC_CODE_INST_BR;3085const BranchInst &II = cast<BranchInst>(I);3086Vals.push_back(VE.getValueID(II.getSuccessor(0)));3087if (II.isConditional()) {3088Vals.push_back(VE.getValueID(II.getSuccessor(1)));3089pushValue(II.getCondition(), InstID, Vals);3090}3091}3092break;3093case Instruction::Switch:3094{3095Code = bitc::FUNC_CODE_INST_SWITCH;3096const SwitchInst &SI = cast<SwitchInst>(I);3097Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));3098pushValue(SI.getCondition(), InstID, Vals);3099Vals.push_back(VE.getValueID(SI.getDefaultDest()));3100for (auto Case : SI.cases()) {3101Vals.push_back(VE.getValueID(Case.getCaseValue()));3102Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));3103}3104}3105break;3106case Instruction::IndirectBr:3107Code = bitc::FUNC_CODE_INST_INDIRECTBR;3108Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));3109// Encode the address operand as relative, but not the basic blocks.3110pushValue(I.getOperand(0), InstID, Vals);3111for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)3112Vals.push_back(VE.getValueID(I.getOperand(i)));3113break;31143115case Instruction::Invoke: {3116const InvokeInst *II = cast<InvokeInst>(&I);3117const Value *Callee = II->getCalledOperand();3118FunctionType *FTy = II->getFunctionType();31193120if (II->hasOperandBundles())3121writeOperandBundles(*II, InstID);31223123Code = bitc::FUNC_CODE_INST_INVOKE;31243125Vals.push_back(VE.getAttributeListID(II->getAttributes()));3126Vals.push_back(II->getCallingConv() | 1 << 13);3127Vals.push_back(VE.getValueID(II->getNormalDest()));3128Vals.push_back(VE.getValueID(II->getUnwindDest()));3129Vals.push_back(VE.getTypeID(FTy));3130pushValueAndType(Callee, InstID, Vals);31313132// Emit value #'s for the fixed parameters.3133for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)3134pushValue(I.getOperand(i), InstID, Vals); // fixed param.31353136// Emit type/value pairs for varargs params.3137if (FTy->isVarArg()) {3138for (unsigned i = FTy->getNumParams(), e = II->arg_size(); i != e; ++i)3139pushValueAndType(I.getOperand(i), InstID, Vals); // vararg3140}3141break;3142}3143case Instruction::Resume:3144Code = bitc::FUNC_CODE_INST_RESUME;3145pushValueAndType(I.getOperand(0), InstID, Vals);3146break;3147case Instruction::CleanupRet: {3148Code = bitc::FUNC_CODE_INST_CLEANUPRET;3149const auto &CRI = cast<CleanupReturnInst>(I);3150pushValue(CRI.getCleanupPad(), InstID, Vals);3151if (CRI.hasUnwindDest())3152Vals.push_back(VE.getValueID(CRI.getUnwindDest()));3153break;3154}3155case Instruction::CatchRet: {3156Code = bitc::FUNC_CODE_INST_CATCHRET;3157const auto &CRI = cast<CatchReturnInst>(I);3158pushValue(CRI.getCatchPad(), InstID, Vals);3159Vals.push_back(VE.getValueID(CRI.getSuccessor()));3160break;3161}3162case Instruction::CleanupPad:3163case Instruction::CatchPad: {3164const auto &FuncletPad = cast<FuncletPadInst>(I);3165Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD3166: bitc::FUNC_CODE_INST_CLEANUPPAD;3167pushValue(FuncletPad.getParentPad(), InstID, Vals);31683169unsigned NumArgOperands = FuncletPad.arg_size();3170Vals.push_back(NumArgOperands);3171for (unsigned Op = 0; Op != NumArgOperands; ++Op)3172pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);3173break;3174}3175case Instruction::CatchSwitch: {3176Code = bitc::FUNC_CODE_INST_CATCHSWITCH;3177const auto &CatchSwitch = cast<CatchSwitchInst>(I);31783179pushValue(CatchSwitch.getParentPad(), InstID, Vals);31803181unsigned NumHandlers = CatchSwitch.getNumHandlers();3182Vals.push_back(NumHandlers);3183for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())3184Vals.push_back(VE.getValueID(CatchPadBB));31853186if (CatchSwitch.hasUnwindDest())3187Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));3188break;3189}3190case Instruction::CallBr: {3191const CallBrInst *CBI = cast<CallBrInst>(&I);3192const Value *Callee = CBI->getCalledOperand();3193FunctionType *FTy = CBI->getFunctionType();31943195if (CBI->hasOperandBundles())3196writeOperandBundles(*CBI, InstID);31973198Code = bitc::FUNC_CODE_INST_CALLBR;31993200Vals.push_back(VE.getAttributeListID(CBI->getAttributes()));32013202Vals.push_back(CBI->getCallingConv() << bitc::CALL_CCONV |32031 << bitc::CALL_EXPLICIT_TYPE);32043205Vals.push_back(VE.getValueID(CBI->getDefaultDest()));3206Vals.push_back(CBI->getNumIndirectDests());3207for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i)3208Vals.push_back(VE.getValueID(CBI->getIndirectDest(i)));32093210Vals.push_back(VE.getTypeID(FTy));3211pushValueAndType(Callee, InstID, Vals);32123213// Emit value #'s for the fixed parameters.3214for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)3215pushValue(I.getOperand(i), InstID, Vals); // fixed param.32163217// Emit type/value pairs for varargs params.3218if (FTy->isVarArg()) {3219for (unsigned i = FTy->getNumParams(), e = CBI->arg_size(); i != e; ++i)3220pushValueAndType(I.getOperand(i), InstID, Vals); // vararg3221}3222break;3223}3224case Instruction::Unreachable:3225Code = bitc::FUNC_CODE_INST_UNREACHABLE;3226AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;3227break;32283229case Instruction::PHI: {3230const PHINode &PN = cast<PHINode>(I);3231Code = bitc::FUNC_CODE_INST_PHI;3232// With the newer instruction encoding, forward references could give3233// negative valued IDs. This is most common for PHIs, so we use3234// signed VBRs.3235SmallVector<uint64_t, 128> Vals64;3236Vals64.push_back(VE.getTypeID(PN.getType()));3237for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {3238pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);3239Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));3240}32413242uint64_t Flags = getOptimizationFlags(&I);3243if (Flags != 0)3244Vals64.push_back(Flags);32453246// Emit a Vals64 vector and exit.3247Stream.EmitRecord(Code, Vals64, AbbrevToUse);3248Vals64.clear();3249return;3250}32513252case Instruction::LandingPad: {3253const LandingPadInst &LP = cast<LandingPadInst>(I);3254Code = bitc::FUNC_CODE_INST_LANDINGPAD;3255Vals.push_back(VE.getTypeID(LP.getType()));3256Vals.push_back(LP.isCleanup());3257Vals.push_back(LP.getNumClauses());3258for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {3259if (LP.isCatch(I))3260Vals.push_back(LandingPadInst::Catch);3261else3262Vals.push_back(LandingPadInst::Filter);3263pushValueAndType(LP.getClause(I), InstID, Vals);3264}3265break;3266}32673268case Instruction::Alloca: {3269Code = bitc::FUNC_CODE_INST_ALLOCA;3270const AllocaInst &AI = cast<AllocaInst>(I);3271Vals.push_back(VE.getTypeID(AI.getAllocatedType()));3272Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));3273Vals.push_back(VE.getValueID(I.getOperand(0))); // size.3274using APV = AllocaPackedValues;3275unsigned Record = 0;3276unsigned EncodedAlign = getEncodedAlign(AI.getAlign());3277Bitfield::set<APV::AlignLower>(3278Record, EncodedAlign & ((1 << APV::AlignLower::Bits) - 1));3279Bitfield::set<APV::AlignUpper>(Record,3280EncodedAlign >> APV::AlignLower::Bits);3281Bitfield::set<APV::UsedWithInAlloca>(Record, AI.isUsedWithInAlloca());3282Bitfield::set<APV::ExplicitType>(Record, true);3283Bitfield::set<APV::SwiftError>(Record, AI.isSwiftError());3284Vals.push_back(Record);32853286unsigned AS = AI.getAddressSpace();3287if (AS != M.getDataLayout().getAllocaAddrSpace())3288Vals.push_back(AS);3289break;3290}32913292case Instruction::Load:3293if (cast<LoadInst>(I).isAtomic()) {3294Code = bitc::FUNC_CODE_INST_LOADATOMIC;3295pushValueAndType(I.getOperand(0), InstID, Vals);3296} else {3297Code = bitc::FUNC_CODE_INST_LOAD;3298if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr3299AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;3300}3301Vals.push_back(VE.getTypeID(I.getType()));3302Vals.push_back(getEncodedAlign(cast<LoadInst>(I).getAlign()));3303Vals.push_back(cast<LoadInst>(I).isVolatile());3304if (cast<LoadInst>(I).isAtomic()) {3305Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));3306Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID()));3307}3308break;3309case Instruction::Store:3310if (cast<StoreInst>(I).isAtomic())3311Code = bitc::FUNC_CODE_INST_STOREATOMIC;3312else3313Code = bitc::FUNC_CODE_INST_STORE;3314pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr3315pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val3316Vals.push_back(getEncodedAlign(cast<StoreInst>(I).getAlign()));3317Vals.push_back(cast<StoreInst>(I).isVolatile());3318if (cast<StoreInst>(I).isAtomic()) {3319Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));3320Vals.push_back(3321getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID()));3322}3323break;3324case Instruction::AtomicCmpXchg:3325Code = bitc::FUNC_CODE_INST_CMPXCHG;3326pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr3327pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.3328pushValue(I.getOperand(2), InstID, Vals); // newval.3329Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());3330Vals.push_back(3331getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));3332Vals.push_back(3333getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID()));3334Vals.push_back(3335getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));3336Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());3337Vals.push_back(getEncodedAlign(cast<AtomicCmpXchgInst>(I).getAlign()));3338break;3339case Instruction::AtomicRMW:3340Code = bitc::FUNC_CODE_INST_ATOMICRMW;3341pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr3342pushValueAndType(I.getOperand(1), InstID, Vals); // valty + val3343Vals.push_back(3344getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));3345Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());3346Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));3347Vals.push_back(3348getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID()));3349Vals.push_back(getEncodedAlign(cast<AtomicRMWInst>(I).getAlign()));3350break;3351case Instruction::Fence:3352Code = bitc::FUNC_CODE_INST_FENCE;3353Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));3354Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID()));3355break;3356case Instruction::Call: {3357const CallInst &CI = cast<CallInst>(I);3358FunctionType *FTy = CI.getFunctionType();33593360if (CI.hasOperandBundles())3361writeOperandBundles(CI, InstID);33623363Code = bitc::FUNC_CODE_INST_CALL;33643365Vals.push_back(VE.getAttributeListID(CI.getAttributes()));33663367unsigned Flags = getOptimizationFlags(&I);3368Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |3369unsigned(CI.isTailCall()) << bitc::CALL_TAIL |3370unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |33711 << bitc::CALL_EXPLICIT_TYPE |3372unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |3373unsigned(Flags != 0) << bitc::CALL_FMF);3374if (Flags != 0)3375Vals.push_back(Flags);33763377Vals.push_back(VE.getTypeID(FTy));3378pushValueAndType(CI.getCalledOperand(), InstID, Vals); // Callee33793380// Emit value #'s for the fixed parameters.3381for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {3382// Check for labels (can happen with asm labels).3383if (FTy->getParamType(i)->isLabelTy())3384Vals.push_back(VE.getValueID(CI.getArgOperand(i)));3385else3386pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.3387}33883389// Emit type/value pairs for varargs params.3390if (FTy->isVarArg()) {3391for (unsigned i = FTy->getNumParams(), e = CI.arg_size(); i != e; ++i)3392pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs3393}3394break;3395}3396case Instruction::VAArg:3397Code = bitc::FUNC_CODE_INST_VAARG;3398Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty3399pushValue(I.getOperand(0), InstID, Vals); // valist.3400Vals.push_back(VE.getTypeID(I.getType())); // restype.3401break;3402case Instruction::Freeze:3403Code = bitc::FUNC_CODE_INST_FREEZE;3404pushValueAndType(I.getOperand(0), InstID, Vals);3405break;3406}34073408Stream.EmitRecord(Code, Vals, AbbrevToUse);3409Vals.clear();3410}34113412/// Write a GlobalValue VST to the module. The purpose of this data structure is3413/// to allow clients to efficiently find the function body.3414void ModuleBitcodeWriter::writeGlobalValueSymbolTable(3415DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {3416// Get the offset of the VST we are writing, and backpatch it into3417// the VST forward declaration record.3418uint64_t VSTOffset = Stream.GetCurrentBitNo();3419// The BitcodeStartBit was the stream offset of the identification block.3420VSTOffset -= bitcodeStartBit();3421assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");3422// Note that we add 1 here because the offset is relative to one word3423// before the start of the identification block, which was historically3424// always the start of the regular bitcode header.3425Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);34263427Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);34283429auto Abbv = std::make_shared<BitCodeAbbrev>();3430Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));3431Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id3432Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset3433unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));34343435for (const Function &F : M) {3436uint64_t Record[2];34373438if (F.isDeclaration())3439continue;34403441Record[0] = VE.getValueID(&F);34423443// Save the word offset of the function (from the start of the3444// actual bitcode written to the stream).3445uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit();3446assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");3447// Note that we add 1 here because the offset is relative to one word3448// before the start of the identification block, which was historically3449// always the start of the regular bitcode header.3450Record[1] = BitcodeIndex / 32 + 1;34513452Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev);3453}34543455Stream.ExitBlock();3456}34573458/// Emit names for arguments, instructions and basic blocks in a function.3459void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(3460const ValueSymbolTable &VST) {3461if (VST.empty())3462return;34633464Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);34653466// FIXME: Set up the abbrev, we know how many values there are!3467// FIXME: We know if the type names can use 7-bit ascii.3468SmallVector<uint64_t, 64> NameVals;34693470for (const ValueName &Name : VST) {3471// Figure out the encoding to use for the name.3472StringEncoding Bits = getStringEncoding(Name.getKey());34733474unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;3475NameVals.push_back(VE.getValueID(Name.getValue()));34763477// VST_CODE_ENTRY: [valueid, namechar x N]3478// VST_CODE_BBENTRY: [bbid, namechar x N]3479unsigned Code;3480if (isa<BasicBlock>(Name.getValue())) {3481Code = bitc::VST_CODE_BBENTRY;3482if (Bits == SE_Char6)3483AbbrevToUse = VST_BBENTRY_6_ABBREV;3484} else {3485Code = bitc::VST_CODE_ENTRY;3486if (Bits == SE_Char6)3487AbbrevToUse = VST_ENTRY_6_ABBREV;3488else if (Bits == SE_Fixed7)3489AbbrevToUse = VST_ENTRY_7_ABBREV;3490}34913492for (const auto P : Name.getKey())3493NameVals.push_back((unsigned char)P);34943495// Emit the finished record.3496Stream.EmitRecord(Code, NameVals, AbbrevToUse);3497NameVals.clear();3498}34993500Stream.ExitBlock();3501}35023503void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {3504assert(Order.Shuffle.size() >= 2 && "Shuffle too small");3505unsigned Code;3506if (isa<BasicBlock>(Order.V))3507Code = bitc::USELIST_CODE_BB;3508else3509Code = bitc::USELIST_CODE_DEFAULT;35103511SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());3512Record.push_back(VE.getValueID(Order.V));3513Stream.EmitRecord(Code, Record);3514}35153516void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {3517assert(VE.shouldPreserveUseListOrder() &&3518"Expected to be preserving use-list order");35193520auto hasMore = [&]() {3521return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;3522};3523if (!hasMore())3524// Nothing to do.3525return;35263527Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);3528while (hasMore()) {3529writeUseList(std::move(VE.UseListOrders.back()));3530VE.UseListOrders.pop_back();3531}3532Stream.ExitBlock();3533}35343535/// Emit a function body to the module stream.3536void ModuleBitcodeWriter::writeFunction(3537const Function &F,3538DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {3539// Save the bitcode index of the start of this function block for recording3540// in the VST.3541FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();35423543Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);3544VE.incorporateFunction(F);35453546SmallVector<unsigned, 64> Vals;35473548// Emit the number of basic blocks, so the reader can create them ahead of3549// time.3550Vals.push_back(VE.getBasicBlocks().size());3551Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);3552Vals.clear();35533554// If there are function-local constants, emit them now.3555unsigned CstStart, CstEnd;3556VE.getFunctionConstantRange(CstStart, CstEnd);3557writeConstants(CstStart, CstEnd, false);35583559// If there is function-local metadata, emit it now.3560writeFunctionMetadata(F);35613562// Keep a running idea of what the instruction ID is.3563unsigned InstID = CstEnd;35643565bool NeedsMetadataAttachment = F.hasMetadata();35663567DILocation *LastDL = nullptr;3568SmallSetVector<Function *, 4> BlockAddressUsers;35693570// Finally, emit all the instructions, in order.3571for (const BasicBlock &BB : F) {3572for (const Instruction &I : BB) {3573writeInstruction(I, InstID, Vals);35743575if (!I.getType()->isVoidTy())3576++InstID;35773578// If the instruction has metadata, write a metadata attachment later.3579NeedsMetadataAttachment |= I.hasMetadataOtherThanDebugLoc();35803581// If the instruction has a debug location, emit it.3582if (DILocation *DL = I.getDebugLoc()) {3583if (DL == LastDL) {3584// Just repeat the same debug loc as last time.3585Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);3586} else {3587Vals.push_back(DL->getLine());3588Vals.push_back(DL->getColumn());3589Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));3590Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));3591Vals.push_back(DL->isImplicitCode());3592Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);3593Vals.clear();3594LastDL = DL;3595}3596}35973598// If the instruction has DbgRecords attached to it, emit them. Note that3599// they come after the instruction so that it's easy to attach them again3600// when reading the bitcode, even though conceptually the debug locations3601// start "before" the instruction.3602if (I.hasDbgRecords() && WriteNewDbgInfoFormatToBitcode) {3603/// Try to push the value only (unwrapped), otherwise push the3604/// metadata wrapped value. Returns true if the value was pushed3605/// without the ValueAsMetadata wrapper.3606auto PushValueOrMetadata = [&Vals, InstID,3607this](Metadata *RawLocation) {3608assert(RawLocation &&3609"RawLocation unexpectedly null in DbgVariableRecord");3610if (ValueAsMetadata *VAM = dyn_cast<ValueAsMetadata>(RawLocation)) {3611SmallVector<unsigned, 2> ValAndType;3612// If the value is a fwd-ref the type is also pushed. We don't3613// want the type, so fwd-refs are kept wrapped (pushValueAndType3614// returns false if the value is pushed without type).3615if (!pushValueAndType(VAM->getValue(), InstID, ValAndType)) {3616Vals.push_back(ValAndType[0]);3617return true;3618}3619}3620// The metadata is a DIArgList, or ValueAsMetadata wrapping a3621// fwd-ref. Push the metadata ID.3622Vals.push_back(VE.getMetadataID(RawLocation));3623return false;3624};36253626// Write out non-instruction debug information attached to this3627// instruction. Write it after the instruction so that it's easy to3628// re-attach to the instruction reading the records in.3629for (DbgRecord &DR : I.DebugMarker->getDbgRecordRange()) {3630if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) {3631Vals.push_back(VE.getMetadataID(&*DLR->getDebugLoc()));3632Vals.push_back(VE.getMetadataID(DLR->getLabel()));3633Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_RECORD_LABEL, Vals);3634Vals.clear();3635continue;3636}36373638// First 3 fields are common to all kinds:3639// DILocation, DILocalVariable, DIExpression3640// dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE)3641// ..., LocationMetadata3642// dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE - abbrev'd)3643// ..., Value3644// dbg_declare (FUNC_CODE_DEBUG_RECORD_DECLARE)3645// ..., LocationMetadata3646// dbg_assign (FUNC_CODE_DEBUG_RECORD_ASSIGN)3647// ..., LocationMetadata, DIAssignID, DIExpression, LocationMetadata3648DbgVariableRecord &DVR = cast<DbgVariableRecord>(DR);3649Vals.push_back(VE.getMetadataID(&*DVR.getDebugLoc()));3650Vals.push_back(VE.getMetadataID(DVR.getVariable()));3651Vals.push_back(VE.getMetadataID(DVR.getExpression()));3652if (DVR.isDbgValue()) {3653if (PushValueOrMetadata(DVR.getRawLocation()))3654Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE, Vals,3655FUNCTION_DEBUG_RECORD_VALUE_ABBREV);3656else3657Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_RECORD_VALUE, Vals);3658} else if (DVR.isDbgDeclare()) {3659Vals.push_back(VE.getMetadataID(DVR.getRawLocation()));3660Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_RECORD_DECLARE, Vals);3661} else {3662assert(DVR.isDbgAssign() && "Unexpected DbgRecord kind");3663Vals.push_back(VE.getMetadataID(DVR.getRawLocation()));3664Vals.push_back(VE.getMetadataID(DVR.getAssignID()));3665Vals.push_back(VE.getMetadataID(DVR.getAddressExpression()));3666Vals.push_back(VE.getMetadataID(DVR.getRawAddress()));3667Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_RECORD_ASSIGN, Vals);3668}3669Vals.clear();3670}3671}3672}36733674if (BlockAddress *BA = BlockAddress::lookup(&BB)) {3675SmallVector<Value *> Worklist{BA};3676SmallPtrSet<Value *, 8> Visited{BA};3677while (!Worklist.empty()) {3678Value *V = Worklist.pop_back_val();3679for (User *U : V->users()) {3680if (auto *I = dyn_cast<Instruction>(U)) {3681Function *P = I->getFunction();3682if (P != &F)3683BlockAddressUsers.insert(P);3684} else if (isa<Constant>(U) && !isa<GlobalValue>(U) &&3685Visited.insert(U).second)3686Worklist.push_back(U);3687}3688}3689}3690}36913692if (!BlockAddressUsers.empty()) {3693Vals.resize(BlockAddressUsers.size());3694for (auto I : llvm::enumerate(BlockAddressUsers))3695Vals[I.index()] = VE.getValueID(I.value());3696Stream.EmitRecord(bitc::FUNC_CODE_BLOCKADDR_USERS, Vals);3697Vals.clear();3698}36993700// Emit names for all the instructions etc.3701if (auto *Symtab = F.getValueSymbolTable())3702writeFunctionLevelValueSymbolTable(*Symtab);37033704if (NeedsMetadataAttachment)3705writeFunctionMetadataAttachment(F);3706if (VE.shouldPreserveUseListOrder())3707writeUseListBlock(&F);3708VE.purgeFunction();3709Stream.ExitBlock();3710}37113712// Emit blockinfo, which defines the standard abbreviations etc.3713void ModuleBitcodeWriter::writeBlockInfo() {3714// We only want to emit block info records for blocks that have multiple3715// instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.3716// Other blocks can define their abbrevs inline.3717Stream.EnterBlockInfoBlock();37183719{ // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.3720auto Abbv = std::make_shared<BitCodeAbbrev>();3721Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));3722Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));3723Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));3724Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));3725if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=3726VST_ENTRY_8_ABBREV)3727llvm_unreachable("Unexpected abbrev ordering!");3728}37293730{ // 7-bit fixed width VST_CODE_ENTRY strings.3731auto Abbv = std::make_shared<BitCodeAbbrev>();3732Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));3733Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));3734Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));3735Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));3736if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=3737VST_ENTRY_7_ABBREV)3738llvm_unreachable("Unexpected abbrev ordering!");3739}3740{ // 6-bit char6 VST_CODE_ENTRY strings.3741auto Abbv = std::make_shared<BitCodeAbbrev>();3742Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));3743Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));3744Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));3745Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));3746if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=3747VST_ENTRY_6_ABBREV)3748llvm_unreachable("Unexpected abbrev ordering!");3749}3750{ // 6-bit char6 VST_CODE_BBENTRY strings.3751auto Abbv = std::make_shared<BitCodeAbbrev>();3752Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));3753Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));3754Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));3755Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));3756if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=3757VST_BBENTRY_6_ABBREV)3758llvm_unreachable("Unexpected abbrev ordering!");3759}37603761{ // SETTYPE abbrev for CONSTANTS_BLOCK.3762auto Abbv = std::make_shared<BitCodeAbbrev>();3763Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));3764Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,3765VE.computeBitsRequiredForTypeIndices()));3766if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=3767CONSTANTS_SETTYPE_ABBREV)3768llvm_unreachable("Unexpected abbrev ordering!");3769}37703771{ // INTEGER abbrev for CONSTANTS_BLOCK.3772auto Abbv = std::make_shared<BitCodeAbbrev>();3773Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));3774Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));3775if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=3776CONSTANTS_INTEGER_ABBREV)3777llvm_unreachable("Unexpected abbrev ordering!");3778}37793780{ // CE_CAST abbrev for CONSTANTS_BLOCK.3781auto Abbv = std::make_shared<BitCodeAbbrev>();3782Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));3783Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc3784Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid3785VE.computeBitsRequiredForTypeIndices()));3786Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id37873788if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=3789CONSTANTS_CE_CAST_Abbrev)3790llvm_unreachable("Unexpected abbrev ordering!");3791}3792{ // NULL abbrev for CONSTANTS_BLOCK.3793auto Abbv = std::make_shared<BitCodeAbbrev>();3794Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));3795if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=3796CONSTANTS_NULL_Abbrev)3797llvm_unreachable("Unexpected abbrev ordering!");3798}37993800// FIXME: This should only use space for first class types!38013802{ // INST_LOAD abbrev for FUNCTION_BLOCK.3803auto Abbv = std::make_shared<BitCodeAbbrev>();3804Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));3805Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr3806Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty3807VE.computeBitsRequiredForTypeIndices()));3808Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align3809Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile3810if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=3811FUNCTION_INST_LOAD_ABBREV)3812llvm_unreachable("Unexpected abbrev ordering!");3813}3814{ // INST_UNOP abbrev for FUNCTION_BLOCK.3815auto Abbv = std::make_shared<BitCodeAbbrev>();3816Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP));3817Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS3818Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc3819if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=3820FUNCTION_INST_UNOP_ABBREV)3821llvm_unreachable("Unexpected abbrev ordering!");3822}3823{ // INST_UNOP_FLAGS abbrev for FUNCTION_BLOCK.3824auto Abbv = std::make_shared<BitCodeAbbrev>();3825Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP));3826Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS3827Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc3828Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags3829if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=3830FUNCTION_INST_UNOP_FLAGS_ABBREV)3831llvm_unreachable("Unexpected abbrev ordering!");3832}3833{ // INST_BINOP abbrev for FUNCTION_BLOCK.3834auto Abbv = std::make_shared<BitCodeAbbrev>();3835Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));3836Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS3837Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS3838Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc3839if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=3840FUNCTION_INST_BINOP_ABBREV)3841llvm_unreachable("Unexpected abbrev ordering!");3842}3843{ // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.3844auto Abbv = std::make_shared<BitCodeAbbrev>();3845Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));3846Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS3847Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS3848Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc3849Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags3850if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=3851FUNCTION_INST_BINOP_FLAGS_ABBREV)3852llvm_unreachable("Unexpected abbrev ordering!");3853}3854{ // INST_CAST abbrev for FUNCTION_BLOCK.3855auto Abbv = std::make_shared<BitCodeAbbrev>();3856Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));3857Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal3858Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty3859VE.computeBitsRequiredForTypeIndices()));3860Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc3861if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=3862FUNCTION_INST_CAST_ABBREV)3863llvm_unreachable("Unexpected abbrev ordering!");3864}3865{ // INST_CAST_FLAGS abbrev for FUNCTION_BLOCK.3866auto Abbv = std::make_shared<BitCodeAbbrev>();3867Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));3868Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal3869Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty3870VE.computeBitsRequiredForTypeIndices()));3871Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc3872Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags3873if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=3874FUNCTION_INST_CAST_FLAGS_ABBREV)3875llvm_unreachable("Unexpected abbrev ordering!");3876}38773878{ // INST_RET abbrev for FUNCTION_BLOCK.3879auto Abbv = std::make_shared<BitCodeAbbrev>();3880Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));3881if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=3882FUNCTION_INST_RET_VOID_ABBREV)3883llvm_unreachable("Unexpected abbrev ordering!");3884}3885{ // INST_RET abbrev for FUNCTION_BLOCK.3886auto Abbv = std::make_shared<BitCodeAbbrev>();3887Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));3888Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID3889if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=3890FUNCTION_INST_RET_VAL_ABBREV)3891llvm_unreachable("Unexpected abbrev ordering!");3892}3893{ // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.3894auto Abbv = std::make_shared<BitCodeAbbrev>();3895Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));3896if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=3897FUNCTION_INST_UNREACHABLE_ABBREV)3898llvm_unreachable("Unexpected abbrev ordering!");3899}3900{3901auto Abbv = std::make_shared<BitCodeAbbrev>();3902Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));3903Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));3904Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty3905Log2_32_Ceil(VE.getTypes().size() + 1)));3906Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));3907Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));3908if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=3909FUNCTION_INST_GEP_ABBREV)3910llvm_unreachable("Unexpected abbrev ordering!");3911}3912{3913auto Abbv = std::make_shared<BitCodeAbbrev>();3914Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE));3915Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // dbgloc3916Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // var3917Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // expr3918Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // val3919if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=3920FUNCTION_DEBUG_RECORD_VALUE_ABBREV)3921llvm_unreachable("Unexpected abbrev ordering! 1");3922}3923Stream.ExitBlock();3924}39253926/// Write the module path strings, currently only used when generating3927/// a combined index file.3928void IndexBitcodeWriter::writeModStrings() {3929Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);39303931// TODO: See which abbrev sizes we actually need to emit39323933// 8-bit fixed-width MST_ENTRY strings.3934auto Abbv = std::make_shared<BitCodeAbbrev>();3935Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));3936Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));3937Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));3938Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));3939unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));39403941// 7-bit fixed width MST_ENTRY strings.3942Abbv = std::make_shared<BitCodeAbbrev>();3943Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));3944Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));3945Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));3946Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));3947unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));39483949// 6-bit char6 MST_ENTRY strings.3950Abbv = std::make_shared<BitCodeAbbrev>();3951Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));3952Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));3953Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));3954Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));3955unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));39563957// Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.3958Abbv = std::make_shared<BitCodeAbbrev>();3959Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH));3960Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));3961Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));3962Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));3963Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));3964Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));3965unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));39663967SmallVector<unsigned, 64> Vals;3968forEachModule([&](const StringMapEntry<ModuleHash> &MPSE) {3969StringRef Key = MPSE.getKey();3970const auto &Hash = MPSE.getValue();3971StringEncoding Bits = getStringEncoding(Key);3972unsigned AbbrevToUse = Abbrev8Bit;3973if (Bits == SE_Char6)3974AbbrevToUse = Abbrev6Bit;3975else if (Bits == SE_Fixed7)3976AbbrevToUse = Abbrev7Bit;39773978auto ModuleId = ModuleIdMap.size();3979ModuleIdMap[Key] = ModuleId;3980Vals.push_back(ModuleId);3981Vals.append(Key.begin(), Key.end());39823983// Emit the finished record.3984Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);39853986// Emit an optional hash for the module now3987if (llvm::any_of(Hash, [](uint32_t H) { return H; })) {3988Vals.assign(Hash.begin(), Hash.end());3989// Emit the hash record.3990Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);3991}39923993Vals.clear();3994});3995Stream.ExitBlock();3996}39973998/// Write the function type metadata related records that need to appear before3999/// a function summary entry (whether per-module or combined).4000template <typename Fn>4001static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream,4002FunctionSummary *FS,4003Fn GetValueID) {4004if (!FS->type_tests().empty())4005Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());40064007SmallVector<uint64_t, 64> Record;40084009auto WriteVFuncIdVec = [&](uint64_t Ty,4010ArrayRef<FunctionSummary::VFuncId> VFs) {4011if (VFs.empty())4012return;4013Record.clear();4014for (auto &VF : VFs) {4015Record.push_back(VF.GUID);4016Record.push_back(VF.Offset);4017}4018Stream.EmitRecord(Ty, Record);4019};40204021WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,4022FS->type_test_assume_vcalls());4023WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,4024FS->type_checked_load_vcalls());40254026auto WriteConstVCallVec = [&](uint64_t Ty,4027ArrayRef<FunctionSummary::ConstVCall> VCs) {4028for (auto &VC : VCs) {4029Record.clear();4030Record.push_back(VC.VFunc.GUID);4031Record.push_back(VC.VFunc.Offset);4032llvm::append_range(Record, VC.Args);4033Stream.EmitRecord(Ty, Record);4034}4035};40364037WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,4038FS->type_test_assume_const_vcalls());4039WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,4040FS->type_checked_load_const_vcalls());40414042auto WriteRange = [&](ConstantRange Range) {4043Range = Range.sextOrTrunc(FunctionSummary::ParamAccess::RangeWidth);4044assert(Range.getLower().getNumWords() == 1);4045assert(Range.getUpper().getNumWords() == 1);4046emitSignedInt64(Record, *Range.getLower().getRawData());4047emitSignedInt64(Record, *Range.getUpper().getRawData());4048};40494050if (!FS->paramAccesses().empty()) {4051Record.clear();4052for (auto &Arg : FS->paramAccesses()) {4053size_t UndoSize = Record.size();4054Record.push_back(Arg.ParamNo);4055WriteRange(Arg.Use);4056Record.push_back(Arg.Calls.size());4057for (auto &Call : Arg.Calls) {4058Record.push_back(Call.ParamNo);4059std::optional<unsigned> ValueID = GetValueID(Call.Callee);4060if (!ValueID) {4061// If ValueID is unknown we can't drop just this call, we must drop4062// entire parameter.4063Record.resize(UndoSize);4064break;4065}4066Record.push_back(*ValueID);4067WriteRange(Call.Offsets);4068}4069}4070if (!Record.empty())4071Stream.EmitRecord(bitc::FS_PARAM_ACCESS, Record);4072}4073}40744075/// Collect type IDs from type tests used by function.4076static void4077getReferencedTypeIds(FunctionSummary *FS,4078std::set<GlobalValue::GUID> &ReferencedTypeIds) {4079if (!FS->type_tests().empty())4080for (auto &TT : FS->type_tests())4081ReferencedTypeIds.insert(TT);40824083auto GetReferencedTypesFromVFuncIdVec =4084[&](ArrayRef<FunctionSummary::VFuncId> VFs) {4085for (auto &VF : VFs)4086ReferencedTypeIds.insert(VF.GUID);4087};40884089GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls());4090GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls());40914092auto GetReferencedTypesFromConstVCallVec =4093[&](ArrayRef<FunctionSummary::ConstVCall> VCs) {4094for (auto &VC : VCs)4095ReferencedTypeIds.insert(VC.VFunc.GUID);4096};40974098GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls());4099GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls());4100}41014102static void writeWholeProgramDevirtResolutionByArg(4103SmallVector<uint64_t, 64> &NameVals, const std::vector<uint64_t> &args,4104const WholeProgramDevirtResolution::ByArg &ByArg) {4105NameVals.push_back(args.size());4106llvm::append_range(NameVals, args);41074108NameVals.push_back(ByArg.TheKind);4109NameVals.push_back(ByArg.Info);4110NameVals.push_back(ByArg.Byte);4111NameVals.push_back(ByArg.Bit);4112}41134114static void writeWholeProgramDevirtResolution(4115SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,4116uint64_t Id, const WholeProgramDevirtResolution &Wpd) {4117NameVals.push_back(Id);41184119NameVals.push_back(Wpd.TheKind);4120NameVals.push_back(StrtabBuilder.add(Wpd.SingleImplName));4121NameVals.push_back(Wpd.SingleImplName.size());41224123NameVals.push_back(Wpd.ResByArg.size());4124for (auto &A : Wpd.ResByArg)4125writeWholeProgramDevirtResolutionByArg(NameVals, A.first, A.second);4126}41274128static void writeTypeIdSummaryRecord(SmallVector<uint64_t, 64> &NameVals,4129StringTableBuilder &StrtabBuilder,4130const std::string &Id,4131const TypeIdSummary &Summary) {4132NameVals.push_back(StrtabBuilder.add(Id));4133NameVals.push_back(Id.size());41344135NameVals.push_back(Summary.TTRes.TheKind);4136NameVals.push_back(Summary.TTRes.SizeM1BitWidth);4137NameVals.push_back(Summary.TTRes.AlignLog2);4138NameVals.push_back(Summary.TTRes.SizeM1);4139NameVals.push_back(Summary.TTRes.BitMask);4140NameVals.push_back(Summary.TTRes.InlineBits);41414142for (auto &W : Summary.WPDRes)4143writeWholeProgramDevirtResolution(NameVals, StrtabBuilder, W.first,4144W.second);4145}41464147static void writeTypeIdCompatibleVtableSummaryRecord(4148SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,4149const std::string &Id, const TypeIdCompatibleVtableInfo &Summary,4150ValueEnumerator &VE) {4151NameVals.push_back(StrtabBuilder.add(Id));4152NameVals.push_back(Id.size());41534154for (auto &P : Summary) {4155NameVals.push_back(P.AddressPointOffset);4156NameVals.push_back(VE.getValueID(P.VTableVI.getValue()));4157}4158}41594160static void writeFunctionHeapProfileRecords(4161BitstreamWriter &Stream, FunctionSummary *FS, unsigned CallsiteAbbrev,4162unsigned AllocAbbrev, bool PerModule,4163std::function<unsigned(const ValueInfo &VI)> GetValueID,4164std::function<unsigned(unsigned)> GetStackIndex) {4165SmallVector<uint64_t> Record;41664167for (auto &CI : FS->callsites()) {4168Record.clear();4169// Per module callsite clones should always have a single entry of4170// value 0.4171assert(!PerModule || (CI.Clones.size() == 1 && CI.Clones[0] == 0));4172Record.push_back(GetValueID(CI.Callee));4173if (!PerModule) {4174Record.push_back(CI.StackIdIndices.size());4175Record.push_back(CI.Clones.size());4176}4177for (auto Id : CI.StackIdIndices)4178Record.push_back(GetStackIndex(Id));4179if (!PerModule) {4180for (auto V : CI.Clones)4181Record.push_back(V);4182}4183Stream.EmitRecord(PerModule ? bitc::FS_PERMODULE_CALLSITE_INFO4184: bitc::FS_COMBINED_CALLSITE_INFO,4185Record, CallsiteAbbrev);4186}41874188for (auto &AI : FS->allocs()) {4189Record.clear();4190// Per module alloc versions should always have a single entry of4191// value 0.4192assert(!PerModule || (AI.Versions.size() == 1 && AI.Versions[0] == 0));4193Record.push_back(AI.MIBs.size());4194if (!PerModule)4195Record.push_back(AI.Versions.size());4196for (auto &MIB : AI.MIBs) {4197Record.push_back((uint8_t)MIB.AllocType);4198Record.push_back(MIB.StackIdIndices.size());4199for (auto Id : MIB.StackIdIndices)4200Record.push_back(GetStackIndex(Id));4201}4202if (!PerModule) {4203for (auto V : AI.Versions)4204Record.push_back(V);4205}4206assert(AI.TotalSizes.empty() || AI.TotalSizes.size() == AI.MIBs.size());4207if (!AI.TotalSizes.empty()) {4208for (auto Size : AI.TotalSizes)4209Record.push_back(Size);4210}4211Stream.EmitRecord(PerModule ? bitc::FS_PERMODULE_ALLOC_INFO4212: bitc::FS_COMBINED_ALLOC_INFO,4213Record, AllocAbbrev);4214}4215}42164217// Helper to emit a single function summary record.4218void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(4219SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,4220unsigned ValueID, unsigned FSCallsRelBFAbbrev,4221unsigned FSCallsProfileAbbrev, unsigned CallsiteAbbrev,4222unsigned AllocAbbrev, const Function &F) {4223NameVals.push_back(ValueID);42244225FunctionSummary *FS = cast<FunctionSummary>(Summary);42264227writeFunctionTypeMetadataRecords(4228Stream, FS, [&](const ValueInfo &VI) -> std::optional<unsigned> {4229return {VE.getValueID(VI.getValue())};4230});42314232writeFunctionHeapProfileRecords(4233Stream, FS, CallsiteAbbrev, AllocAbbrev,4234/*PerModule*/ true,4235/*GetValueId*/ [&](const ValueInfo &VI) { return getValueId(VI); },4236/*GetStackIndex*/ [&](unsigned I) { return I; });42374238auto SpecialRefCnts = FS->specialRefCounts();4239NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));4240NameVals.push_back(FS->instCount());4241NameVals.push_back(getEncodedFFlags(FS->fflags()));4242NameVals.push_back(FS->refs().size());4243NameVals.push_back(SpecialRefCnts.first); // rorefcnt4244NameVals.push_back(SpecialRefCnts.second); // worefcnt42454246for (auto &RI : FS->refs())4247NameVals.push_back(getValueId(RI));42484249const bool UseRelBFRecord =4250WriteRelBFToSummary && !F.hasProfileData() &&4251ForceSummaryEdgesCold == FunctionSummary::FSHT_None;4252for (auto &ECI : FS->calls()) {4253NameVals.push_back(getValueId(ECI.first));4254if (UseRelBFRecord)4255NameVals.push_back(getEncodedRelBFCallEdgeInfo(ECI.second));4256else4257NameVals.push_back(getEncodedHotnessCallEdgeInfo(ECI.second));4258}42594260unsigned FSAbbrev =4261(UseRelBFRecord ? FSCallsRelBFAbbrev : FSCallsProfileAbbrev);4262unsigned Code =4263(UseRelBFRecord ? bitc::FS_PERMODULE_RELBF : bitc::FS_PERMODULE_PROFILE);42644265// Emit the finished record.4266Stream.EmitRecord(Code, NameVals, FSAbbrev);4267NameVals.clear();4268}42694270// Collect the global value references in the given variable's initializer,4271// and emit them in a summary record.4272void ModuleBitcodeWriterBase::writeModuleLevelReferences(4273const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,4274unsigned FSModRefsAbbrev, unsigned FSModVTableRefsAbbrev) {4275auto VI = Index->getValueInfo(V.getGUID());4276if (!VI || VI.getSummaryList().empty()) {4277// Only declarations should not have a summary (a declaration might however4278// have a summary if the def was in module level asm).4279assert(V.isDeclaration());4280return;4281}4282auto *Summary = VI.getSummaryList()[0].get();4283NameVals.push_back(VE.getValueID(&V));4284GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);4285NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));4286NameVals.push_back(getEncodedGVarFlags(VS->varflags()));42874288auto VTableFuncs = VS->vTableFuncs();4289if (!VTableFuncs.empty())4290NameVals.push_back(VS->refs().size());42914292unsigned SizeBeforeRefs = NameVals.size();4293for (auto &RI : VS->refs())4294NameVals.push_back(VE.getValueID(RI.getValue()));4295// Sort the refs for determinism output, the vector returned by FS->refs() has4296// been initialized from a DenseSet.4297llvm::sort(drop_begin(NameVals, SizeBeforeRefs));42984299if (VTableFuncs.empty())4300Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals,4301FSModRefsAbbrev);4302else {4303// VTableFuncs pairs should already be sorted by offset.4304for (auto &P : VTableFuncs) {4305NameVals.push_back(VE.getValueID(P.FuncVI.getValue()));4306NameVals.push_back(P.VTableOffset);4307}43084309Stream.EmitRecord(bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS, NameVals,4310FSModVTableRefsAbbrev);4311}4312NameVals.clear();4313}43144315/// Emit the per-module summary section alongside the rest of4316/// the module's bitcode.4317void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {4318// By default we compile with ThinLTO if the module has a summary, but the4319// client can request full LTO with a module flag.4320bool IsThinLTO = true;4321if (auto *MD =4322mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))4323IsThinLTO = MD->getZExtValue();4324Stream.EnterSubblock(IsThinLTO ? bitc::GLOBALVAL_SUMMARY_BLOCK_ID4325: bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID,43264);43274328Stream.EmitRecord(4329bitc::FS_VERSION,4330ArrayRef<uint64_t>{ModuleSummaryIndex::BitcodeSummaryVersion});43314332// Write the index flags.4333uint64_t Flags = 0;4334// Bits 1-3 are set only in the combined index, skip them.4335if (Index->enableSplitLTOUnit())4336Flags |= 0x8;4337if (Index->hasUnifiedLTO())4338Flags |= 0x200;43394340Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Flags});43414342if (Index->begin() == Index->end()) {4343Stream.ExitBlock();4344return;4345}43464347for (const auto &GVI : valueIds()) {4348Stream.EmitRecord(bitc::FS_VALUE_GUID,4349ArrayRef<uint64_t>{GVI.second, GVI.first});4350}43514352if (!Index->stackIds().empty()) {4353auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();4354StackIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_STACK_IDS));4355// numids x stackid4356StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));4357StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));4358unsigned StackIdAbbvId = Stream.EmitAbbrev(std::move(StackIdAbbv));4359Stream.EmitRecord(bitc::FS_STACK_IDS, Index->stackIds(), StackIdAbbvId);4360}43614362// Abbrev for FS_PERMODULE_PROFILE.4363auto Abbv = std::make_shared<BitCodeAbbrev>();4364Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));4365Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid4366Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // flags4367Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount4368Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags4369Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs4370Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt4371Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt4372// numrefs x valueid, n x (valueid, hotness+tailcall flags)4373Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));4374Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));4375unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));43764377// Abbrev for FS_PERMODULE_RELBF.4378Abbv = std::make_shared<BitCodeAbbrev>();4379Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_RELBF));4380Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid4381Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags4382Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount4383Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags4384Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs4385Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt4386Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt4387// numrefs x valueid, n x (valueid, rel_block_freq+tailcall])4388Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));4389Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));4390unsigned FSCallsRelBFAbbrev = Stream.EmitAbbrev(std::move(Abbv));43914392// Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.4393Abbv = std::make_shared<BitCodeAbbrev>();4394Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));4395Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid4396Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags4397Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids4398Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));4399unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));44004401// Abbrev for FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS.4402Abbv = std::make_shared<BitCodeAbbrev>();4403Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS));4404Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid4405Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags4406Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs4407// numrefs x valueid, n x (valueid , offset)4408Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));4409Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));4410unsigned FSModVTableRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));44114412// Abbrev for FS_ALIAS.4413Abbv = std::make_shared<BitCodeAbbrev>();4414Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));4415Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid4416Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags4417Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid4418unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));44194420// Abbrev for FS_TYPE_ID_METADATA4421Abbv = std::make_shared<BitCodeAbbrev>();4422Abbv->Add(BitCodeAbbrevOp(bitc::FS_TYPE_ID_METADATA));4423Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid strtab index4424Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid length4425// n x (valueid , offset)4426Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));4427Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));4428unsigned TypeIdCompatibleVtableAbbrev = Stream.EmitAbbrev(std::move(Abbv));44294430Abbv = std::make_shared<BitCodeAbbrev>();4431Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_CALLSITE_INFO));4432Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid4433// n x stackidindex4434Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));4435Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));4436unsigned CallsiteAbbrev = Stream.EmitAbbrev(std::move(Abbv));44374438Abbv = std::make_shared<BitCodeAbbrev>();4439Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_ALLOC_INFO));4440Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // nummib4441// n x (alloc type, numstackids, numstackids x stackidindex)4442// optional: nummib x total size4443Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));4444Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));4445unsigned AllocAbbrev = Stream.EmitAbbrev(std::move(Abbv));44464447SmallVector<uint64_t, 64> NameVals;4448// Iterate over the list of functions instead of the Index to4449// ensure the ordering is stable.4450for (const Function &F : M) {4451// Summary emission does not support anonymous functions, they have to4452// renamed using the anonymous function renaming pass.4453if (!F.hasName())4454report_fatal_error("Unexpected anonymous function when writing summary");44554456ValueInfo VI = Index->getValueInfo(F.getGUID());4457if (!VI || VI.getSummaryList().empty()) {4458// Only declarations should not have a summary (a declaration might4459// however have a summary if the def was in module level asm).4460assert(F.isDeclaration());4461continue;4462}4463auto *Summary = VI.getSummaryList()[0].get();4464writePerModuleFunctionSummaryRecord(4465NameVals, Summary, VE.getValueID(&F), FSCallsRelBFAbbrev,4466FSCallsProfileAbbrev, CallsiteAbbrev, AllocAbbrev, F);4467}44684469// Capture references from GlobalVariable initializers, which are outside4470// of a function scope.4471for (const GlobalVariable &G : M.globals())4472writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev,4473FSModVTableRefsAbbrev);44744475for (const GlobalAlias &A : M.aliases()) {4476auto *Aliasee = A.getAliaseeObject();4477// Skip ifunc and nameless functions which don't have an entry in the4478// summary.4479if (!Aliasee->hasName() || isa<GlobalIFunc>(Aliasee))4480continue;4481auto AliasId = VE.getValueID(&A);4482auto AliaseeId = VE.getValueID(Aliasee);4483NameVals.push_back(AliasId);4484auto *Summary = Index->getGlobalValueSummary(A);4485AliasSummary *AS = cast<AliasSummary>(Summary);4486NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));4487NameVals.push_back(AliaseeId);4488Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);4489NameVals.clear();4490}44914492for (auto &S : Index->typeIdCompatibleVtableMap()) {4493writeTypeIdCompatibleVtableSummaryRecord(NameVals, StrtabBuilder, S.first,4494S.second, VE);4495Stream.EmitRecord(bitc::FS_TYPE_ID_METADATA, NameVals,4496TypeIdCompatibleVtableAbbrev);4497NameVals.clear();4498}44994500if (Index->getBlockCount())4501Stream.EmitRecord(bitc::FS_BLOCK_COUNT,4502ArrayRef<uint64_t>{Index->getBlockCount()});45034504Stream.ExitBlock();4505}45064507/// Emit the combined summary section into the combined index file.4508void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {4509Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 4);4510Stream.EmitRecord(4511bitc::FS_VERSION,4512ArrayRef<uint64_t>{ModuleSummaryIndex::BitcodeSummaryVersion});45134514// Write the index flags.4515Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Index.getFlags()});45164517for (const auto &GVI : valueIds()) {4518Stream.EmitRecord(bitc::FS_VALUE_GUID,4519ArrayRef<uint64_t>{GVI.second, GVI.first});4520}45214522// Write the stack ids used by this index, which will be a subset of those in4523// the full index in the case of distributed indexes.4524if (!StackIds.empty()) {4525auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();4526StackIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_STACK_IDS));4527// numids x stackid4528StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));4529StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));4530unsigned StackIdAbbvId = Stream.EmitAbbrev(std::move(StackIdAbbv));4531Stream.EmitRecord(bitc::FS_STACK_IDS, StackIds, StackIdAbbvId);4532}45334534// Abbrev for FS_COMBINED_PROFILE.4535auto Abbv = std::make_shared<BitCodeAbbrev>();4536Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));4537Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid4538Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid4539Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags4540Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount4541Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags4542Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // entrycount4543Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs4544Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt4545Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt4546// numrefs x valueid, n x (valueid, hotness+tailcall flags)4547Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));4548Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));4549unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));45504551// Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.4552Abbv = std::make_shared<BitCodeAbbrev>();4553Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));4554Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid4555Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid4556Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags4557Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids4558Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));4559unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));45604561// Abbrev for FS_COMBINED_ALIAS.4562Abbv = std::make_shared<BitCodeAbbrev>();4563Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS));4564Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid4565Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid4566Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags4567Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid4568unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));45694570Abbv = std::make_shared<BitCodeAbbrev>();4571Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_CALLSITE_INFO));4572Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid4573Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numstackindices4574Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numver4575// numstackindices x stackidindex, numver x version4576Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));4577Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));4578unsigned CallsiteAbbrev = Stream.EmitAbbrev(std::move(Abbv));45794580Abbv = std::make_shared<BitCodeAbbrev>();4581Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALLOC_INFO));4582Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // nummib4583Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numver4584// nummib x (alloc type, numstackids, numstackids x stackidindex),4585// numver x version4586// optional: nummib x total size4587Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));4588Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));4589unsigned AllocAbbrev = Stream.EmitAbbrev(std::move(Abbv));45904591auto shouldImportValueAsDecl = [&](GlobalValueSummary *GVS) -> bool {4592if (DecSummaries == nullptr)4593return false;4594return DecSummaries->count(GVS);4595};45964597// The aliases are emitted as a post-pass, and will point to the value4598// id of the aliasee. Save them in a vector for post-processing.4599SmallVector<AliasSummary *, 64> Aliases;46004601// Save the value id for each summary for alias emission.4602DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;46034604SmallVector<uint64_t, 64> NameVals;46054606// Set that will be populated during call to writeFunctionTypeMetadataRecords4607// with the type ids referenced by this index file.4608std::set<GlobalValue::GUID> ReferencedTypeIds;46094610// For local linkage, we also emit the original name separately4611// immediately after the record.4612auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {4613// We don't need to emit the original name if we are writing the index for4614// distributed backends (in which case ModuleToSummariesForIndex is4615// non-null). The original name is only needed during the thin link, since4616// for SamplePGO the indirect call targets for local functions have4617// have the original name annotated in profile.4618// Continue to emit it when writing out the entire combined index, which is4619// used in testing the thin link via llvm-lto.4620if (ModuleToSummariesForIndex || !GlobalValue::isLocalLinkage(S.linkage()))4621return;4622NameVals.push_back(S.getOriginalName());4623Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals);4624NameVals.clear();4625};46264627std::set<GlobalValue::GUID> DefOrUseGUIDs;4628forEachSummary([&](GVInfo I, bool IsAliasee) {4629GlobalValueSummary *S = I.second;4630assert(S);4631DefOrUseGUIDs.insert(I.first);4632for (const ValueInfo &VI : S->refs())4633DefOrUseGUIDs.insert(VI.getGUID());46344635auto ValueId = getValueId(I.first);4636assert(ValueId);4637SummaryToValueIdMap[S] = *ValueId;46384639// If this is invoked for an aliasee, we want to record the above4640// mapping, but then not emit a summary entry (if the aliasee is4641// to be imported, we will invoke this separately with IsAliasee=false).4642if (IsAliasee)4643return;46444645if (auto *AS = dyn_cast<AliasSummary>(S)) {4646// Will process aliases as a post-pass because the reader wants all4647// global to be loaded first.4648Aliases.push_back(AS);4649return;4650}46514652if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {4653NameVals.push_back(*ValueId);4654assert(ModuleIdMap.count(VS->modulePath()));4655NameVals.push_back(ModuleIdMap[VS->modulePath()]);4656NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));4657NameVals.push_back(getEncodedGVarFlags(VS->varflags()));4658for (auto &RI : VS->refs()) {4659auto RefValueId = getValueId(RI.getGUID());4660if (!RefValueId)4661continue;4662NameVals.push_back(*RefValueId);4663}46644665// Emit the finished record.4666Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals,4667FSModRefsAbbrev);4668NameVals.clear();4669MaybeEmitOriginalName(*S);4670return;4671}46724673auto GetValueId = [&](const ValueInfo &VI) -> std::optional<unsigned> {4674if (!VI)4675return std::nullopt;4676return getValueId(VI.getGUID());4677};46784679auto *FS = cast<FunctionSummary>(S);4680writeFunctionTypeMetadataRecords(Stream, FS, GetValueId);4681getReferencedTypeIds(FS, ReferencedTypeIds);46824683writeFunctionHeapProfileRecords(4684Stream, FS, CallsiteAbbrev, AllocAbbrev,4685/*PerModule*/ false,4686/*GetValueId*/4687[&](const ValueInfo &VI) -> unsigned {4688std::optional<unsigned> ValueID = GetValueId(VI);4689// This can happen in shared index files for distributed ThinLTO if4690// the callee function summary is not included. Record 0 which we4691// will have to deal with conservatively when doing any kind of4692// validation in the ThinLTO backends.4693if (!ValueID)4694return 0;4695return *ValueID;4696},4697/*GetStackIndex*/4698[&](unsigned I) {4699// Get the corresponding index into the list of StackIds actually4700// being written for this combined index (which may be a subset in4701// the case of distributed indexes).4702assert(StackIdIndicesToIndex.contains(I));4703return StackIdIndicesToIndex[I];4704});47054706NameVals.push_back(*ValueId);4707assert(ModuleIdMap.count(FS->modulePath()));4708NameVals.push_back(ModuleIdMap[FS->modulePath()]);4709NameVals.push_back(4710getEncodedGVSummaryFlags(FS->flags(), shouldImportValueAsDecl(FS)));4711NameVals.push_back(FS->instCount());4712NameVals.push_back(getEncodedFFlags(FS->fflags()));4713NameVals.push_back(FS->entryCount());47144715// Fill in below4716NameVals.push_back(0); // numrefs4717NameVals.push_back(0); // rorefcnt4718NameVals.push_back(0); // worefcnt47194720unsigned Count = 0, RORefCnt = 0, WORefCnt = 0;4721for (auto &RI : FS->refs()) {4722auto RefValueId = getValueId(RI.getGUID());4723if (!RefValueId)4724continue;4725NameVals.push_back(*RefValueId);4726if (RI.isReadOnly())4727RORefCnt++;4728else if (RI.isWriteOnly())4729WORefCnt++;4730Count++;4731}4732NameVals[6] = Count;4733NameVals[7] = RORefCnt;4734NameVals[8] = WORefCnt;47354736for (auto &EI : FS->calls()) {4737// If this GUID doesn't have a value id, it doesn't have a function4738// summary and we don't need to record any calls to it.4739std::optional<unsigned> CallValueId = GetValueId(EI.first);4740if (!CallValueId)4741continue;4742NameVals.push_back(*CallValueId);4743NameVals.push_back(getEncodedHotnessCallEdgeInfo(EI.second));4744}47454746// Emit the finished record.4747Stream.EmitRecord(bitc::FS_COMBINED_PROFILE, NameVals,4748FSCallsProfileAbbrev);4749NameVals.clear();4750MaybeEmitOriginalName(*S);4751});47524753for (auto *AS : Aliases) {4754auto AliasValueId = SummaryToValueIdMap[AS];4755assert(AliasValueId);4756NameVals.push_back(AliasValueId);4757assert(ModuleIdMap.count(AS->modulePath()));4758NameVals.push_back(ModuleIdMap[AS->modulePath()]);4759NameVals.push_back(4760getEncodedGVSummaryFlags(AS->flags(), shouldImportValueAsDecl(AS)));4761auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()];4762assert(AliaseeValueId);4763NameVals.push_back(AliaseeValueId);47644765// Emit the finished record.4766Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);4767NameVals.clear();4768MaybeEmitOriginalName(*AS);47694770if (auto *FS = dyn_cast<FunctionSummary>(&AS->getAliasee()))4771getReferencedTypeIds(FS, ReferencedTypeIds);4772}47734774if (!Index.cfiFunctionDefs().empty()) {4775for (auto &S : Index.cfiFunctionDefs()) {4776if (DefOrUseGUIDs.count(4777GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(S)))) {4778NameVals.push_back(StrtabBuilder.add(S));4779NameVals.push_back(S.size());4780}4781}4782if (!NameVals.empty()) {4783Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DEFS, NameVals);4784NameVals.clear();4785}4786}47874788if (!Index.cfiFunctionDecls().empty()) {4789for (auto &S : Index.cfiFunctionDecls()) {4790if (DefOrUseGUIDs.count(4791GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(S)))) {4792NameVals.push_back(StrtabBuilder.add(S));4793NameVals.push_back(S.size());4794}4795}4796if (!NameVals.empty()) {4797Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DECLS, NameVals);4798NameVals.clear();4799}4800}48014802// Walk the GUIDs that were referenced, and write the4803// corresponding type id records.4804for (auto &T : ReferencedTypeIds) {4805auto TidIter = Index.typeIds().equal_range(T);4806for (auto It = TidIter.first; It != TidIter.second; ++It) {4807writeTypeIdSummaryRecord(NameVals, StrtabBuilder, It->second.first,4808It->second.second);4809Stream.EmitRecord(bitc::FS_TYPE_ID, NameVals);4810NameVals.clear();4811}4812}48134814if (Index.getBlockCount())4815Stream.EmitRecord(bitc::FS_BLOCK_COUNT,4816ArrayRef<uint64_t>{Index.getBlockCount()});48174818Stream.ExitBlock();4819}48204821/// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the4822/// current llvm version, and a record for the epoch number.4823static void writeIdentificationBlock(BitstreamWriter &Stream) {4824Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);48254826// Write the "user readable" string identifying the bitcode producer4827auto Abbv = std::make_shared<BitCodeAbbrev>();4828Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING));4829Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));4830Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));4831auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));4832writeStringRecord(Stream, bitc::IDENTIFICATION_CODE_STRING,4833"LLVM" LLVM_VERSION_STRING, StringAbbrev);48344835// Write the epoch version4836Abbv = std::make_shared<BitCodeAbbrev>();4837Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH));4838Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));4839auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));4840constexpr std::array<unsigned, 1> Vals = {{bitc::BITCODE_CURRENT_EPOCH}};4841Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);4842Stream.ExitBlock();4843}48444845void ModuleBitcodeWriter::writeModuleHash(StringRef View) {4846// Emit the module's hash.4847// MODULE_CODE_HASH: [5*i32]4848if (GenerateHash) {4849uint32_t Vals[5];4850Hasher.update(ArrayRef<uint8_t>(4851reinterpret_cast<const uint8_t *>(View.data()), View.size()));4852std::array<uint8_t, 20> Hash = Hasher.result();4853for (int Pos = 0; Pos < 20; Pos += 4) {4854Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);4855}48564857// Emit the finished record.4858Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);48594860if (ModHash)4861// Save the written hash value.4862llvm::copy(Vals, std::begin(*ModHash));4863}4864}48654866void ModuleBitcodeWriter::write() {4867writeIdentificationBlock(Stream);48684869Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);4870// We will want to write the module hash at this point. Block any flushing so4871// we can have access to the whole underlying data later.4872Stream.markAndBlockFlushing();48734874writeModuleVersion();48754876// Emit blockinfo, which defines the standard abbreviations etc.4877writeBlockInfo();48784879// Emit information describing all of the types in the module.4880writeTypeTable();48814882// Emit information about attribute groups.4883writeAttributeGroupTable();48844885// Emit information about parameter attributes.4886writeAttributeTable();48874888writeComdats();48894890// Emit top-level description of module, including target triple, inline asm,4891// descriptors for global variables, and function prototype info.4892writeModuleInfo();48934894// Emit constants.4895writeModuleConstants();48964897// Emit metadata kind names.4898writeModuleMetadataKinds();48994900// Emit metadata.4901writeModuleMetadata();49024903// Emit module-level use-lists.4904if (VE.shouldPreserveUseListOrder())4905writeUseListBlock(nullptr);49064907writeOperandBundleTags();4908writeSyncScopeNames();49094910// Emit function bodies.4911DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;4912for (const Function &F : M)4913if (!F.isDeclaration())4914writeFunction(F, FunctionToBitcodeIndex);49154916// Need to write after the above call to WriteFunction which populates4917// the summary information in the index.4918if (Index)4919writePerModuleGlobalValueSummary();49204921writeGlobalValueSymbolTable(FunctionToBitcodeIndex);49224923writeModuleHash(Stream.getMarkedBufferAndResumeFlushing());49244925Stream.ExitBlock();4926}49274928static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,4929uint32_t &Position) {4930support::endian::write32le(&Buffer[Position], Value);4931Position += 4;4932}49334934/// If generating a bc file on darwin, we have to emit a4935/// header and trailer to make it compatible with the system archiver. To do4936/// this we emit the following header, and then emit a trailer that pads the4937/// file out to be a multiple of 16 bytes.4938///4939/// struct bc_header {4940/// uint32_t Magic; // 0x0B17C0DE4941/// uint32_t Version; // Version, currently always 0.4942/// uint32_t BitcodeOffset; // Offset to traditional bitcode file.4943/// uint32_t BitcodeSize; // Size of traditional bitcode file.4944/// uint32_t CPUType; // CPU specifier.4945/// ... potentially more later ...4946/// };4947static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,4948const Triple &TT) {4949unsigned CPUType = ~0U;49504951// Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,4952// armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic4953// number from /usr/include/mach/machine.h. It is ok to reproduce the4954// specific constants here because they are implicitly part of the Darwin ABI.4955enum {4956DARWIN_CPU_ARCH_ABI64 = 0x01000000,4957DARWIN_CPU_TYPE_X86 = 7,4958DARWIN_CPU_TYPE_ARM = 12,4959DARWIN_CPU_TYPE_POWERPC = 184960};49614962Triple::ArchType Arch = TT.getArch();4963if (Arch == Triple::x86_64)4964CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;4965else if (Arch == Triple::x86)4966CPUType = DARWIN_CPU_TYPE_X86;4967else if (Arch == Triple::ppc)4968CPUType = DARWIN_CPU_TYPE_POWERPC;4969else if (Arch == Triple::ppc64)4970CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;4971else if (Arch == Triple::arm || Arch == Triple::thumb)4972CPUType = DARWIN_CPU_TYPE_ARM;49734974// Traditional Bitcode starts after header.4975assert(Buffer.size() >= BWH_HeaderSize &&4976"Expected header size to be reserved");4977unsigned BCOffset = BWH_HeaderSize;4978unsigned BCSize = Buffer.size() - BWH_HeaderSize;49794980// Write the magic and version.4981unsigned Position = 0;4982writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);4983writeInt32ToBuffer(0, Buffer, Position); // Version.4984writeInt32ToBuffer(BCOffset, Buffer, Position);4985writeInt32ToBuffer(BCSize, Buffer, Position);4986writeInt32ToBuffer(CPUType, Buffer, Position);49874988// If the file is not a multiple of 16 bytes, insert dummy padding.4989while (Buffer.size() & 15)4990Buffer.push_back(0);4991}49924993/// Helper to write the header common to all bitcode files.4994static void writeBitcodeHeader(BitstreamWriter &Stream) {4995// Emit the file header.4996Stream.Emit((unsigned)'B', 8);4997Stream.Emit((unsigned)'C', 8);4998Stream.Emit(0x0, 4);4999Stream.Emit(0xC, 4);5000Stream.Emit(0xE, 4);5001Stream.Emit(0xD, 4);5002}50035004BitcodeWriter::BitcodeWriter(SmallVectorImpl<char> &Buffer)5005: Stream(new BitstreamWriter(Buffer)) {5006writeBitcodeHeader(*Stream);5007}50085009BitcodeWriter::BitcodeWriter(raw_ostream &FS)5010: Stream(new BitstreamWriter(FS, FlushThreshold)) {5011writeBitcodeHeader(*Stream);5012}50135014BitcodeWriter::~BitcodeWriter() { assert(WroteStrtab); }50155016void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) {5017Stream->EnterSubblock(Block, 3);50185019auto Abbv = std::make_shared<BitCodeAbbrev>();5020Abbv->Add(BitCodeAbbrevOp(Record));5021Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));5022auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv));50235024Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob);50255026Stream->ExitBlock();5027}50285029void BitcodeWriter::writeSymtab() {5030assert(!WroteStrtab && !WroteSymtab);50315032// If any module has module-level inline asm, we will require a registered asm5033// parser for the target so that we can create an accurate symbol table for5034// the module.5035for (Module *M : Mods) {5036if (M->getModuleInlineAsm().empty())5037continue;50385039std::string Err;5040const Triple TT(M->getTargetTriple());5041const Target *T = TargetRegistry::lookupTarget(TT.str(), Err);5042if (!T || !T->hasMCAsmParser())5043return;5044}50455046WroteSymtab = true;5047SmallVector<char, 0> Symtab;5048// The irsymtab::build function may be unable to create a symbol table if the5049// module is malformed (e.g. it contains an invalid alias). Writing a symbol5050// table is not required for correctness, but we still want to be able to5051// write malformed modules to bitcode files, so swallow the error.5052if (Error E = irsymtab::build(Mods, Symtab, StrtabBuilder, Alloc)) {5053consumeError(std::move(E));5054return;5055}50565057writeBlob(bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB,5058{Symtab.data(), Symtab.size()});5059}50605061void BitcodeWriter::writeStrtab() {5062assert(!WroteStrtab);50635064std::vector<char> Strtab;5065StrtabBuilder.finalizeInOrder();5066Strtab.resize(StrtabBuilder.getSize());5067StrtabBuilder.write((uint8_t *)Strtab.data());50685069writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB,5070{Strtab.data(), Strtab.size()});50715072WroteStrtab = true;5073}50745075void BitcodeWriter::copyStrtab(StringRef Strtab) {5076writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab);5077WroteStrtab = true;5078}50795080void BitcodeWriter::writeModule(const Module &M,5081bool ShouldPreserveUseListOrder,5082const ModuleSummaryIndex *Index,5083bool GenerateHash, ModuleHash *ModHash) {5084assert(!WroteStrtab);50855086// The Mods vector is used by irsymtab::build, which requires non-const5087// Modules in case it needs to materialize metadata. But the bitcode writer5088// requires that the module is materialized, so we can cast to non-const here,5089// after checking that it is in fact materialized.5090assert(M.isMaterialized());5091Mods.push_back(const_cast<Module *>(&M));50925093ModuleBitcodeWriter ModuleWriter(M, StrtabBuilder, *Stream,5094ShouldPreserveUseListOrder, Index,5095GenerateHash, ModHash);5096ModuleWriter.write();5097}50985099void BitcodeWriter::writeIndex(5100const ModuleSummaryIndex *Index,5101const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex,5102const GVSummaryPtrSet *DecSummaries) {5103IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index, DecSummaries,5104ModuleToSummariesForIndex);5105IndexWriter.write();5106}51075108/// Write the specified module to the specified output stream.5109void llvm::WriteBitcodeToFile(const Module &M, raw_ostream &Out,5110bool ShouldPreserveUseListOrder,5111const ModuleSummaryIndex *Index,5112bool GenerateHash, ModuleHash *ModHash) {5113auto Write = [&](BitcodeWriter &Writer) {5114Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,5115ModHash);5116Writer.writeSymtab();5117Writer.writeStrtab();5118};5119Triple TT(M.getTargetTriple());5120if (TT.isOSDarwin() || TT.isOSBinFormatMachO()) {5121// If this is darwin or another generic macho target, reserve space for the5122// header. Note that the header is computed *after* the output is known, so5123// we currently explicitly use a buffer, write to it, and then subsequently5124// flush to Out.5125SmallVector<char, 0> Buffer;5126Buffer.reserve(256 * 1024);5127Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);5128BitcodeWriter Writer(Buffer);5129Write(Writer);5130emitDarwinBCHeaderAndTrailer(Buffer, TT);5131Out.write(Buffer.data(), Buffer.size());5132} else {5133BitcodeWriter Writer(Out);5134Write(Writer);5135}5136}51375138void IndexBitcodeWriter::write() {5139Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);51405141writeModuleVersion();51425143// Write the module paths in the combined index.5144writeModStrings();51455146// Write the summary combined index records.5147writeCombinedGlobalValueSummary();51485149Stream.ExitBlock();5150}51515152// Write the specified module summary index to the given raw output stream,5153// where it will be written in a new bitcode block. This is used when5154// writing the combined index file for ThinLTO. When writing a subset of the5155// index for a distributed backend, provide a \p ModuleToSummariesForIndex map.5156void llvm::writeIndexToFile(5157const ModuleSummaryIndex &Index, raw_ostream &Out,5158const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex,5159const GVSummaryPtrSet *DecSummaries) {5160SmallVector<char, 0> Buffer;5161Buffer.reserve(256 * 1024);51625163BitcodeWriter Writer(Buffer);5164Writer.writeIndex(&Index, ModuleToSummariesForIndex, DecSummaries);5165Writer.writeStrtab();51665167Out.write((char *)&Buffer.front(), Buffer.size());5168}51695170namespace {51715172/// Class to manage the bitcode writing for a thin link bitcode file.5173class ThinLinkBitcodeWriter : public ModuleBitcodeWriterBase {5174/// ModHash is for use in ThinLTO incremental build, generated while writing5175/// the module bitcode file.5176const ModuleHash *ModHash;51775178public:5179ThinLinkBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder,5180BitstreamWriter &Stream,5181const ModuleSummaryIndex &Index,5182const ModuleHash &ModHash)5183: ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,5184/*ShouldPreserveUseListOrder=*/false, &Index),5185ModHash(&ModHash) {}51865187void write();51885189private:5190void writeSimplifiedModuleInfo();5191};51925193} // end anonymous namespace51945195// This function writes a simpilified module info for thin link bitcode file.5196// It only contains the source file name along with the name(the offset and5197// size in strtab) and linkage for global values. For the global value info5198// entry, in order to keep linkage at offset 5, there are three zeros used5199// as padding.5200void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {5201SmallVector<unsigned, 64> Vals;5202// Emit the module's source file name.5203{5204StringEncoding Bits = getStringEncoding(M.getSourceFileName());5205BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);5206if (Bits == SE_Char6)5207AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);5208else if (Bits == SE_Fixed7)5209AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);52105211// MODULE_CODE_SOURCE_FILENAME: [namechar x N]5212auto Abbv = std::make_shared<BitCodeAbbrev>();5213Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));5214Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));5215Abbv->Add(AbbrevOpToUse);5216unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));52175218for (const auto P : M.getSourceFileName())5219Vals.push_back((unsigned char)P);52205221Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);5222Vals.clear();5223}52245225// Emit the global variable information.5226for (const GlobalVariable &GV : M.globals()) {5227// GLOBALVAR: [strtab offset, strtab size, 0, 0, 0, linkage]5228Vals.push_back(StrtabBuilder.add(GV.getName()));5229Vals.push_back(GV.getName().size());5230Vals.push_back(0);5231Vals.push_back(0);5232Vals.push_back(0);5233Vals.push_back(getEncodedLinkage(GV));52345235Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals);5236Vals.clear();5237}52385239// Emit the function proto information.5240for (const Function &F : M) {5241// FUNCTION: [strtab offset, strtab size, 0, 0, 0, linkage]5242Vals.push_back(StrtabBuilder.add(F.getName()));5243Vals.push_back(F.getName().size());5244Vals.push_back(0);5245Vals.push_back(0);5246Vals.push_back(0);5247Vals.push_back(getEncodedLinkage(F));52485249Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals);5250Vals.clear();5251}52525253// Emit the alias information.5254for (const GlobalAlias &A : M.aliases()) {5255// ALIAS: [strtab offset, strtab size, 0, 0, 0, linkage]5256Vals.push_back(StrtabBuilder.add(A.getName()));5257Vals.push_back(A.getName().size());5258Vals.push_back(0);5259Vals.push_back(0);5260Vals.push_back(0);5261Vals.push_back(getEncodedLinkage(A));52625263Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals);5264Vals.clear();5265}52665267// Emit the ifunc information.5268for (const GlobalIFunc &I : M.ifuncs()) {5269// IFUNC: [strtab offset, strtab size, 0, 0, 0, linkage]5270Vals.push_back(StrtabBuilder.add(I.getName()));5271Vals.push_back(I.getName().size());5272Vals.push_back(0);5273Vals.push_back(0);5274Vals.push_back(0);5275Vals.push_back(getEncodedLinkage(I));52765277Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);5278Vals.clear();5279}5280}52815282void ThinLinkBitcodeWriter::write() {5283Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);52845285writeModuleVersion();52865287writeSimplifiedModuleInfo();52885289writePerModuleGlobalValueSummary();52905291// Write module hash.5292Stream.EmitRecord(bitc::MODULE_CODE_HASH, ArrayRef<uint32_t>(*ModHash));52935294Stream.ExitBlock();5295}52965297void BitcodeWriter::writeThinLinkBitcode(const Module &M,5298const ModuleSummaryIndex &Index,5299const ModuleHash &ModHash) {5300assert(!WroteStrtab);53015302// The Mods vector is used by irsymtab::build, which requires non-const5303// Modules in case it needs to materialize metadata. But the bitcode writer5304// requires that the module is materialized, so we can cast to non-const here,5305// after checking that it is in fact materialized.5306assert(M.isMaterialized());5307Mods.push_back(const_cast<Module *>(&M));53085309ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index,5310ModHash);5311ThinLinkWriter.write();5312}53135314// Write the specified thin link bitcode file to the given raw output stream,5315// where it will be written in a new bitcode block. This is used when5316// writing the per-module index file for ThinLTO.5317void llvm::writeThinLinkBitcodeToFile(const Module &M, raw_ostream &Out,5318const ModuleSummaryIndex &Index,5319const ModuleHash &ModHash) {5320SmallVector<char, 0> Buffer;5321Buffer.reserve(256 * 1024);53225323BitcodeWriter Writer(Buffer);5324Writer.writeThinLinkBitcode(M, Index, ModHash);5325Writer.writeSymtab();5326Writer.writeStrtab();53275328Out.write((char *)&Buffer.front(), Buffer.size());5329}53305331static const char *getSectionNameForBitcode(const Triple &T) {5332switch (T.getObjectFormat()) {5333case Triple::MachO:5334return "__LLVM,__bitcode";5335case Triple::COFF:5336case Triple::ELF:5337case Triple::Wasm:5338case Triple::UnknownObjectFormat:5339return ".llvmbc";5340case Triple::GOFF:5341llvm_unreachable("GOFF is not yet implemented");5342break;5343case Triple::SPIRV:5344if (T.getVendor() == Triple::AMD)5345return ".llvmbc";5346llvm_unreachable("SPIRV is not yet implemented");5347break;5348case Triple::XCOFF:5349llvm_unreachable("XCOFF is not yet implemented");5350break;5351case Triple::DXContainer:5352llvm_unreachable("DXContainer is not yet implemented");5353break;5354}5355llvm_unreachable("Unimplemented ObjectFormatType");5356}53575358static const char *getSectionNameForCommandline(const Triple &T) {5359switch (T.getObjectFormat()) {5360case Triple::MachO:5361return "__LLVM,__cmdline";5362case Triple::COFF:5363case Triple::ELF:5364case Triple::Wasm:5365case Triple::UnknownObjectFormat:5366return ".llvmcmd";5367case Triple::GOFF:5368llvm_unreachable("GOFF is not yet implemented");5369break;5370case Triple::SPIRV:5371if (T.getVendor() == Triple::AMD)5372return ".llvmcmd";5373llvm_unreachable("SPIRV is not yet implemented");5374break;5375case Triple::XCOFF:5376llvm_unreachable("XCOFF is not yet implemented");5377break;5378case Triple::DXContainer:5379llvm_unreachable("DXC is not yet implemented");5380break;5381}5382llvm_unreachable("Unimplemented ObjectFormatType");5383}53845385void llvm::embedBitcodeInModule(llvm::Module &M, llvm::MemoryBufferRef Buf,5386bool EmbedBitcode, bool EmbedCmdline,5387const std::vector<uint8_t> &CmdArgs) {5388// Save llvm.compiler.used and remove it.5389SmallVector<Constant *, 2> UsedArray;5390SmallVector<GlobalValue *, 4> UsedGlobals;5391Type *UsedElementType = PointerType::getUnqual(M.getContext());5392GlobalVariable *Used = collectUsedGlobalVariables(M, UsedGlobals, true);5393for (auto *GV : UsedGlobals) {5394if (GV->getName() != "llvm.embedded.module" &&5395GV->getName() != "llvm.cmdline")5396UsedArray.push_back(5397ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));5398}5399if (Used)5400Used->eraseFromParent();54015402// Embed the bitcode for the llvm module.5403std::string Data;5404ArrayRef<uint8_t> ModuleData;5405Triple T(M.getTargetTriple());54065407if (EmbedBitcode) {5408if (Buf.getBufferSize() == 0 ||5409!isBitcode((const unsigned char *)Buf.getBufferStart(),5410(const unsigned char *)Buf.getBufferEnd())) {5411// If the input is LLVM Assembly, bitcode is produced by serializing5412// the module. Use-lists order need to be preserved in this case.5413llvm::raw_string_ostream OS(Data);5414llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true);5415ModuleData =5416ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());5417} else5418// If the input is LLVM bitcode, write the input byte stream directly.5419ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),5420Buf.getBufferSize());5421}5422llvm::Constant *ModuleConstant =5423llvm::ConstantDataArray::get(M.getContext(), ModuleData);5424llvm::GlobalVariable *GV = new llvm::GlobalVariable(5425M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,5426ModuleConstant);5427GV->setSection(getSectionNameForBitcode(T));5428// Set alignment to 1 to prevent padding between two contributions from input5429// sections after linking.5430GV->setAlignment(Align(1));5431UsedArray.push_back(5432ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));5433if (llvm::GlobalVariable *Old =5434M.getGlobalVariable("llvm.embedded.module", true)) {5435assert(Old->hasZeroLiveUses() &&5436"llvm.embedded.module can only be used once in llvm.compiler.used");5437GV->takeName(Old);5438Old->eraseFromParent();5439} else {5440GV->setName("llvm.embedded.module");5441}54425443// Skip if only bitcode needs to be embedded.5444if (EmbedCmdline) {5445// Embed command-line options.5446ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CmdArgs.data()),5447CmdArgs.size());5448llvm::Constant *CmdConstant =5449llvm::ConstantDataArray::get(M.getContext(), CmdData);5450GV = new llvm::GlobalVariable(M, CmdConstant->getType(), true,5451llvm::GlobalValue::PrivateLinkage,5452CmdConstant);5453GV->setSection(getSectionNameForCommandline(T));5454GV->setAlignment(Align(1));5455UsedArray.push_back(5456ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));5457if (llvm::GlobalVariable *Old = M.getGlobalVariable("llvm.cmdline", true)) {5458assert(Old->hasZeroLiveUses() &&5459"llvm.cmdline can only be used once in llvm.compiler.used");5460GV->takeName(Old);5461Old->eraseFromParent();5462} else {5463GV->setName("llvm.cmdline");5464}5465}54665467if (UsedArray.empty())5468return;54695470// Recreate llvm.compiler.used.5471ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());5472auto *NewUsed = new GlobalVariable(5473M, ATy, false, llvm::GlobalValue::AppendingLinkage,5474llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");5475NewUsed->setSection("llvm.metadata");5476}547754785479