[NFCI][WPD]Use unique string saver to store type id (#106932)
[llvm-project.git] / llvm / lib / Bitcode / Writer / BitcodeWriter.cpp
blob59e070a5110620cf0d2ae4448b9e4cc101e6e313
1 //===- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Bitcode writer implementation.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/Bitcode/BitcodeWriter.h"
14 #include "ValueEnumerator.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/StringMap.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/Bitcode/BitcodeCommon.h"
27 #include "llvm/Bitcode/BitcodeReader.h"
28 #include "llvm/Bitcode/LLVMBitCodes.h"
29 #include "llvm/Bitstream/BitCodes.h"
30 #include "llvm/Bitstream/BitstreamWriter.h"
31 #include "llvm/Config/llvm-config.h"
32 #include "llvm/IR/Attributes.h"
33 #include "llvm/IR/BasicBlock.h"
34 #include "llvm/IR/Comdat.h"
35 #include "llvm/IR/Constant.h"
36 #include "llvm/IR/ConstantRangeList.h"
37 #include "llvm/IR/Constants.h"
38 #include "llvm/IR/DebugInfoMetadata.h"
39 #include "llvm/IR/DebugLoc.h"
40 #include "llvm/IR/DerivedTypes.h"
41 #include "llvm/IR/Function.h"
42 #include "llvm/IR/GlobalAlias.h"
43 #include "llvm/IR/GlobalIFunc.h"
44 #include "llvm/IR/GlobalObject.h"
45 #include "llvm/IR/GlobalValue.h"
46 #include "llvm/IR/GlobalVariable.h"
47 #include "llvm/IR/InlineAsm.h"
48 #include "llvm/IR/InstrTypes.h"
49 #include "llvm/IR/Instruction.h"
50 #include "llvm/IR/Instructions.h"
51 #include "llvm/IR/LLVMContext.h"
52 #include "llvm/IR/Metadata.h"
53 #include "llvm/IR/Module.h"
54 #include "llvm/IR/ModuleSummaryIndex.h"
55 #include "llvm/IR/Operator.h"
56 #include "llvm/IR/Type.h"
57 #include "llvm/IR/UseListOrder.h"
58 #include "llvm/IR/Value.h"
59 #include "llvm/IR/ValueSymbolTable.h"
60 #include "llvm/MC/StringTableBuilder.h"
61 #include "llvm/MC/TargetRegistry.h"
62 #include "llvm/Object/IRSymtab.h"
63 #include "llvm/Support/AtomicOrdering.h"
64 #include "llvm/Support/Casting.h"
65 #include "llvm/Support/CommandLine.h"
66 #include "llvm/Support/Endian.h"
67 #include "llvm/Support/Error.h"
68 #include "llvm/Support/ErrorHandling.h"
69 #include "llvm/Support/MathExtras.h"
70 #include "llvm/Support/SHA1.h"
71 #include "llvm/Support/raw_ostream.h"
72 #include "llvm/TargetParser/Triple.h"
73 #include <algorithm>
74 #include <cassert>
75 #include <cstddef>
76 #include <cstdint>
77 #include <iterator>
78 #include <map>
79 #include <memory>
80 #include <optional>
81 #include <string>
82 #include <utility>
83 #include <vector>
85 using namespace llvm;
87 static cl::opt<unsigned>
88 IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25),
89 cl::desc("Number of metadatas above which we emit an index "
90 "to enable lazy-loading"));
91 static cl::opt<uint32_t> FlushThreshold(
92 "bitcode-flush-threshold", cl::Hidden, cl::init(512),
93 cl::desc("The threshold (unit M) for flushing LLVM bitcode."));
95 static cl::opt<bool> WriteRelBFToSummary(
96 "write-relbf-to-summary", cl::Hidden, cl::init(false),
97 cl::desc("Write relative block frequency to function summary "));
99 namespace llvm {
100 extern FunctionSummary::ForceSummaryHotnessType ForceSummaryEdgesCold;
103 extern bool WriteNewDbgInfoFormatToBitcode;
104 extern llvm::cl::opt<bool> UseNewDbgInfoFormat;
106 namespace {
108 /// These are manifest constants used by the bitcode writer. They do not need to
109 /// be kept in sync with the reader, but need to be consistent within this file.
110 enum {
111 // VALUE_SYMTAB_BLOCK abbrev id's.
112 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
113 VST_ENTRY_7_ABBREV,
114 VST_ENTRY_6_ABBREV,
115 VST_BBENTRY_6_ABBREV,
117 // CONSTANTS_BLOCK abbrev id's.
118 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
119 CONSTANTS_INTEGER_ABBREV,
120 CONSTANTS_CE_CAST_Abbrev,
121 CONSTANTS_NULL_Abbrev,
123 // FUNCTION_BLOCK abbrev id's.
124 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
125 FUNCTION_INST_UNOP_ABBREV,
126 FUNCTION_INST_UNOP_FLAGS_ABBREV,
127 FUNCTION_INST_BINOP_ABBREV,
128 FUNCTION_INST_BINOP_FLAGS_ABBREV,
129 FUNCTION_INST_CAST_ABBREV,
130 FUNCTION_INST_CAST_FLAGS_ABBREV,
131 FUNCTION_INST_RET_VOID_ABBREV,
132 FUNCTION_INST_RET_VAL_ABBREV,
133 FUNCTION_INST_UNREACHABLE_ABBREV,
134 FUNCTION_INST_GEP_ABBREV,
135 FUNCTION_DEBUG_RECORD_VALUE_ABBREV,
138 /// Abstract class to manage the bitcode writing, subclassed for each bitcode
139 /// file type.
140 class BitcodeWriterBase {
141 protected:
142 /// The stream created and owned by the client.
143 BitstreamWriter &Stream;
145 StringTableBuilder &StrtabBuilder;
147 public:
148 /// Constructs a BitcodeWriterBase object that writes to the provided
149 /// \p Stream.
150 BitcodeWriterBase(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder)
151 : Stream(Stream), StrtabBuilder(StrtabBuilder) {}
153 protected:
154 void writeModuleVersion();
157 void BitcodeWriterBase::writeModuleVersion() {
158 // VERSION: [version#]
159 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, ArrayRef<uint64_t>{2});
162 /// Base class to manage the module bitcode writing, currently subclassed for
163 /// ModuleBitcodeWriter and ThinLinkBitcodeWriter.
164 class ModuleBitcodeWriterBase : public BitcodeWriterBase {
165 protected:
166 /// The Module to write to bitcode.
167 const Module &M;
169 /// Enumerates ids for all values in the module.
170 ValueEnumerator VE;
172 /// Optional per-module index to write for ThinLTO.
173 const ModuleSummaryIndex *Index;
175 /// Map that holds the correspondence between GUIDs in the summary index,
176 /// that came from indirect call profiles, and a value id generated by this
177 /// class to use in the VST and summary block records.
178 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
180 /// Tracks the last value id recorded in the GUIDToValueMap.
181 unsigned GlobalValueId;
183 /// Saves the offset of the VSTOffset record that must eventually be
184 /// backpatched with the offset of the actual VST.
185 uint64_t VSTOffsetPlaceholder = 0;
187 public:
188 /// Constructs a ModuleBitcodeWriterBase object for the given Module,
189 /// writing to the provided \p Buffer.
190 ModuleBitcodeWriterBase(const Module &M, StringTableBuilder &StrtabBuilder,
191 BitstreamWriter &Stream,
192 bool ShouldPreserveUseListOrder,
193 const ModuleSummaryIndex *Index)
194 : BitcodeWriterBase(Stream, StrtabBuilder), M(M),
195 VE(M, ShouldPreserveUseListOrder), Index(Index) {
196 // Assign ValueIds to any callee values in the index that came from
197 // indirect call profiles and were recorded as a GUID not a Value*
198 // (which would have been assigned an ID by the ValueEnumerator).
199 // The starting ValueId is just after the number of values in the
200 // ValueEnumerator, so that they can be emitted in the VST.
201 GlobalValueId = VE.getValues().size();
202 if (!Index)
203 return;
204 for (const auto &GUIDSummaryLists : *Index)
205 // Examine all summaries for this GUID.
206 for (auto &Summary : GUIDSummaryLists.second.SummaryList)
207 if (auto FS = dyn_cast<FunctionSummary>(Summary.get())) {
208 // For each call in the function summary, see if the call
209 // is to a GUID (which means it is for an indirect call,
210 // otherwise we would have a Value for it). If so, synthesize
211 // a value id.
212 for (auto &CallEdge : FS->calls())
213 if (!CallEdge.first.haveGVs() || !CallEdge.first.getValue())
214 assignValueId(CallEdge.first.getGUID());
216 // For each referenced variables in the function summary, see if the
217 // variable is represented by a GUID (as opposed to a symbol to
218 // declarations or definitions in the module). If so, synthesize a
219 // value id.
220 for (auto &RefEdge : FS->refs())
221 if (!RefEdge.haveGVs() || !RefEdge.getValue())
222 assignValueId(RefEdge.getGUID());
226 protected:
227 void writePerModuleGlobalValueSummary();
229 private:
230 void writePerModuleFunctionSummaryRecord(
231 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
232 unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
233 unsigned CallsiteAbbrev, unsigned AllocAbbrev, unsigned ContextIdAbbvId,
234 const Function &F);
235 void writeModuleLevelReferences(const GlobalVariable &V,
236 SmallVector<uint64_t, 64> &NameVals,
237 unsigned FSModRefsAbbrev,
238 unsigned FSModVTableRefsAbbrev);
240 void assignValueId(GlobalValue::GUID ValGUID) {
241 GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
244 unsigned getValueId(GlobalValue::GUID ValGUID) {
245 const auto &VMI = GUIDToValueIdMap.find(ValGUID);
246 // Expect that any GUID value had a value Id assigned by an
247 // earlier call to assignValueId.
248 assert(VMI != GUIDToValueIdMap.end() &&
249 "GUID does not have assigned value Id");
250 return VMI->second;
253 // Helper to get the valueId for the type of value recorded in VI.
254 unsigned getValueId(ValueInfo VI) {
255 if (!VI.haveGVs() || !VI.getValue())
256 return getValueId(VI.getGUID());
257 return VE.getValueID(VI.getValue());
260 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
263 /// Class to manage the bitcode writing for a module.
264 class ModuleBitcodeWriter : public ModuleBitcodeWriterBase {
265 /// True if a module hash record should be written.
266 bool GenerateHash;
268 /// If non-null, when GenerateHash is true, the resulting hash is written
269 /// into ModHash.
270 ModuleHash *ModHash;
272 SHA1 Hasher;
274 /// The start bit of the identification block.
275 uint64_t BitcodeStartBit;
277 public:
278 /// Constructs a ModuleBitcodeWriter object for the given Module,
279 /// writing to the provided \p Buffer.
280 ModuleBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder,
281 BitstreamWriter &Stream, bool ShouldPreserveUseListOrder,
282 const ModuleSummaryIndex *Index, bool GenerateHash,
283 ModuleHash *ModHash = nullptr)
284 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
285 ShouldPreserveUseListOrder, Index),
286 GenerateHash(GenerateHash), ModHash(ModHash),
287 BitcodeStartBit(Stream.GetCurrentBitNo()) {}
289 /// Emit the current module to the bitstream.
290 void write();
292 private:
293 uint64_t bitcodeStartBit() { return BitcodeStartBit; }
295 size_t addToStrtab(StringRef Str);
297 void writeAttributeGroupTable();
298 void writeAttributeTable();
299 void writeTypeTable();
300 void writeComdats();
301 void writeValueSymbolTableForwardDecl();
302 void writeModuleInfo();
303 void writeValueAsMetadata(const ValueAsMetadata *MD,
304 SmallVectorImpl<uint64_t> &Record);
305 void writeMDTuple(const MDTuple *N, SmallVectorImpl<uint64_t> &Record,
306 unsigned Abbrev);
307 unsigned createDILocationAbbrev();
308 void writeDILocation(const DILocation *N, SmallVectorImpl<uint64_t> &Record,
309 unsigned &Abbrev);
310 unsigned createGenericDINodeAbbrev();
311 void writeGenericDINode(const GenericDINode *N,
312 SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev);
313 void writeDISubrange(const DISubrange *N, SmallVectorImpl<uint64_t> &Record,
314 unsigned Abbrev);
315 void writeDIGenericSubrange(const DIGenericSubrange *N,
316 SmallVectorImpl<uint64_t> &Record,
317 unsigned Abbrev);
318 void writeDIEnumerator(const DIEnumerator *N,
319 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
320 void writeDIBasicType(const DIBasicType *N, SmallVectorImpl<uint64_t> &Record,
321 unsigned Abbrev);
322 void writeDIStringType(const DIStringType *N,
323 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
324 void writeDIDerivedType(const DIDerivedType *N,
325 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
326 void writeDICompositeType(const DICompositeType *N,
327 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
328 void writeDISubroutineType(const DISubroutineType *N,
329 SmallVectorImpl<uint64_t> &Record,
330 unsigned Abbrev);
331 void writeDIFile(const DIFile *N, SmallVectorImpl<uint64_t> &Record,
332 unsigned Abbrev);
333 void writeDICompileUnit(const DICompileUnit *N,
334 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
335 void writeDISubprogram(const DISubprogram *N,
336 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
337 void writeDILexicalBlock(const DILexicalBlock *N,
338 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
339 void writeDILexicalBlockFile(const DILexicalBlockFile *N,
340 SmallVectorImpl<uint64_t> &Record,
341 unsigned Abbrev);
342 void writeDICommonBlock(const DICommonBlock *N,
343 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
344 void writeDINamespace(const DINamespace *N, SmallVectorImpl<uint64_t> &Record,
345 unsigned Abbrev);
346 void writeDIMacro(const DIMacro *N, SmallVectorImpl<uint64_t> &Record,
347 unsigned Abbrev);
348 void writeDIMacroFile(const DIMacroFile *N, SmallVectorImpl<uint64_t> &Record,
349 unsigned Abbrev);
350 void writeDIArgList(const DIArgList *N, SmallVectorImpl<uint64_t> &Record);
351 void writeDIModule(const DIModule *N, SmallVectorImpl<uint64_t> &Record,
352 unsigned Abbrev);
353 void writeDIAssignID(const DIAssignID *N, SmallVectorImpl<uint64_t> &Record,
354 unsigned Abbrev);
355 void writeDITemplateTypeParameter(const DITemplateTypeParameter *N,
356 SmallVectorImpl<uint64_t> &Record,
357 unsigned Abbrev);
358 void writeDITemplateValueParameter(const DITemplateValueParameter *N,
359 SmallVectorImpl<uint64_t> &Record,
360 unsigned Abbrev);
361 void writeDIGlobalVariable(const DIGlobalVariable *N,
362 SmallVectorImpl<uint64_t> &Record,
363 unsigned Abbrev);
364 void writeDILocalVariable(const DILocalVariable *N,
365 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
366 void writeDILabel(const DILabel *N,
367 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
368 void writeDIExpression(const DIExpression *N,
369 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
370 void writeDIGlobalVariableExpression(const DIGlobalVariableExpression *N,
371 SmallVectorImpl<uint64_t> &Record,
372 unsigned Abbrev);
373 void writeDIObjCProperty(const DIObjCProperty *N,
374 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
375 void writeDIImportedEntity(const DIImportedEntity *N,
376 SmallVectorImpl<uint64_t> &Record,
377 unsigned Abbrev);
378 unsigned createNamedMetadataAbbrev();
379 void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
380 unsigned createMetadataStringsAbbrev();
381 void writeMetadataStrings(ArrayRef<const Metadata *> Strings,
382 SmallVectorImpl<uint64_t> &Record);
383 void writeMetadataRecords(ArrayRef<const Metadata *> MDs,
384 SmallVectorImpl<uint64_t> &Record,
385 std::vector<unsigned> *MDAbbrevs = nullptr,
386 std::vector<uint64_t> *IndexPos = nullptr);
387 void writeModuleMetadata();
388 void writeFunctionMetadata(const Function &F);
389 void writeFunctionMetadataAttachment(const Function &F);
390 void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
391 const GlobalObject &GO);
392 void writeModuleMetadataKinds();
393 void writeOperandBundleTags();
394 void writeSyncScopeNames();
395 void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal);
396 void writeModuleConstants();
397 bool pushValueAndType(const Value *V, unsigned InstID,
398 SmallVectorImpl<unsigned> &Vals);
399 bool pushValueOrMetadata(const Value *V, unsigned InstID,
400 SmallVectorImpl<unsigned> &Vals);
401 void writeOperandBundles(const CallBase &CB, unsigned InstID);
402 void pushValue(const Value *V, unsigned InstID,
403 SmallVectorImpl<unsigned> &Vals);
404 void pushValueSigned(const Value *V, unsigned InstID,
405 SmallVectorImpl<uint64_t> &Vals);
406 void writeInstruction(const Instruction &I, unsigned InstID,
407 SmallVectorImpl<unsigned> &Vals);
408 void writeFunctionLevelValueSymbolTable(const ValueSymbolTable &VST);
409 void writeGlobalValueSymbolTable(
410 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
411 void writeUseList(UseListOrder &&Order);
412 void writeUseListBlock(const Function *F);
413 void
414 writeFunction(const Function &F,
415 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
416 void writeBlockInfo();
417 void writeModuleHash(StringRef View);
419 unsigned getEncodedSyncScopeID(SyncScope::ID SSID) {
420 return unsigned(SSID);
423 unsigned getEncodedAlign(MaybeAlign Alignment) { return encode(Alignment); }
426 /// Class to manage the bitcode writing for a combined index.
427 class IndexBitcodeWriter : public BitcodeWriterBase {
428 /// The combined index to write to bitcode.
429 const ModuleSummaryIndex &Index;
431 /// When writing combined summaries, provides the set of global value
432 /// summaries for which the value (function, function alias, etc) should be
433 /// imported as a declaration.
434 const GVSummaryPtrSet *DecSummaries = nullptr;
436 /// When writing a subset of the index for distributed backends, client
437 /// provides a map of modules to the corresponding GUIDs/summaries to write.
438 const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex;
440 /// Map that holds the correspondence between the GUID used in the combined
441 /// index and a value id generated by this class to use in references.
442 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
444 // The stack ids used by this index, which will be a subset of those in
445 // the full index in the case of distributed indexes.
446 std::vector<uint64_t> StackIds;
448 // Keep a map of the stack id indices used by records being written for this
449 // index to the index of the corresponding stack id in the above StackIds
450 // vector. Ensures we write each referenced stack id once.
451 DenseMap<unsigned, unsigned> StackIdIndicesToIndex;
453 /// Tracks the last value id recorded in the GUIDToValueMap.
454 unsigned GlobalValueId = 0;
456 /// Tracks the assignment of module paths in the module path string table to
457 /// an id assigned for use in summary references to the module path.
458 DenseMap<StringRef, uint64_t> ModuleIdMap;
460 public:
461 /// Constructs a IndexBitcodeWriter object for the given combined index,
462 /// writing to the provided \p Buffer. When writing a subset of the index
463 /// for a distributed backend, provide a \p ModuleToSummariesForIndex map.
464 /// If provided, \p DecSummaries specifies the set of summaries for which
465 /// the corresponding functions or aliased functions should be imported as a
466 /// declaration (but not definition) for each module.
467 IndexBitcodeWriter(
468 BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder,
469 const ModuleSummaryIndex &Index,
470 const GVSummaryPtrSet *DecSummaries = nullptr,
471 const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex = nullptr)
472 : BitcodeWriterBase(Stream, StrtabBuilder), Index(Index),
473 DecSummaries(DecSummaries),
474 ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
476 // See if the StackIdIndex was already added to the StackId map and
477 // vector. If not, record it.
478 auto RecordStackIdReference = [&](unsigned StackIdIndex) {
479 // If the StackIdIndex is not yet in the map, the below insert ensures
480 // that it will point to the new StackIds vector entry we push to just
481 // below.
482 auto Inserted =
483 StackIdIndicesToIndex.insert({StackIdIndex, StackIds.size()});
484 if (Inserted.second)
485 StackIds.push_back(Index.getStackIdAtIndex(StackIdIndex));
488 // Assign unique value ids to all summaries to be written, for use
489 // in writing out the call graph edges. Save the mapping from GUID
490 // to the new global value id to use when writing those edges, which
491 // are currently saved in the index in terms of GUID.
492 forEachSummary([&](GVInfo I, bool IsAliasee) {
493 GUIDToValueIdMap[I.first] = ++GlobalValueId;
494 if (IsAliasee)
495 return;
496 auto *FS = dyn_cast<FunctionSummary>(I.second);
497 if (!FS)
498 return;
499 // Record all stack id indices actually used in the summary entries being
500 // written, so that we can compact them in the case of distributed ThinLTO
501 // indexes.
502 for (auto &CI : FS->callsites()) {
503 // If the stack id list is empty, this callsite info was synthesized for
504 // a missing tail call frame. Ensure that the callee's GUID gets a value
505 // id. Normally we only generate these for defined summaries, which in
506 // the case of distributed ThinLTO is only the functions already defined
507 // in the module or that we want to import. We don't bother to include
508 // all the callee symbols as they aren't normally needed in the backend.
509 // However, for the synthesized callsite infos we do need the callee
510 // GUID in the backend so that we can correlate the identified callee
511 // with this callsite info (which for non-tail calls is done by the
512 // ordering of the callsite infos and verified via stack ids).
513 if (CI.StackIdIndices.empty()) {
514 GUIDToValueIdMap[CI.Callee.getGUID()] = ++GlobalValueId;
515 continue;
517 for (auto Idx : CI.StackIdIndices)
518 RecordStackIdReference(Idx);
520 for (auto &AI : FS->allocs())
521 for (auto &MIB : AI.MIBs)
522 for (auto Idx : MIB.StackIdIndices)
523 RecordStackIdReference(Idx);
527 /// The below iterator returns the GUID and associated summary.
528 using GVInfo = std::pair<GlobalValue::GUID, GlobalValueSummary *>;
530 /// Calls the callback for each value GUID and summary to be written to
531 /// bitcode. This hides the details of whether they are being pulled from the
532 /// entire index or just those in a provided ModuleToSummariesForIndex map.
533 template<typename Functor>
534 void forEachSummary(Functor Callback) {
535 if (ModuleToSummariesForIndex) {
536 for (auto &M : *ModuleToSummariesForIndex)
537 for (auto &Summary : M.second) {
538 Callback(Summary, false);
539 // Ensure aliasee is handled, e.g. for assigning a valueId,
540 // even if we are not importing the aliasee directly (the
541 // imported alias will contain a copy of aliasee).
542 if (auto *AS = dyn_cast<AliasSummary>(Summary.getSecond()))
543 Callback({AS->getAliaseeGUID(), &AS->getAliasee()}, true);
545 } else {
546 for (auto &Summaries : Index)
547 for (auto &Summary : Summaries.second.SummaryList)
548 Callback({Summaries.first, Summary.get()}, false);
552 /// Calls the callback for each entry in the modulePaths StringMap that
553 /// should be written to the module path string table. This hides the details
554 /// of whether they are being pulled from the entire index or just those in a
555 /// provided ModuleToSummariesForIndex map.
556 template <typename Functor> void forEachModule(Functor Callback) {
557 if (ModuleToSummariesForIndex) {
558 for (const auto &M : *ModuleToSummariesForIndex) {
559 const auto &MPI = Index.modulePaths().find(M.first);
560 if (MPI == Index.modulePaths().end()) {
561 // This should only happen if the bitcode file was empty, in which
562 // case we shouldn't be importing (the ModuleToSummariesForIndex
563 // would only include the module we are writing and index for).
564 assert(ModuleToSummariesForIndex->size() == 1);
565 continue;
567 Callback(*MPI);
569 } else {
570 // Since StringMap iteration order isn't guaranteed, order by path string
571 // first.
572 // FIXME: Make this a vector of StringMapEntry instead to avoid the later
573 // map lookup.
574 std::vector<StringRef> ModulePaths;
575 for (auto &[ModPath, _] : Index.modulePaths())
576 ModulePaths.push_back(ModPath);
577 llvm::sort(ModulePaths.begin(), ModulePaths.end());
578 for (auto &ModPath : ModulePaths)
579 Callback(*Index.modulePaths().find(ModPath));
583 /// Main entry point for writing a combined index to bitcode.
584 void write();
586 private:
587 void writeModStrings();
588 void writeCombinedGlobalValueSummary();
590 std::optional<unsigned> getValueId(GlobalValue::GUID ValGUID) {
591 auto VMI = GUIDToValueIdMap.find(ValGUID);
592 if (VMI == GUIDToValueIdMap.end())
593 return std::nullopt;
594 return VMI->second;
597 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
600 } // end anonymous namespace
602 static unsigned getEncodedCastOpcode(unsigned Opcode) {
603 switch (Opcode) {
604 default: llvm_unreachable("Unknown cast instruction!");
605 case Instruction::Trunc : return bitc::CAST_TRUNC;
606 case Instruction::ZExt : return bitc::CAST_ZEXT;
607 case Instruction::SExt : return bitc::CAST_SEXT;
608 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
609 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
610 case Instruction::UIToFP : return bitc::CAST_UITOFP;
611 case Instruction::SIToFP : return bitc::CAST_SITOFP;
612 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
613 case Instruction::FPExt : return bitc::CAST_FPEXT;
614 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
615 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
616 case Instruction::BitCast : return bitc::CAST_BITCAST;
617 case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
621 static unsigned getEncodedUnaryOpcode(unsigned Opcode) {
622 switch (Opcode) {
623 default: llvm_unreachable("Unknown binary instruction!");
624 case Instruction::FNeg: return bitc::UNOP_FNEG;
628 static unsigned getEncodedBinaryOpcode(unsigned Opcode) {
629 switch (Opcode) {
630 default: llvm_unreachable("Unknown binary instruction!");
631 case Instruction::Add:
632 case Instruction::FAdd: return bitc::BINOP_ADD;
633 case Instruction::Sub:
634 case Instruction::FSub: return bitc::BINOP_SUB;
635 case Instruction::Mul:
636 case Instruction::FMul: return bitc::BINOP_MUL;
637 case Instruction::UDiv: return bitc::BINOP_UDIV;
638 case Instruction::FDiv:
639 case Instruction::SDiv: return bitc::BINOP_SDIV;
640 case Instruction::URem: return bitc::BINOP_UREM;
641 case Instruction::FRem:
642 case Instruction::SRem: return bitc::BINOP_SREM;
643 case Instruction::Shl: return bitc::BINOP_SHL;
644 case Instruction::LShr: return bitc::BINOP_LSHR;
645 case Instruction::AShr: return bitc::BINOP_ASHR;
646 case Instruction::And: return bitc::BINOP_AND;
647 case Instruction::Or: return bitc::BINOP_OR;
648 case Instruction::Xor: return bitc::BINOP_XOR;
652 static unsigned getEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
653 switch (Op) {
654 default: llvm_unreachable("Unknown RMW operation!");
655 case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
656 case AtomicRMWInst::Add: return bitc::RMW_ADD;
657 case AtomicRMWInst::Sub: return bitc::RMW_SUB;
658 case AtomicRMWInst::And: return bitc::RMW_AND;
659 case AtomicRMWInst::Nand: return bitc::RMW_NAND;
660 case AtomicRMWInst::Or: return bitc::RMW_OR;
661 case AtomicRMWInst::Xor: return bitc::RMW_XOR;
662 case AtomicRMWInst::Max: return bitc::RMW_MAX;
663 case AtomicRMWInst::Min: return bitc::RMW_MIN;
664 case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
665 case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
666 case AtomicRMWInst::FAdd: return bitc::RMW_FADD;
667 case AtomicRMWInst::FSub: return bitc::RMW_FSUB;
668 case AtomicRMWInst::FMax: return bitc::RMW_FMAX;
669 case AtomicRMWInst::FMin: return bitc::RMW_FMIN;
670 case AtomicRMWInst::UIncWrap:
671 return bitc::RMW_UINC_WRAP;
672 case AtomicRMWInst::UDecWrap:
673 return bitc::RMW_UDEC_WRAP;
674 case AtomicRMWInst::USubCond:
675 return bitc::RMW_USUB_COND;
676 case AtomicRMWInst::USubSat:
677 return bitc::RMW_USUB_SAT;
681 static unsigned getEncodedOrdering(AtomicOrdering Ordering) {
682 switch (Ordering) {
683 case AtomicOrdering::NotAtomic: return bitc::ORDERING_NOTATOMIC;
684 case AtomicOrdering::Unordered: return bitc::ORDERING_UNORDERED;
685 case AtomicOrdering::Monotonic: return bitc::ORDERING_MONOTONIC;
686 case AtomicOrdering::Acquire: return bitc::ORDERING_ACQUIRE;
687 case AtomicOrdering::Release: return bitc::ORDERING_RELEASE;
688 case AtomicOrdering::AcquireRelease: return bitc::ORDERING_ACQREL;
689 case AtomicOrdering::SequentiallyConsistent: return bitc::ORDERING_SEQCST;
691 llvm_unreachable("Invalid ordering");
694 static void writeStringRecord(BitstreamWriter &Stream, unsigned Code,
695 StringRef Str, unsigned AbbrevToUse) {
696 SmallVector<unsigned, 64> Vals;
698 // Code: [strchar x N]
699 for (char C : Str) {
700 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(C))
701 AbbrevToUse = 0;
702 Vals.push_back(C);
705 // Emit the finished record.
706 Stream.EmitRecord(Code, Vals, AbbrevToUse);
709 static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
710 switch (Kind) {
711 case Attribute::Alignment:
712 return bitc::ATTR_KIND_ALIGNMENT;
713 case Attribute::AllocAlign:
714 return bitc::ATTR_KIND_ALLOC_ALIGN;
715 case Attribute::AllocSize:
716 return bitc::ATTR_KIND_ALLOC_SIZE;
717 case Attribute::AlwaysInline:
718 return bitc::ATTR_KIND_ALWAYS_INLINE;
719 case Attribute::Builtin:
720 return bitc::ATTR_KIND_BUILTIN;
721 case Attribute::ByVal:
722 return bitc::ATTR_KIND_BY_VAL;
723 case Attribute::Convergent:
724 return bitc::ATTR_KIND_CONVERGENT;
725 case Attribute::InAlloca:
726 return bitc::ATTR_KIND_IN_ALLOCA;
727 case Attribute::Cold:
728 return bitc::ATTR_KIND_COLD;
729 case Attribute::DisableSanitizerInstrumentation:
730 return bitc::ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION;
731 case Attribute::FnRetThunkExtern:
732 return bitc::ATTR_KIND_FNRETTHUNK_EXTERN;
733 case Attribute::Hot:
734 return bitc::ATTR_KIND_HOT;
735 case Attribute::ElementType:
736 return bitc::ATTR_KIND_ELEMENTTYPE;
737 case Attribute::HybridPatchable:
738 return bitc::ATTR_KIND_HYBRID_PATCHABLE;
739 case Attribute::InlineHint:
740 return bitc::ATTR_KIND_INLINE_HINT;
741 case Attribute::InReg:
742 return bitc::ATTR_KIND_IN_REG;
743 case Attribute::JumpTable:
744 return bitc::ATTR_KIND_JUMP_TABLE;
745 case Attribute::MinSize:
746 return bitc::ATTR_KIND_MIN_SIZE;
747 case Attribute::AllocatedPointer:
748 return bitc::ATTR_KIND_ALLOCATED_POINTER;
749 case Attribute::AllocKind:
750 return bitc::ATTR_KIND_ALLOC_KIND;
751 case Attribute::Memory:
752 return bitc::ATTR_KIND_MEMORY;
753 case Attribute::NoFPClass:
754 return bitc::ATTR_KIND_NOFPCLASS;
755 case Attribute::Naked:
756 return bitc::ATTR_KIND_NAKED;
757 case Attribute::Nest:
758 return bitc::ATTR_KIND_NEST;
759 case Attribute::NoAlias:
760 return bitc::ATTR_KIND_NO_ALIAS;
761 case Attribute::NoBuiltin:
762 return bitc::ATTR_KIND_NO_BUILTIN;
763 case Attribute::NoCallback:
764 return bitc::ATTR_KIND_NO_CALLBACK;
765 case Attribute::NoCapture:
766 return bitc::ATTR_KIND_NO_CAPTURE;
767 case Attribute::NoDivergenceSource:
768 return bitc::ATTR_KIND_NO_DIVERGENCE_SOURCE;
769 case Attribute::NoDuplicate:
770 return bitc::ATTR_KIND_NO_DUPLICATE;
771 case Attribute::NoFree:
772 return bitc::ATTR_KIND_NOFREE;
773 case Attribute::NoImplicitFloat:
774 return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
775 case Attribute::NoInline:
776 return bitc::ATTR_KIND_NO_INLINE;
777 case Attribute::NoRecurse:
778 return bitc::ATTR_KIND_NO_RECURSE;
779 case Attribute::NoMerge:
780 return bitc::ATTR_KIND_NO_MERGE;
781 case Attribute::NonLazyBind:
782 return bitc::ATTR_KIND_NON_LAZY_BIND;
783 case Attribute::NonNull:
784 return bitc::ATTR_KIND_NON_NULL;
785 case Attribute::Dereferenceable:
786 return bitc::ATTR_KIND_DEREFERENCEABLE;
787 case Attribute::DereferenceableOrNull:
788 return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL;
789 case Attribute::NoRedZone:
790 return bitc::ATTR_KIND_NO_RED_ZONE;
791 case Attribute::NoReturn:
792 return bitc::ATTR_KIND_NO_RETURN;
793 case Attribute::NoSync:
794 return bitc::ATTR_KIND_NOSYNC;
795 case Attribute::NoCfCheck:
796 return bitc::ATTR_KIND_NOCF_CHECK;
797 case Attribute::NoProfile:
798 return bitc::ATTR_KIND_NO_PROFILE;
799 case Attribute::SkipProfile:
800 return bitc::ATTR_KIND_SKIP_PROFILE;
801 case Attribute::NoUnwind:
802 return bitc::ATTR_KIND_NO_UNWIND;
803 case Attribute::NoSanitizeBounds:
804 return bitc::ATTR_KIND_NO_SANITIZE_BOUNDS;
805 case Attribute::NoSanitizeCoverage:
806 return bitc::ATTR_KIND_NO_SANITIZE_COVERAGE;
807 case Attribute::NullPointerIsValid:
808 return bitc::ATTR_KIND_NULL_POINTER_IS_VALID;
809 case Attribute::OptimizeForDebugging:
810 return bitc::ATTR_KIND_OPTIMIZE_FOR_DEBUGGING;
811 case Attribute::OptForFuzzing:
812 return bitc::ATTR_KIND_OPT_FOR_FUZZING;
813 case Attribute::OptimizeForSize:
814 return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
815 case Attribute::OptimizeNone:
816 return bitc::ATTR_KIND_OPTIMIZE_NONE;
817 case Attribute::ReadNone:
818 return bitc::ATTR_KIND_READ_NONE;
819 case Attribute::ReadOnly:
820 return bitc::ATTR_KIND_READ_ONLY;
821 case Attribute::Returned:
822 return bitc::ATTR_KIND_RETURNED;
823 case Attribute::ReturnsTwice:
824 return bitc::ATTR_KIND_RETURNS_TWICE;
825 case Attribute::SExt:
826 return bitc::ATTR_KIND_S_EXT;
827 case Attribute::Speculatable:
828 return bitc::ATTR_KIND_SPECULATABLE;
829 case Attribute::StackAlignment:
830 return bitc::ATTR_KIND_STACK_ALIGNMENT;
831 case Attribute::StackProtect:
832 return bitc::ATTR_KIND_STACK_PROTECT;
833 case Attribute::StackProtectReq:
834 return bitc::ATTR_KIND_STACK_PROTECT_REQ;
835 case Attribute::StackProtectStrong:
836 return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
837 case Attribute::SafeStack:
838 return bitc::ATTR_KIND_SAFESTACK;
839 case Attribute::ShadowCallStack:
840 return bitc::ATTR_KIND_SHADOWCALLSTACK;
841 case Attribute::StrictFP:
842 return bitc::ATTR_KIND_STRICT_FP;
843 case Attribute::StructRet:
844 return bitc::ATTR_KIND_STRUCT_RET;
845 case Attribute::SanitizeAddress:
846 return bitc::ATTR_KIND_SANITIZE_ADDRESS;
847 case Attribute::SanitizeHWAddress:
848 return bitc::ATTR_KIND_SANITIZE_HWADDRESS;
849 case Attribute::SanitizeThread:
850 return bitc::ATTR_KIND_SANITIZE_THREAD;
851 case Attribute::SanitizeMemory:
852 return bitc::ATTR_KIND_SANITIZE_MEMORY;
853 case Attribute::SanitizeNumericalStability:
854 return bitc::ATTR_KIND_SANITIZE_NUMERICAL_STABILITY;
855 case Attribute::SanitizeRealtime:
856 return bitc::ATTR_KIND_SANITIZE_REALTIME;
857 case Attribute::SanitizeRealtimeBlocking:
858 return bitc::ATTR_KIND_SANITIZE_REALTIME_BLOCKING;
859 case Attribute::SpeculativeLoadHardening:
860 return bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING;
861 case Attribute::SwiftError:
862 return bitc::ATTR_KIND_SWIFT_ERROR;
863 case Attribute::SwiftSelf:
864 return bitc::ATTR_KIND_SWIFT_SELF;
865 case Attribute::SwiftAsync:
866 return bitc::ATTR_KIND_SWIFT_ASYNC;
867 case Attribute::UWTable:
868 return bitc::ATTR_KIND_UW_TABLE;
869 case Attribute::VScaleRange:
870 return bitc::ATTR_KIND_VSCALE_RANGE;
871 case Attribute::WillReturn:
872 return bitc::ATTR_KIND_WILLRETURN;
873 case Attribute::WriteOnly:
874 return bitc::ATTR_KIND_WRITEONLY;
875 case Attribute::ZExt:
876 return bitc::ATTR_KIND_Z_EXT;
877 case Attribute::ImmArg:
878 return bitc::ATTR_KIND_IMMARG;
879 case Attribute::SanitizeMemTag:
880 return bitc::ATTR_KIND_SANITIZE_MEMTAG;
881 case Attribute::Preallocated:
882 return bitc::ATTR_KIND_PREALLOCATED;
883 case Attribute::NoUndef:
884 return bitc::ATTR_KIND_NOUNDEF;
885 case Attribute::ByRef:
886 return bitc::ATTR_KIND_BYREF;
887 case Attribute::MustProgress:
888 return bitc::ATTR_KIND_MUSTPROGRESS;
889 case Attribute::PresplitCoroutine:
890 return bitc::ATTR_KIND_PRESPLIT_COROUTINE;
891 case Attribute::Writable:
892 return bitc::ATTR_KIND_WRITABLE;
893 case Attribute::CoroDestroyOnlyWhenComplete:
894 return bitc::ATTR_KIND_CORO_ONLY_DESTROY_WHEN_COMPLETE;
895 case Attribute::CoroElideSafe:
896 return bitc::ATTR_KIND_CORO_ELIDE_SAFE;
897 case Attribute::DeadOnUnwind:
898 return bitc::ATTR_KIND_DEAD_ON_UNWIND;
899 case Attribute::Range:
900 return bitc::ATTR_KIND_RANGE;
901 case Attribute::Initializes:
902 return bitc::ATTR_KIND_INITIALIZES;
903 case Attribute::NoExt:
904 return bitc::ATTR_KIND_NO_EXT;
905 case Attribute::EndAttrKinds:
906 llvm_unreachable("Can not encode end-attribute kinds marker.");
907 case Attribute::None:
908 llvm_unreachable("Can not encode none-attribute.");
909 case Attribute::EmptyKey:
910 case Attribute::TombstoneKey:
911 llvm_unreachable("Trying to encode EmptyKey/TombstoneKey");
914 llvm_unreachable("Trying to encode unknown attribute");
917 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
918 if ((int64_t)V >= 0)
919 Vals.push_back(V << 1);
920 else
921 Vals.push_back((-V << 1) | 1);
924 static void emitWideAPInt(SmallVectorImpl<uint64_t> &Vals, const APInt &A) {
925 // We have an arbitrary precision integer value to write whose
926 // bit width is > 64. However, in canonical unsigned integer
927 // format it is likely that the high bits are going to be zero.
928 // So, we only write the number of active words.
929 unsigned NumWords = A.getActiveWords();
930 const uint64_t *RawData = A.getRawData();
931 for (unsigned i = 0; i < NumWords; i++)
932 emitSignedInt64(Vals, RawData[i]);
935 static void emitConstantRange(SmallVectorImpl<uint64_t> &Record,
936 const ConstantRange &CR, bool EmitBitWidth) {
937 unsigned BitWidth = CR.getBitWidth();
938 if (EmitBitWidth)
939 Record.push_back(BitWidth);
940 if (BitWidth > 64) {
941 Record.push_back(CR.getLower().getActiveWords() |
942 (uint64_t(CR.getUpper().getActiveWords()) << 32));
943 emitWideAPInt(Record, CR.getLower());
944 emitWideAPInt(Record, CR.getUpper());
945 } else {
946 emitSignedInt64(Record, CR.getLower().getSExtValue());
947 emitSignedInt64(Record, CR.getUpper().getSExtValue());
951 void ModuleBitcodeWriter::writeAttributeGroupTable() {
952 const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
953 VE.getAttributeGroups();
954 if (AttrGrps.empty()) return;
956 Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
958 SmallVector<uint64_t, 64> Record;
959 for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) {
960 unsigned AttrListIndex = Pair.first;
961 AttributeSet AS = Pair.second;
962 Record.push_back(VE.getAttributeGroupID(Pair));
963 Record.push_back(AttrListIndex);
965 for (Attribute Attr : AS) {
966 if (Attr.isEnumAttribute()) {
967 Record.push_back(0);
968 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
969 } else if (Attr.isIntAttribute()) {
970 Record.push_back(1);
971 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
972 Record.push_back(Attr.getValueAsInt());
973 } else if (Attr.isStringAttribute()) {
974 StringRef Kind = Attr.getKindAsString();
975 StringRef Val = Attr.getValueAsString();
977 Record.push_back(Val.empty() ? 3 : 4);
978 Record.append(Kind.begin(), Kind.end());
979 Record.push_back(0);
980 if (!Val.empty()) {
981 Record.append(Val.begin(), Val.end());
982 Record.push_back(0);
984 } else if (Attr.isTypeAttribute()) {
985 Type *Ty = Attr.getValueAsType();
986 Record.push_back(Ty ? 6 : 5);
987 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
988 if (Ty)
989 Record.push_back(VE.getTypeID(Attr.getValueAsType()));
990 } else if (Attr.isConstantRangeAttribute()) {
991 Record.push_back(7);
992 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
993 emitConstantRange(Record, Attr.getValueAsConstantRange(),
994 /*EmitBitWidth=*/true);
995 } else {
996 assert(Attr.isConstantRangeListAttribute());
997 Record.push_back(8);
998 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
999 ArrayRef<ConstantRange> Val = Attr.getValueAsConstantRangeList();
1000 Record.push_back(Val.size());
1001 Record.push_back(Val[0].getBitWidth());
1002 for (auto &CR : Val)
1003 emitConstantRange(Record, CR, /*EmitBitWidth=*/false);
1007 Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
1008 Record.clear();
1011 Stream.ExitBlock();
1014 void ModuleBitcodeWriter::writeAttributeTable() {
1015 const std::vector<AttributeList> &Attrs = VE.getAttributeLists();
1016 if (Attrs.empty()) return;
1018 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
1020 SmallVector<uint64_t, 64> Record;
1021 for (const AttributeList &AL : Attrs) {
1022 for (unsigned i : AL.indexes()) {
1023 AttributeSet AS = AL.getAttributes(i);
1024 if (AS.hasAttributes())
1025 Record.push_back(VE.getAttributeGroupID({i, AS}));
1028 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
1029 Record.clear();
1032 Stream.ExitBlock();
1035 /// WriteTypeTable - Write out the type table for a module.
1036 void ModuleBitcodeWriter::writeTypeTable() {
1037 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
1039 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
1040 SmallVector<uint64_t, 64> TypeVals;
1042 uint64_t NumBits = VE.computeBitsRequiredForTypeIndices();
1044 // Abbrev for TYPE_CODE_OPAQUE_POINTER.
1045 auto Abbv = std::make_shared<BitCodeAbbrev>();
1046 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_OPAQUE_POINTER));
1047 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
1048 unsigned OpaquePtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1050 // Abbrev for TYPE_CODE_FUNCTION.
1051 Abbv = std::make_shared<BitCodeAbbrev>();
1052 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
1053 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
1054 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1055 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
1056 unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1058 // Abbrev for TYPE_CODE_STRUCT_ANON.
1059 Abbv = std::make_shared<BitCodeAbbrev>();
1060 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
1061 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
1062 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1063 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
1064 unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1066 // Abbrev for TYPE_CODE_STRUCT_NAME.
1067 Abbv = std::make_shared<BitCodeAbbrev>();
1068 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
1069 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1070 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1071 unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1073 // Abbrev for TYPE_CODE_STRUCT_NAMED.
1074 Abbv = std::make_shared<BitCodeAbbrev>();
1075 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
1076 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
1077 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1078 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
1079 unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1081 // Abbrev for TYPE_CODE_ARRAY.
1082 Abbv = std::make_shared<BitCodeAbbrev>();
1083 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
1084 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
1085 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
1086 unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1088 // Emit an entry count so the reader can reserve space.
1089 TypeVals.push_back(TypeList.size());
1090 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
1091 TypeVals.clear();
1093 // Loop over all of the types, emitting each in turn.
1094 for (Type *T : TypeList) {
1095 int AbbrevToUse = 0;
1096 unsigned Code = 0;
1098 switch (T->getTypeID()) {
1099 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
1100 case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break;
1101 case Type::BFloatTyID: Code = bitc::TYPE_CODE_BFLOAT; break;
1102 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
1103 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
1104 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
1105 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
1106 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
1107 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
1108 case Type::MetadataTyID:
1109 Code = bitc::TYPE_CODE_METADATA;
1110 break;
1111 case Type::X86_AMXTyID: Code = bitc::TYPE_CODE_X86_AMX; break;
1112 case Type::TokenTyID: Code = bitc::TYPE_CODE_TOKEN; break;
1113 case Type::IntegerTyID:
1114 // INTEGER: [width]
1115 Code = bitc::TYPE_CODE_INTEGER;
1116 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
1117 break;
1118 case Type::PointerTyID: {
1119 PointerType *PTy = cast<PointerType>(T);
1120 unsigned AddressSpace = PTy->getAddressSpace();
1121 // OPAQUE_POINTER: [address space]
1122 Code = bitc::TYPE_CODE_OPAQUE_POINTER;
1123 TypeVals.push_back(AddressSpace);
1124 if (AddressSpace == 0)
1125 AbbrevToUse = OpaquePtrAbbrev;
1126 break;
1128 case Type::FunctionTyID: {
1129 FunctionType *FT = cast<FunctionType>(T);
1130 // FUNCTION: [isvararg, retty, paramty x N]
1131 Code = bitc::TYPE_CODE_FUNCTION;
1132 TypeVals.push_back(FT->isVarArg());
1133 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
1134 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
1135 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
1136 AbbrevToUse = FunctionAbbrev;
1137 break;
1139 case Type::StructTyID: {
1140 StructType *ST = cast<StructType>(T);
1141 // STRUCT: [ispacked, eltty x N]
1142 TypeVals.push_back(ST->isPacked());
1143 // Output all of the element types.
1144 for (Type *ET : ST->elements())
1145 TypeVals.push_back(VE.getTypeID(ET));
1147 if (ST->isLiteral()) {
1148 Code = bitc::TYPE_CODE_STRUCT_ANON;
1149 AbbrevToUse = StructAnonAbbrev;
1150 } else {
1151 if (ST->isOpaque()) {
1152 Code = bitc::TYPE_CODE_OPAQUE;
1153 } else {
1154 Code = bitc::TYPE_CODE_STRUCT_NAMED;
1155 AbbrevToUse = StructNamedAbbrev;
1158 // Emit the name if it is present.
1159 if (!ST->getName().empty())
1160 writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
1161 StructNameAbbrev);
1163 break;
1165 case Type::ArrayTyID: {
1166 ArrayType *AT = cast<ArrayType>(T);
1167 // ARRAY: [numelts, eltty]
1168 Code = bitc::TYPE_CODE_ARRAY;
1169 TypeVals.push_back(AT->getNumElements());
1170 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
1171 AbbrevToUse = ArrayAbbrev;
1172 break;
1174 case Type::FixedVectorTyID:
1175 case Type::ScalableVectorTyID: {
1176 VectorType *VT = cast<VectorType>(T);
1177 // VECTOR [numelts, eltty] or
1178 // [numelts, eltty, scalable]
1179 Code = bitc::TYPE_CODE_VECTOR;
1180 TypeVals.push_back(VT->getElementCount().getKnownMinValue());
1181 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
1182 if (isa<ScalableVectorType>(VT))
1183 TypeVals.push_back(true);
1184 break;
1186 case Type::TargetExtTyID: {
1187 TargetExtType *TET = cast<TargetExtType>(T);
1188 Code = bitc::TYPE_CODE_TARGET_TYPE;
1189 writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, TET->getName(),
1190 StructNameAbbrev);
1191 TypeVals.push_back(TET->getNumTypeParameters());
1192 for (Type *InnerTy : TET->type_params())
1193 TypeVals.push_back(VE.getTypeID(InnerTy));
1194 for (unsigned IntParam : TET->int_params())
1195 TypeVals.push_back(IntParam);
1196 break;
1198 case Type::TypedPointerTyID:
1199 llvm_unreachable("Typed pointers cannot be added to IR modules");
1202 // Emit the finished record.
1203 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
1204 TypeVals.clear();
1207 Stream.ExitBlock();
1210 static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {
1211 switch (Linkage) {
1212 case GlobalValue::ExternalLinkage:
1213 return 0;
1214 case GlobalValue::WeakAnyLinkage:
1215 return 16;
1216 case GlobalValue::AppendingLinkage:
1217 return 2;
1218 case GlobalValue::InternalLinkage:
1219 return 3;
1220 case GlobalValue::LinkOnceAnyLinkage:
1221 return 18;
1222 case GlobalValue::ExternalWeakLinkage:
1223 return 7;
1224 case GlobalValue::CommonLinkage:
1225 return 8;
1226 case GlobalValue::PrivateLinkage:
1227 return 9;
1228 case GlobalValue::WeakODRLinkage:
1229 return 17;
1230 case GlobalValue::LinkOnceODRLinkage:
1231 return 19;
1232 case GlobalValue::AvailableExternallyLinkage:
1233 return 12;
1235 llvm_unreachable("Invalid linkage");
1238 static unsigned getEncodedLinkage(const GlobalValue &GV) {
1239 return getEncodedLinkage(GV.getLinkage());
1242 static uint64_t getEncodedFFlags(FunctionSummary::FFlags Flags) {
1243 uint64_t RawFlags = 0;
1244 RawFlags |= Flags.ReadNone;
1245 RawFlags |= (Flags.ReadOnly << 1);
1246 RawFlags |= (Flags.NoRecurse << 2);
1247 RawFlags |= (Flags.ReturnDoesNotAlias << 3);
1248 RawFlags |= (Flags.NoInline << 4);
1249 RawFlags |= (Flags.AlwaysInline << 5);
1250 RawFlags |= (Flags.NoUnwind << 6);
1251 RawFlags |= (Flags.MayThrow << 7);
1252 RawFlags |= (Flags.HasUnknownCall << 8);
1253 RawFlags |= (Flags.MustBeUnreachable << 9);
1254 return RawFlags;
1257 // Decode the flags for GlobalValue in the summary. See getDecodedGVSummaryFlags
1258 // in BitcodeReader.cpp.
1259 static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags,
1260 bool ImportAsDecl = false) {
1261 uint64_t RawFlags = 0;
1263 RawFlags |= Flags.NotEligibleToImport; // bool
1264 RawFlags |= (Flags.Live << 1);
1265 RawFlags |= (Flags.DSOLocal << 2);
1266 RawFlags |= (Flags.CanAutoHide << 3);
1268 // Linkage don't need to be remapped at that time for the summary. Any future
1269 // change to the getEncodedLinkage() function will need to be taken into
1270 // account here as well.
1271 RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits
1273 RawFlags |= (Flags.Visibility << 8); // 2 bits
1275 unsigned ImportType = Flags.ImportType | ImportAsDecl;
1276 RawFlags |= (ImportType << 10); // 1 bit
1278 return RawFlags;
1281 static uint64_t getEncodedGVarFlags(GlobalVarSummary::GVarFlags Flags) {
1282 uint64_t RawFlags = Flags.MaybeReadOnly | (Flags.MaybeWriteOnly << 1) |
1283 (Flags.Constant << 2) | Flags.VCallVisibility << 3;
1284 return RawFlags;
1287 static uint64_t getEncodedHotnessCallEdgeInfo(const CalleeInfo &CI) {
1288 uint64_t RawFlags = 0;
1290 RawFlags |= CI.Hotness; // 3 bits
1291 RawFlags |= (CI.HasTailCall << 3); // 1 bit
1293 return RawFlags;
1296 static uint64_t getEncodedRelBFCallEdgeInfo(const CalleeInfo &CI) {
1297 uint64_t RawFlags = 0;
1299 RawFlags |= CI.RelBlockFreq; // CalleeInfo::RelBlockFreqBits bits
1300 RawFlags |= (CI.HasTailCall << CalleeInfo::RelBlockFreqBits); // 1 bit
1302 return RawFlags;
1305 static unsigned getEncodedVisibility(const GlobalValue &GV) {
1306 switch (GV.getVisibility()) {
1307 case GlobalValue::DefaultVisibility: return 0;
1308 case GlobalValue::HiddenVisibility: return 1;
1309 case GlobalValue::ProtectedVisibility: return 2;
1311 llvm_unreachable("Invalid visibility");
1314 static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
1315 switch (GV.getDLLStorageClass()) {
1316 case GlobalValue::DefaultStorageClass: return 0;
1317 case GlobalValue::DLLImportStorageClass: return 1;
1318 case GlobalValue::DLLExportStorageClass: return 2;
1320 llvm_unreachable("Invalid DLL storage class");
1323 static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
1324 switch (GV.getThreadLocalMode()) {
1325 case GlobalVariable::NotThreadLocal: return 0;
1326 case GlobalVariable::GeneralDynamicTLSModel: return 1;
1327 case GlobalVariable::LocalDynamicTLSModel: return 2;
1328 case GlobalVariable::InitialExecTLSModel: return 3;
1329 case GlobalVariable::LocalExecTLSModel: return 4;
1331 llvm_unreachable("Invalid TLS model");
1334 static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
1335 switch (C.getSelectionKind()) {
1336 case Comdat::Any:
1337 return bitc::COMDAT_SELECTION_KIND_ANY;
1338 case Comdat::ExactMatch:
1339 return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
1340 case Comdat::Largest:
1341 return bitc::COMDAT_SELECTION_KIND_LARGEST;
1342 case Comdat::NoDeduplicate:
1343 return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
1344 case Comdat::SameSize:
1345 return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
1347 llvm_unreachable("Invalid selection kind");
1350 static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) {
1351 switch (GV.getUnnamedAddr()) {
1352 case GlobalValue::UnnamedAddr::None: return 0;
1353 case GlobalValue::UnnamedAddr::Local: return 2;
1354 case GlobalValue::UnnamedAddr::Global: return 1;
1356 llvm_unreachable("Invalid unnamed_addr");
1359 size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) {
1360 if (GenerateHash)
1361 Hasher.update(Str);
1362 return StrtabBuilder.add(Str);
1365 void ModuleBitcodeWriter::writeComdats() {
1366 SmallVector<unsigned, 64> Vals;
1367 for (const Comdat *C : VE.getComdats()) {
1368 // COMDAT: [strtab offset, strtab size, selection_kind]
1369 Vals.push_back(addToStrtab(C->getName()));
1370 Vals.push_back(C->getName().size());
1371 Vals.push_back(getEncodedComdatSelectionKind(*C));
1372 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
1373 Vals.clear();
1377 /// Write a record that will eventually hold the word offset of the
1378 /// module-level VST. For now the offset is 0, which will be backpatched
1379 /// after the real VST is written. Saves the bit offset to backpatch.
1380 void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
1381 // Write a placeholder value in for the offset of the real VST,
1382 // which is written after the function blocks so that it can include
1383 // the offset of each function. The placeholder offset will be
1384 // updated when the real VST is written.
1385 auto Abbv = std::make_shared<BitCodeAbbrev>();
1386 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET));
1387 // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
1388 // hold the real VST offset. Must use fixed instead of VBR as we don't
1389 // know how many VBR chunks to reserve ahead of time.
1390 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1391 unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1393 // Emit the placeholder
1394 uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0};
1395 Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
1397 // Compute and save the bit offset to the placeholder, which will be
1398 // patched when the real VST is written. We can simply subtract the 32-bit
1399 // fixed size from the current bit number to get the location to backpatch.
1400 VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32;
1403 enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 };
1405 /// Determine the encoding to use for the given string name and length.
1406 static StringEncoding getStringEncoding(StringRef Str) {
1407 bool isChar6 = true;
1408 for (char C : Str) {
1409 if (isChar6)
1410 isChar6 = BitCodeAbbrevOp::isChar6(C);
1411 if ((unsigned char)C & 128)
1412 // don't bother scanning the rest.
1413 return SE_Fixed8;
1415 if (isChar6)
1416 return SE_Char6;
1417 return SE_Fixed7;
1420 static_assert(sizeof(GlobalValue::SanitizerMetadata) <= sizeof(unsigned),
1421 "Sanitizer Metadata is too large for naive serialization.");
1422 static unsigned
1423 serializeSanitizerMetadata(const GlobalValue::SanitizerMetadata &Meta) {
1424 return Meta.NoAddress | (Meta.NoHWAddress << 1) |
1425 (Meta.Memtag << 2) | (Meta.IsDynInit << 3);
1428 /// Emit top-level description of module, including target triple, inline asm,
1429 /// descriptors for global variables, and function prototype info.
1430 /// Returns the bit offset to backpatch with the location of the real VST.
1431 void ModuleBitcodeWriter::writeModuleInfo() {
1432 // Emit various pieces of data attached to a module.
1433 if (!M.getTargetTriple().empty())
1434 writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(),
1435 0 /*TODO*/);
1436 const std::string &DL = M.getDataLayoutStr();
1437 if (!DL.empty())
1438 writeStringRecord(Stream, bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/);
1439 if (!M.getModuleInlineAsm().empty())
1440 writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(),
1441 0 /*TODO*/);
1443 // Emit information about sections and GC, computing how many there are. Also
1444 // compute the maximum alignment value.
1445 std::map<std::string, unsigned> SectionMap;
1446 std::map<std::string, unsigned> GCMap;
1447 MaybeAlign MaxAlignment;
1448 unsigned MaxGlobalType = 0;
1449 const auto UpdateMaxAlignment = [&MaxAlignment](const MaybeAlign A) {
1450 if (A)
1451 MaxAlignment = !MaxAlignment ? *A : std::max(*MaxAlignment, *A);
1453 for (const GlobalVariable &GV : M.globals()) {
1454 UpdateMaxAlignment(GV.getAlign());
1455 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
1456 if (GV.hasSection()) {
1457 // Give section names unique ID's.
1458 unsigned &Entry = SectionMap[std::string(GV.getSection())];
1459 if (!Entry) {
1460 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
1461 0 /*TODO*/);
1462 Entry = SectionMap.size();
1466 for (const Function &F : M) {
1467 UpdateMaxAlignment(F.getAlign());
1468 if (F.hasSection()) {
1469 // Give section names unique ID's.
1470 unsigned &Entry = SectionMap[std::string(F.getSection())];
1471 if (!Entry) {
1472 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
1473 0 /*TODO*/);
1474 Entry = SectionMap.size();
1477 if (F.hasGC()) {
1478 // Same for GC names.
1479 unsigned &Entry = GCMap[F.getGC()];
1480 if (!Entry) {
1481 writeStringRecord(Stream, bitc::MODULE_CODE_GCNAME, F.getGC(),
1482 0 /*TODO*/);
1483 Entry = GCMap.size();
1488 // Emit abbrev for globals, now that we know # sections and max alignment.
1489 unsigned SimpleGVarAbbrev = 0;
1490 if (!M.global_empty()) {
1491 // Add an abbrev for common globals with no visibility or thread localness.
1492 auto Abbv = std::make_shared<BitCodeAbbrev>();
1493 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
1494 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1495 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1496 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1497 Log2_32_Ceil(MaxGlobalType+1)));
1498 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2
1499 //| explicitType << 1
1500 //| constant
1501 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
1502 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
1503 if (!MaxAlignment) // Alignment.
1504 Abbv->Add(BitCodeAbbrevOp(0));
1505 else {
1506 unsigned MaxEncAlignment = getEncodedAlign(MaxAlignment);
1507 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1508 Log2_32_Ceil(MaxEncAlignment+1)));
1510 if (SectionMap.empty()) // Section.
1511 Abbv->Add(BitCodeAbbrevOp(0));
1512 else
1513 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1514 Log2_32_Ceil(SectionMap.size()+1)));
1515 // Don't bother emitting vis + thread local.
1516 SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1519 SmallVector<unsigned, 64> Vals;
1520 // Emit the module's source file name.
1522 StringEncoding Bits = getStringEncoding(M.getSourceFileName());
1523 BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
1524 if (Bits == SE_Char6)
1525 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
1526 else if (Bits == SE_Fixed7)
1527 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
1529 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
1530 auto Abbv = std::make_shared<BitCodeAbbrev>();
1531 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
1532 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1533 Abbv->Add(AbbrevOpToUse);
1534 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1536 for (const auto P : M.getSourceFileName())
1537 Vals.push_back((unsigned char)P);
1539 // Emit the finished record.
1540 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
1541 Vals.clear();
1544 // Emit the global variable information.
1545 for (const GlobalVariable &GV : M.globals()) {
1546 unsigned AbbrevToUse = 0;
1548 // GLOBALVAR: [strtab offset, strtab size, type, isconst, initid,
1549 // linkage, alignment, section, visibility, threadlocal,
1550 // unnamed_addr, externally_initialized, dllstorageclass,
1551 // comdat, attributes, DSO_Local, GlobalSanitizer, code_model]
1552 Vals.push_back(addToStrtab(GV.getName()));
1553 Vals.push_back(GV.getName().size());
1554 Vals.push_back(VE.getTypeID(GV.getValueType()));
1555 Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
1556 Vals.push_back(GV.isDeclaration() ? 0 :
1557 (VE.getValueID(GV.getInitializer()) + 1));
1558 Vals.push_back(getEncodedLinkage(GV));
1559 Vals.push_back(getEncodedAlign(GV.getAlign()));
1560 Vals.push_back(GV.hasSection() ? SectionMap[std::string(GV.getSection())]
1561 : 0);
1562 if (GV.isThreadLocal() ||
1563 GV.getVisibility() != GlobalValue::DefaultVisibility ||
1564 GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1565 GV.isExternallyInitialized() ||
1566 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
1567 GV.hasComdat() || GV.hasAttributes() || GV.isDSOLocal() ||
1568 GV.hasPartition() || GV.hasSanitizerMetadata() || GV.getCodeModel()) {
1569 Vals.push_back(getEncodedVisibility(GV));
1570 Vals.push_back(getEncodedThreadLocalMode(GV));
1571 Vals.push_back(getEncodedUnnamedAddr(GV));
1572 Vals.push_back(GV.isExternallyInitialized());
1573 Vals.push_back(getEncodedDLLStorageClass(GV));
1574 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
1576 auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
1577 Vals.push_back(VE.getAttributeListID(AL));
1579 Vals.push_back(GV.isDSOLocal());
1580 Vals.push_back(addToStrtab(GV.getPartition()));
1581 Vals.push_back(GV.getPartition().size());
1583 Vals.push_back((GV.hasSanitizerMetadata() ? serializeSanitizerMetadata(
1584 GV.getSanitizerMetadata())
1585 : 0));
1586 Vals.push_back(GV.getCodeModelRaw());
1587 } else {
1588 AbbrevToUse = SimpleGVarAbbrev;
1591 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
1592 Vals.clear();
1595 // Emit the function proto information.
1596 for (const Function &F : M) {
1597 // FUNCTION: [strtab offset, strtab size, type, callingconv, isproto,
1598 // linkage, paramattrs, alignment, section, visibility, gc,
1599 // unnamed_addr, prologuedata, dllstorageclass, comdat,
1600 // prefixdata, personalityfn, DSO_Local, addrspace]
1601 Vals.push_back(addToStrtab(F.getName()));
1602 Vals.push_back(F.getName().size());
1603 Vals.push_back(VE.getTypeID(F.getFunctionType()));
1604 Vals.push_back(F.getCallingConv());
1605 Vals.push_back(F.isDeclaration());
1606 Vals.push_back(getEncodedLinkage(F));
1607 Vals.push_back(VE.getAttributeListID(F.getAttributes()));
1608 Vals.push_back(getEncodedAlign(F.getAlign()));
1609 Vals.push_back(F.hasSection() ? SectionMap[std::string(F.getSection())]
1610 : 0);
1611 Vals.push_back(getEncodedVisibility(F));
1612 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
1613 Vals.push_back(getEncodedUnnamedAddr(F));
1614 Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
1615 : 0);
1616 Vals.push_back(getEncodedDLLStorageClass(F));
1617 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
1618 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
1619 : 0);
1620 Vals.push_back(
1621 F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
1623 Vals.push_back(F.isDSOLocal());
1624 Vals.push_back(F.getAddressSpace());
1625 Vals.push_back(addToStrtab(F.getPartition()));
1626 Vals.push_back(F.getPartition().size());
1628 unsigned AbbrevToUse = 0;
1629 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
1630 Vals.clear();
1633 // Emit the alias information.
1634 for (const GlobalAlias &A : M.aliases()) {
1635 // ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage,
1636 // visibility, dllstorageclass, threadlocal, unnamed_addr,
1637 // DSO_Local]
1638 Vals.push_back(addToStrtab(A.getName()));
1639 Vals.push_back(A.getName().size());
1640 Vals.push_back(VE.getTypeID(A.getValueType()));
1641 Vals.push_back(A.getType()->getAddressSpace());
1642 Vals.push_back(VE.getValueID(A.getAliasee()));
1643 Vals.push_back(getEncodedLinkage(A));
1644 Vals.push_back(getEncodedVisibility(A));
1645 Vals.push_back(getEncodedDLLStorageClass(A));
1646 Vals.push_back(getEncodedThreadLocalMode(A));
1647 Vals.push_back(getEncodedUnnamedAddr(A));
1648 Vals.push_back(A.isDSOLocal());
1649 Vals.push_back(addToStrtab(A.getPartition()));
1650 Vals.push_back(A.getPartition().size());
1652 unsigned AbbrevToUse = 0;
1653 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
1654 Vals.clear();
1657 // Emit the ifunc information.
1658 for (const GlobalIFunc &I : M.ifuncs()) {
1659 // IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver
1660 // val#, linkage, visibility, DSO_Local]
1661 Vals.push_back(addToStrtab(I.getName()));
1662 Vals.push_back(I.getName().size());
1663 Vals.push_back(VE.getTypeID(I.getValueType()));
1664 Vals.push_back(I.getType()->getAddressSpace());
1665 Vals.push_back(VE.getValueID(I.getResolver()));
1666 Vals.push_back(getEncodedLinkage(I));
1667 Vals.push_back(getEncodedVisibility(I));
1668 Vals.push_back(I.isDSOLocal());
1669 Vals.push_back(addToStrtab(I.getPartition()));
1670 Vals.push_back(I.getPartition().size());
1671 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
1672 Vals.clear();
1675 writeValueSymbolTableForwardDecl();
1678 static uint64_t getOptimizationFlags(const Value *V) {
1679 uint64_t Flags = 0;
1681 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
1682 if (OBO->hasNoSignedWrap())
1683 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
1684 if (OBO->hasNoUnsignedWrap())
1685 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
1686 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
1687 if (PEO->isExact())
1688 Flags |= 1 << bitc::PEO_EXACT;
1689 } else if (const auto *PDI = dyn_cast<PossiblyDisjointInst>(V)) {
1690 if (PDI->isDisjoint())
1691 Flags |= 1 << bitc::PDI_DISJOINT;
1692 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
1693 if (FPMO->hasAllowReassoc())
1694 Flags |= bitc::AllowReassoc;
1695 if (FPMO->hasNoNaNs())
1696 Flags |= bitc::NoNaNs;
1697 if (FPMO->hasNoInfs())
1698 Flags |= bitc::NoInfs;
1699 if (FPMO->hasNoSignedZeros())
1700 Flags |= bitc::NoSignedZeros;
1701 if (FPMO->hasAllowReciprocal())
1702 Flags |= bitc::AllowReciprocal;
1703 if (FPMO->hasAllowContract())
1704 Flags |= bitc::AllowContract;
1705 if (FPMO->hasApproxFunc())
1706 Flags |= bitc::ApproxFunc;
1707 } else if (const auto *NNI = dyn_cast<PossiblyNonNegInst>(V)) {
1708 if (NNI->hasNonNeg())
1709 Flags |= 1 << bitc::PNNI_NON_NEG;
1710 } else if (const auto *TI = dyn_cast<TruncInst>(V)) {
1711 if (TI->hasNoSignedWrap())
1712 Flags |= 1 << bitc::TIO_NO_SIGNED_WRAP;
1713 if (TI->hasNoUnsignedWrap())
1714 Flags |= 1 << bitc::TIO_NO_UNSIGNED_WRAP;
1715 } else if (const auto *GEP = dyn_cast<GEPOperator>(V)) {
1716 if (GEP->isInBounds())
1717 Flags |= 1 << bitc::GEP_INBOUNDS;
1718 if (GEP->hasNoUnsignedSignedWrap())
1719 Flags |= 1 << bitc::GEP_NUSW;
1720 if (GEP->hasNoUnsignedWrap())
1721 Flags |= 1 << bitc::GEP_NUW;
1722 } else if (const auto *ICmp = dyn_cast<ICmpInst>(V)) {
1723 if (ICmp->hasSameSign())
1724 Flags |= 1 << bitc::ICMP_SAME_SIGN;
1727 return Flags;
1730 void ModuleBitcodeWriter::writeValueAsMetadata(
1731 const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
1732 // Mimic an MDNode with a value as one operand.
1733 Value *V = MD->getValue();
1734 Record.push_back(VE.getTypeID(V->getType()));
1735 Record.push_back(VE.getValueID(V));
1736 Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
1737 Record.clear();
1740 void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N,
1741 SmallVectorImpl<uint64_t> &Record,
1742 unsigned Abbrev) {
1743 for (const MDOperand &MDO : N->operands()) {
1744 Metadata *MD = MDO;
1745 assert(!(MD && isa<LocalAsMetadata>(MD)) &&
1746 "Unexpected function-local metadata");
1747 Record.push_back(VE.getMetadataOrNullID(MD));
1749 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
1750 : bitc::METADATA_NODE,
1751 Record, Abbrev);
1752 Record.clear();
1755 unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
1756 // Assume the column is usually under 128, and always output the inlined-at
1757 // location (it's never more expensive than building an array size 1).
1758 auto Abbv = std::make_shared<BitCodeAbbrev>();
1759 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
1760 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1761 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1762 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1763 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1764 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1765 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1766 return Stream.EmitAbbrev(std::move(Abbv));
1769 void ModuleBitcodeWriter::writeDILocation(const DILocation *N,
1770 SmallVectorImpl<uint64_t> &Record,
1771 unsigned &Abbrev) {
1772 if (!Abbrev)
1773 Abbrev = createDILocationAbbrev();
1775 Record.push_back(N->isDistinct());
1776 Record.push_back(N->getLine());
1777 Record.push_back(N->getColumn());
1778 Record.push_back(VE.getMetadataID(N->getScope()));
1779 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
1780 Record.push_back(N->isImplicitCode());
1782 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
1783 Record.clear();
1786 unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
1787 // Assume the column is usually under 128, and always output the inlined-at
1788 // location (it's never more expensive than building an array size 1).
1789 auto Abbv = std::make_shared<BitCodeAbbrev>();
1790 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
1791 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1792 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1793 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1794 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1795 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1796 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1797 return Stream.EmitAbbrev(std::move(Abbv));
1800 void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N,
1801 SmallVectorImpl<uint64_t> &Record,
1802 unsigned &Abbrev) {
1803 if (!Abbrev)
1804 Abbrev = createGenericDINodeAbbrev();
1806 Record.push_back(N->isDistinct());
1807 Record.push_back(N->getTag());
1808 Record.push_back(0); // Per-tag version field; unused for now.
1810 for (auto &I : N->operands())
1811 Record.push_back(VE.getMetadataOrNullID(I));
1813 Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
1814 Record.clear();
1817 void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N,
1818 SmallVectorImpl<uint64_t> &Record,
1819 unsigned Abbrev) {
1820 const uint64_t Version = 2 << 1;
1821 Record.push_back((uint64_t)N->isDistinct() | Version);
1822 Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
1823 Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
1824 Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
1825 Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
1827 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
1828 Record.clear();
1831 void ModuleBitcodeWriter::writeDIGenericSubrange(
1832 const DIGenericSubrange *N, SmallVectorImpl<uint64_t> &Record,
1833 unsigned Abbrev) {
1834 Record.push_back((uint64_t)N->isDistinct());
1835 Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
1836 Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
1837 Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
1838 Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
1840 Stream.EmitRecord(bitc::METADATA_GENERIC_SUBRANGE, Record, Abbrev);
1841 Record.clear();
1844 void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,
1845 SmallVectorImpl<uint64_t> &Record,
1846 unsigned Abbrev) {
1847 const uint64_t IsBigInt = 1 << 2;
1848 Record.push_back(IsBigInt | (N->isUnsigned() << 1) | N->isDistinct());
1849 Record.push_back(N->getValue().getBitWidth());
1850 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1851 emitWideAPInt(Record, N->getValue());
1853 Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
1854 Record.clear();
1857 void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N,
1858 SmallVectorImpl<uint64_t> &Record,
1859 unsigned Abbrev) {
1860 Record.push_back(N->isDistinct());
1861 Record.push_back(N->getTag());
1862 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1863 Record.push_back(N->getSizeInBits());
1864 Record.push_back(N->getAlignInBits());
1865 Record.push_back(N->getEncoding());
1866 Record.push_back(N->getFlags());
1867 Record.push_back(N->getNumExtraInhabitants());
1869 Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
1870 Record.clear();
1873 void ModuleBitcodeWriter::writeDIStringType(const DIStringType *N,
1874 SmallVectorImpl<uint64_t> &Record,
1875 unsigned Abbrev) {
1876 Record.push_back(N->isDistinct());
1877 Record.push_back(N->getTag());
1878 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1879 Record.push_back(VE.getMetadataOrNullID(N->getStringLength()));
1880 Record.push_back(VE.getMetadataOrNullID(N->getStringLengthExp()));
1881 Record.push_back(VE.getMetadataOrNullID(N->getStringLocationExp()));
1882 Record.push_back(N->getSizeInBits());
1883 Record.push_back(N->getAlignInBits());
1884 Record.push_back(N->getEncoding());
1886 Stream.EmitRecord(bitc::METADATA_STRING_TYPE, Record, Abbrev);
1887 Record.clear();
1890 void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,
1891 SmallVectorImpl<uint64_t> &Record,
1892 unsigned Abbrev) {
1893 Record.push_back(N->isDistinct());
1894 Record.push_back(N->getTag());
1895 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1896 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1897 Record.push_back(N->getLine());
1898 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1899 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1900 Record.push_back(N->getSizeInBits());
1901 Record.push_back(N->getAlignInBits());
1902 Record.push_back(N->getOffsetInBits());
1903 Record.push_back(N->getFlags());
1904 Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
1906 // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
1907 // that there is no DWARF address space associated with DIDerivedType.
1908 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
1909 Record.push_back(*DWARFAddressSpace + 1);
1910 else
1911 Record.push_back(0);
1913 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
1915 if (auto PtrAuthData = N->getPtrAuthData())
1916 Record.push_back(PtrAuthData->RawData);
1917 else
1918 Record.push_back(0);
1920 Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
1921 Record.clear();
1924 void ModuleBitcodeWriter::writeDICompositeType(
1925 const DICompositeType *N, SmallVectorImpl<uint64_t> &Record,
1926 unsigned Abbrev) {
1927 const unsigned IsNotUsedInOldTypeRef = 0x2;
1928 Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct());
1929 Record.push_back(N->getTag());
1930 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1931 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1932 Record.push_back(N->getLine());
1933 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1934 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1935 Record.push_back(N->getSizeInBits());
1936 Record.push_back(N->getAlignInBits());
1937 Record.push_back(N->getOffsetInBits());
1938 Record.push_back(N->getFlags());
1939 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1940 Record.push_back(N->getRuntimeLang());
1941 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
1942 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1943 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
1944 Record.push_back(VE.getMetadataOrNullID(N->getDiscriminator()));
1945 Record.push_back(VE.getMetadataOrNullID(N->getRawDataLocation()));
1946 Record.push_back(VE.getMetadataOrNullID(N->getRawAssociated()));
1947 Record.push_back(VE.getMetadataOrNullID(N->getRawAllocated()));
1948 Record.push_back(VE.getMetadataOrNullID(N->getRawRank()));
1949 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
1950 Record.push_back(N->getNumExtraInhabitants());
1951 Record.push_back(VE.getMetadataOrNullID(N->getRawSpecification()));
1953 Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
1954 Record.clear();
1957 void ModuleBitcodeWriter::writeDISubroutineType(
1958 const DISubroutineType *N, SmallVectorImpl<uint64_t> &Record,
1959 unsigned Abbrev) {
1960 const unsigned HasNoOldTypeRefs = 0x2;
1961 Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
1962 Record.push_back(N->getFlags());
1963 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
1964 Record.push_back(N->getCC());
1966 Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
1967 Record.clear();
1970 void ModuleBitcodeWriter::writeDIFile(const DIFile *N,
1971 SmallVectorImpl<uint64_t> &Record,
1972 unsigned Abbrev) {
1973 Record.push_back(N->isDistinct());
1974 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
1975 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
1976 if (N->getRawChecksum()) {
1977 Record.push_back(N->getRawChecksum()->Kind);
1978 Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()->Value));
1979 } else {
1980 // Maintain backwards compatibility with the old internal representation of
1981 // CSK_None in ChecksumKind by writing nulls here when Checksum is None.
1982 Record.push_back(0);
1983 Record.push_back(VE.getMetadataOrNullID(nullptr));
1985 auto Source = N->getRawSource();
1986 if (Source)
1987 Record.push_back(VE.getMetadataOrNullID(Source));
1989 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
1990 Record.clear();
1993 void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
1994 SmallVectorImpl<uint64_t> &Record,
1995 unsigned Abbrev) {
1996 assert(N->isDistinct() && "Expected distinct compile units");
1997 Record.push_back(/* IsDistinct */ true);
1998 Record.push_back(N->getSourceLanguage());
1999 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2000 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
2001 Record.push_back(N->isOptimized());
2002 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
2003 Record.push_back(N->getRuntimeVersion());
2004 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
2005 Record.push_back(N->getEmissionKind());
2006 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
2007 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
2008 Record.push_back(/* subprograms */ 0);
2009 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
2010 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
2011 Record.push_back(N->getDWOId());
2012 Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
2013 Record.push_back(N->getSplitDebugInlining());
2014 Record.push_back(N->getDebugInfoForProfiling());
2015 Record.push_back((unsigned)N->getNameTableKind());
2016 Record.push_back(N->getRangesBaseAddress());
2017 Record.push_back(VE.getMetadataOrNullID(N->getRawSysRoot()));
2018 Record.push_back(VE.getMetadataOrNullID(N->getRawSDK()));
2020 Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
2021 Record.clear();
2024 void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,
2025 SmallVectorImpl<uint64_t> &Record,
2026 unsigned Abbrev) {
2027 const uint64_t HasUnitFlag = 1 << 1;
2028 const uint64_t HasSPFlagsFlag = 1 << 2;
2029 Record.push_back(uint64_t(N->isDistinct()) | HasUnitFlag | HasSPFlagsFlag);
2030 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2031 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2032 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
2033 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2034 Record.push_back(N->getLine());
2035 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2036 Record.push_back(N->getScopeLine());
2037 Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
2038 Record.push_back(N->getSPFlags());
2039 Record.push_back(N->getVirtualIndex());
2040 Record.push_back(N->getFlags());
2041 Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
2042 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
2043 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
2044 Record.push_back(VE.getMetadataOrNullID(N->getRetainedNodes().get()));
2045 Record.push_back(N->getThisAdjustment());
2046 Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get()));
2047 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2048 Record.push_back(VE.getMetadataOrNullID(N->getRawTargetFuncName()));
2050 Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
2051 Record.clear();
2054 void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
2055 SmallVectorImpl<uint64_t> &Record,
2056 unsigned Abbrev) {
2057 Record.push_back(N->isDistinct());
2058 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2059 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2060 Record.push_back(N->getLine());
2061 Record.push_back(N->getColumn());
2063 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
2064 Record.clear();
2067 void ModuleBitcodeWriter::writeDILexicalBlockFile(
2068 const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record,
2069 unsigned Abbrev) {
2070 Record.push_back(N->isDistinct());
2071 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2072 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2073 Record.push_back(N->getDiscriminator());
2075 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
2076 Record.clear();
2079 void ModuleBitcodeWriter::writeDICommonBlock(const DICommonBlock *N,
2080 SmallVectorImpl<uint64_t> &Record,
2081 unsigned Abbrev) {
2082 Record.push_back(N->isDistinct());
2083 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2084 Record.push_back(VE.getMetadataOrNullID(N->getDecl()));
2085 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2086 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2087 Record.push_back(N->getLineNo());
2089 Stream.EmitRecord(bitc::METADATA_COMMON_BLOCK, Record, Abbrev);
2090 Record.clear();
2093 void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,
2094 SmallVectorImpl<uint64_t> &Record,
2095 unsigned Abbrev) {
2096 Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
2097 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2098 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2100 Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
2101 Record.clear();
2104 void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,
2105 SmallVectorImpl<uint64_t> &Record,
2106 unsigned Abbrev) {
2107 Record.push_back(N->isDistinct());
2108 Record.push_back(N->getMacinfoType());
2109 Record.push_back(N->getLine());
2110 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2111 Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
2113 Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
2114 Record.clear();
2117 void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,
2118 SmallVectorImpl<uint64_t> &Record,
2119 unsigned Abbrev) {
2120 Record.push_back(N->isDistinct());
2121 Record.push_back(N->getMacinfoType());
2122 Record.push_back(N->getLine());
2123 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2124 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
2126 Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
2127 Record.clear();
2130 void ModuleBitcodeWriter::writeDIArgList(const DIArgList *N,
2131 SmallVectorImpl<uint64_t> &Record) {
2132 Record.reserve(N->getArgs().size());
2133 for (ValueAsMetadata *MD : N->getArgs())
2134 Record.push_back(VE.getMetadataID(MD));
2136 Stream.EmitRecord(bitc::METADATA_ARG_LIST, Record);
2137 Record.clear();
2140 void ModuleBitcodeWriter::writeDIModule(const DIModule *N,
2141 SmallVectorImpl<uint64_t> &Record,
2142 unsigned Abbrev) {
2143 Record.push_back(N->isDistinct());
2144 for (auto &I : N->operands())
2145 Record.push_back(VE.getMetadataOrNullID(I));
2146 Record.push_back(N->getLineNo());
2147 Record.push_back(N->getIsDecl());
2149 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
2150 Record.clear();
2153 void ModuleBitcodeWriter::writeDIAssignID(const DIAssignID *N,
2154 SmallVectorImpl<uint64_t> &Record,
2155 unsigned Abbrev) {
2156 // There are no arguments for this metadata type.
2157 Record.push_back(N->isDistinct());
2158 Stream.EmitRecord(bitc::METADATA_ASSIGN_ID, Record, Abbrev);
2159 Record.clear();
2162 void ModuleBitcodeWriter::writeDITemplateTypeParameter(
2163 const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record,
2164 unsigned Abbrev) {
2165 Record.push_back(N->isDistinct());
2166 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2167 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2168 Record.push_back(N->isDefault());
2170 Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
2171 Record.clear();
2174 void ModuleBitcodeWriter::writeDITemplateValueParameter(
2175 const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record,
2176 unsigned Abbrev) {
2177 Record.push_back(N->isDistinct());
2178 Record.push_back(N->getTag());
2179 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2180 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2181 Record.push_back(N->isDefault());
2182 Record.push_back(VE.getMetadataOrNullID(N->getValue()));
2184 Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
2185 Record.clear();
2188 void ModuleBitcodeWriter::writeDIGlobalVariable(
2189 const DIGlobalVariable *N, SmallVectorImpl<uint64_t> &Record,
2190 unsigned Abbrev) {
2191 const uint64_t Version = 2 << 1;
2192 Record.push_back((uint64_t)N->isDistinct() | Version);
2193 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2194 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2195 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
2196 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2197 Record.push_back(N->getLine());
2198 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2199 Record.push_back(N->isLocalToUnit());
2200 Record.push_back(N->isDefinition());
2201 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
2202 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams()));
2203 Record.push_back(N->getAlignInBits());
2204 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2206 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
2207 Record.clear();
2210 void ModuleBitcodeWriter::writeDILocalVariable(
2211 const DILocalVariable *N, SmallVectorImpl<uint64_t> &Record,
2212 unsigned Abbrev) {
2213 // In order to support all possible bitcode formats in BitcodeReader we need
2214 // to distinguish the following cases:
2215 // 1) Record has no artificial tag (Record[1]),
2216 // has no obsolete inlinedAt field (Record[9]).
2217 // In this case Record size will be 8, HasAlignment flag is false.
2218 // 2) Record has artificial tag (Record[1]),
2219 // has no obsolete inlignedAt field (Record[9]).
2220 // In this case Record size will be 9, HasAlignment flag is false.
2221 // 3) Record has both artificial tag (Record[1]) and
2222 // obsolete inlignedAt field (Record[9]).
2223 // In this case Record size will be 10, HasAlignment flag is false.
2224 // 4) Record has neither artificial tag, nor inlignedAt field, but
2225 // HasAlignment flag is true and Record[8] contains alignment value.
2226 const uint64_t HasAlignmentFlag = 1 << 1;
2227 Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
2228 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2229 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2230 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2231 Record.push_back(N->getLine());
2232 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2233 Record.push_back(N->getArg());
2234 Record.push_back(N->getFlags());
2235 Record.push_back(N->getAlignInBits());
2236 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2238 Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
2239 Record.clear();
2242 void ModuleBitcodeWriter::writeDILabel(
2243 const DILabel *N, SmallVectorImpl<uint64_t> &Record,
2244 unsigned Abbrev) {
2245 Record.push_back((uint64_t)N->isDistinct());
2246 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2247 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2248 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2249 Record.push_back(N->getLine());
2251 Stream.EmitRecord(bitc::METADATA_LABEL, Record, Abbrev);
2252 Record.clear();
2255 void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,
2256 SmallVectorImpl<uint64_t> &Record,
2257 unsigned Abbrev) {
2258 Record.reserve(N->getElements().size() + 1);
2259 const uint64_t Version = 3 << 1;
2260 Record.push_back((uint64_t)N->isDistinct() | Version);
2261 Record.append(N->elements_begin(), N->elements_end());
2263 Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
2264 Record.clear();
2267 void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
2268 const DIGlobalVariableExpression *N, SmallVectorImpl<uint64_t> &Record,
2269 unsigned Abbrev) {
2270 Record.push_back(N->isDistinct());
2271 Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
2272 Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
2274 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR, Record, Abbrev);
2275 Record.clear();
2278 void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
2279 SmallVectorImpl<uint64_t> &Record,
2280 unsigned Abbrev) {
2281 Record.push_back(N->isDistinct());
2282 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2283 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2284 Record.push_back(N->getLine());
2285 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
2286 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
2287 Record.push_back(N->getAttributes());
2288 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2290 Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
2291 Record.clear();
2294 void ModuleBitcodeWriter::writeDIImportedEntity(
2295 const DIImportedEntity *N, SmallVectorImpl<uint64_t> &Record,
2296 unsigned Abbrev) {
2297 Record.push_back(N->isDistinct());
2298 Record.push_back(N->getTag());
2299 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2300 Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
2301 Record.push_back(N->getLine());
2302 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2303 Record.push_back(VE.getMetadataOrNullID(N->getRawFile()));
2304 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
2306 Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
2307 Record.clear();
2310 unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
2311 auto Abbv = std::make_shared<BitCodeAbbrev>();
2312 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
2313 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2314 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2315 return Stream.EmitAbbrev(std::move(Abbv));
2318 void ModuleBitcodeWriter::writeNamedMetadata(
2319 SmallVectorImpl<uint64_t> &Record) {
2320 if (M.named_metadata_empty())
2321 return;
2323 unsigned Abbrev = createNamedMetadataAbbrev();
2324 for (const NamedMDNode &NMD : M.named_metadata()) {
2325 // Write name.
2326 StringRef Str = NMD.getName();
2327 Record.append(Str.bytes_begin(), Str.bytes_end());
2328 Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
2329 Record.clear();
2331 // Write named metadata operands.
2332 for (const MDNode *N : NMD.operands())
2333 Record.push_back(VE.getMetadataID(N));
2334 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
2335 Record.clear();
2339 unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
2340 auto Abbv = std::make_shared<BitCodeAbbrev>();
2341 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS));
2342 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
2343 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
2344 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2345 return Stream.EmitAbbrev(std::move(Abbv));
2348 /// Write out a record for MDString.
2350 /// All the metadata strings in a metadata block are emitted in a single
2351 /// record. The sizes and strings themselves are shoved into a blob.
2352 void ModuleBitcodeWriter::writeMetadataStrings(
2353 ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) {
2354 if (Strings.empty())
2355 return;
2357 // Start the record with the number of strings.
2358 Record.push_back(bitc::METADATA_STRINGS);
2359 Record.push_back(Strings.size());
2361 // Emit the sizes of the strings in the blob.
2362 SmallString<256> Blob;
2364 BitstreamWriter W(Blob);
2365 for (const Metadata *MD : Strings)
2366 W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
2367 W.FlushToWord();
2370 // Add the offset to the strings to the record.
2371 Record.push_back(Blob.size());
2373 // Add the strings to the blob.
2374 for (const Metadata *MD : Strings)
2375 Blob.append(cast<MDString>(MD)->getString());
2377 // Emit the final record.
2378 Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
2379 Record.clear();
2382 // Generates an enum to use as an index in the Abbrev array of Metadata record.
2383 enum MetadataAbbrev : unsigned {
2384 #define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
2385 #include "llvm/IR/Metadata.def"
2386 LastPlusOne
2389 void ModuleBitcodeWriter::writeMetadataRecords(
2390 ArrayRef<const Metadata *> MDs, SmallVectorImpl<uint64_t> &Record,
2391 std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
2392 if (MDs.empty())
2393 return;
2395 // Initialize MDNode abbreviations.
2396 #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
2397 #include "llvm/IR/Metadata.def"
2399 for (const Metadata *MD : MDs) {
2400 if (IndexPos)
2401 IndexPos->push_back(Stream.GetCurrentBitNo());
2402 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
2403 assert(N->isResolved() && "Expected forward references to be resolved");
2405 switch (N->getMetadataID()) {
2406 default:
2407 llvm_unreachable("Invalid MDNode subclass");
2408 #define HANDLE_MDNODE_LEAF(CLASS) \
2409 case Metadata::CLASS##Kind: \
2410 if (MDAbbrevs) \
2411 write##CLASS(cast<CLASS>(N), Record, \
2412 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
2413 else \
2414 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
2415 continue;
2416 #include "llvm/IR/Metadata.def"
2419 if (auto *AL = dyn_cast<DIArgList>(MD)) {
2420 writeDIArgList(AL, Record);
2421 continue;
2423 writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
2427 void ModuleBitcodeWriter::writeModuleMetadata() {
2428 if (!VE.hasMDs() && M.named_metadata_empty())
2429 return;
2431 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 4);
2432 SmallVector<uint64_t, 64> Record;
2434 // Emit all abbrevs upfront, so that the reader can jump in the middle of the
2435 // block and load any metadata.
2436 std::vector<unsigned> MDAbbrevs;
2438 MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
2439 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
2440 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
2441 createGenericDINodeAbbrev();
2443 auto Abbv = std::make_shared<BitCodeAbbrev>();
2444 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX_OFFSET));
2445 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2446 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2447 unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2449 Abbv = std::make_shared<BitCodeAbbrev>();
2450 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX));
2451 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2452 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2453 unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2455 // Emit MDStrings together upfront.
2456 writeMetadataStrings(VE.getMDStrings(), Record);
2458 // We only emit an index for the metadata record if we have more than a given
2459 // (naive) threshold of metadatas, otherwise it is not worth it.
2460 if (VE.getNonMDStrings().size() > IndexThreshold) {
2461 // Write a placeholder value in for the offset of the metadata index,
2462 // which is written after the records, so that it can include
2463 // the offset of each entry. The placeholder offset will be
2464 // updated after all records are emitted.
2465 uint64_t Vals[] = {0, 0};
2466 Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
2469 // Compute and save the bit offset to the current position, which will be
2470 // patched when we emit the index later. We can simply subtract the 64-bit
2471 // fixed size from the current bit number to get the location to backpatch.
2472 uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
2474 // This index will contain the bitpos for each individual record.
2475 std::vector<uint64_t> IndexPos;
2476 IndexPos.reserve(VE.getNonMDStrings().size());
2478 // Write all the records
2479 writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
2481 if (VE.getNonMDStrings().size() > IndexThreshold) {
2482 // Now that we have emitted all the records we will emit the index. But
2483 // first
2484 // backpatch the forward reference so that the reader can skip the records
2485 // efficiently.
2486 Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
2487 Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
2489 // Delta encode the index.
2490 uint64_t PreviousValue = IndexOffsetRecordBitPos;
2491 for (auto &Elt : IndexPos) {
2492 auto EltDelta = Elt - PreviousValue;
2493 PreviousValue = Elt;
2494 Elt = EltDelta;
2496 // Emit the index record.
2497 Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
2498 IndexPos.clear();
2501 // Write the named metadata now.
2502 writeNamedMetadata(Record);
2504 auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
2505 SmallVector<uint64_t, 4> Record;
2506 Record.push_back(VE.getValueID(&GO));
2507 pushGlobalMetadataAttachment(Record, GO);
2508 Stream.EmitRecord(bitc::METADATA_GLOBAL_DECL_ATTACHMENT, Record);
2510 for (const Function &F : M)
2511 if (F.isDeclaration() && F.hasMetadata())
2512 AddDeclAttachedMetadata(F);
2513 // FIXME: Only store metadata for declarations here, and move data for global
2514 // variable definitions to a separate block (PR28134).
2515 for (const GlobalVariable &GV : M.globals())
2516 if (GV.hasMetadata())
2517 AddDeclAttachedMetadata(GV);
2519 Stream.ExitBlock();
2522 void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
2523 if (!VE.hasMDs())
2524 return;
2526 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
2527 SmallVector<uint64_t, 64> Record;
2528 writeMetadataStrings(VE.getMDStrings(), Record);
2529 writeMetadataRecords(VE.getNonMDStrings(), Record);
2530 Stream.ExitBlock();
2533 void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
2534 SmallVectorImpl<uint64_t> &Record, const GlobalObject &GO) {
2535 // [n x [id, mdnode]]
2536 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2537 GO.getAllMetadata(MDs);
2538 for (const auto &I : MDs) {
2539 Record.push_back(I.first);
2540 Record.push_back(VE.getMetadataID(I.second));
2544 void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
2545 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
2547 SmallVector<uint64_t, 64> Record;
2549 if (F.hasMetadata()) {
2550 pushGlobalMetadataAttachment(Record, F);
2551 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
2552 Record.clear();
2555 // Write metadata attachments
2556 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
2557 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2558 for (const BasicBlock &BB : F)
2559 for (const Instruction &I : BB) {
2560 MDs.clear();
2561 I.getAllMetadataOtherThanDebugLoc(MDs);
2563 // If no metadata, ignore instruction.
2564 if (MDs.empty()) continue;
2566 Record.push_back(VE.getInstructionID(&I));
2568 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
2569 Record.push_back(MDs[i].first);
2570 Record.push_back(VE.getMetadataID(MDs[i].second));
2572 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
2573 Record.clear();
2576 Stream.ExitBlock();
2579 void ModuleBitcodeWriter::writeModuleMetadataKinds() {
2580 SmallVector<uint64_t, 64> Record;
2582 // Write metadata kinds
2583 // METADATA_KIND - [n x [id, name]]
2584 SmallVector<StringRef, 8> Names;
2585 M.getMDKindNames(Names);
2587 if (Names.empty()) return;
2589 Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3);
2591 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
2592 Record.push_back(MDKindID);
2593 StringRef KName = Names[MDKindID];
2594 Record.append(KName.begin(), KName.end());
2596 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
2597 Record.clear();
2600 Stream.ExitBlock();
2603 void ModuleBitcodeWriter::writeOperandBundleTags() {
2604 // Write metadata kinds
2606 // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
2608 // OPERAND_BUNDLE_TAG - [strchr x N]
2610 SmallVector<StringRef, 8> Tags;
2611 M.getOperandBundleTags(Tags);
2613 if (Tags.empty())
2614 return;
2616 Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3);
2618 SmallVector<uint64_t, 64> Record;
2620 for (auto Tag : Tags) {
2621 Record.append(Tag.begin(), Tag.end());
2623 Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
2624 Record.clear();
2627 Stream.ExitBlock();
2630 void ModuleBitcodeWriter::writeSyncScopeNames() {
2631 SmallVector<StringRef, 8> SSNs;
2632 M.getContext().getSyncScopeNames(SSNs);
2633 if (SSNs.empty())
2634 return;
2636 Stream.EnterSubblock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID, 2);
2638 SmallVector<uint64_t, 64> Record;
2639 for (auto SSN : SSNs) {
2640 Record.append(SSN.begin(), SSN.end());
2641 Stream.EmitRecord(bitc::SYNC_SCOPE_NAME, Record, 0);
2642 Record.clear();
2645 Stream.ExitBlock();
2648 void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
2649 bool isGlobal) {
2650 if (FirstVal == LastVal) return;
2652 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
2654 unsigned AggregateAbbrev = 0;
2655 unsigned String8Abbrev = 0;
2656 unsigned CString7Abbrev = 0;
2657 unsigned CString6Abbrev = 0;
2658 // If this is a constant pool for the module, emit module-specific abbrevs.
2659 if (isGlobal) {
2660 // Abbrev for CST_CODE_AGGREGATE.
2661 auto Abbv = std::make_shared<BitCodeAbbrev>();
2662 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
2663 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2664 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
2665 AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2667 // Abbrev for CST_CODE_STRING.
2668 Abbv = std::make_shared<BitCodeAbbrev>();
2669 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
2670 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2671 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2672 String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2673 // Abbrev for CST_CODE_CSTRING.
2674 Abbv = std::make_shared<BitCodeAbbrev>();
2675 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2676 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2677 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2678 CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2679 // Abbrev for CST_CODE_CSTRING.
2680 Abbv = std::make_shared<BitCodeAbbrev>();
2681 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2682 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2683 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2684 CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2687 SmallVector<uint64_t, 64> Record;
2689 const ValueEnumerator::ValueList &Vals = VE.getValues();
2690 Type *LastTy = nullptr;
2691 for (unsigned i = FirstVal; i != LastVal; ++i) {
2692 const Value *V = Vals[i].first;
2693 // If we need to switch types, do so now.
2694 if (V->getType() != LastTy) {
2695 LastTy = V->getType();
2696 Record.push_back(VE.getTypeID(LastTy));
2697 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
2698 CONSTANTS_SETTYPE_ABBREV);
2699 Record.clear();
2702 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
2703 Record.push_back(VE.getTypeID(IA->getFunctionType()));
2704 Record.push_back(
2705 unsigned(IA->hasSideEffects()) | unsigned(IA->isAlignStack()) << 1 |
2706 unsigned(IA->getDialect() & 1) << 2 | unsigned(IA->canThrow()) << 3);
2708 // Add the asm string.
2709 const std::string &AsmStr = IA->getAsmString();
2710 Record.push_back(AsmStr.size());
2711 Record.append(AsmStr.begin(), AsmStr.end());
2713 // Add the constraint string.
2714 const std::string &ConstraintStr = IA->getConstraintString();
2715 Record.push_back(ConstraintStr.size());
2716 Record.append(ConstraintStr.begin(), ConstraintStr.end());
2717 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
2718 Record.clear();
2719 continue;
2721 const Constant *C = cast<Constant>(V);
2722 unsigned Code = -1U;
2723 unsigned AbbrevToUse = 0;
2724 if (C->isNullValue()) {
2725 Code = bitc::CST_CODE_NULL;
2726 } else if (isa<PoisonValue>(C)) {
2727 Code = bitc::CST_CODE_POISON;
2728 } else if (isa<UndefValue>(C)) {
2729 Code = bitc::CST_CODE_UNDEF;
2730 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
2731 if (IV->getBitWidth() <= 64) {
2732 uint64_t V = IV->getSExtValue();
2733 emitSignedInt64(Record, V);
2734 Code = bitc::CST_CODE_INTEGER;
2735 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
2736 } else { // Wide integers, > 64 bits in size.
2737 emitWideAPInt(Record, IV->getValue());
2738 Code = bitc::CST_CODE_WIDE_INTEGER;
2740 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
2741 Code = bitc::CST_CODE_FLOAT;
2742 Type *Ty = CFP->getType()->getScalarType();
2743 if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() ||
2744 Ty->isDoubleTy()) {
2745 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
2746 } else if (Ty->isX86_FP80Ty()) {
2747 // api needed to prevent premature destruction
2748 // bits are not in the same order as a normal i80 APInt, compensate.
2749 APInt api = CFP->getValueAPF().bitcastToAPInt();
2750 const uint64_t *p = api.getRawData();
2751 Record.push_back((p[1] << 48) | (p[0] >> 16));
2752 Record.push_back(p[0] & 0xffffLL);
2753 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
2754 APInt api = CFP->getValueAPF().bitcastToAPInt();
2755 const uint64_t *p = api.getRawData();
2756 Record.push_back(p[0]);
2757 Record.push_back(p[1]);
2758 } else {
2759 assert(0 && "Unknown FP type!");
2761 } else if (isa<ConstantDataSequential>(C) &&
2762 cast<ConstantDataSequential>(C)->isString()) {
2763 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
2764 // Emit constant strings specially.
2765 unsigned NumElts = Str->getNumElements();
2766 // If this is a null-terminated string, use the denser CSTRING encoding.
2767 if (Str->isCString()) {
2768 Code = bitc::CST_CODE_CSTRING;
2769 --NumElts; // Don't encode the null, which isn't allowed by char6.
2770 } else {
2771 Code = bitc::CST_CODE_STRING;
2772 AbbrevToUse = String8Abbrev;
2774 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
2775 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
2776 for (unsigned i = 0; i != NumElts; ++i) {
2777 unsigned char V = Str->getElementAsInteger(i);
2778 Record.push_back(V);
2779 isCStr7 &= (V & 128) == 0;
2780 if (isCStrChar6)
2781 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
2784 if (isCStrChar6)
2785 AbbrevToUse = CString6Abbrev;
2786 else if (isCStr7)
2787 AbbrevToUse = CString7Abbrev;
2788 } else if (const ConstantDataSequential *CDS =
2789 dyn_cast<ConstantDataSequential>(C)) {
2790 Code = bitc::CST_CODE_DATA;
2791 Type *EltTy = CDS->getElementType();
2792 if (isa<IntegerType>(EltTy)) {
2793 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2794 Record.push_back(CDS->getElementAsInteger(i));
2795 } else {
2796 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2797 Record.push_back(
2798 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
2800 } else if (isa<ConstantAggregate>(C)) {
2801 Code = bitc::CST_CODE_AGGREGATE;
2802 for (const Value *Op : C->operands())
2803 Record.push_back(VE.getValueID(Op));
2804 AbbrevToUse = AggregateAbbrev;
2805 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2806 switch (CE->getOpcode()) {
2807 default:
2808 if (Instruction::isCast(CE->getOpcode())) {
2809 Code = bitc::CST_CODE_CE_CAST;
2810 Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
2811 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2812 Record.push_back(VE.getValueID(C->getOperand(0)));
2813 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
2814 } else {
2815 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
2816 Code = bitc::CST_CODE_CE_BINOP;
2817 Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
2818 Record.push_back(VE.getValueID(C->getOperand(0)));
2819 Record.push_back(VE.getValueID(C->getOperand(1)));
2820 uint64_t Flags = getOptimizationFlags(CE);
2821 if (Flags != 0)
2822 Record.push_back(Flags);
2824 break;
2825 case Instruction::FNeg: {
2826 assert(CE->getNumOperands() == 1 && "Unknown constant expr!");
2827 Code = bitc::CST_CODE_CE_UNOP;
2828 Record.push_back(getEncodedUnaryOpcode(CE->getOpcode()));
2829 Record.push_back(VE.getValueID(C->getOperand(0)));
2830 uint64_t Flags = getOptimizationFlags(CE);
2831 if (Flags != 0)
2832 Record.push_back(Flags);
2833 break;
2835 case Instruction::GetElementPtr: {
2836 Code = bitc::CST_CODE_CE_GEP;
2837 const auto *GO = cast<GEPOperator>(C);
2838 Record.push_back(VE.getTypeID(GO->getSourceElementType()));
2839 Record.push_back(getOptimizationFlags(GO));
2840 if (std::optional<ConstantRange> Range = GO->getInRange()) {
2841 Code = bitc::CST_CODE_CE_GEP_WITH_INRANGE;
2842 emitConstantRange(Record, *Range, /*EmitBitWidth=*/true);
2844 for (const Value *Op : CE->operands()) {
2845 Record.push_back(VE.getTypeID(Op->getType()));
2846 Record.push_back(VE.getValueID(Op));
2848 break;
2850 case Instruction::ExtractElement:
2851 Code = bitc::CST_CODE_CE_EXTRACTELT;
2852 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2853 Record.push_back(VE.getValueID(C->getOperand(0)));
2854 Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
2855 Record.push_back(VE.getValueID(C->getOperand(1)));
2856 break;
2857 case Instruction::InsertElement:
2858 Code = bitc::CST_CODE_CE_INSERTELT;
2859 Record.push_back(VE.getValueID(C->getOperand(0)));
2860 Record.push_back(VE.getValueID(C->getOperand(1)));
2861 Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
2862 Record.push_back(VE.getValueID(C->getOperand(2)));
2863 break;
2864 case Instruction::ShuffleVector:
2865 // If the return type and argument types are the same, this is a
2866 // standard shufflevector instruction. If the types are different,
2867 // then the shuffle is widening or truncating the input vectors, and
2868 // the argument type must also be encoded.
2869 if (C->getType() == C->getOperand(0)->getType()) {
2870 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
2871 } else {
2872 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
2873 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2875 Record.push_back(VE.getValueID(C->getOperand(0)));
2876 Record.push_back(VE.getValueID(C->getOperand(1)));
2877 Record.push_back(VE.getValueID(CE->getShuffleMaskForBitcode()));
2878 break;
2880 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
2881 Code = bitc::CST_CODE_BLOCKADDRESS;
2882 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
2883 Record.push_back(VE.getValueID(BA->getFunction()));
2884 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
2885 } else if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) {
2886 Code = bitc::CST_CODE_DSO_LOCAL_EQUIVALENT;
2887 Record.push_back(VE.getTypeID(Equiv->getGlobalValue()->getType()));
2888 Record.push_back(VE.getValueID(Equiv->getGlobalValue()));
2889 } else if (const auto *NC = dyn_cast<NoCFIValue>(C)) {
2890 Code = bitc::CST_CODE_NO_CFI_VALUE;
2891 Record.push_back(VE.getTypeID(NC->getGlobalValue()->getType()));
2892 Record.push_back(VE.getValueID(NC->getGlobalValue()));
2893 } else if (const auto *CPA = dyn_cast<ConstantPtrAuth>(C)) {
2894 Code = bitc::CST_CODE_PTRAUTH;
2895 Record.push_back(VE.getValueID(CPA->getPointer()));
2896 Record.push_back(VE.getValueID(CPA->getKey()));
2897 Record.push_back(VE.getValueID(CPA->getDiscriminator()));
2898 Record.push_back(VE.getValueID(CPA->getAddrDiscriminator()));
2899 } else {
2900 #ifndef NDEBUG
2901 C->dump();
2902 #endif
2903 llvm_unreachable("Unknown constant!");
2905 Stream.EmitRecord(Code, Record, AbbrevToUse);
2906 Record.clear();
2909 Stream.ExitBlock();
2912 void ModuleBitcodeWriter::writeModuleConstants() {
2913 const ValueEnumerator::ValueList &Vals = VE.getValues();
2915 // Find the first constant to emit, which is the first non-globalvalue value.
2916 // We know globalvalues have been emitted by WriteModuleInfo.
2917 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
2918 if (!isa<GlobalValue>(Vals[i].first)) {
2919 writeConstants(i, Vals.size(), true);
2920 return;
2925 /// pushValueAndType - The file has to encode both the value and type id for
2926 /// many values, because we need to know what type to create for forward
2927 /// references. However, most operands are not forward references, so this type
2928 /// field is not needed.
2930 /// This function adds V's value ID to Vals. If the value ID is higher than the
2931 /// instruction ID, then it is a forward reference, and it also includes the
2932 /// type ID. The value ID that is written is encoded relative to the InstID.
2933 bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
2934 SmallVectorImpl<unsigned> &Vals) {
2935 unsigned ValID = VE.getValueID(V);
2936 // Make encoding relative to the InstID.
2937 Vals.push_back(InstID - ValID);
2938 if (ValID >= InstID) {
2939 Vals.push_back(VE.getTypeID(V->getType()));
2940 return true;
2942 return false;
2945 bool ModuleBitcodeWriter::pushValueOrMetadata(const Value *V, unsigned InstID,
2946 SmallVectorImpl<unsigned> &Vals) {
2947 bool IsMetadata = V->getType()->isMetadataTy();
2948 if (IsMetadata) {
2949 Vals.push_back(bitc::OB_METADATA);
2950 Metadata *MD = cast<MetadataAsValue>(V)->getMetadata();
2951 unsigned ValID = VE.getMetadataID(MD);
2952 Vals.push_back(InstID - ValID);
2953 return false;
2955 return pushValueAndType(V, InstID, Vals);
2958 void ModuleBitcodeWriter::writeOperandBundles(const CallBase &CS,
2959 unsigned InstID) {
2960 SmallVector<unsigned, 64> Record;
2961 LLVMContext &C = CS.getContext();
2963 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
2964 const auto &Bundle = CS.getOperandBundleAt(i);
2965 Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
2967 for (auto &Input : Bundle.Inputs)
2968 pushValueOrMetadata(Input, InstID, Record);
2970 Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record);
2971 Record.clear();
2975 /// pushValue - Like pushValueAndType, but where the type of the value is
2976 /// omitted (perhaps it was already encoded in an earlier operand).
2977 void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
2978 SmallVectorImpl<unsigned> &Vals) {
2979 unsigned ValID = VE.getValueID(V);
2980 Vals.push_back(InstID - ValID);
2983 void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
2984 SmallVectorImpl<uint64_t> &Vals) {
2985 unsigned ValID = VE.getValueID(V);
2986 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
2987 emitSignedInt64(Vals, diff);
2990 /// WriteInstruction - Emit an instruction to the specified stream.
2991 void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
2992 unsigned InstID,
2993 SmallVectorImpl<unsigned> &Vals) {
2994 unsigned Code = 0;
2995 unsigned AbbrevToUse = 0;
2996 VE.setInstructionID(&I);
2997 switch (I.getOpcode()) {
2998 default:
2999 if (Instruction::isCast(I.getOpcode())) {
3000 Code = bitc::FUNC_CODE_INST_CAST;
3001 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
3002 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
3003 Vals.push_back(VE.getTypeID(I.getType()));
3004 Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
3005 uint64_t Flags = getOptimizationFlags(&I);
3006 if (Flags != 0) {
3007 if (AbbrevToUse == FUNCTION_INST_CAST_ABBREV)
3008 AbbrevToUse = FUNCTION_INST_CAST_FLAGS_ABBREV;
3009 Vals.push_back(Flags);
3011 } else {
3012 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
3013 Code = bitc::FUNC_CODE_INST_BINOP;
3014 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
3015 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
3016 pushValue(I.getOperand(1), InstID, Vals);
3017 Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
3018 uint64_t Flags = getOptimizationFlags(&I);
3019 if (Flags != 0) {
3020 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
3021 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
3022 Vals.push_back(Flags);
3025 break;
3026 case Instruction::FNeg: {
3027 Code = bitc::FUNC_CODE_INST_UNOP;
3028 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
3029 AbbrevToUse = FUNCTION_INST_UNOP_ABBREV;
3030 Vals.push_back(getEncodedUnaryOpcode(I.getOpcode()));
3031 uint64_t Flags = getOptimizationFlags(&I);
3032 if (Flags != 0) {
3033 if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV)
3034 AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV;
3035 Vals.push_back(Flags);
3037 break;
3039 case Instruction::GetElementPtr: {
3040 Code = bitc::FUNC_CODE_INST_GEP;
3041 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
3042 auto &GEPInst = cast<GetElementPtrInst>(I);
3043 Vals.push_back(getOptimizationFlags(&I));
3044 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
3045 for (const Value *Op : I.operands())
3046 pushValueAndType(Op, InstID, Vals);
3047 break;
3049 case Instruction::ExtractValue: {
3050 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
3051 pushValueAndType(I.getOperand(0), InstID, Vals);
3052 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
3053 Vals.append(EVI->idx_begin(), EVI->idx_end());
3054 break;
3056 case Instruction::InsertValue: {
3057 Code = bitc::FUNC_CODE_INST_INSERTVAL;
3058 pushValueAndType(I.getOperand(0), InstID, Vals);
3059 pushValueAndType(I.getOperand(1), InstID, Vals);
3060 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
3061 Vals.append(IVI->idx_begin(), IVI->idx_end());
3062 break;
3064 case Instruction::Select: {
3065 Code = bitc::FUNC_CODE_INST_VSELECT;
3066 pushValueAndType(I.getOperand(1), InstID, Vals);
3067 pushValue(I.getOperand(2), InstID, Vals);
3068 pushValueAndType(I.getOperand(0), InstID, Vals);
3069 uint64_t Flags = getOptimizationFlags(&I);
3070 if (Flags != 0)
3071 Vals.push_back(Flags);
3072 break;
3074 case Instruction::ExtractElement:
3075 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
3076 pushValueAndType(I.getOperand(0), InstID, Vals);
3077 pushValueAndType(I.getOperand(1), InstID, Vals);
3078 break;
3079 case Instruction::InsertElement:
3080 Code = bitc::FUNC_CODE_INST_INSERTELT;
3081 pushValueAndType(I.getOperand(0), InstID, Vals);
3082 pushValue(I.getOperand(1), InstID, Vals);
3083 pushValueAndType(I.getOperand(2), InstID, Vals);
3084 break;
3085 case Instruction::ShuffleVector:
3086 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
3087 pushValueAndType(I.getOperand(0), InstID, Vals);
3088 pushValue(I.getOperand(1), InstID, Vals);
3089 pushValue(cast<ShuffleVectorInst>(I).getShuffleMaskForBitcode(), InstID,
3090 Vals);
3091 break;
3092 case Instruction::ICmp:
3093 case Instruction::FCmp: {
3094 // compare returning Int1Ty or vector of Int1Ty
3095 Code = bitc::FUNC_CODE_INST_CMP2;
3096 pushValueAndType(I.getOperand(0), InstID, Vals);
3097 pushValue(I.getOperand(1), InstID, Vals);
3098 Vals.push_back(cast<CmpInst>(I).getPredicate());
3099 uint64_t Flags = getOptimizationFlags(&I);
3100 if (Flags != 0)
3101 Vals.push_back(Flags);
3102 break;
3105 case Instruction::Ret:
3107 Code = bitc::FUNC_CODE_INST_RET;
3108 unsigned NumOperands = I.getNumOperands();
3109 if (NumOperands == 0)
3110 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
3111 else if (NumOperands == 1) {
3112 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
3113 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
3114 } else {
3115 for (const Value *Op : I.operands())
3116 pushValueAndType(Op, InstID, Vals);
3119 break;
3120 case Instruction::Br:
3122 Code = bitc::FUNC_CODE_INST_BR;
3123 const BranchInst &II = cast<BranchInst>(I);
3124 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
3125 if (II.isConditional()) {
3126 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
3127 pushValue(II.getCondition(), InstID, Vals);
3130 break;
3131 case Instruction::Switch:
3133 Code = bitc::FUNC_CODE_INST_SWITCH;
3134 const SwitchInst &SI = cast<SwitchInst>(I);
3135 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
3136 pushValue(SI.getCondition(), InstID, Vals);
3137 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
3138 for (auto Case : SI.cases()) {
3139 Vals.push_back(VE.getValueID(Case.getCaseValue()));
3140 Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
3143 break;
3144 case Instruction::IndirectBr:
3145 Code = bitc::FUNC_CODE_INST_INDIRECTBR;
3146 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
3147 // Encode the address operand as relative, but not the basic blocks.
3148 pushValue(I.getOperand(0), InstID, Vals);
3149 for (const Value *Op : drop_begin(I.operands()))
3150 Vals.push_back(VE.getValueID(Op));
3151 break;
3153 case Instruction::Invoke: {
3154 const InvokeInst *II = cast<InvokeInst>(&I);
3155 const Value *Callee = II->getCalledOperand();
3156 FunctionType *FTy = II->getFunctionType();
3158 if (II->hasOperandBundles())
3159 writeOperandBundles(*II, InstID);
3161 Code = bitc::FUNC_CODE_INST_INVOKE;
3163 Vals.push_back(VE.getAttributeListID(II->getAttributes()));
3164 Vals.push_back(II->getCallingConv() | 1 << 13);
3165 Vals.push_back(VE.getValueID(II->getNormalDest()));
3166 Vals.push_back(VE.getValueID(II->getUnwindDest()));
3167 Vals.push_back(VE.getTypeID(FTy));
3168 pushValueAndType(Callee, InstID, Vals);
3170 // Emit value #'s for the fixed parameters.
3171 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3172 pushValue(I.getOperand(i), InstID, Vals); // fixed param.
3174 // Emit type/value pairs for varargs params.
3175 if (FTy->isVarArg()) {
3176 for (unsigned i = FTy->getNumParams(), e = II->arg_size(); i != e; ++i)
3177 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
3179 break;
3181 case Instruction::Resume:
3182 Code = bitc::FUNC_CODE_INST_RESUME;
3183 pushValueAndType(I.getOperand(0), InstID, Vals);
3184 break;
3185 case Instruction::CleanupRet: {
3186 Code = bitc::FUNC_CODE_INST_CLEANUPRET;
3187 const auto &CRI = cast<CleanupReturnInst>(I);
3188 pushValue(CRI.getCleanupPad(), InstID, Vals);
3189 if (CRI.hasUnwindDest())
3190 Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
3191 break;
3193 case Instruction::CatchRet: {
3194 Code = bitc::FUNC_CODE_INST_CATCHRET;
3195 const auto &CRI = cast<CatchReturnInst>(I);
3196 pushValue(CRI.getCatchPad(), InstID, Vals);
3197 Vals.push_back(VE.getValueID(CRI.getSuccessor()));
3198 break;
3200 case Instruction::CleanupPad:
3201 case Instruction::CatchPad: {
3202 const auto &FuncletPad = cast<FuncletPadInst>(I);
3203 Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
3204 : bitc::FUNC_CODE_INST_CLEANUPPAD;
3205 pushValue(FuncletPad.getParentPad(), InstID, Vals);
3207 unsigned NumArgOperands = FuncletPad.arg_size();
3208 Vals.push_back(NumArgOperands);
3209 for (unsigned Op = 0; Op != NumArgOperands; ++Op)
3210 pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
3211 break;
3213 case Instruction::CatchSwitch: {
3214 Code = bitc::FUNC_CODE_INST_CATCHSWITCH;
3215 const auto &CatchSwitch = cast<CatchSwitchInst>(I);
3217 pushValue(CatchSwitch.getParentPad(), InstID, Vals);
3219 unsigned NumHandlers = CatchSwitch.getNumHandlers();
3220 Vals.push_back(NumHandlers);
3221 for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
3222 Vals.push_back(VE.getValueID(CatchPadBB));
3224 if (CatchSwitch.hasUnwindDest())
3225 Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
3226 break;
3228 case Instruction::CallBr: {
3229 const CallBrInst *CBI = cast<CallBrInst>(&I);
3230 const Value *Callee = CBI->getCalledOperand();
3231 FunctionType *FTy = CBI->getFunctionType();
3233 if (CBI->hasOperandBundles())
3234 writeOperandBundles(*CBI, InstID);
3236 Code = bitc::FUNC_CODE_INST_CALLBR;
3238 Vals.push_back(VE.getAttributeListID(CBI->getAttributes()));
3240 Vals.push_back(CBI->getCallingConv() << bitc::CALL_CCONV |
3241 1 << bitc::CALL_EXPLICIT_TYPE);
3243 Vals.push_back(VE.getValueID(CBI->getDefaultDest()));
3244 Vals.push_back(CBI->getNumIndirectDests());
3245 for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i)
3246 Vals.push_back(VE.getValueID(CBI->getIndirectDest(i)));
3248 Vals.push_back(VE.getTypeID(FTy));
3249 pushValueAndType(Callee, InstID, Vals);
3251 // Emit value #'s for the fixed parameters.
3252 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3253 pushValue(I.getOperand(i), InstID, Vals); // fixed param.
3255 // Emit type/value pairs for varargs params.
3256 if (FTy->isVarArg()) {
3257 for (unsigned i = FTy->getNumParams(), e = CBI->arg_size(); i != e; ++i)
3258 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
3260 break;
3262 case Instruction::Unreachable:
3263 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
3264 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
3265 break;
3267 case Instruction::PHI: {
3268 const PHINode &PN = cast<PHINode>(I);
3269 Code = bitc::FUNC_CODE_INST_PHI;
3270 // With the newer instruction encoding, forward references could give
3271 // negative valued IDs. This is most common for PHIs, so we use
3272 // signed VBRs.
3273 SmallVector<uint64_t, 128> Vals64;
3274 Vals64.push_back(VE.getTypeID(PN.getType()));
3275 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
3276 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
3277 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
3280 uint64_t Flags = getOptimizationFlags(&I);
3281 if (Flags != 0)
3282 Vals64.push_back(Flags);
3284 // Emit a Vals64 vector and exit.
3285 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
3286 Vals64.clear();
3287 return;
3290 case Instruction::LandingPad: {
3291 const LandingPadInst &LP = cast<LandingPadInst>(I);
3292 Code = bitc::FUNC_CODE_INST_LANDINGPAD;
3293 Vals.push_back(VE.getTypeID(LP.getType()));
3294 Vals.push_back(LP.isCleanup());
3295 Vals.push_back(LP.getNumClauses());
3296 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
3297 if (LP.isCatch(I))
3298 Vals.push_back(LandingPadInst::Catch);
3299 else
3300 Vals.push_back(LandingPadInst::Filter);
3301 pushValueAndType(LP.getClause(I), InstID, Vals);
3303 break;
3306 case Instruction::Alloca: {
3307 Code = bitc::FUNC_CODE_INST_ALLOCA;
3308 const AllocaInst &AI = cast<AllocaInst>(I);
3309 Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
3310 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
3311 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
3312 using APV = AllocaPackedValues;
3313 unsigned Record = 0;
3314 unsigned EncodedAlign = getEncodedAlign(AI.getAlign());
3315 Bitfield::set<APV::AlignLower>(
3316 Record, EncodedAlign & ((1 << APV::AlignLower::Bits) - 1));
3317 Bitfield::set<APV::AlignUpper>(Record,
3318 EncodedAlign >> APV::AlignLower::Bits);
3319 Bitfield::set<APV::UsedWithInAlloca>(Record, AI.isUsedWithInAlloca());
3320 Bitfield::set<APV::ExplicitType>(Record, true);
3321 Bitfield::set<APV::SwiftError>(Record, AI.isSwiftError());
3322 Vals.push_back(Record);
3324 unsigned AS = AI.getAddressSpace();
3325 if (AS != M.getDataLayout().getAllocaAddrSpace())
3326 Vals.push_back(AS);
3327 break;
3330 case Instruction::Load:
3331 if (cast<LoadInst>(I).isAtomic()) {
3332 Code = bitc::FUNC_CODE_INST_LOADATOMIC;
3333 pushValueAndType(I.getOperand(0), InstID, Vals);
3334 } else {
3335 Code = bitc::FUNC_CODE_INST_LOAD;
3336 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
3337 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
3339 Vals.push_back(VE.getTypeID(I.getType()));
3340 Vals.push_back(getEncodedAlign(cast<LoadInst>(I).getAlign()));
3341 Vals.push_back(cast<LoadInst>(I).isVolatile());
3342 if (cast<LoadInst>(I).isAtomic()) {
3343 Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
3344 Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID()));
3346 break;
3347 case Instruction::Store:
3348 if (cast<StoreInst>(I).isAtomic())
3349 Code = bitc::FUNC_CODE_INST_STOREATOMIC;
3350 else
3351 Code = bitc::FUNC_CODE_INST_STORE;
3352 pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr
3353 pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val
3354 Vals.push_back(getEncodedAlign(cast<StoreInst>(I).getAlign()));
3355 Vals.push_back(cast<StoreInst>(I).isVolatile());
3356 if (cast<StoreInst>(I).isAtomic()) {
3357 Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
3358 Vals.push_back(
3359 getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID()));
3361 break;
3362 case Instruction::AtomicCmpXchg:
3363 Code = bitc::FUNC_CODE_INST_CMPXCHG;
3364 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
3365 pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
3366 pushValue(I.getOperand(2), InstID, Vals); // newval.
3367 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
3368 Vals.push_back(
3369 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
3370 Vals.push_back(
3371 getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID()));
3372 Vals.push_back(
3373 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
3374 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
3375 Vals.push_back(getEncodedAlign(cast<AtomicCmpXchgInst>(I).getAlign()));
3376 break;
3377 case Instruction::AtomicRMW:
3378 Code = bitc::FUNC_CODE_INST_ATOMICRMW;
3379 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
3380 pushValueAndType(I.getOperand(1), InstID, Vals); // valty + val
3381 Vals.push_back(
3382 getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
3383 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
3384 Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
3385 Vals.push_back(
3386 getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID()));
3387 Vals.push_back(getEncodedAlign(cast<AtomicRMWInst>(I).getAlign()));
3388 break;
3389 case Instruction::Fence:
3390 Code = bitc::FUNC_CODE_INST_FENCE;
3391 Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
3392 Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID()));
3393 break;
3394 case Instruction::Call: {
3395 const CallInst &CI = cast<CallInst>(I);
3396 FunctionType *FTy = CI.getFunctionType();
3398 if (CI.hasOperandBundles())
3399 writeOperandBundles(CI, InstID);
3401 Code = bitc::FUNC_CODE_INST_CALL;
3403 Vals.push_back(VE.getAttributeListID(CI.getAttributes()));
3405 unsigned Flags = getOptimizationFlags(&I);
3406 Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |
3407 unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
3408 unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
3409 1 << bitc::CALL_EXPLICIT_TYPE |
3410 unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
3411 unsigned(Flags != 0) << bitc::CALL_FMF);
3412 if (Flags != 0)
3413 Vals.push_back(Flags);
3415 Vals.push_back(VE.getTypeID(FTy));
3416 pushValueAndType(CI.getCalledOperand(), InstID, Vals); // Callee
3418 // Emit value #'s for the fixed parameters.
3419 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3420 // Check for labels (can happen with asm labels).
3421 if (FTy->getParamType(i)->isLabelTy())
3422 Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
3423 else
3424 pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
3427 // Emit type/value pairs for varargs params.
3428 if (FTy->isVarArg()) {
3429 for (unsigned i = FTy->getNumParams(), e = CI.arg_size(); i != e; ++i)
3430 pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
3432 break;
3434 case Instruction::VAArg:
3435 Code = bitc::FUNC_CODE_INST_VAARG;
3436 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
3437 pushValue(I.getOperand(0), InstID, Vals); // valist.
3438 Vals.push_back(VE.getTypeID(I.getType())); // restype.
3439 break;
3440 case Instruction::Freeze:
3441 Code = bitc::FUNC_CODE_INST_FREEZE;
3442 pushValueAndType(I.getOperand(0), InstID, Vals);
3443 break;
3446 Stream.EmitRecord(Code, Vals, AbbrevToUse);
3447 Vals.clear();
3450 /// Write a GlobalValue VST to the module. The purpose of this data structure is
3451 /// to allow clients to efficiently find the function body.
3452 void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
3453 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3454 // Get the offset of the VST we are writing, and backpatch it into
3455 // the VST forward declaration record.
3456 uint64_t VSTOffset = Stream.GetCurrentBitNo();
3457 // The BitcodeStartBit was the stream offset of the identification block.
3458 VSTOffset -= bitcodeStartBit();
3459 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
3460 // Note that we add 1 here because the offset is relative to one word
3461 // before the start of the identification block, which was historically
3462 // always the start of the regular bitcode header.
3463 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
3465 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
3467 auto Abbv = std::make_shared<BitCodeAbbrev>();
3468 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
3469 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3470 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
3471 unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3473 for (const Function &F : M) {
3474 uint64_t Record[2];
3476 if (F.isDeclaration())
3477 continue;
3479 Record[0] = VE.getValueID(&F);
3481 // Save the word offset of the function (from the start of the
3482 // actual bitcode written to the stream).
3483 uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit();
3484 assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
3485 // Note that we add 1 here because the offset is relative to one word
3486 // before the start of the identification block, which was historically
3487 // always the start of the regular bitcode header.
3488 Record[1] = BitcodeIndex / 32 + 1;
3490 Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev);
3493 Stream.ExitBlock();
3496 /// Emit names for arguments, instructions and basic blocks in a function.
3497 void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
3498 const ValueSymbolTable &VST) {
3499 if (VST.empty())
3500 return;
3502 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
3504 // FIXME: Set up the abbrev, we know how many values there are!
3505 // FIXME: We know if the type names can use 7-bit ascii.
3506 SmallVector<uint64_t, 64> NameVals;
3508 for (const ValueName &Name : VST) {
3509 // Figure out the encoding to use for the name.
3510 StringEncoding Bits = getStringEncoding(Name.getKey());
3512 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
3513 NameVals.push_back(VE.getValueID(Name.getValue()));
3515 // VST_CODE_ENTRY: [valueid, namechar x N]
3516 // VST_CODE_BBENTRY: [bbid, namechar x N]
3517 unsigned Code;
3518 if (isa<BasicBlock>(Name.getValue())) {
3519 Code = bitc::VST_CODE_BBENTRY;
3520 if (Bits == SE_Char6)
3521 AbbrevToUse = VST_BBENTRY_6_ABBREV;
3522 } else {
3523 Code = bitc::VST_CODE_ENTRY;
3524 if (Bits == SE_Char6)
3525 AbbrevToUse = VST_ENTRY_6_ABBREV;
3526 else if (Bits == SE_Fixed7)
3527 AbbrevToUse = VST_ENTRY_7_ABBREV;
3530 for (const auto P : Name.getKey())
3531 NameVals.push_back((unsigned char)P);
3533 // Emit the finished record.
3534 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
3535 NameVals.clear();
3538 Stream.ExitBlock();
3541 void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
3542 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
3543 unsigned Code;
3544 if (isa<BasicBlock>(Order.V))
3545 Code = bitc::USELIST_CODE_BB;
3546 else
3547 Code = bitc::USELIST_CODE_DEFAULT;
3549 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
3550 Record.push_back(VE.getValueID(Order.V));
3551 Stream.EmitRecord(Code, Record);
3554 void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
3555 assert(VE.shouldPreserveUseListOrder() &&
3556 "Expected to be preserving use-list order");
3558 auto hasMore = [&]() {
3559 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
3561 if (!hasMore())
3562 // Nothing to do.
3563 return;
3565 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
3566 while (hasMore()) {
3567 writeUseList(std::move(VE.UseListOrders.back()));
3568 VE.UseListOrders.pop_back();
3570 Stream.ExitBlock();
3573 /// Emit a function body to the module stream.
3574 void ModuleBitcodeWriter::writeFunction(
3575 const Function &F,
3576 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3577 // Save the bitcode index of the start of this function block for recording
3578 // in the VST.
3579 FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
3581 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
3582 VE.incorporateFunction(F);
3584 SmallVector<unsigned, 64> Vals;
3586 // Emit the number of basic blocks, so the reader can create them ahead of
3587 // time.
3588 Vals.push_back(VE.getBasicBlocks().size());
3589 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
3590 Vals.clear();
3592 // If there are function-local constants, emit them now.
3593 unsigned CstStart, CstEnd;
3594 VE.getFunctionConstantRange(CstStart, CstEnd);
3595 writeConstants(CstStart, CstEnd, false);
3597 // If there is function-local metadata, emit it now.
3598 writeFunctionMetadata(F);
3600 // Keep a running idea of what the instruction ID is.
3601 unsigned InstID = CstEnd;
3603 bool NeedsMetadataAttachment = F.hasMetadata();
3605 DILocation *LastDL = nullptr;
3606 SmallSetVector<Function *, 4> BlockAddressUsers;
3608 // Finally, emit all the instructions, in order.
3609 for (const BasicBlock &BB : F) {
3610 for (const Instruction &I : BB) {
3611 writeInstruction(I, InstID, Vals);
3613 if (!I.getType()->isVoidTy())
3614 ++InstID;
3616 // If the instruction has metadata, write a metadata attachment later.
3617 NeedsMetadataAttachment |= I.hasMetadataOtherThanDebugLoc();
3619 // If the instruction has a debug location, emit it.
3620 if (DILocation *DL = I.getDebugLoc()) {
3621 if (DL == LastDL) {
3622 // Just repeat the same debug loc as last time.
3623 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
3624 } else {
3625 Vals.push_back(DL->getLine());
3626 Vals.push_back(DL->getColumn());
3627 Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
3628 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
3629 Vals.push_back(DL->isImplicitCode());
3630 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
3631 Vals.clear();
3632 LastDL = DL;
3636 // If the instruction has DbgRecords attached to it, emit them. Note that
3637 // they come after the instruction so that it's easy to attach them again
3638 // when reading the bitcode, even though conceptually the debug locations
3639 // start "before" the instruction.
3640 if (I.hasDbgRecords() && WriteNewDbgInfoFormatToBitcode) {
3641 /// Try to push the value only (unwrapped), otherwise push the
3642 /// metadata wrapped value. Returns true if the value was pushed
3643 /// without the ValueAsMetadata wrapper.
3644 auto PushValueOrMetadata = [&Vals, InstID,
3645 this](Metadata *RawLocation) {
3646 assert(RawLocation &&
3647 "RawLocation unexpectedly null in DbgVariableRecord");
3648 if (ValueAsMetadata *VAM = dyn_cast<ValueAsMetadata>(RawLocation)) {
3649 SmallVector<unsigned, 2> ValAndType;
3650 // If the value is a fwd-ref the type is also pushed. We don't
3651 // want the type, so fwd-refs are kept wrapped (pushValueAndType
3652 // returns false if the value is pushed without type).
3653 if (!pushValueAndType(VAM->getValue(), InstID, ValAndType)) {
3654 Vals.push_back(ValAndType[0]);
3655 return true;
3658 // The metadata is a DIArgList, or ValueAsMetadata wrapping a
3659 // fwd-ref. Push the metadata ID.
3660 Vals.push_back(VE.getMetadataID(RawLocation));
3661 return false;
3664 // Write out non-instruction debug information attached to this
3665 // instruction. Write it after the instruction so that it's easy to
3666 // re-attach to the instruction reading the records in.
3667 for (DbgRecord &DR : I.DebugMarker->getDbgRecordRange()) {
3668 if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) {
3669 Vals.push_back(VE.getMetadataID(&*DLR->getDebugLoc()));
3670 Vals.push_back(VE.getMetadataID(DLR->getLabel()));
3671 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_RECORD_LABEL, Vals);
3672 Vals.clear();
3673 continue;
3676 // First 3 fields are common to all kinds:
3677 // DILocation, DILocalVariable, DIExpression
3678 // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE)
3679 // ..., LocationMetadata
3680 // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE - abbrev'd)
3681 // ..., Value
3682 // dbg_declare (FUNC_CODE_DEBUG_RECORD_DECLARE)
3683 // ..., LocationMetadata
3684 // dbg_assign (FUNC_CODE_DEBUG_RECORD_ASSIGN)
3685 // ..., LocationMetadata, DIAssignID, DIExpression, LocationMetadata
3686 DbgVariableRecord &DVR = cast<DbgVariableRecord>(DR);
3687 Vals.push_back(VE.getMetadataID(&*DVR.getDebugLoc()));
3688 Vals.push_back(VE.getMetadataID(DVR.getVariable()));
3689 Vals.push_back(VE.getMetadataID(DVR.getExpression()));
3690 if (DVR.isDbgValue()) {
3691 if (PushValueOrMetadata(DVR.getRawLocation()))
3692 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE, Vals,
3693 FUNCTION_DEBUG_RECORD_VALUE_ABBREV);
3694 else
3695 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_RECORD_VALUE, Vals);
3696 } else if (DVR.isDbgDeclare()) {
3697 Vals.push_back(VE.getMetadataID(DVR.getRawLocation()));
3698 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_RECORD_DECLARE, Vals);
3699 } else {
3700 assert(DVR.isDbgAssign() && "Unexpected DbgRecord kind");
3701 Vals.push_back(VE.getMetadataID(DVR.getRawLocation()));
3702 Vals.push_back(VE.getMetadataID(DVR.getAssignID()));
3703 Vals.push_back(VE.getMetadataID(DVR.getAddressExpression()));
3704 Vals.push_back(VE.getMetadataID(DVR.getRawAddress()));
3705 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_RECORD_ASSIGN, Vals);
3707 Vals.clear();
3712 if (BlockAddress *BA = BlockAddress::lookup(&BB)) {
3713 SmallVector<Value *> Worklist{BA};
3714 SmallPtrSet<Value *, 8> Visited{BA};
3715 while (!Worklist.empty()) {
3716 Value *V = Worklist.pop_back_val();
3717 for (User *U : V->users()) {
3718 if (auto *I = dyn_cast<Instruction>(U)) {
3719 Function *P = I->getFunction();
3720 if (P != &F)
3721 BlockAddressUsers.insert(P);
3722 } else if (isa<Constant>(U) && !isa<GlobalValue>(U) &&
3723 Visited.insert(U).second)
3724 Worklist.push_back(U);
3730 if (!BlockAddressUsers.empty()) {
3731 Vals.resize(BlockAddressUsers.size());
3732 for (auto I : llvm::enumerate(BlockAddressUsers))
3733 Vals[I.index()] = VE.getValueID(I.value());
3734 Stream.EmitRecord(bitc::FUNC_CODE_BLOCKADDR_USERS, Vals);
3735 Vals.clear();
3738 // Emit names for all the instructions etc.
3739 if (auto *Symtab = F.getValueSymbolTable())
3740 writeFunctionLevelValueSymbolTable(*Symtab);
3742 if (NeedsMetadataAttachment)
3743 writeFunctionMetadataAttachment(F);
3744 if (VE.shouldPreserveUseListOrder())
3745 writeUseListBlock(&F);
3746 VE.purgeFunction();
3747 Stream.ExitBlock();
3750 // Emit blockinfo, which defines the standard abbreviations etc.
3751 void ModuleBitcodeWriter::writeBlockInfo() {
3752 // We only want to emit block info records for blocks that have multiple
3753 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
3754 // Other blocks can define their abbrevs inline.
3755 Stream.EnterBlockInfoBlock();
3757 { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
3758 auto Abbv = std::make_shared<BitCodeAbbrev>();
3759 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
3760 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3761 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3762 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
3763 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3764 VST_ENTRY_8_ABBREV)
3765 llvm_unreachable("Unexpected abbrev ordering!");
3768 { // 7-bit fixed width VST_CODE_ENTRY strings.
3769 auto Abbv = std::make_shared<BitCodeAbbrev>();
3770 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
3771 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3772 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3773 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
3774 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3775 VST_ENTRY_7_ABBREV)
3776 llvm_unreachable("Unexpected abbrev ordering!");
3778 { // 6-bit char6 VST_CODE_ENTRY strings.
3779 auto Abbv = std::make_shared<BitCodeAbbrev>();
3780 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
3781 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3782 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3783 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3784 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3785 VST_ENTRY_6_ABBREV)
3786 llvm_unreachable("Unexpected abbrev ordering!");
3788 { // 6-bit char6 VST_CODE_BBENTRY strings.
3789 auto Abbv = std::make_shared<BitCodeAbbrev>();
3790 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
3791 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3792 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3793 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3794 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3795 VST_BBENTRY_6_ABBREV)
3796 llvm_unreachable("Unexpected abbrev ordering!");
3799 { // SETTYPE abbrev for CONSTANTS_BLOCK.
3800 auto Abbv = std::make_shared<BitCodeAbbrev>();
3801 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
3802 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
3803 VE.computeBitsRequiredForTypeIndices()));
3804 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3805 CONSTANTS_SETTYPE_ABBREV)
3806 llvm_unreachable("Unexpected abbrev ordering!");
3809 { // INTEGER abbrev for CONSTANTS_BLOCK.
3810 auto Abbv = std::make_shared<BitCodeAbbrev>();
3811 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
3812 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3813 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3814 CONSTANTS_INTEGER_ABBREV)
3815 llvm_unreachable("Unexpected abbrev ordering!");
3818 { // CE_CAST abbrev for CONSTANTS_BLOCK.
3819 auto Abbv = std::make_shared<BitCodeAbbrev>();
3820 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
3821 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
3822 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
3823 VE.computeBitsRequiredForTypeIndices()));
3824 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3826 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3827 CONSTANTS_CE_CAST_Abbrev)
3828 llvm_unreachable("Unexpected abbrev ordering!");
3830 { // NULL abbrev for CONSTANTS_BLOCK.
3831 auto Abbv = std::make_shared<BitCodeAbbrev>();
3832 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
3833 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3834 CONSTANTS_NULL_Abbrev)
3835 llvm_unreachable("Unexpected abbrev ordering!");
3838 // FIXME: This should only use space for first class types!
3840 { // INST_LOAD abbrev for FUNCTION_BLOCK.
3841 auto Abbv = std::make_shared<BitCodeAbbrev>();
3842 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
3843 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
3844 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3845 VE.computeBitsRequiredForTypeIndices()));
3846 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
3847 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
3848 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3849 FUNCTION_INST_LOAD_ABBREV)
3850 llvm_unreachable("Unexpected abbrev ordering!");
3852 { // INST_UNOP abbrev for FUNCTION_BLOCK.
3853 auto Abbv = std::make_shared<BitCodeAbbrev>();
3854 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP));
3855 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3856 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3857 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3858 FUNCTION_INST_UNOP_ABBREV)
3859 llvm_unreachable("Unexpected abbrev ordering!");
3861 { // INST_UNOP_FLAGS abbrev for FUNCTION_BLOCK.
3862 auto Abbv = std::make_shared<BitCodeAbbrev>();
3863 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP));
3864 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3865 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3866 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
3867 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3868 FUNCTION_INST_UNOP_FLAGS_ABBREV)
3869 llvm_unreachable("Unexpected abbrev ordering!");
3871 { // INST_BINOP abbrev for FUNCTION_BLOCK.
3872 auto Abbv = std::make_shared<BitCodeAbbrev>();
3873 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3874 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3875 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3876 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3877 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3878 FUNCTION_INST_BINOP_ABBREV)
3879 llvm_unreachable("Unexpected abbrev ordering!");
3881 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
3882 auto Abbv = std::make_shared<BitCodeAbbrev>();
3883 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3884 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3885 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3886 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3887 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
3888 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3889 FUNCTION_INST_BINOP_FLAGS_ABBREV)
3890 llvm_unreachable("Unexpected abbrev ordering!");
3892 { // INST_CAST abbrev for FUNCTION_BLOCK.
3893 auto Abbv = std::make_shared<BitCodeAbbrev>();
3894 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
3895 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
3896 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3897 VE.computeBitsRequiredForTypeIndices()));
3898 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3899 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3900 FUNCTION_INST_CAST_ABBREV)
3901 llvm_unreachable("Unexpected abbrev ordering!");
3903 { // INST_CAST_FLAGS abbrev for FUNCTION_BLOCK.
3904 auto Abbv = std::make_shared<BitCodeAbbrev>();
3905 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
3906 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
3907 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3908 VE.computeBitsRequiredForTypeIndices()));
3909 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3910 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
3911 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3912 FUNCTION_INST_CAST_FLAGS_ABBREV)
3913 llvm_unreachable("Unexpected abbrev ordering!");
3916 { // INST_RET abbrev for FUNCTION_BLOCK.
3917 auto Abbv = std::make_shared<BitCodeAbbrev>();
3918 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
3919 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3920 FUNCTION_INST_RET_VOID_ABBREV)
3921 llvm_unreachable("Unexpected abbrev ordering!");
3923 { // INST_RET abbrev for FUNCTION_BLOCK.
3924 auto Abbv = std::make_shared<BitCodeAbbrev>();
3925 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
3926 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
3927 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3928 FUNCTION_INST_RET_VAL_ABBREV)
3929 llvm_unreachable("Unexpected abbrev ordering!");
3931 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
3932 auto Abbv = std::make_shared<BitCodeAbbrev>();
3933 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
3934 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3935 FUNCTION_INST_UNREACHABLE_ABBREV)
3936 llvm_unreachable("Unexpected abbrev ordering!");
3939 auto Abbv = std::make_shared<BitCodeAbbrev>();
3940 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
3941 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
3942 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3943 Log2_32_Ceil(VE.getTypes().size() + 1)));
3944 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3945 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
3946 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3947 FUNCTION_INST_GEP_ABBREV)
3948 llvm_unreachable("Unexpected abbrev ordering!");
3951 auto Abbv = std::make_shared<BitCodeAbbrev>();
3952 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE));
3953 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // dbgloc
3954 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // var
3955 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // expr
3956 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // val
3957 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3958 FUNCTION_DEBUG_RECORD_VALUE_ABBREV)
3959 llvm_unreachable("Unexpected abbrev ordering! 1");
3961 Stream.ExitBlock();
3964 /// Write the module path strings, currently only used when generating
3965 /// a combined index file.
3966 void IndexBitcodeWriter::writeModStrings() {
3967 Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);
3969 // TODO: See which abbrev sizes we actually need to emit
3971 // 8-bit fixed-width MST_ENTRY strings.
3972 auto Abbv = std::make_shared<BitCodeAbbrev>();
3973 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3974 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3975 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3976 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
3977 unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
3979 // 7-bit fixed width MST_ENTRY strings.
3980 Abbv = std::make_shared<BitCodeAbbrev>();
3981 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3982 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3983 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3984 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
3985 unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
3987 // 6-bit char6 MST_ENTRY strings.
3988 Abbv = std::make_shared<BitCodeAbbrev>();
3989 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3990 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3991 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3992 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3993 unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
3995 // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
3996 Abbv = std::make_shared<BitCodeAbbrev>();
3997 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH));
3998 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3999 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4000 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4001 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4002 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4003 unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
4005 SmallVector<unsigned, 64> Vals;
4006 forEachModule([&](const StringMapEntry<ModuleHash> &MPSE) {
4007 StringRef Key = MPSE.getKey();
4008 const auto &Hash = MPSE.getValue();
4009 StringEncoding Bits = getStringEncoding(Key);
4010 unsigned AbbrevToUse = Abbrev8Bit;
4011 if (Bits == SE_Char6)
4012 AbbrevToUse = Abbrev6Bit;
4013 else if (Bits == SE_Fixed7)
4014 AbbrevToUse = Abbrev7Bit;
4016 auto ModuleId = ModuleIdMap.size();
4017 ModuleIdMap[Key] = ModuleId;
4018 Vals.push_back(ModuleId);
4019 Vals.append(Key.begin(), Key.end());
4021 // Emit the finished record.
4022 Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
4024 // Emit an optional hash for the module now
4025 if (llvm::any_of(Hash, [](uint32_t H) { return H; })) {
4026 Vals.assign(Hash.begin(), Hash.end());
4027 // Emit the hash record.
4028 Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
4031 Vals.clear();
4033 Stream.ExitBlock();
4036 /// Write the function type metadata related records that need to appear before
4037 /// a function summary entry (whether per-module or combined).
4038 template <typename Fn>
4039 static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream,
4040 FunctionSummary *FS,
4041 Fn GetValueID) {
4042 if (!FS->type_tests().empty())
4043 Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
4045 SmallVector<uint64_t, 64> Record;
4047 auto WriteVFuncIdVec = [&](uint64_t Ty,
4048 ArrayRef<FunctionSummary::VFuncId> VFs) {
4049 if (VFs.empty())
4050 return;
4051 Record.clear();
4052 for (auto &VF : VFs) {
4053 Record.push_back(VF.GUID);
4054 Record.push_back(VF.Offset);
4056 Stream.EmitRecord(Ty, Record);
4059 WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
4060 FS->type_test_assume_vcalls());
4061 WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
4062 FS->type_checked_load_vcalls());
4064 auto WriteConstVCallVec = [&](uint64_t Ty,
4065 ArrayRef<FunctionSummary::ConstVCall> VCs) {
4066 for (auto &VC : VCs) {
4067 Record.clear();
4068 Record.push_back(VC.VFunc.GUID);
4069 Record.push_back(VC.VFunc.Offset);
4070 llvm::append_range(Record, VC.Args);
4071 Stream.EmitRecord(Ty, Record);
4075 WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
4076 FS->type_test_assume_const_vcalls());
4077 WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
4078 FS->type_checked_load_const_vcalls());
4080 auto WriteRange = [&](ConstantRange Range) {
4081 Range = Range.sextOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
4082 assert(Range.getLower().getNumWords() == 1);
4083 assert(Range.getUpper().getNumWords() == 1);
4084 emitSignedInt64(Record, *Range.getLower().getRawData());
4085 emitSignedInt64(Record, *Range.getUpper().getRawData());
4088 if (!FS->paramAccesses().empty()) {
4089 Record.clear();
4090 for (auto &Arg : FS->paramAccesses()) {
4091 size_t UndoSize = Record.size();
4092 Record.push_back(Arg.ParamNo);
4093 WriteRange(Arg.Use);
4094 Record.push_back(Arg.Calls.size());
4095 for (auto &Call : Arg.Calls) {
4096 Record.push_back(Call.ParamNo);
4097 std::optional<unsigned> ValueID = GetValueID(Call.Callee);
4098 if (!ValueID) {
4099 // If ValueID is unknown we can't drop just this call, we must drop
4100 // entire parameter.
4101 Record.resize(UndoSize);
4102 break;
4104 Record.push_back(*ValueID);
4105 WriteRange(Call.Offsets);
4108 if (!Record.empty())
4109 Stream.EmitRecord(bitc::FS_PARAM_ACCESS, Record);
4113 /// Collect type IDs from type tests used by function.
4114 static void
4115 getReferencedTypeIds(FunctionSummary *FS,
4116 std::set<GlobalValue::GUID> &ReferencedTypeIds) {
4117 if (!FS->type_tests().empty())
4118 for (auto &TT : FS->type_tests())
4119 ReferencedTypeIds.insert(TT);
4121 auto GetReferencedTypesFromVFuncIdVec =
4122 [&](ArrayRef<FunctionSummary::VFuncId> VFs) {
4123 for (auto &VF : VFs)
4124 ReferencedTypeIds.insert(VF.GUID);
4127 GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls());
4128 GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls());
4130 auto GetReferencedTypesFromConstVCallVec =
4131 [&](ArrayRef<FunctionSummary::ConstVCall> VCs) {
4132 for (auto &VC : VCs)
4133 ReferencedTypeIds.insert(VC.VFunc.GUID);
4136 GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls());
4137 GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls());
4140 static void writeWholeProgramDevirtResolutionByArg(
4141 SmallVector<uint64_t, 64> &NameVals, const std::vector<uint64_t> &args,
4142 const WholeProgramDevirtResolution::ByArg &ByArg) {
4143 NameVals.push_back(args.size());
4144 llvm::append_range(NameVals, args);
4146 NameVals.push_back(ByArg.TheKind);
4147 NameVals.push_back(ByArg.Info);
4148 NameVals.push_back(ByArg.Byte);
4149 NameVals.push_back(ByArg.Bit);
4152 static void writeWholeProgramDevirtResolution(
4153 SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
4154 uint64_t Id, const WholeProgramDevirtResolution &Wpd) {
4155 NameVals.push_back(Id);
4157 NameVals.push_back(Wpd.TheKind);
4158 NameVals.push_back(StrtabBuilder.add(Wpd.SingleImplName));
4159 NameVals.push_back(Wpd.SingleImplName.size());
4161 NameVals.push_back(Wpd.ResByArg.size());
4162 for (auto &A : Wpd.ResByArg)
4163 writeWholeProgramDevirtResolutionByArg(NameVals, A.first, A.second);
4166 static void writeTypeIdSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
4167 StringTableBuilder &StrtabBuilder,
4168 StringRef Id,
4169 const TypeIdSummary &Summary) {
4170 NameVals.push_back(StrtabBuilder.add(Id));
4171 NameVals.push_back(Id.size());
4173 NameVals.push_back(Summary.TTRes.TheKind);
4174 NameVals.push_back(Summary.TTRes.SizeM1BitWidth);
4175 NameVals.push_back(Summary.TTRes.AlignLog2);
4176 NameVals.push_back(Summary.TTRes.SizeM1);
4177 NameVals.push_back(Summary.TTRes.BitMask);
4178 NameVals.push_back(Summary.TTRes.InlineBits);
4180 for (auto &W : Summary.WPDRes)
4181 writeWholeProgramDevirtResolution(NameVals, StrtabBuilder, W.first,
4182 W.second);
4185 static void writeTypeIdCompatibleVtableSummaryRecord(
4186 SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
4187 StringRef Id, const TypeIdCompatibleVtableInfo &Summary,
4188 ValueEnumerator &VE) {
4189 NameVals.push_back(StrtabBuilder.add(Id));
4190 NameVals.push_back(Id.size());
4192 for (auto &P : Summary) {
4193 NameVals.push_back(P.AddressPointOffset);
4194 NameVals.push_back(VE.getValueID(P.VTableVI.getValue()));
4198 static void writeFunctionHeapProfileRecords(
4199 BitstreamWriter &Stream, FunctionSummary *FS, unsigned CallsiteAbbrev,
4200 unsigned AllocAbbrev, unsigned ContextIdAbbvId, bool PerModule,
4201 std::function<unsigned(const ValueInfo &VI)> GetValueID,
4202 std::function<unsigned(unsigned)> GetStackIndex,
4203 bool WriteContextSizeInfoIndex) {
4204 SmallVector<uint64_t> Record;
4206 for (auto &CI : FS->callsites()) {
4207 Record.clear();
4208 // Per module callsite clones should always have a single entry of
4209 // value 0.
4210 assert(!PerModule || (CI.Clones.size() == 1 && CI.Clones[0] == 0));
4211 Record.push_back(GetValueID(CI.Callee));
4212 if (!PerModule) {
4213 Record.push_back(CI.StackIdIndices.size());
4214 Record.push_back(CI.Clones.size());
4216 for (auto Id : CI.StackIdIndices)
4217 Record.push_back(GetStackIndex(Id));
4218 if (!PerModule) {
4219 for (auto V : CI.Clones)
4220 Record.push_back(V);
4222 Stream.EmitRecord(PerModule ? bitc::FS_PERMODULE_CALLSITE_INFO
4223 : bitc::FS_COMBINED_CALLSITE_INFO,
4224 Record, CallsiteAbbrev);
4227 for (auto &AI : FS->allocs()) {
4228 Record.clear();
4229 // Per module alloc versions should always have a single entry of
4230 // value 0.
4231 assert(!PerModule || (AI.Versions.size() == 1 && AI.Versions[0] == 0));
4232 Record.push_back(AI.MIBs.size());
4233 if (!PerModule)
4234 Record.push_back(AI.Versions.size());
4235 for (auto &MIB : AI.MIBs) {
4236 Record.push_back((uint8_t)MIB.AllocType);
4237 Record.push_back(MIB.StackIdIndices.size());
4238 for (auto Id : MIB.StackIdIndices)
4239 Record.push_back(GetStackIndex(Id));
4241 if (!PerModule) {
4242 for (auto V : AI.Versions)
4243 Record.push_back(V);
4245 assert(AI.ContextSizeInfos.empty() ||
4246 AI.ContextSizeInfos.size() == AI.MIBs.size());
4247 // Optionally emit the context size information if it exists.
4248 if (WriteContextSizeInfoIndex && !AI.ContextSizeInfos.empty()) {
4249 // The abbreviation id for the context ids record should have been created
4250 // if we are emitting the per-module index, which is where we write this
4251 // info.
4252 assert(ContextIdAbbvId);
4253 SmallVector<uint32_t> ContextIds;
4254 // At least one context id per ContextSizeInfos entry (MIB), broken into 2
4255 // halves.
4256 ContextIds.reserve(AI.ContextSizeInfos.size() * 2);
4257 for (auto &Infos : AI.ContextSizeInfos) {
4258 Record.push_back(Infos.size());
4259 for (auto [FullStackId, TotalSize] : Infos) {
4260 // The context ids are emitted separately as a fixed width array,
4261 // which is more efficient than a VBR given that these hashes are
4262 // typically close to 64-bits. The max fixed width entry is 32 bits so
4263 // it is split into 2.
4264 ContextIds.push_back(static_cast<uint32_t>(FullStackId >> 32));
4265 ContextIds.push_back(static_cast<uint32_t>(FullStackId));
4266 Record.push_back(TotalSize);
4269 // The context ids are expected by the reader to immediately precede the
4270 // associated alloc info record.
4271 Stream.EmitRecord(bitc::FS_ALLOC_CONTEXT_IDS, ContextIds,
4272 ContextIdAbbvId);
4274 Stream.EmitRecord(PerModule ? bitc::FS_PERMODULE_ALLOC_INFO
4275 : bitc::FS_COMBINED_ALLOC_INFO,
4276 Record, AllocAbbrev);
4280 // Helper to emit a single function summary record.
4281 void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
4282 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
4283 unsigned ValueID, unsigned FSCallsRelBFAbbrev,
4284 unsigned FSCallsProfileAbbrev, unsigned CallsiteAbbrev,
4285 unsigned AllocAbbrev, unsigned ContextIdAbbvId, const Function &F) {
4286 NameVals.push_back(ValueID);
4288 FunctionSummary *FS = cast<FunctionSummary>(Summary);
4290 writeFunctionTypeMetadataRecords(
4291 Stream, FS, [&](const ValueInfo &VI) -> std::optional<unsigned> {
4292 return {VE.getValueID(VI.getValue())};
4295 writeFunctionHeapProfileRecords(
4296 Stream, FS, CallsiteAbbrev, AllocAbbrev, ContextIdAbbvId,
4297 /*PerModule*/ true,
4298 /*GetValueId*/ [&](const ValueInfo &VI) { return getValueId(VI); },
4299 /*GetStackIndex*/ [&](unsigned I) { return I; },
4300 /*WriteContextSizeInfoIndex*/ true);
4302 auto SpecialRefCnts = FS->specialRefCounts();
4303 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
4304 NameVals.push_back(FS->instCount());
4305 NameVals.push_back(getEncodedFFlags(FS->fflags()));
4306 NameVals.push_back(FS->refs().size());
4307 NameVals.push_back(SpecialRefCnts.first); // rorefcnt
4308 NameVals.push_back(SpecialRefCnts.second); // worefcnt
4310 for (auto &RI : FS->refs())
4311 NameVals.push_back(getValueId(RI));
4313 const bool UseRelBFRecord =
4314 WriteRelBFToSummary && !F.hasProfileData() &&
4315 ForceSummaryEdgesCold == FunctionSummary::FSHT_None;
4316 for (auto &ECI : FS->calls()) {
4317 NameVals.push_back(getValueId(ECI.first));
4318 if (UseRelBFRecord)
4319 NameVals.push_back(getEncodedRelBFCallEdgeInfo(ECI.second));
4320 else
4321 NameVals.push_back(getEncodedHotnessCallEdgeInfo(ECI.second));
4324 unsigned FSAbbrev =
4325 (UseRelBFRecord ? FSCallsRelBFAbbrev : FSCallsProfileAbbrev);
4326 unsigned Code =
4327 (UseRelBFRecord ? bitc::FS_PERMODULE_RELBF : bitc::FS_PERMODULE_PROFILE);
4329 // Emit the finished record.
4330 Stream.EmitRecord(Code, NameVals, FSAbbrev);
4331 NameVals.clear();
4334 // Collect the global value references in the given variable's initializer,
4335 // and emit them in a summary record.
4336 void ModuleBitcodeWriterBase::writeModuleLevelReferences(
4337 const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
4338 unsigned FSModRefsAbbrev, unsigned FSModVTableRefsAbbrev) {
4339 auto VI = Index->getValueInfo(V.getGUID());
4340 if (!VI || VI.getSummaryList().empty()) {
4341 // Only declarations should not have a summary (a declaration might however
4342 // have a summary if the def was in module level asm).
4343 assert(V.isDeclaration());
4344 return;
4346 auto *Summary = VI.getSummaryList()[0].get();
4347 NameVals.push_back(VE.getValueID(&V));
4348 GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
4349 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
4350 NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
4352 auto VTableFuncs = VS->vTableFuncs();
4353 if (!VTableFuncs.empty())
4354 NameVals.push_back(VS->refs().size());
4356 unsigned SizeBeforeRefs = NameVals.size();
4357 for (auto &RI : VS->refs())
4358 NameVals.push_back(VE.getValueID(RI.getValue()));
4359 // Sort the refs for determinism output, the vector returned by FS->refs() has
4360 // been initialized from a DenseSet.
4361 llvm::sort(drop_begin(NameVals, SizeBeforeRefs));
4363 if (VTableFuncs.empty())
4364 Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals,
4365 FSModRefsAbbrev);
4366 else {
4367 // VTableFuncs pairs should already be sorted by offset.
4368 for (auto &P : VTableFuncs) {
4369 NameVals.push_back(VE.getValueID(P.FuncVI.getValue()));
4370 NameVals.push_back(P.VTableOffset);
4373 Stream.EmitRecord(bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS, NameVals,
4374 FSModVTableRefsAbbrev);
4376 NameVals.clear();
4379 /// Emit the per-module summary section alongside the rest of
4380 /// the module's bitcode.
4381 void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
4382 // By default we compile with ThinLTO if the module has a summary, but the
4383 // client can request full LTO with a module flag.
4384 bool IsThinLTO = true;
4385 if (auto *MD =
4386 mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
4387 IsThinLTO = MD->getZExtValue();
4388 Stream.EnterSubblock(IsThinLTO ? bitc::GLOBALVAL_SUMMARY_BLOCK_ID
4389 : bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID,
4392 Stream.EmitRecord(
4393 bitc::FS_VERSION,
4394 ArrayRef<uint64_t>{ModuleSummaryIndex::BitcodeSummaryVersion});
4396 // Write the index flags.
4397 uint64_t Flags = 0;
4398 // Bits 1-3 are set only in the combined index, skip them.
4399 if (Index->enableSplitLTOUnit())
4400 Flags |= 0x8;
4401 if (Index->hasUnifiedLTO())
4402 Flags |= 0x200;
4404 Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Flags});
4406 if (Index->begin() == Index->end()) {
4407 Stream.ExitBlock();
4408 return;
4411 auto Abbv = std::make_shared<BitCodeAbbrev>();
4412 Abbv->Add(BitCodeAbbrevOp(bitc::FS_VALUE_GUID));
4413 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4414 // GUIDS often use up most of 64-bits, so encode as two Fixed 32.
4415 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4416 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4417 unsigned ValueGuidAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4419 for (const auto &GVI : valueIds()) {
4420 Stream.EmitRecord(bitc::FS_VALUE_GUID,
4421 ArrayRef<uint32_t>{GVI.second,
4422 static_cast<uint32_t>(GVI.first >> 32),
4423 static_cast<uint32_t>(GVI.first)},
4424 ValueGuidAbbrev);
4427 if (!Index->stackIds().empty()) {
4428 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
4429 StackIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_STACK_IDS));
4430 // numids x stackid
4431 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4432 // The stack ids are hashes that are close to 64 bits in size, so emitting
4433 // as a pair of 32-bit fixed-width values is more efficient than a VBR.
4434 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4435 unsigned StackIdAbbvId = Stream.EmitAbbrev(std::move(StackIdAbbv));
4436 SmallVector<uint32_t> Vals;
4437 Vals.reserve(Index->stackIds().size() * 2);
4438 for (auto Id : Index->stackIds()) {
4439 Vals.push_back(static_cast<uint32_t>(Id >> 32));
4440 Vals.push_back(static_cast<uint32_t>(Id));
4442 Stream.EmitRecord(bitc::FS_STACK_IDS, Vals, StackIdAbbvId);
4445 // n x context id
4446 auto ContextIdAbbv = std::make_shared<BitCodeAbbrev>();
4447 ContextIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_ALLOC_CONTEXT_IDS));
4448 ContextIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4449 // The context ids are hashes that are close to 64 bits in size, so emitting
4450 // as a pair of 32-bit fixed-width values is more efficient than a VBR.
4451 ContextIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4452 unsigned ContextIdAbbvId = Stream.EmitAbbrev(std::move(ContextIdAbbv));
4454 // Abbrev for FS_PERMODULE_PROFILE.
4455 Abbv = std::make_shared<BitCodeAbbrev>();
4456 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));
4457 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4458 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // flags
4459 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
4460 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
4461 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4462 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
4463 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
4464 // numrefs x valueid, n x (valueid, hotness+tailcall flags)
4465 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4466 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4467 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4469 // Abbrev for FS_PERMODULE_RELBF.
4470 Abbv = std::make_shared<BitCodeAbbrev>();
4471 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_RELBF));
4472 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4473 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4474 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
4475 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
4476 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4477 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
4478 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
4479 // numrefs x valueid, n x (valueid, rel_block_freq+tailcall])
4480 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4481 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4482 unsigned FSCallsRelBFAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4484 // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
4485 Abbv = std::make_shared<BitCodeAbbrev>();
4486 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));
4487 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4488 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4489 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
4490 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4491 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4493 // Abbrev for FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS.
4494 Abbv = std::make_shared<BitCodeAbbrev>();
4495 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS));
4496 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4497 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4498 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4499 // numrefs x valueid, n x (valueid , offset)
4500 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4501 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4502 unsigned FSModVTableRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4504 // Abbrev for FS_ALIAS.
4505 Abbv = std::make_shared<BitCodeAbbrev>();
4506 Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
4507 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4508 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4509 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4510 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4512 // Abbrev for FS_TYPE_ID_METADATA
4513 Abbv = std::make_shared<BitCodeAbbrev>();
4514 Abbv->Add(BitCodeAbbrevOp(bitc::FS_TYPE_ID_METADATA));
4515 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid strtab index
4516 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid length
4517 // n x (valueid , offset)
4518 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4519 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4520 unsigned TypeIdCompatibleVtableAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4522 Abbv = std::make_shared<BitCodeAbbrev>();
4523 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_CALLSITE_INFO));
4524 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4525 // n x stackidindex
4526 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4527 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4528 unsigned CallsiteAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4530 Abbv = std::make_shared<BitCodeAbbrev>();
4531 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_ALLOC_INFO));
4532 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // nummib
4533 // n x (alloc type, numstackids, numstackids x stackidindex)
4534 // optional: nummib x (numcontext x total size)
4535 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4536 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4537 unsigned AllocAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4539 SmallVector<uint64_t, 64> NameVals;
4540 // Iterate over the list of functions instead of the Index to
4541 // ensure the ordering is stable.
4542 for (const Function &F : M) {
4543 // Summary emission does not support anonymous functions, they have to
4544 // renamed using the anonymous function renaming pass.
4545 if (!F.hasName())
4546 report_fatal_error("Unexpected anonymous function when writing summary");
4548 ValueInfo VI = Index->getValueInfo(F.getGUID());
4549 if (!VI || VI.getSummaryList().empty()) {
4550 // Only declarations should not have a summary (a declaration might
4551 // however have a summary if the def was in module level asm).
4552 assert(F.isDeclaration());
4553 continue;
4555 auto *Summary = VI.getSummaryList()[0].get();
4556 writePerModuleFunctionSummaryRecord(
4557 NameVals, Summary, VE.getValueID(&F), FSCallsRelBFAbbrev,
4558 FSCallsProfileAbbrev, CallsiteAbbrev, AllocAbbrev, ContextIdAbbvId, F);
4561 // Capture references from GlobalVariable initializers, which are outside
4562 // of a function scope.
4563 for (const GlobalVariable &G : M.globals())
4564 writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev,
4565 FSModVTableRefsAbbrev);
4567 for (const GlobalAlias &A : M.aliases()) {
4568 auto *Aliasee = A.getAliaseeObject();
4569 // Skip ifunc and nameless functions which don't have an entry in the
4570 // summary.
4571 if (!Aliasee->hasName() || isa<GlobalIFunc>(Aliasee))
4572 continue;
4573 auto AliasId = VE.getValueID(&A);
4574 auto AliaseeId = VE.getValueID(Aliasee);
4575 NameVals.push_back(AliasId);
4576 auto *Summary = Index->getGlobalValueSummary(A);
4577 AliasSummary *AS = cast<AliasSummary>(Summary);
4578 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
4579 NameVals.push_back(AliaseeId);
4580 Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
4581 NameVals.clear();
4584 for (auto &S : Index->typeIdCompatibleVtableMap()) {
4585 writeTypeIdCompatibleVtableSummaryRecord(NameVals, StrtabBuilder, S.first,
4586 S.second, VE);
4587 Stream.EmitRecord(bitc::FS_TYPE_ID_METADATA, NameVals,
4588 TypeIdCompatibleVtableAbbrev);
4589 NameVals.clear();
4592 if (Index->getBlockCount())
4593 Stream.EmitRecord(bitc::FS_BLOCK_COUNT,
4594 ArrayRef<uint64_t>{Index->getBlockCount()});
4596 Stream.ExitBlock();
4599 /// Emit the combined summary section into the combined index file.
4600 void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
4601 Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 4);
4602 Stream.EmitRecord(
4603 bitc::FS_VERSION,
4604 ArrayRef<uint64_t>{ModuleSummaryIndex::BitcodeSummaryVersion});
4606 // Write the index flags.
4607 Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Index.getFlags()});
4609 auto Abbv = std::make_shared<BitCodeAbbrev>();
4610 Abbv->Add(BitCodeAbbrevOp(bitc::FS_VALUE_GUID));
4611 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4612 // GUIDS often use up most of 64-bits, so encode as two Fixed 32.
4613 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4614 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4615 unsigned ValueGuidAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4617 for (const auto &GVI : valueIds()) {
4618 Stream.EmitRecord(bitc::FS_VALUE_GUID,
4619 ArrayRef<uint32_t>{GVI.second,
4620 static_cast<uint32_t>(GVI.first >> 32),
4621 static_cast<uint32_t>(GVI.first)},
4622 ValueGuidAbbrev);
4625 // Write the stack ids used by this index, which will be a subset of those in
4626 // the full index in the case of distributed indexes.
4627 if (!StackIds.empty()) {
4628 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
4629 StackIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_STACK_IDS));
4630 // numids x stackid
4631 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4632 // The stack ids are hashes that are close to 64 bits in size, so emitting
4633 // as a pair of 32-bit fixed-width values is more efficient than a VBR.
4634 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4635 unsigned StackIdAbbvId = Stream.EmitAbbrev(std::move(StackIdAbbv));
4636 SmallVector<uint32_t> Vals;
4637 Vals.reserve(StackIds.size() * 2);
4638 for (auto Id : StackIds) {
4639 Vals.push_back(static_cast<uint32_t>(Id >> 32));
4640 Vals.push_back(static_cast<uint32_t>(Id));
4642 Stream.EmitRecord(bitc::FS_STACK_IDS, Vals, StackIdAbbvId);
4645 // Abbrev for FS_COMBINED_PROFILE.
4646 Abbv = std::make_shared<BitCodeAbbrev>();
4647 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));
4648 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4649 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
4650 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4651 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
4652 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
4653 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // entrycount
4654 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4655 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
4656 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
4657 // numrefs x valueid, n x (valueid, hotness+tailcall flags)
4658 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4659 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4660 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4662 // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
4663 Abbv = std::make_shared<BitCodeAbbrev>();
4664 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));
4665 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4666 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
4667 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4668 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
4669 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4670 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4672 // Abbrev for FS_COMBINED_ALIAS.
4673 Abbv = std::make_shared<BitCodeAbbrev>();
4674 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS));
4675 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4676 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
4677 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4678 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4679 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4681 Abbv = std::make_shared<BitCodeAbbrev>();
4682 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_CALLSITE_INFO));
4683 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4684 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numstackindices
4685 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numver
4686 // numstackindices x stackidindex, numver x version
4687 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4688 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4689 unsigned CallsiteAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4691 Abbv = std::make_shared<BitCodeAbbrev>();
4692 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALLOC_INFO));
4693 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // nummib
4694 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numver
4695 // nummib x (alloc type, numstackids, numstackids x stackidindex),
4696 // numver x version
4697 // optional: nummib x total size
4698 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4699 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4700 unsigned AllocAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4702 auto shouldImportValueAsDecl = [&](GlobalValueSummary *GVS) -> bool {
4703 if (DecSummaries == nullptr)
4704 return false;
4705 return DecSummaries->count(GVS);
4708 // The aliases are emitted as a post-pass, and will point to the value
4709 // id of the aliasee. Save them in a vector for post-processing.
4710 SmallVector<AliasSummary *, 64> Aliases;
4712 // Save the value id for each summary for alias emission.
4713 DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
4715 SmallVector<uint64_t, 64> NameVals;
4717 // Set that will be populated during call to writeFunctionTypeMetadataRecords
4718 // with the type ids referenced by this index file.
4719 std::set<GlobalValue::GUID> ReferencedTypeIds;
4721 // For local linkage, we also emit the original name separately
4722 // immediately after the record.
4723 auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
4724 // We don't need to emit the original name if we are writing the index for
4725 // distributed backends (in which case ModuleToSummariesForIndex is
4726 // non-null). The original name is only needed during the thin link, since
4727 // for SamplePGO the indirect call targets for local functions have
4728 // have the original name annotated in profile.
4729 // Continue to emit it when writing out the entire combined index, which is
4730 // used in testing the thin link via llvm-lto.
4731 if (ModuleToSummariesForIndex || !GlobalValue::isLocalLinkage(S.linkage()))
4732 return;
4733 NameVals.push_back(S.getOriginalName());
4734 Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals);
4735 NameVals.clear();
4738 DenseSet<GlobalValue::GUID> DefOrUseGUIDs;
4739 forEachSummary([&](GVInfo I, bool IsAliasee) {
4740 GlobalValueSummary *S = I.second;
4741 assert(S);
4742 DefOrUseGUIDs.insert(I.first);
4743 for (const ValueInfo &VI : S->refs())
4744 DefOrUseGUIDs.insert(VI.getGUID());
4746 auto ValueId = getValueId(I.first);
4747 assert(ValueId);
4748 SummaryToValueIdMap[S] = *ValueId;
4750 // If this is invoked for an aliasee, we want to record the above
4751 // mapping, but then not emit a summary entry (if the aliasee is
4752 // to be imported, we will invoke this separately with IsAliasee=false).
4753 if (IsAliasee)
4754 return;
4756 if (auto *AS = dyn_cast<AliasSummary>(S)) {
4757 // Will process aliases as a post-pass because the reader wants all
4758 // global to be loaded first.
4759 Aliases.push_back(AS);
4760 return;
4763 if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
4764 NameVals.push_back(*ValueId);
4765 assert(ModuleIdMap.count(VS->modulePath()));
4766 NameVals.push_back(ModuleIdMap[VS->modulePath()]);
4767 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
4768 NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
4769 for (auto &RI : VS->refs()) {
4770 auto RefValueId = getValueId(RI.getGUID());
4771 if (!RefValueId)
4772 continue;
4773 NameVals.push_back(*RefValueId);
4776 // Emit the finished record.
4777 Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals,
4778 FSModRefsAbbrev);
4779 NameVals.clear();
4780 MaybeEmitOriginalName(*S);
4781 return;
4784 auto GetValueId = [&](const ValueInfo &VI) -> std::optional<unsigned> {
4785 if (!VI)
4786 return std::nullopt;
4787 return getValueId(VI.getGUID());
4790 auto *FS = cast<FunctionSummary>(S);
4791 writeFunctionTypeMetadataRecords(Stream, FS, GetValueId);
4792 getReferencedTypeIds(FS, ReferencedTypeIds);
4794 writeFunctionHeapProfileRecords(
4795 Stream, FS, CallsiteAbbrev, AllocAbbrev, /*ContextIdAbbvId*/ 0,
4796 /*PerModule*/ false,
4797 /*GetValueId*/
4798 [&](const ValueInfo &VI) -> unsigned {
4799 std::optional<unsigned> ValueID = GetValueId(VI);
4800 // This can happen in shared index files for distributed ThinLTO if
4801 // the callee function summary is not included. Record 0 which we
4802 // will have to deal with conservatively when doing any kind of
4803 // validation in the ThinLTO backends.
4804 if (!ValueID)
4805 return 0;
4806 return *ValueID;
4808 /*GetStackIndex*/
4809 [&](unsigned I) {
4810 // Get the corresponding index into the list of StackIds actually
4811 // being written for this combined index (which may be a subset in
4812 // the case of distributed indexes).
4813 assert(StackIdIndicesToIndex.contains(I));
4814 return StackIdIndicesToIndex[I];
4816 /*WriteContextSizeInfoIndex*/ false);
4818 NameVals.push_back(*ValueId);
4819 assert(ModuleIdMap.count(FS->modulePath()));
4820 NameVals.push_back(ModuleIdMap[FS->modulePath()]);
4821 NameVals.push_back(
4822 getEncodedGVSummaryFlags(FS->flags(), shouldImportValueAsDecl(FS)));
4823 NameVals.push_back(FS->instCount());
4824 NameVals.push_back(getEncodedFFlags(FS->fflags()));
4825 // TODO: Stop writing entry count and bump bitcode version.
4826 NameVals.push_back(0 /* EntryCount */);
4828 // Fill in below
4829 NameVals.push_back(0); // numrefs
4830 NameVals.push_back(0); // rorefcnt
4831 NameVals.push_back(0); // worefcnt
4833 unsigned Count = 0, RORefCnt = 0, WORefCnt = 0;
4834 for (auto &RI : FS->refs()) {
4835 auto RefValueId = getValueId(RI.getGUID());
4836 if (!RefValueId)
4837 continue;
4838 NameVals.push_back(*RefValueId);
4839 if (RI.isReadOnly())
4840 RORefCnt++;
4841 else if (RI.isWriteOnly())
4842 WORefCnt++;
4843 Count++;
4845 NameVals[6] = Count;
4846 NameVals[7] = RORefCnt;
4847 NameVals[8] = WORefCnt;
4849 for (auto &EI : FS->calls()) {
4850 // If this GUID doesn't have a value id, it doesn't have a function
4851 // summary and we don't need to record any calls to it.
4852 std::optional<unsigned> CallValueId = GetValueId(EI.first);
4853 if (!CallValueId)
4854 continue;
4855 NameVals.push_back(*CallValueId);
4856 NameVals.push_back(getEncodedHotnessCallEdgeInfo(EI.second));
4859 // Emit the finished record.
4860 Stream.EmitRecord(bitc::FS_COMBINED_PROFILE, NameVals,
4861 FSCallsProfileAbbrev);
4862 NameVals.clear();
4863 MaybeEmitOriginalName(*S);
4866 for (auto *AS : Aliases) {
4867 auto AliasValueId = SummaryToValueIdMap[AS];
4868 assert(AliasValueId);
4869 NameVals.push_back(AliasValueId);
4870 assert(ModuleIdMap.count(AS->modulePath()));
4871 NameVals.push_back(ModuleIdMap[AS->modulePath()]);
4872 NameVals.push_back(
4873 getEncodedGVSummaryFlags(AS->flags(), shouldImportValueAsDecl(AS)));
4874 auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()];
4875 assert(AliaseeValueId);
4876 NameVals.push_back(AliaseeValueId);
4878 // Emit the finished record.
4879 Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
4880 NameVals.clear();
4881 MaybeEmitOriginalName(*AS);
4883 if (auto *FS = dyn_cast<FunctionSummary>(&AS->getAliasee()))
4884 getReferencedTypeIds(FS, ReferencedTypeIds);
4887 if (!Index.cfiFunctionDefs().empty()) {
4888 for (auto &S : Index.cfiFunctionDefs()) {
4889 if (DefOrUseGUIDs.contains(
4890 GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(S)))) {
4891 NameVals.push_back(StrtabBuilder.add(S));
4892 NameVals.push_back(S.size());
4895 if (!NameVals.empty()) {
4896 Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DEFS, NameVals);
4897 NameVals.clear();
4901 if (!Index.cfiFunctionDecls().empty()) {
4902 for (auto &S : Index.cfiFunctionDecls()) {
4903 if (DefOrUseGUIDs.contains(
4904 GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(S)))) {
4905 NameVals.push_back(StrtabBuilder.add(S));
4906 NameVals.push_back(S.size());
4909 if (!NameVals.empty()) {
4910 Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DECLS, NameVals);
4911 NameVals.clear();
4915 // Walk the GUIDs that were referenced, and write the
4916 // corresponding type id records.
4917 for (auto &T : ReferencedTypeIds) {
4918 auto TidIter = Index.typeIds().equal_range(T);
4919 for (const auto &[GUID, TypeIdPair] : make_range(TidIter)) {
4920 writeTypeIdSummaryRecord(NameVals, StrtabBuilder, TypeIdPair.first,
4921 TypeIdPair.second);
4922 Stream.EmitRecord(bitc::FS_TYPE_ID, NameVals);
4923 NameVals.clear();
4927 if (Index.getBlockCount())
4928 Stream.EmitRecord(bitc::FS_BLOCK_COUNT,
4929 ArrayRef<uint64_t>{Index.getBlockCount()});
4931 Stream.ExitBlock();
4934 /// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
4935 /// current llvm version, and a record for the epoch number.
4936 static void writeIdentificationBlock(BitstreamWriter &Stream) {
4937 Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);
4939 // Write the "user readable" string identifying the bitcode producer
4940 auto Abbv = std::make_shared<BitCodeAbbrev>();
4941 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING));
4942 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4943 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
4944 auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4945 writeStringRecord(Stream, bitc::IDENTIFICATION_CODE_STRING,
4946 "LLVM" LLVM_VERSION_STRING, StringAbbrev);
4948 // Write the epoch version
4949 Abbv = std::make_shared<BitCodeAbbrev>();
4950 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH));
4951 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4952 auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4953 constexpr std::array<unsigned, 1> Vals = {{bitc::BITCODE_CURRENT_EPOCH}};
4954 Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
4955 Stream.ExitBlock();
4958 void ModuleBitcodeWriter::writeModuleHash(StringRef View) {
4959 // Emit the module's hash.
4960 // MODULE_CODE_HASH: [5*i32]
4961 if (GenerateHash) {
4962 uint32_t Vals[5];
4963 Hasher.update(ArrayRef<uint8_t>(
4964 reinterpret_cast<const uint8_t *>(View.data()), View.size()));
4965 std::array<uint8_t, 20> Hash = Hasher.result();
4966 for (int Pos = 0; Pos < 20; Pos += 4) {
4967 Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);
4970 // Emit the finished record.
4971 Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
4973 if (ModHash)
4974 // Save the written hash value.
4975 llvm::copy(Vals, std::begin(*ModHash));
4979 void ModuleBitcodeWriter::write() {
4980 writeIdentificationBlock(Stream);
4982 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
4983 // We will want to write the module hash at this point. Block any flushing so
4984 // we can have access to the whole underlying data later.
4985 Stream.markAndBlockFlushing();
4987 writeModuleVersion();
4989 // Emit blockinfo, which defines the standard abbreviations etc.
4990 writeBlockInfo();
4992 // Emit information describing all of the types in the module.
4993 writeTypeTable();
4995 // Emit information about attribute groups.
4996 writeAttributeGroupTable();
4998 // Emit information about parameter attributes.
4999 writeAttributeTable();
5001 writeComdats();
5003 // Emit top-level description of module, including target triple, inline asm,
5004 // descriptors for global variables, and function prototype info.
5005 writeModuleInfo();
5007 // Emit constants.
5008 writeModuleConstants();
5010 // Emit metadata kind names.
5011 writeModuleMetadataKinds();
5013 // Emit metadata.
5014 writeModuleMetadata();
5016 // Emit module-level use-lists.
5017 if (VE.shouldPreserveUseListOrder())
5018 writeUseListBlock(nullptr);
5020 writeOperandBundleTags();
5021 writeSyncScopeNames();
5023 // Emit function bodies.
5024 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
5025 for (const Function &F : M)
5026 if (!F.isDeclaration())
5027 writeFunction(F, FunctionToBitcodeIndex);
5029 // Need to write after the above call to WriteFunction which populates
5030 // the summary information in the index.
5031 if (Index)
5032 writePerModuleGlobalValueSummary();
5034 writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
5036 writeModuleHash(Stream.getMarkedBufferAndResumeFlushing());
5038 Stream.ExitBlock();
5041 static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
5042 uint32_t &Position) {
5043 support::endian::write32le(&Buffer[Position], Value);
5044 Position += 4;
5047 /// If generating a bc file on darwin, we have to emit a
5048 /// header and trailer to make it compatible with the system archiver. To do
5049 /// this we emit the following header, and then emit a trailer that pads the
5050 /// file out to be a multiple of 16 bytes.
5052 /// struct bc_header {
5053 /// uint32_t Magic; // 0x0B17C0DE
5054 /// uint32_t Version; // Version, currently always 0.
5055 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
5056 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
5057 /// uint32_t CPUType; // CPU specifier.
5058 /// ... potentially more later ...
5059 /// };
5060 static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
5061 const Triple &TT) {
5062 unsigned CPUType = ~0U;
5064 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
5065 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
5066 // number from /usr/include/mach/machine.h. It is ok to reproduce the
5067 // specific constants here because they are implicitly part of the Darwin ABI.
5068 enum {
5069 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
5070 DARWIN_CPU_TYPE_X86 = 7,
5071 DARWIN_CPU_TYPE_ARM = 12,
5072 DARWIN_CPU_TYPE_POWERPC = 18
5075 Triple::ArchType Arch = TT.getArch();
5076 if (Arch == Triple::x86_64)
5077 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
5078 else if (Arch == Triple::x86)
5079 CPUType = DARWIN_CPU_TYPE_X86;
5080 else if (Arch == Triple::ppc)
5081 CPUType = DARWIN_CPU_TYPE_POWERPC;
5082 else if (Arch == Triple::ppc64)
5083 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
5084 else if (Arch == Triple::arm || Arch == Triple::thumb)
5085 CPUType = DARWIN_CPU_TYPE_ARM;
5087 // Traditional Bitcode starts after header.
5088 assert(Buffer.size() >= BWH_HeaderSize &&
5089 "Expected header size to be reserved");
5090 unsigned BCOffset = BWH_HeaderSize;
5091 unsigned BCSize = Buffer.size() - BWH_HeaderSize;
5093 // Write the magic and version.
5094 unsigned Position = 0;
5095 writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
5096 writeInt32ToBuffer(0, Buffer, Position); // Version.
5097 writeInt32ToBuffer(BCOffset, Buffer, Position);
5098 writeInt32ToBuffer(BCSize, Buffer, Position);
5099 writeInt32ToBuffer(CPUType, Buffer, Position);
5101 // If the file is not a multiple of 16 bytes, insert dummy padding.
5102 while (Buffer.size() & 15)
5103 Buffer.push_back(0);
5106 /// Helper to write the header common to all bitcode files.
5107 static void writeBitcodeHeader(BitstreamWriter &Stream) {
5108 // Emit the file header.
5109 Stream.Emit((unsigned)'B', 8);
5110 Stream.Emit((unsigned)'C', 8);
5111 Stream.Emit(0x0, 4);
5112 Stream.Emit(0xC, 4);
5113 Stream.Emit(0xE, 4);
5114 Stream.Emit(0xD, 4);
5117 BitcodeWriter::BitcodeWriter(SmallVectorImpl<char> &Buffer)
5118 : Stream(new BitstreamWriter(Buffer)) {
5119 writeBitcodeHeader(*Stream);
5122 BitcodeWriter::BitcodeWriter(raw_ostream &FS)
5123 : Stream(new BitstreamWriter(FS, FlushThreshold)) {
5124 writeBitcodeHeader(*Stream);
5127 BitcodeWriter::~BitcodeWriter() { assert(WroteStrtab); }
5129 void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) {
5130 Stream->EnterSubblock(Block, 3);
5132 auto Abbv = std::make_shared<BitCodeAbbrev>();
5133 Abbv->Add(BitCodeAbbrevOp(Record));
5134 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
5135 auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv));
5137 Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob);
5139 Stream->ExitBlock();
5142 void BitcodeWriter::writeSymtab() {
5143 assert(!WroteStrtab && !WroteSymtab);
5145 // If any module has module-level inline asm, we will require a registered asm
5146 // parser for the target so that we can create an accurate symbol table for
5147 // the module.
5148 for (Module *M : Mods) {
5149 if (M->getModuleInlineAsm().empty())
5150 continue;
5152 std::string Err;
5153 const Triple TT(M->getTargetTriple());
5154 const Target *T = TargetRegistry::lookupTarget(TT.str(), Err);
5155 if (!T || !T->hasMCAsmParser())
5156 return;
5159 WroteSymtab = true;
5160 SmallVector<char, 0> Symtab;
5161 // The irsymtab::build function may be unable to create a symbol table if the
5162 // module is malformed (e.g. it contains an invalid alias). Writing a symbol
5163 // table is not required for correctness, but we still want to be able to
5164 // write malformed modules to bitcode files, so swallow the error.
5165 if (Error E = irsymtab::build(Mods, Symtab, StrtabBuilder, Alloc)) {
5166 consumeError(std::move(E));
5167 return;
5170 writeBlob(bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB,
5171 {Symtab.data(), Symtab.size()});
5174 void BitcodeWriter::writeStrtab() {
5175 assert(!WroteStrtab);
5177 std::vector<char> Strtab;
5178 StrtabBuilder.finalizeInOrder();
5179 Strtab.resize(StrtabBuilder.getSize());
5180 StrtabBuilder.write((uint8_t *)Strtab.data());
5182 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB,
5183 {Strtab.data(), Strtab.size()});
5185 WroteStrtab = true;
5188 void BitcodeWriter::copyStrtab(StringRef Strtab) {
5189 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab);
5190 WroteStrtab = true;
5193 void BitcodeWriter::writeModule(const Module &M,
5194 bool ShouldPreserveUseListOrder,
5195 const ModuleSummaryIndex *Index,
5196 bool GenerateHash, ModuleHash *ModHash) {
5197 assert(!WroteStrtab);
5199 // The Mods vector is used by irsymtab::build, which requires non-const
5200 // Modules in case it needs to materialize metadata. But the bitcode writer
5201 // requires that the module is materialized, so we can cast to non-const here,
5202 // after checking that it is in fact materialized.
5203 assert(M.isMaterialized());
5204 Mods.push_back(const_cast<Module *>(&M));
5206 ModuleBitcodeWriter ModuleWriter(M, StrtabBuilder, *Stream,
5207 ShouldPreserveUseListOrder, Index,
5208 GenerateHash, ModHash);
5209 ModuleWriter.write();
5212 void BitcodeWriter::writeIndex(
5213 const ModuleSummaryIndex *Index,
5214 const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex,
5215 const GVSummaryPtrSet *DecSummaries) {
5216 IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index, DecSummaries,
5217 ModuleToSummariesForIndex);
5218 IndexWriter.write();
5221 /// Write the specified module to the specified output stream.
5222 void llvm::WriteBitcodeToFile(const Module &M, raw_ostream &Out,
5223 bool ShouldPreserveUseListOrder,
5224 const ModuleSummaryIndex *Index,
5225 bool GenerateHash, ModuleHash *ModHash) {
5226 auto Write = [&](BitcodeWriter &Writer) {
5227 Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
5228 ModHash);
5229 Writer.writeSymtab();
5230 Writer.writeStrtab();
5232 Triple TT(M.getTargetTriple());
5233 if (TT.isOSDarwin() || TT.isOSBinFormatMachO()) {
5234 // If this is darwin or another generic macho target, reserve space for the
5235 // header. Note that the header is computed *after* the output is known, so
5236 // we currently explicitly use a buffer, write to it, and then subsequently
5237 // flush to Out.
5238 SmallVector<char, 0> Buffer;
5239 Buffer.reserve(256 * 1024);
5240 Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
5241 BitcodeWriter Writer(Buffer);
5242 Write(Writer);
5243 emitDarwinBCHeaderAndTrailer(Buffer, TT);
5244 Out.write(Buffer.data(), Buffer.size());
5245 } else {
5246 BitcodeWriter Writer(Out);
5247 Write(Writer);
5251 void IndexBitcodeWriter::write() {
5252 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
5254 writeModuleVersion();
5256 // Write the module paths in the combined index.
5257 writeModStrings();
5259 // Write the summary combined index records.
5260 writeCombinedGlobalValueSummary();
5262 Stream.ExitBlock();
5265 // Write the specified module summary index to the given raw output stream,
5266 // where it will be written in a new bitcode block. This is used when
5267 // writing the combined index file for ThinLTO. When writing a subset of the
5268 // index for a distributed backend, provide a \p ModuleToSummariesForIndex map.
5269 void llvm::writeIndexToFile(
5270 const ModuleSummaryIndex &Index, raw_ostream &Out,
5271 const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex,
5272 const GVSummaryPtrSet *DecSummaries) {
5273 SmallVector<char, 0> Buffer;
5274 Buffer.reserve(256 * 1024);
5276 BitcodeWriter Writer(Buffer);
5277 Writer.writeIndex(&Index, ModuleToSummariesForIndex, DecSummaries);
5278 Writer.writeStrtab();
5280 Out.write((char *)&Buffer.front(), Buffer.size());
5283 namespace {
5285 /// Class to manage the bitcode writing for a thin link bitcode file.
5286 class ThinLinkBitcodeWriter : public ModuleBitcodeWriterBase {
5287 /// ModHash is for use in ThinLTO incremental build, generated while writing
5288 /// the module bitcode file.
5289 const ModuleHash *ModHash;
5291 public:
5292 ThinLinkBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder,
5293 BitstreamWriter &Stream,
5294 const ModuleSummaryIndex &Index,
5295 const ModuleHash &ModHash)
5296 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
5297 /*ShouldPreserveUseListOrder=*/false, &Index),
5298 ModHash(&ModHash) {}
5300 void write();
5302 private:
5303 void writeSimplifiedModuleInfo();
5306 } // end anonymous namespace
5308 // This function writes a simpilified module info for thin link bitcode file.
5309 // It only contains the source file name along with the name(the offset and
5310 // size in strtab) and linkage for global values. For the global value info
5311 // entry, in order to keep linkage at offset 5, there are three zeros used
5312 // as padding.
5313 void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {
5314 SmallVector<unsigned, 64> Vals;
5315 // Emit the module's source file name.
5317 StringEncoding Bits = getStringEncoding(M.getSourceFileName());
5318 BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
5319 if (Bits == SE_Char6)
5320 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
5321 else if (Bits == SE_Fixed7)
5322 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
5324 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
5325 auto Abbv = std::make_shared<BitCodeAbbrev>();
5326 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
5327 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5328 Abbv->Add(AbbrevOpToUse);
5329 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5331 for (const auto P : M.getSourceFileName())
5332 Vals.push_back((unsigned char)P);
5334 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
5335 Vals.clear();
5338 // Emit the global variable information.
5339 for (const GlobalVariable &GV : M.globals()) {
5340 // GLOBALVAR: [strtab offset, strtab size, 0, 0, 0, linkage]
5341 Vals.push_back(StrtabBuilder.add(GV.getName()));
5342 Vals.push_back(GV.getName().size());
5343 Vals.push_back(0);
5344 Vals.push_back(0);
5345 Vals.push_back(0);
5346 Vals.push_back(getEncodedLinkage(GV));
5348 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals);
5349 Vals.clear();
5352 // Emit the function proto information.
5353 for (const Function &F : M) {
5354 // FUNCTION: [strtab offset, strtab size, 0, 0, 0, linkage]
5355 Vals.push_back(StrtabBuilder.add(F.getName()));
5356 Vals.push_back(F.getName().size());
5357 Vals.push_back(0);
5358 Vals.push_back(0);
5359 Vals.push_back(0);
5360 Vals.push_back(getEncodedLinkage(F));
5362 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals);
5363 Vals.clear();
5366 // Emit the alias information.
5367 for (const GlobalAlias &A : M.aliases()) {
5368 // ALIAS: [strtab offset, strtab size, 0, 0, 0, linkage]
5369 Vals.push_back(StrtabBuilder.add(A.getName()));
5370 Vals.push_back(A.getName().size());
5371 Vals.push_back(0);
5372 Vals.push_back(0);
5373 Vals.push_back(0);
5374 Vals.push_back(getEncodedLinkage(A));
5376 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals);
5377 Vals.clear();
5380 // Emit the ifunc information.
5381 for (const GlobalIFunc &I : M.ifuncs()) {
5382 // IFUNC: [strtab offset, strtab size, 0, 0, 0, linkage]
5383 Vals.push_back(StrtabBuilder.add(I.getName()));
5384 Vals.push_back(I.getName().size());
5385 Vals.push_back(0);
5386 Vals.push_back(0);
5387 Vals.push_back(0);
5388 Vals.push_back(getEncodedLinkage(I));
5390 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
5391 Vals.clear();
5395 void ThinLinkBitcodeWriter::write() {
5396 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
5398 writeModuleVersion();
5400 writeSimplifiedModuleInfo();
5402 writePerModuleGlobalValueSummary();
5404 // Write module hash.
5405 Stream.EmitRecord(bitc::MODULE_CODE_HASH, ArrayRef<uint32_t>(*ModHash));
5407 Stream.ExitBlock();
5410 void BitcodeWriter::writeThinLinkBitcode(const Module &M,
5411 const ModuleSummaryIndex &Index,
5412 const ModuleHash &ModHash) {
5413 assert(!WroteStrtab);
5415 // The Mods vector is used by irsymtab::build, which requires non-const
5416 // Modules in case it needs to materialize metadata. But the bitcode writer
5417 // requires that the module is materialized, so we can cast to non-const here,
5418 // after checking that it is in fact materialized.
5419 assert(M.isMaterialized());
5420 Mods.push_back(const_cast<Module *>(&M));
5422 ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index,
5423 ModHash);
5424 ThinLinkWriter.write();
5427 // Write the specified thin link bitcode file to the given raw output stream,
5428 // where it will be written in a new bitcode block. This is used when
5429 // writing the per-module index file for ThinLTO.
5430 void llvm::writeThinLinkBitcodeToFile(const Module &M, raw_ostream &Out,
5431 const ModuleSummaryIndex &Index,
5432 const ModuleHash &ModHash) {
5433 SmallVector<char, 0> Buffer;
5434 Buffer.reserve(256 * 1024);
5436 BitcodeWriter Writer(Buffer);
5437 Writer.writeThinLinkBitcode(M, Index, ModHash);
5438 Writer.writeSymtab();
5439 Writer.writeStrtab();
5441 Out.write((char *)&Buffer.front(), Buffer.size());
5444 static const char *getSectionNameForBitcode(const Triple &T) {
5445 switch (T.getObjectFormat()) {
5446 case Triple::MachO:
5447 return "__LLVM,__bitcode";
5448 case Triple::COFF:
5449 case Triple::ELF:
5450 case Triple::Wasm:
5451 case Triple::UnknownObjectFormat:
5452 return ".llvmbc";
5453 case Triple::GOFF:
5454 llvm_unreachable("GOFF is not yet implemented");
5455 break;
5456 case Triple::SPIRV:
5457 if (T.getVendor() == Triple::AMD)
5458 return ".llvmbc";
5459 llvm_unreachable("SPIRV is not yet implemented");
5460 break;
5461 case Triple::XCOFF:
5462 llvm_unreachable("XCOFF is not yet implemented");
5463 break;
5464 case Triple::DXContainer:
5465 llvm_unreachable("DXContainer is not yet implemented");
5466 break;
5468 llvm_unreachable("Unimplemented ObjectFormatType");
5471 static const char *getSectionNameForCommandline(const Triple &T) {
5472 switch (T.getObjectFormat()) {
5473 case Triple::MachO:
5474 return "__LLVM,__cmdline";
5475 case Triple::COFF:
5476 case Triple::ELF:
5477 case Triple::Wasm:
5478 case Triple::UnknownObjectFormat:
5479 return ".llvmcmd";
5480 case Triple::GOFF:
5481 llvm_unreachable("GOFF is not yet implemented");
5482 break;
5483 case Triple::SPIRV:
5484 if (T.getVendor() == Triple::AMD)
5485 return ".llvmcmd";
5486 llvm_unreachable("SPIRV is not yet implemented");
5487 break;
5488 case Triple::XCOFF:
5489 llvm_unreachable("XCOFF is not yet implemented");
5490 break;
5491 case Triple::DXContainer:
5492 llvm_unreachable("DXC is not yet implemented");
5493 break;
5495 llvm_unreachable("Unimplemented ObjectFormatType");
5498 void llvm::embedBitcodeInModule(llvm::Module &M, llvm::MemoryBufferRef Buf,
5499 bool EmbedBitcode, bool EmbedCmdline,
5500 const std::vector<uint8_t> &CmdArgs) {
5501 // Save llvm.compiler.used and remove it.
5502 SmallVector<Constant *, 2> UsedArray;
5503 SmallVector<GlobalValue *, 4> UsedGlobals;
5504 GlobalVariable *Used = collectUsedGlobalVariables(M, UsedGlobals, true);
5505 Type *UsedElementType = Used ? Used->getValueType()->getArrayElementType()
5506 : PointerType::getUnqual(M.getContext());
5507 for (auto *GV : UsedGlobals) {
5508 if (GV->getName() != "llvm.embedded.module" &&
5509 GV->getName() != "llvm.cmdline")
5510 UsedArray.push_back(
5511 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
5513 if (Used)
5514 Used->eraseFromParent();
5516 // Embed the bitcode for the llvm module.
5517 std::string Data;
5518 ArrayRef<uint8_t> ModuleData;
5519 Triple T(M.getTargetTriple());
5521 if (EmbedBitcode) {
5522 if (Buf.getBufferSize() == 0 ||
5523 !isBitcode((const unsigned char *)Buf.getBufferStart(),
5524 (const unsigned char *)Buf.getBufferEnd())) {
5525 // If the input is LLVM Assembly, bitcode is produced by serializing
5526 // the module. Use-lists order need to be preserved in this case.
5527 llvm::raw_string_ostream OS(Data);
5528 llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true);
5529 ModuleData =
5530 ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
5531 } else
5532 // If the input is LLVM bitcode, write the input byte stream directly.
5533 ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
5534 Buf.getBufferSize());
5536 llvm::Constant *ModuleConstant =
5537 llvm::ConstantDataArray::get(M.getContext(), ModuleData);
5538 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
5539 M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
5540 ModuleConstant);
5541 GV->setSection(getSectionNameForBitcode(T));
5542 // Set alignment to 1 to prevent padding between two contributions from input
5543 // sections after linking.
5544 GV->setAlignment(Align(1));
5545 UsedArray.push_back(
5546 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
5547 if (llvm::GlobalVariable *Old =
5548 M.getGlobalVariable("llvm.embedded.module", true)) {
5549 assert(Old->hasZeroLiveUses() &&
5550 "llvm.embedded.module can only be used once in llvm.compiler.used");
5551 GV->takeName(Old);
5552 Old->eraseFromParent();
5553 } else {
5554 GV->setName("llvm.embedded.module");
5557 // Skip if only bitcode needs to be embedded.
5558 if (EmbedCmdline) {
5559 // Embed command-line options.
5560 ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CmdArgs.data()),
5561 CmdArgs.size());
5562 llvm::Constant *CmdConstant =
5563 llvm::ConstantDataArray::get(M.getContext(), CmdData);
5564 GV = new llvm::GlobalVariable(M, CmdConstant->getType(), true,
5565 llvm::GlobalValue::PrivateLinkage,
5566 CmdConstant);
5567 GV->setSection(getSectionNameForCommandline(T));
5568 GV->setAlignment(Align(1));
5569 UsedArray.push_back(
5570 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
5571 if (llvm::GlobalVariable *Old = M.getGlobalVariable("llvm.cmdline", true)) {
5572 assert(Old->hasZeroLiveUses() &&
5573 "llvm.cmdline can only be used once in llvm.compiler.used");
5574 GV->takeName(Old);
5575 Old->eraseFromParent();
5576 } else {
5577 GV->setName("llvm.cmdline");
5581 if (UsedArray.empty())
5582 return;
5584 // Recreate llvm.compiler.used.
5585 ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
5586 auto *NewUsed = new GlobalVariable(
5587 M, ATy, false, llvm::GlobalValue::AppendingLinkage,
5588 llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
5589 NewUsed->setSection("llvm.metadata");