1044eb2f6SDimitry Andric //===- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ------------------===//
2009b1c42SEd Schouten //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6009b1c42SEd Schouten //
7009b1c42SEd Schouten //===----------------------------------------------------------------------===//
8009b1c42SEd Schouten //
9009b1c42SEd Schouten // Bitcode writer implementation.
10009b1c42SEd Schouten //
11009b1c42SEd Schouten //===----------------------------------------------------------------------===//
12009b1c42SEd Schouten
13b915e9e0SDimitry Andric #include "llvm/Bitcode/BitcodeWriter.h"
144a16efa3SDimitry Andric #include "ValueEnumerator.h"
15044eb2f6SDimitry Andric #include "llvm/ADT/APFloat.h"
16044eb2f6SDimitry Andric #include "llvm/ADT/APInt.h"
17044eb2f6SDimitry Andric #include "llvm/ADT/ArrayRef.h"
18044eb2f6SDimitry Andric #include "llvm/ADT/DenseMap.h"
19044eb2f6SDimitry Andric #include "llvm/ADT/STLExtras.h"
20145449b1SDimitry Andric #include "llvm/ADT/SetVector.h"
21145449b1SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
22044eb2f6SDimitry Andric #include "llvm/ADT/SmallString.h"
23044eb2f6SDimitry Andric #include "llvm/ADT/SmallVector.h"
24044eb2f6SDimitry Andric #include "llvm/ADT/StringMap.h"
25044eb2f6SDimitry Andric #include "llvm/ADT/StringRef.h"
26b60736ecSDimitry Andric #include "llvm/Bitcode/BitcodeCommon.h"
27706b4fc4SDimitry Andric #include "llvm/Bitcode/BitcodeReader.h"
28706b4fc4SDimitry Andric #include "llvm/Bitcode/LLVMBitCodes.h"
29e6d15924SDimitry Andric #include "llvm/Bitstream/BitCodes.h"
30e6d15924SDimitry Andric #include "llvm/Bitstream/BitstreamWriter.h"
31eb11fae6SDimitry Andric #include "llvm/Config/llvm-config.h"
32044eb2f6SDimitry Andric #include "llvm/IR/Attributes.h"
33044eb2f6SDimitry Andric #include "llvm/IR/BasicBlock.h"
34044eb2f6SDimitry Andric #include "llvm/IR/Comdat.h"
35044eb2f6SDimitry Andric #include "llvm/IR/Constant.h"
36ac9a064cSDimitry Andric #include "llvm/IR/ConstantRangeList.h"
374a16efa3SDimitry Andric #include "llvm/IR/Constants.h"
385a5ac124SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
39044eb2f6SDimitry Andric #include "llvm/IR/DebugLoc.h"
404a16efa3SDimitry Andric #include "llvm/IR/DerivedTypes.h"
41044eb2f6SDimitry Andric #include "llvm/IR/Function.h"
42044eb2f6SDimitry Andric #include "llvm/IR/GlobalAlias.h"
43044eb2f6SDimitry Andric #include "llvm/IR/GlobalIFunc.h"
44044eb2f6SDimitry Andric #include "llvm/IR/GlobalObject.h"
45044eb2f6SDimitry Andric #include "llvm/IR/GlobalValue.h"
46044eb2f6SDimitry Andric #include "llvm/IR/GlobalVariable.h"
474a16efa3SDimitry Andric #include "llvm/IR/InlineAsm.h"
48044eb2f6SDimitry Andric #include "llvm/IR/InstrTypes.h"
49044eb2f6SDimitry Andric #include "llvm/IR/Instruction.h"
504a16efa3SDimitry Andric #include "llvm/IR/Instructions.h"
51dd58ef01SDimitry Andric #include "llvm/IR/LLVMContext.h"
52044eb2f6SDimitry Andric #include "llvm/IR/Metadata.h"
534a16efa3SDimitry Andric #include "llvm/IR/Module.h"
54044eb2f6SDimitry Andric #include "llvm/IR/ModuleSummaryIndex.h"
554a16efa3SDimitry Andric #include "llvm/IR/Operator.h"
56044eb2f6SDimitry Andric #include "llvm/IR/Type.h"
5767c32a98SDimitry Andric #include "llvm/IR/UseListOrder.h"
58044eb2f6SDimitry Andric #include "llvm/IR/Value.h"
594a16efa3SDimitry Andric #include "llvm/IR/ValueSymbolTable.h"
60d99dafe2SDimitry Andric #include "llvm/MC/StringTableBuilder.h"
61c0981da4SDimitry Andric #include "llvm/MC/TargetRegistry.h"
629df3605dSDimitry Andric #include "llvm/Object/IRSymtab.h"
63044eb2f6SDimitry Andric #include "llvm/Support/AtomicOrdering.h"
64044eb2f6SDimitry Andric #include "llvm/Support/Casting.h"
65044eb2f6SDimitry Andric #include "llvm/Support/CommandLine.h"
66044eb2f6SDimitry Andric #include "llvm/Support/Endian.h"
67044eb2f6SDimitry Andric #include "llvm/Support/Error.h"
6859850d08SRoman Divacky #include "llvm/Support/ErrorHandling.h"
69009b1c42SEd Schouten #include "llvm/Support/MathExtras.h"
7001095a5dSDimitry Andric #include "llvm/Support/SHA1.h"
714a16efa3SDimitry Andric #include "llvm/Support/raw_ostream.h"
727fa27ce4SDimitry Andric #include "llvm/TargetParser/Triple.h"
73044eb2f6SDimitry Andric #include <algorithm>
74044eb2f6SDimitry Andric #include <cassert>
75044eb2f6SDimitry Andric #include <cstddef>
76044eb2f6SDimitry Andric #include <cstdint>
77044eb2f6SDimitry Andric #include <iterator>
78411bd29eSDimitry Andric #include <map>
79044eb2f6SDimitry Andric #include <memory>
80e3b55780SDimitry Andric #include <optional>
81044eb2f6SDimitry Andric #include <string>
82044eb2f6SDimitry Andric #include <utility>
83044eb2f6SDimitry Andric #include <vector>
84044eb2f6SDimitry Andric
85009b1c42SEd Schouten using namespace llvm;
86009b1c42SEd Schouten
87044eb2f6SDimitry Andric static cl::opt<unsigned>
88b915e9e0SDimitry Andric IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25),
89b915e9e0SDimitry Andric cl::desc("Number of metadatas above which we emit an index "
90b915e9e0SDimitry Andric "to enable lazy-loading"));
91b60736ecSDimitry Andric static cl::opt<uint32_t> FlushThreshold(
92b60736ecSDimitry Andric "bitcode-flush-threshold", cl::Hidden, cl::init(512),
93b60736ecSDimitry Andric cl::desc("The threshold (unit M) for flushing LLVM bitcode."));
94044eb2f6SDimitry Andric
951d5ae102SDimitry Andric static cl::opt<bool> WriteRelBFToSummary(
96eb11fae6SDimitry Andric "write-relbf-to-summary", cl::Hidden, cl::init(false),
97eb11fae6SDimitry Andric cl::desc("Write relative block frequency to function summary "));
98eb11fae6SDimitry Andric
99e3b55780SDimitry Andric namespace llvm {
100eb11fae6SDimitry Andric extern FunctionSummary::ForceSummaryHotnessType ForceSummaryEdgesCold;
101e3b55780SDimitry Andric }
102eb11fae6SDimitry Andric
103ac9a064cSDimitry Andric extern bool WriteNewDbgInfoFormatToBitcode;
104ac9a064cSDimitry Andric extern llvm::cl::opt<bool> UseNewDbgInfoFormat;
105ac9a064cSDimitry Andric
106044eb2f6SDimitry Andric namespace {
107044eb2f6SDimitry Andric
108009b1c42SEd Schouten /// These are manifest constants used by the bitcode writer. They do not need to
109009b1c42SEd Schouten /// be kept in sync with the reader, but need to be consistent within this file.
110009b1c42SEd Schouten enum {
111009b1c42SEd Schouten // VALUE_SYMTAB_BLOCK abbrev id's.
112009b1c42SEd Schouten VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
113009b1c42SEd Schouten VST_ENTRY_7_ABBREV,
114009b1c42SEd Schouten VST_ENTRY_6_ABBREV,
115009b1c42SEd Schouten VST_BBENTRY_6_ABBREV,
116009b1c42SEd Schouten
117009b1c42SEd Schouten // CONSTANTS_BLOCK abbrev id's.
118009b1c42SEd Schouten CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
119009b1c42SEd Schouten CONSTANTS_INTEGER_ABBREV,
120009b1c42SEd Schouten CONSTANTS_CE_CAST_Abbrev,
121009b1c42SEd Schouten CONSTANTS_NULL_Abbrev,
122009b1c42SEd Schouten
123009b1c42SEd Schouten // FUNCTION_BLOCK abbrev id's.
124009b1c42SEd Schouten FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
125d8e91e46SDimitry Andric FUNCTION_INST_UNOP_ABBREV,
126d8e91e46SDimitry Andric FUNCTION_INST_UNOP_FLAGS_ABBREV,
127009b1c42SEd Schouten FUNCTION_INST_BINOP_ABBREV,
12859850d08SRoman Divacky FUNCTION_INST_BINOP_FLAGS_ABBREV,
129009b1c42SEd Schouten FUNCTION_INST_CAST_ABBREV,
130b1c73532SDimitry Andric FUNCTION_INST_CAST_FLAGS_ABBREV,
131009b1c42SEd Schouten FUNCTION_INST_RET_VOID_ABBREV,
132009b1c42SEd Schouten FUNCTION_INST_RET_VAL_ABBREV,
1335a5ac124SDimitry Andric FUNCTION_INST_UNREACHABLE_ABBREV,
1345a5ac124SDimitry Andric FUNCTION_INST_GEP_ABBREV,
135ac9a064cSDimitry Andric FUNCTION_DEBUG_RECORD_VALUE_ABBREV,
136009b1c42SEd Schouten };
137009b1c42SEd Schouten
13801095a5dSDimitry Andric /// Abstract class to manage the bitcode writing, subclassed for each bitcode
139b915e9e0SDimitry Andric /// file type.
140b915e9e0SDimitry Andric class BitcodeWriterBase {
14101095a5dSDimitry Andric protected:
142b915e9e0SDimitry Andric /// The stream created and owned by the client.
143b915e9e0SDimitry Andric BitstreamWriter &Stream;
14401095a5dSDimitry Andric
1457c7aba6eSDimitry Andric StringTableBuilder &StrtabBuilder;
1467c7aba6eSDimitry Andric
14701095a5dSDimitry Andric public:
148b915e9e0SDimitry Andric /// Constructs a BitcodeWriterBase object that writes to the provided
149b915e9e0SDimitry Andric /// \p Stream.
BitcodeWriterBase(BitstreamWriter & Stream,StringTableBuilder & StrtabBuilder)1507c7aba6eSDimitry Andric BitcodeWriterBase(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder)
1517c7aba6eSDimitry Andric : Stream(Stream), StrtabBuilder(StrtabBuilder) {}
15201095a5dSDimitry Andric
15301095a5dSDimitry Andric protected:
154d99dafe2SDimitry Andric void writeModuleVersion();
15501095a5dSDimitry Andric };
15601095a5dSDimitry Andric
writeModuleVersion()157d99dafe2SDimitry Andric void BitcodeWriterBase::writeModuleVersion() {
158d99dafe2SDimitry Andric // VERSION: [version#]
159d99dafe2SDimitry Andric Stream.EmitRecord(bitc::MODULE_CODE_VERSION, ArrayRef<uint64_t>{2});
160d99dafe2SDimitry Andric }
161d99dafe2SDimitry Andric
162044eb2f6SDimitry Andric /// Base class to manage the module bitcode writing, currently subclassed for
163044eb2f6SDimitry Andric /// ModuleBitcodeWriter and ThinLinkBitcodeWriter.
164044eb2f6SDimitry Andric class ModuleBitcodeWriterBase : public BitcodeWriterBase {
165044eb2f6SDimitry Andric protected:
16601095a5dSDimitry Andric /// The Module to write to bitcode.
16701095a5dSDimitry Andric const Module &M;
16801095a5dSDimitry Andric
16901095a5dSDimitry Andric /// Enumerates ids for all values in the module.
17001095a5dSDimitry Andric ValueEnumerator VE;
17101095a5dSDimitry Andric
17201095a5dSDimitry Andric /// Optional per-module index to write for ThinLTO.
17301095a5dSDimitry Andric const ModuleSummaryIndex *Index;
17401095a5dSDimitry Andric
17501095a5dSDimitry Andric /// Map that holds the correspondence between GUIDs in the summary index,
17601095a5dSDimitry Andric /// that came from indirect call profiles, and a value id generated by this
17701095a5dSDimitry Andric /// class to use in the VST and summary block records.
17801095a5dSDimitry Andric std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
17901095a5dSDimitry Andric
18001095a5dSDimitry Andric /// Tracks the last value id recorded in the GUIDToValueMap.
18101095a5dSDimitry Andric unsigned GlobalValueId;
18201095a5dSDimitry Andric
183d99dafe2SDimitry Andric /// Saves the offset of the VSTOffset record that must eventually be
184d99dafe2SDimitry Andric /// backpatched with the offset of the actual VST.
185d99dafe2SDimitry Andric uint64_t VSTOffsetPlaceholder = 0;
186d99dafe2SDimitry Andric
18701095a5dSDimitry Andric public:
188044eb2f6SDimitry Andric /// Constructs a ModuleBitcodeWriterBase object for the given Module,
18901095a5dSDimitry Andric /// writing to the provided \p Buffer.
ModuleBitcodeWriterBase(const Module & M,StringTableBuilder & StrtabBuilder,BitstreamWriter & Stream,bool ShouldPreserveUseListOrder,const ModuleSummaryIndex * Index)190eb11fae6SDimitry Andric ModuleBitcodeWriterBase(const Module &M, StringTableBuilder &StrtabBuilder,
191044eb2f6SDimitry Andric BitstreamWriter &Stream,
192044eb2f6SDimitry Andric bool ShouldPreserveUseListOrder,
193044eb2f6SDimitry Andric const ModuleSummaryIndex *Index)
194eb11fae6SDimitry Andric : BitcodeWriterBase(Stream, StrtabBuilder), M(M),
195eb11fae6SDimitry Andric VE(M, ShouldPreserveUseListOrder), Index(Index) {
19601095a5dSDimitry Andric // Assign ValueIds to any callee values in the index that came from
19701095a5dSDimitry Andric // indirect call profiles and were recorded as a GUID not a Value*
19801095a5dSDimitry Andric // (which would have been assigned an ID by the ValueEnumerator).
19901095a5dSDimitry Andric // The starting ValueId is just after the number of values in the
20001095a5dSDimitry Andric // ValueEnumerator, so that they can be emitted in the VST.
20101095a5dSDimitry Andric GlobalValueId = VE.getValues().size();
202b915e9e0SDimitry Andric if (!Index)
203b915e9e0SDimitry Andric return;
20401095a5dSDimitry Andric for (const auto &GUIDSummaryLists : *Index)
20501095a5dSDimitry Andric // Examine all summaries for this GUID.
206c46e6a59SDimitry Andric for (auto &Summary : GUIDSummaryLists.second.SummaryList)
207ac9a064cSDimitry Andric if (auto FS = dyn_cast<FunctionSummary>(Summary.get())) {
20801095a5dSDimitry Andric // For each call in the function summary, see if the call
20901095a5dSDimitry Andric // is to a GUID (which means it is for an indirect call,
21001095a5dSDimitry Andric // otherwise we would have a Value for it). If so, synthesize
21101095a5dSDimitry Andric // a value id.
21201095a5dSDimitry Andric for (auto &CallEdge : FS->calls())
213eb11fae6SDimitry Andric if (!CallEdge.first.haveGVs() || !CallEdge.first.getValue())
21401095a5dSDimitry Andric assignValueId(CallEdge.first.getGUID());
215ac9a064cSDimitry Andric
216ac9a064cSDimitry Andric // For each referenced variables in the function summary, see if the
217ac9a064cSDimitry Andric // variable is represented by a GUID (as opposed to a symbol to
218ac9a064cSDimitry Andric // declarations or definitions in the module). If so, synthesize a
219ac9a064cSDimitry Andric // value id.
220ac9a064cSDimitry Andric for (auto &RefEdge : FS->refs())
221ac9a064cSDimitry Andric if (!RefEdge.haveGVs() || !RefEdge.getValue())
222ac9a064cSDimitry Andric assignValueId(RefEdge.getGUID());
223ac9a064cSDimitry Andric }
22401095a5dSDimitry Andric }
22501095a5dSDimitry Andric
226044eb2f6SDimitry Andric protected:
227044eb2f6SDimitry Andric void writePerModuleGlobalValueSummary();
228044eb2f6SDimitry Andric
229044eb2f6SDimitry Andric private:
230e3b55780SDimitry Andric void writePerModuleFunctionSummaryRecord(
231e3b55780SDimitry Andric SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
232e3b55780SDimitry Andric unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
233e3b55780SDimitry Andric unsigned CallsiteAbbrev, unsigned AllocAbbrev, const Function &F);
234044eb2f6SDimitry Andric void writeModuleLevelReferences(const GlobalVariable &V,
235044eb2f6SDimitry Andric SmallVector<uint64_t, 64> &NameVals,
236e6d15924SDimitry Andric unsigned FSModRefsAbbrev,
237e6d15924SDimitry Andric unsigned FSModVTableRefsAbbrev);
238044eb2f6SDimitry Andric
assignValueId(GlobalValue::GUID ValGUID)239044eb2f6SDimitry Andric void assignValueId(GlobalValue::GUID ValGUID) {
240044eb2f6SDimitry Andric GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
241044eb2f6SDimitry Andric }
242044eb2f6SDimitry Andric
getValueId(GlobalValue::GUID ValGUID)243044eb2f6SDimitry Andric unsigned getValueId(GlobalValue::GUID ValGUID) {
244044eb2f6SDimitry Andric const auto &VMI = GUIDToValueIdMap.find(ValGUID);
245044eb2f6SDimitry Andric // Expect that any GUID value had a value Id assigned by an
246044eb2f6SDimitry Andric // earlier call to assignValueId.
247044eb2f6SDimitry Andric assert(VMI != GUIDToValueIdMap.end() &&
248044eb2f6SDimitry Andric "GUID does not have assigned value Id");
249044eb2f6SDimitry Andric return VMI->second;
250044eb2f6SDimitry Andric }
251044eb2f6SDimitry Andric
252044eb2f6SDimitry Andric // Helper to get the valueId for the type of value recorded in VI.
getValueId(ValueInfo VI)253044eb2f6SDimitry Andric unsigned getValueId(ValueInfo VI) {
254eb11fae6SDimitry Andric if (!VI.haveGVs() || !VI.getValue())
255044eb2f6SDimitry Andric return getValueId(VI.getGUID());
256044eb2f6SDimitry Andric return VE.getValueID(VI.getValue());
257044eb2f6SDimitry Andric }
258044eb2f6SDimitry Andric
valueIds()259044eb2f6SDimitry Andric std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
260044eb2f6SDimitry Andric };
261044eb2f6SDimitry Andric
262044eb2f6SDimitry Andric /// Class to manage the bitcode writing for a module.
263044eb2f6SDimitry Andric class ModuleBitcodeWriter : public ModuleBitcodeWriterBase {
264044eb2f6SDimitry Andric /// True if a module hash record should be written.
265044eb2f6SDimitry Andric bool GenerateHash;
266044eb2f6SDimitry Andric
267044eb2f6SDimitry Andric /// If non-null, when GenerateHash is true, the resulting hash is written
268044eb2f6SDimitry Andric /// into ModHash.
269044eb2f6SDimitry Andric ModuleHash *ModHash;
270044eb2f6SDimitry Andric
271044eb2f6SDimitry Andric SHA1 Hasher;
272044eb2f6SDimitry Andric
273044eb2f6SDimitry Andric /// The start bit of the identification block.
274044eb2f6SDimitry Andric uint64_t BitcodeStartBit;
275044eb2f6SDimitry Andric
276044eb2f6SDimitry Andric public:
277044eb2f6SDimitry Andric /// Constructs a ModuleBitcodeWriter object for the given Module,
278044eb2f6SDimitry Andric /// writing to the provided \p Buffer.
ModuleBitcodeWriter(const Module & M,StringTableBuilder & StrtabBuilder,BitstreamWriter & Stream,bool ShouldPreserveUseListOrder,const ModuleSummaryIndex * Index,bool GenerateHash,ModuleHash * ModHash=nullptr)279ac9a064cSDimitry Andric ModuleBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder,
280044eb2f6SDimitry Andric BitstreamWriter &Stream, bool ShouldPreserveUseListOrder,
281044eb2f6SDimitry Andric const ModuleSummaryIndex *Index, bool GenerateHash,
282044eb2f6SDimitry Andric ModuleHash *ModHash = nullptr)
283044eb2f6SDimitry Andric : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
284044eb2f6SDimitry Andric ShouldPreserveUseListOrder, Index),
285ac9a064cSDimitry Andric GenerateHash(GenerateHash), ModHash(ModHash),
286044eb2f6SDimitry Andric BitcodeStartBit(Stream.GetCurrentBitNo()) {}
287044eb2f6SDimitry Andric
28801095a5dSDimitry Andric /// Emit the current module to the bitstream.
289b915e9e0SDimitry Andric void write();
29001095a5dSDimitry Andric
291b915e9e0SDimitry Andric private:
bitcodeStartBit()29201095a5dSDimitry Andric uint64_t bitcodeStartBit() { return BitcodeStartBit; }
29301095a5dSDimitry Andric
294ca089b24SDimitry Andric size_t addToStrtab(StringRef Str);
295ca089b24SDimitry Andric
29601095a5dSDimitry Andric void writeAttributeGroupTable();
29701095a5dSDimitry Andric void writeAttributeTable();
29801095a5dSDimitry Andric void writeTypeTable();
29901095a5dSDimitry Andric void writeComdats();
300d99dafe2SDimitry Andric void writeValueSymbolTableForwardDecl();
30101095a5dSDimitry Andric void writeModuleInfo();
30201095a5dSDimitry Andric void writeValueAsMetadata(const ValueAsMetadata *MD,
30301095a5dSDimitry Andric SmallVectorImpl<uint64_t> &Record);
30401095a5dSDimitry Andric void writeMDTuple(const MDTuple *N, SmallVectorImpl<uint64_t> &Record,
30501095a5dSDimitry Andric unsigned Abbrev);
30601095a5dSDimitry Andric unsigned createDILocationAbbrev();
30701095a5dSDimitry Andric void writeDILocation(const DILocation *N, SmallVectorImpl<uint64_t> &Record,
30801095a5dSDimitry Andric unsigned &Abbrev);
30901095a5dSDimitry Andric unsigned createGenericDINodeAbbrev();
31001095a5dSDimitry Andric void writeGenericDINode(const GenericDINode *N,
31101095a5dSDimitry Andric SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev);
31201095a5dSDimitry Andric void writeDISubrange(const DISubrange *N, SmallVectorImpl<uint64_t> &Record,
31301095a5dSDimitry Andric unsigned Abbrev);
314b60736ecSDimitry Andric void writeDIGenericSubrange(const DIGenericSubrange *N,
315b60736ecSDimitry Andric SmallVectorImpl<uint64_t> &Record,
316b60736ecSDimitry Andric unsigned Abbrev);
31701095a5dSDimitry Andric void writeDIEnumerator(const DIEnumerator *N,
31801095a5dSDimitry Andric SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
31901095a5dSDimitry Andric void writeDIBasicType(const DIBasicType *N, SmallVectorImpl<uint64_t> &Record,
32001095a5dSDimitry Andric unsigned Abbrev);
321b60736ecSDimitry Andric void writeDIStringType(const DIStringType *N,
322b60736ecSDimitry Andric SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
32301095a5dSDimitry Andric void writeDIDerivedType(const DIDerivedType *N,
32401095a5dSDimitry Andric SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
32501095a5dSDimitry Andric void writeDICompositeType(const DICompositeType *N,
32601095a5dSDimitry Andric SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
32701095a5dSDimitry Andric void writeDISubroutineType(const DISubroutineType *N,
32801095a5dSDimitry Andric SmallVectorImpl<uint64_t> &Record,
32901095a5dSDimitry Andric unsigned Abbrev);
33001095a5dSDimitry Andric void writeDIFile(const DIFile *N, SmallVectorImpl<uint64_t> &Record,
33101095a5dSDimitry Andric unsigned Abbrev);
33201095a5dSDimitry Andric void writeDICompileUnit(const DICompileUnit *N,
33301095a5dSDimitry Andric SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
33401095a5dSDimitry Andric void writeDISubprogram(const DISubprogram *N,
33501095a5dSDimitry Andric SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
33601095a5dSDimitry Andric void writeDILexicalBlock(const DILexicalBlock *N,
33701095a5dSDimitry Andric SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
33801095a5dSDimitry Andric void writeDILexicalBlockFile(const DILexicalBlockFile *N,
33901095a5dSDimitry Andric SmallVectorImpl<uint64_t> &Record,
34001095a5dSDimitry Andric unsigned Abbrev);
341e6d15924SDimitry Andric void writeDICommonBlock(const DICommonBlock *N,
342e6d15924SDimitry Andric SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
34301095a5dSDimitry Andric void writeDINamespace(const DINamespace *N, SmallVectorImpl<uint64_t> &Record,
34401095a5dSDimitry Andric unsigned Abbrev);
34501095a5dSDimitry Andric void writeDIMacro(const DIMacro *N, SmallVectorImpl<uint64_t> &Record,
34601095a5dSDimitry Andric unsigned Abbrev);
34701095a5dSDimitry Andric void writeDIMacroFile(const DIMacroFile *N, SmallVectorImpl<uint64_t> &Record,
34801095a5dSDimitry Andric unsigned Abbrev);
349b1c73532SDimitry Andric void writeDIArgList(const DIArgList *N, SmallVectorImpl<uint64_t> &Record);
35001095a5dSDimitry Andric void writeDIModule(const DIModule *N, SmallVectorImpl<uint64_t> &Record,
35101095a5dSDimitry Andric unsigned Abbrev);
352e3b55780SDimitry Andric void writeDIAssignID(const DIAssignID *N, SmallVectorImpl<uint64_t> &Record,
353e3b55780SDimitry Andric unsigned Abbrev);
35401095a5dSDimitry Andric void writeDITemplateTypeParameter(const DITemplateTypeParameter *N,
35501095a5dSDimitry Andric SmallVectorImpl<uint64_t> &Record,
35601095a5dSDimitry Andric unsigned Abbrev);
35701095a5dSDimitry Andric void writeDITemplateValueParameter(const DITemplateValueParameter *N,
35801095a5dSDimitry Andric SmallVectorImpl<uint64_t> &Record,
35901095a5dSDimitry Andric unsigned Abbrev);
36001095a5dSDimitry Andric void writeDIGlobalVariable(const DIGlobalVariable *N,
36101095a5dSDimitry Andric SmallVectorImpl<uint64_t> &Record,
36201095a5dSDimitry Andric unsigned Abbrev);
36301095a5dSDimitry Andric void writeDILocalVariable(const DILocalVariable *N,
36401095a5dSDimitry Andric SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
365eb11fae6SDimitry Andric void writeDILabel(const DILabel *N,
366eb11fae6SDimitry Andric SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
36701095a5dSDimitry Andric void writeDIExpression(const DIExpression *N,
36801095a5dSDimitry Andric SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
369b915e9e0SDimitry Andric void writeDIGlobalVariableExpression(const DIGlobalVariableExpression *N,
370b915e9e0SDimitry Andric SmallVectorImpl<uint64_t> &Record,
371b915e9e0SDimitry Andric unsigned Abbrev);
37201095a5dSDimitry Andric void writeDIObjCProperty(const DIObjCProperty *N,
37301095a5dSDimitry Andric SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
37401095a5dSDimitry Andric void writeDIImportedEntity(const DIImportedEntity *N,
37501095a5dSDimitry Andric SmallVectorImpl<uint64_t> &Record,
37601095a5dSDimitry Andric unsigned Abbrev);
37701095a5dSDimitry Andric unsigned createNamedMetadataAbbrev();
37801095a5dSDimitry Andric void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
37901095a5dSDimitry Andric unsigned createMetadataStringsAbbrev();
38001095a5dSDimitry Andric void writeMetadataStrings(ArrayRef<const Metadata *> Strings,
38101095a5dSDimitry Andric SmallVectorImpl<uint64_t> &Record);
38201095a5dSDimitry Andric void writeMetadataRecords(ArrayRef<const Metadata *> MDs,
383b915e9e0SDimitry Andric SmallVectorImpl<uint64_t> &Record,
384b915e9e0SDimitry Andric std::vector<unsigned> *MDAbbrevs = nullptr,
385b915e9e0SDimitry Andric std::vector<uint64_t> *IndexPos = nullptr);
38601095a5dSDimitry Andric void writeModuleMetadata();
38701095a5dSDimitry Andric void writeFunctionMetadata(const Function &F);
38801095a5dSDimitry Andric void writeFunctionMetadataAttachment(const Function &F);
38901095a5dSDimitry Andric void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
39001095a5dSDimitry Andric const GlobalObject &GO);
39101095a5dSDimitry Andric void writeModuleMetadataKinds();
39201095a5dSDimitry Andric void writeOperandBundleTags();
393ca089b24SDimitry Andric void writeSyncScopeNames();
39401095a5dSDimitry Andric void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal);
39501095a5dSDimitry Andric void writeModuleConstants();
39601095a5dSDimitry Andric bool pushValueAndType(const Value *V, unsigned InstID,
39701095a5dSDimitry Andric SmallVectorImpl<unsigned> &Vals);
398cfca06d7SDimitry Andric void writeOperandBundles(const CallBase &CB, unsigned InstID);
39901095a5dSDimitry Andric void pushValue(const Value *V, unsigned InstID,
40001095a5dSDimitry Andric SmallVectorImpl<unsigned> &Vals);
40101095a5dSDimitry Andric void pushValueSigned(const Value *V, unsigned InstID,
40201095a5dSDimitry Andric SmallVectorImpl<uint64_t> &Vals);
40301095a5dSDimitry Andric void writeInstruction(const Instruction &I, unsigned InstID,
40401095a5dSDimitry Andric SmallVectorImpl<unsigned> &Vals);
405d99dafe2SDimitry Andric void writeFunctionLevelValueSymbolTable(const ValueSymbolTable &VST);
406d99dafe2SDimitry Andric void writeGlobalValueSymbolTable(
407d99dafe2SDimitry Andric DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
40801095a5dSDimitry Andric void writeUseList(UseListOrder &&Order);
40901095a5dSDimitry Andric void writeUseListBlock(const Function *F);
41001095a5dSDimitry Andric void
41101095a5dSDimitry Andric writeFunction(const Function &F,
41201095a5dSDimitry Andric DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
41301095a5dSDimitry Andric void writeBlockInfo();
414ac9a064cSDimitry Andric void writeModuleHash(StringRef View);
41501095a5dSDimitry Andric
getEncodedSyncScopeID(SyncScope::ID SSID)416ca089b24SDimitry Andric unsigned getEncodedSyncScopeID(SyncScope::ID SSID) {
417ca089b24SDimitry Andric return unsigned(SSID);
418ca089b24SDimitry Andric }
419b60736ecSDimitry Andric
getEncodedAlign(MaybeAlign Alignment)420b60736ecSDimitry Andric unsigned getEncodedAlign(MaybeAlign Alignment) { return encode(Alignment); }
42101095a5dSDimitry Andric };
42201095a5dSDimitry Andric
42301095a5dSDimitry Andric /// Class to manage the bitcode writing for a combined index.
424b915e9e0SDimitry Andric class IndexBitcodeWriter : public BitcodeWriterBase {
42501095a5dSDimitry Andric /// The combined index to write to bitcode.
42601095a5dSDimitry Andric const ModuleSummaryIndex &Index;
42701095a5dSDimitry Andric
428ac9a064cSDimitry Andric /// When writing combined summaries, provides the set of global value
429ac9a064cSDimitry Andric /// summaries for which the value (function, function alias, etc) should be
430ac9a064cSDimitry Andric /// imported as a declaration.
431ac9a064cSDimitry Andric const GVSummaryPtrSet *DecSummaries = nullptr;
432ac9a064cSDimitry Andric
43301095a5dSDimitry Andric /// When writing a subset of the index for distributed backends, client
43401095a5dSDimitry Andric /// provides a map of modules to the corresponding GUIDs/summaries to write.
435b915e9e0SDimitry Andric const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex;
43601095a5dSDimitry Andric
43701095a5dSDimitry Andric /// Map that holds the correspondence between the GUID used in the combined
43801095a5dSDimitry Andric /// index and a value id generated by this class to use in references.
43901095a5dSDimitry Andric std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
44001095a5dSDimitry Andric
441ac9a064cSDimitry Andric // The stack ids used by this index, which will be a subset of those in
442ac9a064cSDimitry Andric // the full index in the case of distributed indexes.
443ac9a064cSDimitry Andric std::vector<uint64_t> StackIds;
444ac9a064cSDimitry Andric
445ac9a064cSDimitry Andric // Keep a map of the stack id indices used by records being written for this
446ac9a064cSDimitry Andric // index to the index of the corresponding stack id in the above StackIds
447ac9a064cSDimitry Andric // vector. Ensures we write each referenced stack id once.
448ac9a064cSDimitry Andric DenseMap<unsigned, unsigned> StackIdIndicesToIndex;
449e3b55780SDimitry Andric
45001095a5dSDimitry Andric /// Tracks the last value id recorded in the GUIDToValueMap.
45101095a5dSDimitry Andric unsigned GlobalValueId = 0;
45201095a5dSDimitry Andric
453b1c73532SDimitry Andric /// Tracks the assignment of module paths in the module path string table to
454b1c73532SDimitry Andric /// an id assigned for use in summary references to the module path.
455b1c73532SDimitry Andric DenseMap<StringRef, uint64_t> ModuleIdMap;
456b1c73532SDimitry Andric
45701095a5dSDimitry Andric public:
45801095a5dSDimitry Andric /// Constructs a IndexBitcodeWriter object for the given combined index,
45901095a5dSDimitry Andric /// writing to the provided \p Buffer. When writing a subset of the index
46001095a5dSDimitry Andric /// for a distributed backend, provide a \p ModuleToSummariesForIndex map.
461ac9a064cSDimitry Andric /// If provided, \p DecSummaries specifies the set of summaries for which
462ac9a064cSDimitry Andric /// the corresponding functions or aliased functions should be imported as a
463ac9a064cSDimitry Andric /// declaration (but not definition) for each module.
IndexBitcodeWriter(BitstreamWriter & Stream,StringTableBuilder & StrtabBuilder,const ModuleSummaryIndex & Index,const GVSummaryPtrSet * DecSummaries=nullptr,const std::map<std::string,GVSummaryMapTy> * ModuleToSummariesForIndex=nullptr)4647c7aba6eSDimitry Andric IndexBitcodeWriter(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder,
4657c7aba6eSDimitry Andric const ModuleSummaryIndex &Index,
466ac9a064cSDimitry Andric const GVSummaryPtrSet *DecSummaries = nullptr,
467b915e9e0SDimitry Andric const std::map<std::string, GVSummaryMapTy>
46801095a5dSDimitry Andric *ModuleToSummariesForIndex = nullptr)
4697c7aba6eSDimitry Andric : BitcodeWriterBase(Stream, StrtabBuilder), Index(Index),
470ac9a064cSDimitry Andric DecSummaries(DecSummaries),
47101095a5dSDimitry Andric ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
472ac9a064cSDimitry Andric
473ac9a064cSDimitry Andric // See if the StackIdIndex was already added to the StackId map and
474ac9a064cSDimitry Andric // vector. If not, record it.
475ac9a064cSDimitry Andric auto RecordStackIdReference = [&](unsigned StackIdIndex) {
476ac9a064cSDimitry Andric // If the StackIdIndex is not yet in the map, the below insert ensures
477ac9a064cSDimitry Andric // that it will point to the new StackIds vector entry we push to just
478ac9a064cSDimitry Andric // below.
479ac9a064cSDimitry Andric auto Inserted =
480ac9a064cSDimitry Andric StackIdIndicesToIndex.insert({StackIdIndex, StackIds.size()});
481ac9a064cSDimitry Andric if (Inserted.second)
482ac9a064cSDimitry Andric StackIds.push_back(Index.getStackIdAtIndex(StackIdIndex));
483ac9a064cSDimitry Andric };
484ac9a064cSDimitry Andric
48501095a5dSDimitry Andric // Assign unique value ids to all summaries to be written, for use
48601095a5dSDimitry Andric // in writing out the call graph edges. Save the mapping from GUID
48701095a5dSDimitry Andric // to the new global value id to use when writing those edges, which
48801095a5dSDimitry Andric // are currently saved in the index in terms of GUID.
489e3b55780SDimitry Andric forEachSummary([&](GVInfo I, bool IsAliasee) {
49001095a5dSDimitry Andric GUIDToValueIdMap[I.first] = ++GlobalValueId;
491e3b55780SDimitry Andric if (IsAliasee)
492e3b55780SDimitry Andric return;
493e3b55780SDimitry Andric auto *FS = dyn_cast<FunctionSummary>(I.second);
494e3b55780SDimitry Andric if (!FS)
495e3b55780SDimitry Andric return;
496e3b55780SDimitry Andric // Record all stack id indices actually used in the summary entries being
497e3b55780SDimitry Andric // written, so that we can compact them in the case of distributed ThinLTO
498e3b55780SDimitry Andric // indexes.
499950076cdSDimitry Andric for (auto &CI : FS->callsites()) {
500950076cdSDimitry Andric // If the stack id list is empty, this callsite info was synthesized for
501950076cdSDimitry Andric // a missing tail call frame. Ensure that the callee's GUID gets a value
502950076cdSDimitry Andric // id. Normally we only generate these for defined summaries, which in
503950076cdSDimitry Andric // the case of distributed ThinLTO is only the functions already defined
504950076cdSDimitry Andric // in the module or that we want to import. We don't bother to include
505950076cdSDimitry Andric // all the callee symbols as they aren't normally needed in the backend.
506950076cdSDimitry Andric // However, for the synthesized callsite infos we do need the callee
507950076cdSDimitry Andric // GUID in the backend so that we can correlate the identified callee
508950076cdSDimitry Andric // with this callsite info (which for non-tail calls is done by the
509950076cdSDimitry Andric // ordering of the callsite infos and verified via stack ids).
510950076cdSDimitry Andric if (CI.StackIdIndices.empty()) {
511950076cdSDimitry Andric GUIDToValueIdMap[CI.Callee.getGUID()] = ++GlobalValueId;
512950076cdSDimitry Andric continue;
513950076cdSDimitry Andric }
514e3b55780SDimitry Andric for (auto Idx : CI.StackIdIndices)
515ac9a064cSDimitry Andric RecordStackIdReference(Idx);
516950076cdSDimitry Andric }
517e3b55780SDimitry Andric for (auto &AI : FS->allocs())
518e3b55780SDimitry Andric for (auto &MIB : AI.MIBs)
519e3b55780SDimitry Andric for (auto Idx : MIB.StackIdIndices)
520ac9a064cSDimitry Andric RecordStackIdReference(Idx);
521148779dfSDimitry Andric });
52201095a5dSDimitry Andric }
52301095a5dSDimitry Andric
52401095a5dSDimitry Andric /// The below iterator returns the GUID and associated summary.
525044eb2f6SDimitry Andric using GVInfo = std::pair<GlobalValue::GUID, GlobalValueSummary *>;
52601095a5dSDimitry Andric
527148779dfSDimitry Andric /// Calls the callback for each value GUID and summary to be written to
528148779dfSDimitry Andric /// bitcode. This hides the details of whether they are being pulled from the
529148779dfSDimitry Andric /// entire index or just those in a provided ModuleToSummariesForIndex map.
530d288ef4cSDimitry Andric template<typename Functor>
forEachSummary(Functor Callback)531d288ef4cSDimitry Andric void forEachSummary(Functor Callback) {
532148779dfSDimitry Andric if (ModuleToSummariesForIndex) {
533148779dfSDimitry Andric for (auto &M : *ModuleToSummariesForIndex)
534044eb2f6SDimitry Andric for (auto &Summary : M.second) {
535044eb2f6SDimitry Andric Callback(Summary, false);
536044eb2f6SDimitry Andric // Ensure aliasee is handled, e.g. for assigning a valueId,
537044eb2f6SDimitry Andric // even if we are not importing the aliasee directly (the
538044eb2f6SDimitry Andric // imported alias will contain a copy of aliasee).
539044eb2f6SDimitry Andric if (auto *AS = dyn_cast<AliasSummary>(Summary.getSecond()))
540044eb2f6SDimitry Andric Callback({AS->getAliaseeGUID(), &AS->getAliasee()}, true);
541044eb2f6SDimitry Andric }
54201095a5dSDimitry Andric } else {
543148779dfSDimitry Andric for (auto &Summaries : Index)
544c46e6a59SDimitry Andric for (auto &Summary : Summaries.second.SummaryList)
545044eb2f6SDimitry Andric Callback({Summaries.first, Summary.get()}, false);
54601095a5dSDimitry Andric }
54701095a5dSDimitry Andric }
54801095a5dSDimitry Andric
549d288ef4cSDimitry Andric /// Calls the callback for each entry in the modulePaths StringMap that
550d288ef4cSDimitry Andric /// should be written to the module path string table. This hides the details
551d288ef4cSDimitry Andric /// of whether they are being pulled from the entire index or just those in a
552d288ef4cSDimitry Andric /// provided ModuleToSummariesForIndex map.
forEachModule(Functor Callback)553d288ef4cSDimitry Andric template <typename Functor> void forEachModule(Functor Callback) {
554d288ef4cSDimitry Andric if (ModuleToSummariesForIndex) {
555d288ef4cSDimitry Andric for (const auto &M : *ModuleToSummariesForIndex) {
556d288ef4cSDimitry Andric const auto &MPI = Index.modulePaths().find(M.first);
557d288ef4cSDimitry Andric if (MPI == Index.modulePaths().end()) {
558d288ef4cSDimitry Andric // This should only happen if the bitcode file was empty, in which
559d288ef4cSDimitry Andric // case we shouldn't be importing (the ModuleToSummariesForIndex
560d288ef4cSDimitry Andric // would only include the module we are writing and index for).
561d288ef4cSDimitry Andric assert(ModuleToSummariesForIndex->size() == 1);
562d288ef4cSDimitry Andric continue;
563d288ef4cSDimitry Andric }
564d288ef4cSDimitry Andric Callback(*MPI);
565d288ef4cSDimitry Andric }
566d288ef4cSDimitry Andric } else {
567b1c73532SDimitry Andric // Since StringMap iteration order isn't guaranteed, order by path string
568b1c73532SDimitry Andric // first.
569b1c73532SDimitry Andric // FIXME: Make this a vector of StringMapEntry instead to avoid the later
570b1c73532SDimitry Andric // map lookup.
571b1c73532SDimitry Andric std::vector<StringRef> ModulePaths;
572b1c73532SDimitry Andric for (auto &[ModPath, _] : Index.modulePaths())
573b1c73532SDimitry Andric ModulePaths.push_back(ModPath);
574b1c73532SDimitry Andric llvm::sort(ModulePaths.begin(), ModulePaths.end());
575b1c73532SDimitry Andric for (auto &ModPath : ModulePaths)
576b1c73532SDimitry Andric Callback(*Index.modulePaths().find(ModPath));
577d288ef4cSDimitry Andric }
578d288ef4cSDimitry Andric }
579d288ef4cSDimitry Andric
580b915e9e0SDimitry Andric /// Main entry point for writing a combined index to bitcode.
581b915e9e0SDimitry Andric void write();
58201095a5dSDimitry Andric
583b915e9e0SDimitry Andric private:
58401095a5dSDimitry Andric void writeModStrings();
58501095a5dSDimitry Andric void writeCombinedGlobalValueSummary();
58601095a5dSDimitry Andric
getValueId(GlobalValue::GUID ValGUID)587e3b55780SDimitry Andric std::optional<unsigned> getValueId(GlobalValue::GUID ValGUID) {
588d99dafe2SDimitry Andric auto VMI = GUIDToValueIdMap.find(ValGUID);
589f382538dSDimitry Andric if (VMI == GUIDToValueIdMap.end())
590e3b55780SDimitry Andric return std::nullopt;
591d99dafe2SDimitry Andric return VMI->second;
59201095a5dSDimitry Andric }
593044eb2f6SDimitry Andric
valueIds()59401095a5dSDimitry Andric std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
59501095a5dSDimitry Andric };
596044eb2f6SDimitry Andric
59701095a5dSDimitry Andric } // end anonymous namespace
59801095a5dSDimitry Andric
getEncodedCastOpcode(unsigned Opcode)59901095a5dSDimitry Andric static unsigned getEncodedCastOpcode(unsigned Opcode) {
600009b1c42SEd Schouten switch (Opcode) {
60159850d08SRoman Divacky default: llvm_unreachable("Unknown cast instruction!");
602009b1c42SEd Schouten case Instruction::Trunc : return bitc::CAST_TRUNC;
603009b1c42SEd Schouten case Instruction::ZExt : return bitc::CAST_ZEXT;
604009b1c42SEd Schouten case Instruction::SExt : return bitc::CAST_SEXT;
605009b1c42SEd Schouten case Instruction::FPToUI : return bitc::CAST_FPTOUI;
606009b1c42SEd Schouten case Instruction::FPToSI : return bitc::CAST_FPTOSI;
607009b1c42SEd Schouten case Instruction::UIToFP : return bitc::CAST_UITOFP;
608009b1c42SEd Schouten case Instruction::SIToFP : return bitc::CAST_SITOFP;
609009b1c42SEd Schouten case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
610009b1c42SEd Schouten case Instruction::FPExt : return bitc::CAST_FPEXT;
611009b1c42SEd Schouten case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
612009b1c42SEd Schouten case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
613009b1c42SEd Schouten case Instruction::BitCast : return bitc::CAST_BITCAST;
614f8af5cf6SDimitry Andric case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
615009b1c42SEd Schouten }
616009b1c42SEd Schouten }
617009b1c42SEd Schouten
getEncodedUnaryOpcode(unsigned Opcode)618d8e91e46SDimitry Andric static unsigned getEncodedUnaryOpcode(unsigned Opcode) {
619d8e91e46SDimitry Andric switch (Opcode) {
620d8e91e46SDimitry Andric default: llvm_unreachable("Unknown binary instruction!");
6211d5ae102SDimitry Andric case Instruction::FNeg: return bitc::UNOP_FNEG;
622d8e91e46SDimitry Andric }
623d8e91e46SDimitry Andric }
624d8e91e46SDimitry Andric
getEncodedBinaryOpcode(unsigned Opcode)62501095a5dSDimitry Andric static unsigned getEncodedBinaryOpcode(unsigned Opcode) {
626009b1c42SEd Schouten switch (Opcode) {
62759850d08SRoman Divacky default: llvm_unreachable("Unknown binary instruction!");
628f4fe016fSEd Schouten case Instruction::Add:
629f4fe016fSEd Schouten case Instruction::FAdd: return bitc::BINOP_ADD;
630f4fe016fSEd Schouten case Instruction::Sub:
631f4fe016fSEd Schouten case Instruction::FSub: return bitc::BINOP_SUB;
632f4fe016fSEd Schouten case Instruction::Mul:
633f4fe016fSEd Schouten case Instruction::FMul: return bitc::BINOP_MUL;
634009b1c42SEd Schouten case Instruction::UDiv: return bitc::BINOP_UDIV;
635009b1c42SEd Schouten case Instruction::FDiv:
636009b1c42SEd Schouten case Instruction::SDiv: return bitc::BINOP_SDIV;
637009b1c42SEd Schouten case Instruction::URem: return bitc::BINOP_UREM;
638009b1c42SEd Schouten case Instruction::FRem:
639009b1c42SEd Schouten case Instruction::SRem: return bitc::BINOP_SREM;
640009b1c42SEd Schouten case Instruction::Shl: return bitc::BINOP_SHL;
641009b1c42SEd Schouten case Instruction::LShr: return bitc::BINOP_LSHR;
642009b1c42SEd Schouten case Instruction::AShr: return bitc::BINOP_ASHR;
643009b1c42SEd Schouten case Instruction::And: return bitc::BINOP_AND;
644009b1c42SEd Schouten case Instruction::Or: return bitc::BINOP_OR;
645009b1c42SEd Schouten case Instruction::Xor: return bitc::BINOP_XOR;
646009b1c42SEd Schouten }
647009b1c42SEd Schouten }
648009b1c42SEd Schouten
getEncodedRMWOperation(AtomicRMWInst::BinOp Op)64901095a5dSDimitry Andric static unsigned getEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
65030815c53SDimitry Andric switch (Op) {
65130815c53SDimitry Andric default: llvm_unreachable("Unknown RMW operation!");
65230815c53SDimitry Andric case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
65330815c53SDimitry Andric case AtomicRMWInst::Add: return bitc::RMW_ADD;
65430815c53SDimitry Andric case AtomicRMWInst::Sub: return bitc::RMW_SUB;
65530815c53SDimitry Andric case AtomicRMWInst::And: return bitc::RMW_AND;
65630815c53SDimitry Andric case AtomicRMWInst::Nand: return bitc::RMW_NAND;
65730815c53SDimitry Andric case AtomicRMWInst::Or: return bitc::RMW_OR;
65830815c53SDimitry Andric case AtomicRMWInst::Xor: return bitc::RMW_XOR;
65930815c53SDimitry Andric case AtomicRMWInst::Max: return bitc::RMW_MAX;
66030815c53SDimitry Andric case AtomicRMWInst::Min: return bitc::RMW_MIN;
66130815c53SDimitry Andric case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
66230815c53SDimitry Andric case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
663e6d15924SDimitry Andric case AtomicRMWInst::FAdd: return bitc::RMW_FADD;
664e6d15924SDimitry Andric case AtomicRMWInst::FSub: return bitc::RMW_FSUB;
6651f917f69SDimitry Andric case AtomicRMWInst::FMax: return bitc::RMW_FMAX;
6661f917f69SDimitry Andric case AtomicRMWInst::FMin: return bitc::RMW_FMIN;
667e3b55780SDimitry Andric case AtomicRMWInst::UIncWrap:
668e3b55780SDimitry Andric return bitc::RMW_UINC_WRAP;
669e3b55780SDimitry Andric case AtomicRMWInst::UDecWrap:
670e3b55780SDimitry Andric return bitc::RMW_UDEC_WRAP;
67130815c53SDimitry Andric }
67230815c53SDimitry Andric }
67330815c53SDimitry Andric
getEncodedOrdering(AtomicOrdering Ordering)67401095a5dSDimitry Andric static unsigned getEncodedOrdering(AtomicOrdering Ordering) {
67530815c53SDimitry Andric switch (Ordering) {
67601095a5dSDimitry Andric case AtomicOrdering::NotAtomic: return bitc::ORDERING_NOTATOMIC;
67701095a5dSDimitry Andric case AtomicOrdering::Unordered: return bitc::ORDERING_UNORDERED;
67801095a5dSDimitry Andric case AtomicOrdering::Monotonic: return bitc::ORDERING_MONOTONIC;
67901095a5dSDimitry Andric case AtomicOrdering::Acquire: return bitc::ORDERING_ACQUIRE;
68001095a5dSDimitry Andric case AtomicOrdering::Release: return bitc::ORDERING_RELEASE;
68101095a5dSDimitry Andric case AtomicOrdering::AcquireRelease: return bitc::ORDERING_ACQREL;
68201095a5dSDimitry Andric case AtomicOrdering::SequentiallyConsistent: return bitc::ORDERING_SEQCST;
68330815c53SDimitry Andric }
68463faed5bSDimitry Andric llvm_unreachable("Invalid ordering");
68530815c53SDimitry Andric }
68630815c53SDimitry Andric
writeStringRecord(BitstreamWriter & Stream,unsigned Code,StringRef Str,unsigned AbbrevToUse)687b915e9e0SDimitry Andric static void writeStringRecord(BitstreamWriter &Stream, unsigned Code,
688b915e9e0SDimitry Andric StringRef Str, unsigned AbbrevToUse) {
689009b1c42SEd Schouten SmallVector<unsigned, 64> Vals;
690009b1c42SEd Schouten
691009b1c42SEd Schouten // Code: [strchar x N]
692f65dcba8SDimitry Andric for (char C : Str) {
693f65dcba8SDimitry Andric if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(C))
694411bd29eSDimitry Andric AbbrevToUse = 0;
695f65dcba8SDimitry Andric Vals.push_back(C);
696411bd29eSDimitry Andric }
697009b1c42SEd Schouten
698009b1c42SEd Schouten // Emit the finished record.
699009b1c42SEd Schouten Stream.EmitRecord(Code, Vals, AbbrevToUse);
700009b1c42SEd Schouten }
701009b1c42SEd Schouten
getAttrKindEncoding(Attribute::AttrKind Kind)702f8af5cf6SDimitry Andric static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
703f8af5cf6SDimitry Andric switch (Kind) {
704f8af5cf6SDimitry Andric case Attribute::Alignment:
705f8af5cf6SDimitry Andric return bitc::ATTR_KIND_ALIGNMENT;
706145449b1SDimitry Andric case Attribute::AllocAlign:
707145449b1SDimitry Andric return bitc::ATTR_KIND_ALLOC_ALIGN;
70801095a5dSDimitry Andric case Attribute::AllocSize:
70901095a5dSDimitry Andric return bitc::ATTR_KIND_ALLOC_SIZE;
710f8af5cf6SDimitry Andric case Attribute::AlwaysInline:
711f8af5cf6SDimitry Andric return bitc::ATTR_KIND_ALWAYS_INLINE;
712f8af5cf6SDimitry Andric case Attribute::Builtin:
713f8af5cf6SDimitry Andric return bitc::ATTR_KIND_BUILTIN;
714f8af5cf6SDimitry Andric case Attribute::ByVal:
715f8af5cf6SDimitry Andric return bitc::ATTR_KIND_BY_VAL;
7165a5ac124SDimitry Andric case Attribute::Convergent:
7175a5ac124SDimitry Andric return bitc::ATTR_KIND_CONVERGENT;
7185ca98fd9SDimitry Andric case Attribute::InAlloca:
7195ca98fd9SDimitry Andric return bitc::ATTR_KIND_IN_ALLOCA;
720f8af5cf6SDimitry Andric case Attribute::Cold:
721f8af5cf6SDimitry Andric return bitc::ATTR_KIND_COLD;
722c0981da4SDimitry Andric case Attribute::DisableSanitizerInstrumentation:
723c0981da4SDimitry Andric return bitc::ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION;
7241f917f69SDimitry Andric case Attribute::FnRetThunkExtern:
7251f917f69SDimitry Andric return bitc::ATTR_KIND_FNRETTHUNK_EXTERN;
726b60736ecSDimitry Andric case Attribute::Hot:
727b60736ecSDimitry Andric return bitc::ATTR_KIND_HOT;
728344a3780SDimitry Andric case Attribute::ElementType:
729344a3780SDimitry Andric return bitc::ATTR_KIND_ELEMENTTYPE;
730ac9a064cSDimitry Andric case Attribute::HybridPatchable:
731ac9a064cSDimitry Andric return bitc::ATTR_KIND_HYBRID_PATCHABLE;
732f8af5cf6SDimitry Andric case Attribute::InlineHint:
733f8af5cf6SDimitry Andric return bitc::ATTR_KIND_INLINE_HINT;
734f8af5cf6SDimitry Andric case Attribute::InReg:
735f8af5cf6SDimitry Andric return bitc::ATTR_KIND_IN_REG;
7365ca98fd9SDimitry Andric case Attribute::JumpTable:
7375ca98fd9SDimitry Andric return bitc::ATTR_KIND_JUMP_TABLE;
738f8af5cf6SDimitry Andric case Attribute::MinSize:
739f8af5cf6SDimitry Andric return bitc::ATTR_KIND_MIN_SIZE;
740145449b1SDimitry Andric case Attribute::AllocatedPointer:
741145449b1SDimitry Andric return bitc::ATTR_KIND_ALLOCATED_POINTER;
742145449b1SDimitry Andric case Attribute::AllocKind:
743145449b1SDimitry Andric return bitc::ATTR_KIND_ALLOC_KIND;
744e3b55780SDimitry Andric case Attribute::Memory:
745e3b55780SDimitry Andric return bitc::ATTR_KIND_MEMORY;
7467fa27ce4SDimitry Andric case Attribute::NoFPClass:
7477fa27ce4SDimitry Andric return bitc::ATTR_KIND_NOFPCLASS;
748f8af5cf6SDimitry Andric case Attribute::Naked:
749f8af5cf6SDimitry Andric return bitc::ATTR_KIND_NAKED;
750f8af5cf6SDimitry Andric case Attribute::Nest:
751f8af5cf6SDimitry Andric return bitc::ATTR_KIND_NEST;
752f8af5cf6SDimitry Andric case Attribute::NoAlias:
753f8af5cf6SDimitry Andric return bitc::ATTR_KIND_NO_ALIAS;
754f8af5cf6SDimitry Andric case Attribute::NoBuiltin:
755f8af5cf6SDimitry Andric return bitc::ATTR_KIND_NO_BUILTIN;
756b60736ecSDimitry Andric case Attribute::NoCallback:
757b60736ecSDimitry Andric return bitc::ATTR_KIND_NO_CALLBACK;
758f8af5cf6SDimitry Andric case Attribute::NoCapture:
759f8af5cf6SDimitry Andric return bitc::ATTR_KIND_NO_CAPTURE;
760f8af5cf6SDimitry Andric case Attribute::NoDuplicate:
761f8af5cf6SDimitry Andric return bitc::ATTR_KIND_NO_DUPLICATE;
762e6d15924SDimitry Andric case Attribute::NoFree:
763e6d15924SDimitry Andric return bitc::ATTR_KIND_NOFREE;
764f8af5cf6SDimitry Andric case Attribute::NoImplicitFloat:
765f8af5cf6SDimitry Andric return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
766f8af5cf6SDimitry Andric case Attribute::NoInline:
767f8af5cf6SDimitry Andric return bitc::ATTR_KIND_NO_INLINE;
768dd58ef01SDimitry Andric case Attribute::NoRecurse:
769dd58ef01SDimitry Andric return bitc::ATTR_KIND_NO_RECURSE;
770cfca06d7SDimitry Andric case Attribute::NoMerge:
771cfca06d7SDimitry Andric return bitc::ATTR_KIND_NO_MERGE;
772f8af5cf6SDimitry Andric case Attribute::NonLazyBind:
773f8af5cf6SDimitry Andric return bitc::ATTR_KIND_NON_LAZY_BIND;
7745ca98fd9SDimitry Andric case Attribute::NonNull:
7755ca98fd9SDimitry Andric return bitc::ATTR_KIND_NON_NULL;
7765ca98fd9SDimitry Andric case Attribute::Dereferenceable:
7775ca98fd9SDimitry Andric return bitc::ATTR_KIND_DEREFERENCEABLE;
7785a5ac124SDimitry Andric case Attribute::DereferenceableOrNull:
7795a5ac124SDimitry Andric return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL;
780f8af5cf6SDimitry Andric case Attribute::NoRedZone:
781f8af5cf6SDimitry Andric return bitc::ATTR_KIND_NO_RED_ZONE;
782f8af5cf6SDimitry Andric case Attribute::NoReturn:
783f8af5cf6SDimitry Andric return bitc::ATTR_KIND_NO_RETURN;
784e6d15924SDimitry Andric case Attribute::NoSync:
785e6d15924SDimitry Andric return bitc::ATTR_KIND_NOSYNC;
786eb11fae6SDimitry Andric case Attribute::NoCfCheck:
787eb11fae6SDimitry Andric return bitc::ATTR_KIND_NOCF_CHECK;
788b60736ecSDimitry Andric case Attribute::NoProfile:
789b60736ecSDimitry Andric return bitc::ATTR_KIND_NO_PROFILE;
790e3b55780SDimitry Andric case Attribute::SkipProfile:
791e3b55780SDimitry Andric return bitc::ATTR_KIND_SKIP_PROFILE;
792f8af5cf6SDimitry Andric case Attribute::NoUnwind:
793f8af5cf6SDimitry Andric return bitc::ATTR_KIND_NO_UNWIND;
794145449b1SDimitry Andric case Attribute::NoSanitizeBounds:
795145449b1SDimitry Andric return bitc::ATTR_KIND_NO_SANITIZE_BOUNDS;
796344a3780SDimitry Andric case Attribute::NoSanitizeCoverage:
797344a3780SDimitry Andric return bitc::ATTR_KIND_NO_SANITIZE_COVERAGE;
798cfca06d7SDimitry Andric case Attribute::NullPointerIsValid:
799cfca06d7SDimitry Andric return bitc::ATTR_KIND_NULL_POINTER_IS_VALID;
800b1c73532SDimitry Andric case Attribute::OptimizeForDebugging:
801b1c73532SDimitry Andric return bitc::ATTR_KIND_OPTIMIZE_FOR_DEBUGGING;
802eb11fae6SDimitry Andric case Attribute::OptForFuzzing:
803eb11fae6SDimitry Andric return bitc::ATTR_KIND_OPT_FOR_FUZZING;
804f8af5cf6SDimitry Andric case Attribute::OptimizeForSize:
805f8af5cf6SDimitry Andric return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
806f8af5cf6SDimitry Andric case Attribute::OptimizeNone:
807f8af5cf6SDimitry Andric return bitc::ATTR_KIND_OPTIMIZE_NONE;
808f8af5cf6SDimitry Andric case Attribute::ReadNone:
809f8af5cf6SDimitry Andric return bitc::ATTR_KIND_READ_NONE;
810f8af5cf6SDimitry Andric case Attribute::ReadOnly:
811f8af5cf6SDimitry Andric return bitc::ATTR_KIND_READ_ONLY;
812f8af5cf6SDimitry Andric case Attribute::Returned:
813f8af5cf6SDimitry Andric return bitc::ATTR_KIND_RETURNED;
814f8af5cf6SDimitry Andric case Attribute::ReturnsTwice:
815f8af5cf6SDimitry Andric return bitc::ATTR_KIND_RETURNS_TWICE;
816f8af5cf6SDimitry Andric case Attribute::SExt:
817f8af5cf6SDimitry Andric return bitc::ATTR_KIND_S_EXT;
818a303c417SDimitry Andric case Attribute::Speculatable:
819a303c417SDimitry Andric return bitc::ATTR_KIND_SPECULATABLE;
820f8af5cf6SDimitry Andric case Attribute::StackAlignment:
821f8af5cf6SDimitry Andric return bitc::ATTR_KIND_STACK_ALIGNMENT;
822f8af5cf6SDimitry Andric case Attribute::StackProtect:
823f8af5cf6SDimitry Andric return bitc::ATTR_KIND_STACK_PROTECT;
824f8af5cf6SDimitry Andric case Attribute::StackProtectReq:
825f8af5cf6SDimitry Andric return bitc::ATTR_KIND_STACK_PROTECT_REQ;
826f8af5cf6SDimitry Andric case Attribute::StackProtectStrong:
827f8af5cf6SDimitry Andric return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
8283a0822f0SDimitry Andric case Attribute::SafeStack:
8293a0822f0SDimitry Andric return bitc::ATTR_KIND_SAFESTACK;
830eb11fae6SDimitry Andric case Attribute::ShadowCallStack:
831eb11fae6SDimitry Andric return bitc::ATTR_KIND_SHADOWCALLSTACK;
832044eb2f6SDimitry Andric case Attribute::StrictFP:
833044eb2f6SDimitry Andric return bitc::ATTR_KIND_STRICT_FP;
834f8af5cf6SDimitry Andric case Attribute::StructRet:
835f8af5cf6SDimitry Andric return bitc::ATTR_KIND_STRUCT_RET;
836f8af5cf6SDimitry Andric case Attribute::SanitizeAddress:
837f8af5cf6SDimitry Andric return bitc::ATTR_KIND_SANITIZE_ADDRESS;
838044eb2f6SDimitry Andric case Attribute::SanitizeHWAddress:
839044eb2f6SDimitry Andric return bitc::ATTR_KIND_SANITIZE_HWADDRESS;
840f8af5cf6SDimitry Andric case Attribute::SanitizeThread:
841f8af5cf6SDimitry Andric return bitc::ATTR_KIND_SANITIZE_THREAD;
842f8af5cf6SDimitry Andric case Attribute::SanitizeMemory:
843f8af5cf6SDimitry Andric return bitc::ATTR_KIND_SANITIZE_MEMORY;
844ac9a064cSDimitry Andric case Attribute::SanitizeNumericalStability:
845ac9a064cSDimitry Andric return bitc::ATTR_KIND_SANITIZE_NUMERICAL_STABILITY;
846d8e91e46SDimitry Andric case Attribute::SpeculativeLoadHardening:
847d8e91e46SDimitry Andric return bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING;
84801095a5dSDimitry Andric case Attribute::SwiftError:
84901095a5dSDimitry Andric return bitc::ATTR_KIND_SWIFT_ERROR;
85001095a5dSDimitry Andric case Attribute::SwiftSelf:
85101095a5dSDimitry Andric return bitc::ATTR_KIND_SWIFT_SELF;
852344a3780SDimitry Andric case Attribute::SwiftAsync:
853344a3780SDimitry Andric return bitc::ATTR_KIND_SWIFT_ASYNC;
854f8af5cf6SDimitry Andric case Attribute::UWTable:
855f8af5cf6SDimitry Andric return bitc::ATTR_KIND_UW_TABLE;
856344a3780SDimitry Andric case Attribute::VScaleRange:
857344a3780SDimitry Andric return bitc::ATTR_KIND_VSCALE_RANGE;
858e6d15924SDimitry Andric case Attribute::WillReturn:
859e6d15924SDimitry Andric return bitc::ATTR_KIND_WILLRETURN;
86001095a5dSDimitry Andric case Attribute::WriteOnly:
86101095a5dSDimitry Andric return bitc::ATTR_KIND_WRITEONLY;
862f8af5cf6SDimitry Andric case Attribute::ZExt:
863f8af5cf6SDimitry Andric return bitc::ATTR_KIND_Z_EXT;
864e6d15924SDimitry Andric case Attribute::ImmArg:
865e6d15924SDimitry Andric return bitc::ATTR_KIND_IMMARG;
866e6d15924SDimitry Andric case Attribute::SanitizeMemTag:
867e6d15924SDimitry Andric return bitc::ATTR_KIND_SANITIZE_MEMTAG;
868cfca06d7SDimitry Andric case Attribute::Preallocated:
869cfca06d7SDimitry Andric return bitc::ATTR_KIND_PREALLOCATED;
870cfca06d7SDimitry Andric case Attribute::NoUndef:
871cfca06d7SDimitry Andric return bitc::ATTR_KIND_NOUNDEF;
872b60736ecSDimitry Andric case Attribute::ByRef:
873b60736ecSDimitry Andric return bitc::ATTR_KIND_BYREF;
874b60736ecSDimitry Andric case Attribute::MustProgress:
875b60736ecSDimitry Andric return bitc::ATTR_KIND_MUSTPROGRESS;
876145449b1SDimitry Andric case Attribute::PresplitCoroutine:
877145449b1SDimitry Andric return bitc::ATTR_KIND_PRESPLIT_COROUTINE;
878b1c73532SDimitry Andric case Attribute::Writable:
879b1c73532SDimitry Andric return bitc::ATTR_KIND_WRITABLE;
880b1c73532SDimitry Andric case Attribute::CoroDestroyOnlyWhenComplete:
881b1c73532SDimitry Andric return bitc::ATTR_KIND_CORO_ONLY_DESTROY_WHEN_COMPLETE;
882312c0ed1SDimitry Andric case Attribute::DeadOnUnwind:
883312c0ed1SDimitry Andric return bitc::ATTR_KIND_DEAD_ON_UNWIND;
884ac9a064cSDimitry Andric case Attribute::Range:
885ac9a064cSDimitry Andric return bitc::ATTR_KIND_RANGE;
886ac9a064cSDimitry Andric case Attribute::Initializes:
887ac9a064cSDimitry Andric return bitc::ATTR_KIND_INITIALIZES;
888f8af5cf6SDimitry Andric case Attribute::EndAttrKinds:
889f8af5cf6SDimitry Andric llvm_unreachable("Can not encode end-attribute kinds marker.");
890f8af5cf6SDimitry Andric case Attribute::None:
891f8af5cf6SDimitry Andric llvm_unreachable("Can not encode none-attribute.");
892cfca06d7SDimitry Andric case Attribute::EmptyKey:
893cfca06d7SDimitry Andric case Attribute::TombstoneKey:
894cfca06d7SDimitry Andric llvm_unreachable("Trying to encode EmptyKey/TombstoneKey");
895f8af5cf6SDimitry Andric }
896f8af5cf6SDimitry Andric
897f8af5cf6SDimitry Andric llvm_unreachable("Trying to encode unknown attribute");
898f8af5cf6SDimitry Andric }
899f8af5cf6SDimitry Andric
emitSignedInt64(SmallVectorImpl<uint64_t> & Vals,uint64_t V)900ac9a064cSDimitry Andric static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
901ac9a064cSDimitry Andric if ((int64_t)V >= 0)
902ac9a064cSDimitry Andric Vals.push_back(V << 1);
903ac9a064cSDimitry Andric else
904ac9a064cSDimitry Andric Vals.push_back((-V << 1) | 1);
905ac9a064cSDimitry Andric }
906ac9a064cSDimitry Andric
emitWideAPInt(SmallVectorImpl<uint64_t> & Vals,const APInt & A)907ac9a064cSDimitry Andric static void emitWideAPInt(SmallVectorImpl<uint64_t> &Vals, const APInt &A) {
908ac9a064cSDimitry Andric // We have an arbitrary precision integer value to write whose
909ac9a064cSDimitry Andric // bit width is > 64. However, in canonical unsigned integer
910ac9a064cSDimitry Andric // format it is likely that the high bits are going to be zero.
911ac9a064cSDimitry Andric // So, we only write the number of active words.
912ac9a064cSDimitry Andric unsigned NumWords = A.getActiveWords();
913ac9a064cSDimitry Andric const uint64_t *RawData = A.getRawData();
914ac9a064cSDimitry Andric for (unsigned i = 0; i < NumWords; i++)
915ac9a064cSDimitry Andric emitSignedInt64(Vals, RawData[i]);
916ac9a064cSDimitry Andric }
917ac9a064cSDimitry Andric
emitConstantRange(SmallVectorImpl<uint64_t> & Record,const ConstantRange & CR,bool EmitBitWidth)918ac9a064cSDimitry Andric static void emitConstantRange(SmallVectorImpl<uint64_t> &Record,
919ac9a064cSDimitry Andric const ConstantRange &CR, bool EmitBitWidth) {
920ac9a064cSDimitry Andric unsigned BitWidth = CR.getBitWidth();
921ac9a064cSDimitry Andric if (EmitBitWidth)
922ac9a064cSDimitry Andric Record.push_back(BitWidth);
923ac9a064cSDimitry Andric if (BitWidth > 64) {
924ac9a064cSDimitry Andric Record.push_back(CR.getLower().getActiveWords() |
925ac9a064cSDimitry Andric (uint64_t(CR.getUpper().getActiveWords()) << 32));
926ac9a064cSDimitry Andric emitWideAPInt(Record, CR.getLower());
927ac9a064cSDimitry Andric emitWideAPInt(Record, CR.getUpper());
928ac9a064cSDimitry Andric } else {
929ac9a064cSDimitry Andric emitSignedInt64(Record, CR.getLower().getSExtValue());
930ac9a064cSDimitry Andric emitSignedInt64(Record, CR.getUpper().getSExtValue());
931ac9a064cSDimitry Andric }
932ac9a064cSDimitry Andric }
933ac9a064cSDimitry Andric
writeAttributeGroupTable()93401095a5dSDimitry Andric void ModuleBitcodeWriter::writeAttributeGroupTable() {
93512f3ca4cSDimitry Andric const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
93612f3ca4cSDimitry Andric VE.getAttributeGroups();
9374a16efa3SDimitry Andric if (AttrGrps.empty()) return;
9384a16efa3SDimitry Andric
9394a16efa3SDimitry Andric Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
9404a16efa3SDimitry Andric
9414a16efa3SDimitry Andric SmallVector<uint64_t, 64> Record;
94212f3ca4cSDimitry Andric for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) {
94312f3ca4cSDimitry Andric unsigned AttrListIndex = Pair.first;
94412f3ca4cSDimitry Andric AttributeSet AS = Pair.second;
94512f3ca4cSDimitry Andric Record.push_back(VE.getAttributeGroupID(Pair));
94612f3ca4cSDimitry Andric Record.push_back(AttrListIndex);
9474a16efa3SDimitry Andric
94812f3ca4cSDimitry Andric for (Attribute Attr : AS) {
9494a16efa3SDimitry Andric if (Attr.isEnumAttribute()) {
9504a16efa3SDimitry Andric Record.push_back(0);
951f8af5cf6SDimitry Andric Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
9525ca98fd9SDimitry Andric } else if (Attr.isIntAttribute()) {
9534a16efa3SDimitry Andric Record.push_back(1);
954f8af5cf6SDimitry Andric Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
9554a16efa3SDimitry Andric Record.push_back(Attr.getValueAsInt());
956e6d15924SDimitry Andric } else if (Attr.isStringAttribute()) {
9574a16efa3SDimitry Andric StringRef Kind = Attr.getKindAsString();
9584a16efa3SDimitry Andric StringRef Val = Attr.getValueAsString();
9594a16efa3SDimitry Andric
9604a16efa3SDimitry Andric Record.push_back(Val.empty() ? 3 : 4);
9614a16efa3SDimitry Andric Record.append(Kind.begin(), Kind.end());
9624a16efa3SDimitry Andric Record.push_back(0);
9634a16efa3SDimitry Andric if (!Val.empty()) {
9644a16efa3SDimitry Andric Record.append(Val.begin(), Val.end());
9654a16efa3SDimitry Andric Record.push_back(0);
9664a16efa3SDimitry Andric }
967ac9a064cSDimitry Andric } else if (Attr.isTypeAttribute()) {
968e6d15924SDimitry Andric Type *Ty = Attr.getValueAsType();
969e6d15924SDimitry Andric Record.push_back(Ty ? 6 : 5);
970e6d15924SDimitry Andric Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
971e6d15924SDimitry Andric if (Ty)
972e6d15924SDimitry Andric Record.push_back(VE.getTypeID(Attr.getValueAsType()));
973ac9a064cSDimitry Andric } else if (Attr.isConstantRangeAttribute()) {
974ac9a064cSDimitry Andric Record.push_back(7);
975ac9a064cSDimitry Andric Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
976ac9a064cSDimitry Andric emitConstantRange(Record, Attr.getValueAsConstantRange(),
977ac9a064cSDimitry Andric /*EmitBitWidth=*/true);
978ac9a064cSDimitry Andric } else {
979ac9a064cSDimitry Andric assert(Attr.isConstantRangeListAttribute());
980ac9a064cSDimitry Andric Record.push_back(8);
981ac9a064cSDimitry Andric Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
982ac9a064cSDimitry Andric ArrayRef<ConstantRange> Val = Attr.getValueAsConstantRangeList();
983ac9a064cSDimitry Andric Record.push_back(Val.size());
984ac9a064cSDimitry Andric Record.push_back(Val[0].getBitWidth());
985ac9a064cSDimitry Andric for (auto &CR : Val)
986ac9a064cSDimitry Andric emitConstantRange(Record, CR, /*EmitBitWidth=*/false);
9874a16efa3SDimitry Andric }
9884a16efa3SDimitry Andric }
9894a16efa3SDimitry Andric
9904a16efa3SDimitry Andric Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
9914a16efa3SDimitry Andric Record.clear();
9924a16efa3SDimitry Andric }
9934a16efa3SDimitry Andric
9944a16efa3SDimitry Andric Stream.ExitBlock();
9954a16efa3SDimitry Andric }
9964a16efa3SDimitry Andric
writeAttributeTable()99701095a5dSDimitry Andric void ModuleBitcodeWriter::writeAttributeTable() {
99812f3ca4cSDimitry Andric const std::vector<AttributeList> &Attrs = VE.getAttributeLists();
999009b1c42SEd Schouten if (Attrs.empty()) return;
1000009b1c42SEd Schouten
1001009b1c42SEd Schouten Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
1002009b1c42SEd Schouten
1003009b1c42SEd Schouten SmallVector<uint64_t, 64> Record;
100477fc4c14SDimitry Andric for (const AttributeList &AL : Attrs) {
1005c0981da4SDimitry Andric for (unsigned i : AL.indexes()) {
1006ab44ce3dSDimitry Andric AttributeSet AS = AL.getAttributes(i);
1007ab44ce3dSDimitry Andric if (AS.hasAttributes())
1008ab44ce3dSDimitry Andric Record.push_back(VE.getAttributeGroupID({i, AS}));
1009ab44ce3dSDimitry Andric }
1010009b1c42SEd Schouten
1011009b1c42SEd Schouten Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
1012009b1c42SEd Schouten Record.clear();
1013009b1c42SEd Schouten }
1014009b1c42SEd Schouten
1015009b1c42SEd Schouten Stream.ExitBlock();
1016009b1c42SEd Schouten }
1017009b1c42SEd Schouten
1018009b1c42SEd Schouten /// WriteTypeTable - Write out the type table for a module.
writeTypeTable()101901095a5dSDimitry Andric void ModuleBitcodeWriter::writeTypeTable() {
1020009b1c42SEd Schouten const ValueEnumerator::TypeList &TypeList = VE.getTypes();
1021009b1c42SEd Schouten
1022411bd29eSDimitry Andric Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
1023009b1c42SEd Schouten SmallVector<uint64_t, 64> TypeVals;
1024009b1c42SEd Schouten
1025ac9a064cSDimitry Andric uint64_t NumBits = VE.computeBitsRequiredForTypeIndices();
102663faed5bSDimitry Andric
1027344a3780SDimitry Andric // Abbrev for TYPE_CODE_OPAQUE_POINTER.
10287fa27ce4SDimitry Andric auto Abbv = std::make_shared<BitCodeAbbrev>();
1029344a3780SDimitry Andric Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_OPAQUE_POINTER));
1030344a3780SDimitry Andric Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
1031344a3780SDimitry Andric unsigned OpaquePtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1032344a3780SDimitry Andric
1033009b1c42SEd Schouten // Abbrev for TYPE_CODE_FUNCTION.
10347e7b6700SDimitry Andric Abbv = std::make_shared<BitCodeAbbrev>();
1035009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
1036009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
1037009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
103863faed5bSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
10397e7b6700SDimitry Andric unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1040009b1c42SEd Schouten
1041411bd29eSDimitry Andric // Abbrev for TYPE_CODE_STRUCT_ANON.
10427e7b6700SDimitry Andric Abbv = std::make_shared<BitCodeAbbrev>();
1043411bd29eSDimitry Andric Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
1044009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
1045009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
104663faed5bSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
10477e7b6700SDimitry Andric unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1048411bd29eSDimitry Andric
1049411bd29eSDimitry Andric // Abbrev for TYPE_CODE_STRUCT_NAME.
10507e7b6700SDimitry Andric Abbv = std::make_shared<BitCodeAbbrev>();
1051411bd29eSDimitry Andric Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
1052411bd29eSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1053411bd29eSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
10547e7b6700SDimitry Andric unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1055411bd29eSDimitry Andric
1056411bd29eSDimitry Andric // Abbrev for TYPE_CODE_STRUCT_NAMED.
10577e7b6700SDimitry Andric Abbv = std::make_shared<BitCodeAbbrev>();
1058411bd29eSDimitry Andric Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
1059411bd29eSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
1060411bd29eSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
106163faed5bSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
10627e7b6700SDimitry Andric unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1063411bd29eSDimitry Andric
1064009b1c42SEd Schouten // Abbrev for TYPE_CODE_ARRAY.
10657e7b6700SDimitry Andric Abbv = std::make_shared<BitCodeAbbrev>();
1066009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
1067009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
106863faed5bSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
10697e7b6700SDimitry Andric unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1070009b1c42SEd Schouten
1071009b1c42SEd Schouten // Emit an entry count so the reader can reserve space.
1072009b1c42SEd Schouten TypeVals.push_back(TypeList.size());
1073009b1c42SEd Schouten Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
1074009b1c42SEd Schouten TypeVals.clear();
1075009b1c42SEd Schouten
1076009b1c42SEd Schouten // Loop over all of the types, emitting each in turn.
1077f65dcba8SDimitry Andric for (Type *T : TypeList) {
1078009b1c42SEd Schouten int AbbrevToUse = 0;
1079009b1c42SEd Schouten unsigned Code = 0;
1080009b1c42SEd Schouten
1081009b1c42SEd Schouten switch (T->getTypeID()) {
1082009b1c42SEd Schouten case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
108363faed5bSDimitry Andric case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break;
1084cfca06d7SDimitry Andric case Type::BFloatTyID: Code = bitc::TYPE_CODE_BFLOAT; break;
1085009b1c42SEd Schouten case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
1086009b1c42SEd Schouten case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
1087009b1c42SEd Schouten case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
1088009b1c42SEd Schouten case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
1089009b1c42SEd Schouten case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
1090009b1c42SEd Schouten case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
1091009b1c42SEd Schouten case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
1092cf099d11SDimitry Andric case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break;
1093b60736ecSDimitry Andric case Type::X86_AMXTyID: Code = bitc::TYPE_CODE_X86_AMX; break;
1094dd58ef01SDimitry Andric case Type::TokenTyID: Code = bitc::TYPE_CODE_TOKEN; break;
1095009b1c42SEd Schouten case Type::IntegerTyID:
1096009b1c42SEd Schouten // INTEGER: [width]
1097009b1c42SEd Schouten Code = bitc::TYPE_CODE_INTEGER;
1098009b1c42SEd Schouten TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
1099009b1c42SEd Schouten break;
1100009b1c42SEd Schouten case Type::PointerTyID: {
110130815c53SDimitry Andric PointerType *PTy = cast<PointerType>(T);
1102344a3780SDimitry Andric unsigned AddressSpace = PTy->getAddressSpace();
1103344a3780SDimitry Andric // OPAQUE_POINTER: [address space]
1104344a3780SDimitry Andric Code = bitc::TYPE_CODE_OPAQUE_POINTER;
1105344a3780SDimitry Andric TypeVals.push_back(AddressSpace);
1106344a3780SDimitry Andric if (AddressSpace == 0)
1107344a3780SDimitry Andric AbbrevToUse = OpaquePtrAbbrev;
1108009b1c42SEd Schouten break;
1109009b1c42SEd Schouten }
1110009b1c42SEd Schouten case Type::FunctionTyID: {
111130815c53SDimitry Andric FunctionType *FT = cast<FunctionType>(T);
111263faed5bSDimitry Andric // FUNCTION: [isvararg, retty, paramty x N]
1113009b1c42SEd Schouten Code = bitc::TYPE_CODE_FUNCTION;
1114009b1c42SEd Schouten TypeVals.push_back(FT->isVarArg());
1115009b1c42SEd Schouten TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
1116009b1c42SEd Schouten for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
1117009b1c42SEd Schouten TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
1118009b1c42SEd Schouten AbbrevToUse = FunctionAbbrev;
1119009b1c42SEd Schouten break;
1120009b1c42SEd Schouten }
1121009b1c42SEd Schouten case Type::StructTyID: {
112230815c53SDimitry Andric StructType *ST = cast<StructType>(T);
1123009b1c42SEd Schouten // STRUCT: [ispacked, eltty x N]
1124009b1c42SEd Schouten TypeVals.push_back(ST->isPacked());
1125009b1c42SEd Schouten // Output all of the element types.
1126c0981da4SDimitry Andric for (Type *ET : ST->elements())
1127c0981da4SDimitry Andric TypeVals.push_back(VE.getTypeID(ET));
1128411bd29eSDimitry Andric
112930815c53SDimitry Andric if (ST->isLiteral()) {
1130411bd29eSDimitry Andric Code = bitc::TYPE_CODE_STRUCT_ANON;
1131411bd29eSDimitry Andric AbbrevToUse = StructAnonAbbrev;
1132411bd29eSDimitry Andric } else {
1133411bd29eSDimitry Andric if (ST->isOpaque()) {
1134411bd29eSDimitry Andric Code = bitc::TYPE_CODE_OPAQUE;
1135411bd29eSDimitry Andric } else {
1136411bd29eSDimitry Andric Code = bitc::TYPE_CODE_STRUCT_NAMED;
1137411bd29eSDimitry Andric AbbrevToUse = StructNamedAbbrev;
1138411bd29eSDimitry Andric }
1139411bd29eSDimitry Andric
1140411bd29eSDimitry Andric // Emit the name if it is present.
1141411bd29eSDimitry Andric if (!ST->getName().empty())
1142b915e9e0SDimitry Andric writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
114301095a5dSDimitry Andric StructNameAbbrev);
1144411bd29eSDimitry Andric }
1145009b1c42SEd Schouten break;
1146009b1c42SEd Schouten }
1147009b1c42SEd Schouten case Type::ArrayTyID: {
114830815c53SDimitry Andric ArrayType *AT = cast<ArrayType>(T);
1149009b1c42SEd Schouten // ARRAY: [numelts, eltty]
1150009b1c42SEd Schouten Code = bitc::TYPE_CODE_ARRAY;
1151009b1c42SEd Schouten TypeVals.push_back(AT->getNumElements());
1152009b1c42SEd Schouten TypeVals.push_back(VE.getTypeID(AT->getElementType()));
1153009b1c42SEd Schouten AbbrevToUse = ArrayAbbrev;
1154009b1c42SEd Schouten break;
1155009b1c42SEd Schouten }
1156cfca06d7SDimitry Andric case Type::FixedVectorTyID:
1157cfca06d7SDimitry Andric case Type::ScalableVectorTyID: {
115830815c53SDimitry Andric VectorType *VT = cast<VectorType>(T);
1159e6d15924SDimitry Andric // VECTOR [numelts, eltty] or
1160e6d15924SDimitry Andric // [numelts, eltty, scalable]
1161009b1c42SEd Schouten Code = bitc::TYPE_CODE_VECTOR;
1162b60736ecSDimitry Andric TypeVals.push_back(VT->getElementCount().getKnownMinValue());
1163009b1c42SEd Schouten TypeVals.push_back(VE.getTypeID(VT->getElementType()));
1164cfca06d7SDimitry Andric if (isa<ScalableVectorType>(VT))
1165cfca06d7SDimitry Andric TypeVals.push_back(true);
1166009b1c42SEd Schouten break;
1167009b1c42SEd Schouten }
1168e3b55780SDimitry Andric case Type::TargetExtTyID: {
1169e3b55780SDimitry Andric TargetExtType *TET = cast<TargetExtType>(T);
1170e3b55780SDimitry Andric Code = bitc::TYPE_CODE_TARGET_TYPE;
1171e3b55780SDimitry Andric writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, TET->getName(),
1172e3b55780SDimitry Andric StructNameAbbrev);
1173e3b55780SDimitry Andric TypeVals.push_back(TET->getNumTypeParameters());
1174e3b55780SDimitry Andric for (Type *InnerTy : TET->type_params())
1175e3b55780SDimitry Andric TypeVals.push_back(VE.getTypeID(InnerTy));
1176e3b55780SDimitry Andric for (unsigned IntParam : TET->int_params())
1177e3b55780SDimitry Andric TypeVals.push_back(IntParam);
1178e3b55780SDimitry Andric break;
1179e3b55780SDimitry Andric }
1180e3b55780SDimitry Andric case Type::TypedPointerTyID:
1181e3b55780SDimitry Andric llvm_unreachable("Typed pointers cannot be added to IR modules");
1182009b1c42SEd Schouten }
1183009b1c42SEd Schouten
1184009b1c42SEd Schouten // Emit the finished record.
1185009b1c42SEd Schouten Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
1186009b1c42SEd Schouten TypeVals.clear();
1187009b1c42SEd Schouten }
1188009b1c42SEd Schouten
1189009b1c42SEd Schouten Stream.ExitBlock();
1190009b1c42SEd Schouten }
1191009b1c42SEd Schouten
getEncodedLinkage(const GlobalValue::LinkageTypes Linkage)119201095a5dSDimitry Andric static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {
119301095a5dSDimitry Andric switch (Linkage) {
119467c32a98SDimitry Andric case GlobalValue::ExternalLinkage:
119567c32a98SDimitry Andric return 0;
119667c32a98SDimitry Andric case GlobalValue::WeakAnyLinkage:
11975a5ac124SDimitry Andric return 16;
119867c32a98SDimitry Andric case GlobalValue::AppendingLinkage:
119967c32a98SDimitry Andric return 2;
120067c32a98SDimitry Andric case GlobalValue::InternalLinkage:
120167c32a98SDimitry Andric return 3;
120267c32a98SDimitry Andric case GlobalValue::LinkOnceAnyLinkage:
12035a5ac124SDimitry Andric return 18;
120467c32a98SDimitry Andric case GlobalValue::ExternalWeakLinkage:
120567c32a98SDimitry Andric return 7;
120667c32a98SDimitry Andric case GlobalValue::CommonLinkage:
120767c32a98SDimitry Andric return 8;
120867c32a98SDimitry Andric case GlobalValue::PrivateLinkage:
120967c32a98SDimitry Andric return 9;
121067c32a98SDimitry Andric case GlobalValue::WeakODRLinkage:
12115a5ac124SDimitry Andric return 17;
121267c32a98SDimitry Andric case GlobalValue::LinkOnceODRLinkage:
12135a5ac124SDimitry Andric return 19;
121467c32a98SDimitry Andric case GlobalValue::AvailableExternallyLinkage:
121567c32a98SDimitry Andric return 12;
1216009b1c42SEd Schouten }
121763faed5bSDimitry Andric llvm_unreachable("Invalid linkage");
1218009b1c42SEd Schouten }
1219009b1c42SEd Schouten
getEncodedLinkage(const GlobalValue & GV)122001095a5dSDimitry Andric static unsigned getEncodedLinkage(const GlobalValue &GV) {
122101095a5dSDimitry Andric return getEncodedLinkage(GV.getLinkage());
122201095a5dSDimitry Andric }
122301095a5dSDimitry Andric
getEncodedFFlags(FunctionSummary::FFlags Flags)1224044eb2f6SDimitry Andric static uint64_t getEncodedFFlags(FunctionSummary::FFlags Flags) {
1225044eb2f6SDimitry Andric uint64_t RawFlags = 0;
1226044eb2f6SDimitry Andric RawFlags |= Flags.ReadNone;
1227044eb2f6SDimitry Andric RawFlags |= (Flags.ReadOnly << 1);
1228044eb2f6SDimitry Andric RawFlags |= (Flags.NoRecurse << 2);
1229044eb2f6SDimitry Andric RawFlags |= (Flags.ReturnDoesNotAlias << 3);
1230d8e91e46SDimitry Andric RawFlags |= (Flags.NoInline << 4);
1231706b4fc4SDimitry Andric RawFlags |= (Flags.AlwaysInline << 5);
1232c0981da4SDimitry Andric RawFlags |= (Flags.NoUnwind << 6);
1233c0981da4SDimitry Andric RawFlags |= (Flags.MayThrow << 7);
1234c0981da4SDimitry Andric RawFlags |= (Flags.HasUnknownCall << 8);
123577fc4c14SDimitry Andric RawFlags |= (Flags.MustBeUnreachable << 9);
1236044eb2f6SDimitry Andric return RawFlags;
1237044eb2f6SDimitry Andric }
1238044eb2f6SDimitry Andric
1239344a3780SDimitry Andric // Decode the flags for GlobalValue in the summary. See getDecodedGVSummaryFlags
1240344a3780SDimitry Andric // in BitcodeReader.cpp.
getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags,bool ImportAsDecl=false)1241ac9a064cSDimitry Andric static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags,
1242ac9a064cSDimitry Andric bool ImportAsDecl = false) {
124301095a5dSDimitry Andric uint64_t RawFlags = 0;
124401095a5dSDimitry Andric
12457e7b6700SDimitry Andric RawFlags |= Flags.NotEligibleToImport; // bool
1246d288ef4cSDimitry Andric RawFlags |= (Flags.Live << 1);
1247044eb2f6SDimitry Andric RawFlags |= (Flags.DSOLocal << 2);
1248e6d15924SDimitry Andric RawFlags |= (Flags.CanAutoHide << 3);
1249044eb2f6SDimitry Andric
125001095a5dSDimitry Andric // Linkage don't need to be remapped at that time for the summary. Any future
125101095a5dSDimitry Andric // change to the getEncodedLinkage() function will need to be taken into
125201095a5dSDimitry Andric // account here as well.
125301095a5dSDimitry Andric RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits
125401095a5dSDimitry Andric
1255344a3780SDimitry Andric RawFlags |= (Flags.Visibility << 8); // 2 bits
1256344a3780SDimitry Andric
1257ac9a064cSDimitry Andric unsigned ImportType = Flags.ImportType | ImportAsDecl;
1258ac9a064cSDimitry Andric RawFlags |= (ImportType << 10); // 1 bit
1259ac9a064cSDimitry Andric
126001095a5dSDimitry Andric return RawFlags;
126101095a5dSDimitry Andric }
126201095a5dSDimitry Andric
getEncodedGVarFlags(GlobalVarSummary::GVarFlags Flags)1263d8e91e46SDimitry Andric static uint64_t getEncodedGVarFlags(GlobalVarSummary::GVarFlags Flags) {
1264cfca06d7SDimitry Andric uint64_t RawFlags = Flags.MaybeReadOnly | (Flags.MaybeWriteOnly << 1) |
1265cfca06d7SDimitry Andric (Flags.Constant << 2) | Flags.VCallVisibility << 3;
1266d8e91e46SDimitry Andric return RawFlags;
1267d8e91e46SDimitry Andric }
1268d8e91e46SDimitry Andric
getEncodedHotnessCallEdgeInfo(const CalleeInfo & CI)1269b1c73532SDimitry Andric static uint64_t getEncodedHotnessCallEdgeInfo(const CalleeInfo &CI) {
1270b1c73532SDimitry Andric uint64_t RawFlags = 0;
1271b1c73532SDimitry Andric
1272b1c73532SDimitry Andric RawFlags |= CI.Hotness; // 3 bits
1273b1c73532SDimitry Andric RawFlags |= (CI.HasTailCall << 3); // 1 bit
1274b1c73532SDimitry Andric
1275b1c73532SDimitry Andric return RawFlags;
1276b1c73532SDimitry Andric }
1277b1c73532SDimitry Andric
getEncodedRelBFCallEdgeInfo(const CalleeInfo & CI)1278b1c73532SDimitry Andric static uint64_t getEncodedRelBFCallEdgeInfo(const CalleeInfo &CI) {
1279b1c73532SDimitry Andric uint64_t RawFlags = 0;
1280b1c73532SDimitry Andric
1281b1c73532SDimitry Andric RawFlags |= CI.RelBlockFreq; // CalleeInfo::RelBlockFreqBits bits
1282b1c73532SDimitry Andric RawFlags |= (CI.HasTailCall << CalleeInfo::RelBlockFreqBits); // 1 bit
1283b1c73532SDimitry Andric
1284b1c73532SDimitry Andric return RawFlags;
1285b1c73532SDimitry Andric }
1286b1c73532SDimitry Andric
getEncodedVisibility(const GlobalValue & GV)12875ca98fd9SDimitry Andric static unsigned getEncodedVisibility(const GlobalValue &GV) {
12885ca98fd9SDimitry Andric switch (GV.getVisibility()) {
1289009b1c42SEd Schouten case GlobalValue::DefaultVisibility: return 0;
1290009b1c42SEd Schouten case GlobalValue::HiddenVisibility: return 1;
1291009b1c42SEd Schouten case GlobalValue::ProtectedVisibility: return 2;
1292009b1c42SEd Schouten }
129363faed5bSDimitry Andric llvm_unreachable("Invalid visibility");
1294009b1c42SEd Schouten }
1295009b1c42SEd Schouten
getEncodedDLLStorageClass(const GlobalValue & GV)12965ca98fd9SDimitry Andric static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
12975ca98fd9SDimitry Andric switch (GV.getDLLStorageClass()) {
12985ca98fd9SDimitry Andric case GlobalValue::DefaultStorageClass: return 0;
12995ca98fd9SDimitry Andric case GlobalValue::DLLImportStorageClass: return 1;
13005ca98fd9SDimitry Andric case GlobalValue::DLLExportStorageClass: return 2;
13015ca98fd9SDimitry Andric }
13025ca98fd9SDimitry Andric llvm_unreachable("Invalid DLL storage class");
13035ca98fd9SDimitry Andric }
13045ca98fd9SDimitry Andric
getEncodedThreadLocalMode(const GlobalValue & GV)13055ca98fd9SDimitry Andric static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
13065ca98fd9SDimitry Andric switch (GV.getThreadLocalMode()) {
130758b69754SDimitry Andric case GlobalVariable::NotThreadLocal: return 0;
130858b69754SDimitry Andric case GlobalVariable::GeneralDynamicTLSModel: return 1;
130958b69754SDimitry Andric case GlobalVariable::LocalDynamicTLSModel: return 2;
131058b69754SDimitry Andric case GlobalVariable::InitialExecTLSModel: return 3;
131158b69754SDimitry Andric case GlobalVariable::LocalExecTLSModel: return 4;
131258b69754SDimitry Andric }
131358b69754SDimitry Andric llvm_unreachable("Invalid TLS model");
131458b69754SDimitry Andric }
131558b69754SDimitry Andric
getEncodedComdatSelectionKind(const Comdat & C)13165ca98fd9SDimitry Andric static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
13175ca98fd9SDimitry Andric switch (C.getSelectionKind()) {
13185ca98fd9SDimitry Andric case Comdat::Any:
13195ca98fd9SDimitry Andric return bitc::COMDAT_SELECTION_KIND_ANY;
13205ca98fd9SDimitry Andric case Comdat::ExactMatch:
13215ca98fd9SDimitry Andric return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
13225ca98fd9SDimitry Andric case Comdat::Largest:
13235ca98fd9SDimitry Andric return bitc::COMDAT_SELECTION_KIND_LARGEST;
1324344a3780SDimitry Andric case Comdat::NoDeduplicate:
13255ca98fd9SDimitry Andric return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
13265ca98fd9SDimitry Andric case Comdat::SameSize:
13275ca98fd9SDimitry Andric return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
13285ca98fd9SDimitry Andric }
13295ca98fd9SDimitry Andric llvm_unreachable("Invalid selection kind");
13305ca98fd9SDimitry Andric }
13315ca98fd9SDimitry Andric
getEncodedUnnamedAddr(const GlobalValue & GV)133201095a5dSDimitry Andric static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) {
133301095a5dSDimitry Andric switch (GV.getUnnamedAddr()) {
133401095a5dSDimitry Andric case GlobalValue::UnnamedAddr::None: return 0;
133501095a5dSDimitry Andric case GlobalValue::UnnamedAddr::Local: return 2;
133601095a5dSDimitry Andric case GlobalValue::UnnamedAddr::Global: return 1;
133701095a5dSDimitry Andric }
133801095a5dSDimitry Andric llvm_unreachable("Invalid unnamed_addr");
133901095a5dSDimitry Andric }
134001095a5dSDimitry Andric
addToStrtab(StringRef Str)1341ca089b24SDimitry Andric size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) {
1342ca089b24SDimitry Andric if (GenerateHash)
1343ca089b24SDimitry Andric Hasher.update(Str);
1344ca089b24SDimitry Andric return StrtabBuilder.add(Str);
1345ca089b24SDimitry Andric }
1346ca089b24SDimitry Andric
writeComdats()134701095a5dSDimitry Andric void ModuleBitcodeWriter::writeComdats() {
134801095a5dSDimitry Andric SmallVector<unsigned, 64> Vals;
13495ca98fd9SDimitry Andric for (const Comdat *C : VE.getComdats()) {
1350d99dafe2SDimitry Andric // COMDAT: [strtab offset, strtab size, selection_kind]
1351ca089b24SDimitry Andric Vals.push_back(addToStrtab(C->getName()));
1352d99dafe2SDimitry Andric Vals.push_back(C->getName().size());
13535ca98fd9SDimitry Andric Vals.push_back(getEncodedComdatSelectionKind(*C));
13545ca98fd9SDimitry Andric Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
13555ca98fd9SDimitry Andric Vals.clear();
13565ca98fd9SDimitry Andric }
13575ca98fd9SDimitry Andric }
13585ca98fd9SDimitry Andric
1359dd58ef01SDimitry Andric /// Write a record that will eventually hold the word offset of the
1360dd58ef01SDimitry Andric /// module-level VST. For now the offset is 0, which will be backpatched
136101095a5dSDimitry Andric /// after the real VST is written. Saves the bit offset to backpatch.
writeValueSymbolTableForwardDecl()1362d99dafe2SDimitry Andric void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
1363dd58ef01SDimitry Andric // Write a placeholder value in for the offset of the real VST,
1364dd58ef01SDimitry Andric // which is written after the function blocks so that it can include
1365dd58ef01SDimitry Andric // the offset of each function. The placeholder offset will be
1366dd58ef01SDimitry Andric // updated when the real VST is written.
13677e7b6700SDimitry Andric auto Abbv = std::make_shared<BitCodeAbbrev>();
1368dd58ef01SDimitry Andric Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET));
1369dd58ef01SDimitry Andric // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
1370dd58ef01SDimitry Andric // hold the real VST offset. Must use fixed instead of VBR as we don't
1371dd58ef01SDimitry Andric // know how many VBR chunks to reserve ahead of time.
1372dd58ef01SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
13737e7b6700SDimitry Andric unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1374dd58ef01SDimitry Andric
1375dd58ef01SDimitry Andric // Emit the placeholder
1376dd58ef01SDimitry Andric uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0};
1377dd58ef01SDimitry Andric Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
1378dd58ef01SDimitry Andric
137901095a5dSDimitry Andric // Compute and save the bit offset to the placeholder, which will be
1380dd58ef01SDimitry Andric // patched when the real VST is written. We can simply subtract the 32-bit
1381dd58ef01SDimitry Andric // fixed size from the current bit number to get the location to backpatch.
138201095a5dSDimitry Andric VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32;
138301095a5dSDimitry Andric }
138401095a5dSDimitry Andric
138501095a5dSDimitry Andric enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 };
138601095a5dSDimitry Andric
138701095a5dSDimitry Andric /// Determine the encoding to use for the given string name and length.
getStringEncoding(StringRef Str)1388d288ef4cSDimitry Andric static StringEncoding getStringEncoding(StringRef Str) {
138901095a5dSDimitry Andric bool isChar6 = true;
1390d288ef4cSDimitry Andric for (char C : Str) {
139101095a5dSDimitry Andric if (isChar6)
1392d288ef4cSDimitry Andric isChar6 = BitCodeAbbrevOp::isChar6(C);
1393d288ef4cSDimitry Andric if ((unsigned char)C & 128)
139401095a5dSDimitry Andric // don't bother scanning the rest.
139501095a5dSDimitry Andric return SE_Fixed8;
139601095a5dSDimitry Andric }
139701095a5dSDimitry Andric if (isChar6)
139801095a5dSDimitry Andric return SE_Char6;
139901095a5dSDimitry Andric return SE_Fixed7;
1400dd58ef01SDimitry Andric }
1401dd58ef01SDimitry Andric
1402145449b1SDimitry Andric static_assert(sizeof(GlobalValue::SanitizerMetadata) <= sizeof(unsigned),
1403145449b1SDimitry Andric "Sanitizer Metadata is too large for naive serialization.");
1404145449b1SDimitry Andric static unsigned
serializeSanitizerMetadata(const GlobalValue::SanitizerMetadata & Meta)1405145449b1SDimitry Andric serializeSanitizerMetadata(const GlobalValue::SanitizerMetadata &Meta) {
1406145449b1SDimitry Andric return Meta.NoAddress | (Meta.NoHWAddress << 1) |
14071f917f69SDimitry Andric (Meta.Memtag << 2) | (Meta.IsDynInit << 3);
1408145449b1SDimitry Andric }
1409145449b1SDimitry Andric
1410dd58ef01SDimitry Andric /// Emit top-level description of module, including target triple, inline asm,
1411dd58ef01SDimitry Andric /// descriptors for global variables, and function prototype info.
1412dd58ef01SDimitry Andric /// Returns the bit offset to backpatch with the location of the real VST.
writeModuleInfo()141301095a5dSDimitry Andric void ModuleBitcodeWriter::writeModuleInfo() {
1414009b1c42SEd Schouten // Emit various pieces of data attached to a module.
141501095a5dSDimitry Andric if (!M.getTargetTriple().empty())
1416b915e9e0SDimitry Andric writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(),
141701095a5dSDimitry Andric 0 /*TODO*/);
141801095a5dSDimitry Andric const std::string &DL = M.getDataLayoutStr();
14195ca98fd9SDimitry Andric if (!DL.empty())
1420b915e9e0SDimitry Andric writeStringRecord(Stream, bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/);
142101095a5dSDimitry Andric if (!M.getModuleInlineAsm().empty())
1422b915e9e0SDimitry Andric writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(),
142301095a5dSDimitry Andric 0 /*TODO*/);
1424009b1c42SEd Schouten
1425009b1c42SEd Schouten // Emit information about sections and GC, computing how many there are. Also
1426009b1c42SEd Schouten // compute the maximum alignment value.
1427009b1c42SEd Schouten std::map<std::string, unsigned> SectionMap;
1428009b1c42SEd Schouten std::map<std::string, unsigned> GCMap;
1429b60736ecSDimitry Andric MaybeAlign MaxAlignment;
1430009b1c42SEd Schouten unsigned MaxGlobalType = 0;
1431b60736ecSDimitry Andric const auto UpdateMaxAlignment = [&MaxAlignment](const MaybeAlign A) {
1432b60736ecSDimitry Andric if (A)
1433b60736ecSDimitry Andric MaxAlignment = !MaxAlignment ? *A : std::max(*MaxAlignment, *A);
1434b60736ecSDimitry Andric };
1435cfca06d7SDimitry Andric for (const GlobalVariable &GV : M.globals()) {
1436b60736ecSDimitry Andric UpdateMaxAlignment(GV.getAlign());
14375a5ac124SDimitry Andric MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
14385ca98fd9SDimitry Andric if (GV.hasSection()) {
1439009b1c42SEd Schouten // Give section names unique ID's.
1440cfca06d7SDimitry Andric unsigned &Entry = SectionMap[std::string(GV.getSection())];
144130815c53SDimitry Andric if (!Entry) {
1442b915e9e0SDimitry Andric writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
144301095a5dSDimitry Andric 0 /*TODO*/);
1444009b1c42SEd Schouten Entry = SectionMap.size();
1445009b1c42SEd Schouten }
144630815c53SDimitry Andric }
144730815c53SDimitry Andric }
144801095a5dSDimitry Andric for (const Function &F : M) {
1449b60736ecSDimitry Andric UpdateMaxAlignment(F.getAlign());
14505ca98fd9SDimitry Andric if (F.hasSection()) {
1451009b1c42SEd Schouten // Give section names unique ID's.
1452cfca06d7SDimitry Andric unsigned &Entry = SectionMap[std::string(F.getSection())];
1453009b1c42SEd Schouten if (!Entry) {
1454b915e9e0SDimitry Andric writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
145501095a5dSDimitry Andric 0 /*TODO*/);
1456009b1c42SEd Schouten Entry = SectionMap.size();
1457009b1c42SEd Schouten }
1458009b1c42SEd Schouten }
14595ca98fd9SDimitry Andric if (F.hasGC()) {
1460009b1c42SEd Schouten // Same for GC names.
14615ca98fd9SDimitry Andric unsigned &Entry = GCMap[F.getGC()];
1462009b1c42SEd Schouten if (!Entry) {
1463b915e9e0SDimitry Andric writeStringRecord(Stream, bitc::MODULE_CODE_GCNAME, F.getGC(),
1464b915e9e0SDimitry Andric 0 /*TODO*/);
1465009b1c42SEd Schouten Entry = GCMap.size();
1466009b1c42SEd Schouten }
1467009b1c42SEd Schouten }
1468009b1c42SEd Schouten }
1469009b1c42SEd Schouten
1470009b1c42SEd Schouten // Emit abbrev for globals, now that we know # sections and max alignment.
1471009b1c42SEd Schouten unsigned SimpleGVarAbbrev = 0;
147201095a5dSDimitry Andric if (!M.global_empty()) {
1473009b1c42SEd Schouten // Add an abbrev for common globals with no visibility or thread localness.
14747e7b6700SDimitry Andric auto Abbv = std::make_shared<BitCodeAbbrev>();
1475009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
1476d99dafe2SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1477d99dafe2SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1478009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1479009b1c42SEd Schouten Log2_32_Ceil(MaxGlobalType+1)));
14805a5ac124SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2
14815a5ac124SDimitry Andric //| explicitType << 1
14825a5ac124SDimitry Andric //| constant
1483009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
14845a5ac124SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
1485b60736ecSDimitry Andric if (!MaxAlignment) // Alignment.
1486009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(0));
1487009b1c42SEd Schouten else {
1488b60736ecSDimitry Andric unsigned MaxEncAlignment = getEncodedAlign(MaxAlignment);
1489009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1490009b1c42SEd Schouten Log2_32_Ceil(MaxEncAlignment+1)));
1491009b1c42SEd Schouten }
1492009b1c42SEd Schouten if (SectionMap.empty()) // Section.
1493009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(0));
1494009b1c42SEd Schouten else
1495009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1496009b1c42SEd Schouten Log2_32_Ceil(SectionMap.size()+1)));
1497009b1c42SEd Schouten // Don't bother emitting vis + thread local.
14987e7b6700SDimitry Andric SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1499009b1c42SEd Schouten }
1500009b1c42SEd Schouten
1501009b1c42SEd Schouten SmallVector<unsigned, 64> Vals;
1502d99dafe2SDimitry Andric // Emit the module's source file name.
1503d99dafe2SDimitry Andric {
1504d288ef4cSDimitry Andric StringEncoding Bits = getStringEncoding(M.getSourceFileName());
1505d99dafe2SDimitry Andric BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
1506d99dafe2SDimitry Andric if (Bits == SE_Char6)
1507d99dafe2SDimitry Andric AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
1508d99dafe2SDimitry Andric else if (Bits == SE_Fixed7)
1509d99dafe2SDimitry Andric AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
1510d99dafe2SDimitry Andric
1511d99dafe2SDimitry Andric // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
1512d99dafe2SDimitry Andric auto Abbv = std::make_shared<BitCodeAbbrev>();
1513d99dafe2SDimitry Andric Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
1514d99dafe2SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1515d99dafe2SDimitry Andric Abbv->Add(AbbrevOpToUse);
1516d99dafe2SDimitry Andric unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1517d99dafe2SDimitry Andric
1518d99dafe2SDimitry Andric for (const auto P : M.getSourceFileName())
1519d99dafe2SDimitry Andric Vals.push_back((unsigned char)P);
1520d99dafe2SDimitry Andric
1521d99dafe2SDimitry Andric // Emit the finished record.
1522d99dafe2SDimitry Andric Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
1523d99dafe2SDimitry Andric Vals.clear();
1524d99dafe2SDimitry Andric }
1525d99dafe2SDimitry Andric
1526d99dafe2SDimitry Andric // Emit the global variable information.
152701095a5dSDimitry Andric for (const GlobalVariable &GV : M.globals()) {
1528009b1c42SEd Schouten unsigned AbbrevToUse = 0;
1529009b1c42SEd Schouten
1530d99dafe2SDimitry Andric // GLOBALVAR: [strtab offset, strtab size, type, isconst, initid,
1531cf099d11SDimitry Andric // linkage, alignment, section, visibility, threadlocal,
15325a5ac124SDimitry Andric // unnamed_addr, externally_initialized, dllstorageclass,
1533b1c73532SDimitry Andric // comdat, attributes, DSO_Local, GlobalSanitizer, code_model]
1534ca089b24SDimitry Andric Vals.push_back(addToStrtab(GV.getName()));
1535d99dafe2SDimitry Andric Vals.push_back(GV.getName().size());
15365a5ac124SDimitry Andric Vals.push_back(VE.getTypeID(GV.getValueType()));
15375a5ac124SDimitry Andric Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
15385ca98fd9SDimitry Andric Vals.push_back(GV.isDeclaration() ? 0 :
15395ca98fd9SDimitry Andric (VE.getValueID(GV.getInitializer()) + 1));
1540009b1c42SEd Schouten Vals.push_back(getEncodedLinkage(GV));
1541b60736ecSDimitry Andric Vals.push_back(getEncodedAlign(GV.getAlign()));
1542cfca06d7SDimitry Andric Vals.push_back(GV.hasSection() ? SectionMap[std::string(GV.getSection())]
1543cfca06d7SDimitry Andric : 0);
15445ca98fd9SDimitry Andric if (GV.isThreadLocal() ||
15455ca98fd9SDimitry Andric GV.getVisibility() != GlobalValue::DefaultVisibility ||
154601095a5dSDimitry Andric GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
154701095a5dSDimitry Andric GV.isExternallyInitialized() ||
15485ca98fd9SDimitry Andric GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
1549145449b1SDimitry Andric GV.hasComdat() || GV.hasAttributes() || GV.isDSOLocal() ||
1550b1c73532SDimitry Andric GV.hasPartition() || GV.hasSanitizerMetadata() || GV.getCodeModel()) {
1551009b1c42SEd Schouten Vals.push_back(getEncodedVisibility(GV));
155258b69754SDimitry Andric Vals.push_back(getEncodedThreadLocalMode(GV));
155301095a5dSDimitry Andric Vals.push_back(getEncodedUnnamedAddr(GV));
15545ca98fd9SDimitry Andric Vals.push_back(GV.isExternallyInitialized());
15555ca98fd9SDimitry Andric Vals.push_back(getEncodedDLLStorageClass(GV));
15565ca98fd9SDimitry Andric Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
15576b3f41edSDimitry Andric
15586b3f41edSDimitry Andric auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
15596b3f41edSDimitry Andric Vals.push_back(VE.getAttributeListID(AL));
1560044eb2f6SDimitry Andric
1561044eb2f6SDimitry Andric Vals.push_back(GV.isDSOLocal());
1562e6d15924SDimitry Andric Vals.push_back(addToStrtab(GV.getPartition()));
1563e6d15924SDimitry Andric Vals.push_back(GV.getPartition().size());
1564145449b1SDimitry Andric
1565145449b1SDimitry Andric Vals.push_back((GV.hasSanitizerMetadata() ? serializeSanitizerMetadata(
1566145449b1SDimitry Andric GV.getSanitizerMetadata())
1567145449b1SDimitry Andric : 0));
1568b1c73532SDimitry Andric Vals.push_back(GV.getCodeModelRaw());
1569009b1c42SEd Schouten } else {
1570009b1c42SEd Schouten AbbrevToUse = SimpleGVarAbbrev;
1571009b1c42SEd Schouten }
1572009b1c42SEd Schouten
1573009b1c42SEd Schouten Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
1574009b1c42SEd Schouten Vals.clear();
1575009b1c42SEd Schouten }
1576009b1c42SEd Schouten
1577009b1c42SEd Schouten // Emit the function proto information.
157801095a5dSDimitry Andric for (const Function &F : M) {
1579d99dafe2SDimitry Andric // FUNCTION: [strtab offset, strtab size, type, callingconv, isproto,
1580d99dafe2SDimitry Andric // linkage, paramattrs, alignment, section, visibility, gc,
1581d99dafe2SDimitry Andric // unnamed_addr, prologuedata, dllstorageclass, comdat,
1582d8e91e46SDimitry Andric // prefixdata, personalityfn, DSO_Local, addrspace]
1583ca089b24SDimitry Andric Vals.push_back(addToStrtab(F.getName()));
1584d99dafe2SDimitry Andric Vals.push_back(F.getName().size());
15855a5ac124SDimitry Andric Vals.push_back(VE.getTypeID(F.getFunctionType()));
15865ca98fd9SDimitry Andric Vals.push_back(F.getCallingConv());
15875ca98fd9SDimitry Andric Vals.push_back(F.isDeclaration());
1588009b1c42SEd Schouten Vals.push_back(getEncodedLinkage(F));
158912f3ca4cSDimitry Andric Vals.push_back(VE.getAttributeListID(F.getAttributes()));
1590b60736ecSDimitry Andric Vals.push_back(getEncodedAlign(F.getAlign()));
1591cfca06d7SDimitry Andric Vals.push_back(F.hasSection() ? SectionMap[std::string(F.getSection())]
1592cfca06d7SDimitry Andric : 0);
1593009b1c42SEd Schouten Vals.push_back(getEncodedVisibility(F));
15945ca98fd9SDimitry Andric Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
159501095a5dSDimitry Andric Vals.push_back(getEncodedUnnamedAddr(F));
159667c32a98SDimitry Andric Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
1597f8af5cf6SDimitry Andric : 0);
15985ca98fd9SDimitry Andric Vals.push_back(getEncodedDLLStorageClass(F));
15995ca98fd9SDimitry Andric Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
160067c32a98SDimitry Andric Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
160167c32a98SDimitry Andric : 0);
16023a0822f0SDimitry Andric Vals.push_back(
16033a0822f0SDimitry Andric F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
1604009b1c42SEd Schouten
1605044eb2f6SDimitry Andric Vals.push_back(F.isDSOLocal());
1606d8e91e46SDimitry Andric Vals.push_back(F.getAddressSpace());
1607e6d15924SDimitry Andric Vals.push_back(addToStrtab(F.getPartition()));
1608e6d15924SDimitry Andric Vals.push_back(F.getPartition().size());
1609d8e91e46SDimitry Andric
1610009b1c42SEd Schouten unsigned AbbrevToUse = 0;
1611009b1c42SEd Schouten Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
1612009b1c42SEd Schouten Vals.clear();
1613009b1c42SEd Schouten }
1614009b1c42SEd Schouten
1615009b1c42SEd Schouten // Emit the alias information.
161601095a5dSDimitry Andric for (const GlobalAlias &A : M.aliases()) {
1617d99dafe2SDimitry Andric // ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage,
1618044eb2f6SDimitry Andric // visibility, dllstorageclass, threadlocal, unnamed_addr,
1619044eb2f6SDimitry Andric // DSO_Local]
1620ca089b24SDimitry Andric Vals.push_back(addToStrtab(A.getName()));
1621d99dafe2SDimitry Andric Vals.push_back(A.getName().size());
1622dd58ef01SDimitry Andric Vals.push_back(VE.getTypeID(A.getValueType()));
1623dd58ef01SDimitry Andric Vals.push_back(A.getType()->getAddressSpace());
16245ca98fd9SDimitry Andric Vals.push_back(VE.getValueID(A.getAliasee()));
16255ca98fd9SDimitry Andric Vals.push_back(getEncodedLinkage(A));
16265ca98fd9SDimitry Andric Vals.push_back(getEncodedVisibility(A));
16275ca98fd9SDimitry Andric Vals.push_back(getEncodedDLLStorageClass(A));
16285ca98fd9SDimitry Andric Vals.push_back(getEncodedThreadLocalMode(A));
162901095a5dSDimitry Andric Vals.push_back(getEncodedUnnamedAddr(A));
1630044eb2f6SDimitry Andric Vals.push_back(A.isDSOLocal());
1631e6d15924SDimitry Andric Vals.push_back(addToStrtab(A.getPartition()));
1632e6d15924SDimitry Andric Vals.push_back(A.getPartition().size());
1633044eb2f6SDimitry Andric
1634009b1c42SEd Schouten unsigned AbbrevToUse = 0;
1635009b1c42SEd Schouten Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
1636009b1c42SEd Schouten Vals.clear();
1637009b1c42SEd Schouten }
1638dd58ef01SDimitry Andric
163901095a5dSDimitry Andric // Emit the ifunc information.
164001095a5dSDimitry Andric for (const GlobalIFunc &I : M.ifuncs()) {
1641d99dafe2SDimitry Andric // IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver
1642eb11fae6SDimitry Andric // val#, linkage, visibility, DSO_Local]
1643ca089b24SDimitry Andric Vals.push_back(addToStrtab(I.getName()));
1644d99dafe2SDimitry Andric Vals.push_back(I.getName().size());
164501095a5dSDimitry Andric Vals.push_back(VE.getTypeID(I.getValueType()));
164601095a5dSDimitry Andric Vals.push_back(I.getType()->getAddressSpace());
164701095a5dSDimitry Andric Vals.push_back(VE.getValueID(I.getResolver()));
164801095a5dSDimitry Andric Vals.push_back(getEncodedLinkage(I));
164901095a5dSDimitry Andric Vals.push_back(getEncodedVisibility(I));
1650eb11fae6SDimitry Andric Vals.push_back(I.isDSOLocal());
1651e6d15924SDimitry Andric Vals.push_back(addToStrtab(I.getPartition()));
1652e6d15924SDimitry Andric Vals.push_back(I.getPartition().size());
165301095a5dSDimitry Andric Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
1654dd58ef01SDimitry Andric Vals.clear();
1655009b1c42SEd Schouten }
1656009b1c42SEd Schouten
165701095a5dSDimitry Andric writeValueSymbolTableForwardDecl();
165801095a5dSDimitry Andric }
165901095a5dSDimitry Andric
getOptimizationFlags(const Value * V)166001095a5dSDimitry Andric static uint64_t getOptimizationFlags(const Value *V) {
166159850d08SRoman Divacky uint64_t Flags = 0;
166259850d08SRoman Divacky
166367c32a98SDimitry Andric if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
166459850d08SRoman Divacky if (OBO->hasNoSignedWrap())
166559850d08SRoman Divacky Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
166659850d08SRoman Divacky if (OBO->hasNoUnsignedWrap())
166759850d08SRoman Divacky Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
166867c32a98SDimitry Andric } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
1669cf099d11SDimitry Andric if (PEO->isExact())
1670cf099d11SDimitry Andric Flags |= 1 << bitc::PEO_EXACT;
1671b1c73532SDimitry Andric } else if (const auto *PDI = dyn_cast<PossiblyDisjointInst>(V)) {
1672b1c73532SDimitry Andric if (PDI->isDisjoint())
1673b1c73532SDimitry Andric Flags |= 1 << bitc::PDI_DISJOINT;
167467c32a98SDimitry Andric } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
1675044eb2f6SDimitry Andric if (FPMO->hasAllowReassoc())
1676eb11fae6SDimitry Andric Flags |= bitc::AllowReassoc;
16774a16efa3SDimitry Andric if (FPMO->hasNoNaNs())
1678eb11fae6SDimitry Andric Flags |= bitc::NoNaNs;
16794a16efa3SDimitry Andric if (FPMO->hasNoInfs())
1680eb11fae6SDimitry Andric Flags |= bitc::NoInfs;
16814a16efa3SDimitry Andric if (FPMO->hasNoSignedZeros())
1682eb11fae6SDimitry Andric Flags |= bitc::NoSignedZeros;
16834a16efa3SDimitry Andric if (FPMO->hasAllowReciprocal())
1684eb11fae6SDimitry Andric Flags |= bitc::AllowReciprocal;
168571d5a254SDimitry Andric if (FPMO->hasAllowContract())
1686eb11fae6SDimitry Andric Flags |= bitc::AllowContract;
1687044eb2f6SDimitry Andric if (FPMO->hasApproxFunc())
1688eb11fae6SDimitry Andric Flags |= bitc::ApproxFunc;
1689b1c73532SDimitry Andric } else if (const auto *NNI = dyn_cast<PossiblyNonNegInst>(V)) {
1690b1c73532SDimitry Andric if (NNI->hasNonNeg())
1691b1c73532SDimitry Andric Flags |= 1 << bitc::PNNI_NON_NEG;
1692ac9a064cSDimitry Andric } else if (const auto *TI = dyn_cast<TruncInst>(V)) {
1693ac9a064cSDimitry Andric if (TI->hasNoSignedWrap())
1694ac9a064cSDimitry Andric Flags |= 1 << bitc::TIO_NO_SIGNED_WRAP;
1695ac9a064cSDimitry Andric if (TI->hasNoUnsignedWrap())
1696ac9a064cSDimitry Andric Flags |= 1 << bitc::TIO_NO_UNSIGNED_WRAP;
1697ac9a064cSDimitry Andric } else if (const auto *GEP = dyn_cast<GEPOperator>(V)) {
1698ac9a064cSDimitry Andric if (GEP->isInBounds())
1699ac9a064cSDimitry Andric Flags |= 1 << bitc::GEP_INBOUNDS;
1700ac9a064cSDimitry Andric if (GEP->hasNoUnsignedSignedWrap())
1701ac9a064cSDimitry Andric Flags |= 1 << bitc::GEP_NUSW;
1702ac9a064cSDimitry Andric if (GEP->hasNoUnsignedWrap())
1703ac9a064cSDimitry Andric Flags |= 1 << bitc::GEP_NUW;
170459850d08SRoman Divacky }
170559850d08SRoman Divacky
170659850d08SRoman Divacky return Flags;
170759850d08SRoman Divacky }
170859850d08SRoman Divacky
writeValueAsMetadata(const ValueAsMetadata * MD,SmallVectorImpl<uint64_t> & Record)170901095a5dSDimitry Andric void ModuleBitcodeWriter::writeValueAsMetadata(
171001095a5dSDimitry Andric const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
171167c32a98SDimitry Andric // Mimic an MDNode with a value as one operand.
171267c32a98SDimitry Andric Value *V = MD->getValue();
171367c32a98SDimitry Andric Record.push_back(VE.getTypeID(V->getType()));
171467c32a98SDimitry Andric Record.push_back(VE.getValueID(V));
171567c32a98SDimitry Andric Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
171667c32a98SDimitry Andric Record.clear();
171767c32a98SDimitry Andric }
171867c32a98SDimitry Andric
writeMDTuple(const MDTuple * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)171901095a5dSDimitry Andric void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N,
172001095a5dSDimitry Andric SmallVectorImpl<uint64_t> &Record,
172101095a5dSDimitry Andric unsigned Abbrev) {
1722ac9a064cSDimitry Andric for (const MDOperand &MDO : N->operands()) {
1723ac9a064cSDimitry Andric Metadata *MD = MDO;
17245a5ac124SDimitry Andric assert(!(MD && isa<LocalAsMetadata>(MD)) &&
17255a5ac124SDimitry Andric "Unexpected function-local metadata");
17265a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(MD));
172759850d08SRoman Divacky }
172867c32a98SDimitry Andric Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
172967c32a98SDimitry Andric : bitc::METADATA_NODE,
17305a5ac124SDimitry Andric Record, Abbrev);
173167c32a98SDimitry Andric Record.clear();
173267c32a98SDimitry Andric }
173367c32a98SDimitry Andric
createDILocationAbbrev()173401095a5dSDimitry Andric unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
173501095a5dSDimitry Andric // Assume the column is usually under 128, and always output the inlined-at
173601095a5dSDimitry Andric // location (it's never more expensive than building an array size 1).
17377e7b6700SDimitry Andric auto Abbv = std::make_shared<BitCodeAbbrev>();
173801095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
173901095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
174001095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
174101095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
174201095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
174301095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1744d8e91e46SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
17457e7b6700SDimitry Andric return Stream.EmitAbbrev(std::move(Abbv));
174601095a5dSDimitry Andric }
174701095a5dSDimitry Andric
writeDILocation(const DILocation * N,SmallVectorImpl<uint64_t> & Record,unsigned & Abbrev)174801095a5dSDimitry Andric void ModuleBitcodeWriter::writeDILocation(const DILocation *N,
174967c32a98SDimitry Andric SmallVectorImpl<uint64_t> &Record,
175001095a5dSDimitry Andric unsigned &Abbrev) {
175101095a5dSDimitry Andric if (!Abbrev)
175201095a5dSDimitry Andric Abbrev = createDILocationAbbrev();
175301095a5dSDimitry Andric
175467c32a98SDimitry Andric Record.push_back(N->isDistinct());
175567c32a98SDimitry Andric Record.push_back(N->getLine());
175667c32a98SDimitry Andric Record.push_back(N->getColumn());
175767c32a98SDimitry Andric Record.push_back(VE.getMetadataID(N->getScope()));
17585a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
1759d8e91e46SDimitry Andric Record.push_back(N->isImplicitCode());
176067c32a98SDimitry Andric
176167c32a98SDimitry Andric Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
176259850d08SRoman Divacky Record.clear();
176359850d08SRoman Divacky }
176459850d08SRoman Divacky
createGenericDINodeAbbrev()176501095a5dSDimitry Andric unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
176601095a5dSDimitry Andric // Assume the column is usually under 128, and always output the inlined-at
176701095a5dSDimitry Andric // location (it's never more expensive than building an array size 1).
17687e7b6700SDimitry Andric auto Abbv = std::make_shared<BitCodeAbbrev>();
176901095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
177001095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
177101095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
177201095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
177301095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
177401095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
177501095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
17767e7b6700SDimitry Andric return Stream.EmitAbbrev(std::move(Abbv));
177701095a5dSDimitry Andric }
177801095a5dSDimitry Andric
writeGenericDINode(const GenericDINode * N,SmallVectorImpl<uint64_t> & Record,unsigned & Abbrev)177901095a5dSDimitry Andric void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N,
17805a5ac124SDimitry Andric SmallVectorImpl<uint64_t> &Record,
178101095a5dSDimitry Andric unsigned &Abbrev) {
178201095a5dSDimitry Andric if (!Abbrev)
178301095a5dSDimitry Andric Abbrev = createGenericDINodeAbbrev();
178401095a5dSDimitry Andric
17855a5ac124SDimitry Andric Record.push_back(N->isDistinct());
17865a5ac124SDimitry Andric Record.push_back(N->getTag());
17875a5ac124SDimitry Andric Record.push_back(0); // Per-tag version field; unused for now.
17885a5ac124SDimitry Andric
17895a5ac124SDimitry Andric for (auto &I : N->operands())
17905a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(I));
17915a5ac124SDimitry Andric
17925a5ac124SDimitry Andric Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
17935a5ac124SDimitry Andric Record.clear();
17945a5ac124SDimitry Andric }
17955a5ac124SDimitry Andric
writeDISubrange(const DISubrange * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)179601095a5dSDimitry Andric void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N,
17975a5ac124SDimitry Andric SmallVectorImpl<uint64_t> &Record,
17985a5ac124SDimitry Andric unsigned Abbrev) {
1799cfca06d7SDimitry Andric const uint64_t Version = 2 << 1;
1800eb11fae6SDimitry Andric Record.push_back((uint64_t)N->isDistinct() | Version);
1801eb11fae6SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
1802cfca06d7SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
1803cfca06d7SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
1804cfca06d7SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
18055a5ac124SDimitry Andric
18065a5ac124SDimitry Andric Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
18075a5ac124SDimitry Andric Record.clear();
18085a5ac124SDimitry Andric }
18095a5ac124SDimitry Andric
writeDIGenericSubrange(const DIGenericSubrange * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)1810b60736ecSDimitry Andric void ModuleBitcodeWriter::writeDIGenericSubrange(
1811b60736ecSDimitry Andric const DIGenericSubrange *N, SmallVectorImpl<uint64_t> &Record,
1812b60736ecSDimitry Andric unsigned Abbrev) {
1813b60736ecSDimitry Andric Record.push_back((uint64_t)N->isDistinct());
1814b60736ecSDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
1815b60736ecSDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
1816b60736ecSDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
1817b60736ecSDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
1818b60736ecSDimitry Andric
1819b60736ecSDimitry Andric Stream.EmitRecord(bitc::METADATA_GENERIC_SUBRANGE, Record, Abbrev);
1820b60736ecSDimitry Andric Record.clear();
1821b60736ecSDimitry Andric }
1822b60736ecSDimitry Andric
writeDIEnumerator(const DIEnumerator * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)182301095a5dSDimitry Andric void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,
18245a5ac124SDimitry Andric SmallVectorImpl<uint64_t> &Record,
18255a5ac124SDimitry Andric unsigned Abbrev) {
1826cfca06d7SDimitry Andric const uint64_t IsBigInt = 1 << 2;
1827cfca06d7SDimitry Andric Record.push_back(IsBigInt | (N->isUnsigned() << 1) | N->isDistinct());
1828cfca06d7SDimitry Andric Record.push_back(N->getValue().getBitWidth());
18295a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1830cfca06d7SDimitry Andric emitWideAPInt(Record, N->getValue());
18315a5ac124SDimitry Andric
18325a5ac124SDimitry Andric Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
18335a5ac124SDimitry Andric Record.clear();
18345a5ac124SDimitry Andric }
18355a5ac124SDimitry Andric
writeDIBasicType(const DIBasicType * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)183601095a5dSDimitry Andric void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N,
18375a5ac124SDimitry Andric SmallVectorImpl<uint64_t> &Record,
18385a5ac124SDimitry Andric unsigned Abbrev) {
18395a5ac124SDimitry Andric Record.push_back(N->isDistinct());
18405a5ac124SDimitry Andric Record.push_back(N->getTag());
18415a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
18425a5ac124SDimitry Andric Record.push_back(N->getSizeInBits());
18435a5ac124SDimitry Andric Record.push_back(N->getAlignInBits());
18445a5ac124SDimitry Andric Record.push_back(N->getEncoding());
1845d8e91e46SDimitry Andric Record.push_back(N->getFlags());
18465a5ac124SDimitry Andric
18475a5ac124SDimitry Andric Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
18485a5ac124SDimitry Andric Record.clear();
18495a5ac124SDimitry Andric }
18505a5ac124SDimitry Andric
writeDIStringType(const DIStringType * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)1851b60736ecSDimitry Andric void ModuleBitcodeWriter::writeDIStringType(const DIStringType *N,
1852b60736ecSDimitry Andric SmallVectorImpl<uint64_t> &Record,
1853b60736ecSDimitry Andric unsigned Abbrev) {
1854b60736ecSDimitry Andric Record.push_back(N->isDistinct());
1855b60736ecSDimitry Andric Record.push_back(N->getTag());
1856b60736ecSDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1857b60736ecSDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getStringLength()));
1858b60736ecSDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getStringLengthExp()));
18596f8fc217SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getStringLocationExp()));
1860b60736ecSDimitry Andric Record.push_back(N->getSizeInBits());
1861b60736ecSDimitry Andric Record.push_back(N->getAlignInBits());
1862b60736ecSDimitry Andric Record.push_back(N->getEncoding());
1863b60736ecSDimitry Andric
1864b60736ecSDimitry Andric Stream.EmitRecord(bitc::METADATA_STRING_TYPE, Record, Abbrev);
1865b60736ecSDimitry Andric Record.clear();
1866b60736ecSDimitry Andric }
1867b60736ecSDimitry Andric
writeDIDerivedType(const DIDerivedType * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)186801095a5dSDimitry Andric void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,
18695a5ac124SDimitry Andric SmallVectorImpl<uint64_t> &Record,
18705a5ac124SDimitry Andric unsigned Abbrev) {
18715a5ac124SDimitry Andric Record.push_back(N->isDistinct());
18725a5ac124SDimitry Andric Record.push_back(N->getTag());
18735a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
18745a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getFile()));
18755a5ac124SDimitry Andric Record.push_back(N->getLine());
18765a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getScope()));
18775a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
18785a5ac124SDimitry Andric Record.push_back(N->getSizeInBits());
18795a5ac124SDimitry Andric Record.push_back(N->getAlignInBits());
18805a5ac124SDimitry Andric Record.push_back(N->getOffsetInBits());
18815a5ac124SDimitry Andric Record.push_back(N->getFlags());
18825a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
18835a5ac124SDimitry Andric
188471d5a254SDimitry Andric // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
188571d5a254SDimitry Andric // that there is no DWARF address space associated with DIDerivedType.
188671d5a254SDimitry Andric if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
188771d5a254SDimitry Andric Record.push_back(*DWARFAddressSpace + 1);
188871d5a254SDimitry Andric else
188971d5a254SDimitry Andric Record.push_back(0);
189071d5a254SDimitry Andric
1891c0981da4SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
1892c0981da4SDimitry Andric
1893ac9a064cSDimitry Andric if (auto PtrAuthData = N->getPtrAuthData())
1894ac9a064cSDimitry Andric Record.push_back(PtrAuthData->RawData);
1895ac9a064cSDimitry Andric else
1896ac9a064cSDimitry Andric Record.push_back(0);
1897ac9a064cSDimitry Andric
18985a5ac124SDimitry Andric Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
18995a5ac124SDimitry Andric Record.clear();
19005a5ac124SDimitry Andric }
19015a5ac124SDimitry Andric
writeDICompositeType(const DICompositeType * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)190201095a5dSDimitry Andric void ModuleBitcodeWriter::writeDICompositeType(
190301095a5dSDimitry Andric const DICompositeType *N, SmallVectorImpl<uint64_t> &Record,
19045a5ac124SDimitry Andric unsigned Abbrev) {
190501095a5dSDimitry Andric const unsigned IsNotUsedInOldTypeRef = 0x2;
190601095a5dSDimitry Andric Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct());
19075a5ac124SDimitry Andric Record.push_back(N->getTag());
19085a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
19095a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getFile()));
19105a5ac124SDimitry Andric Record.push_back(N->getLine());
19115a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getScope()));
19125a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
19135a5ac124SDimitry Andric Record.push_back(N->getSizeInBits());
19145a5ac124SDimitry Andric Record.push_back(N->getAlignInBits());
19155a5ac124SDimitry Andric Record.push_back(N->getOffsetInBits());
19165a5ac124SDimitry Andric Record.push_back(N->getFlags());
19175a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
19185a5ac124SDimitry Andric Record.push_back(N->getRuntimeLang());
19195a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
19205a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
19215a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
1922eb11fae6SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getDiscriminator()));
1923cfca06d7SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRawDataLocation()));
1924b60736ecSDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRawAssociated()));
1925b60736ecSDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRawAllocated()));
1926b60736ecSDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRawRank()));
1927c0981da4SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
19285a5ac124SDimitry Andric
19295a5ac124SDimitry Andric Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
19305a5ac124SDimitry Andric Record.clear();
19315a5ac124SDimitry Andric }
19325a5ac124SDimitry Andric
writeDISubroutineType(const DISubroutineType * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)193301095a5dSDimitry Andric void ModuleBitcodeWriter::writeDISubroutineType(
193401095a5dSDimitry Andric const DISubroutineType *N, SmallVectorImpl<uint64_t> &Record,
19355a5ac124SDimitry Andric unsigned Abbrev) {
193601095a5dSDimitry Andric const unsigned HasNoOldTypeRefs = 0x2;
193701095a5dSDimitry Andric Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
19385a5ac124SDimitry Andric Record.push_back(N->getFlags());
19395a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
194001095a5dSDimitry Andric Record.push_back(N->getCC());
19415a5ac124SDimitry Andric
19425a5ac124SDimitry Andric Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
19435a5ac124SDimitry Andric Record.clear();
19445a5ac124SDimitry Andric }
19455a5ac124SDimitry Andric
writeDIFile(const DIFile * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)194601095a5dSDimitry Andric void ModuleBitcodeWriter::writeDIFile(const DIFile *N,
194701095a5dSDimitry Andric SmallVectorImpl<uint64_t> &Record,
194801095a5dSDimitry Andric unsigned Abbrev) {
19495a5ac124SDimitry Andric Record.push_back(N->isDistinct());
19505a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
19515a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
1952eb11fae6SDimitry Andric if (N->getRawChecksum()) {
1953eb11fae6SDimitry Andric Record.push_back(N->getRawChecksum()->Kind);
1954eb11fae6SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()->Value));
1955eb11fae6SDimitry Andric } else {
1956eb11fae6SDimitry Andric // Maintain backwards compatibility with the old internal representation of
1957eb11fae6SDimitry Andric // CSK_None in ChecksumKind by writing nulls here when Checksum is None.
1958eb11fae6SDimitry Andric Record.push_back(0);
1959eb11fae6SDimitry Andric Record.push_back(VE.getMetadataOrNullID(nullptr));
1960eb11fae6SDimitry Andric }
1961eb11fae6SDimitry Andric auto Source = N->getRawSource();
1962eb11fae6SDimitry Andric if (Source)
1963e3b55780SDimitry Andric Record.push_back(VE.getMetadataOrNullID(Source));
19645a5ac124SDimitry Andric
19655a5ac124SDimitry Andric Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
19665a5ac124SDimitry Andric Record.clear();
19675a5ac124SDimitry Andric }
19685a5ac124SDimitry Andric
writeDICompileUnit(const DICompileUnit * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)196901095a5dSDimitry Andric void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
19705a5ac124SDimitry Andric SmallVectorImpl<uint64_t> &Record,
19715a5ac124SDimitry Andric unsigned Abbrev) {
1972dd58ef01SDimitry Andric assert(N->isDistinct() && "Expected distinct compile units");
1973dd58ef01SDimitry Andric Record.push_back(/* IsDistinct */ true);
19745a5ac124SDimitry Andric Record.push_back(N->getSourceLanguage());
19755a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getFile()));
19765a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
19775a5ac124SDimitry Andric Record.push_back(N->isOptimized());
19785a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
19795a5ac124SDimitry Andric Record.push_back(N->getRuntimeVersion());
19805a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
19815a5ac124SDimitry Andric Record.push_back(N->getEmissionKind());
19825a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
19835a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
198401095a5dSDimitry Andric Record.push_back(/* subprograms */ 0);
19855a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
19865a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
19875a5ac124SDimitry Andric Record.push_back(N->getDWOId());
1988dd58ef01SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
1989b915e9e0SDimitry Andric Record.push_back(N->getSplitDebugInlining());
199071d5a254SDimitry Andric Record.push_back(N->getDebugInfoForProfiling());
1991d8e91e46SDimitry Andric Record.push_back((unsigned)N->getNameTableKind());
1992cfca06d7SDimitry Andric Record.push_back(N->getRangesBaseAddress());
1993cfca06d7SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRawSysRoot()));
1994cfca06d7SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRawSDK()));
19955a5ac124SDimitry Andric
19965a5ac124SDimitry Andric Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
19975a5ac124SDimitry Andric Record.clear();
19985a5ac124SDimitry Andric }
19995a5ac124SDimitry Andric
writeDISubprogram(const DISubprogram * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)200001095a5dSDimitry Andric void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,
20015a5ac124SDimitry Andric SmallVectorImpl<uint64_t> &Record,
20025a5ac124SDimitry Andric unsigned Abbrev) {
2003d8e91e46SDimitry Andric const uint64_t HasUnitFlag = 1 << 1;
2004d8e91e46SDimitry Andric const uint64_t HasSPFlagsFlag = 1 << 2;
2005d8e91e46SDimitry Andric Record.push_back(uint64_t(N->isDistinct()) | HasUnitFlag | HasSPFlagsFlag);
20065a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getScope()));
20075a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
20085a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
20095a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getFile()));
20105a5ac124SDimitry Andric Record.push_back(N->getLine());
20115a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getType()));
20125a5ac124SDimitry Andric Record.push_back(N->getScopeLine());
20135a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
2014d8e91e46SDimitry Andric Record.push_back(N->getSPFlags());
20155a5ac124SDimitry Andric Record.push_back(N->getVirtualIndex());
20165a5ac124SDimitry Andric Record.push_back(N->getFlags());
201701095a5dSDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
20185a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
20195a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
2020eb11fae6SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRetainedNodes().get()));
202101095a5dSDimitry Andric Record.push_back(N->getThisAdjustment());
2022a303c417SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get()));
2023c0981da4SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2024145449b1SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRawTargetFuncName()));
20255a5ac124SDimitry Andric
20265a5ac124SDimitry Andric Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
20275a5ac124SDimitry Andric Record.clear();
20285a5ac124SDimitry Andric }
20295a5ac124SDimitry Andric
writeDILexicalBlock(const DILexicalBlock * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)203001095a5dSDimitry Andric void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
20315a5ac124SDimitry Andric SmallVectorImpl<uint64_t> &Record,
20325a5ac124SDimitry Andric unsigned Abbrev) {
20335a5ac124SDimitry Andric Record.push_back(N->isDistinct());
20345a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getScope()));
20355a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getFile()));
20365a5ac124SDimitry Andric Record.push_back(N->getLine());
20375a5ac124SDimitry Andric Record.push_back(N->getColumn());
20385a5ac124SDimitry Andric
20395a5ac124SDimitry Andric Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
20405a5ac124SDimitry Andric Record.clear();
20415a5ac124SDimitry Andric }
20425a5ac124SDimitry Andric
writeDILexicalBlockFile(const DILexicalBlockFile * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)204301095a5dSDimitry Andric void ModuleBitcodeWriter::writeDILexicalBlockFile(
204401095a5dSDimitry Andric const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record,
20455a5ac124SDimitry Andric unsigned Abbrev) {
20465a5ac124SDimitry Andric Record.push_back(N->isDistinct());
20475a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getScope()));
20485a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getFile()));
20495a5ac124SDimitry Andric Record.push_back(N->getDiscriminator());
20505a5ac124SDimitry Andric
20515a5ac124SDimitry Andric Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
20525a5ac124SDimitry Andric Record.clear();
20535a5ac124SDimitry Andric }
20545a5ac124SDimitry Andric
writeDICommonBlock(const DICommonBlock * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)2055e6d15924SDimitry Andric void ModuleBitcodeWriter::writeDICommonBlock(const DICommonBlock *N,
2056e6d15924SDimitry Andric SmallVectorImpl<uint64_t> &Record,
2057e6d15924SDimitry Andric unsigned Abbrev) {
2058e6d15924SDimitry Andric Record.push_back(N->isDistinct());
2059e6d15924SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2060e6d15924SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getDecl()));
2061e6d15924SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2062e6d15924SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2063e6d15924SDimitry Andric Record.push_back(N->getLineNo());
2064e6d15924SDimitry Andric
2065e6d15924SDimitry Andric Stream.EmitRecord(bitc::METADATA_COMMON_BLOCK, Record, Abbrev);
2066e6d15924SDimitry Andric Record.clear();
2067e6d15924SDimitry Andric }
2068e6d15924SDimitry Andric
writeDINamespace(const DINamespace * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)206901095a5dSDimitry Andric void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,
20705a5ac124SDimitry Andric SmallVectorImpl<uint64_t> &Record,
20715a5ac124SDimitry Andric unsigned Abbrev) {
2072b915e9e0SDimitry Andric Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
20735a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getScope()));
20745a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
20755a5ac124SDimitry Andric
20765a5ac124SDimitry Andric Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
20775a5ac124SDimitry Andric Record.clear();
20785a5ac124SDimitry Andric }
20795a5ac124SDimitry Andric
writeDIMacro(const DIMacro * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)208001095a5dSDimitry Andric void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,
208101095a5dSDimitry Andric SmallVectorImpl<uint64_t> &Record,
208201095a5dSDimitry Andric unsigned Abbrev) {
2083dd58ef01SDimitry Andric Record.push_back(N->isDistinct());
2084dd58ef01SDimitry Andric Record.push_back(N->getMacinfoType());
2085dd58ef01SDimitry Andric Record.push_back(N->getLine());
2086dd58ef01SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2087dd58ef01SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
2088dd58ef01SDimitry Andric
2089dd58ef01SDimitry Andric Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
2090dd58ef01SDimitry Andric Record.clear();
2091dd58ef01SDimitry Andric }
2092dd58ef01SDimitry Andric
writeDIMacroFile(const DIMacroFile * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)209301095a5dSDimitry Andric void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,
2094dd58ef01SDimitry Andric SmallVectorImpl<uint64_t> &Record,
2095dd58ef01SDimitry Andric unsigned Abbrev) {
2096dd58ef01SDimitry Andric Record.push_back(N->isDistinct());
2097dd58ef01SDimitry Andric Record.push_back(N->getMacinfoType());
2098dd58ef01SDimitry Andric Record.push_back(N->getLine());
2099dd58ef01SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2100dd58ef01SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
2101dd58ef01SDimitry Andric
2102dd58ef01SDimitry Andric Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
2103dd58ef01SDimitry Andric Record.clear();
2104dd58ef01SDimitry Andric }
2105dd58ef01SDimitry Andric
writeDIArgList(const DIArgList * N,SmallVectorImpl<uint64_t> & Record)2106344a3780SDimitry Andric void ModuleBitcodeWriter::writeDIArgList(const DIArgList *N,
2107b1c73532SDimitry Andric SmallVectorImpl<uint64_t> &Record) {
2108344a3780SDimitry Andric Record.reserve(N->getArgs().size());
2109344a3780SDimitry Andric for (ValueAsMetadata *MD : N->getArgs())
2110344a3780SDimitry Andric Record.push_back(VE.getMetadataID(MD));
2111344a3780SDimitry Andric
2112b1c73532SDimitry Andric Stream.EmitRecord(bitc::METADATA_ARG_LIST, Record);
2113344a3780SDimitry Andric Record.clear();
2114344a3780SDimitry Andric }
2115344a3780SDimitry Andric
writeDIModule(const DIModule * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)211601095a5dSDimitry Andric void ModuleBitcodeWriter::writeDIModule(const DIModule *N,
211701095a5dSDimitry Andric SmallVectorImpl<uint64_t> &Record,
211801095a5dSDimitry Andric unsigned Abbrev) {
21191a82d4c0SDimitry Andric Record.push_back(N->isDistinct());
21201a82d4c0SDimitry Andric for (auto &I : N->operands())
21211a82d4c0SDimitry Andric Record.push_back(VE.getMetadataOrNullID(I));
2122cfca06d7SDimitry Andric Record.push_back(N->getLineNo());
2123b60736ecSDimitry Andric Record.push_back(N->getIsDecl());
21241a82d4c0SDimitry Andric
21251a82d4c0SDimitry Andric Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
21261a82d4c0SDimitry Andric Record.clear();
21271a82d4c0SDimitry Andric }
21281a82d4c0SDimitry Andric
writeDIAssignID(const DIAssignID * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)2129e3b55780SDimitry Andric void ModuleBitcodeWriter::writeDIAssignID(const DIAssignID *N,
2130e3b55780SDimitry Andric SmallVectorImpl<uint64_t> &Record,
2131e3b55780SDimitry Andric unsigned Abbrev) {
2132e3b55780SDimitry Andric // There are no arguments for this metadata type.
2133e3b55780SDimitry Andric Record.push_back(N->isDistinct());
2134e3b55780SDimitry Andric Stream.EmitRecord(bitc::METADATA_ASSIGN_ID, Record, Abbrev);
2135e3b55780SDimitry Andric Record.clear();
2136e3b55780SDimitry Andric }
2137e3b55780SDimitry Andric
writeDITemplateTypeParameter(const DITemplateTypeParameter * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)213801095a5dSDimitry Andric void ModuleBitcodeWriter::writeDITemplateTypeParameter(
213901095a5dSDimitry Andric const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record,
21405a5ac124SDimitry Andric unsigned Abbrev) {
21415a5ac124SDimitry Andric Record.push_back(N->isDistinct());
21425a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
21435a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getType()));
2144cfca06d7SDimitry Andric Record.push_back(N->isDefault());
21455a5ac124SDimitry Andric
21465a5ac124SDimitry Andric Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
21475a5ac124SDimitry Andric Record.clear();
21485a5ac124SDimitry Andric }
21495a5ac124SDimitry Andric
writeDITemplateValueParameter(const DITemplateValueParameter * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)215001095a5dSDimitry Andric void ModuleBitcodeWriter::writeDITemplateValueParameter(
215101095a5dSDimitry Andric const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record,
21525a5ac124SDimitry Andric unsigned Abbrev) {
21535a5ac124SDimitry Andric Record.push_back(N->isDistinct());
21545a5ac124SDimitry Andric Record.push_back(N->getTag());
21555a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
21565a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getType()));
2157cfca06d7SDimitry Andric Record.push_back(N->isDefault());
21585a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getValue()));
21595a5ac124SDimitry Andric
21605a5ac124SDimitry Andric Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
21615a5ac124SDimitry Andric Record.clear();
21625a5ac124SDimitry Andric }
21635a5ac124SDimitry Andric
writeDIGlobalVariable(const DIGlobalVariable * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)216401095a5dSDimitry Andric void ModuleBitcodeWriter::writeDIGlobalVariable(
216501095a5dSDimitry Andric const DIGlobalVariable *N, SmallVectorImpl<uint64_t> &Record,
21665a5ac124SDimitry Andric unsigned Abbrev) {
2167d8e91e46SDimitry Andric const uint64_t Version = 2 << 1;
2168b915e9e0SDimitry Andric Record.push_back((uint64_t)N->isDistinct() | Version);
21695a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getScope()));
21705a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
21715a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
21725a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getFile()));
21735a5ac124SDimitry Andric Record.push_back(N->getLine());
21745a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getType()));
21755a5ac124SDimitry Andric Record.push_back(N->isLocalToUnit());
21765a5ac124SDimitry Andric Record.push_back(N->isDefinition());
21775a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
2178d8e91e46SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams()));
2179b915e9e0SDimitry Andric Record.push_back(N->getAlignInBits());
2180c0981da4SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
21815a5ac124SDimitry Andric
21825a5ac124SDimitry Andric Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
21835a5ac124SDimitry Andric Record.clear();
21845a5ac124SDimitry Andric }
21855a5ac124SDimitry Andric
writeDILocalVariable(const DILocalVariable * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)218601095a5dSDimitry Andric void ModuleBitcodeWriter::writeDILocalVariable(
218701095a5dSDimitry Andric const DILocalVariable *N, SmallVectorImpl<uint64_t> &Record,
21885a5ac124SDimitry Andric unsigned Abbrev) {
2189b915e9e0SDimitry Andric // In order to support all possible bitcode formats in BitcodeReader we need
2190b915e9e0SDimitry Andric // to distinguish the following cases:
2191b915e9e0SDimitry Andric // 1) Record has no artificial tag (Record[1]),
2192b915e9e0SDimitry Andric // has no obsolete inlinedAt field (Record[9]).
2193b915e9e0SDimitry Andric // In this case Record size will be 8, HasAlignment flag is false.
2194b915e9e0SDimitry Andric // 2) Record has artificial tag (Record[1]),
2195b915e9e0SDimitry Andric // has no obsolete inlignedAt field (Record[9]).
2196b915e9e0SDimitry Andric // In this case Record size will be 9, HasAlignment flag is false.
2197b915e9e0SDimitry Andric // 3) Record has both artificial tag (Record[1]) and
2198b915e9e0SDimitry Andric // obsolete inlignedAt field (Record[9]).
2199b915e9e0SDimitry Andric // In this case Record size will be 10, HasAlignment flag is false.
2200b915e9e0SDimitry Andric // 4) Record has neither artificial tag, nor inlignedAt field, but
2201b915e9e0SDimitry Andric // HasAlignment flag is true and Record[8] contains alignment value.
2202b915e9e0SDimitry Andric const uint64_t HasAlignmentFlag = 1 << 1;
2203b915e9e0SDimitry Andric Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
22045a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getScope()));
22055a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
22065a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getFile()));
22075a5ac124SDimitry Andric Record.push_back(N->getLine());
22085a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getType()));
22095a5ac124SDimitry Andric Record.push_back(N->getArg());
22105a5ac124SDimitry Andric Record.push_back(N->getFlags());
2211b915e9e0SDimitry Andric Record.push_back(N->getAlignInBits());
2212c0981da4SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
22135a5ac124SDimitry Andric
22145a5ac124SDimitry Andric Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
22155a5ac124SDimitry Andric Record.clear();
22165a5ac124SDimitry Andric }
22175a5ac124SDimitry Andric
writeDILabel(const DILabel * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)2218eb11fae6SDimitry Andric void ModuleBitcodeWriter::writeDILabel(
2219eb11fae6SDimitry Andric const DILabel *N, SmallVectorImpl<uint64_t> &Record,
2220eb11fae6SDimitry Andric unsigned Abbrev) {
2221eb11fae6SDimitry Andric Record.push_back((uint64_t)N->isDistinct());
2222eb11fae6SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2223eb11fae6SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2224eb11fae6SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2225eb11fae6SDimitry Andric Record.push_back(N->getLine());
2226eb11fae6SDimitry Andric
2227eb11fae6SDimitry Andric Stream.EmitRecord(bitc::METADATA_LABEL, Record, Abbrev);
2228eb11fae6SDimitry Andric Record.clear();
2229eb11fae6SDimitry Andric }
2230eb11fae6SDimitry Andric
writeDIExpression(const DIExpression * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)223101095a5dSDimitry Andric void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,
22325a5ac124SDimitry Andric SmallVectorImpl<uint64_t> &Record,
22335a5ac124SDimitry Andric unsigned Abbrev) {
22345a5ac124SDimitry Andric Record.reserve(N->getElements().size() + 1);
22357c7aba6eSDimitry Andric const uint64_t Version = 3 << 1;
2236d99dafe2SDimitry Andric Record.push_back((uint64_t)N->isDistinct() | Version);
22375a5ac124SDimitry Andric Record.append(N->elements_begin(), N->elements_end());
22385a5ac124SDimitry Andric
22395a5ac124SDimitry Andric Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
22405a5ac124SDimitry Andric Record.clear();
22415a5ac124SDimitry Andric }
22425a5ac124SDimitry Andric
writeDIGlobalVariableExpression(const DIGlobalVariableExpression * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)2243b915e9e0SDimitry Andric void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
2244b915e9e0SDimitry Andric const DIGlobalVariableExpression *N, SmallVectorImpl<uint64_t> &Record,
2245b915e9e0SDimitry Andric unsigned Abbrev) {
2246b915e9e0SDimitry Andric Record.push_back(N->isDistinct());
2247b915e9e0SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
2248b915e9e0SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
2249b915e9e0SDimitry Andric
2250b915e9e0SDimitry Andric Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR, Record, Abbrev);
2251b915e9e0SDimitry Andric Record.clear();
2252b915e9e0SDimitry Andric }
2253b915e9e0SDimitry Andric
writeDIObjCProperty(const DIObjCProperty * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)225401095a5dSDimitry Andric void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
22555a5ac124SDimitry Andric SmallVectorImpl<uint64_t> &Record,
22565a5ac124SDimitry Andric unsigned Abbrev) {
22575a5ac124SDimitry Andric Record.push_back(N->isDistinct());
22585a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
22595a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getFile()));
22605a5ac124SDimitry Andric Record.push_back(N->getLine());
22615a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
22625a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
22635a5ac124SDimitry Andric Record.push_back(N->getAttributes());
22645a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getType()));
22655a5ac124SDimitry Andric
22665a5ac124SDimitry Andric Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
22675a5ac124SDimitry Andric Record.clear();
22685a5ac124SDimitry Andric }
22695a5ac124SDimitry Andric
writeDIImportedEntity(const DIImportedEntity * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)227001095a5dSDimitry Andric void ModuleBitcodeWriter::writeDIImportedEntity(
227101095a5dSDimitry Andric const DIImportedEntity *N, SmallVectorImpl<uint64_t> &Record,
22725a5ac124SDimitry Andric unsigned Abbrev) {
22735a5ac124SDimitry Andric Record.push_back(N->isDistinct());
22745a5ac124SDimitry Andric Record.push_back(N->getTag());
22755a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getScope()));
22765a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
22775a5ac124SDimitry Andric Record.push_back(N->getLine());
22785a5ac124SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
227993c91e39SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getRawFile()));
2280c0981da4SDimitry Andric Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
22815a5ac124SDimitry Andric
22825a5ac124SDimitry Andric Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
22835a5ac124SDimitry Andric Record.clear();
22845a5ac124SDimitry Andric }
22855a5ac124SDimitry Andric
createNamedMetadataAbbrev()228601095a5dSDimitry Andric unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
22877e7b6700SDimitry Andric auto Abbv = std::make_shared<BitCodeAbbrev>();
228801095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
228959850d08SRoman Divacky Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
229059850d08SRoman Divacky Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
22917e7b6700SDimitry Andric return Stream.EmitAbbrev(std::move(Abbv));
229259850d08SRoman Divacky }
229359850d08SRoman Divacky
writeNamedMetadata(SmallVectorImpl<uint64_t> & Record)229401095a5dSDimitry Andric void ModuleBitcodeWriter::writeNamedMetadata(
229501095a5dSDimitry Andric SmallVectorImpl<uint64_t> &Record) {
229601095a5dSDimitry Andric if (M.named_metadata_empty())
229701095a5dSDimitry Andric return;
229801095a5dSDimitry Andric
229901095a5dSDimitry Andric unsigned Abbrev = createNamedMetadataAbbrev();
230001095a5dSDimitry Andric for (const NamedMDNode &NMD : M.named_metadata()) {
230101095a5dSDimitry Andric // Write name.
230201095a5dSDimitry Andric StringRef Str = NMD.getName();
230301095a5dSDimitry Andric Record.append(Str.bytes_begin(), Str.bytes_end());
230401095a5dSDimitry Andric Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
230501095a5dSDimitry Andric Record.clear();
230601095a5dSDimitry Andric
230701095a5dSDimitry Andric // Write named metadata operands.
230801095a5dSDimitry Andric for (const MDNode *N : NMD.operands())
230901095a5dSDimitry Andric Record.push_back(VE.getMetadataID(N));
231001095a5dSDimitry Andric Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
231101095a5dSDimitry Andric Record.clear();
231201095a5dSDimitry Andric }
231301095a5dSDimitry Andric }
231401095a5dSDimitry Andric
createMetadataStringsAbbrev()231501095a5dSDimitry Andric unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
23167e7b6700SDimitry Andric auto Abbv = std::make_shared<BitCodeAbbrev>();
231701095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS));
231801095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
231901095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
232001095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
23217e7b6700SDimitry Andric return Stream.EmitAbbrev(std::move(Abbv));
232201095a5dSDimitry Andric }
232301095a5dSDimitry Andric
232401095a5dSDimitry Andric /// Write out a record for MDString.
232501095a5dSDimitry Andric ///
232601095a5dSDimitry Andric /// All the metadata strings in a metadata block are emitted in a single
232701095a5dSDimitry Andric /// record. The sizes and strings themselves are shoved into a blob.
writeMetadataStrings(ArrayRef<const Metadata * > Strings,SmallVectorImpl<uint64_t> & Record)232801095a5dSDimitry Andric void ModuleBitcodeWriter::writeMetadataStrings(
232901095a5dSDimitry Andric ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) {
233001095a5dSDimitry Andric if (Strings.empty())
233101095a5dSDimitry Andric return;
233201095a5dSDimitry Andric
233301095a5dSDimitry Andric // Start the record with the number of strings.
233401095a5dSDimitry Andric Record.push_back(bitc::METADATA_STRINGS);
233501095a5dSDimitry Andric Record.push_back(Strings.size());
233601095a5dSDimitry Andric
233701095a5dSDimitry Andric // Emit the sizes of the strings in the blob.
233801095a5dSDimitry Andric SmallString<256> Blob;
233901095a5dSDimitry Andric {
234001095a5dSDimitry Andric BitstreamWriter W(Blob);
234101095a5dSDimitry Andric for (const Metadata *MD : Strings)
234201095a5dSDimitry Andric W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
234301095a5dSDimitry Andric W.FlushToWord();
234401095a5dSDimitry Andric }
234501095a5dSDimitry Andric
234601095a5dSDimitry Andric // Add the offset to the strings to the record.
234701095a5dSDimitry Andric Record.push_back(Blob.size());
234801095a5dSDimitry Andric
234901095a5dSDimitry Andric // Add the strings to the blob.
235001095a5dSDimitry Andric for (const Metadata *MD : Strings)
235101095a5dSDimitry Andric Blob.append(cast<MDString>(MD)->getString());
235201095a5dSDimitry Andric
235301095a5dSDimitry Andric // Emit the final record.
235401095a5dSDimitry Andric Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
235501095a5dSDimitry Andric Record.clear();
235601095a5dSDimitry Andric }
235701095a5dSDimitry Andric
2358b915e9e0SDimitry Andric // Generates an enum to use as an index in the Abbrev array of Metadata record.
2359b915e9e0SDimitry Andric enum MetadataAbbrev : unsigned {
2360b915e9e0SDimitry Andric #define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
2361b915e9e0SDimitry Andric #include "llvm/IR/Metadata.def"
2362b915e9e0SDimitry Andric LastPlusOne
2363b915e9e0SDimitry Andric };
2364b915e9e0SDimitry Andric
writeMetadataRecords(ArrayRef<const Metadata * > MDs,SmallVectorImpl<uint64_t> & Record,std::vector<unsigned> * MDAbbrevs,std::vector<uint64_t> * IndexPos)236501095a5dSDimitry Andric void ModuleBitcodeWriter::writeMetadataRecords(
2366b915e9e0SDimitry Andric ArrayRef<const Metadata *> MDs, SmallVectorImpl<uint64_t> &Record,
2367b915e9e0SDimitry Andric std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
236801095a5dSDimitry Andric if (MDs.empty())
236901095a5dSDimitry Andric return;
237001095a5dSDimitry Andric
23715a5ac124SDimitry Andric // Initialize MDNode abbreviations.
23725a5ac124SDimitry Andric #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
23735a5ac124SDimitry Andric #include "llvm/IR/Metadata.def"
23745a5ac124SDimitry Andric
237567c32a98SDimitry Andric for (const Metadata *MD : MDs) {
2376b915e9e0SDimitry Andric if (IndexPos)
2377b915e9e0SDimitry Andric IndexPos->push_back(Stream.GetCurrentBitNo());
237867c32a98SDimitry Andric if (const MDNode *N = dyn_cast<MDNode>(MD)) {
23795a5ac124SDimitry Andric assert(N->isResolved() && "Expected forward references to be resolved");
23805a5ac124SDimitry Andric
23815a5ac124SDimitry Andric switch (N->getMetadataID()) {
23825a5ac124SDimitry Andric default:
23835a5ac124SDimitry Andric llvm_unreachable("Invalid MDNode subclass");
23845a5ac124SDimitry Andric #define HANDLE_MDNODE_LEAF(CLASS) \
23855a5ac124SDimitry Andric case Metadata::CLASS##Kind: \
2386b915e9e0SDimitry Andric if (MDAbbrevs) \
2387b915e9e0SDimitry Andric write##CLASS(cast<CLASS>(N), Record, \
2388b915e9e0SDimitry Andric (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
2389b915e9e0SDimitry Andric else \
239001095a5dSDimitry Andric write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
239167c32a98SDimitry Andric continue;
23925a5ac124SDimitry Andric #include "llvm/IR/Metadata.def"
23935a5ac124SDimitry Andric }
239467c32a98SDimitry Andric }
2395b1c73532SDimitry Andric if (auto *AL = dyn_cast<DIArgList>(MD)) {
2396b1c73532SDimitry Andric writeDIArgList(AL, Record);
2397b1c73532SDimitry Andric continue;
2398b1c73532SDimitry Andric }
239901095a5dSDimitry Andric writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
240067c32a98SDimitry Andric }
2401d39c594dSDimitry Andric }
2402d39c594dSDimitry Andric
writeModuleMetadata()240301095a5dSDimitry Andric void ModuleBitcodeWriter::writeModuleMetadata() {
240401095a5dSDimitry Andric if (!VE.hasMDs() && M.named_metadata_empty())
240501095a5dSDimitry Andric return;
240659850d08SRoman Divacky
2407b915e9e0SDimitry Andric Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 4);
240801095a5dSDimitry Andric SmallVector<uint64_t, 64> Record;
2409b915e9e0SDimitry Andric
2410b915e9e0SDimitry Andric // Emit all abbrevs upfront, so that the reader can jump in the middle of the
2411b915e9e0SDimitry Andric // block and load any metadata.
2412b915e9e0SDimitry Andric std::vector<unsigned> MDAbbrevs;
2413b915e9e0SDimitry Andric
2414b915e9e0SDimitry Andric MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
2415b915e9e0SDimitry Andric MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
2416b915e9e0SDimitry Andric MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
2417b915e9e0SDimitry Andric createGenericDINodeAbbrev();
2418b915e9e0SDimitry Andric
24197e7b6700SDimitry Andric auto Abbv = std::make_shared<BitCodeAbbrev>();
2420b915e9e0SDimitry Andric Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX_OFFSET));
2421b915e9e0SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2422b915e9e0SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
24237e7b6700SDimitry Andric unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2424b915e9e0SDimitry Andric
24257e7b6700SDimitry Andric Abbv = std::make_shared<BitCodeAbbrev>();
2426b915e9e0SDimitry Andric Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX));
2427b915e9e0SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2428b915e9e0SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
24297e7b6700SDimitry Andric unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2430b915e9e0SDimitry Andric
2431b915e9e0SDimitry Andric // Emit MDStrings together upfront.
243201095a5dSDimitry Andric writeMetadataStrings(VE.getMDStrings(), Record);
2433b915e9e0SDimitry Andric
2434b915e9e0SDimitry Andric // We only emit an index for the metadata record if we have more than a given
2435b915e9e0SDimitry Andric // (naive) threshold of metadatas, otherwise it is not worth it.
2436b915e9e0SDimitry Andric if (VE.getNonMDStrings().size() > IndexThreshold) {
2437b915e9e0SDimitry Andric // Write a placeholder value in for the offset of the metadata index,
2438b915e9e0SDimitry Andric // which is written after the records, so that it can include
2439b915e9e0SDimitry Andric // the offset of each entry. The placeholder offset will be
2440b915e9e0SDimitry Andric // updated after all records are emitted.
2441b915e9e0SDimitry Andric uint64_t Vals[] = {0, 0};
2442b915e9e0SDimitry Andric Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
2443b915e9e0SDimitry Andric }
2444b915e9e0SDimitry Andric
2445b915e9e0SDimitry Andric // Compute and save the bit offset to the current position, which will be
2446b915e9e0SDimitry Andric // patched when we emit the index later. We can simply subtract the 64-bit
2447b915e9e0SDimitry Andric // fixed size from the current bit number to get the location to backpatch.
2448b915e9e0SDimitry Andric uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
2449b915e9e0SDimitry Andric
2450b915e9e0SDimitry Andric // This index will contain the bitpos for each individual record.
2451b915e9e0SDimitry Andric std::vector<uint64_t> IndexPos;
2452b915e9e0SDimitry Andric IndexPos.reserve(VE.getNonMDStrings().size());
2453b915e9e0SDimitry Andric
2454b915e9e0SDimitry Andric // Write all the records
2455b915e9e0SDimitry Andric writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
2456b915e9e0SDimitry Andric
2457b915e9e0SDimitry Andric if (VE.getNonMDStrings().size() > IndexThreshold) {
2458b915e9e0SDimitry Andric // Now that we have emitted all the records we will emit the index. But
2459b915e9e0SDimitry Andric // first
2460b915e9e0SDimitry Andric // backpatch the forward reference so that the reader can skip the records
2461b915e9e0SDimitry Andric // efficiently.
2462b915e9e0SDimitry Andric Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
2463b915e9e0SDimitry Andric Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
2464b915e9e0SDimitry Andric
2465b915e9e0SDimitry Andric // Delta encode the index.
2466b915e9e0SDimitry Andric uint64_t PreviousValue = IndexOffsetRecordBitPos;
2467b915e9e0SDimitry Andric for (auto &Elt : IndexPos) {
2468b915e9e0SDimitry Andric auto EltDelta = Elt - PreviousValue;
2469b915e9e0SDimitry Andric PreviousValue = Elt;
2470b915e9e0SDimitry Andric Elt = EltDelta;
2471b915e9e0SDimitry Andric }
2472b915e9e0SDimitry Andric // Emit the index record.
2473b915e9e0SDimitry Andric Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
2474b915e9e0SDimitry Andric IndexPos.clear();
2475b915e9e0SDimitry Andric }
2476b915e9e0SDimitry Andric
2477b915e9e0SDimitry Andric // Write the named metadata now.
247801095a5dSDimitry Andric writeNamedMetadata(Record);
2479829000e0SRoman Divacky
248001095a5dSDimitry Andric auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
248101095a5dSDimitry Andric SmallVector<uint64_t, 4> Record;
248201095a5dSDimitry Andric Record.push_back(VE.getValueID(&GO));
248301095a5dSDimitry Andric pushGlobalMetadataAttachment(Record, GO);
248401095a5dSDimitry Andric Stream.EmitRecord(bitc::METADATA_GLOBAL_DECL_ATTACHMENT, Record);
248501095a5dSDimitry Andric };
248601095a5dSDimitry Andric for (const Function &F : M)
248701095a5dSDimitry Andric if (F.isDeclaration() && F.hasMetadata())
248801095a5dSDimitry Andric AddDeclAttachedMetadata(F);
248901095a5dSDimitry Andric // FIXME: Only store metadata for declarations here, and move data for global
249001095a5dSDimitry Andric // variable definitions to a separate block (PR28134).
249101095a5dSDimitry Andric for (const GlobalVariable &GV : M.globals())
249201095a5dSDimitry Andric if (GV.hasMetadata())
249301095a5dSDimitry Andric AddDeclAttachedMetadata(GV);
249401095a5dSDimitry Andric
2495829000e0SRoman Divacky Stream.ExitBlock();
2496829000e0SRoman Divacky }
2497829000e0SRoman Divacky
writeFunctionMetadata(const Function & F)249801095a5dSDimitry Andric void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
249901095a5dSDimitry Andric if (!VE.hasMDs())
250001095a5dSDimitry Andric return;
2501b5efedafSRoman Divacky
250201095a5dSDimitry Andric Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
250359850d08SRoman Divacky SmallVector<uint64_t, 64> Record;
250401095a5dSDimitry Andric writeMetadataStrings(VE.getMDStrings(), Record);
250501095a5dSDimitry Andric writeMetadataRecords(VE.getNonMDStrings(), Record);
250601095a5dSDimitry Andric Stream.ExitBlock();
250701095a5dSDimitry Andric }
250859850d08SRoman Divacky
pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> & Record,const GlobalObject & GO)250901095a5dSDimitry Andric void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
251001095a5dSDimitry Andric SmallVectorImpl<uint64_t> &Record, const GlobalObject &GO) {
251101095a5dSDimitry Andric // [n x [id, mdnode]]
25121e7804dbSRoman Divacky SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
251301095a5dSDimitry Andric GO.getAllMetadata(MDs);
25145a5ac124SDimitry Andric for (const auto &I : MDs) {
25155a5ac124SDimitry Andric Record.push_back(I.first);
25165a5ac124SDimitry Andric Record.push_back(VE.getMetadataID(I.second));
25175a5ac124SDimitry Andric }
251801095a5dSDimitry Andric }
251901095a5dSDimitry Andric
writeFunctionMetadataAttachment(const Function & F)252001095a5dSDimitry Andric void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
252101095a5dSDimitry Andric Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
252201095a5dSDimitry Andric
252301095a5dSDimitry Andric SmallVector<uint64_t, 64> Record;
252401095a5dSDimitry Andric
252501095a5dSDimitry Andric if (F.hasMetadata()) {
252601095a5dSDimitry Andric pushGlobalMetadataAttachment(Record, F);
25275a5ac124SDimitry Andric Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
25285a5ac124SDimitry Andric Record.clear();
25295a5ac124SDimitry Andric }
25301e7804dbSRoman Divacky
253101095a5dSDimitry Andric // Write metadata attachments
253201095a5dSDimitry Andric // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
253301095a5dSDimitry Andric SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2534dd58ef01SDimitry Andric for (const BasicBlock &BB : F)
2535dd58ef01SDimitry Andric for (const Instruction &I : BB) {
25364a142eb2SRoman Divacky MDs.clear();
2537dd58ef01SDimitry Andric I.getAllMetadataOtherThanDebugLoc(MDs);
25381e7804dbSRoman Divacky
25391e7804dbSRoman Divacky // If no metadata, ignore instruction.
25401e7804dbSRoman Divacky if (MDs.empty()) continue;
25411e7804dbSRoman Divacky
2542dd58ef01SDimitry Andric Record.push_back(VE.getInstructionID(&I));
25431e7804dbSRoman Divacky
25441e7804dbSRoman Divacky for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
25451e7804dbSRoman Divacky Record.push_back(MDs[i].first);
254667c32a98SDimitry Andric Record.push_back(VE.getMetadataID(MDs[i].second));
254759850d08SRoman Divacky }
2548411bd29eSDimitry Andric Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
254959850d08SRoman Divacky Record.clear();
255059850d08SRoman Divacky }
255159850d08SRoman Divacky
255259850d08SRoman Divacky Stream.ExitBlock();
255359850d08SRoman Divacky }
255459850d08SRoman Divacky
writeModuleMetadataKinds()255501095a5dSDimitry Andric void ModuleBitcodeWriter::writeModuleMetadataKinds() {
255659850d08SRoman Divacky SmallVector<uint64_t, 64> Record;
255759850d08SRoman Divacky
255859850d08SRoman Divacky // Write metadata kinds
255959850d08SRoman Divacky // METADATA_KIND - [n x [id, name]]
25604a16efa3SDimitry Andric SmallVector<StringRef, 8> Names;
256101095a5dSDimitry Andric M.getMDKindNames(Names);
25621e7804dbSRoman Divacky
2563d39c594dSDimitry Andric if (Names.empty()) return;
25641e7804dbSRoman Divacky
2565dd58ef01SDimitry Andric Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3);
25661e7804dbSRoman Divacky
2567d39c594dSDimitry Andric for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
25681e7804dbSRoman Divacky Record.push_back(MDKindID);
25691e7804dbSRoman Divacky StringRef KName = Names[MDKindID];
25701e7804dbSRoman Divacky Record.append(KName.begin(), KName.end());
25711e7804dbSRoman Divacky
257259850d08SRoman Divacky Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
257359850d08SRoman Divacky Record.clear();
257459850d08SRoman Divacky }
257559850d08SRoman Divacky
257659850d08SRoman Divacky Stream.ExitBlock();
257759850d08SRoman Divacky }
2578009b1c42SEd Schouten
writeOperandBundleTags()257901095a5dSDimitry Andric void ModuleBitcodeWriter::writeOperandBundleTags() {
2580dd58ef01SDimitry Andric // Write metadata kinds
2581dd58ef01SDimitry Andric //
2582dd58ef01SDimitry Andric // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
2583dd58ef01SDimitry Andric //
2584dd58ef01SDimitry Andric // OPERAND_BUNDLE_TAG - [strchr x N]
2585dd58ef01SDimitry Andric
2586dd58ef01SDimitry Andric SmallVector<StringRef, 8> Tags;
258701095a5dSDimitry Andric M.getOperandBundleTags(Tags);
2588dd58ef01SDimitry Andric
2589dd58ef01SDimitry Andric if (Tags.empty())
2590dd58ef01SDimitry Andric return;
2591dd58ef01SDimitry Andric
2592dd58ef01SDimitry Andric Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3);
2593dd58ef01SDimitry Andric
2594dd58ef01SDimitry Andric SmallVector<uint64_t, 64> Record;
2595dd58ef01SDimitry Andric
2596dd58ef01SDimitry Andric for (auto Tag : Tags) {
2597dd58ef01SDimitry Andric Record.append(Tag.begin(), Tag.end());
2598dd58ef01SDimitry Andric
2599dd58ef01SDimitry Andric Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
2600dd58ef01SDimitry Andric Record.clear();
2601dd58ef01SDimitry Andric }
2602dd58ef01SDimitry Andric
2603dd58ef01SDimitry Andric Stream.ExitBlock();
2604dd58ef01SDimitry Andric }
2605dd58ef01SDimitry Andric
writeSyncScopeNames()2606ca089b24SDimitry Andric void ModuleBitcodeWriter::writeSyncScopeNames() {
2607ca089b24SDimitry Andric SmallVector<StringRef, 8> SSNs;
2608ca089b24SDimitry Andric M.getContext().getSyncScopeNames(SSNs);
2609ca089b24SDimitry Andric if (SSNs.empty())
2610ca089b24SDimitry Andric return;
2611ca089b24SDimitry Andric
2612ca089b24SDimitry Andric Stream.EnterSubblock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID, 2);
2613ca089b24SDimitry Andric
2614ca089b24SDimitry Andric SmallVector<uint64_t, 64> Record;
2615ca089b24SDimitry Andric for (auto SSN : SSNs) {
2616ca089b24SDimitry Andric Record.append(SSN.begin(), SSN.end());
2617ca089b24SDimitry Andric Stream.EmitRecord(bitc::SYNC_SCOPE_NAME, Record, 0);
2618ca089b24SDimitry Andric Record.clear();
2619ca089b24SDimitry Andric }
2620ca089b24SDimitry Andric
2621ca089b24SDimitry Andric Stream.ExitBlock();
2622ca089b24SDimitry Andric }
2623ca089b24SDimitry Andric
writeConstants(unsigned FirstVal,unsigned LastVal,bool isGlobal)262401095a5dSDimitry Andric void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
262501095a5dSDimitry Andric bool isGlobal) {
2626009b1c42SEd Schouten if (FirstVal == LastVal) return;
2627009b1c42SEd Schouten
2628009b1c42SEd Schouten Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
2629009b1c42SEd Schouten
2630009b1c42SEd Schouten unsigned AggregateAbbrev = 0;
2631009b1c42SEd Schouten unsigned String8Abbrev = 0;
2632009b1c42SEd Schouten unsigned CString7Abbrev = 0;
2633009b1c42SEd Schouten unsigned CString6Abbrev = 0;
2634009b1c42SEd Schouten // If this is a constant pool for the module, emit module-specific abbrevs.
2635009b1c42SEd Schouten if (isGlobal) {
2636009b1c42SEd Schouten // Abbrev for CST_CODE_AGGREGATE.
26377e7b6700SDimitry Andric auto Abbv = std::make_shared<BitCodeAbbrev>();
2638009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
2639009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2640009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
26417e7b6700SDimitry Andric AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2642009b1c42SEd Schouten
2643009b1c42SEd Schouten // Abbrev for CST_CODE_STRING.
26447e7b6700SDimitry Andric Abbv = std::make_shared<BitCodeAbbrev>();
2645009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
2646009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2647009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
26487e7b6700SDimitry Andric String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2649009b1c42SEd Schouten // Abbrev for CST_CODE_CSTRING.
26507e7b6700SDimitry Andric Abbv = std::make_shared<BitCodeAbbrev>();
2651009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2652009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2653009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
26547e7b6700SDimitry Andric CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2655009b1c42SEd Schouten // Abbrev for CST_CODE_CSTRING.
26567e7b6700SDimitry Andric Abbv = std::make_shared<BitCodeAbbrev>();
2657009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2658009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2659009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
26607e7b6700SDimitry Andric CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2661009b1c42SEd Schouten }
2662009b1c42SEd Schouten
2663009b1c42SEd Schouten SmallVector<uint64_t, 64> Record;
2664009b1c42SEd Schouten
2665009b1c42SEd Schouten const ValueEnumerator::ValueList &Vals = VE.getValues();
26665ca98fd9SDimitry Andric Type *LastTy = nullptr;
2667009b1c42SEd Schouten for (unsigned i = FirstVal; i != LastVal; ++i) {
2668009b1c42SEd Schouten const Value *V = Vals[i].first;
2669009b1c42SEd Schouten // If we need to switch types, do so now.
2670009b1c42SEd Schouten if (V->getType() != LastTy) {
2671009b1c42SEd Schouten LastTy = V->getType();
2672009b1c42SEd Schouten Record.push_back(VE.getTypeID(LastTy));
2673009b1c42SEd Schouten Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
2674009b1c42SEd Schouten CONSTANTS_SETTYPE_ABBREV);
2675009b1c42SEd Schouten Record.clear();
2676009b1c42SEd Schouten }
2677009b1c42SEd Schouten
2678009b1c42SEd Schouten if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
26796f8fc217SDimitry Andric Record.push_back(VE.getTypeID(IA->getFunctionType()));
2680344a3780SDimitry Andric Record.push_back(
2681344a3780SDimitry Andric unsigned(IA->hasSideEffects()) | unsigned(IA->isAlignStack()) << 1 |
2682344a3780SDimitry Andric unsigned(IA->getDialect() & 1) << 2 | unsigned(IA->canThrow()) << 3);
2683009b1c42SEd Schouten
2684009b1c42SEd Schouten // Add the asm string.
2685009b1c42SEd Schouten const std::string &AsmStr = IA->getAsmString();
2686009b1c42SEd Schouten Record.push_back(AsmStr.size());
26875a5ac124SDimitry Andric Record.append(AsmStr.begin(), AsmStr.end());
2688009b1c42SEd Schouten
2689009b1c42SEd Schouten // Add the constraint string.
2690009b1c42SEd Schouten const std::string &ConstraintStr = IA->getConstraintString();
2691009b1c42SEd Schouten Record.push_back(ConstraintStr.size());
26925a5ac124SDimitry Andric Record.append(ConstraintStr.begin(), ConstraintStr.end());
2693009b1c42SEd Schouten Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
2694009b1c42SEd Schouten Record.clear();
2695009b1c42SEd Schouten continue;
2696009b1c42SEd Schouten }
2697009b1c42SEd Schouten const Constant *C = cast<Constant>(V);
2698009b1c42SEd Schouten unsigned Code = -1U;
2699009b1c42SEd Schouten unsigned AbbrevToUse = 0;
2700009b1c42SEd Schouten if (C->isNullValue()) {
2701009b1c42SEd Schouten Code = bitc::CST_CODE_NULL;
2702b60736ecSDimitry Andric } else if (isa<PoisonValue>(C)) {
2703b60736ecSDimitry Andric Code = bitc::CST_CODE_POISON;
2704009b1c42SEd Schouten } else if (isa<UndefValue>(C)) {
2705009b1c42SEd Schouten Code = bitc::CST_CODE_UNDEF;
2706009b1c42SEd Schouten } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
2707f8af5cf6SDimitry Andric if (IV->getBitWidth() <= 64) {
2708f8af5cf6SDimitry Andric uint64_t V = IV->getSExtValue();
2709f8af5cf6SDimitry Andric emitSignedInt64(Record, V);
2710f8af5cf6SDimitry Andric Code = bitc::CST_CODE_INTEGER;
2711f8af5cf6SDimitry Andric AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
2712f8af5cf6SDimitry Andric } else { // Wide integers, > 64 bits in size.
2713cfca06d7SDimitry Andric emitWideAPInt(Record, IV->getValue());
2714f8af5cf6SDimitry Andric Code = bitc::CST_CODE_WIDE_INTEGER;
2715f8af5cf6SDimitry Andric }
2716009b1c42SEd Schouten } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
2717009b1c42SEd Schouten Code = bitc::CST_CODE_FLOAT;
2718ac9a064cSDimitry Andric Type *Ty = CFP->getType()->getScalarType();
2719cfca06d7SDimitry Andric if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() ||
2720cfca06d7SDimitry Andric Ty->isDoubleTy()) {
2721009b1c42SEd Schouten Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
272259850d08SRoman Divacky } else if (Ty->isX86_FP80Ty()) {
2723009b1c42SEd Schouten // api needed to prevent premature destruction
2724009b1c42SEd Schouten // bits are not in the same order as a normal i80 APInt, compensate.
2725009b1c42SEd Schouten APInt api = CFP->getValueAPF().bitcastToAPInt();
2726009b1c42SEd Schouten const uint64_t *p = api.getRawData();
2727009b1c42SEd Schouten Record.push_back((p[1] << 48) | (p[0] >> 16));
2728009b1c42SEd Schouten Record.push_back(p[0] & 0xffffLL);
272959850d08SRoman Divacky } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
2730009b1c42SEd Schouten APInt api = CFP->getValueAPF().bitcastToAPInt();
2731009b1c42SEd Schouten const uint64_t *p = api.getRawData();
2732009b1c42SEd Schouten Record.push_back(p[0]);
2733009b1c42SEd Schouten Record.push_back(p[1]);
2734009b1c42SEd Schouten } else {
2735009b1c42SEd Schouten assert(0 && "Unknown FP type!");
2736009b1c42SEd Schouten }
273763faed5bSDimitry Andric } else if (isa<ConstantDataSequential>(C) &&
273863faed5bSDimitry Andric cast<ConstantDataSequential>(C)->isString()) {
273963faed5bSDimitry Andric const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
2740009b1c42SEd Schouten // Emit constant strings specially.
274163faed5bSDimitry Andric unsigned NumElts = Str->getNumElements();
2742009b1c42SEd Schouten // If this is a null-terminated string, use the denser CSTRING encoding.
274363faed5bSDimitry Andric if (Str->isCString()) {
2744009b1c42SEd Schouten Code = bitc::CST_CODE_CSTRING;
274563faed5bSDimitry Andric --NumElts; // Don't encode the null, which isn't allowed by char6.
2746009b1c42SEd Schouten } else {
2747009b1c42SEd Schouten Code = bitc::CST_CODE_STRING;
2748009b1c42SEd Schouten AbbrevToUse = String8Abbrev;
2749009b1c42SEd Schouten }
2750009b1c42SEd Schouten bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
2751009b1c42SEd Schouten bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
275263faed5bSDimitry Andric for (unsigned i = 0; i != NumElts; ++i) {
275363faed5bSDimitry Andric unsigned char V = Str->getElementAsInteger(i);
2754009b1c42SEd Schouten Record.push_back(V);
2755009b1c42SEd Schouten isCStr7 &= (V & 128) == 0;
2756009b1c42SEd Schouten if (isCStrChar6)
2757009b1c42SEd Schouten isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
2758009b1c42SEd Schouten }
2759009b1c42SEd Schouten
2760009b1c42SEd Schouten if (isCStrChar6)
2761009b1c42SEd Schouten AbbrevToUse = CString6Abbrev;
2762009b1c42SEd Schouten else if (isCStr7)
2763009b1c42SEd Schouten AbbrevToUse = CString7Abbrev;
276463faed5bSDimitry Andric } else if (const ConstantDataSequential *CDS =
276563faed5bSDimitry Andric dyn_cast<ConstantDataSequential>(C)) {
276663faed5bSDimitry Andric Code = bitc::CST_CODE_DATA;
2767cfca06d7SDimitry Andric Type *EltTy = CDS->getElementType();
276863faed5bSDimitry Andric if (isa<IntegerType>(EltTy)) {
276963faed5bSDimitry Andric for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
277063faed5bSDimitry Andric Record.push_back(CDS->getElementAsInteger(i));
277163faed5bSDimitry Andric } else {
2772050e163aSDimitry Andric for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2773050e163aSDimitry Andric Record.push_back(
2774050e163aSDimitry Andric CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
277563faed5bSDimitry Andric }
277601095a5dSDimitry Andric } else if (isa<ConstantAggregate>(C)) {
2777009b1c42SEd Schouten Code = bitc::CST_CODE_AGGREGATE;
27781a82d4c0SDimitry Andric for (const Value *Op : C->operands())
27791a82d4c0SDimitry Andric Record.push_back(VE.getValueID(Op));
2780009b1c42SEd Schouten AbbrevToUse = AggregateAbbrev;
2781009b1c42SEd Schouten } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2782009b1c42SEd Schouten switch (CE->getOpcode()) {
2783009b1c42SEd Schouten default:
2784009b1c42SEd Schouten if (Instruction::isCast(CE->getOpcode())) {
2785009b1c42SEd Schouten Code = bitc::CST_CODE_CE_CAST;
278601095a5dSDimitry Andric Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
2787009b1c42SEd Schouten Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2788009b1c42SEd Schouten Record.push_back(VE.getValueID(C->getOperand(0)));
2789009b1c42SEd Schouten AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
2790009b1c42SEd Schouten } else {
2791009b1c42SEd Schouten assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
2792009b1c42SEd Schouten Code = bitc::CST_CODE_CE_BINOP;
279301095a5dSDimitry Andric Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
2794009b1c42SEd Schouten Record.push_back(VE.getValueID(C->getOperand(0)));
2795009b1c42SEd Schouten Record.push_back(VE.getValueID(C->getOperand(1)));
279601095a5dSDimitry Andric uint64_t Flags = getOptimizationFlags(CE);
279759850d08SRoman Divacky if (Flags != 0)
279859850d08SRoman Divacky Record.push_back(Flags);
2799009b1c42SEd Schouten }
2800009b1c42SEd Schouten break;
2801d8e91e46SDimitry Andric case Instruction::FNeg: {
2802d8e91e46SDimitry Andric assert(CE->getNumOperands() == 1 && "Unknown constant expr!");
2803d8e91e46SDimitry Andric Code = bitc::CST_CODE_CE_UNOP;
2804d8e91e46SDimitry Andric Record.push_back(getEncodedUnaryOpcode(CE->getOpcode()));
2805d8e91e46SDimitry Andric Record.push_back(VE.getValueID(C->getOperand(0)));
2806d8e91e46SDimitry Andric uint64_t Flags = getOptimizationFlags(CE);
2807d8e91e46SDimitry Andric if (Flags != 0)
2808d8e91e46SDimitry Andric Record.push_back(Flags);
2809d8e91e46SDimitry Andric break;
2810d8e91e46SDimitry Andric }
28115a5ac124SDimitry Andric case Instruction::GetElementPtr: {
2812009b1c42SEd Schouten Code = bitc::CST_CODE_CE_GEP;
28135a5ac124SDimitry Andric const auto *GO = cast<GEPOperator>(C);
28145a5ac124SDimitry Andric Record.push_back(VE.getTypeID(GO->getSourceElementType()));
2815ac9a064cSDimitry Andric Record.push_back(getOptimizationFlags(GO));
2816ac9a064cSDimitry Andric if (std::optional<ConstantRange> Range = GO->getInRange()) {
2817ac9a064cSDimitry Andric Code = bitc::CST_CODE_CE_GEP_WITH_INRANGE;
2818ac9a064cSDimitry Andric emitConstantRange(Record, *Range, /*EmitBitWidth=*/true);
2819ac9a064cSDimitry Andric }
2820009b1c42SEd Schouten for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
2821009b1c42SEd Schouten Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
2822009b1c42SEd Schouten Record.push_back(VE.getValueID(C->getOperand(i)));
2823009b1c42SEd Schouten }
2824009b1c42SEd Schouten break;
28255a5ac124SDimitry Andric }
2826009b1c42SEd Schouten case Instruction::ExtractElement:
2827009b1c42SEd Schouten Code = bitc::CST_CODE_CE_EXTRACTELT;
2828009b1c42SEd Schouten Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2829009b1c42SEd Schouten Record.push_back(VE.getValueID(C->getOperand(0)));
28305ca98fd9SDimitry Andric Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
2831009b1c42SEd Schouten Record.push_back(VE.getValueID(C->getOperand(1)));
2832009b1c42SEd Schouten break;
2833009b1c42SEd Schouten case Instruction::InsertElement:
2834009b1c42SEd Schouten Code = bitc::CST_CODE_CE_INSERTELT;
2835009b1c42SEd Schouten Record.push_back(VE.getValueID(C->getOperand(0)));
2836009b1c42SEd Schouten Record.push_back(VE.getValueID(C->getOperand(1)));
28375ca98fd9SDimitry Andric Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
2838009b1c42SEd Schouten Record.push_back(VE.getValueID(C->getOperand(2)));
2839009b1c42SEd Schouten break;
2840009b1c42SEd Schouten case Instruction::ShuffleVector:
2841009b1c42SEd Schouten // If the return type and argument types are the same, this is a
2842009b1c42SEd Schouten // standard shufflevector instruction. If the types are different,
2843009b1c42SEd Schouten // then the shuffle is widening or truncating the input vectors, and
2844009b1c42SEd Schouten // the argument type must also be encoded.
2845009b1c42SEd Schouten if (C->getType() == C->getOperand(0)->getType()) {
2846009b1c42SEd Schouten Code = bitc::CST_CODE_CE_SHUFFLEVEC;
2847009b1c42SEd Schouten } else {
2848009b1c42SEd Schouten Code = bitc::CST_CODE_CE_SHUFVEC_EX;
2849009b1c42SEd Schouten Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2850009b1c42SEd Schouten }
2851009b1c42SEd Schouten Record.push_back(VE.getValueID(C->getOperand(0)));
2852009b1c42SEd Schouten Record.push_back(VE.getValueID(C->getOperand(1)));
2853cfca06d7SDimitry Andric Record.push_back(VE.getValueID(CE->getShuffleMaskForBitcode()));
2854009b1c42SEd Schouten break;
2855009b1c42SEd Schouten }
285636bf506aSRoman Divacky } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
285736bf506aSRoman Divacky Code = bitc::CST_CODE_BLOCKADDRESS;
285836bf506aSRoman Divacky Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
285936bf506aSRoman Divacky Record.push_back(VE.getValueID(BA->getFunction()));
286036bf506aSRoman Divacky Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
2861344a3780SDimitry Andric } else if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) {
2862344a3780SDimitry Andric Code = bitc::CST_CODE_DSO_LOCAL_EQUIVALENT;
2863344a3780SDimitry Andric Record.push_back(VE.getTypeID(Equiv->getGlobalValue()->getType()));
2864344a3780SDimitry Andric Record.push_back(VE.getValueID(Equiv->getGlobalValue()));
286577fc4c14SDimitry Andric } else if (const auto *NC = dyn_cast<NoCFIValue>(C)) {
286677fc4c14SDimitry Andric Code = bitc::CST_CODE_NO_CFI_VALUE;
286777fc4c14SDimitry Andric Record.push_back(VE.getTypeID(NC->getGlobalValue()->getType()));
286877fc4c14SDimitry Andric Record.push_back(VE.getValueID(NC->getGlobalValue()));
2869ac9a064cSDimitry Andric } else if (const auto *CPA = dyn_cast<ConstantPtrAuth>(C)) {
2870ac9a064cSDimitry Andric Code = bitc::CST_CODE_PTRAUTH;
2871ac9a064cSDimitry Andric Record.push_back(VE.getValueID(CPA->getPointer()));
2872ac9a064cSDimitry Andric Record.push_back(VE.getValueID(CPA->getKey()));
2873ac9a064cSDimitry Andric Record.push_back(VE.getValueID(CPA->getDiscriminator()));
2874ac9a064cSDimitry Andric Record.push_back(VE.getValueID(CPA->getAddrDiscriminator()));
2875009b1c42SEd Schouten } else {
2876d39c594dSDimitry Andric #ifndef NDEBUG
2877d39c594dSDimitry Andric C->dump();
2878d39c594dSDimitry Andric #endif
287959850d08SRoman Divacky llvm_unreachable("Unknown constant!");
2880009b1c42SEd Schouten }
2881009b1c42SEd Schouten Stream.EmitRecord(Code, Record, AbbrevToUse);
2882009b1c42SEd Schouten Record.clear();
2883009b1c42SEd Schouten }
2884009b1c42SEd Schouten
2885009b1c42SEd Schouten Stream.ExitBlock();
2886009b1c42SEd Schouten }
2887009b1c42SEd Schouten
writeModuleConstants()288801095a5dSDimitry Andric void ModuleBitcodeWriter::writeModuleConstants() {
2889009b1c42SEd Schouten const ValueEnumerator::ValueList &Vals = VE.getValues();
2890009b1c42SEd Schouten
2891009b1c42SEd Schouten // Find the first constant to emit, which is the first non-globalvalue value.
2892009b1c42SEd Schouten // We know globalvalues have been emitted by WriteModuleInfo.
2893009b1c42SEd Schouten for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
2894009b1c42SEd Schouten if (!isa<GlobalValue>(Vals[i].first)) {
289501095a5dSDimitry Andric writeConstants(i, Vals.size(), true);
2896009b1c42SEd Schouten return;
2897009b1c42SEd Schouten }
2898009b1c42SEd Schouten }
2899009b1c42SEd Schouten }
2900009b1c42SEd Schouten
290101095a5dSDimitry Andric /// pushValueAndType - The file has to encode both the value and type id for
2902009b1c42SEd Schouten /// many values, because we need to know what type to create for forward
2903009b1c42SEd Schouten /// references. However, most operands are not forward references, so this type
2904009b1c42SEd Schouten /// field is not needed.
2905009b1c42SEd Schouten ///
2906009b1c42SEd Schouten /// This function adds V's value ID to Vals. If the value ID is higher than the
2907009b1c42SEd Schouten /// instruction ID, then it is a forward reference, and it also includes the
2908522600a2SDimitry Andric /// type ID. The value ID that is written is encoded relative to the InstID.
pushValueAndType(const Value * V,unsigned InstID,SmallVectorImpl<unsigned> & Vals)290901095a5dSDimitry Andric bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
291001095a5dSDimitry Andric SmallVectorImpl<unsigned> &Vals) {
2911009b1c42SEd Schouten unsigned ValID = VE.getValueID(V);
2912522600a2SDimitry Andric // Make encoding relative to the InstID.
2913522600a2SDimitry Andric Vals.push_back(InstID - ValID);
2914009b1c42SEd Schouten if (ValID >= InstID) {
2915009b1c42SEd Schouten Vals.push_back(VE.getTypeID(V->getType()));
2916009b1c42SEd Schouten return true;
2917009b1c42SEd Schouten }
2918009b1c42SEd Schouten return false;
2919009b1c42SEd Schouten }
2920009b1c42SEd Schouten
writeOperandBundles(const CallBase & CS,unsigned InstID)2921cfca06d7SDimitry Andric void ModuleBitcodeWriter::writeOperandBundles(const CallBase &CS,
292201095a5dSDimitry Andric unsigned InstID) {
2923dd58ef01SDimitry Andric SmallVector<unsigned, 64> Record;
2924cfca06d7SDimitry Andric LLVMContext &C = CS.getContext();
2925dd58ef01SDimitry Andric
2926dd58ef01SDimitry Andric for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
2927dd58ef01SDimitry Andric const auto &Bundle = CS.getOperandBundleAt(i);
2928dd58ef01SDimitry Andric Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
2929dd58ef01SDimitry Andric
2930dd58ef01SDimitry Andric for (auto &Input : Bundle.Inputs)
293101095a5dSDimitry Andric pushValueAndType(Input, InstID, Record);
2932dd58ef01SDimitry Andric
2933dd58ef01SDimitry Andric Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record);
2934dd58ef01SDimitry Andric Record.clear();
2935dd58ef01SDimitry Andric }
2936dd58ef01SDimitry Andric }
2937dd58ef01SDimitry Andric
293801095a5dSDimitry Andric /// pushValue - Like pushValueAndType, but where the type of the value is
2939522600a2SDimitry Andric /// omitted (perhaps it was already encoded in an earlier operand).
pushValue(const Value * V,unsigned InstID,SmallVectorImpl<unsigned> & Vals)294001095a5dSDimitry Andric void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
294101095a5dSDimitry Andric SmallVectorImpl<unsigned> &Vals) {
2942522600a2SDimitry Andric unsigned ValID = VE.getValueID(V);
2943522600a2SDimitry Andric Vals.push_back(InstID - ValID);
2944522600a2SDimitry Andric }
2945522600a2SDimitry Andric
pushValueSigned(const Value * V,unsigned InstID,SmallVectorImpl<uint64_t> & Vals)294601095a5dSDimitry Andric void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
294701095a5dSDimitry Andric SmallVectorImpl<uint64_t> &Vals) {
2948522600a2SDimitry Andric unsigned ValID = VE.getValueID(V);
2949522600a2SDimitry Andric int64_t diff = ((int32_t)InstID - (int32_t)ValID);
2950522600a2SDimitry Andric emitSignedInt64(Vals, diff);
2951522600a2SDimitry Andric }
2952522600a2SDimitry Andric
2953009b1c42SEd Schouten /// WriteInstruction - Emit an instruction to the specified stream.
writeInstruction(const Instruction & I,unsigned InstID,SmallVectorImpl<unsigned> & Vals)295401095a5dSDimitry Andric void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
295501095a5dSDimitry Andric unsigned InstID,
2956f8af5cf6SDimitry Andric SmallVectorImpl<unsigned> &Vals) {
2957009b1c42SEd Schouten unsigned Code = 0;
2958009b1c42SEd Schouten unsigned AbbrevToUse = 0;
295959850d08SRoman Divacky VE.setInstructionID(&I);
2960009b1c42SEd Schouten switch (I.getOpcode()) {
2961009b1c42SEd Schouten default:
2962009b1c42SEd Schouten if (Instruction::isCast(I.getOpcode())) {
2963009b1c42SEd Schouten Code = bitc::FUNC_CODE_INST_CAST;
296401095a5dSDimitry Andric if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2965009b1c42SEd Schouten AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
2966009b1c42SEd Schouten Vals.push_back(VE.getTypeID(I.getType()));
296701095a5dSDimitry Andric Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
2968b1c73532SDimitry Andric uint64_t Flags = getOptimizationFlags(&I);
2969b1c73532SDimitry Andric if (Flags != 0) {
2970b1c73532SDimitry Andric if (AbbrevToUse == FUNCTION_INST_CAST_ABBREV)
2971b1c73532SDimitry Andric AbbrevToUse = FUNCTION_INST_CAST_FLAGS_ABBREV;
2972b1c73532SDimitry Andric Vals.push_back(Flags);
2973b1c73532SDimitry Andric }
2974009b1c42SEd Schouten } else {
2975009b1c42SEd Schouten assert(isa<BinaryOperator>(I) && "Unknown instruction!");
2976009b1c42SEd Schouten Code = bitc::FUNC_CODE_INST_BINOP;
297701095a5dSDimitry Andric if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2978009b1c42SEd Schouten AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
297901095a5dSDimitry Andric pushValue(I.getOperand(1), InstID, Vals);
298001095a5dSDimitry Andric Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
298101095a5dSDimitry Andric uint64_t Flags = getOptimizationFlags(&I);
298259850d08SRoman Divacky if (Flags != 0) {
298359850d08SRoman Divacky if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
298459850d08SRoman Divacky AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
298559850d08SRoman Divacky Vals.push_back(Flags);
298659850d08SRoman Divacky }
2987009b1c42SEd Schouten }
2988009b1c42SEd Schouten break;
2989d8e91e46SDimitry Andric case Instruction::FNeg: {
2990d8e91e46SDimitry Andric Code = bitc::FUNC_CODE_INST_UNOP;
2991d8e91e46SDimitry Andric if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2992d8e91e46SDimitry Andric AbbrevToUse = FUNCTION_INST_UNOP_ABBREV;
2993d8e91e46SDimitry Andric Vals.push_back(getEncodedUnaryOpcode(I.getOpcode()));
2994d8e91e46SDimitry Andric uint64_t Flags = getOptimizationFlags(&I);
2995d8e91e46SDimitry Andric if (Flags != 0) {
2996d8e91e46SDimitry Andric if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV)
2997d8e91e46SDimitry Andric AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV;
2998d8e91e46SDimitry Andric Vals.push_back(Flags);
2999d8e91e46SDimitry Andric }
3000d8e91e46SDimitry Andric break;
3001d8e91e46SDimitry Andric }
30025a5ac124SDimitry Andric case Instruction::GetElementPtr: {
3003009b1c42SEd Schouten Code = bitc::FUNC_CODE_INST_GEP;
30045a5ac124SDimitry Andric AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
30055a5ac124SDimitry Andric auto &GEPInst = cast<GetElementPtrInst>(I);
3006ac9a064cSDimitry Andric Vals.push_back(getOptimizationFlags(&I));
30075a5ac124SDimitry Andric Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
3008009b1c42SEd Schouten for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
300901095a5dSDimitry Andric pushValueAndType(I.getOperand(i), InstID, Vals);
3010009b1c42SEd Schouten break;
30115a5ac124SDimitry Andric }
3012009b1c42SEd Schouten case Instruction::ExtractValue: {
3013009b1c42SEd Schouten Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
301401095a5dSDimitry Andric pushValueAndType(I.getOperand(0), InstID, Vals);
3015009b1c42SEd Schouten const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
30165a5ac124SDimitry Andric Vals.append(EVI->idx_begin(), EVI->idx_end());
3017009b1c42SEd Schouten break;
3018009b1c42SEd Schouten }
3019009b1c42SEd Schouten case Instruction::InsertValue: {
3020009b1c42SEd Schouten Code = bitc::FUNC_CODE_INST_INSERTVAL;
302101095a5dSDimitry Andric pushValueAndType(I.getOperand(0), InstID, Vals);
302201095a5dSDimitry Andric pushValueAndType(I.getOperand(1), InstID, Vals);
3023009b1c42SEd Schouten const InsertValueInst *IVI = cast<InsertValueInst>(&I);
30245a5ac124SDimitry Andric Vals.append(IVI->idx_begin(), IVI->idx_end());
3025009b1c42SEd Schouten break;
3026009b1c42SEd Schouten }
3027e6d15924SDimitry Andric case Instruction::Select: {
3028009b1c42SEd Schouten Code = bitc::FUNC_CODE_INST_VSELECT;
302901095a5dSDimitry Andric pushValueAndType(I.getOperand(1), InstID, Vals);
303001095a5dSDimitry Andric pushValue(I.getOperand(2), InstID, Vals);
303101095a5dSDimitry Andric pushValueAndType(I.getOperand(0), InstID, Vals);
3032e6d15924SDimitry Andric uint64_t Flags = getOptimizationFlags(&I);
3033e6d15924SDimitry Andric if (Flags != 0)
3034e6d15924SDimitry Andric Vals.push_back(Flags);
3035009b1c42SEd Schouten break;
3036e6d15924SDimitry Andric }
3037009b1c42SEd Schouten case Instruction::ExtractElement:
3038009b1c42SEd Schouten Code = bitc::FUNC_CODE_INST_EXTRACTELT;
303901095a5dSDimitry Andric pushValueAndType(I.getOperand(0), InstID, Vals);
304001095a5dSDimitry Andric pushValueAndType(I.getOperand(1), InstID, Vals);
3041009b1c42SEd Schouten break;
3042009b1c42SEd Schouten case Instruction::InsertElement:
3043009b1c42SEd Schouten Code = bitc::FUNC_CODE_INST_INSERTELT;
304401095a5dSDimitry Andric pushValueAndType(I.getOperand(0), InstID, Vals);
304501095a5dSDimitry Andric pushValue(I.getOperand(1), InstID, Vals);
304601095a5dSDimitry Andric pushValueAndType(I.getOperand(2), InstID, Vals);
3047009b1c42SEd Schouten break;
3048009b1c42SEd Schouten case Instruction::ShuffleVector:
3049009b1c42SEd Schouten Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
305001095a5dSDimitry Andric pushValueAndType(I.getOperand(0), InstID, Vals);
305101095a5dSDimitry Andric pushValue(I.getOperand(1), InstID, Vals);
3052cfca06d7SDimitry Andric pushValue(cast<ShuffleVectorInst>(I).getShuffleMaskForBitcode(), InstID,
3053cfca06d7SDimitry Andric Vals);
3054009b1c42SEd Schouten break;
3055009b1c42SEd Schouten case Instruction::ICmp:
3056ee8648bdSDimitry Andric case Instruction::FCmp: {
3057009b1c42SEd Schouten // compare returning Int1Ty or vector of Int1Ty
3058009b1c42SEd Schouten Code = bitc::FUNC_CODE_INST_CMP2;
305901095a5dSDimitry Andric pushValueAndType(I.getOperand(0), InstID, Vals);
306001095a5dSDimitry Andric pushValue(I.getOperand(1), InstID, Vals);
3061009b1c42SEd Schouten Vals.push_back(cast<CmpInst>(I).getPredicate());
306201095a5dSDimitry Andric uint64_t Flags = getOptimizationFlags(&I);
3063ee8648bdSDimitry Andric if (Flags != 0)
3064ee8648bdSDimitry Andric Vals.push_back(Flags);
3065009b1c42SEd Schouten break;
3066ee8648bdSDimitry Andric }
3067009b1c42SEd Schouten
3068009b1c42SEd Schouten case Instruction::Ret:
3069009b1c42SEd Schouten {
3070009b1c42SEd Schouten Code = bitc::FUNC_CODE_INST_RET;
3071009b1c42SEd Schouten unsigned NumOperands = I.getNumOperands();
3072009b1c42SEd Schouten if (NumOperands == 0)
3073009b1c42SEd Schouten AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
3074009b1c42SEd Schouten else if (NumOperands == 1) {
307501095a5dSDimitry Andric if (!pushValueAndType(I.getOperand(0), InstID, Vals))
3076009b1c42SEd Schouten AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
3077009b1c42SEd Schouten } else {
3078009b1c42SEd Schouten for (unsigned i = 0, e = NumOperands; i != e; ++i)
307901095a5dSDimitry Andric pushValueAndType(I.getOperand(i), InstID, Vals);
3080009b1c42SEd Schouten }
3081009b1c42SEd Schouten }
3082009b1c42SEd Schouten break;
3083009b1c42SEd Schouten case Instruction::Br:
3084009b1c42SEd Schouten {
3085009b1c42SEd Schouten Code = bitc::FUNC_CODE_INST_BR;
30864a16efa3SDimitry Andric const BranchInst &II = cast<BranchInst>(I);
3087009b1c42SEd Schouten Vals.push_back(VE.getValueID(II.getSuccessor(0)));
3088009b1c42SEd Schouten if (II.isConditional()) {
3089009b1c42SEd Schouten Vals.push_back(VE.getValueID(II.getSuccessor(1)));
309001095a5dSDimitry Andric pushValue(II.getCondition(), InstID, Vals);
3091009b1c42SEd Schouten }
3092009b1c42SEd Schouten }
3093009b1c42SEd Schouten break;
3094009b1c42SEd Schouten case Instruction::Switch:
309563faed5bSDimitry Andric {
3096009b1c42SEd Schouten Code = bitc::FUNC_CODE_INST_SWITCH;
30974a16efa3SDimitry Andric const SwitchInst &SI = cast<SwitchInst>(I);
3098f8af5cf6SDimitry Andric Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
309901095a5dSDimitry Andric pushValue(SI.getCondition(), InstID, Vals);
3100f8af5cf6SDimitry Andric Vals.push_back(VE.getValueID(SI.getDefaultDest()));
310171d5a254SDimitry Andric for (auto Case : SI.cases()) {
3102dd58ef01SDimitry Andric Vals.push_back(VE.getValueID(Case.getCaseValue()));
3103dd58ef01SDimitry Andric Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
310463faed5bSDimitry Andric }
310563faed5bSDimitry Andric }
3106009b1c42SEd Schouten break;
310736bf506aSRoman Divacky case Instruction::IndirectBr:
310836bf506aSRoman Divacky Code = bitc::FUNC_CODE_INST_INDIRECTBR;
310936bf506aSRoman Divacky Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
3110522600a2SDimitry Andric // Encode the address operand as relative, but not the basic blocks.
311101095a5dSDimitry Andric pushValue(I.getOperand(0), InstID, Vals);
3112522600a2SDimitry Andric for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
311336bf506aSRoman Divacky Vals.push_back(VE.getValueID(I.getOperand(i)));
311436bf506aSRoman Divacky break;
311536bf506aSRoman Divacky
3116009b1c42SEd Schouten case Instruction::Invoke: {
3117009b1c42SEd Schouten const InvokeInst *II = cast<InvokeInst>(&I);
3118cfca06d7SDimitry Andric const Value *Callee = II->getCalledOperand();
31195a5ac124SDimitry Andric FunctionType *FTy = II->getFunctionType();
3120dd58ef01SDimitry Andric
3121dd58ef01SDimitry Andric if (II->hasOperandBundles())
3122cfca06d7SDimitry Andric writeOperandBundles(*II, InstID);
3123dd58ef01SDimitry Andric
3124009b1c42SEd Schouten Code = bitc::FUNC_CODE_INST_INVOKE;
3125009b1c42SEd Schouten
312612f3ca4cSDimitry Andric Vals.push_back(VE.getAttributeListID(II->getAttributes()));
31275a5ac124SDimitry Andric Vals.push_back(II->getCallingConv() | 1 << 13);
3128009b1c42SEd Schouten Vals.push_back(VE.getValueID(II->getNormalDest()));
3129009b1c42SEd Schouten Vals.push_back(VE.getValueID(II->getUnwindDest()));
31305a5ac124SDimitry Andric Vals.push_back(VE.getTypeID(FTy));
313101095a5dSDimitry Andric pushValueAndType(Callee, InstID, Vals);
3132009b1c42SEd Schouten
3133009b1c42SEd Schouten // Emit value #'s for the fixed parameters.
3134009b1c42SEd Schouten for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
313501095a5dSDimitry Andric pushValue(I.getOperand(i), InstID, Vals); // fixed param.
3136009b1c42SEd Schouten
3137009b1c42SEd Schouten // Emit type/value pairs for varargs params.
3138009b1c42SEd Schouten if (FTy->isVarArg()) {
3139c0981da4SDimitry Andric for (unsigned i = FTy->getNumParams(), e = II->arg_size(); i != e; ++i)
314001095a5dSDimitry Andric pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
3141009b1c42SEd Schouten }
3142009b1c42SEd Schouten break;
3143009b1c42SEd Schouten }
314430815c53SDimitry Andric case Instruction::Resume:
314530815c53SDimitry Andric Code = bitc::FUNC_CODE_INST_RESUME;
314601095a5dSDimitry Andric pushValueAndType(I.getOperand(0), InstID, Vals);
314730815c53SDimitry Andric break;
3148dd58ef01SDimitry Andric case Instruction::CleanupRet: {
3149dd58ef01SDimitry Andric Code = bitc::FUNC_CODE_INST_CLEANUPRET;
3150dd58ef01SDimitry Andric const auto &CRI = cast<CleanupReturnInst>(I);
315101095a5dSDimitry Andric pushValue(CRI.getCleanupPad(), InstID, Vals);
3152dd58ef01SDimitry Andric if (CRI.hasUnwindDest())
3153dd58ef01SDimitry Andric Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
3154dd58ef01SDimitry Andric break;
3155dd58ef01SDimitry Andric }
3156dd58ef01SDimitry Andric case Instruction::CatchRet: {
3157dd58ef01SDimitry Andric Code = bitc::FUNC_CODE_INST_CATCHRET;
3158dd58ef01SDimitry Andric const auto &CRI = cast<CatchReturnInst>(I);
315901095a5dSDimitry Andric pushValue(CRI.getCatchPad(), InstID, Vals);
3160dd58ef01SDimitry Andric Vals.push_back(VE.getValueID(CRI.getSuccessor()));
3161dd58ef01SDimitry Andric break;
3162dd58ef01SDimitry Andric }
3163dd58ef01SDimitry Andric case Instruction::CleanupPad:
3164dd58ef01SDimitry Andric case Instruction::CatchPad: {
3165dd58ef01SDimitry Andric const auto &FuncletPad = cast<FuncletPadInst>(I);
3166dd58ef01SDimitry Andric Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
3167dd58ef01SDimitry Andric : bitc::FUNC_CODE_INST_CLEANUPPAD;
316801095a5dSDimitry Andric pushValue(FuncletPad.getParentPad(), InstID, Vals);
3169dd58ef01SDimitry Andric
3170e3b55780SDimitry Andric unsigned NumArgOperands = FuncletPad.arg_size();
3171dd58ef01SDimitry Andric Vals.push_back(NumArgOperands);
3172dd58ef01SDimitry Andric for (unsigned Op = 0; Op != NumArgOperands; ++Op)
317301095a5dSDimitry Andric pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
3174dd58ef01SDimitry Andric break;
3175dd58ef01SDimitry Andric }
3176dd58ef01SDimitry Andric case Instruction::CatchSwitch: {
3177dd58ef01SDimitry Andric Code = bitc::FUNC_CODE_INST_CATCHSWITCH;
3178dd58ef01SDimitry Andric const auto &CatchSwitch = cast<CatchSwitchInst>(I);
3179dd58ef01SDimitry Andric
318001095a5dSDimitry Andric pushValue(CatchSwitch.getParentPad(), InstID, Vals);
3181dd58ef01SDimitry Andric
3182dd58ef01SDimitry Andric unsigned NumHandlers = CatchSwitch.getNumHandlers();
3183dd58ef01SDimitry Andric Vals.push_back(NumHandlers);
3184dd58ef01SDimitry Andric for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
3185dd58ef01SDimitry Andric Vals.push_back(VE.getValueID(CatchPadBB));
3186dd58ef01SDimitry Andric
3187dd58ef01SDimitry Andric if (CatchSwitch.hasUnwindDest())
3188dd58ef01SDimitry Andric Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
3189dd58ef01SDimitry Andric break;
3190dd58ef01SDimitry Andric }
3191e6d15924SDimitry Andric case Instruction::CallBr: {
3192e6d15924SDimitry Andric const CallBrInst *CBI = cast<CallBrInst>(&I);
3193cfca06d7SDimitry Andric const Value *Callee = CBI->getCalledOperand();
3194e6d15924SDimitry Andric FunctionType *FTy = CBI->getFunctionType();
3195e6d15924SDimitry Andric
3196e6d15924SDimitry Andric if (CBI->hasOperandBundles())
3197cfca06d7SDimitry Andric writeOperandBundles(*CBI, InstID);
3198e6d15924SDimitry Andric
3199e6d15924SDimitry Andric Code = bitc::FUNC_CODE_INST_CALLBR;
3200e6d15924SDimitry Andric
3201e6d15924SDimitry Andric Vals.push_back(VE.getAttributeListID(CBI->getAttributes()));
3202e6d15924SDimitry Andric
3203e6d15924SDimitry Andric Vals.push_back(CBI->getCallingConv() << bitc::CALL_CCONV |
3204e6d15924SDimitry Andric 1 << bitc::CALL_EXPLICIT_TYPE);
3205e6d15924SDimitry Andric
3206e6d15924SDimitry Andric Vals.push_back(VE.getValueID(CBI->getDefaultDest()));
3207e6d15924SDimitry Andric Vals.push_back(CBI->getNumIndirectDests());
3208e6d15924SDimitry Andric for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i)
3209e6d15924SDimitry Andric Vals.push_back(VE.getValueID(CBI->getIndirectDest(i)));
3210e6d15924SDimitry Andric
3211e6d15924SDimitry Andric Vals.push_back(VE.getTypeID(FTy));
3212e6d15924SDimitry Andric pushValueAndType(Callee, InstID, Vals);
3213e6d15924SDimitry Andric
3214e6d15924SDimitry Andric // Emit value #'s for the fixed parameters.
3215e6d15924SDimitry Andric for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3216e6d15924SDimitry Andric pushValue(I.getOperand(i), InstID, Vals); // fixed param.
3217e6d15924SDimitry Andric
3218e6d15924SDimitry Andric // Emit type/value pairs for varargs params.
3219e6d15924SDimitry Andric if (FTy->isVarArg()) {
3220c0981da4SDimitry Andric for (unsigned i = FTy->getNumParams(), e = CBI->arg_size(); i != e; ++i)
3221e6d15924SDimitry Andric pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
3222e6d15924SDimitry Andric }
3223e6d15924SDimitry Andric break;
3224e6d15924SDimitry Andric }
3225009b1c42SEd Schouten case Instruction::Unreachable:
3226009b1c42SEd Schouten Code = bitc::FUNC_CODE_INST_UNREACHABLE;
3227009b1c42SEd Schouten AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
3228009b1c42SEd Schouten break;
3229009b1c42SEd Schouten
3230411bd29eSDimitry Andric case Instruction::PHI: {
3231411bd29eSDimitry Andric const PHINode &PN = cast<PHINode>(I);
3232009b1c42SEd Schouten Code = bitc::FUNC_CODE_INST_PHI;
3233522600a2SDimitry Andric // With the newer instruction encoding, forward references could give
3234522600a2SDimitry Andric // negative valued IDs. This is most common for PHIs, so we use
3235522600a2SDimitry Andric // signed VBRs.
3236522600a2SDimitry Andric SmallVector<uint64_t, 128> Vals64;
3237522600a2SDimitry Andric Vals64.push_back(VE.getTypeID(PN.getType()));
3238411bd29eSDimitry Andric for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
323901095a5dSDimitry Andric pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
3240522600a2SDimitry Andric Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
3241411bd29eSDimitry Andric }
32421d5ae102SDimitry Andric
32431d5ae102SDimitry Andric uint64_t Flags = getOptimizationFlags(&I);
32441d5ae102SDimitry Andric if (Flags != 0)
32451d5ae102SDimitry Andric Vals64.push_back(Flags);
32461d5ae102SDimitry Andric
3247522600a2SDimitry Andric // Emit a Vals64 vector and exit.
3248522600a2SDimitry Andric Stream.EmitRecord(Code, Vals64, AbbrevToUse);
3249522600a2SDimitry Andric Vals64.clear();
3250522600a2SDimitry Andric return;
3251411bd29eSDimitry Andric }
3252009b1c42SEd Schouten
325330815c53SDimitry Andric case Instruction::LandingPad: {
325430815c53SDimitry Andric const LandingPadInst &LP = cast<LandingPadInst>(I);
325530815c53SDimitry Andric Code = bitc::FUNC_CODE_INST_LANDINGPAD;
325630815c53SDimitry Andric Vals.push_back(VE.getTypeID(LP.getType()));
325730815c53SDimitry Andric Vals.push_back(LP.isCleanup());
325830815c53SDimitry Andric Vals.push_back(LP.getNumClauses());
325930815c53SDimitry Andric for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
326030815c53SDimitry Andric if (LP.isCatch(I))
326130815c53SDimitry Andric Vals.push_back(LandingPadInst::Catch);
326230815c53SDimitry Andric else
326330815c53SDimitry Andric Vals.push_back(LandingPadInst::Filter);
326401095a5dSDimitry Andric pushValueAndType(LP.getClause(I), InstID, Vals);
326530815c53SDimitry Andric }
326630815c53SDimitry Andric break;
326730815c53SDimitry Andric }
326830815c53SDimitry Andric
32695ca98fd9SDimitry Andric case Instruction::Alloca: {
3270009b1c42SEd Schouten Code = bitc::FUNC_CODE_INST_ALLOCA;
32715a5ac124SDimitry Andric const AllocaInst &AI = cast<AllocaInst>(I);
32725a5ac124SDimitry Andric Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
327366e41e3cSRoman Divacky Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
3274009b1c42SEd Schouten Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
3275b60736ecSDimitry Andric using APV = AllocaPackedValues;
3276b60736ecSDimitry Andric unsigned Record = 0;
3277c0981da4SDimitry Andric unsigned EncodedAlign = getEncodedAlign(AI.getAlign());
3278c0981da4SDimitry Andric Bitfield::set<APV::AlignLower>(
3279c0981da4SDimitry Andric Record, EncodedAlign & ((1 << APV::AlignLower::Bits) - 1));
3280c0981da4SDimitry Andric Bitfield::set<APV::AlignUpper>(Record,
3281c0981da4SDimitry Andric EncodedAlign >> APV::AlignLower::Bits);
3282b60736ecSDimitry Andric Bitfield::set<APV::UsedWithInAlloca>(Record, AI.isUsedWithInAlloca());
3283b60736ecSDimitry Andric Bitfield::set<APV::ExplicitType>(Record, true);
3284b60736ecSDimitry Andric Bitfield::set<APV::SwiftError>(Record, AI.isSwiftError());
3285b60736ecSDimitry Andric Vals.push_back(Record);
3286145449b1SDimitry Andric
3287145449b1SDimitry Andric unsigned AS = AI.getAddressSpace();
3288145449b1SDimitry Andric if (AS != M.getDataLayout().getAllocaAddrSpace())
3289145449b1SDimitry Andric Vals.push_back(AS);
3290009b1c42SEd Schouten break;
32915ca98fd9SDimitry Andric }
3292009b1c42SEd Schouten
3293009b1c42SEd Schouten case Instruction::Load:
329430815c53SDimitry Andric if (cast<LoadInst>(I).isAtomic()) {
329530815c53SDimitry Andric Code = bitc::FUNC_CODE_INST_LOADATOMIC;
329601095a5dSDimitry Andric pushValueAndType(I.getOperand(0), InstID, Vals);
329730815c53SDimitry Andric } else {
3298009b1c42SEd Schouten Code = bitc::FUNC_CODE_INST_LOAD;
329901095a5dSDimitry Andric if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
3300009b1c42SEd Schouten AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
330130815c53SDimitry Andric }
33025a5ac124SDimitry Andric Vals.push_back(VE.getTypeID(I.getType()));
3303b60736ecSDimitry Andric Vals.push_back(getEncodedAlign(cast<LoadInst>(I).getAlign()));
3304009b1c42SEd Schouten Vals.push_back(cast<LoadInst>(I).isVolatile());
330530815c53SDimitry Andric if (cast<LoadInst>(I).isAtomic()) {
330601095a5dSDimitry Andric Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
3307ca089b24SDimitry Andric Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID()));
330830815c53SDimitry Andric }
3309009b1c42SEd Schouten break;
3310009b1c42SEd Schouten case Instruction::Store:
331130815c53SDimitry Andric if (cast<StoreInst>(I).isAtomic())
331230815c53SDimitry Andric Code = bitc::FUNC_CODE_INST_STOREATOMIC;
331330815c53SDimitry Andric else
3314411bd29eSDimitry Andric Code = bitc::FUNC_CODE_INST_STORE;
331501095a5dSDimitry Andric pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr
331601095a5dSDimitry Andric pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val
3317b60736ecSDimitry Andric Vals.push_back(getEncodedAlign(cast<StoreInst>(I).getAlign()));
3318009b1c42SEd Schouten Vals.push_back(cast<StoreInst>(I).isVolatile());
331930815c53SDimitry Andric if (cast<StoreInst>(I).isAtomic()) {
332001095a5dSDimitry Andric Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
3321ca089b24SDimitry Andric Vals.push_back(
3322ca089b24SDimitry Andric getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID()));
332330815c53SDimitry Andric }
332430815c53SDimitry Andric break;
332530815c53SDimitry Andric case Instruction::AtomicCmpXchg:
332630815c53SDimitry Andric Code = bitc::FUNC_CODE_INST_CMPXCHG;
332701095a5dSDimitry Andric pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
332801095a5dSDimitry Andric pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
332901095a5dSDimitry Andric pushValue(I.getOperand(2), InstID, Vals); // newval.
333030815c53SDimitry Andric Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
333101095a5dSDimitry Andric Vals.push_back(
333201095a5dSDimitry Andric getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
333301095a5dSDimitry Andric Vals.push_back(
3334ca089b24SDimitry Andric getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID()));
333501095a5dSDimitry Andric Vals.push_back(
333601095a5dSDimitry Andric getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
33375ca98fd9SDimitry Andric Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
3338344a3780SDimitry Andric Vals.push_back(getEncodedAlign(cast<AtomicCmpXchgInst>(I).getAlign()));
333930815c53SDimitry Andric break;
334030815c53SDimitry Andric case Instruction::AtomicRMW:
334130815c53SDimitry Andric Code = bitc::FUNC_CODE_INST_ATOMICRMW;
334201095a5dSDimitry Andric pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
3343344a3780SDimitry Andric pushValueAndType(I.getOperand(1), InstID, Vals); // valty + val
334401095a5dSDimitry Andric Vals.push_back(
334501095a5dSDimitry Andric getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
334630815c53SDimitry Andric Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
334701095a5dSDimitry Andric Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
334801095a5dSDimitry Andric Vals.push_back(
3349ca089b24SDimitry Andric getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID()));
3350344a3780SDimitry Andric Vals.push_back(getEncodedAlign(cast<AtomicRMWInst>(I).getAlign()));
335130815c53SDimitry Andric break;
335230815c53SDimitry Andric case Instruction::Fence:
335330815c53SDimitry Andric Code = bitc::FUNC_CODE_INST_FENCE;
335401095a5dSDimitry Andric Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
3355ca089b24SDimitry Andric Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID()));
3356009b1c42SEd Schouten break;
3357009b1c42SEd Schouten case Instruction::Call: {
335866e41e3cSRoman Divacky const CallInst &CI = cast<CallInst>(I);
33595a5ac124SDimitry Andric FunctionType *FTy = CI.getFunctionType();
3360009b1c42SEd Schouten
3361dd58ef01SDimitry Andric if (CI.hasOperandBundles())
3362cfca06d7SDimitry Andric writeOperandBundles(CI, InstID);
3363dd58ef01SDimitry Andric
3364411bd29eSDimitry Andric Code = bitc::FUNC_CODE_INST_CALL;
3365009b1c42SEd Schouten
336612f3ca4cSDimitry Andric Vals.push_back(VE.getAttributeListID(CI.getAttributes()));
3367dd58ef01SDimitry Andric
336801095a5dSDimitry Andric unsigned Flags = getOptimizationFlags(&I);
3369dd58ef01SDimitry Andric Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |
3370dd58ef01SDimitry Andric unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
3371dd58ef01SDimitry Andric unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
3372dd58ef01SDimitry Andric 1 << bitc::CALL_EXPLICIT_TYPE |
3373dd58ef01SDimitry Andric unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
3374dd58ef01SDimitry Andric unsigned(Flags != 0) << bitc::CALL_FMF);
3375dd58ef01SDimitry Andric if (Flags != 0)
3376dd58ef01SDimitry Andric Vals.push_back(Flags);
3377dd58ef01SDimitry Andric
33785a5ac124SDimitry Andric Vals.push_back(VE.getTypeID(FTy));
3379cfca06d7SDimitry Andric pushValueAndType(CI.getCalledOperand(), InstID, Vals); // Callee
3380009b1c42SEd Schouten
3381009b1c42SEd Schouten // Emit value #'s for the fixed parameters.
3382522600a2SDimitry Andric for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3383522600a2SDimitry Andric // Check for labels (can happen with asm labels).
3384522600a2SDimitry Andric if (FTy->getParamType(i)->isLabelTy())
3385522600a2SDimitry Andric Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
3386522600a2SDimitry Andric else
338701095a5dSDimitry Andric pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
3388522600a2SDimitry Andric }
3389009b1c42SEd Schouten
3390009b1c42SEd Schouten // Emit type/value pairs for varargs params.
3391009b1c42SEd Schouten if (FTy->isVarArg()) {
3392c0981da4SDimitry Andric for (unsigned i = FTy->getNumParams(), e = CI.arg_size(); i != e; ++i)
339301095a5dSDimitry Andric pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
3394009b1c42SEd Schouten }
3395009b1c42SEd Schouten break;
3396009b1c42SEd Schouten }
3397009b1c42SEd Schouten case Instruction::VAArg:
3398009b1c42SEd Schouten Code = bitc::FUNC_CODE_INST_VAARG;
3399009b1c42SEd Schouten Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
340001095a5dSDimitry Andric pushValue(I.getOperand(0), InstID, Vals); // valist.
3401009b1c42SEd Schouten Vals.push_back(VE.getTypeID(I.getType())); // restype.
3402009b1c42SEd Schouten break;
3403706b4fc4SDimitry Andric case Instruction::Freeze:
3404706b4fc4SDimitry Andric Code = bitc::FUNC_CODE_INST_FREEZE;
3405706b4fc4SDimitry Andric pushValueAndType(I.getOperand(0), InstID, Vals);
3406706b4fc4SDimitry Andric break;
3407009b1c42SEd Schouten }
3408009b1c42SEd Schouten
3409009b1c42SEd Schouten Stream.EmitRecord(Code, Vals, AbbrevToUse);
3410009b1c42SEd Schouten Vals.clear();
3411009b1c42SEd Schouten }
3412009b1c42SEd Schouten
3413d99dafe2SDimitry Andric /// Write a GlobalValue VST to the module. The purpose of this data structure is
3414d99dafe2SDimitry Andric /// to allow clients to efficiently find the function body.
writeGlobalValueSymbolTable(DenseMap<const Function *,uint64_t> & FunctionToBitcodeIndex)3415d99dafe2SDimitry Andric void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
3416d99dafe2SDimitry Andric DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3417dd58ef01SDimitry Andric // Get the offset of the VST we are writing, and backpatch it into
3418dd58ef01SDimitry Andric // the VST forward declaration record.
3419dd58ef01SDimitry Andric uint64_t VSTOffset = Stream.GetCurrentBitNo();
3420b915e9e0SDimitry Andric // The BitcodeStartBit was the stream offset of the identification block.
342101095a5dSDimitry Andric VSTOffset -= bitcodeStartBit();
3422dd58ef01SDimitry Andric assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
3423b915e9e0SDimitry Andric // Note that we add 1 here because the offset is relative to one word
3424b915e9e0SDimitry Andric // before the start of the identification block, which was historically
3425b915e9e0SDimitry Andric // always the start of the regular bitcode header.
3426b915e9e0SDimitry Andric Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
3427dd58ef01SDimitry Andric
3428009b1c42SEd Schouten Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
3429009b1c42SEd Schouten
34307e7b6700SDimitry Andric auto Abbv = std::make_shared<BitCodeAbbrev>();
3431dd58ef01SDimitry Andric Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
3432dd58ef01SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3433dd58ef01SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
3434d99dafe2SDimitry Andric unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3435dd58ef01SDimitry Andric
3436d99dafe2SDimitry Andric for (const Function &F : M) {
3437d99dafe2SDimitry Andric uint64_t Record[2];
3438dd58ef01SDimitry Andric
3439d99dafe2SDimitry Andric if (F.isDeclaration())
3440d99dafe2SDimitry Andric continue;
344101095a5dSDimitry Andric
3442d99dafe2SDimitry Andric Record[0] = VE.getValueID(&F);
3443d99dafe2SDimitry Andric
3444d99dafe2SDimitry Andric // Save the word offset of the function (from the start of the
3445d99dafe2SDimitry Andric // actual bitcode written to the stream).
3446d99dafe2SDimitry Andric uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit();
3447d99dafe2SDimitry Andric assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
3448d99dafe2SDimitry Andric // Note that we add 1 here because the offset is relative to one word
3449d99dafe2SDimitry Andric // before the start of the identification block, which was historically
3450d99dafe2SDimitry Andric // always the start of the regular bitcode header.
3451d99dafe2SDimitry Andric Record[1] = BitcodeIndex / 32 + 1;
3452d99dafe2SDimitry Andric
3453d99dafe2SDimitry Andric Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev);
3454dd58ef01SDimitry Andric }
3455dd58ef01SDimitry Andric
3456d99dafe2SDimitry Andric Stream.ExitBlock();
3457d99dafe2SDimitry Andric }
3458d99dafe2SDimitry Andric
3459d99dafe2SDimitry Andric /// Emit names for arguments, instructions and basic blocks in a function.
writeFunctionLevelValueSymbolTable(const ValueSymbolTable & VST)3460d99dafe2SDimitry Andric void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
3461d99dafe2SDimitry Andric const ValueSymbolTable &VST) {
3462d99dafe2SDimitry Andric if (VST.empty())
3463d99dafe2SDimitry Andric return;
3464d99dafe2SDimitry Andric
3465d99dafe2SDimitry Andric Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
3466d99dafe2SDimitry Andric
3467009b1c42SEd Schouten // FIXME: Set up the abbrev, we know how many values there are!
3468009b1c42SEd Schouten // FIXME: We know if the type names can use 7-bit ascii.
346901095a5dSDimitry Andric SmallVector<uint64_t, 64> NameVals;
3470009b1c42SEd Schouten
3471dd58ef01SDimitry Andric for (const ValueName &Name : VST) {
3472009b1c42SEd Schouten // Figure out the encoding to use for the name.
3473d288ef4cSDimitry Andric StringEncoding Bits = getStringEncoding(Name.getKey());
3474009b1c42SEd Schouten
3475009b1c42SEd Schouten unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
3476dd58ef01SDimitry Andric NameVals.push_back(VE.getValueID(Name.getValue()));
3477dd58ef01SDimitry Andric
347801095a5dSDimitry Andric // VST_CODE_ENTRY: [valueid, namechar x N]
347901095a5dSDimitry Andric // VST_CODE_BBENTRY: [bbid, namechar x N]
3480009b1c42SEd Schouten unsigned Code;
3481dd58ef01SDimitry Andric if (isa<BasicBlock>(Name.getValue())) {
3482009b1c42SEd Schouten Code = bitc::VST_CODE_BBENTRY;
3483dd58ef01SDimitry Andric if (Bits == SE_Char6)
3484009b1c42SEd Schouten AbbrevToUse = VST_BBENTRY_6_ABBREV;
3485009b1c42SEd Schouten } else {
3486009b1c42SEd Schouten Code = bitc::VST_CODE_ENTRY;
3487dd58ef01SDimitry Andric if (Bits == SE_Char6)
3488009b1c42SEd Schouten AbbrevToUse = VST_ENTRY_6_ABBREV;
3489dd58ef01SDimitry Andric else if (Bits == SE_Fixed7)
3490009b1c42SEd Schouten AbbrevToUse = VST_ENTRY_7_ABBREV;
3491009b1c42SEd Schouten }
3492009b1c42SEd Schouten
3493dd58ef01SDimitry Andric for (const auto P : Name.getKey())
3494dd58ef01SDimitry Andric NameVals.push_back((unsigned char)P);
3495009b1c42SEd Schouten
3496009b1c42SEd Schouten // Emit the finished record.
3497009b1c42SEd Schouten Stream.EmitRecord(Code, NameVals, AbbrevToUse);
3498009b1c42SEd Schouten NameVals.clear();
3499009b1c42SEd Schouten }
3500009b1c42SEd Schouten
3501dd58ef01SDimitry Andric Stream.ExitBlock();
3502dd58ef01SDimitry Andric }
3503dd58ef01SDimitry Andric
writeUseList(UseListOrder && Order)350401095a5dSDimitry Andric void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
350567c32a98SDimitry Andric assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
350667c32a98SDimitry Andric unsigned Code;
350767c32a98SDimitry Andric if (isa<BasicBlock>(Order.V))
350867c32a98SDimitry Andric Code = bitc::USELIST_CODE_BB;
350967c32a98SDimitry Andric else
351067c32a98SDimitry Andric Code = bitc::USELIST_CODE_DEFAULT;
351167c32a98SDimitry Andric
35125a5ac124SDimitry Andric SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
351367c32a98SDimitry Andric Record.push_back(VE.getValueID(Order.V));
351467c32a98SDimitry Andric Stream.EmitRecord(Code, Record);
351567c32a98SDimitry Andric }
351667c32a98SDimitry Andric
writeUseListBlock(const Function * F)351701095a5dSDimitry Andric void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
35185a5ac124SDimitry Andric assert(VE.shouldPreserveUseListOrder() &&
35195a5ac124SDimitry Andric "Expected to be preserving use-list order");
35205a5ac124SDimitry Andric
352167c32a98SDimitry Andric auto hasMore = [&]() {
352267c32a98SDimitry Andric return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
352367c32a98SDimitry Andric };
352467c32a98SDimitry Andric if (!hasMore())
352567c32a98SDimitry Andric // Nothing to do.
352667c32a98SDimitry Andric return;
352767c32a98SDimitry Andric
352867c32a98SDimitry Andric Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
352967c32a98SDimitry Andric while (hasMore()) {
353001095a5dSDimitry Andric writeUseList(std::move(VE.UseListOrders.back()));
353167c32a98SDimitry Andric VE.UseListOrders.pop_back();
353267c32a98SDimitry Andric }
353367c32a98SDimitry Andric Stream.ExitBlock();
353467c32a98SDimitry Andric }
353567c32a98SDimitry Andric
3536dd58ef01SDimitry Andric /// Emit a function body to the module stream.
writeFunction(const Function & F,DenseMap<const Function *,uint64_t> & FunctionToBitcodeIndex)353701095a5dSDimitry Andric void ModuleBitcodeWriter::writeFunction(
353801095a5dSDimitry Andric const Function &F,
353901095a5dSDimitry Andric DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3540dd58ef01SDimitry Andric // Save the bitcode index of the start of this function block for recording
3541dd58ef01SDimitry Andric // in the VST.
354201095a5dSDimitry Andric FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
3543dd58ef01SDimitry Andric
3544009b1c42SEd Schouten Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
3545009b1c42SEd Schouten VE.incorporateFunction(F);
3546009b1c42SEd Schouten
3547009b1c42SEd Schouten SmallVector<unsigned, 64> Vals;
3548009b1c42SEd Schouten
3549009b1c42SEd Schouten // Emit the number of basic blocks, so the reader can create them ahead of
3550009b1c42SEd Schouten // time.
3551009b1c42SEd Schouten Vals.push_back(VE.getBasicBlocks().size());
3552009b1c42SEd Schouten Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
3553009b1c42SEd Schouten Vals.clear();
3554009b1c42SEd Schouten
3555009b1c42SEd Schouten // If there are function-local constants, emit them now.
3556009b1c42SEd Schouten unsigned CstStart, CstEnd;
3557009b1c42SEd Schouten VE.getFunctionConstantRange(CstStart, CstEnd);
355801095a5dSDimitry Andric writeConstants(CstStart, CstEnd, false);
3559009b1c42SEd Schouten
3560829000e0SRoman Divacky // If there is function-local metadata, emit it now.
356101095a5dSDimitry Andric writeFunctionMetadata(F);
3562829000e0SRoman Divacky
3563009b1c42SEd Schouten // Keep a running idea of what the instruction ID is.
3564009b1c42SEd Schouten unsigned InstID = CstEnd;
3565009b1c42SEd Schouten
35665a5ac124SDimitry Andric bool NeedsMetadataAttachment = F.hasMetadata();
3567b5efedafSRoman Divacky
35685a5ac124SDimitry Andric DILocation *LastDL = nullptr;
3569145449b1SDimitry Andric SmallSetVector<Function *, 4> BlockAddressUsers;
3570145449b1SDimitry Andric
3571009b1c42SEd Schouten // Finally, emit all the instructions, in order.
3572145449b1SDimitry Andric for (const BasicBlock &BB : F) {
3573f65dcba8SDimitry Andric for (const Instruction &I : BB) {
3574f65dcba8SDimitry Andric writeInstruction(I, InstID, Vals);
3575dd58ef01SDimitry Andric
3576f65dcba8SDimitry Andric if (!I.getType()->isVoidTy())
3577009b1c42SEd Schouten ++InstID;
3578b5efedafSRoman Divacky
3579b5efedafSRoman Divacky // If the instruction has metadata, write a metadata attachment later.
3580f65dcba8SDimitry Andric NeedsMetadataAttachment |= I.hasMetadataOtherThanDebugLoc();
3581b5efedafSRoman Divacky
3582b5efedafSRoman Divacky // If the instruction has a debug location, emit it.
3583ac9a064cSDimitry Andric if (DILocation *DL = I.getDebugLoc()) {
35845a5ac124SDimitry Andric if (DL == LastDL) {
3585b5efedafSRoman Divacky // Just repeat the same debug loc as last time.
3586b5efedafSRoman Divacky Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
3587ac9a064cSDimitry Andric } else {
35885a5ac124SDimitry Andric Vals.push_back(DL->getLine());
35895a5ac124SDimitry Andric Vals.push_back(DL->getColumn());
35905a5ac124SDimitry Andric Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
35915a5ac124SDimitry Andric Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
3592d8e91e46SDimitry Andric Vals.push_back(DL->isImplicitCode());
3593411bd29eSDimitry Andric Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
3594b5efedafSRoman Divacky Vals.clear();
3595b5efedafSRoman Divacky LastDL = DL;
3596b5efedafSRoman Divacky }
3597ac9a064cSDimitry Andric }
3598ac9a064cSDimitry Andric
3599ac9a064cSDimitry Andric // If the instruction has DbgRecords attached to it, emit them. Note that
3600ac9a064cSDimitry Andric // they come after the instruction so that it's easy to attach them again
3601ac9a064cSDimitry Andric // when reading the bitcode, even though conceptually the debug locations
3602ac9a064cSDimitry Andric // start "before" the instruction.
3603ac9a064cSDimitry Andric if (I.hasDbgRecords() && WriteNewDbgInfoFormatToBitcode) {
3604ac9a064cSDimitry Andric /// Try to push the value only (unwrapped), otherwise push the
3605ac9a064cSDimitry Andric /// metadata wrapped value. Returns true if the value was pushed
3606ac9a064cSDimitry Andric /// without the ValueAsMetadata wrapper.
3607ac9a064cSDimitry Andric auto PushValueOrMetadata = [&Vals, InstID,
3608ac9a064cSDimitry Andric this](Metadata *RawLocation) {
3609ac9a064cSDimitry Andric assert(RawLocation &&
3610ac9a064cSDimitry Andric "RawLocation unexpectedly null in DbgVariableRecord");
3611ac9a064cSDimitry Andric if (ValueAsMetadata *VAM = dyn_cast<ValueAsMetadata>(RawLocation)) {
3612ac9a064cSDimitry Andric SmallVector<unsigned, 2> ValAndType;
3613ac9a064cSDimitry Andric // If the value is a fwd-ref the type is also pushed. We don't
3614ac9a064cSDimitry Andric // want the type, so fwd-refs are kept wrapped (pushValueAndType
3615ac9a064cSDimitry Andric // returns false if the value is pushed without type).
3616ac9a064cSDimitry Andric if (!pushValueAndType(VAM->getValue(), InstID, ValAndType)) {
3617ac9a064cSDimitry Andric Vals.push_back(ValAndType[0]);
3618ac9a064cSDimitry Andric return true;
3619ac9a064cSDimitry Andric }
3620ac9a064cSDimitry Andric }
3621ac9a064cSDimitry Andric // The metadata is a DIArgList, or ValueAsMetadata wrapping a
3622ac9a064cSDimitry Andric // fwd-ref. Push the metadata ID.
3623ac9a064cSDimitry Andric Vals.push_back(VE.getMetadataID(RawLocation));
3624ac9a064cSDimitry Andric return false;
3625ac9a064cSDimitry Andric };
3626ac9a064cSDimitry Andric
3627ac9a064cSDimitry Andric // Write out non-instruction debug information attached to this
3628ac9a064cSDimitry Andric // instruction. Write it after the instruction so that it's easy to
3629ac9a064cSDimitry Andric // re-attach to the instruction reading the records in.
3630ac9a064cSDimitry Andric for (DbgRecord &DR : I.DebugMarker->getDbgRecordRange()) {
3631ac9a064cSDimitry Andric if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) {
3632ac9a064cSDimitry Andric Vals.push_back(VE.getMetadataID(&*DLR->getDebugLoc()));
3633ac9a064cSDimitry Andric Vals.push_back(VE.getMetadataID(DLR->getLabel()));
3634ac9a064cSDimitry Andric Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_RECORD_LABEL, Vals);
3635ac9a064cSDimitry Andric Vals.clear();
3636ac9a064cSDimitry Andric continue;
3637ac9a064cSDimitry Andric }
3638ac9a064cSDimitry Andric
3639ac9a064cSDimitry Andric // First 3 fields are common to all kinds:
3640ac9a064cSDimitry Andric // DILocation, DILocalVariable, DIExpression
3641ac9a064cSDimitry Andric // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE)
3642ac9a064cSDimitry Andric // ..., LocationMetadata
3643ac9a064cSDimitry Andric // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE - abbrev'd)
3644ac9a064cSDimitry Andric // ..., Value
3645ac9a064cSDimitry Andric // dbg_declare (FUNC_CODE_DEBUG_RECORD_DECLARE)
3646ac9a064cSDimitry Andric // ..., LocationMetadata
3647ac9a064cSDimitry Andric // dbg_assign (FUNC_CODE_DEBUG_RECORD_ASSIGN)
3648ac9a064cSDimitry Andric // ..., LocationMetadata, DIAssignID, DIExpression, LocationMetadata
3649ac9a064cSDimitry Andric DbgVariableRecord &DVR = cast<DbgVariableRecord>(DR);
3650ac9a064cSDimitry Andric Vals.push_back(VE.getMetadataID(&*DVR.getDebugLoc()));
3651ac9a064cSDimitry Andric Vals.push_back(VE.getMetadataID(DVR.getVariable()));
3652ac9a064cSDimitry Andric Vals.push_back(VE.getMetadataID(DVR.getExpression()));
3653ac9a064cSDimitry Andric if (DVR.isDbgValue()) {
3654ac9a064cSDimitry Andric if (PushValueOrMetadata(DVR.getRawLocation()))
3655ac9a064cSDimitry Andric Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE, Vals,
3656ac9a064cSDimitry Andric FUNCTION_DEBUG_RECORD_VALUE_ABBREV);
3657ac9a064cSDimitry Andric else
3658ac9a064cSDimitry Andric Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_RECORD_VALUE, Vals);
3659ac9a064cSDimitry Andric } else if (DVR.isDbgDeclare()) {
3660ac9a064cSDimitry Andric Vals.push_back(VE.getMetadataID(DVR.getRawLocation()));
3661ac9a064cSDimitry Andric Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_RECORD_DECLARE, Vals);
3662ac9a064cSDimitry Andric } else {
3663ac9a064cSDimitry Andric assert(DVR.isDbgAssign() && "Unexpected DbgRecord kind");
3664ac9a064cSDimitry Andric Vals.push_back(VE.getMetadataID(DVR.getRawLocation()));
3665ac9a064cSDimitry Andric Vals.push_back(VE.getMetadataID(DVR.getAssignID()));
3666ac9a064cSDimitry Andric Vals.push_back(VE.getMetadataID(DVR.getAddressExpression()));
3667ac9a064cSDimitry Andric Vals.push_back(VE.getMetadataID(DVR.getRawAddress()));
3668ac9a064cSDimitry Andric Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_RECORD_ASSIGN, Vals);
3669ac9a064cSDimitry Andric }
3670ac9a064cSDimitry Andric Vals.clear();
3671ac9a064cSDimitry Andric }
3672ac9a064cSDimitry Andric }
3673ac9a064cSDimitry Andric }
3674009b1c42SEd Schouten
3675145449b1SDimitry Andric if (BlockAddress *BA = BlockAddress::lookup(&BB)) {
3676145449b1SDimitry Andric SmallVector<Value *> Worklist{BA};
3677145449b1SDimitry Andric SmallPtrSet<Value *, 8> Visited{BA};
3678145449b1SDimitry Andric while (!Worklist.empty()) {
3679145449b1SDimitry Andric Value *V = Worklist.pop_back_val();
3680145449b1SDimitry Andric for (User *U : V->users()) {
3681145449b1SDimitry Andric if (auto *I = dyn_cast<Instruction>(U)) {
3682145449b1SDimitry Andric Function *P = I->getFunction();
3683145449b1SDimitry Andric if (P != &F)
3684145449b1SDimitry Andric BlockAddressUsers.insert(P);
3685145449b1SDimitry Andric } else if (isa<Constant>(U) && !isa<GlobalValue>(U) &&
3686145449b1SDimitry Andric Visited.insert(U).second)
3687145449b1SDimitry Andric Worklist.push_back(U);
3688145449b1SDimitry Andric }
3689145449b1SDimitry Andric }
3690145449b1SDimitry Andric }
3691145449b1SDimitry Andric }
3692145449b1SDimitry Andric
3693145449b1SDimitry Andric if (!BlockAddressUsers.empty()) {
3694145449b1SDimitry Andric Vals.resize(BlockAddressUsers.size());
3695145449b1SDimitry Andric for (auto I : llvm::enumerate(BlockAddressUsers))
3696145449b1SDimitry Andric Vals[I.index()] = VE.getValueID(I.value());
3697145449b1SDimitry Andric Stream.EmitRecord(bitc::FUNC_CODE_BLOCKADDR_USERS, Vals);
3698145449b1SDimitry Andric Vals.clear();
3699145449b1SDimitry Andric }
3700145449b1SDimitry Andric
3701009b1c42SEd Schouten // Emit names for all the instructions etc.
3702b915e9e0SDimitry Andric if (auto *Symtab = F.getValueSymbolTable())
3703d99dafe2SDimitry Andric writeFunctionLevelValueSymbolTable(*Symtab);
3704009b1c42SEd Schouten
3705b5efedafSRoman Divacky if (NeedsMetadataAttachment)
370601095a5dSDimitry Andric writeFunctionMetadataAttachment(F);
37075a5ac124SDimitry Andric if (VE.shouldPreserveUseListOrder())
370801095a5dSDimitry Andric writeUseListBlock(&F);
3709009b1c42SEd Schouten VE.purgeFunction();
3710009b1c42SEd Schouten Stream.ExitBlock();
3711009b1c42SEd Schouten }
3712009b1c42SEd Schouten
3713009b1c42SEd Schouten // Emit blockinfo, which defines the standard abbreviations etc.
writeBlockInfo()371401095a5dSDimitry Andric void ModuleBitcodeWriter::writeBlockInfo() {
3715009b1c42SEd Schouten // We only want to emit block info records for blocks that have multiple
3716522600a2SDimitry Andric // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
3717522600a2SDimitry Andric // Other blocks can define their abbrevs inline.
3718b915e9e0SDimitry Andric Stream.EnterBlockInfoBlock();
3719009b1c42SEd Schouten
372001095a5dSDimitry Andric { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
37217e7b6700SDimitry Andric auto Abbv = std::make_shared<BitCodeAbbrev>();
3722009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
3723009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3724009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3725009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
372601095a5dSDimitry Andric if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
372701095a5dSDimitry Andric VST_ENTRY_8_ABBREV)
372859850d08SRoman Divacky llvm_unreachable("Unexpected abbrev ordering!");
3729009b1c42SEd Schouten }
3730009b1c42SEd Schouten
373101095a5dSDimitry Andric { // 7-bit fixed width VST_CODE_ENTRY strings.
37327e7b6700SDimitry Andric auto Abbv = std::make_shared<BitCodeAbbrev>();
3733009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
3734009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3735009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3736009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
373701095a5dSDimitry Andric if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
373801095a5dSDimitry Andric VST_ENTRY_7_ABBREV)
373959850d08SRoman Divacky llvm_unreachable("Unexpected abbrev ordering!");
3740009b1c42SEd Schouten }
374101095a5dSDimitry Andric { // 6-bit char6 VST_CODE_ENTRY strings.
37427e7b6700SDimitry Andric auto Abbv = std::make_shared<BitCodeAbbrev>();
3743009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
3744009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3745009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3746009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
374701095a5dSDimitry Andric if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
374801095a5dSDimitry Andric VST_ENTRY_6_ABBREV)
374959850d08SRoman Divacky llvm_unreachable("Unexpected abbrev ordering!");
3750009b1c42SEd Schouten }
375101095a5dSDimitry Andric { // 6-bit char6 VST_CODE_BBENTRY strings.
37527e7b6700SDimitry Andric auto Abbv = std::make_shared<BitCodeAbbrev>();
3753009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
3754009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3755009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3756009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
375701095a5dSDimitry Andric if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
375801095a5dSDimitry Andric VST_BBENTRY_6_ABBREV)
375959850d08SRoman Divacky llvm_unreachable("Unexpected abbrev ordering!");
3760009b1c42SEd Schouten }
3761009b1c42SEd Schouten
3762009b1c42SEd Schouten { // SETTYPE abbrev for CONSTANTS_BLOCK.
37637e7b6700SDimitry Andric auto Abbv = std::make_shared<BitCodeAbbrev>();
3764009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
3765009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
3766ac9a064cSDimitry Andric VE.computeBitsRequiredForTypeIndices()));
376701095a5dSDimitry Andric if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
376801095a5dSDimitry Andric CONSTANTS_SETTYPE_ABBREV)
376959850d08SRoman Divacky llvm_unreachable("Unexpected abbrev ordering!");
3770009b1c42SEd Schouten }
3771009b1c42SEd Schouten
3772009b1c42SEd Schouten { // INTEGER abbrev for CONSTANTS_BLOCK.
37737e7b6700SDimitry Andric auto Abbv = std::make_shared<BitCodeAbbrev>();
3774009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
3775009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
377601095a5dSDimitry Andric if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
377701095a5dSDimitry Andric CONSTANTS_INTEGER_ABBREV)
377859850d08SRoman Divacky llvm_unreachable("Unexpected abbrev ordering!");
3779009b1c42SEd Schouten }
3780009b1c42SEd Schouten
3781009b1c42SEd Schouten { // CE_CAST abbrev for CONSTANTS_BLOCK.
37827e7b6700SDimitry Andric auto Abbv = std::make_shared<BitCodeAbbrev>();
3783009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
3784009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
3785009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
3786ac9a064cSDimitry Andric VE.computeBitsRequiredForTypeIndices()));
3787009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3788009b1c42SEd Schouten
378901095a5dSDimitry Andric if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
379001095a5dSDimitry Andric CONSTANTS_CE_CAST_Abbrev)
379159850d08SRoman Divacky llvm_unreachable("Unexpected abbrev ordering!");
3792009b1c42SEd Schouten }
3793009b1c42SEd Schouten { // NULL abbrev for CONSTANTS_BLOCK.
37947e7b6700SDimitry Andric auto Abbv = std::make_shared<BitCodeAbbrev>();
3795009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
379601095a5dSDimitry Andric if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
379701095a5dSDimitry Andric CONSTANTS_NULL_Abbrev)
379859850d08SRoman Divacky llvm_unreachable("Unexpected abbrev ordering!");
3799009b1c42SEd Schouten }
3800009b1c42SEd Schouten
3801009b1c42SEd Schouten // FIXME: This should only use space for first class types!
3802009b1c42SEd Schouten
3803009b1c42SEd Schouten { // INST_LOAD abbrev for FUNCTION_BLOCK.
38047e7b6700SDimitry Andric auto Abbv = std::make_shared<BitCodeAbbrev>();
3805009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
3806009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
38075a5ac124SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3808ac9a064cSDimitry Andric VE.computeBitsRequiredForTypeIndices()));
3809009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
3810009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
381101095a5dSDimitry Andric if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
381201095a5dSDimitry Andric FUNCTION_INST_LOAD_ABBREV)
381359850d08SRoman Divacky llvm_unreachable("Unexpected abbrev ordering!");
3814009b1c42SEd Schouten }
3815d8e91e46SDimitry Andric { // INST_UNOP abbrev for FUNCTION_BLOCK.
3816d8e91e46SDimitry Andric auto Abbv = std::make_shared<BitCodeAbbrev>();
3817d8e91e46SDimitry Andric Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP));
3818d8e91e46SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3819d8e91e46SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3820d8e91e46SDimitry Andric if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3821d8e91e46SDimitry Andric FUNCTION_INST_UNOP_ABBREV)
3822d8e91e46SDimitry Andric llvm_unreachable("Unexpected abbrev ordering!");
3823d8e91e46SDimitry Andric }
3824d8e91e46SDimitry Andric { // INST_UNOP_FLAGS abbrev for FUNCTION_BLOCK.
3825d8e91e46SDimitry Andric auto Abbv = std::make_shared<BitCodeAbbrev>();
3826d8e91e46SDimitry Andric Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP));
3827d8e91e46SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3828d8e91e46SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3829d8e91e46SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
3830d8e91e46SDimitry Andric if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3831d8e91e46SDimitry Andric FUNCTION_INST_UNOP_FLAGS_ABBREV)
3832d8e91e46SDimitry Andric llvm_unreachable("Unexpected abbrev ordering!");
3833d8e91e46SDimitry Andric }
3834009b1c42SEd Schouten { // INST_BINOP abbrev for FUNCTION_BLOCK.
38357e7b6700SDimitry Andric auto Abbv = std::make_shared<BitCodeAbbrev>();
3836009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3837009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3838009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3839009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
384001095a5dSDimitry Andric if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
384101095a5dSDimitry Andric FUNCTION_INST_BINOP_ABBREV)
384259850d08SRoman Divacky llvm_unreachable("Unexpected abbrev ordering!");
384359850d08SRoman Divacky }
384459850d08SRoman Divacky { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
38457e7b6700SDimitry Andric auto Abbv = std::make_shared<BitCodeAbbrev>();
384659850d08SRoman Divacky Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
384759850d08SRoman Divacky Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
384859850d08SRoman Divacky Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
384959850d08SRoman Divacky Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3850eb11fae6SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
385101095a5dSDimitry Andric if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
385201095a5dSDimitry Andric FUNCTION_INST_BINOP_FLAGS_ABBREV)
385359850d08SRoman Divacky llvm_unreachable("Unexpected abbrev ordering!");
3854009b1c42SEd Schouten }
3855009b1c42SEd Schouten { // INST_CAST abbrev for FUNCTION_BLOCK.
38567e7b6700SDimitry Andric auto Abbv = std::make_shared<BitCodeAbbrev>();
3857009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
3858009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
3859009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3860ac9a064cSDimitry Andric VE.computeBitsRequiredForTypeIndices()));
3861009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
386201095a5dSDimitry Andric if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
386301095a5dSDimitry Andric FUNCTION_INST_CAST_ABBREV)
386459850d08SRoman Divacky llvm_unreachable("Unexpected abbrev ordering!");
3865009b1c42SEd Schouten }
3866b1c73532SDimitry Andric { // INST_CAST_FLAGS abbrev for FUNCTION_BLOCK.
3867b1c73532SDimitry Andric auto Abbv = std::make_shared<BitCodeAbbrev>();
3868b1c73532SDimitry Andric Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
3869b1c73532SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
3870b1c73532SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3871ac9a064cSDimitry Andric VE.computeBitsRequiredForTypeIndices()));
3872b1c73532SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3873b1c73532SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
3874b1c73532SDimitry Andric if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3875b1c73532SDimitry Andric FUNCTION_INST_CAST_FLAGS_ABBREV)
3876b1c73532SDimitry Andric llvm_unreachable("Unexpected abbrev ordering!");
3877b1c73532SDimitry Andric }
3878009b1c42SEd Schouten
3879009b1c42SEd Schouten { // INST_RET abbrev for FUNCTION_BLOCK.
38807e7b6700SDimitry Andric auto Abbv = std::make_shared<BitCodeAbbrev>();
3881009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
388201095a5dSDimitry Andric if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
388301095a5dSDimitry Andric FUNCTION_INST_RET_VOID_ABBREV)
388459850d08SRoman Divacky llvm_unreachable("Unexpected abbrev ordering!");
3885009b1c42SEd Schouten }
3886009b1c42SEd Schouten { // INST_RET abbrev for FUNCTION_BLOCK.
38877e7b6700SDimitry Andric auto Abbv = std::make_shared<BitCodeAbbrev>();
3888009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
3889009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
389001095a5dSDimitry Andric if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
389101095a5dSDimitry Andric FUNCTION_INST_RET_VAL_ABBREV)
389259850d08SRoman Divacky llvm_unreachable("Unexpected abbrev ordering!");
3893009b1c42SEd Schouten }
3894009b1c42SEd Schouten { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
38957e7b6700SDimitry Andric auto Abbv = std::make_shared<BitCodeAbbrev>();
3896009b1c42SEd Schouten Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
389701095a5dSDimitry Andric if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
389801095a5dSDimitry Andric FUNCTION_INST_UNREACHABLE_ABBREV)
389959850d08SRoman Divacky llvm_unreachable("Unexpected abbrev ordering!");
3900009b1c42SEd Schouten }
39015a5ac124SDimitry Andric {
39027e7b6700SDimitry Andric auto Abbv = std::make_shared<BitCodeAbbrev>();
39035a5ac124SDimitry Andric Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
3904ac9a064cSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
39055a5ac124SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
39065a5ac124SDimitry Andric Log2_32_Ceil(VE.getTypes().size() + 1)));
39075a5ac124SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
39085a5ac124SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
39095a5ac124SDimitry Andric if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
39105a5ac124SDimitry Andric FUNCTION_INST_GEP_ABBREV)
39115a5ac124SDimitry Andric llvm_unreachable("Unexpected abbrev ordering!");
39125a5ac124SDimitry Andric }
3913ac9a064cSDimitry Andric {
3914ac9a064cSDimitry Andric auto Abbv = std::make_shared<BitCodeAbbrev>();
3915ac9a064cSDimitry Andric Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE));
3916ac9a064cSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // dbgloc
3917ac9a064cSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // var
3918ac9a064cSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // expr
3919ac9a064cSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // val
3920ac9a064cSDimitry Andric if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3921ac9a064cSDimitry Andric FUNCTION_DEBUG_RECORD_VALUE_ABBREV)
3922ac9a064cSDimitry Andric llvm_unreachable("Unexpected abbrev ordering! 1");
3923ac9a064cSDimitry Andric }
3924009b1c42SEd Schouten Stream.ExitBlock();
3925009b1c42SEd Schouten }
3926009b1c42SEd Schouten
3927dd58ef01SDimitry Andric /// Write the module path strings, currently only used when generating
3928dd58ef01SDimitry Andric /// a combined index file.
writeModStrings()392901095a5dSDimitry Andric void IndexBitcodeWriter::writeModStrings() {
3930dd58ef01SDimitry Andric Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);
3931dd58ef01SDimitry Andric
3932dd58ef01SDimitry Andric // TODO: See which abbrev sizes we actually need to emit
3933dd58ef01SDimitry Andric
3934dd58ef01SDimitry Andric // 8-bit fixed-width MST_ENTRY strings.
39357e7b6700SDimitry Andric auto Abbv = std::make_shared<BitCodeAbbrev>();
3936dd58ef01SDimitry Andric Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3937dd58ef01SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3938dd58ef01SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3939dd58ef01SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
39407e7b6700SDimitry Andric unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
3941dd58ef01SDimitry Andric
3942dd58ef01SDimitry Andric // 7-bit fixed width MST_ENTRY strings.
39437e7b6700SDimitry Andric Abbv = std::make_shared<BitCodeAbbrev>();
3944dd58ef01SDimitry Andric Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3945dd58ef01SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3946dd58ef01SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3947dd58ef01SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
39487e7b6700SDimitry Andric unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
3949dd58ef01SDimitry Andric
3950dd58ef01SDimitry Andric // 6-bit char6 MST_ENTRY strings.
39517e7b6700SDimitry Andric Abbv = std::make_shared<BitCodeAbbrev>();
3952dd58ef01SDimitry Andric Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3953dd58ef01SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3954dd58ef01SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3955dd58ef01SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
39567e7b6700SDimitry Andric unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
3957dd58ef01SDimitry Andric
395801095a5dSDimitry Andric // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
39597e7b6700SDimitry Andric Abbv = std::make_shared<BitCodeAbbrev>();
396001095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH));
396101095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
396201095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
396301095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
396401095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
396501095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
39667e7b6700SDimitry Andric unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
396701095a5dSDimitry Andric
396801095a5dSDimitry Andric SmallVector<unsigned, 64> Vals;
3969b1c73532SDimitry Andric forEachModule([&](const StringMapEntry<ModuleHash> &MPSE) {
3970d288ef4cSDimitry Andric StringRef Key = MPSE.getKey();
3971b1c73532SDimitry Andric const auto &Hash = MPSE.getValue();
3972d288ef4cSDimitry Andric StringEncoding Bits = getStringEncoding(Key);
3973dd58ef01SDimitry Andric unsigned AbbrevToUse = Abbrev8Bit;
3974dd58ef01SDimitry Andric if (Bits == SE_Char6)
3975dd58ef01SDimitry Andric AbbrevToUse = Abbrev6Bit;
3976dd58ef01SDimitry Andric else if (Bits == SE_Fixed7)
3977dd58ef01SDimitry Andric AbbrevToUse = Abbrev7Bit;
3978dd58ef01SDimitry Andric
3979b1c73532SDimitry Andric auto ModuleId = ModuleIdMap.size();
3980b1c73532SDimitry Andric ModuleIdMap[Key] = ModuleId;
3981b1c73532SDimitry Andric Vals.push_back(ModuleId);
3982d288ef4cSDimitry Andric Vals.append(Key.begin(), Key.end());
3983dd58ef01SDimitry Andric
3984dd58ef01SDimitry Andric // Emit the finished record.
398501095a5dSDimitry Andric Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
398601095a5dSDimitry Andric
398701095a5dSDimitry Andric // Emit an optional hash for the module now
3988d288ef4cSDimitry Andric if (llvm::any_of(Hash, [](uint32_t H) { return H; })) {
3989d288ef4cSDimitry Andric Vals.assign(Hash.begin(), Hash.end());
399001095a5dSDimitry Andric // Emit the hash record.
399101095a5dSDimitry Andric Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
399201095a5dSDimitry Andric }
399301095a5dSDimitry Andric
399401095a5dSDimitry Andric Vals.clear();
3995d288ef4cSDimitry Andric });
3996dd58ef01SDimitry Andric Stream.ExitBlock();
3997dd58ef01SDimitry Andric }
3998dd58ef01SDimitry Andric
399971d5a254SDimitry Andric /// Write the function type metadata related records that need to appear before
400071d5a254SDimitry Andric /// a function summary entry (whether per-module or combined).
4001b60736ecSDimitry Andric template <typename Fn>
writeFunctionTypeMetadataRecords(BitstreamWriter & Stream,FunctionSummary * FS,Fn GetValueID)4002d8e91e46SDimitry Andric static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream,
4003b60736ecSDimitry Andric FunctionSummary *FS,
4004b60736ecSDimitry Andric Fn GetValueID) {
4005d8e91e46SDimitry Andric if (!FS->type_tests().empty())
400671d5a254SDimitry Andric Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
400771d5a254SDimitry Andric
400871d5a254SDimitry Andric SmallVector<uint64_t, 64> Record;
400971d5a254SDimitry Andric
401071d5a254SDimitry Andric auto WriteVFuncIdVec = [&](uint64_t Ty,
401171d5a254SDimitry Andric ArrayRef<FunctionSummary::VFuncId> VFs) {
401271d5a254SDimitry Andric if (VFs.empty())
401371d5a254SDimitry Andric return;
401471d5a254SDimitry Andric Record.clear();
401571d5a254SDimitry Andric for (auto &VF : VFs) {
401671d5a254SDimitry Andric Record.push_back(VF.GUID);
401771d5a254SDimitry Andric Record.push_back(VF.Offset);
401871d5a254SDimitry Andric }
401971d5a254SDimitry Andric Stream.EmitRecord(Ty, Record);
402071d5a254SDimitry Andric };
402171d5a254SDimitry Andric
402271d5a254SDimitry Andric WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
402371d5a254SDimitry Andric FS->type_test_assume_vcalls());
402471d5a254SDimitry Andric WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
402571d5a254SDimitry Andric FS->type_checked_load_vcalls());
402671d5a254SDimitry Andric
402771d5a254SDimitry Andric auto WriteConstVCallVec = [&](uint64_t Ty,
402871d5a254SDimitry Andric ArrayRef<FunctionSummary::ConstVCall> VCs) {
402971d5a254SDimitry Andric for (auto &VC : VCs) {
403071d5a254SDimitry Andric Record.clear();
403171d5a254SDimitry Andric Record.push_back(VC.VFunc.GUID);
403271d5a254SDimitry Andric Record.push_back(VC.VFunc.Offset);
4033b60736ecSDimitry Andric llvm::append_range(Record, VC.Args);
403471d5a254SDimitry Andric Stream.EmitRecord(Ty, Record);
403571d5a254SDimitry Andric }
403671d5a254SDimitry Andric };
403771d5a254SDimitry Andric
403871d5a254SDimitry Andric WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
403971d5a254SDimitry Andric FS->type_test_assume_const_vcalls());
404071d5a254SDimitry Andric WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
404171d5a254SDimitry Andric FS->type_checked_load_const_vcalls());
4042cfca06d7SDimitry Andric
4043cfca06d7SDimitry Andric auto WriteRange = [&](ConstantRange Range) {
4044cfca06d7SDimitry Andric Range = Range.sextOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
4045cfca06d7SDimitry Andric assert(Range.getLower().getNumWords() == 1);
4046cfca06d7SDimitry Andric assert(Range.getUpper().getNumWords() == 1);
4047cfca06d7SDimitry Andric emitSignedInt64(Record, *Range.getLower().getRawData());
4048cfca06d7SDimitry Andric emitSignedInt64(Record, *Range.getUpper().getRawData());
4049cfca06d7SDimitry Andric };
4050cfca06d7SDimitry Andric
4051cfca06d7SDimitry Andric if (!FS->paramAccesses().empty()) {
4052cfca06d7SDimitry Andric Record.clear();
4053cfca06d7SDimitry Andric for (auto &Arg : FS->paramAccesses()) {
4054b60736ecSDimitry Andric size_t UndoSize = Record.size();
4055cfca06d7SDimitry Andric Record.push_back(Arg.ParamNo);
4056cfca06d7SDimitry Andric WriteRange(Arg.Use);
4057cfca06d7SDimitry Andric Record.push_back(Arg.Calls.size());
4058cfca06d7SDimitry Andric for (auto &Call : Arg.Calls) {
4059cfca06d7SDimitry Andric Record.push_back(Call.ParamNo);
4060e3b55780SDimitry Andric std::optional<unsigned> ValueID = GetValueID(Call.Callee);
4061b60736ecSDimitry Andric if (!ValueID) {
4062b60736ecSDimitry Andric // If ValueID is unknown we can't drop just this call, we must drop
4063b60736ecSDimitry Andric // entire parameter.
4064b60736ecSDimitry Andric Record.resize(UndoSize);
4065b60736ecSDimitry Andric break;
4066b60736ecSDimitry Andric }
4067b60736ecSDimitry Andric Record.push_back(*ValueID);
4068cfca06d7SDimitry Andric WriteRange(Call.Offsets);
4069cfca06d7SDimitry Andric }
4070cfca06d7SDimitry Andric }
4071b60736ecSDimitry Andric if (!Record.empty())
4072cfca06d7SDimitry Andric Stream.EmitRecord(bitc::FS_PARAM_ACCESS, Record);
4073cfca06d7SDimitry Andric }
407471d5a254SDimitry Andric }
407571d5a254SDimitry Andric
4076d8e91e46SDimitry Andric /// Collect type IDs from type tests used by function.
4077d8e91e46SDimitry Andric static void
getReferencedTypeIds(FunctionSummary * FS,std::set<GlobalValue::GUID> & ReferencedTypeIds)4078d8e91e46SDimitry Andric getReferencedTypeIds(FunctionSummary *FS,
4079d8e91e46SDimitry Andric std::set<GlobalValue::GUID> &ReferencedTypeIds) {
4080d8e91e46SDimitry Andric if (!FS->type_tests().empty())
4081d8e91e46SDimitry Andric for (auto &TT : FS->type_tests())
4082d8e91e46SDimitry Andric ReferencedTypeIds.insert(TT);
4083d8e91e46SDimitry Andric
4084d8e91e46SDimitry Andric auto GetReferencedTypesFromVFuncIdVec =
4085d8e91e46SDimitry Andric [&](ArrayRef<FunctionSummary::VFuncId> VFs) {
4086d8e91e46SDimitry Andric for (auto &VF : VFs)
4087d8e91e46SDimitry Andric ReferencedTypeIds.insert(VF.GUID);
4088d8e91e46SDimitry Andric };
4089d8e91e46SDimitry Andric
4090d8e91e46SDimitry Andric GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls());
4091d8e91e46SDimitry Andric GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls());
4092d8e91e46SDimitry Andric
4093d8e91e46SDimitry Andric auto GetReferencedTypesFromConstVCallVec =
4094d8e91e46SDimitry Andric [&](ArrayRef<FunctionSummary::ConstVCall> VCs) {
4095d8e91e46SDimitry Andric for (auto &VC : VCs)
4096d8e91e46SDimitry Andric ReferencedTypeIds.insert(VC.VFunc.GUID);
4097d8e91e46SDimitry Andric };
4098d8e91e46SDimitry Andric
4099d8e91e46SDimitry Andric GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls());
4100d8e91e46SDimitry Andric GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls());
4101d8e91e46SDimitry Andric }
4102d8e91e46SDimitry Andric
writeWholeProgramDevirtResolutionByArg(SmallVector<uint64_t,64> & NameVals,const std::vector<uint64_t> & args,const WholeProgramDevirtResolution::ByArg & ByArg)4103eb11fae6SDimitry Andric static void writeWholeProgramDevirtResolutionByArg(
4104eb11fae6SDimitry Andric SmallVector<uint64_t, 64> &NameVals, const std::vector<uint64_t> &args,
4105eb11fae6SDimitry Andric const WholeProgramDevirtResolution::ByArg &ByArg) {
4106eb11fae6SDimitry Andric NameVals.push_back(args.size());
4107b60736ecSDimitry Andric llvm::append_range(NameVals, args);
4108eb11fae6SDimitry Andric
4109eb11fae6SDimitry Andric NameVals.push_back(ByArg.TheKind);
4110eb11fae6SDimitry Andric NameVals.push_back(ByArg.Info);
4111eb11fae6SDimitry Andric NameVals.push_back(ByArg.Byte);
4112eb11fae6SDimitry Andric NameVals.push_back(ByArg.Bit);
4113eb11fae6SDimitry Andric }
4114eb11fae6SDimitry Andric
writeWholeProgramDevirtResolution(SmallVector<uint64_t,64> & NameVals,StringTableBuilder & StrtabBuilder,uint64_t Id,const WholeProgramDevirtResolution & Wpd)4115eb11fae6SDimitry Andric static void writeWholeProgramDevirtResolution(
4116eb11fae6SDimitry Andric SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
4117eb11fae6SDimitry Andric uint64_t Id, const WholeProgramDevirtResolution &Wpd) {
4118eb11fae6SDimitry Andric NameVals.push_back(Id);
4119eb11fae6SDimitry Andric
4120eb11fae6SDimitry Andric NameVals.push_back(Wpd.TheKind);
4121eb11fae6SDimitry Andric NameVals.push_back(StrtabBuilder.add(Wpd.SingleImplName));
4122eb11fae6SDimitry Andric NameVals.push_back(Wpd.SingleImplName.size());
4123eb11fae6SDimitry Andric
4124eb11fae6SDimitry Andric NameVals.push_back(Wpd.ResByArg.size());
4125eb11fae6SDimitry Andric for (auto &A : Wpd.ResByArg)
4126eb11fae6SDimitry Andric writeWholeProgramDevirtResolutionByArg(NameVals, A.first, A.second);
4127eb11fae6SDimitry Andric }
4128eb11fae6SDimitry Andric
writeTypeIdSummaryRecord(SmallVector<uint64_t,64> & NameVals,StringTableBuilder & StrtabBuilder,const std::string & Id,const TypeIdSummary & Summary)4129eb11fae6SDimitry Andric static void writeTypeIdSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
4130eb11fae6SDimitry Andric StringTableBuilder &StrtabBuilder,
4131eb11fae6SDimitry Andric const std::string &Id,
4132eb11fae6SDimitry Andric const TypeIdSummary &Summary) {
4133eb11fae6SDimitry Andric NameVals.push_back(StrtabBuilder.add(Id));
4134eb11fae6SDimitry Andric NameVals.push_back(Id.size());
4135eb11fae6SDimitry Andric
4136eb11fae6SDimitry Andric NameVals.push_back(Summary.TTRes.TheKind);
4137eb11fae6SDimitry Andric NameVals.push_back(Summary.TTRes.SizeM1BitWidth);
4138eb11fae6SDimitry Andric NameVals.push_back(Summary.TTRes.AlignLog2);
4139eb11fae6SDimitry Andric NameVals.push_back(Summary.TTRes.SizeM1);
4140eb11fae6SDimitry Andric NameVals.push_back(Summary.TTRes.BitMask);
4141eb11fae6SDimitry Andric NameVals.push_back(Summary.TTRes.InlineBits);
4142eb11fae6SDimitry Andric
4143eb11fae6SDimitry Andric for (auto &W : Summary.WPDRes)
4144eb11fae6SDimitry Andric writeWholeProgramDevirtResolution(NameVals, StrtabBuilder, W.first,
4145eb11fae6SDimitry Andric W.second);
4146eb11fae6SDimitry Andric }
4147eb11fae6SDimitry Andric
writeTypeIdCompatibleVtableSummaryRecord(SmallVector<uint64_t,64> & NameVals,StringTableBuilder & StrtabBuilder,const std::string & Id,const TypeIdCompatibleVtableInfo & Summary,ValueEnumerator & VE)4148e6d15924SDimitry Andric static void writeTypeIdCompatibleVtableSummaryRecord(
4149e6d15924SDimitry Andric SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
4150e6d15924SDimitry Andric const std::string &Id, const TypeIdCompatibleVtableInfo &Summary,
4151e6d15924SDimitry Andric ValueEnumerator &VE) {
4152e6d15924SDimitry Andric NameVals.push_back(StrtabBuilder.add(Id));
4153e6d15924SDimitry Andric NameVals.push_back(Id.size());
4154e6d15924SDimitry Andric
4155e6d15924SDimitry Andric for (auto &P : Summary) {
4156e6d15924SDimitry Andric NameVals.push_back(P.AddressPointOffset);
4157e6d15924SDimitry Andric NameVals.push_back(VE.getValueID(P.VTableVI.getValue()));
4158e6d15924SDimitry Andric }
4159e6d15924SDimitry Andric }
4160e6d15924SDimitry Andric
writeFunctionHeapProfileRecords(BitstreamWriter & Stream,FunctionSummary * FS,unsigned CallsiteAbbrev,unsigned AllocAbbrev,bool PerModule,std::function<unsigned (const ValueInfo & VI)> GetValueID,std::function<unsigned (unsigned)> GetStackIndex)4161e3b55780SDimitry Andric static void writeFunctionHeapProfileRecords(
4162e3b55780SDimitry Andric BitstreamWriter &Stream, FunctionSummary *FS, unsigned CallsiteAbbrev,
4163e3b55780SDimitry Andric unsigned AllocAbbrev, bool PerModule,
4164e3b55780SDimitry Andric std::function<unsigned(const ValueInfo &VI)> GetValueID,
4165e3b55780SDimitry Andric std::function<unsigned(unsigned)> GetStackIndex) {
4166e3b55780SDimitry Andric SmallVector<uint64_t> Record;
4167e3b55780SDimitry Andric
4168e3b55780SDimitry Andric for (auto &CI : FS->callsites()) {
4169e3b55780SDimitry Andric Record.clear();
4170e3b55780SDimitry Andric // Per module callsite clones should always have a single entry of
4171e3b55780SDimitry Andric // value 0.
4172e3b55780SDimitry Andric assert(!PerModule || (CI.Clones.size() == 1 && CI.Clones[0] == 0));
4173e3b55780SDimitry Andric Record.push_back(GetValueID(CI.Callee));
4174e3b55780SDimitry Andric if (!PerModule) {
4175e3b55780SDimitry Andric Record.push_back(CI.StackIdIndices.size());
4176e3b55780SDimitry Andric Record.push_back(CI.Clones.size());
4177e3b55780SDimitry Andric }
4178e3b55780SDimitry Andric for (auto Id : CI.StackIdIndices)
4179e3b55780SDimitry Andric Record.push_back(GetStackIndex(Id));
4180e3b55780SDimitry Andric if (!PerModule) {
4181e3b55780SDimitry Andric for (auto V : CI.Clones)
4182e3b55780SDimitry Andric Record.push_back(V);
4183e3b55780SDimitry Andric }
4184e3b55780SDimitry Andric Stream.EmitRecord(PerModule ? bitc::FS_PERMODULE_CALLSITE_INFO
4185e3b55780SDimitry Andric : bitc::FS_COMBINED_CALLSITE_INFO,
4186e3b55780SDimitry Andric Record, CallsiteAbbrev);
4187e3b55780SDimitry Andric }
4188e3b55780SDimitry Andric
4189e3b55780SDimitry Andric for (auto &AI : FS->allocs()) {
4190e3b55780SDimitry Andric Record.clear();
4191e3b55780SDimitry Andric // Per module alloc versions should always have a single entry of
4192e3b55780SDimitry Andric // value 0.
4193e3b55780SDimitry Andric assert(!PerModule || (AI.Versions.size() == 1 && AI.Versions[0] == 0));
4194e3b55780SDimitry Andric Record.push_back(AI.MIBs.size());
4195ac9a064cSDimitry Andric if (!PerModule)
4196e3b55780SDimitry Andric Record.push_back(AI.Versions.size());
4197e3b55780SDimitry Andric for (auto &MIB : AI.MIBs) {
4198e3b55780SDimitry Andric Record.push_back((uint8_t)MIB.AllocType);
4199e3b55780SDimitry Andric Record.push_back(MIB.StackIdIndices.size());
4200e3b55780SDimitry Andric for (auto Id : MIB.StackIdIndices)
4201e3b55780SDimitry Andric Record.push_back(GetStackIndex(Id));
4202e3b55780SDimitry Andric }
4203e3b55780SDimitry Andric if (!PerModule) {
4204e3b55780SDimitry Andric for (auto V : AI.Versions)
4205e3b55780SDimitry Andric Record.push_back(V);
4206e3b55780SDimitry Andric }
4207ac9a064cSDimitry Andric assert(AI.TotalSizes.empty() || AI.TotalSizes.size() == AI.MIBs.size());
4208ac9a064cSDimitry Andric if (!AI.TotalSizes.empty()) {
4209ac9a064cSDimitry Andric for (auto Size : AI.TotalSizes)
4210ac9a064cSDimitry Andric Record.push_back(Size);
4211ac9a064cSDimitry Andric }
4212e3b55780SDimitry Andric Stream.EmitRecord(PerModule ? bitc::FS_PERMODULE_ALLOC_INFO
4213e3b55780SDimitry Andric : bitc::FS_COMBINED_ALLOC_INFO,
4214e3b55780SDimitry Andric Record, AllocAbbrev);
4215e3b55780SDimitry Andric }
4216e3b55780SDimitry Andric }
4217e3b55780SDimitry Andric
4218dd58ef01SDimitry Andric // Helper to emit a single function summary record.
writePerModuleFunctionSummaryRecord(SmallVector<uint64_t,64> & NameVals,GlobalValueSummary * Summary,unsigned ValueID,unsigned FSCallsRelBFAbbrev,unsigned FSCallsProfileAbbrev,unsigned CallsiteAbbrev,unsigned AllocAbbrev,const Function & F)4219044eb2f6SDimitry Andric void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
422001095a5dSDimitry Andric SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
4221b1c73532SDimitry Andric unsigned ValueID, unsigned FSCallsRelBFAbbrev,
4222b1c73532SDimitry Andric unsigned FSCallsProfileAbbrev, unsigned CallsiteAbbrev,
4223b1c73532SDimitry Andric unsigned AllocAbbrev, const Function &F) {
4224dd58ef01SDimitry Andric NameVals.push_back(ValueID);
422501095a5dSDimitry Andric
422601095a5dSDimitry Andric FunctionSummary *FS = cast<FunctionSummary>(Summary);
4227b60736ecSDimitry Andric
4228b60736ecSDimitry Andric writeFunctionTypeMetadataRecords(
4229e3b55780SDimitry Andric Stream, FS, [&](const ValueInfo &VI) -> std::optional<unsigned> {
4230b60736ecSDimitry Andric return {VE.getValueID(VI.getValue())};
4231b60736ecSDimitry Andric });
4232b915e9e0SDimitry Andric
4233e3b55780SDimitry Andric writeFunctionHeapProfileRecords(
4234e3b55780SDimitry Andric Stream, FS, CallsiteAbbrev, AllocAbbrev,
4235e3b55780SDimitry Andric /*PerModule*/ true,
4236e3b55780SDimitry Andric /*GetValueId*/ [&](const ValueInfo &VI) { return getValueId(VI); },
4237e3b55780SDimitry Andric /*GetStackIndex*/ [&](unsigned I) { return I; });
4238e3b55780SDimitry Andric
4239e6d15924SDimitry Andric auto SpecialRefCnts = FS->specialRefCounts();
424001095a5dSDimitry Andric NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
4241dd58ef01SDimitry Andric NameVals.push_back(FS->instCount());
4242044eb2f6SDimitry Andric NameVals.push_back(getEncodedFFlags(FS->fflags()));
424301095a5dSDimitry Andric NameVals.push_back(FS->refs().size());
4244e6d15924SDimitry Andric NameVals.push_back(SpecialRefCnts.first); // rorefcnt
4245e6d15924SDimitry Andric NameVals.push_back(SpecialRefCnts.second); // worefcnt
424601095a5dSDimitry Andric
424701095a5dSDimitry Andric for (auto &RI : FS->refs())
4248ac9a064cSDimitry Andric NameVals.push_back(getValueId(RI));
424901095a5dSDimitry Andric
4250b1c73532SDimitry Andric const bool UseRelBFRecord =
4251b1c73532SDimitry Andric WriteRelBFToSummary && !F.hasProfileData() &&
4252b1c73532SDimitry Andric ForceSummaryEdgesCold == FunctionSummary::FSHT_None;
4253b915e9e0SDimitry Andric for (auto &ECI : FS->calls()) {
425401095a5dSDimitry Andric NameVals.push_back(getValueId(ECI.first));
4255b1c73532SDimitry Andric if (UseRelBFRecord)
4256b1c73532SDimitry Andric NameVals.push_back(getEncodedRelBFCallEdgeInfo(ECI.second));
4257b1c73532SDimitry Andric else
4258b1c73532SDimitry Andric NameVals.push_back(getEncodedHotnessCallEdgeInfo(ECI.second));
425901095a5dSDimitry Andric }
426001095a5dSDimitry Andric
4261b1c73532SDimitry Andric unsigned FSAbbrev =
4262b1c73532SDimitry Andric (UseRelBFRecord ? FSCallsRelBFAbbrev : FSCallsProfileAbbrev);
426301095a5dSDimitry Andric unsigned Code =
4264b1c73532SDimitry Andric (UseRelBFRecord ? bitc::FS_PERMODULE_RELBF : bitc::FS_PERMODULE_PROFILE);
4265dd58ef01SDimitry Andric
4266dd58ef01SDimitry Andric // Emit the finished record.
426701095a5dSDimitry Andric Stream.EmitRecord(Code, NameVals, FSAbbrev);
4268dd58ef01SDimitry Andric NameVals.clear();
4269dd58ef01SDimitry Andric }
4270dd58ef01SDimitry Andric
427101095a5dSDimitry Andric // Collect the global value references in the given variable's initializer,
427201095a5dSDimitry Andric // and emit them in a summary record.
writeModuleLevelReferences(const GlobalVariable & V,SmallVector<uint64_t,64> & NameVals,unsigned FSModRefsAbbrev,unsigned FSModVTableRefsAbbrev)4273044eb2f6SDimitry Andric void ModuleBitcodeWriterBase::writeModuleLevelReferences(
427401095a5dSDimitry Andric const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
4275e6d15924SDimitry Andric unsigned FSModRefsAbbrev, unsigned FSModVTableRefsAbbrev) {
4276eb11fae6SDimitry Andric auto VI = Index->getValueInfo(V.getGUID());
4277c46e6a59SDimitry Andric if (!VI || VI.getSummaryList().empty()) {
4278b915e9e0SDimitry Andric // Only declarations should not have a summary (a declaration might however
4279b915e9e0SDimitry Andric // have a summary if the def was in module level asm).
4280b915e9e0SDimitry Andric assert(V.isDeclaration());
428101095a5dSDimitry Andric return;
4282b915e9e0SDimitry Andric }
4283c46e6a59SDimitry Andric auto *Summary = VI.getSummaryList()[0].get();
428401095a5dSDimitry Andric NameVals.push_back(VE.getValueID(&V));
428501095a5dSDimitry Andric GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
4286b915e9e0SDimitry Andric NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
4287d8e91e46SDimitry Andric NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
428801095a5dSDimitry Andric
4289e6d15924SDimitry Andric auto VTableFuncs = VS->vTableFuncs();
4290e6d15924SDimitry Andric if (!VTableFuncs.empty())
4291e6d15924SDimitry Andric NameVals.push_back(VS->refs().size());
4292e6d15924SDimitry Andric
429301095a5dSDimitry Andric unsigned SizeBeforeRefs = NameVals.size();
429401095a5dSDimitry Andric for (auto &RI : VS->refs())
429501095a5dSDimitry Andric NameVals.push_back(VE.getValueID(RI.getValue()));
429601095a5dSDimitry Andric // Sort the refs for determinism output, the vector returned by FS->refs() has
429701095a5dSDimitry Andric // been initialized from a DenseSet.
4298b60736ecSDimitry Andric llvm::sort(drop_begin(NameVals, SizeBeforeRefs));
429901095a5dSDimitry Andric
4300e6d15924SDimitry Andric if (VTableFuncs.empty())
430101095a5dSDimitry Andric Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals,
430201095a5dSDimitry Andric FSModRefsAbbrev);
4303e6d15924SDimitry Andric else {
4304e6d15924SDimitry Andric // VTableFuncs pairs should already be sorted by offset.
4305e6d15924SDimitry Andric for (auto &P : VTableFuncs) {
4306e6d15924SDimitry Andric NameVals.push_back(VE.getValueID(P.FuncVI.getValue()));
4307e6d15924SDimitry Andric NameVals.push_back(P.VTableOffset);
4308e6d15924SDimitry Andric }
4309e6d15924SDimitry Andric
4310e6d15924SDimitry Andric Stream.EmitRecord(bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS, NameVals,
4311e6d15924SDimitry Andric FSModVTableRefsAbbrev);
4312e6d15924SDimitry Andric }
431301095a5dSDimitry Andric NameVals.clear();
431401095a5dSDimitry Andric }
431501095a5dSDimitry Andric
431601095a5dSDimitry Andric /// Emit the per-module summary section alongside the rest of
4317dd58ef01SDimitry Andric /// the module's bitcode.
writePerModuleGlobalValueSummary()4318044eb2f6SDimitry Andric void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
43197ab83427SDimitry Andric // By default we compile with ThinLTO if the module has a summary, but the
43207ab83427SDimitry Andric // client can request full LTO with a module flag.
43217ab83427SDimitry Andric bool IsThinLTO = true;
43227ab83427SDimitry Andric if (auto *MD =
43237ab83427SDimitry Andric mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
43247ab83427SDimitry Andric IsThinLTO = MD->getZExtValue();
43257ab83427SDimitry Andric Stream.EnterSubblock(IsThinLTO ? bitc::GLOBALVAL_SUMMARY_BLOCK_ID
43267ab83427SDimitry Andric : bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID,
43277ab83427SDimitry Andric 4);
432801095a5dSDimitry Andric
4329706b4fc4SDimitry Andric Stream.EmitRecord(
4330706b4fc4SDimitry Andric bitc::FS_VERSION,
4331706b4fc4SDimitry Andric ArrayRef<uint64_t>{ModuleSummaryIndex::BitcodeSummaryVersion});
433201095a5dSDimitry Andric
4333d8e91e46SDimitry Andric // Write the index flags.
4334d8e91e46SDimitry Andric uint64_t Flags = 0;
4335d8e91e46SDimitry Andric // Bits 1-3 are set only in the combined index, skip them.
4336d8e91e46SDimitry Andric if (Index->enableSplitLTOUnit())
4337d8e91e46SDimitry Andric Flags |= 0x8;
43387fa27ce4SDimitry Andric if (Index->hasUnifiedLTO())
43397fa27ce4SDimitry Andric Flags |= 0x200;
43407fa27ce4SDimitry Andric
4341d8e91e46SDimitry Andric Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Flags});
4342d8e91e46SDimitry Andric
4343b915e9e0SDimitry Andric if (Index->begin() == Index->end()) {
4344b915e9e0SDimitry Andric Stream.ExitBlock();
4345b915e9e0SDimitry Andric return;
4346b915e9e0SDimitry Andric }
4347b915e9e0SDimitry Andric
4348d99dafe2SDimitry Andric for (const auto &GVI : valueIds()) {
4349d99dafe2SDimitry Andric Stream.EmitRecord(bitc::FS_VALUE_GUID,
4350d99dafe2SDimitry Andric ArrayRef<uint64_t>{GVI.second, GVI.first});
4351d99dafe2SDimitry Andric }
4352d99dafe2SDimitry Andric
4353e3b55780SDimitry Andric if (!Index->stackIds().empty()) {
4354e3b55780SDimitry Andric auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
4355e3b55780SDimitry Andric StackIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_STACK_IDS));
4356e3b55780SDimitry Andric // numids x stackid
4357e3b55780SDimitry Andric StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4358e3b55780SDimitry Andric StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4359e3b55780SDimitry Andric unsigned StackIdAbbvId = Stream.EmitAbbrev(std::move(StackIdAbbv));
4360e3b55780SDimitry Andric Stream.EmitRecord(bitc::FS_STACK_IDS, Index->stackIds(), StackIdAbbvId);
4361e3b55780SDimitry Andric }
4362e3b55780SDimitry Andric
436301095a5dSDimitry Andric // Abbrev for FS_PERMODULE_PROFILE.
4364eb11fae6SDimitry Andric auto Abbv = std::make_shared<BitCodeAbbrev>();
436501095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));
436601095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
43677fa27ce4SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // flags
4368dd58ef01SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
4369044eb2f6SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
437001095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4371e6d15924SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
4372e6d15924SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
4373b1c73532SDimitry Andric // numrefs x valueid, n x (valueid, hotness+tailcall flags)
437401095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
437501095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
43767e7b6700SDimitry Andric unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4377dd58ef01SDimitry Andric
4378b1c73532SDimitry Andric // Abbrev for FS_PERMODULE_RELBF.
4379eb11fae6SDimitry Andric Abbv = std::make_shared<BitCodeAbbrev>();
4380eb11fae6SDimitry Andric Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_RELBF));
4381eb11fae6SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4382eb11fae6SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4383eb11fae6SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
4384eb11fae6SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
4385eb11fae6SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4386e6d15924SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
4387e6d15924SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
4388b1c73532SDimitry Andric // numrefs x valueid, n x (valueid, rel_block_freq+tailcall])
4389eb11fae6SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4390eb11fae6SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4391b1c73532SDimitry Andric unsigned FSCallsRelBFAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4392eb11fae6SDimitry Andric
439301095a5dSDimitry Andric // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
43947e7b6700SDimitry Andric Abbv = std::make_shared<BitCodeAbbrev>();
439501095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));
439601095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
439701095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
439801095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
439901095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
44007e7b6700SDimitry Andric unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4401dd58ef01SDimitry Andric
4402e6d15924SDimitry Andric // Abbrev for FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS.
4403e6d15924SDimitry Andric Abbv = std::make_shared<BitCodeAbbrev>();
4404e6d15924SDimitry Andric Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS));
4405e6d15924SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4406e6d15924SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4407e6d15924SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4408e6d15924SDimitry Andric // numrefs x valueid, n x (valueid , offset)
4409e6d15924SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4410e6d15924SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4411e6d15924SDimitry Andric unsigned FSModVTableRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4412e6d15924SDimitry Andric
441301095a5dSDimitry Andric // Abbrev for FS_ALIAS.
44147e7b6700SDimitry Andric Abbv = std::make_shared<BitCodeAbbrev>();
441501095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
441601095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
441701095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
441801095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
44197e7b6700SDimitry Andric unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4420dd58ef01SDimitry Andric
4421e6d15924SDimitry Andric // Abbrev for FS_TYPE_ID_METADATA
4422e6d15924SDimitry Andric Abbv = std::make_shared<BitCodeAbbrev>();
4423e6d15924SDimitry Andric Abbv->Add(BitCodeAbbrevOp(bitc::FS_TYPE_ID_METADATA));
4424e6d15924SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid strtab index
4425e6d15924SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid length
4426e6d15924SDimitry Andric // n x (valueid , offset)
4427e6d15924SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4428e6d15924SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4429e6d15924SDimitry Andric unsigned TypeIdCompatibleVtableAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4430e6d15924SDimitry Andric
4431e3b55780SDimitry Andric Abbv = std::make_shared<BitCodeAbbrev>();
4432e3b55780SDimitry Andric Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_CALLSITE_INFO));
4433e3b55780SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4434e3b55780SDimitry Andric // n x stackidindex
4435e3b55780SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4436e3b55780SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4437e3b55780SDimitry Andric unsigned CallsiteAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4438e3b55780SDimitry Andric
4439e3b55780SDimitry Andric Abbv = std::make_shared<BitCodeAbbrev>();
4440e3b55780SDimitry Andric Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_ALLOC_INFO));
4441ac9a064cSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // nummib
4442e3b55780SDimitry Andric // n x (alloc type, numstackids, numstackids x stackidindex)
4443ac9a064cSDimitry Andric // optional: nummib x total size
4444e3b55780SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4445e3b55780SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4446e3b55780SDimitry Andric unsigned AllocAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4447e3b55780SDimitry Andric
444801095a5dSDimitry Andric SmallVector<uint64_t, 64> NameVals;
444901095a5dSDimitry Andric // Iterate over the list of functions instead of the Index to
445001095a5dSDimitry Andric // ensure the ordering is stable.
445101095a5dSDimitry Andric for (const Function &F : M) {
445201095a5dSDimitry Andric // Summary emission does not support anonymous functions, they have to
445301095a5dSDimitry Andric // renamed using the anonymous function renaming pass.
445401095a5dSDimitry Andric if (!F.hasName())
445501095a5dSDimitry Andric report_fatal_error("Unexpected anonymous function when writing summary");
4456dd58ef01SDimitry Andric
4457eb11fae6SDimitry Andric ValueInfo VI = Index->getValueInfo(F.getGUID());
4458c46e6a59SDimitry Andric if (!VI || VI.getSummaryList().empty()) {
4459b915e9e0SDimitry Andric // Only declarations should not have a summary (a declaration might
4460b915e9e0SDimitry Andric // however have a summary if the def was in module level asm).
4461b915e9e0SDimitry Andric assert(F.isDeclaration());
4462b915e9e0SDimitry Andric continue;
4463b915e9e0SDimitry Andric }
4464c46e6a59SDimitry Andric auto *Summary = VI.getSummaryList()[0].get();
4465b1c73532SDimitry Andric writePerModuleFunctionSummaryRecord(
4466b1c73532SDimitry Andric NameVals, Summary, VE.getValueID(&F), FSCallsRelBFAbbrev,
4467b1c73532SDimitry Andric FSCallsProfileAbbrev, CallsiteAbbrev, AllocAbbrev, F);
446801095a5dSDimitry Andric }
446901095a5dSDimitry Andric
447001095a5dSDimitry Andric // Capture references from GlobalVariable initializers, which are outside
447101095a5dSDimitry Andric // of a function scope.
447201095a5dSDimitry Andric for (const GlobalVariable &G : M.globals())
4473e6d15924SDimitry Andric writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev,
4474e6d15924SDimitry Andric FSModVTableRefsAbbrev);
447501095a5dSDimitry Andric
447601095a5dSDimitry Andric for (const GlobalAlias &A : M.aliases()) {
4477c0981da4SDimitry Andric auto *Aliasee = A.getAliaseeObject();
44784b4fe385SDimitry Andric // Skip ifunc and nameless functions which don't have an entry in the
44794b4fe385SDimitry Andric // summary.
44804b4fe385SDimitry Andric if (!Aliasee->hasName() || isa<GlobalIFunc>(Aliasee))
448101095a5dSDimitry Andric continue;
448201095a5dSDimitry Andric auto AliasId = VE.getValueID(&A);
448301095a5dSDimitry Andric auto AliaseeId = VE.getValueID(Aliasee);
448401095a5dSDimitry Andric NameVals.push_back(AliasId);
4485b915e9e0SDimitry Andric auto *Summary = Index->getGlobalValueSummary(A);
4486b915e9e0SDimitry Andric AliasSummary *AS = cast<AliasSummary>(Summary);
4487b915e9e0SDimitry Andric NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
448801095a5dSDimitry Andric NameVals.push_back(AliaseeId);
448901095a5dSDimitry Andric Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
4490dd58ef01SDimitry Andric NameVals.clear();
4491dd58ef01SDimitry Andric }
449201095a5dSDimitry Andric
4493e6d15924SDimitry Andric for (auto &S : Index->typeIdCompatibleVtableMap()) {
4494e6d15924SDimitry Andric writeTypeIdCompatibleVtableSummaryRecord(NameVals, StrtabBuilder, S.first,
4495e6d15924SDimitry Andric S.second, VE);
4496e6d15924SDimitry Andric Stream.EmitRecord(bitc::FS_TYPE_ID_METADATA, NameVals,
4497e6d15924SDimitry Andric TypeIdCompatibleVtableAbbrev);
4498e6d15924SDimitry Andric NameVals.clear();
4499e6d15924SDimitry Andric }
4500e6d15924SDimitry Andric
45017fa27ce4SDimitry Andric if (Index->getBlockCount())
4502cfca06d7SDimitry Andric Stream.EmitRecord(bitc::FS_BLOCK_COUNT,
4503cfca06d7SDimitry Andric ArrayRef<uint64_t>{Index->getBlockCount()});
4504cfca06d7SDimitry Andric
450501095a5dSDimitry Andric Stream.ExitBlock();
450601095a5dSDimitry Andric }
450701095a5dSDimitry Andric
450801095a5dSDimitry Andric /// Emit the combined summary section into the combined index file.
writeCombinedGlobalValueSummary()450901095a5dSDimitry Andric void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
4510e3b55780SDimitry Andric Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 4);
4511706b4fc4SDimitry Andric Stream.EmitRecord(
4512706b4fc4SDimitry Andric bitc::FS_VERSION,
4513706b4fc4SDimitry Andric ArrayRef<uint64_t>{ModuleSummaryIndex::BitcodeSummaryVersion});
451401095a5dSDimitry Andric
4515eb11fae6SDimitry Andric // Write the index flags.
4516cfca06d7SDimitry Andric Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Index.getFlags()});
4517eb11fae6SDimitry Andric
4518d99dafe2SDimitry Andric for (const auto &GVI : valueIds()) {
4519d99dafe2SDimitry Andric Stream.EmitRecord(bitc::FS_VALUE_GUID,
4520d99dafe2SDimitry Andric ArrayRef<uint64_t>{GVI.second, GVI.first});
4521d99dafe2SDimitry Andric }
4522d99dafe2SDimitry Andric
4523ac9a064cSDimitry Andric // Write the stack ids used by this index, which will be a subset of those in
4524ac9a064cSDimitry Andric // the full index in the case of distributed indexes.
4525ac9a064cSDimitry Andric if (!StackIds.empty()) {
4526e3b55780SDimitry Andric auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
4527e3b55780SDimitry Andric StackIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_STACK_IDS));
4528e3b55780SDimitry Andric // numids x stackid
4529e3b55780SDimitry Andric StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4530e3b55780SDimitry Andric StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4531e3b55780SDimitry Andric unsigned StackIdAbbvId = Stream.EmitAbbrev(std::move(StackIdAbbv));
4532e3b55780SDimitry Andric Stream.EmitRecord(bitc::FS_STACK_IDS, StackIds, StackIdAbbvId);
4533e3b55780SDimitry Andric }
4534e3b55780SDimitry Andric
453501095a5dSDimitry Andric // Abbrev for FS_COMBINED_PROFILE.
4536b1c73532SDimitry Andric auto Abbv = std::make_shared<BitCodeAbbrev>();
453701095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));
453801095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
453901095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
454001095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
454101095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
4542044eb2f6SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
4543e6d15924SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // entrycount
454401095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4545e6d15924SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
4546e6d15924SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
4547b1c73532SDimitry Andric // numrefs x valueid, n x (valueid, hotness+tailcall flags)
454801095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
454901095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
45507e7b6700SDimitry Andric unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
455101095a5dSDimitry Andric
455201095a5dSDimitry Andric // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
45537e7b6700SDimitry Andric Abbv = std::make_shared<BitCodeAbbrev>();
455401095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));
455501095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
455601095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
455701095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
455801095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
455901095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
45607e7b6700SDimitry Andric unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
456101095a5dSDimitry Andric
456201095a5dSDimitry Andric // Abbrev for FS_COMBINED_ALIAS.
45637e7b6700SDimitry Andric Abbv = std::make_shared<BitCodeAbbrev>();
456401095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS));
456501095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
456601095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
456701095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
456801095a5dSDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
45697e7b6700SDimitry Andric unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
457001095a5dSDimitry Andric
4571e3b55780SDimitry Andric Abbv = std::make_shared<BitCodeAbbrev>();
4572e3b55780SDimitry Andric Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_CALLSITE_INFO));
4573e3b55780SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4574e3b55780SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numstackindices
4575e3b55780SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numver
4576e3b55780SDimitry Andric // numstackindices x stackidindex, numver x version
4577e3b55780SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4578e3b55780SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4579e3b55780SDimitry Andric unsigned CallsiteAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4580e3b55780SDimitry Andric
4581e3b55780SDimitry Andric Abbv = std::make_shared<BitCodeAbbrev>();
4582e3b55780SDimitry Andric Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALLOC_INFO));
4583e3b55780SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // nummib
4584e3b55780SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numver
4585e3b55780SDimitry Andric // nummib x (alloc type, numstackids, numstackids x stackidindex),
4586e3b55780SDimitry Andric // numver x version
4587ac9a064cSDimitry Andric // optional: nummib x total size
4588e3b55780SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4589e3b55780SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4590e3b55780SDimitry Andric unsigned AllocAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4591e3b55780SDimitry Andric
4592ac9a064cSDimitry Andric auto shouldImportValueAsDecl = [&](GlobalValueSummary *GVS) -> bool {
4593ac9a064cSDimitry Andric if (DecSummaries == nullptr)
4594ac9a064cSDimitry Andric return false;
4595ac9a064cSDimitry Andric return DecSummaries->count(GVS);
4596ac9a064cSDimitry Andric };
4597ac9a064cSDimitry Andric
459801095a5dSDimitry Andric // The aliases are emitted as a post-pass, and will point to the value
459901095a5dSDimitry Andric // id of the aliasee. Save them in a vector for post-processing.
460001095a5dSDimitry Andric SmallVector<AliasSummary *, 64> Aliases;
460101095a5dSDimitry Andric
460201095a5dSDimitry Andric // Save the value id for each summary for alias emission.
460301095a5dSDimitry Andric DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
460401095a5dSDimitry Andric
460501095a5dSDimitry Andric SmallVector<uint64_t, 64> NameVals;
460601095a5dSDimitry Andric
4607eb11fae6SDimitry Andric // Set that will be populated during call to writeFunctionTypeMetadataRecords
4608eb11fae6SDimitry Andric // with the type ids referenced by this index file.
4609eb11fae6SDimitry Andric std::set<GlobalValue::GUID> ReferencedTypeIds;
4610eb11fae6SDimitry Andric
461101095a5dSDimitry Andric // For local linkage, we also emit the original name separately
461201095a5dSDimitry Andric // immediately after the record.
461301095a5dSDimitry Andric auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
4614c0981da4SDimitry Andric // We don't need to emit the original name if we are writing the index for
4615c0981da4SDimitry Andric // distributed backends (in which case ModuleToSummariesForIndex is
4616c0981da4SDimitry Andric // non-null). The original name is only needed during the thin link, since
4617c0981da4SDimitry Andric // for SamplePGO the indirect call targets for local functions have
4618c0981da4SDimitry Andric // have the original name annotated in profile.
4619c0981da4SDimitry Andric // Continue to emit it when writing out the entire combined index, which is
4620c0981da4SDimitry Andric // used in testing the thin link via llvm-lto.
4621c0981da4SDimitry Andric if (ModuleToSummariesForIndex || !GlobalValue::isLocalLinkage(S.linkage()))
462201095a5dSDimitry Andric return;
462301095a5dSDimitry Andric NameVals.push_back(S.getOriginalName());
462401095a5dSDimitry Andric Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals);
462501095a5dSDimitry Andric NameVals.clear();
462601095a5dSDimitry Andric };
462701095a5dSDimitry Andric
4628e6d15924SDimitry Andric std::set<GlobalValue::GUID> DefOrUseGUIDs;
4629044eb2f6SDimitry Andric forEachSummary([&](GVInfo I, bool IsAliasee) {
463001095a5dSDimitry Andric GlobalValueSummary *S = I.second;
463101095a5dSDimitry Andric assert(S);
4632e6d15924SDimitry Andric DefOrUseGUIDs.insert(I.first);
4633e6d15924SDimitry Andric for (const ValueInfo &VI : S->refs())
4634e6d15924SDimitry Andric DefOrUseGUIDs.insert(VI.getGUID());
463501095a5dSDimitry Andric
4636f382538dSDimitry Andric auto ValueId = getValueId(I.first);
4637f382538dSDimitry Andric assert(ValueId);
4638f382538dSDimitry Andric SummaryToValueIdMap[S] = *ValueId;
463901095a5dSDimitry Andric
4640044eb2f6SDimitry Andric // If this is invoked for an aliasee, we want to record the above
4641044eb2f6SDimitry Andric // mapping, but then not emit a summary entry (if the aliasee is
4642044eb2f6SDimitry Andric // to be imported, we will invoke this separately with IsAliasee=false).
4643044eb2f6SDimitry Andric if (IsAliasee)
4644044eb2f6SDimitry Andric return;
4645044eb2f6SDimitry Andric
464601095a5dSDimitry Andric if (auto *AS = dyn_cast<AliasSummary>(S)) {
464701095a5dSDimitry Andric // Will process aliases as a post-pass because the reader wants all
464801095a5dSDimitry Andric // global to be loaded first.
464901095a5dSDimitry Andric Aliases.push_back(AS);
4650148779dfSDimitry Andric return;
465101095a5dSDimitry Andric }
465201095a5dSDimitry Andric
465301095a5dSDimitry Andric if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
4654f382538dSDimitry Andric NameVals.push_back(*ValueId);
4655b1c73532SDimitry Andric assert(ModuleIdMap.count(VS->modulePath()));
4656b1c73532SDimitry Andric NameVals.push_back(ModuleIdMap[VS->modulePath()]);
465701095a5dSDimitry Andric NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
4658d8e91e46SDimitry Andric NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
465901095a5dSDimitry Andric for (auto &RI : VS->refs()) {
4660f382538dSDimitry Andric auto RefValueId = getValueId(RI.getGUID());
4661f382538dSDimitry Andric if (!RefValueId)
4662f382538dSDimitry Andric continue;
4663f382538dSDimitry Andric NameVals.push_back(*RefValueId);
466401095a5dSDimitry Andric }
466501095a5dSDimitry Andric
466601095a5dSDimitry Andric // Emit the finished record.
466701095a5dSDimitry Andric Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals,
466801095a5dSDimitry Andric FSModRefsAbbrev);
466901095a5dSDimitry Andric NameVals.clear();
467001095a5dSDimitry Andric MaybeEmitOriginalName(*S);
4671148779dfSDimitry Andric return;
467201095a5dSDimitry Andric }
467301095a5dSDimitry Andric
4674e3b55780SDimitry Andric auto GetValueId = [&](const ValueInfo &VI) -> std::optional<unsigned> {
4675e3b55780SDimitry Andric if (!VI)
4676e3b55780SDimitry Andric return std::nullopt;
4677c0981da4SDimitry Andric return getValueId(VI.getGUID());
4678b60736ecSDimitry Andric };
4679b60736ecSDimitry Andric
468001095a5dSDimitry Andric auto *FS = cast<FunctionSummary>(S);
4681b60736ecSDimitry Andric writeFunctionTypeMetadataRecords(Stream, FS, GetValueId);
4682d8e91e46SDimitry Andric getReferencedTypeIds(FS, ReferencedTypeIds);
4683b915e9e0SDimitry Andric
4684e3b55780SDimitry Andric writeFunctionHeapProfileRecords(
4685e3b55780SDimitry Andric Stream, FS, CallsiteAbbrev, AllocAbbrev,
4686e3b55780SDimitry Andric /*PerModule*/ false,
4687ac9a064cSDimitry Andric /*GetValueId*/
4688ac9a064cSDimitry Andric [&](const ValueInfo &VI) -> unsigned {
4689e3b55780SDimitry Andric std::optional<unsigned> ValueID = GetValueId(VI);
4690e3b55780SDimitry Andric // This can happen in shared index files for distributed ThinLTO if
4691e3b55780SDimitry Andric // the callee function summary is not included. Record 0 which we
4692e3b55780SDimitry Andric // will have to deal with conservatively when doing any kind of
4693e3b55780SDimitry Andric // validation in the ThinLTO backends.
4694e3b55780SDimitry Andric if (!ValueID)
4695e3b55780SDimitry Andric return 0;
4696e3b55780SDimitry Andric return *ValueID;
4697e3b55780SDimitry Andric },
4698ac9a064cSDimitry Andric /*GetStackIndex*/
4699ac9a064cSDimitry Andric [&](unsigned I) {
4700ac9a064cSDimitry Andric // Get the corresponding index into the list of StackIds actually
4701ac9a064cSDimitry Andric // being written for this combined index (which may be a subset in
4702ac9a064cSDimitry Andric // the case of distributed indexes).
4703ac9a064cSDimitry Andric assert(StackIdIndicesToIndex.contains(I));
4704ac9a064cSDimitry Andric return StackIdIndicesToIndex[I];
4705e3b55780SDimitry Andric });
4706e3b55780SDimitry Andric
4707f382538dSDimitry Andric NameVals.push_back(*ValueId);
4708b1c73532SDimitry Andric assert(ModuleIdMap.count(FS->modulePath()));
4709b1c73532SDimitry Andric NameVals.push_back(ModuleIdMap[FS->modulePath()]);
4710ac9a064cSDimitry Andric NameVals.push_back(
4711ac9a064cSDimitry Andric getEncodedGVSummaryFlags(FS->flags(), shouldImportValueAsDecl(FS)));
471201095a5dSDimitry Andric NameVals.push_back(FS->instCount());
4713044eb2f6SDimitry Andric NameVals.push_back(getEncodedFFlags(FS->fflags()));
4714d8e91e46SDimitry Andric NameVals.push_back(FS->entryCount());
471501095a5dSDimitry Andric
4716d8e91e46SDimitry Andric // Fill in below
4717d8e91e46SDimitry Andric NameVals.push_back(0); // numrefs
4718e6d15924SDimitry Andric NameVals.push_back(0); // rorefcnt
4719e6d15924SDimitry Andric NameVals.push_back(0); // worefcnt
4720d8e91e46SDimitry Andric
4721e6d15924SDimitry Andric unsigned Count = 0, RORefCnt = 0, WORefCnt = 0;
472201095a5dSDimitry Andric for (auto &RI : FS->refs()) {
4723f382538dSDimitry Andric auto RefValueId = getValueId(RI.getGUID());
4724f382538dSDimitry Andric if (!RefValueId)
4725f382538dSDimitry Andric continue;
4726f382538dSDimitry Andric NameVals.push_back(*RefValueId);
4727d8e91e46SDimitry Andric if (RI.isReadOnly())
4728e6d15924SDimitry Andric RORefCnt++;
4729e6d15924SDimitry Andric else if (RI.isWriteOnly())
4730e6d15924SDimitry Andric WORefCnt++;
4731f382538dSDimitry Andric Count++;
473201095a5dSDimitry Andric }
4733d8e91e46SDimitry Andric NameVals[6] = Count;
4734e6d15924SDimitry Andric NameVals[7] = RORefCnt;
4735e6d15924SDimitry Andric NameVals[8] = WORefCnt;
473601095a5dSDimitry Andric
473701095a5dSDimitry Andric for (auto &EI : FS->calls()) {
473801095a5dSDimitry Andric // If this GUID doesn't have a value id, it doesn't have a function
473901095a5dSDimitry Andric // summary and we don't need to record any calls to it.
4740e3b55780SDimitry Andric std::optional<unsigned> CallValueId = GetValueId(EI.first);
4741f382538dSDimitry Andric if (!CallValueId)
474201095a5dSDimitry Andric continue;
4743f382538dSDimitry Andric NameVals.push_back(*CallValueId);
4744b1c73532SDimitry Andric NameVals.push_back(getEncodedHotnessCallEdgeInfo(EI.second));
474501095a5dSDimitry Andric }
474601095a5dSDimitry Andric
474701095a5dSDimitry Andric // Emit the finished record.
4748b1c73532SDimitry Andric Stream.EmitRecord(bitc::FS_COMBINED_PROFILE, NameVals,
4749b1c73532SDimitry Andric FSCallsProfileAbbrev);
475001095a5dSDimitry Andric NameVals.clear();
475101095a5dSDimitry Andric MaybeEmitOriginalName(*S);
4752148779dfSDimitry Andric });
475301095a5dSDimitry Andric
475401095a5dSDimitry Andric for (auto *AS : Aliases) {
475501095a5dSDimitry Andric auto AliasValueId = SummaryToValueIdMap[AS];
475601095a5dSDimitry Andric assert(AliasValueId);
475701095a5dSDimitry Andric NameVals.push_back(AliasValueId);
4758b1c73532SDimitry Andric assert(ModuleIdMap.count(AS->modulePath()));
4759b1c73532SDimitry Andric NameVals.push_back(ModuleIdMap[AS->modulePath()]);
4760ac9a064cSDimitry Andric NameVals.push_back(
4761ac9a064cSDimitry Andric getEncodedGVSummaryFlags(AS->flags(), shouldImportValueAsDecl(AS)));
476201095a5dSDimitry Andric auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()];
476301095a5dSDimitry Andric assert(AliaseeValueId);
476401095a5dSDimitry Andric NameVals.push_back(AliaseeValueId);
476501095a5dSDimitry Andric
476601095a5dSDimitry Andric // Emit the finished record.
476701095a5dSDimitry Andric Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
476801095a5dSDimitry Andric NameVals.clear();
476901095a5dSDimitry Andric MaybeEmitOriginalName(*AS);
4770d8e91e46SDimitry Andric
4771d8e91e46SDimitry Andric if (auto *FS = dyn_cast<FunctionSummary>(&AS->getAliasee()))
4772d8e91e46SDimitry Andric getReferencedTypeIds(FS, ReferencedTypeIds);
4773dd58ef01SDimitry Andric }
4774dd58ef01SDimitry Andric
47757c7aba6eSDimitry Andric if (!Index.cfiFunctionDefs().empty()) {
47767c7aba6eSDimitry Andric for (auto &S : Index.cfiFunctionDefs()) {
4777e6d15924SDimitry Andric if (DefOrUseGUIDs.count(
4778e6d15924SDimitry Andric GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(S)))) {
47797c7aba6eSDimitry Andric NameVals.push_back(StrtabBuilder.add(S));
47807c7aba6eSDimitry Andric NameVals.push_back(S.size());
47817c7aba6eSDimitry Andric }
4782e6d15924SDimitry Andric }
4783e6d15924SDimitry Andric if (!NameVals.empty()) {
47847c7aba6eSDimitry Andric Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DEFS, NameVals);
47857c7aba6eSDimitry Andric NameVals.clear();
47867c7aba6eSDimitry Andric }
4787e6d15924SDimitry Andric }
47887c7aba6eSDimitry Andric
47897c7aba6eSDimitry Andric if (!Index.cfiFunctionDecls().empty()) {
47907c7aba6eSDimitry Andric for (auto &S : Index.cfiFunctionDecls()) {
4791e6d15924SDimitry Andric if (DefOrUseGUIDs.count(
4792e6d15924SDimitry Andric GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(S)))) {
47937c7aba6eSDimitry Andric NameVals.push_back(StrtabBuilder.add(S));
47947c7aba6eSDimitry Andric NameVals.push_back(S.size());
47957c7aba6eSDimitry Andric }
4796e6d15924SDimitry Andric }
4797e6d15924SDimitry Andric if (!NameVals.empty()) {
47987c7aba6eSDimitry Andric Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DECLS, NameVals);
47997c7aba6eSDimitry Andric NameVals.clear();
48007c7aba6eSDimitry Andric }
4801e6d15924SDimitry Andric }
48027c7aba6eSDimitry Andric
4803d8e91e46SDimitry Andric // Walk the GUIDs that were referenced, and write the
4804d8e91e46SDimitry Andric // corresponding type id records.
4805d8e91e46SDimitry Andric for (auto &T : ReferencedTypeIds) {
4806d8e91e46SDimitry Andric auto TidIter = Index.typeIds().equal_range(T);
4807d8e91e46SDimitry Andric for (auto It = TidIter.first; It != TidIter.second; ++It) {
4808d8e91e46SDimitry Andric writeTypeIdSummaryRecord(NameVals, StrtabBuilder, It->second.first,
4809d8e91e46SDimitry Andric It->second.second);
4810eb11fae6SDimitry Andric Stream.EmitRecord(bitc::FS_TYPE_ID, NameVals);
4811eb11fae6SDimitry Andric NameVals.clear();
4812eb11fae6SDimitry Andric }
4813eb11fae6SDimitry Andric }
4814eb11fae6SDimitry Andric
48157fa27ce4SDimitry Andric if (Index.getBlockCount())
4816cfca06d7SDimitry Andric Stream.EmitRecord(bitc::FS_BLOCK_COUNT,
4817cfca06d7SDimitry Andric ArrayRef<uint64_t>{Index.getBlockCount()});
4818cfca06d7SDimitry Andric
4819dd58ef01SDimitry Andric Stream.ExitBlock();
4820dd58ef01SDimitry Andric }
4821dd58ef01SDimitry Andric
4822b915e9e0SDimitry Andric /// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
4823b915e9e0SDimitry Andric /// current llvm version, and a record for the epoch number.
writeIdentificationBlock(BitstreamWriter & Stream)482471d5a254SDimitry Andric static void writeIdentificationBlock(BitstreamWriter &Stream) {
4825dd58ef01SDimitry Andric Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);
4826dd58ef01SDimitry Andric
4827dd58ef01SDimitry Andric // Write the "user readable" string identifying the bitcode producer
48287e7b6700SDimitry Andric auto Abbv = std::make_shared<BitCodeAbbrev>();
4829dd58ef01SDimitry Andric Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING));
4830dd58ef01SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4831dd58ef01SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
48327e7b6700SDimitry Andric auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4833b915e9e0SDimitry Andric writeStringRecord(Stream, bitc::IDENTIFICATION_CODE_STRING,
483401095a5dSDimitry Andric "LLVM" LLVM_VERSION_STRING, StringAbbrev);
4835dd58ef01SDimitry Andric
4836dd58ef01SDimitry Andric // Write the epoch version
48377e7b6700SDimitry Andric Abbv = std::make_shared<BitCodeAbbrev>();
4838dd58ef01SDimitry Andric Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH));
4839dd58ef01SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
48407e7b6700SDimitry Andric auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4841cfca06d7SDimitry Andric constexpr std::array<unsigned, 1> Vals = {{bitc::BITCODE_CURRENT_EPOCH}};
4842dd58ef01SDimitry Andric Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
4843dd58ef01SDimitry Andric Stream.ExitBlock();
4844dd58ef01SDimitry Andric }
4845dd58ef01SDimitry Andric
writeModuleHash(StringRef View)4846ac9a064cSDimitry Andric void ModuleBitcodeWriter::writeModuleHash(StringRef View) {
484701095a5dSDimitry Andric // Emit the module's hash.
484801095a5dSDimitry Andric // MODULE_CODE_HASH: [5*i32]
484971d5a254SDimitry Andric if (GenerateHash) {
485071d5a254SDimitry Andric uint32_t Vals[5];
4851ac9a064cSDimitry Andric Hasher.update(ArrayRef<uint8_t>(
4852ac9a064cSDimitry Andric reinterpret_cast<const uint8_t *>(View.data()), View.size()));
4853145449b1SDimitry Andric std::array<uint8_t, 20> Hash = Hasher.result();
485401095a5dSDimitry Andric for (int Pos = 0; Pos < 20; Pos += 4) {
4855b915e9e0SDimitry Andric Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);
485601095a5dSDimitry Andric }
485701095a5dSDimitry Andric
485801095a5dSDimitry Andric // Emit the finished record.
485901095a5dSDimitry Andric Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
486071d5a254SDimitry Andric
486171d5a254SDimitry Andric if (ModHash)
486271d5a254SDimitry Andric // Save the written hash value.
4863d8e91e46SDimitry Andric llvm::copy(Vals, std::begin(*ModHash));
4864044eb2f6SDimitry Andric }
486501095a5dSDimitry Andric }
486601095a5dSDimitry Andric
write()4867b915e9e0SDimitry Andric void ModuleBitcodeWriter::write() {
4868b915e9e0SDimitry Andric writeIdentificationBlock(Stream);
486901095a5dSDimitry Andric
4870009b1c42SEd Schouten Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
4871ac9a064cSDimitry Andric // We will want to write the module hash at this point. Block any flushing so
4872ac9a064cSDimitry Andric // we can have access to the whole underlying data later.
4873ac9a064cSDimitry Andric Stream.markAndBlockFlushing();
4874009b1c42SEd Schouten
4875d99dafe2SDimitry Andric writeModuleVersion();
4876009b1c42SEd Schouten
4877009b1c42SEd Schouten // Emit blockinfo, which defines the standard abbreviations etc.
487801095a5dSDimitry Andric writeBlockInfo();
4879009b1c42SEd Schouten
4880e6d15924SDimitry Andric // Emit information describing all of the types in the module.
4881e6d15924SDimitry Andric writeTypeTable();
4882e6d15924SDimitry Andric
48834a16efa3SDimitry Andric // Emit information about attribute groups.
488401095a5dSDimitry Andric writeAttributeGroupTable();
48854a16efa3SDimitry Andric
4886009b1c42SEd Schouten // Emit information about parameter attributes.
488701095a5dSDimitry Andric writeAttributeTable();
4888009b1c42SEd Schouten
488901095a5dSDimitry Andric writeComdats();
48905ca98fd9SDimitry Andric
4891009b1c42SEd Schouten // Emit top-level description of module, including target triple, inline asm,
4892009b1c42SEd Schouten // descriptors for global variables, and function prototype info.
489301095a5dSDimitry Andric writeModuleInfo();
4894009b1c42SEd Schouten
4895009b1c42SEd Schouten // Emit constants.
489601095a5dSDimitry Andric writeModuleConstants();
489701095a5dSDimitry Andric
489801095a5dSDimitry Andric // Emit metadata kind names.
489901095a5dSDimitry Andric writeModuleMetadataKinds();
4900009b1c42SEd Schouten
490159850d08SRoman Divacky // Emit metadata.
490201095a5dSDimitry Andric writeModuleMetadata();
490359850d08SRoman Divacky
490467c32a98SDimitry Andric // Emit module-level use-lists.
49055a5ac124SDimitry Andric if (VE.shouldPreserveUseListOrder())
490601095a5dSDimitry Andric writeUseListBlock(nullptr);
490763faed5bSDimitry Andric
490801095a5dSDimitry Andric writeOperandBundleTags();
4909ca089b24SDimitry Andric writeSyncScopeNames();
4910dd58ef01SDimitry Andric
491163faed5bSDimitry Andric // Emit function bodies.
491201095a5dSDimitry Andric DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
4913f65dcba8SDimitry Andric for (const Function &F : M)
4914f65dcba8SDimitry Andric if (!F.isDeclaration())
4915f65dcba8SDimitry Andric writeFunction(F, FunctionToBitcodeIndex);
4916dd58ef01SDimitry Andric
4917dd58ef01SDimitry Andric // Need to write after the above call to WriteFunction which populates
4918dd58ef01SDimitry Andric // the summary information in the index.
491901095a5dSDimitry Andric if (Index)
492001095a5dSDimitry Andric writePerModuleGlobalValueSummary();
4921dd58ef01SDimitry Andric
4922d99dafe2SDimitry Andric writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
492301095a5dSDimitry Andric
4924ac9a064cSDimitry Andric writeModuleHash(Stream.getMarkedBufferAndResumeFlushing());
492563faed5bSDimitry Andric
4926009b1c42SEd Schouten Stream.ExitBlock();
4927009b1c42SEd Schouten }
4928009b1c42SEd Schouten
writeInt32ToBuffer(uint32_t Value,SmallVectorImpl<char> & Buffer,uint32_t & Position)492901095a5dSDimitry Andric static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
493001095a5dSDimitry Andric uint32_t &Position) {
493101095a5dSDimitry Andric support::endian::write32le(&Buffer[Position], Value);
493201095a5dSDimitry Andric Position += 4;
493301095a5dSDimitry Andric }
493401095a5dSDimitry Andric
493501095a5dSDimitry Andric /// If generating a bc file on darwin, we have to emit a
4936009b1c42SEd Schouten /// header and trailer to make it compatible with the system archiver. To do
4937009b1c42SEd Schouten /// this we emit the following header, and then emit a trailer that pads the
4938009b1c42SEd Schouten /// file out to be a multiple of 16 bytes.
4939009b1c42SEd Schouten ///
4940009b1c42SEd Schouten /// struct bc_header {
4941009b1c42SEd Schouten /// uint32_t Magic; // 0x0B17C0DE
4942009b1c42SEd Schouten /// uint32_t Version; // Version, currently always 0.
4943009b1c42SEd Schouten /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
4944009b1c42SEd Schouten /// uint32_t BitcodeSize; // Size of traditional bitcode file.
4945009b1c42SEd Schouten /// uint32_t CPUType; // CPU specifier.
4946009b1c42SEd Schouten /// ... potentially more later ...
4947009b1c42SEd Schouten /// };
emitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> & Buffer,const Triple & TT)494801095a5dSDimitry Andric static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
494963faed5bSDimitry Andric const Triple &TT) {
4950009b1c42SEd Schouten unsigned CPUType = ~0U;
4951009b1c42SEd Schouten
49526fe5c7aaSRoman Divacky // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
49536fe5c7aaSRoman Divacky // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
49546fe5c7aaSRoman Divacky // number from /usr/include/mach/machine.h. It is ok to reproduce the
4955009b1c42SEd Schouten // specific constants here because they are implicitly part of the Darwin ABI.
4956009b1c42SEd Schouten enum {
4957009b1c42SEd Schouten DARWIN_CPU_ARCH_ABI64 = 0x01000000,
4958009b1c42SEd Schouten DARWIN_CPU_TYPE_X86 = 7,
49596fe5c7aaSRoman Divacky DARWIN_CPU_TYPE_ARM = 12,
4960009b1c42SEd Schouten DARWIN_CPU_TYPE_POWERPC = 18
4961009b1c42SEd Schouten };
4962009b1c42SEd Schouten
4963411bd29eSDimitry Andric Triple::ArchType Arch = TT.getArch();
4964411bd29eSDimitry Andric if (Arch == Triple::x86_64)
4965009b1c42SEd Schouten CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
4966411bd29eSDimitry Andric else if (Arch == Triple::x86)
4967009b1c42SEd Schouten CPUType = DARWIN_CPU_TYPE_X86;
4968411bd29eSDimitry Andric else if (Arch == Triple::ppc)
4969009b1c42SEd Schouten CPUType = DARWIN_CPU_TYPE_POWERPC;
4970411bd29eSDimitry Andric else if (Arch == Triple::ppc64)
4971009b1c42SEd Schouten CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
4972411bd29eSDimitry Andric else if (Arch == Triple::arm || Arch == Triple::thumb)
49736fe5c7aaSRoman Divacky CPUType = DARWIN_CPU_TYPE_ARM;
4974009b1c42SEd Schouten
4975009b1c42SEd Schouten // Traditional Bitcode starts after header.
497601095a5dSDimitry Andric assert(Buffer.size() >= BWH_HeaderSize &&
497763faed5bSDimitry Andric "Expected header size to be reserved");
497801095a5dSDimitry Andric unsigned BCOffset = BWH_HeaderSize;
497901095a5dSDimitry Andric unsigned BCSize = Buffer.size() - BWH_HeaderSize;
4980009b1c42SEd Schouten
498163faed5bSDimitry Andric // Write the magic and version.
498263faed5bSDimitry Andric unsigned Position = 0;
498301095a5dSDimitry Andric writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
498401095a5dSDimitry Andric writeInt32ToBuffer(0, Buffer, Position); // Version.
498501095a5dSDimitry Andric writeInt32ToBuffer(BCOffset, Buffer, Position);
498601095a5dSDimitry Andric writeInt32ToBuffer(BCSize, Buffer, Position);
498701095a5dSDimitry Andric writeInt32ToBuffer(CPUType, Buffer, Position);
4988009b1c42SEd Schouten
4989009b1c42SEd Schouten // If the file is not a multiple of 16 bytes, insert dummy padding.
499063faed5bSDimitry Andric while (Buffer.size() & 15)
499163faed5bSDimitry Andric Buffer.push_back(0);
4992009b1c42SEd Schouten }
4993009b1c42SEd Schouten
4994dd58ef01SDimitry Andric /// Helper to write the header common to all bitcode files.
writeBitcodeHeader(BitstreamWriter & Stream)4995b915e9e0SDimitry Andric static void writeBitcodeHeader(BitstreamWriter &Stream) {
4996dd58ef01SDimitry Andric // Emit the file header.
4997dd58ef01SDimitry Andric Stream.Emit((unsigned)'B', 8);
4998dd58ef01SDimitry Andric Stream.Emit((unsigned)'C', 8);
4999dd58ef01SDimitry Andric Stream.Emit(0x0, 4);
5000dd58ef01SDimitry Andric Stream.Emit(0xC, 4);
5001dd58ef01SDimitry Andric Stream.Emit(0xE, 4);
5002dd58ef01SDimitry Andric Stream.Emit(0xD, 4);
5003dd58ef01SDimitry Andric }
5004dd58ef01SDimitry Andric
BitcodeWriter(SmallVectorImpl<char> & Buffer)5005ac9a064cSDimitry Andric BitcodeWriter::BitcodeWriter(SmallVectorImpl<char> &Buffer)
5006ac9a064cSDimitry Andric : Stream(new BitstreamWriter(Buffer)) {
5007ac9a064cSDimitry Andric writeBitcodeHeader(*Stream);
5008ac9a064cSDimitry Andric }
5009ac9a064cSDimitry Andric
BitcodeWriter(raw_ostream & FS)5010ac9a064cSDimitry Andric BitcodeWriter::BitcodeWriter(raw_ostream &FS)
5011ac9a064cSDimitry Andric : Stream(new BitstreamWriter(FS, FlushThreshold)) {
5012b915e9e0SDimitry Andric writeBitcodeHeader(*Stream);
5013b915e9e0SDimitry Andric }
5014b915e9e0SDimitry Andric
~BitcodeWriter()5015d99dafe2SDimitry Andric BitcodeWriter::~BitcodeWriter() { assert(WroteStrtab); }
5016d99dafe2SDimitry Andric
writeBlob(unsigned Block,unsigned Record,StringRef Blob)5017d99dafe2SDimitry Andric void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) {
5018d99dafe2SDimitry Andric Stream->EnterSubblock(Block, 3);
5019d99dafe2SDimitry Andric
5020d99dafe2SDimitry Andric auto Abbv = std::make_shared<BitCodeAbbrev>();
5021d99dafe2SDimitry Andric Abbv->Add(BitCodeAbbrevOp(Record));
5022d99dafe2SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
5023d99dafe2SDimitry Andric auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv));
5024d99dafe2SDimitry Andric
5025d99dafe2SDimitry Andric Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob);
5026d99dafe2SDimitry Andric
5027d99dafe2SDimitry Andric Stream->ExitBlock();
5028d99dafe2SDimitry Andric }
5029d99dafe2SDimitry Andric
writeSymtab()50309df3605dSDimitry Andric void BitcodeWriter::writeSymtab() {
50319df3605dSDimitry Andric assert(!WroteStrtab && !WroteSymtab);
50329df3605dSDimitry Andric
50339df3605dSDimitry Andric // If any module has module-level inline asm, we will require a registered asm
50349df3605dSDimitry Andric // parser for the target so that we can create an accurate symbol table for
50359df3605dSDimitry Andric // the module.
50369df3605dSDimitry Andric for (Module *M : Mods) {
50379df3605dSDimitry Andric if (M->getModuleInlineAsm().empty())
50389df3605dSDimitry Andric continue;
50399df3605dSDimitry Andric
50409df3605dSDimitry Andric std::string Err;
50419df3605dSDimitry Andric const Triple TT(M->getTargetTriple());
50429df3605dSDimitry Andric const Target *T = TargetRegistry::lookupTarget(TT.str(), Err);
50439df3605dSDimitry Andric if (!T || !T->hasMCAsmParser())
50449df3605dSDimitry Andric return;
50459df3605dSDimitry Andric }
50469df3605dSDimitry Andric
50479df3605dSDimitry Andric WroteSymtab = true;
50489df3605dSDimitry Andric SmallVector<char, 0> Symtab;
50499df3605dSDimitry Andric // The irsymtab::build function may be unable to create a symbol table if the
50509df3605dSDimitry Andric // module is malformed (e.g. it contains an invalid alias). Writing a symbol
50519df3605dSDimitry Andric // table is not required for correctness, but we still want to be able to
50529df3605dSDimitry Andric // write malformed modules to bitcode files, so swallow the error.
50539df3605dSDimitry Andric if (Error E = irsymtab::build(Mods, Symtab, StrtabBuilder, Alloc)) {
50549df3605dSDimitry Andric consumeError(std::move(E));
50559df3605dSDimitry Andric return;
50569df3605dSDimitry Andric }
50579df3605dSDimitry Andric
50589df3605dSDimitry Andric writeBlob(bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB,
50599df3605dSDimitry Andric {Symtab.data(), Symtab.size()});
50609df3605dSDimitry Andric }
50619df3605dSDimitry Andric
writeStrtab()5062d99dafe2SDimitry Andric void BitcodeWriter::writeStrtab() {
5063d99dafe2SDimitry Andric assert(!WroteStrtab);
5064d99dafe2SDimitry Andric
5065d99dafe2SDimitry Andric std::vector<char> Strtab;
5066d99dafe2SDimitry Andric StrtabBuilder.finalizeInOrder();
5067d99dafe2SDimitry Andric Strtab.resize(StrtabBuilder.getSize());
5068d99dafe2SDimitry Andric StrtabBuilder.write((uint8_t *)Strtab.data());
5069d99dafe2SDimitry Andric
5070d99dafe2SDimitry Andric writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB,
5071d99dafe2SDimitry Andric {Strtab.data(), Strtab.size()});
5072d99dafe2SDimitry Andric
5073d99dafe2SDimitry Andric WroteStrtab = true;
5074d99dafe2SDimitry Andric }
5075d99dafe2SDimitry Andric
copyStrtab(StringRef Strtab)5076d99dafe2SDimitry Andric void BitcodeWriter::copyStrtab(StringRef Strtab) {
5077d99dafe2SDimitry Andric writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab);
5078d99dafe2SDimitry Andric WroteStrtab = true;
5079d99dafe2SDimitry Andric }
5080b915e9e0SDimitry Andric
writeModule(const Module & M,bool ShouldPreserveUseListOrder,const ModuleSummaryIndex * Index,bool GenerateHash,ModuleHash * ModHash)5081eb11fae6SDimitry Andric void BitcodeWriter::writeModule(const Module &M,
5082b915e9e0SDimitry Andric bool ShouldPreserveUseListOrder,
5083b915e9e0SDimitry Andric const ModuleSummaryIndex *Index,
508471d5a254SDimitry Andric bool GenerateHash, ModuleHash *ModHash) {
50859df3605dSDimitry Andric assert(!WroteStrtab);
50869df3605dSDimitry Andric
50879df3605dSDimitry Andric // The Mods vector is used by irsymtab::build, which requires non-const
50889df3605dSDimitry Andric // Modules in case it needs to materialize metadata. But the bitcode writer
50899df3605dSDimitry Andric // requires that the module is materialized, so we can cast to non-const here,
50909df3605dSDimitry Andric // after checking that it is in fact materialized.
5091eb11fae6SDimitry Andric assert(M.isMaterialized());
5092eb11fae6SDimitry Andric Mods.push_back(const_cast<Module *>(&M));
50939df3605dSDimitry Andric
5094ac9a064cSDimitry Andric ModuleBitcodeWriter ModuleWriter(M, StrtabBuilder, *Stream,
509571d5a254SDimitry Andric ShouldPreserveUseListOrder, Index,
509671d5a254SDimitry Andric GenerateHash, ModHash);
5097b915e9e0SDimitry Andric ModuleWriter.write();
5098b915e9e0SDimitry Andric }
5099b915e9e0SDimitry Andric
writeIndex(const ModuleSummaryIndex * Index,const std::map<std::string,GVSummaryMapTy> * ModuleToSummariesForIndex,const GVSummaryPtrSet * DecSummaries)51007c7aba6eSDimitry Andric void BitcodeWriter::writeIndex(
51017c7aba6eSDimitry Andric const ModuleSummaryIndex *Index,
5102ac9a064cSDimitry Andric const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex,
5103ac9a064cSDimitry Andric const GVSummaryPtrSet *DecSummaries) {
5104ac9a064cSDimitry Andric IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index, DecSummaries,
51057c7aba6eSDimitry Andric ModuleToSummariesForIndex);
51067c7aba6eSDimitry Andric IndexWriter.write();
51077c7aba6eSDimitry Andric }
51087c7aba6eSDimitry Andric
5109eb11fae6SDimitry Andric /// Write the specified module to the specified output stream.
WriteBitcodeToFile(const Module & M,raw_ostream & Out,bool ShouldPreserveUseListOrder,const ModuleSummaryIndex * Index,bool GenerateHash,ModuleHash * ModHash)5110eb11fae6SDimitry Andric void llvm::WriteBitcodeToFile(const Module &M, raw_ostream &Out,
5111dd58ef01SDimitry Andric bool ShouldPreserveUseListOrder,
511201095a5dSDimitry Andric const ModuleSummaryIndex *Index,
511371d5a254SDimitry Andric bool GenerateHash, ModuleHash *ModHash) {
5114ac9a064cSDimitry Andric auto Write = [&](BitcodeWriter &Writer) {
511571d5a254SDimitry Andric Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
511671d5a254SDimitry Andric ModHash);
51179df3605dSDimitry Andric Writer.writeSymtab();
5118d99dafe2SDimitry Andric Writer.writeStrtab();
5119ac9a064cSDimitry Andric };
5120ac9a064cSDimitry Andric Triple TT(M.getTargetTriple());
5121ac9a064cSDimitry Andric if (TT.isOSDarwin() || TT.isOSBinFormatMachO()) {
5122ac9a064cSDimitry Andric // If this is darwin or another generic macho target, reserve space for the
5123ac9a064cSDimitry Andric // header. Note that the header is computed *after* the output is known, so
5124ac9a064cSDimitry Andric // we currently explicitly use a buffer, write to it, and then subsequently
5125ac9a064cSDimitry Andric // flush to Out.
5126ac9a064cSDimitry Andric SmallVector<char, 0> Buffer;
5127ac9a064cSDimitry Andric Buffer.reserve(256 * 1024);
5128ac9a064cSDimitry Andric Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
5129ac9a064cSDimitry Andric BitcodeWriter Writer(Buffer);
5130ac9a064cSDimitry Andric Write(Writer);
513101095a5dSDimitry Andric emitDarwinBCHeaderAndTrailer(Buffer, TT);
5132ac9a064cSDimitry Andric Out.write(Buffer.data(), Buffer.size());
5133ac9a064cSDimitry Andric } else {
5134ac9a064cSDimitry Andric BitcodeWriter Writer(Out);
5135ac9a064cSDimitry Andric Write(Writer);
5136ac9a064cSDimitry Andric }
5137009b1c42SEd Schouten }
5138dd58ef01SDimitry Andric
write()5139b915e9e0SDimitry Andric void IndexBitcodeWriter::write() {
5140dd58ef01SDimitry Andric Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
5141dd58ef01SDimitry Andric
5142d99dafe2SDimitry Andric writeModuleVersion();
5143dd58ef01SDimitry Andric
514401095a5dSDimitry Andric // Write the module paths in the combined index.
514501095a5dSDimitry Andric writeModStrings();
514601095a5dSDimitry Andric
514701095a5dSDimitry Andric // Write the summary combined index records.
514801095a5dSDimitry Andric writeCombinedGlobalValueSummary();
5149dd58ef01SDimitry Andric
5150dd58ef01SDimitry Andric Stream.ExitBlock();
515101095a5dSDimitry Andric }
515201095a5dSDimitry Andric
515301095a5dSDimitry Andric // Write the specified module summary index to the given raw output stream,
515401095a5dSDimitry Andric // where it will be written in a new bitcode block. This is used when
515501095a5dSDimitry Andric // writing the combined index file for ThinLTO. When writing a subset of the
515601095a5dSDimitry Andric // index for a distributed backend, provide a \p ModuleToSummariesForIndex map.
writeIndexToFile(const ModuleSummaryIndex & Index,raw_ostream & Out,const std::map<std::string,GVSummaryMapTy> * ModuleToSummariesForIndex,const GVSummaryPtrSet * DecSummaries)5157ecbca9f5SDimitry Andric void llvm::writeIndexToFile(
515801095a5dSDimitry Andric const ModuleSummaryIndex &Index, raw_ostream &Out,
5159ac9a064cSDimitry Andric const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex,
5160ac9a064cSDimitry Andric const GVSummaryPtrSet *DecSummaries) {
516101095a5dSDimitry Andric SmallVector<char, 0> Buffer;
516201095a5dSDimitry Andric Buffer.reserve(256 * 1024);
516301095a5dSDimitry Andric
51647c7aba6eSDimitry Andric BitcodeWriter Writer(Buffer);
5165ac9a064cSDimitry Andric Writer.writeIndex(&Index, ModuleToSummariesForIndex, DecSummaries);
51667c7aba6eSDimitry Andric Writer.writeStrtab();
5167dd58ef01SDimitry Andric
5168dd58ef01SDimitry Andric Out.write((char *)&Buffer.front(), Buffer.size());
5169dd58ef01SDimitry Andric }
5170044eb2f6SDimitry Andric
5171044eb2f6SDimitry Andric namespace {
5172044eb2f6SDimitry Andric
5173044eb2f6SDimitry Andric /// Class to manage the bitcode writing for a thin link bitcode file.
5174044eb2f6SDimitry Andric class ThinLinkBitcodeWriter : public ModuleBitcodeWriterBase {
5175044eb2f6SDimitry Andric /// ModHash is for use in ThinLTO incremental build, generated while writing
5176044eb2f6SDimitry Andric /// the module bitcode file.
5177044eb2f6SDimitry Andric const ModuleHash *ModHash;
5178044eb2f6SDimitry Andric
5179044eb2f6SDimitry Andric public:
ThinLinkBitcodeWriter(const Module & M,StringTableBuilder & StrtabBuilder,BitstreamWriter & Stream,const ModuleSummaryIndex & Index,const ModuleHash & ModHash)5180eb11fae6SDimitry Andric ThinLinkBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder,
5181044eb2f6SDimitry Andric BitstreamWriter &Stream,
5182044eb2f6SDimitry Andric const ModuleSummaryIndex &Index,
5183044eb2f6SDimitry Andric const ModuleHash &ModHash)
5184044eb2f6SDimitry Andric : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
5185044eb2f6SDimitry Andric /*ShouldPreserveUseListOrder=*/false, &Index),
5186044eb2f6SDimitry Andric ModHash(&ModHash) {}
5187044eb2f6SDimitry Andric
5188044eb2f6SDimitry Andric void write();
5189044eb2f6SDimitry Andric
5190044eb2f6SDimitry Andric private:
5191044eb2f6SDimitry Andric void writeSimplifiedModuleInfo();
5192044eb2f6SDimitry Andric };
5193044eb2f6SDimitry Andric
5194044eb2f6SDimitry Andric } // end anonymous namespace
5195044eb2f6SDimitry Andric
5196044eb2f6SDimitry Andric // This function writes a simpilified module info for thin link bitcode file.
5197044eb2f6SDimitry Andric // It only contains the source file name along with the name(the offset and
5198044eb2f6SDimitry Andric // size in strtab) and linkage for global values. For the global value info
5199044eb2f6SDimitry Andric // entry, in order to keep linkage at offset 5, there are three zeros used
5200044eb2f6SDimitry Andric // as padding.
writeSimplifiedModuleInfo()5201044eb2f6SDimitry Andric void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {
5202044eb2f6SDimitry Andric SmallVector<unsigned, 64> Vals;
5203044eb2f6SDimitry Andric // Emit the module's source file name.
5204044eb2f6SDimitry Andric {
5205044eb2f6SDimitry Andric StringEncoding Bits = getStringEncoding(M.getSourceFileName());
5206044eb2f6SDimitry Andric BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
5207044eb2f6SDimitry Andric if (Bits == SE_Char6)
5208044eb2f6SDimitry Andric AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
5209044eb2f6SDimitry Andric else if (Bits == SE_Fixed7)
5210044eb2f6SDimitry Andric AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
5211044eb2f6SDimitry Andric
5212044eb2f6SDimitry Andric // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
5213044eb2f6SDimitry Andric auto Abbv = std::make_shared<BitCodeAbbrev>();
5214044eb2f6SDimitry Andric Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
5215044eb2f6SDimitry Andric Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5216044eb2f6SDimitry Andric Abbv->Add(AbbrevOpToUse);
5217044eb2f6SDimitry Andric unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5218044eb2f6SDimitry Andric
5219044eb2f6SDimitry Andric for (const auto P : M.getSourceFileName())
5220044eb2f6SDimitry Andric Vals.push_back((unsigned char)P);
5221044eb2f6SDimitry Andric
5222044eb2f6SDimitry Andric Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
5223044eb2f6SDimitry Andric Vals.clear();
5224044eb2f6SDimitry Andric }
5225044eb2f6SDimitry Andric
5226044eb2f6SDimitry Andric // Emit the global variable information.
5227044eb2f6SDimitry Andric for (const GlobalVariable &GV : M.globals()) {
5228044eb2f6SDimitry Andric // GLOBALVAR: [strtab offset, strtab size, 0, 0, 0, linkage]
5229044eb2f6SDimitry Andric Vals.push_back(StrtabBuilder.add(GV.getName()));
5230044eb2f6SDimitry Andric Vals.push_back(GV.getName().size());
5231044eb2f6SDimitry Andric Vals.push_back(0);
5232044eb2f6SDimitry Andric Vals.push_back(0);
5233044eb2f6SDimitry Andric Vals.push_back(0);
5234044eb2f6SDimitry Andric Vals.push_back(getEncodedLinkage(GV));
5235044eb2f6SDimitry Andric
5236044eb2f6SDimitry Andric Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals);
5237044eb2f6SDimitry Andric Vals.clear();
5238044eb2f6SDimitry Andric }
5239044eb2f6SDimitry Andric
5240044eb2f6SDimitry Andric // Emit the function proto information.
5241044eb2f6SDimitry Andric for (const Function &F : M) {
5242044eb2f6SDimitry Andric // FUNCTION: [strtab offset, strtab size, 0, 0, 0, linkage]
5243044eb2f6SDimitry Andric Vals.push_back(StrtabBuilder.add(F.getName()));
5244044eb2f6SDimitry Andric Vals.push_back(F.getName().size());
5245044eb2f6SDimitry Andric Vals.push_back(0);
5246044eb2f6SDimitry Andric Vals.push_back(0);
5247044eb2f6SDimitry Andric Vals.push_back(0);
5248044eb2f6SDimitry Andric Vals.push_back(getEncodedLinkage(F));
5249044eb2f6SDimitry Andric
5250044eb2f6SDimitry Andric Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals);
5251044eb2f6SDimitry Andric Vals.clear();
5252044eb2f6SDimitry Andric }
5253044eb2f6SDimitry Andric
5254044eb2f6SDimitry Andric // Emit the alias information.
5255044eb2f6SDimitry Andric for (const GlobalAlias &A : M.aliases()) {
5256044eb2f6SDimitry Andric // ALIAS: [strtab offset, strtab size, 0, 0, 0, linkage]
5257044eb2f6SDimitry Andric Vals.push_back(StrtabBuilder.add(A.getName()));
5258044eb2f6SDimitry Andric Vals.push_back(A.getName().size());
5259044eb2f6SDimitry Andric Vals.push_back(0);
5260044eb2f6SDimitry Andric Vals.push_back(0);
5261044eb2f6SDimitry Andric Vals.push_back(0);
5262044eb2f6SDimitry Andric Vals.push_back(getEncodedLinkage(A));
5263044eb2f6SDimitry Andric
5264044eb2f6SDimitry Andric Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals);
5265044eb2f6SDimitry Andric Vals.clear();
5266044eb2f6SDimitry Andric }
5267044eb2f6SDimitry Andric
5268044eb2f6SDimitry Andric // Emit the ifunc information.
5269044eb2f6SDimitry Andric for (const GlobalIFunc &I : M.ifuncs()) {
5270044eb2f6SDimitry Andric // IFUNC: [strtab offset, strtab size, 0, 0, 0, linkage]
5271044eb2f6SDimitry Andric Vals.push_back(StrtabBuilder.add(I.getName()));
5272044eb2f6SDimitry Andric Vals.push_back(I.getName().size());
5273044eb2f6SDimitry Andric Vals.push_back(0);
5274044eb2f6SDimitry Andric Vals.push_back(0);
5275044eb2f6SDimitry Andric Vals.push_back(0);
5276044eb2f6SDimitry Andric Vals.push_back(getEncodedLinkage(I));
5277044eb2f6SDimitry Andric
5278044eb2f6SDimitry Andric Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
5279044eb2f6SDimitry Andric Vals.clear();
5280044eb2f6SDimitry Andric }
5281044eb2f6SDimitry Andric }
5282044eb2f6SDimitry Andric
write()5283044eb2f6SDimitry Andric void ThinLinkBitcodeWriter::write() {
5284044eb2f6SDimitry Andric Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
5285044eb2f6SDimitry Andric
5286044eb2f6SDimitry Andric writeModuleVersion();
5287044eb2f6SDimitry Andric
5288044eb2f6SDimitry Andric writeSimplifiedModuleInfo();
5289044eb2f6SDimitry Andric
5290044eb2f6SDimitry Andric writePerModuleGlobalValueSummary();
5291044eb2f6SDimitry Andric
5292044eb2f6SDimitry Andric // Write module hash.
5293044eb2f6SDimitry Andric Stream.EmitRecord(bitc::MODULE_CODE_HASH, ArrayRef<uint32_t>(*ModHash));
5294044eb2f6SDimitry Andric
5295044eb2f6SDimitry Andric Stream.ExitBlock();
5296044eb2f6SDimitry Andric }
5297044eb2f6SDimitry Andric
writeThinLinkBitcode(const Module & M,const ModuleSummaryIndex & Index,const ModuleHash & ModHash)5298eb11fae6SDimitry Andric void BitcodeWriter::writeThinLinkBitcode(const Module &M,
5299044eb2f6SDimitry Andric const ModuleSummaryIndex &Index,
5300044eb2f6SDimitry Andric const ModuleHash &ModHash) {
5301044eb2f6SDimitry Andric assert(!WroteStrtab);
5302044eb2f6SDimitry Andric
5303044eb2f6SDimitry Andric // The Mods vector is used by irsymtab::build, which requires non-const
5304044eb2f6SDimitry Andric // Modules in case it needs to materialize metadata. But the bitcode writer
5305044eb2f6SDimitry Andric // requires that the module is materialized, so we can cast to non-const here,
5306044eb2f6SDimitry Andric // after checking that it is in fact materialized.
5307eb11fae6SDimitry Andric assert(M.isMaterialized());
5308eb11fae6SDimitry Andric Mods.push_back(const_cast<Module *>(&M));
5309044eb2f6SDimitry Andric
5310044eb2f6SDimitry Andric ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index,
5311044eb2f6SDimitry Andric ModHash);
5312044eb2f6SDimitry Andric ThinLinkWriter.write();
5313044eb2f6SDimitry Andric }
5314044eb2f6SDimitry Andric
5315044eb2f6SDimitry Andric // Write the specified thin link bitcode file to the given raw output stream,
5316044eb2f6SDimitry Andric // where it will be written in a new bitcode block. This is used when
5317044eb2f6SDimitry Andric // writing the per-module index file for ThinLTO.
writeThinLinkBitcodeToFile(const Module & M,raw_ostream & Out,const ModuleSummaryIndex & Index,const ModuleHash & ModHash)5318ecbca9f5SDimitry Andric void llvm::writeThinLinkBitcodeToFile(const Module &M, raw_ostream &Out,
5319044eb2f6SDimitry Andric const ModuleSummaryIndex &Index,
5320044eb2f6SDimitry Andric const ModuleHash &ModHash) {
5321044eb2f6SDimitry Andric SmallVector<char, 0> Buffer;
5322044eb2f6SDimitry Andric Buffer.reserve(256 * 1024);
5323044eb2f6SDimitry Andric
5324044eb2f6SDimitry Andric BitcodeWriter Writer(Buffer);
5325044eb2f6SDimitry Andric Writer.writeThinLinkBitcode(M, Index, ModHash);
5326044eb2f6SDimitry Andric Writer.writeSymtab();
5327044eb2f6SDimitry Andric Writer.writeStrtab();
5328044eb2f6SDimitry Andric
5329044eb2f6SDimitry Andric Out.write((char *)&Buffer.front(), Buffer.size());
5330044eb2f6SDimitry Andric }
5331706b4fc4SDimitry Andric
getSectionNameForBitcode(const Triple & T)5332706b4fc4SDimitry Andric static const char *getSectionNameForBitcode(const Triple &T) {
5333706b4fc4SDimitry Andric switch (T.getObjectFormat()) {
5334706b4fc4SDimitry Andric case Triple::MachO:
5335706b4fc4SDimitry Andric return "__LLVM,__bitcode";
5336706b4fc4SDimitry Andric case Triple::COFF:
5337706b4fc4SDimitry Andric case Triple::ELF:
5338706b4fc4SDimitry Andric case Triple::Wasm:
5339706b4fc4SDimitry Andric case Triple::UnknownObjectFormat:
5340706b4fc4SDimitry Andric return ".llvmbc";
5341b60736ecSDimitry Andric case Triple::GOFF:
5342b60736ecSDimitry Andric llvm_unreachable("GOFF is not yet implemented");
5343b60736ecSDimitry Andric break;
5344145449b1SDimitry Andric case Triple::SPIRV:
5345ac9a064cSDimitry Andric if (T.getVendor() == Triple::AMD)
5346ac9a064cSDimitry Andric return ".llvmbc";
5347145449b1SDimitry Andric llvm_unreachable("SPIRV is not yet implemented");
5348145449b1SDimitry Andric break;
5349706b4fc4SDimitry Andric case Triple::XCOFF:
5350706b4fc4SDimitry Andric llvm_unreachable("XCOFF is not yet implemented");
5351706b4fc4SDimitry Andric break;
5352145449b1SDimitry Andric case Triple::DXContainer:
5353145449b1SDimitry Andric llvm_unreachable("DXContainer is not yet implemented");
5354145449b1SDimitry Andric break;
5355706b4fc4SDimitry Andric }
5356706b4fc4SDimitry Andric llvm_unreachable("Unimplemented ObjectFormatType");
5357706b4fc4SDimitry Andric }
5358706b4fc4SDimitry Andric
getSectionNameForCommandline(const Triple & T)5359706b4fc4SDimitry Andric static const char *getSectionNameForCommandline(const Triple &T) {
5360706b4fc4SDimitry Andric switch (T.getObjectFormat()) {
5361706b4fc4SDimitry Andric case Triple::MachO:
5362706b4fc4SDimitry Andric return "__LLVM,__cmdline";
5363706b4fc4SDimitry Andric case Triple::COFF:
5364706b4fc4SDimitry Andric case Triple::ELF:
5365706b4fc4SDimitry Andric case Triple::Wasm:
5366706b4fc4SDimitry Andric case Triple::UnknownObjectFormat:
5367706b4fc4SDimitry Andric return ".llvmcmd";
5368b60736ecSDimitry Andric case Triple::GOFF:
5369b60736ecSDimitry Andric llvm_unreachable("GOFF is not yet implemented");
5370b60736ecSDimitry Andric break;
5371145449b1SDimitry Andric case Triple::SPIRV:
5372ac9a064cSDimitry Andric if (T.getVendor() == Triple::AMD)
5373ac9a064cSDimitry Andric return ".llvmcmd";
5374145449b1SDimitry Andric llvm_unreachable("SPIRV is not yet implemented");
5375145449b1SDimitry Andric break;
5376706b4fc4SDimitry Andric case Triple::XCOFF:
5377706b4fc4SDimitry Andric llvm_unreachable("XCOFF is not yet implemented");
5378706b4fc4SDimitry Andric break;
5379145449b1SDimitry Andric case Triple::DXContainer:
5380145449b1SDimitry Andric llvm_unreachable("DXC is not yet implemented");
5381145449b1SDimitry Andric break;
5382706b4fc4SDimitry Andric }
5383706b4fc4SDimitry Andric llvm_unreachable("Unimplemented ObjectFormatType");
5384706b4fc4SDimitry Andric }
5385706b4fc4SDimitry Andric
embedBitcodeInModule(llvm::Module & M,llvm::MemoryBufferRef Buf,bool EmbedBitcode,bool EmbedCmdline,const std::vector<uint8_t> & CmdArgs)5386ecbca9f5SDimitry Andric void llvm::embedBitcodeInModule(llvm::Module &M, llvm::MemoryBufferRef Buf,
5387b60736ecSDimitry Andric bool EmbedBitcode, bool EmbedCmdline,
5388b60736ecSDimitry Andric const std::vector<uint8_t> &CmdArgs) {
5389706b4fc4SDimitry Andric // Save llvm.compiler.used and remove it.
5390706b4fc4SDimitry Andric SmallVector<Constant *, 2> UsedArray;
5391344a3780SDimitry Andric SmallVector<GlobalValue *, 4> UsedGlobals;
5392b1c73532SDimitry Andric Type *UsedElementType = PointerType::getUnqual(M.getContext());
5393706b4fc4SDimitry Andric GlobalVariable *Used = collectUsedGlobalVariables(M, UsedGlobals, true);
5394706b4fc4SDimitry Andric for (auto *GV : UsedGlobals) {
5395706b4fc4SDimitry Andric if (GV->getName() != "llvm.embedded.module" &&
5396706b4fc4SDimitry Andric GV->getName() != "llvm.cmdline")
5397706b4fc4SDimitry Andric UsedArray.push_back(
5398706b4fc4SDimitry Andric ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
5399706b4fc4SDimitry Andric }
5400706b4fc4SDimitry Andric if (Used)
5401706b4fc4SDimitry Andric Used->eraseFromParent();
5402706b4fc4SDimitry Andric
5403706b4fc4SDimitry Andric // Embed the bitcode for the llvm module.
5404706b4fc4SDimitry Andric std::string Data;
5405706b4fc4SDimitry Andric ArrayRef<uint8_t> ModuleData;
5406706b4fc4SDimitry Andric Triple T(M.getTargetTriple());
5407b60736ecSDimitry Andric
5408706b4fc4SDimitry Andric if (EmbedBitcode) {
5409b60736ecSDimitry Andric if (Buf.getBufferSize() == 0 ||
5410b60736ecSDimitry Andric !isBitcode((const unsigned char *)Buf.getBufferStart(),
5411706b4fc4SDimitry Andric (const unsigned char *)Buf.getBufferEnd())) {
5412706b4fc4SDimitry Andric // If the input is LLVM Assembly, bitcode is produced by serializing
5413706b4fc4SDimitry Andric // the module. Use-lists order need to be preserved in this case.
5414706b4fc4SDimitry Andric llvm::raw_string_ostream OS(Data);
5415706b4fc4SDimitry Andric llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true);
5416706b4fc4SDimitry Andric ModuleData =
5417706b4fc4SDimitry Andric ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
5418706b4fc4SDimitry Andric } else
5419706b4fc4SDimitry Andric // If the input is LLVM bitcode, write the input byte stream directly.
5420706b4fc4SDimitry Andric ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
5421706b4fc4SDimitry Andric Buf.getBufferSize());
5422706b4fc4SDimitry Andric }
5423706b4fc4SDimitry Andric llvm::Constant *ModuleConstant =
5424706b4fc4SDimitry Andric llvm::ConstantDataArray::get(M.getContext(), ModuleData);
5425706b4fc4SDimitry Andric llvm::GlobalVariable *GV = new llvm::GlobalVariable(
5426706b4fc4SDimitry Andric M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
5427706b4fc4SDimitry Andric ModuleConstant);
5428706b4fc4SDimitry Andric GV->setSection(getSectionNameForBitcode(T));
5429b60736ecSDimitry Andric // Set alignment to 1 to prevent padding between two contributions from input
5430b60736ecSDimitry Andric // sections after linking.
5431b60736ecSDimitry Andric GV->setAlignment(Align(1));
5432706b4fc4SDimitry Andric UsedArray.push_back(
5433706b4fc4SDimitry Andric ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
5434706b4fc4SDimitry Andric if (llvm::GlobalVariable *Old =
5435706b4fc4SDimitry Andric M.getGlobalVariable("llvm.embedded.module", true)) {
5436145449b1SDimitry Andric assert(Old->hasZeroLiveUses() &&
5437706b4fc4SDimitry Andric "llvm.embedded.module can only be used once in llvm.compiler.used");
5438706b4fc4SDimitry Andric GV->takeName(Old);
5439706b4fc4SDimitry Andric Old->eraseFromParent();
5440706b4fc4SDimitry Andric } else {
5441706b4fc4SDimitry Andric GV->setName("llvm.embedded.module");
5442706b4fc4SDimitry Andric }
5443706b4fc4SDimitry Andric
5444706b4fc4SDimitry Andric // Skip if only bitcode needs to be embedded.
5445b60736ecSDimitry Andric if (EmbedCmdline) {
5446706b4fc4SDimitry Andric // Embed command-line options.
5447b60736ecSDimitry Andric ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CmdArgs.data()),
5448b60736ecSDimitry Andric CmdArgs.size());
5449706b4fc4SDimitry Andric llvm::Constant *CmdConstant =
5450706b4fc4SDimitry Andric llvm::ConstantDataArray::get(M.getContext(), CmdData);
5451706b4fc4SDimitry Andric GV = new llvm::GlobalVariable(M, CmdConstant->getType(), true,
5452706b4fc4SDimitry Andric llvm::GlobalValue::PrivateLinkage,
5453706b4fc4SDimitry Andric CmdConstant);
5454706b4fc4SDimitry Andric GV->setSection(getSectionNameForCommandline(T));
5455b60736ecSDimitry Andric GV->setAlignment(Align(1));
5456706b4fc4SDimitry Andric UsedArray.push_back(
5457706b4fc4SDimitry Andric ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
5458706b4fc4SDimitry Andric if (llvm::GlobalVariable *Old = M.getGlobalVariable("llvm.cmdline", true)) {
5459145449b1SDimitry Andric assert(Old->hasZeroLiveUses() &&
5460706b4fc4SDimitry Andric "llvm.cmdline can only be used once in llvm.compiler.used");
5461706b4fc4SDimitry Andric GV->takeName(Old);
5462706b4fc4SDimitry Andric Old->eraseFromParent();
5463706b4fc4SDimitry Andric } else {
5464706b4fc4SDimitry Andric GV->setName("llvm.cmdline");
5465706b4fc4SDimitry Andric }
5466706b4fc4SDimitry Andric }
5467706b4fc4SDimitry Andric
5468706b4fc4SDimitry Andric if (UsedArray.empty())
5469706b4fc4SDimitry Andric return;
5470706b4fc4SDimitry Andric
5471706b4fc4SDimitry Andric // Recreate llvm.compiler.used.
5472706b4fc4SDimitry Andric ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
5473706b4fc4SDimitry Andric auto *NewUsed = new GlobalVariable(
5474706b4fc4SDimitry Andric M, ATy, false, llvm::GlobalValue::AppendingLinkage,
5475706b4fc4SDimitry Andric llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
5476706b4fc4SDimitry Andric NewUsed->setSection("llvm.metadata");
5477706b4fc4SDimitry Andric }
5478