1 //===- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ------------------===//
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
7 //===----------------------------------------------------------------------===//
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/Constants.h"
37 #include "llvm/IR/DebugInfoMetadata.h"
38 #include "llvm/IR/DebugLoc.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GlobalAlias.h"
42 #include "llvm/IR/GlobalIFunc.h"
43 #include "llvm/IR/GlobalObject.h"
44 #include "llvm/IR/GlobalValue.h"
45 #include "llvm/IR/GlobalVariable.h"
46 #include "llvm/IR/InlineAsm.h"
47 #include "llvm/IR/InstrTypes.h"
48 #include "llvm/IR/Instruction.h"
49 #include "llvm/IR/Instructions.h"
50 #include "llvm/IR/LLVMContext.h"
51 #include "llvm/IR/Metadata.h"
52 #include "llvm/IR/Module.h"
53 #include "llvm/IR/ModuleSummaryIndex.h"
54 #include "llvm/IR/Operator.h"
55 #include "llvm/IR/Type.h"
56 #include "llvm/IR/UseListOrder.h"
57 #include "llvm/IR/Value.h"
58 #include "llvm/IR/ValueSymbolTable.h"
59 #include "llvm/MC/StringTableBuilder.h"
60 #include "llvm/MC/TargetRegistry.h"
61 #include "llvm/Object/IRSymtab.h"
62 #include "llvm/Support/AtomicOrdering.h"
63 #include "llvm/Support/Casting.h"
64 #include "llvm/Support/CommandLine.h"
65 #include "llvm/Support/Endian.h"
66 #include "llvm/Support/Error.h"
67 #include "llvm/Support/ErrorHandling.h"
68 #include "llvm/Support/MathExtras.h"
69 #include "llvm/Support/SHA1.h"
70 #include "llvm/Support/raw_ostream.h"
71 #include "llvm/TargetParser/Triple.h"
86 static cl::opt
<unsigned>
87 IndexThreshold("bitcode-mdindex-threshold", cl::Hidden
, cl::init(25),
88 cl::desc("Number of metadatas above which we emit an index "
89 "to enable lazy-loading"));
90 static cl::opt
<uint32_t> FlushThreshold(
91 "bitcode-flush-threshold", cl::Hidden
, cl::init(512),
92 cl::desc("The threshold (unit M) for flushing LLVM bitcode."));
94 static cl::opt
<bool> WriteRelBFToSummary(
95 "write-relbf-to-summary", cl::Hidden
, cl::init(false),
96 cl::desc("Write relative block frequency to function summary "));
99 extern FunctionSummary::ForceSummaryHotnessType ForceSummaryEdgesCold
;
102 extern bool WriteNewDbgInfoFormatToBitcode
;
103 extern llvm::cl::opt
<bool> UseNewDbgInfoFormat
;
107 /// These are manifest constants used by the bitcode writer. They do not need to
108 /// be kept in sync with the reader, but need to be consistent within this file.
110 // VALUE_SYMTAB_BLOCK abbrev id's.
111 VST_ENTRY_8_ABBREV
= bitc::FIRST_APPLICATION_ABBREV
,
114 VST_BBENTRY_6_ABBREV
,
116 // CONSTANTS_BLOCK abbrev id's.
117 CONSTANTS_SETTYPE_ABBREV
= bitc::FIRST_APPLICATION_ABBREV
,
118 CONSTANTS_INTEGER_ABBREV
,
119 CONSTANTS_CE_CAST_Abbrev
,
120 CONSTANTS_NULL_Abbrev
,
122 // FUNCTION_BLOCK abbrev id's.
123 FUNCTION_INST_LOAD_ABBREV
= bitc::FIRST_APPLICATION_ABBREV
,
124 FUNCTION_INST_UNOP_ABBREV
,
125 FUNCTION_INST_UNOP_FLAGS_ABBREV
,
126 FUNCTION_INST_BINOP_ABBREV
,
127 FUNCTION_INST_BINOP_FLAGS_ABBREV
,
128 FUNCTION_INST_CAST_ABBREV
,
129 FUNCTION_INST_CAST_FLAGS_ABBREV
,
130 FUNCTION_INST_RET_VOID_ABBREV
,
131 FUNCTION_INST_RET_VAL_ABBREV
,
132 FUNCTION_INST_UNREACHABLE_ABBREV
,
133 FUNCTION_INST_GEP_ABBREV
,
134 FUNCTION_DEBUG_RECORD_VALUE_ABBREV
,
137 /// Abstract class to manage the bitcode writing, subclassed for each bitcode
139 class BitcodeWriterBase
{
141 /// The stream created and owned by the client.
142 BitstreamWriter
&Stream
;
144 StringTableBuilder
&StrtabBuilder
;
147 /// Constructs a BitcodeWriterBase object that writes to the provided
149 BitcodeWriterBase(BitstreamWriter
&Stream
, StringTableBuilder
&StrtabBuilder
)
150 : Stream(Stream
), StrtabBuilder(StrtabBuilder
) {}
153 void writeModuleVersion();
156 void BitcodeWriterBase::writeModuleVersion() {
157 // VERSION: [version#]
158 Stream
.EmitRecord(bitc::MODULE_CODE_VERSION
, ArrayRef
<uint64_t>{2});
161 /// Base class to manage the module bitcode writing, currently subclassed for
162 /// ModuleBitcodeWriter and ThinLinkBitcodeWriter.
163 class ModuleBitcodeWriterBase
: public BitcodeWriterBase
{
165 /// The Module to write to bitcode.
168 /// Enumerates ids for all values in the module.
171 /// Optional per-module index to write for ThinLTO.
172 const ModuleSummaryIndex
*Index
;
174 /// Map that holds the correspondence between GUIDs in the summary index,
175 /// that came from indirect call profiles, and a value id generated by this
176 /// class to use in the VST and summary block records.
177 std::map
<GlobalValue::GUID
, unsigned> GUIDToValueIdMap
;
179 /// Tracks the last value id recorded in the GUIDToValueMap.
180 unsigned GlobalValueId
;
182 /// Saves the offset of the VSTOffset record that must eventually be
183 /// backpatched with the offset of the actual VST.
184 uint64_t VSTOffsetPlaceholder
= 0;
187 /// Constructs a ModuleBitcodeWriterBase object for the given Module,
188 /// writing to the provided \p Buffer.
189 ModuleBitcodeWriterBase(const Module
&M
, StringTableBuilder
&StrtabBuilder
,
190 BitstreamWriter
&Stream
,
191 bool ShouldPreserveUseListOrder
,
192 const ModuleSummaryIndex
*Index
)
193 : BitcodeWriterBase(Stream
, StrtabBuilder
), M(M
),
194 VE(M
, ShouldPreserveUseListOrder
), Index(Index
) {
195 // Assign ValueIds to any callee values in the index that came from
196 // indirect call profiles and were recorded as a GUID not a Value*
197 // (which would have been assigned an ID by the ValueEnumerator).
198 // The starting ValueId is just after the number of values in the
199 // ValueEnumerator, so that they can be emitted in the VST.
200 GlobalValueId
= VE
.getValues().size();
203 for (const auto &GUIDSummaryLists
: *Index
)
204 // Examine all summaries for this GUID.
205 for (auto &Summary
: GUIDSummaryLists
.second
.SummaryList
)
206 if (auto FS
= dyn_cast
<FunctionSummary
>(Summary
.get())) {
207 // For each call in the function summary, see if the call
208 // is to a GUID (which means it is for an indirect call,
209 // otherwise we would have a Value for it). If so, synthesize
211 for (auto &CallEdge
: FS
->calls())
212 if (!CallEdge
.first
.haveGVs() || !CallEdge
.first
.getValue())
213 assignValueId(CallEdge
.first
.getGUID());
215 // For each referenced variables in the function summary, see if the
216 // variable is represented by a GUID (as opposed to a symbol to
217 // declarations or definitions in the module). If so, synthesize a
219 for (auto &RefEdge
: FS
->refs())
220 if (!RefEdge
.haveGVs() || !RefEdge
.getValue())
221 assignValueId(RefEdge
.getGUID());
226 void writePerModuleGlobalValueSummary();
229 void writePerModuleFunctionSummaryRecord(
230 SmallVector
<uint64_t, 64> &NameVals
, GlobalValueSummary
*Summary
,
231 unsigned ValueID
, unsigned FSCallsAbbrev
, unsigned FSCallsProfileAbbrev
,
232 unsigned CallsiteAbbrev
, unsigned AllocAbbrev
, const Function
&F
);
233 void writeModuleLevelReferences(const GlobalVariable
&V
,
234 SmallVector
<uint64_t, 64> &NameVals
,
235 unsigned FSModRefsAbbrev
,
236 unsigned FSModVTableRefsAbbrev
);
238 void assignValueId(GlobalValue::GUID ValGUID
) {
239 GUIDToValueIdMap
[ValGUID
] = ++GlobalValueId
;
242 unsigned getValueId(GlobalValue::GUID ValGUID
) {
243 const auto &VMI
= GUIDToValueIdMap
.find(ValGUID
);
244 // Expect that any GUID value had a value Id assigned by an
245 // earlier call to assignValueId.
246 assert(VMI
!= GUIDToValueIdMap
.end() &&
247 "GUID does not have assigned value Id");
251 // Helper to get the valueId for the type of value recorded in VI.
252 unsigned getValueId(ValueInfo VI
) {
253 if (!VI
.haveGVs() || !VI
.getValue())
254 return getValueId(VI
.getGUID());
255 return VE
.getValueID(VI
.getValue());
258 std::map
<GlobalValue::GUID
, unsigned> &valueIds() { return GUIDToValueIdMap
; }
261 /// Class to manage the bitcode writing for a module.
262 class ModuleBitcodeWriter
: public ModuleBitcodeWriterBase
{
263 /// Pointer to the buffer allocated by caller for bitcode writing.
264 const SmallVectorImpl
<char> &Buffer
;
266 /// True if a module hash record should be written.
269 /// If non-null, when GenerateHash is true, the resulting hash is written
275 /// The start bit of the identification block.
276 uint64_t BitcodeStartBit
;
279 /// Constructs a ModuleBitcodeWriter object for the given Module,
280 /// writing to the provided \p Buffer.
281 ModuleBitcodeWriter(const Module
&M
, SmallVectorImpl
<char> &Buffer
,
282 StringTableBuilder
&StrtabBuilder
,
283 BitstreamWriter
&Stream
, bool ShouldPreserveUseListOrder
,
284 const ModuleSummaryIndex
*Index
, bool GenerateHash
,
285 ModuleHash
*ModHash
= nullptr)
286 : ModuleBitcodeWriterBase(M
, StrtabBuilder
, Stream
,
287 ShouldPreserveUseListOrder
, Index
),
288 Buffer(Buffer
), GenerateHash(GenerateHash
), ModHash(ModHash
),
289 BitcodeStartBit(Stream
.GetCurrentBitNo()) {}
291 /// Emit the current module to the bitstream.
295 uint64_t bitcodeStartBit() { return BitcodeStartBit
; }
297 size_t addToStrtab(StringRef Str
);
299 void writeAttributeGroupTable();
300 void writeAttributeTable();
301 void writeTypeTable();
303 void writeValueSymbolTableForwardDecl();
304 void writeModuleInfo();
305 void writeValueAsMetadata(const ValueAsMetadata
*MD
,
306 SmallVectorImpl
<uint64_t> &Record
);
307 void writeMDTuple(const MDTuple
*N
, SmallVectorImpl
<uint64_t> &Record
,
309 unsigned createDILocationAbbrev();
310 void writeDILocation(const DILocation
*N
, SmallVectorImpl
<uint64_t> &Record
,
312 unsigned createGenericDINodeAbbrev();
313 void writeGenericDINode(const GenericDINode
*N
,
314 SmallVectorImpl
<uint64_t> &Record
, unsigned &Abbrev
);
315 void writeDISubrange(const DISubrange
*N
, SmallVectorImpl
<uint64_t> &Record
,
317 void writeDIGenericSubrange(const DIGenericSubrange
*N
,
318 SmallVectorImpl
<uint64_t> &Record
,
320 void writeDIEnumerator(const DIEnumerator
*N
,
321 SmallVectorImpl
<uint64_t> &Record
, unsigned Abbrev
);
322 void writeDIBasicType(const DIBasicType
*N
, SmallVectorImpl
<uint64_t> &Record
,
324 void writeDIStringType(const DIStringType
*N
,
325 SmallVectorImpl
<uint64_t> &Record
, unsigned Abbrev
);
326 void writeDIDerivedType(const DIDerivedType
*N
,
327 SmallVectorImpl
<uint64_t> &Record
, unsigned Abbrev
);
328 void writeDICompositeType(const DICompositeType
*N
,
329 SmallVectorImpl
<uint64_t> &Record
, unsigned Abbrev
);
330 void writeDISubroutineType(const DISubroutineType
*N
,
331 SmallVectorImpl
<uint64_t> &Record
,
333 void writeDIFile(const DIFile
*N
, SmallVectorImpl
<uint64_t> &Record
,
335 void writeDICompileUnit(const DICompileUnit
*N
,
336 SmallVectorImpl
<uint64_t> &Record
, unsigned Abbrev
);
337 void writeDISubprogram(const DISubprogram
*N
,
338 SmallVectorImpl
<uint64_t> &Record
, unsigned Abbrev
);
339 void writeDILexicalBlock(const DILexicalBlock
*N
,
340 SmallVectorImpl
<uint64_t> &Record
, unsigned Abbrev
);
341 void writeDILexicalBlockFile(const DILexicalBlockFile
*N
,
342 SmallVectorImpl
<uint64_t> &Record
,
344 void writeDICommonBlock(const DICommonBlock
*N
,
345 SmallVectorImpl
<uint64_t> &Record
, unsigned Abbrev
);
346 void writeDINamespace(const DINamespace
*N
, SmallVectorImpl
<uint64_t> &Record
,
348 void writeDIMacro(const DIMacro
*N
, SmallVectorImpl
<uint64_t> &Record
,
350 void writeDIMacroFile(const DIMacroFile
*N
, SmallVectorImpl
<uint64_t> &Record
,
352 void writeDIArgList(const DIArgList
*N
, SmallVectorImpl
<uint64_t> &Record
);
353 void writeDIModule(const DIModule
*N
, SmallVectorImpl
<uint64_t> &Record
,
355 void writeDIAssignID(const DIAssignID
*N
, SmallVectorImpl
<uint64_t> &Record
,
357 void writeDITemplateTypeParameter(const DITemplateTypeParameter
*N
,
358 SmallVectorImpl
<uint64_t> &Record
,
360 void writeDITemplateValueParameter(const DITemplateValueParameter
*N
,
361 SmallVectorImpl
<uint64_t> &Record
,
363 void writeDIGlobalVariable(const DIGlobalVariable
*N
,
364 SmallVectorImpl
<uint64_t> &Record
,
366 void writeDILocalVariable(const DILocalVariable
*N
,
367 SmallVectorImpl
<uint64_t> &Record
, unsigned Abbrev
);
368 void writeDILabel(const DILabel
*N
,
369 SmallVectorImpl
<uint64_t> &Record
, unsigned Abbrev
);
370 void writeDIExpression(const DIExpression
*N
,
371 SmallVectorImpl
<uint64_t> &Record
, unsigned Abbrev
);
372 void writeDIGlobalVariableExpression(const DIGlobalVariableExpression
*N
,
373 SmallVectorImpl
<uint64_t> &Record
,
375 void writeDIObjCProperty(const DIObjCProperty
*N
,
376 SmallVectorImpl
<uint64_t> &Record
, unsigned Abbrev
);
377 void writeDIImportedEntity(const DIImportedEntity
*N
,
378 SmallVectorImpl
<uint64_t> &Record
,
380 unsigned createNamedMetadataAbbrev();
381 void writeNamedMetadata(SmallVectorImpl
<uint64_t> &Record
);
382 unsigned createMetadataStringsAbbrev();
383 void writeMetadataStrings(ArrayRef
<const Metadata
*> Strings
,
384 SmallVectorImpl
<uint64_t> &Record
);
385 void writeMetadataRecords(ArrayRef
<const Metadata
*> MDs
,
386 SmallVectorImpl
<uint64_t> &Record
,
387 std::vector
<unsigned> *MDAbbrevs
= nullptr,
388 std::vector
<uint64_t> *IndexPos
= nullptr);
389 void writeModuleMetadata();
390 void writeFunctionMetadata(const Function
&F
);
391 void writeFunctionMetadataAttachment(const Function
&F
);
392 void pushGlobalMetadataAttachment(SmallVectorImpl
<uint64_t> &Record
,
393 const GlobalObject
&GO
);
394 void writeModuleMetadataKinds();
395 void writeOperandBundleTags();
396 void writeSyncScopeNames();
397 void writeConstants(unsigned FirstVal
, unsigned LastVal
, bool isGlobal
);
398 void writeModuleConstants();
399 bool pushValueAndType(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
);
414 writeFunction(const Function
&F
,
415 DenseMap
<const Function
*, uint64_t> &FunctionToBitcodeIndex
);
416 void writeBlockInfo();
417 void writeModuleHash(size_t BlockStartPos
);
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 a subset of the index for distributed backends, client
432 /// provides a map of modules to the corresponding GUIDs/summaries to write.
433 const std::map
<std::string
, GVSummaryMapTy
> *ModuleToSummariesForIndex
;
435 /// Map that holds the correspondence between the GUID used in the combined
436 /// index and a value id generated by this class to use in references.
437 std::map
<GlobalValue::GUID
, unsigned> GUIDToValueIdMap
;
439 // The sorted stack id indices actually used in the summary entries being
440 // written, which will be a subset of those in the full index in the case of
441 // distributed indexes.
442 std::vector
<unsigned> StackIdIndices
;
444 /// Tracks the last value id recorded in the GUIDToValueMap.
445 unsigned GlobalValueId
= 0;
447 /// Tracks the assignment of module paths in the module path string table to
448 /// an id assigned for use in summary references to the module path.
449 DenseMap
<StringRef
, uint64_t> ModuleIdMap
;
452 /// Constructs a IndexBitcodeWriter object for the given combined index,
453 /// writing to the provided \p Buffer. When writing a subset of the index
454 /// for a distributed backend, provide a \p ModuleToSummariesForIndex map.
455 IndexBitcodeWriter(BitstreamWriter
&Stream
, StringTableBuilder
&StrtabBuilder
,
456 const ModuleSummaryIndex
&Index
,
457 const std::map
<std::string
, GVSummaryMapTy
>
458 *ModuleToSummariesForIndex
= nullptr)
459 : BitcodeWriterBase(Stream
, StrtabBuilder
), Index(Index
),
460 ModuleToSummariesForIndex(ModuleToSummariesForIndex
) {
461 // Assign unique value ids to all summaries to be written, for use
462 // in writing out the call graph edges. Save the mapping from GUID
463 // to the new global value id to use when writing those edges, which
464 // are currently saved in the index in terms of GUID.
465 forEachSummary([&](GVInfo I
, bool IsAliasee
) {
466 GUIDToValueIdMap
[I
.first
] = ++GlobalValueId
;
469 auto *FS
= dyn_cast
<FunctionSummary
>(I
.second
);
472 // Record all stack id indices actually used in the summary entries being
473 // written, so that we can compact them in the case of distributed ThinLTO
475 for (auto &CI
: FS
->callsites()) {
476 // If the stack id list is empty, this callsite info was synthesized for
477 // a missing tail call frame. Ensure that the callee's GUID gets a value
478 // id. Normally we only generate these for defined summaries, which in
479 // the case of distributed ThinLTO is only the functions already defined
480 // in the module or that we want to import. We don't bother to include
481 // all the callee symbols as they aren't normally needed in the backend.
482 // However, for the synthesized callsite infos we do need the callee
483 // GUID in the backend so that we can correlate the identified callee
484 // with this callsite info (which for non-tail calls is done by the
485 // ordering of the callsite infos and verified via stack ids).
486 if (CI
.StackIdIndices
.empty()) {
487 GUIDToValueIdMap
[CI
.Callee
.getGUID()] = ++GlobalValueId
;
490 for (auto Idx
: CI
.StackIdIndices
)
491 StackIdIndices
.push_back(Idx
);
493 for (auto &AI
: FS
->allocs())
494 for (auto &MIB
: AI
.MIBs
)
495 for (auto Idx
: MIB
.StackIdIndices
)
496 StackIdIndices
.push_back(Idx
);
498 llvm::sort(StackIdIndices
);
499 StackIdIndices
.erase(
500 std::unique(StackIdIndices
.begin(), StackIdIndices
.end()),
501 StackIdIndices
.end());
504 /// The below iterator returns the GUID and associated summary.
505 using GVInfo
= std::pair
<GlobalValue::GUID
, GlobalValueSummary
*>;
507 /// Calls the callback for each value GUID and summary to be written to
508 /// bitcode. This hides the details of whether they are being pulled from the
509 /// entire index or just those in a provided ModuleToSummariesForIndex map.
510 template<typename Functor
>
511 void forEachSummary(Functor Callback
) {
512 if (ModuleToSummariesForIndex
) {
513 for (auto &M
: *ModuleToSummariesForIndex
)
514 for (auto &Summary
: M
.second
) {
515 Callback(Summary
, false);
516 // Ensure aliasee is handled, e.g. for assigning a valueId,
517 // even if we are not importing the aliasee directly (the
518 // imported alias will contain a copy of aliasee).
519 if (auto *AS
= dyn_cast
<AliasSummary
>(Summary
.getSecond()))
520 Callback({AS
->getAliaseeGUID(), &AS
->getAliasee()}, true);
523 for (auto &Summaries
: Index
)
524 for (auto &Summary
: Summaries
.second
.SummaryList
)
525 Callback({Summaries
.first
, Summary
.get()}, false);
529 /// Calls the callback for each entry in the modulePaths StringMap that
530 /// should be written to the module path string table. This hides the details
531 /// of whether they are being pulled from the entire index or just those in a
532 /// provided ModuleToSummariesForIndex map.
533 template <typename Functor
> void forEachModule(Functor Callback
) {
534 if (ModuleToSummariesForIndex
) {
535 for (const auto &M
: *ModuleToSummariesForIndex
) {
536 const auto &MPI
= Index
.modulePaths().find(M
.first
);
537 if (MPI
== Index
.modulePaths().end()) {
538 // This should only happen if the bitcode file was empty, in which
539 // case we shouldn't be importing (the ModuleToSummariesForIndex
540 // would only include the module we are writing and index for).
541 assert(ModuleToSummariesForIndex
->size() == 1);
547 // Since StringMap iteration order isn't guaranteed, order by path string
549 // FIXME: Make this a vector of StringMapEntry instead to avoid the later
551 std::vector
<StringRef
> ModulePaths
;
552 for (auto &[ModPath
, _
] : Index
.modulePaths())
553 ModulePaths
.push_back(ModPath
);
554 llvm::sort(ModulePaths
.begin(), ModulePaths
.end());
555 for (auto &ModPath
: ModulePaths
)
556 Callback(*Index
.modulePaths().find(ModPath
));
560 /// Main entry point for writing a combined index to bitcode.
564 void writeModStrings();
565 void writeCombinedGlobalValueSummary();
567 std::optional
<unsigned> getValueId(GlobalValue::GUID ValGUID
) {
568 auto VMI
= GUIDToValueIdMap
.find(ValGUID
);
569 if (VMI
== GUIDToValueIdMap
.end())
574 std::map
<GlobalValue::GUID
, unsigned> &valueIds() { return GUIDToValueIdMap
; }
577 } // end anonymous namespace
579 static unsigned getEncodedCastOpcode(unsigned Opcode
) {
581 default: llvm_unreachable("Unknown cast instruction!");
582 case Instruction::Trunc
: return bitc::CAST_TRUNC
;
583 case Instruction::ZExt
: return bitc::CAST_ZEXT
;
584 case Instruction::SExt
: return bitc::CAST_SEXT
;
585 case Instruction::FPToUI
: return bitc::CAST_FPTOUI
;
586 case Instruction::FPToSI
: return bitc::CAST_FPTOSI
;
587 case Instruction::UIToFP
: return bitc::CAST_UITOFP
;
588 case Instruction::SIToFP
: return bitc::CAST_SITOFP
;
589 case Instruction::FPTrunc
: return bitc::CAST_FPTRUNC
;
590 case Instruction::FPExt
: return bitc::CAST_FPEXT
;
591 case Instruction::PtrToInt
: return bitc::CAST_PTRTOINT
;
592 case Instruction::IntToPtr
: return bitc::CAST_INTTOPTR
;
593 case Instruction::BitCast
: return bitc::CAST_BITCAST
;
594 case Instruction::AddrSpaceCast
: return bitc::CAST_ADDRSPACECAST
;
598 static unsigned getEncodedUnaryOpcode(unsigned Opcode
) {
600 default: llvm_unreachable("Unknown binary instruction!");
601 case Instruction::FNeg
: return bitc::UNOP_FNEG
;
605 static unsigned getEncodedBinaryOpcode(unsigned Opcode
) {
607 default: llvm_unreachable("Unknown binary instruction!");
608 case Instruction::Add
:
609 case Instruction::FAdd
: return bitc::BINOP_ADD
;
610 case Instruction::Sub
:
611 case Instruction::FSub
: return bitc::BINOP_SUB
;
612 case Instruction::Mul
:
613 case Instruction::FMul
: return bitc::BINOP_MUL
;
614 case Instruction::UDiv
: return bitc::BINOP_UDIV
;
615 case Instruction::FDiv
:
616 case Instruction::SDiv
: return bitc::BINOP_SDIV
;
617 case Instruction::URem
: return bitc::BINOP_UREM
;
618 case Instruction::FRem
:
619 case Instruction::SRem
: return bitc::BINOP_SREM
;
620 case Instruction::Shl
: return bitc::BINOP_SHL
;
621 case Instruction::LShr
: return bitc::BINOP_LSHR
;
622 case Instruction::AShr
: return bitc::BINOP_ASHR
;
623 case Instruction::And
: return bitc::BINOP_AND
;
624 case Instruction::Or
: return bitc::BINOP_OR
;
625 case Instruction::Xor
: return bitc::BINOP_XOR
;
629 static unsigned getEncodedRMWOperation(AtomicRMWInst::BinOp Op
) {
631 default: llvm_unreachable("Unknown RMW operation!");
632 case AtomicRMWInst::Xchg
: return bitc::RMW_XCHG
;
633 case AtomicRMWInst::Add
: return bitc::RMW_ADD
;
634 case AtomicRMWInst::Sub
: return bitc::RMW_SUB
;
635 case AtomicRMWInst::And
: return bitc::RMW_AND
;
636 case AtomicRMWInst::Nand
: return bitc::RMW_NAND
;
637 case AtomicRMWInst::Or
: return bitc::RMW_OR
;
638 case AtomicRMWInst::Xor
: return bitc::RMW_XOR
;
639 case AtomicRMWInst::Max
: return bitc::RMW_MAX
;
640 case AtomicRMWInst::Min
: return bitc::RMW_MIN
;
641 case AtomicRMWInst::UMax
: return bitc::RMW_UMAX
;
642 case AtomicRMWInst::UMin
: return bitc::RMW_UMIN
;
643 case AtomicRMWInst::FAdd
: return bitc::RMW_FADD
;
644 case AtomicRMWInst::FSub
: return bitc::RMW_FSUB
;
645 case AtomicRMWInst::FMax
: return bitc::RMW_FMAX
;
646 case AtomicRMWInst::FMin
: return bitc::RMW_FMIN
;
647 case AtomicRMWInst::UIncWrap
:
648 return bitc::RMW_UINC_WRAP
;
649 case AtomicRMWInst::UDecWrap
:
650 return bitc::RMW_UDEC_WRAP
;
654 static unsigned getEncodedOrdering(AtomicOrdering Ordering
) {
656 case AtomicOrdering::NotAtomic
: return bitc::ORDERING_NOTATOMIC
;
657 case AtomicOrdering::Unordered
: return bitc::ORDERING_UNORDERED
;
658 case AtomicOrdering::Monotonic
: return bitc::ORDERING_MONOTONIC
;
659 case AtomicOrdering::Acquire
: return bitc::ORDERING_ACQUIRE
;
660 case AtomicOrdering::Release
: return bitc::ORDERING_RELEASE
;
661 case AtomicOrdering::AcquireRelease
: return bitc::ORDERING_ACQREL
;
662 case AtomicOrdering::SequentiallyConsistent
: return bitc::ORDERING_SEQCST
;
664 llvm_unreachable("Invalid ordering");
667 static void writeStringRecord(BitstreamWriter
&Stream
, unsigned Code
,
668 StringRef Str
, unsigned AbbrevToUse
) {
669 SmallVector
<unsigned, 64> Vals
;
671 // Code: [strchar x N]
673 if (AbbrevToUse
&& !BitCodeAbbrevOp::isChar6(C
))
678 // Emit the finished record.
679 Stream
.EmitRecord(Code
, Vals
, AbbrevToUse
);
682 static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind
) {
684 case Attribute::Alignment
:
685 return bitc::ATTR_KIND_ALIGNMENT
;
686 case Attribute::AllocAlign
:
687 return bitc::ATTR_KIND_ALLOC_ALIGN
;
688 case Attribute::AllocSize
:
689 return bitc::ATTR_KIND_ALLOC_SIZE
;
690 case Attribute::AlwaysInline
:
691 return bitc::ATTR_KIND_ALWAYS_INLINE
;
692 case Attribute::Builtin
:
693 return bitc::ATTR_KIND_BUILTIN
;
694 case Attribute::ByVal
:
695 return bitc::ATTR_KIND_BY_VAL
;
696 case Attribute::Convergent
:
697 return bitc::ATTR_KIND_CONVERGENT
;
698 case Attribute::InAlloca
:
699 return bitc::ATTR_KIND_IN_ALLOCA
;
700 case Attribute::Cold
:
701 return bitc::ATTR_KIND_COLD
;
702 case Attribute::DisableSanitizerInstrumentation
:
703 return bitc::ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION
;
704 case Attribute::FnRetThunkExtern
:
705 return bitc::ATTR_KIND_FNRETTHUNK_EXTERN
;
707 return bitc::ATTR_KIND_HOT
;
708 case Attribute::ElementType
:
709 return bitc::ATTR_KIND_ELEMENTTYPE
;
710 case Attribute::InlineHint
:
711 return bitc::ATTR_KIND_INLINE_HINT
;
712 case Attribute::InReg
:
713 return bitc::ATTR_KIND_IN_REG
;
714 case Attribute::JumpTable
:
715 return bitc::ATTR_KIND_JUMP_TABLE
;
716 case Attribute::MinSize
:
717 return bitc::ATTR_KIND_MIN_SIZE
;
718 case Attribute::AllocatedPointer
:
719 return bitc::ATTR_KIND_ALLOCATED_POINTER
;
720 case Attribute::AllocKind
:
721 return bitc::ATTR_KIND_ALLOC_KIND
;
722 case Attribute::Memory
:
723 return bitc::ATTR_KIND_MEMORY
;
724 case Attribute::NoFPClass
:
725 return bitc::ATTR_KIND_NOFPCLASS
;
726 case Attribute::Naked
:
727 return bitc::ATTR_KIND_NAKED
;
728 case Attribute::Nest
:
729 return bitc::ATTR_KIND_NEST
;
730 case Attribute::NoAlias
:
731 return bitc::ATTR_KIND_NO_ALIAS
;
732 case Attribute::NoBuiltin
:
733 return bitc::ATTR_KIND_NO_BUILTIN
;
734 case Attribute::NoCallback
:
735 return bitc::ATTR_KIND_NO_CALLBACK
;
736 case Attribute::NoCapture
:
737 return bitc::ATTR_KIND_NO_CAPTURE
;
738 case Attribute::NoDuplicate
:
739 return bitc::ATTR_KIND_NO_DUPLICATE
;
740 case Attribute::NoFree
:
741 return bitc::ATTR_KIND_NOFREE
;
742 case Attribute::NoImplicitFloat
:
743 return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT
;
744 case Attribute::NoInline
:
745 return bitc::ATTR_KIND_NO_INLINE
;
746 case Attribute::NoRecurse
:
747 return bitc::ATTR_KIND_NO_RECURSE
;
748 case Attribute::NoMerge
:
749 return bitc::ATTR_KIND_NO_MERGE
;
750 case Attribute::NonLazyBind
:
751 return bitc::ATTR_KIND_NON_LAZY_BIND
;
752 case Attribute::NonNull
:
753 return bitc::ATTR_KIND_NON_NULL
;
754 case Attribute::Dereferenceable
:
755 return bitc::ATTR_KIND_DEREFERENCEABLE
;
756 case Attribute::DereferenceableOrNull
:
757 return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL
;
758 case Attribute::NoRedZone
:
759 return bitc::ATTR_KIND_NO_RED_ZONE
;
760 case Attribute::NoReturn
:
761 return bitc::ATTR_KIND_NO_RETURN
;
762 case Attribute::NoSync
:
763 return bitc::ATTR_KIND_NOSYNC
;
764 case Attribute::NoCfCheck
:
765 return bitc::ATTR_KIND_NOCF_CHECK
;
766 case Attribute::NoProfile
:
767 return bitc::ATTR_KIND_NO_PROFILE
;
768 case Attribute::SkipProfile
:
769 return bitc::ATTR_KIND_SKIP_PROFILE
;
770 case Attribute::NoUnwind
:
771 return bitc::ATTR_KIND_NO_UNWIND
;
772 case Attribute::NoSanitizeBounds
:
773 return bitc::ATTR_KIND_NO_SANITIZE_BOUNDS
;
774 case Attribute::NoSanitizeCoverage
:
775 return bitc::ATTR_KIND_NO_SANITIZE_COVERAGE
;
776 case Attribute::NullPointerIsValid
:
777 return bitc::ATTR_KIND_NULL_POINTER_IS_VALID
;
778 case Attribute::OptimizeForDebugging
:
779 return bitc::ATTR_KIND_OPTIMIZE_FOR_DEBUGGING
;
780 case Attribute::OptForFuzzing
:
781 return bitc::ATTR_KIND_OPT_FOR_FUZZING
;
782 case Attribute::OptimizeForSize
:
783 return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE
;
784 case Attribute::OptimizeNone
:
785 return bitc::ATTR_KIND_OPTIMIZE_NONE
;
786 case Attribute::ReadNone
:
787 return bitc::ATTR_KIND_READ_NONE
;
788 case Attribute::ReadOnly
:
789 return bitc::ATTR_KIND_READ_ONLY
;
790 case Attribute::Returned
:
791 return bitc::ATTR_KIND_RETURNED
;
792 case Attribute::ReturnsTwice
:
793 return bitc::ATTR_KIND_RETURNS_TWICE
;
794 case Attribute::SExt
:
795 return bitc::ATTR_KIND_S_EXT
;
796 case Attribute::Speculatable
:
797 return bitc::ATTR_KIND_SPECULATABLE
;
798 case Attribute::StackAlignment
:
799 return bitc::ATTR_KIND_STACK_ALIGNMENT
;
800 case Attribute::StackProtect
:
801 return bitc::ATTR_KIND_STACK_PROTECT
;
802 case Attribute::StackProtectReq
:
803 return bitc::ATTR_KIND_STACK_PROTECT_REQ
;
804 case Attribute::StackProtectStrong
:
805 return bitc::ATTR_KIND_STACK_PROTECT_STRONG
;
806 case Attribute::SafeStack
:
807 return bitc::ATTR_KIND_SAFESTACK
;
808 case Attribute::ShadowCallStack
:
809 return bitc::ATTR_KIND_SHADOWCALLSTACK
;
810 case Attribute::StrictFP
:
811 return bitc::ATTR_KIND_STRICT_FP
;
812 case Attribute::StructRet
:
813 return bitc::ATTR_KIND_STRUCT_RET
;
814 case Attribute::SanitizeAddress
:
815 return bitc::ATTR_KIND_SANITIZE_ADDRESS
;
816 case Attribute::SanitizeHWAddress
:
817 return bitc::ATTR_KIND_SANITIZE_HWADDRESS
;
818 case Attribute::SanitizeThread
:
819 return bitc::ATTR_KIND_SANITIZE_THREAD
;
820 case Attribute::SanitizeMemory
:
821 return bitc::ATTR_KIND_SANITIZE_MEMORY
;
822 case Attribute::SpeculativeLoadHardening
:
823 return bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING
;
824 case Attribute::SwiftError
:
825 return bitc::ATTR_KIND_SWIFT_ERROR
;
826 case Attribute::SwiftSelf
:
827 return bitc::ATTR_KIND_SWIFT_SELF
;
828 case Attribute::SwiftAsync
:
829 return bitc::ATTR_KIND_SWIFT_ASYNC
;
830 case Attribute::UWTable
:
831 return bitc::ATTR_KIND_UW_TABLE
;
832 case Attribute::VScaleRange
:
833 return bitc::ATTR_KIND_VSCALE_RANGE
;
834 case Attribute::WillReturn
:
835 return bitc::ATTR_KIND_WILLRETURN
;
836 case Attribute::WriteOnly
:
837 return bitc::ATTR_KIND_WRITEONLY
;
838 case Attribute::ZExt
:
839 return bitc::ATTR_KIND_Z_EXT
;
840 case Attribute::ImmArg
:
841 return bitc::ATTR_KIND_IMMARG
;
842 case Attribute::SanitizeMemTag
:
843 return bitc::ATTR_KIND_SANITIZE_MEMTAG
;
844 case Attribute::Preallocated
:
845 return bitc::ATTR_KIND_PREALLOCATED
;
846 case Attribute::NoUndef
:
847 return bitc::ATTR_KIND_NOUNDEF
;
848 case Attribute::ByRef
:
849 return bitc::ATTR_KIND_BYREF
;
850 case Attribute::MustProgress
:
851 return bitc::ATTR_KIND_MUSTPROGRESS
;
852 case Attribute::PresplitCoroutine
:
853 return bitc::ATTR_KIND_PRESPLIT_COROUTINE
;
854 case Attribute::Writable
:
855 return bitc::ATTR_KIND_WRITABLE
;
856 case Attribute::CoroDestroyOnlyWhenComplete
:
857 return bitc::ATTR_KIND_CORO_ONLY_DESTROY_WHEN_COMPLETE
;
858 case Attribute::DeadOnUnwind
:
859 return bitc::ATTR_KIND_DEAD_ON_UNWIND
;
860 case Attribute::Range
:
861 return bitc::ATTR_KIND_RANGE
;
862 case Attribute::EndAttrKinds
:
863 llvm_unreachable("Can not encode end-attribute kinds marker.");
864 case Attribute::None
:
865 llvm_unreachable("Can not encode none-attribute.");
866 case Attribute::EmptyKey
:
867 case Attribute::TombstoneKey
:
868 llvm_unreachable("Trying to encode EmptyKey/TombstoneKey");
871 llvm_unreachable("Trying to encode unknown attribute");
874 static void emitSignedInt64(SmallVectorImpl
<uint64_t> &Vals
, uint64_t V
) {
876 Vals
.push_back(V
<< 1);
878 Vals
.push_back((-V
<< 1) | 1);
881 static void emitWideAPInt(SmallVectorImpl
<uint64_t> &Vals
, const APInt
&A
) {
882 // We have an arbitrary precision integer value to write whose
883 // bit width is > 64. However, in canonical unsigned integer
884 // format it is likely that the high bits are going to be zero.
885 // So, we only write the number of active words.
886 unsigned NumWords
= A
.getActiveWords();
887 const uint64_t *RawData
= A
.getRawData();
888 for (unsigned i
= 0; i
< NumWords
; i
++)
889 emitSignedInt64(Vals
, RawData
[i
]);
892 static void emitConstantRange(SmallVectorImpl
<uint64_t> &Record
,
893 const ConstantRange
&CR
) {
894 unsigned BitWidth
= CR
.getBitWidth();
895 Record
.push_back(BitWidth
);
897 Record
.push_back(CR
.getLower().getActiveWords() |
898 (uint64_t(CR
.getUpper().getActiveWords()) << 32));
899 emitWideAPInt(Record
, CR
.getLower());
900 emitWideAPInt(Record
, CR
.getUpper());
902 emitSignedInt64(Record
, CR
.getLower().getSExtValue());
903 emitSignedInt64(Record
, CR
.getUpper().getSExtValue());
907 void ModuleBitcodeWriter::writeAttributeGroupTable() {
908 const std::vector
<ValueEnumerator::IndexAndAttrSet
> &AttrGrps
=
909 VE
.getAttributeGroups();
910 if (AttrGrps
.empty()) return;
912 Stream
.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID
, 3);
914 SmallVector
<uint64_t, 64> Record
;
915 for (ValueEnumerator::IndexAndAttrSet Pair
: AttrGrps
) {
916 unsigned AttrListIndex
= Pair
.first
;
917 AttributeSet AS
= Pair
.second
;
918 Record
.push_back(VE
.getAttributeGroupID(Pair
));
919 Record
.push_back(AttrListIndex
);
921 for (Attribute Attr
: AS
) {
922 if (Attr
.isEnumAttribute()) {
924 Record
.push_back(getAttrKindEncoding(Attr
.getKindAsEnum()));
925 } else if (Attr
.isIntAttribute()) {
927 Record
.push_back(getAttrKindEncoding(Attr
.getKindAsEnum()));
928 Record
.push_back(Attr
.getValueAsInt());
929 } else if (Attr
.isStringAttribute()) {
930 StringRef Kind
= Attr
.getKindAsString();
931 StringRef Val
= Attr
.getValueAsString();
933 Record
.push_back(Val
.empty() ? 3 : 4);
934 Record
.append(Kind
.begin(), Kind
.end());
937 Record
.append(Val
.begin(), Val
.end());
940 } else if (Attr
.isTypeAttribute()) {
941 Type
*Ty
= Attr
.getValueAsType();
942 Record
.push_back(Ty
? 6 : 5);
943 Record
.push_back(getAttrKindEncoding(Attr
.getKindAsEnum()));
945 Record
.push_back(VE
.getTypeID(Attr
.getValueAsType()));
947 assert(Attr
.isConstantRangeAttribute());
949 Record
.push_back(getAttrKindEncoding(Attr
.getKindAsEnum()));
950 emitConstantRange(Record
, Attr
.getValueAsConstantRange());
954 Stream
.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY
, Record
);
961 void ModuleBitcodeWriter::writeAttributeTable() {
962 const std::vector
<AttributeList
> &Attrs
= VE
.getAttributeLists();
963 if (Attrs
.empty()) return;
965 Stream
.EnterSubblock(bitc::PARAMATTR_BLOCK_ID
, 3);
967 SmallVector
<uint64_t, 64> Record
;
968 for (const AttributeList
&AL
: Attrs
) {
969 for (unsigned i
: AL
.indexes()) {
970 AttributeSet AS
= AL
.getAttributes(i
);
971 if (AS
.hasAttributes())
972 Record
.push_back(VE
.getAttributeGroupID({i
, AS
}));
975 Stream
.EmitRecord(bitc::PARAMATTR_CODE_ENTRY
, Record
);
982 /// WriteTypeTable - Write out the type table for a module.
983 void ModuleBitcodeWriter::writeTypeTable() {
984 const ValueEnumerator::TypeList
&TypeList
= VE
.getTypes();
986 Stream
.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW
, 4 /*count from # abbrevs */);
987 SmallVector
<uint64_t, 64> TypeVals
;
989 uint64_t NumBits
= VE
.computeBitsRequiredForTypeIndicies();
991 // Abbrev for TYPE_CODE_OPAQUE_POINTER.
992 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
993 Abbv
->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_OPAQUE_POINTER
));
994 Abbv
->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
995 unsigned OpaquePtrAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
997 // Abbrev for TYPE_CODE_FUNCTION.
998 Abbv
= std::make_shared
<BitCodeAbbrev
>();
999 Abbv
->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION
));
1000 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 1)); // isvararg
1001 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
1002 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, NumBits
));
1003 unsigned FunctionAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
1005 // Abbrev for TYPE_CODE_STRUCT_ANON.
1006 Abbv
= std::make_shared
<BitCodeAbbrev
>();
1007 Abbv
->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON
));
1008 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 1)); // ispacked
1009 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
1010 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, NumBits
));
1011 unsigned StructAnonAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
1013 // Abbrev for TYPE_CODE_STRUCT_NAME.
1014 Abbv
= std::make_shared
<BitCodeAbbrev
>();
1015 Abbv
->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME
));
1016 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
1017 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6
));
1018 unsigned StructNameAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
1020 // Abbrev for TYPE_CODE_STRUCT_NAMED.
1021 Abbv
= std::make_shared
<BitCodeAbbrev
>();
1022 Abbv
->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED
));
1023 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 1)); // ispacked
1024 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
1025 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, NumBits
));
1026 unsigned StructNamedAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
1028 // Abbrev for TYPE_CODE_ARRAY.
1029 Abbv
= std::make_shared
<BitCodeAbbrev
>();
1030 Abbv
->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY
));
1031 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // size
1032 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, NumBits
));
1033 unsigned ArrayAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
1035 // Emit an entry count so the reader can reserve space.
1036 TypeVals
.push_back(TypeList
.size());
1037 Stream
.EmitRecord(bitc::TYPE_CODE_NUMENTRY
, TypeVals
);
1040 // Loop over all of the types, emitting each in turn.
1041 for (Type
*T
: TypeList
) {
1042 int AbbrevToUse
= 0;
1045 switch (T
->getTypeID()) {
1046 case Type::VoidTyID
: Code
= bitc::TYPE_CODE_VOID
; break;
1047 case Type::HalfTyID
: Code
= bitc::TYPE_CODE_HALF
; break;
1048 case Type::BFloatTyID
: Code
= bitc::TYPE_CODE_BFLOAT
; break;
1049 case Type::FloatTyID
: Code
= bitc::TYPE_CODE_FLOAT
; break;
1050 case Type::DoubleTyID
: Code
= bitc::TYPE_CODE_DOUBLE
; break;
1051 case Type::X86_FP80TyID
: Code
= bitc::TYPE_CODE_X86_FP80
; break;
1052 case Type::FP128TyID
: Code
= bitc::TYPE_CODE_FP128
; break;
1053 case Type::PPC_FP128TyID
: Code
= bitc::TYPE_CODE_PPC_FP128
; break;
1054 case Type::LabelTyID
: Code
= bitc::TYPE_CODE_LABEL
; break;
1055 case Type::MetadataTyID
: Code
= bitc::TYPE_CODE_METADATA
; break;
1056 case Type::X86_MMXTyID
: Code
= bitc::TYPE_CODE_X86_MMX
; break;
1057 case Type::X86_AMXTyID
: Code
= bitc::TYPE_CODE_X86_AMX
; break;
1058 case Type::TokenTyID
: Code
= bitc::TYPE_CODE_TOKEN
; break;
1059 case Type::IntegerTyID
:
1061 Code
= bitc::TYPE_CODE_INTEGER
;
1062 TypeVals
.push_back(cast
<IntegerType
>(T
)->getBitWidth());
1064 case Type::PointerTyID
: {
1065 PointerType
*PTy
= cast
<PointerType
>(T
);
1066 unsigned AddressSpace
= PTy
->getAddressSpace();
1067 // OPAQUE_POINTER: [address space]
1068 Code
= bitc::TYPE_CODE_OPAQUE_POINTER
;
1069 TypeVals
.push_back(AddressSpace
);
1070 if (AddressSpace
== 0)
1071 AbbrevToUse
= OpaquePtrAbbrev
;
1074 case Type::FunctionTyID
: {
1075 FunctionType
*FT
= cast
<FunctionType
>(T
);
1076 // FUNCTION: [isvararg, retty, paramty x N]
1077 Code
= bitc::TYPE_CODE_FUNCTION
;
1078 TypeVals
.push_back(FT
->isVarArg());
1079 TypeVals
.push_back(VE
.getTypeID(FT
->getReturnType()));
1080 for (unsigned i
= 0, e
= FT
->getNumParams(); i
!= e
; ++i
)
1081 TypeVals
.push_back(VE
.getTypeID(FT
->getParamType(i
)));
1082 AbbrevToUse
= FunctionAbbrev
;
1085 case Type::StructTyID
: {
1086 StructType
*ST
= cast
<StructType
>(T
);
1087 // STRUCT: [ispacked, eltty x N]
1088 TypeVals
.push_back(ST
->isPacked());
1089 // Output all of the element types.
1090 for (Type
*ET
: ST
->elements())
1091 TypeVals
.push_back(VE
.getTypeID(ET
));
1093 if (ST
->isLiteral()) {
1094 Code
= bitc::TYPE_CODE_STRUCT_ANON
;
1095 AbbrevToUse
= StructAnonAbbrev
;
1097 if (ST
->isOpaque()) {
1098 Code
= bitc::TYPE_CODE_OPAQUE
;
1100 Code
= bitc::TYPE_CODE_STRUCT_NAMED
;
1101 AbbrevToUse
= StructNamedAbbrev
;
1104 // Emit the name if it is present.
1105 if (!ST
->getName().empty())
1106 writeStringRecord(Stream
, bitc::TYPE_CODE_STRUCT_NAME
, ST
->getName(),
1111 case Type::ArrayTyID
: {
1112 ArrayType
*AT
= cast
<ArrayType
>(T
);
1113 // ARRAY: [numelts, eltty]
1114 Code
= bitc::TYPE_CODE_ARRAY
;
1115 TypeVals
.push_back(AT
->getNumElements());
1116 TypeVals
.push_back(VE
.getTypeID(AT
->getElementType()));
1117 AbbrevToUse
= ArrayAbbrev
;
1120 case Type::FixedVectorTyID
:
1121 case Type::ScalableVectorTyID
: {
1122 VectorType
*VT
= cast
<VectorType
>(T
);
1123 // VECTOR [numelts, eltty] or
1124 // [numelts, eltty, scalable]
1125 Code
= bitc::TYPE_CODE_VECTOR
;
1126 TypeVals
.push_back(VT
->getElementCount().getKnownMinValue());
1127 TypeVals
.push_back(VE
.getTypeID(VT
->getElementType()));
1128 if (isa
<ScalableVectorType
>(VT
))
1129 TypeVals
.push_back(true);
1132 case Type::TargetExtTyID
: {
1133 TargetExtType
*TET
= cast
<TargetExtType
>(T
);
1134 Code
= bitc::TYPE_CODE_TARGET_TYPE
;
1135 writeStringRecord(Stream
, bitc::TYPE_CODE_STRUCT_NAME
, TET
->getName(),
1137 TypeVals
.push_back(TET
->getNumTypeParameters());
1138 for (Type
*InnerTy
: TET
->type_params())
1139 TypeVals
.push_back(VE
.getTypeID(InnerTy
));
1140 for (unsigned IntParam
: TET
->int_params())
1141 TypeVals
.push_back(IntParam
);
1144 case Type::TypedPointerTyID
:
1145 llvm_unreachable("Typed pointers cannot be added to IR modules");
1148 // Emit the finished record.
1149 Stream
.EmitRecord(Code
, TypeVals
, AbbrevToUse
);
1156 static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage
) {
1158 case GlobalValue::ExternalLinkage
:
1160 case GlobalValue::WeakAnyLinkage
:
1162 case GlobalValue::AppendingLinkage
:
1164 case GlobalValue::InternalLinkage
:
1166 case GlobalValue::LinkOnceAnyLinkage
:
1168 case GlobalValue::ExternalWeakLinkage
:
1170 case GlobalValue::CommonLinkage
:
1172 case GlobalValue::PrivateLinkage
:
1174 case GlobalValue::WeakODRLinkage
:
1176 case GlobalValue::LinkOnceODRLinkage
:
1178 case GlobalValue::AvailableExternallyLinkage
:
1181 llvm_unreachable("Invalid linkage");
1184 static unsigned getEncodedLinkage(const GlobalValue
&GV
) {
1185 return getEncodedLinkage(GV
.getLinkage());
1188 static uint64_t getEncodedFFlags(FunctionSummary::FFlags Flags
) {
1189 uint64_t RawFlags
= 0;
1190 RawFlags
|= Flags
.ReadNone
;
1191 RawFlags
|= (Flags
.ReadOnly
<< 1);
1192 RawFlags
|= (Flags
.NoRecurse
<< 2);
1193 RawFlags
|= (Flags
.ReturnDoesNotAlias
<< 3);
1194 RawFlags
|= (Flags
.NoInline
<< 4);
1195 RawFlags
|= (Flags
.AlwaysInline
<< 5);
1196 RawFlags
|= (Flags
.NoUnwind
<< 6);
1197 RawFlags
|= (Flags
.MayThrow
<< 7);
1198 RawFlags
|= (Flags
.HasUnknownCall
<< 8);
1199 RawFlags
|= (Flags
.MustBeUnreachable
<< 9);
1203 // Decode the flags for GlobalValue in the summary. See getDecodedGVSummaryFlags
1204 // in BitcodeReader.cpp.
1205 static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags
) {
1206 uint64_t RawFlags
= 0;
1208 RawFlags
|= Flags
.NotEligibleToImport
; // bool
1209 RawFlags
|= (Flags
.Live
<< 1);
1210 RawFlags
|= (Flags
.DSOLocal
<< 2);
1211 RawFlags
|= (Flags
.CanAutoHide
<< 3);
1213 // Linkage don't need to be remapped at that time for the summary. Any future
1214 // change to the getEncodedLinkage() function will need to be taken into
1215 // account here as well.
1216 RawFlags
= (RawFlags
<< 4) | Flags
.Linkage
; // 4 bits
1218 RawFlags
|= (Flags
.Visibility
<< 8); // 2 bits
1220 RawFlags
|= (Flags
.ImportType
<< 10); // 1 bit
1225 static uint64_t getEncodedGVarFlags(GlobalVarSummary::GVarFlags Flags
) {
1226 uint64_t RawFlags
= Flags
.MaybeReadOnly
| (Flags
.MaybeWriteOnly
<< 1) |
1227 (Flags
.Constant
<< 2) | Flags
.VCallVisibility
<< 3;
1231 static uint64_t getEncodedHotnessCallEdgeInfo(const CalleeInfo
&CI
) {
1232 uint64_t RawFlags
= 0;
1234 RawFlags
|= CI
.Hotness
; // 3 bits
1235 RawFlags
|= (CI
.HasTailCall
<< 3); // 1 bit
1240 static uint64_t getEncodedRelBFCallEdgeInfo(const CalleeInfo
&CI
) {
1241 uint64_t RawFlags
= 0;
1243 RawFlags
|= CI
.RelBlockFreq
; // CalleeInfo::RelBlockFreqBits bits
1244 RawFlags
|= (CI
.HasTailCall
<< CalleeInfo::RelBlockFreqBits
); // 1 bit
1249 static unsigned getEncodedVisibility(const GlobalValue
&GV
) {
1250 switch (GV
.getVisibility()) {
1251 case GlobalValue::DefaultVisibility
: return 0;
1252 case GlobalValue::HiddenVisibility
: return 1;
1253 case GlobalValue::ProtectedVisibility
: return 2;
1255 llvm_unreachable("Invalid visibility");
1258 static unsigned getEncodedDLLStorageClass(const GlobalValue
&GV
) {
1259 switch (GV
.getDLLStorageClass()) {
1260 case GlobalValue::DefaultStorageClass
: return 0;
1261 case GlobalValue::DLLImportStorageClass
: return 1;
1262 case GlobalValue::DLLExportStorageClass
: return 2;
1264 llvm_unreachable("Invalid DLL storage class");
1267 static unsigned getEncodedThreadLocalMode(const GlobalValue
&GV
) {
1268 switch (GV
.getThreadLocalMode()) {
1269 case GlobalVariable::NotThreadLocal
: return 0;
1270 case GlobalVariable::GeneralDynamicTLSModel
: return 1;
1271 case GlobalVariable::LocalDynamicTLSModel
: return 2;
1272 case GlobalVariable::InitialExecTLSModel
: return 3;
1273 case GlobalVariable::LocalExecTLSModel
: return 4;
1275 llvm_unreachable("Invalid TLS model");
1278 static unsigned getEncodedComdatSelectionKind(const Comdat
&C
) {
1279 switch (C
.getSelectionKind()) {
1281 return bitc::COMDAT_SELECTION_KIND_ANY
;
1282 case Comdat::ExactMatch
:
1283 return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH
;
1284 case Comdat::Largest
:
1285 return bitc::COMDAT_SELECTION_KIND_LARGEST
;
1286 case Comdat::NoDeduplicate
:
1287 return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES
;
1288 case Comdat::SameSize
:
1289 return bitc::COMDAT_SELECTION_KIND_SAME_SIZE
;
1291 llvm_unreachable("Invalid selection kind");
1294 static unsigned getEncodedUnnamedAddr(const GlobalValue
&GV
) {
1295 switch (GV
.getUnnamedAddr()) {
1296 case GlobalValue::UnnamedAddr::None
: return 0;
1297 case GlobalValue::UnnamedAddr::Local
: return 2;
1298 case GlobalValue::UnnamedAddr::Global
: return 1;
1300 llvm_unreachable("Invalid unnamed_addr");
1303 size_t ModuleBitcodeWriter::addToStrtab(StringRef Str
) {
1306 return StrtabBuilder
.add(Str
);
1309 void ModuleBitcodeWriter::writeComdats() {
1310 SmallVector
<unsigned, 64> Vals
;
1311 for (const Comdat
*C
: VE
.getComdats()) {
1312 // COMDAT: [strtab offset, strtab size, selection_kind]
1313 Vals
.push_back(addToStrtab(C
->getName()));
1314 Vals
.push_back(C
->getName().size());
1315 Vals
.push_back(getEncodedComdatSelectionKind(*C
));
1316 Stream
.EmitRecord(bitc::MODULE_CODE_COMDAT
, Vals
, /*AbbrevToUse=*/0);
1321 /// Write a record that will eventually hold the word offset of the
1322 /// module-level VST. For now the offset is 0, which will be backpatched
1323 /// after the real VST is written. Saves the bit offset to backpatch.
1324 void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
1325 // Write a placeholder value in for the offset of the real VST,
1326 // which is written after the function blocks so that it can include
1327 // the offset of each function. The placeholder offset will be
1328 // updated when the real VST is written.
1329 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
1330 Abbv
->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET
));
1331 // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
1332 // hold the real VST offset. Must use fixed instead of VBR as we don't
1333 // know how many VBR chunks to reserve ahead of time.
1334 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 32));
1335 unsigned VSTOffsetAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
1337 // Emit the placeholder
1338 uint64_t Vals
[] = {bitc::MODULE_CODE_VSTOFFSET
, 0};
1339 Stream
.EmitRecordWithAbbrev(VSTOffsetAbbrev
, Vals
);
1341 // Compute and save the bit offset to the placeholder, which will be
1342 // patched when the real VST is written. We can simply subtract the 32-bit
1343 // fixed size from the current bit number to get the location to backpatch.
1344 VSTOffsetPlaceholder
= Stream
.GetCurrentBitNo() - 32;
1347 enum StringEncoding
{ SE_Char6
, SE_Fixed7
, SE_Fixed8
};
1349 /// Determine the encoding to use for the given string name and length.
1350 static StringEncoding
getStringEncoding(StringRef Str
) {
1351 bool isChar6
= true;
1352 for (char C
: Str
) {
1354 isChar6
= BitCodeAbbrevOp::isChar6(C
);
1355 if ((unsigned char)C
& 128)
1356 // don't bother scanning the rest.
1364 static_assert(sizeof(GlobalValue::SanitizerMetadata
) <= sizeof(unsigned),
1365 "Sanitizer Metadata is too large for naive serialization.");
1367 serializeSanitizerMetadata(const GlobalValue::SanitizerMetadata
&Meta
) {
1368 return Meta
.NoAddress
| (Meta
.NoHWAddress
<< 1) |
1369 (Meta
.Memtag
<< 2) | (Meta
.IsDynInit
<< 3);
1372 /// Emit top-level description of module, including target triple, inline asm,
1373 /// descriptors for global variables, and function prototype info.
1374 /// Returns the bit offset to backpatch with the location of the real VST.
1375 void ModuleBitcodeWriter::writeModuleInfo() {
1376 // Emit various pieces of data attached to a module.
1377 if (!M
.getTargetTriple().empty())
1378 writeStringRecord(Stream
, bitc::MODULE_CODE_TRIPLE
, M
.getTargetTriple(),
1380 const std::string
&DL
= M
.getDataLayoutStr();
1382 writeStringRecord(Stream
, bitc::MODULE_CODE_DATALAYOUT
, DL
, 0 /*TODO*/);
1383 if (!M
.getModuleInlineAsm().empty())
1384 writeStringRecord(Stream
, bitc::MODULE_CODE_ASM
, M
.getModuleInlineAsm(),
1387 // Emit information about sections and GC, computing how many there are. Also
1388 // compute the maximum alignment value.
1389 std::map
<std::string
, unsigned> SectionMap
;
1390 std::map
<std::string
, unsigned> GCMap
;
1391 MaybeAlign MaxAlignment
;
1392 unsigned MaxGlobalType
= 0;
1393 const auto UpdateMaxAlignment
= [&MaxAlignment
](const MaybeAlign A
) {
1395 MaxAlignment
= !MaxAlignment
? *A
: std::max(*MaxAlignment
, *A
);
1397 for (const GlobalVariable
&GV
: M
.globals()) {
1398 UpdateMaxAlignment(GV
.getAlign());
1399 MaxGlobalType
= std::max(MaxGlobalType
, VE
.getTypeID(GV
.getValueType()));
1400 if (GV
.hasSection()) {
1401 // Give section names unique ID's.
1402 unsigned &Entry
= SectionMap
[std::string(GV
.getSection())];
1404 writeStringRecord(Stream
, bitc::MODULE_CODE_SECTIONNAME
, GV
.getSection(),
1406 Entry
= SectionMap
.size();
1410 for (const Function
&F
: M
) {
1411 UpdateMaxAlignment(F
.getAlign());
1412 if (F
.hasSection()) {
1413 // Give section names unique ID's.
1414 unsigned &Entry
= SectionMap
[std::string(F
.getSection())];
1416 writeStringRecord(Stream
, bitc::MODULE_CODE_SECTIONNAME
, F
.getSection(),
1418 Entry
= SectionMap
.size();
1422 // Same for GC names.
1423 unsigned &Entry
= GCMap
[F
.getGC()];
1425 writeStringRecord(Stream
, bitc::MODULE_CODE_GCNAME
, F
.getGC(),
1427 Entry
= GCMap
.size();
1432 // Emit abbrev for globals, now that we know # sections and max alignment.
1433 unsigned SimpleGVarAbbrev
= 0;
1434 if (!M
.global_empty()) {
1435 // Add an abbrev for common globals with no visibility or thread localness.
1436 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
1437 Abbv
->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR
));
1438 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8));
1439 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8));
1440 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
,
1441 Log2_32_Ceil(MaxGlobalType
+1)));
1442 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6)); // AddrSpace << 2
1443 //| explicitType << 1
1445 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6)); // Initializer.
1446 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 5)); // Linkage.
1447 if (!MaxAlignment
) // Alignment.
1448 Abbv
->Add(BitCodeAbbrevOp(0));
1450 unsigned MaxEncAlignment
= getEncodedAlign(MaxAlignment
);
1451 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
,
1452 Log2_32_Ceil(MaxEncAlignment
+1)));
1454 if (SectionMap
.empty()) // Section.
1455 Abbv
->Add(BitCodeAbbrevOp(0));
1457 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
,
1458 Log2_32_Ceil(SectionMap
.size()+1)));
1459 // Don't bother emitting vis + thread local.
1460 SimpleGVarAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
1463 SmallVector
<unsigned, 64> Vals
;
1464 // Emit the module's source file name.
1466 StringEncoding Bits
= getStringEncoding(M
.getSourceFileName());
1467 BitCodeAbbrevOp AbbrevOpToUse
= BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 8);
1468 if (Bits
== SE_Char6
)
1469 AbbrevOpToUse
= BitCodeAbbrevOp(BitCodeAbbrevOp::Char6
);
1470 else if (Bits
== SE_Fixed7
)
1471 AbbrevOpToUse
= BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 7);
1473 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
1474 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
1475 Abbv
->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME
));
1476 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
1477 Abbv
->Add(AbbrevOpToUse
);
1478 unsigned FilenameAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
1480 for (const auto P
: M
.getSourceFileName())
1481 Vals
.push_back((unsigned char)P
);
1483 // Emit the finished record.
1484 Stream
.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME
, Vals
, FilenameAbbrev
);
1488 // Emit the global variable information.
1489 for (const GlobalVariable
&GV
: M
.globals()) {
1490 unsigned AbbrevToUse
= 0;
1492 // GLOBALVAR: [strtab offset, strtab size, type, isconst, initid,
1493 // linkage, alignment, section, visibility, threadlocal,
1494 // unnamed_addr, externally_initialized, dllstorageclass,
1495 // comdat, attributes, DSO_Local, GlobalSanitizer, code_model]
1496 Vals
.push_back(addToStrtab(GV
.getName()));
1497 Vals
.push_back(GV
.getName().size());
1498 Vals
.push_back(VE
.getTypeID(GV
.getValueType()));
1499 Vals
.push_back(GV
.getType()->getAddressSpace() << 2 | 2 | GV
.isConstant());
1500 Vals
.push_back(GV
.isDeclaration() ? 0 :
1501 (VE
.getValueID(GV
.getInitializer()) + 1));
1502 Vals
.push_back(getEncodedLinkage(GV
));
1503 Vals
.push_back(getEncodedAlign(GV
.getAlign()));
1504 Vals
.push_back(GV
.hasSection() ? SectionMap
[std::string(GV
.getSection())]
1506 if (GV
.isThreadLocal() ||
1507 GV
.getVisibility() != GlobalValue::DefaultVisibility
||
1508 GV
.getUnnamedAddr() != GlobalValue::UnnamedAddr::None
||
1509 GV
.isExternallyInitialized() ||
1510 GV
.getDLLStorageClass() != GlobalValue::DefaultStorageClass
||
1511 GV
.hasComdat() || GV
.hasAttributes() || GV
.isDSOLocal() ||
1512 GV
.hasPartition() || GV
.hasSanitizerMetadata() || GV
.getCodeModel()) {
1513 Vals
.push_back(getEncodedVisibility(GV
));
1514 Vals
.push_back(getEncodedThreadLocalMode(GV
));
1515 Vals
.push_back(getEncodedUnnamedAddr(GV
));
1516 Vals
.push_back(GV
.isExternallyInitialized());
1517 Vals
.push_back(getEncodedDLLStorageClass(GV
));
1518 Vals
.push_back(GV
.hasComdat() ? VE
.getComdatID(GV
.getComdat()) : 0);
1520 auto AL
= GV
.getAttributesAsList(AttributeList::FunctionIndex
);
1521 Vals
.push_back(VE
.getAttributeListID(AL
));
1523 Vals
.push_back(GV
.isDSOLocal());
1524 Vals
.push_back(addToStrtab(GV
.getPartition()));
1525 Vals
.push_back(GV
.getPartition().size());
1527 Vals
.push_back((GV
.hasSanitizerMetadata() ? serializeSanitizerMetadata(
1528 GV
.getSanitizerMetadata())
1530 Vals
.push_back(GV
.getCodeModelRaw());
1532 AbbrevToUse
= SimpleGVarAbbrev
;
1535 Stream
.EmitRecord(bitc::MODULE_CODE_GLOBALVAR
, Vals
, AbbrevToUse
);
1539 // Emit the function proto information.
1540 for (const Function
&F
: M
) {
1541 // FUNCTION: [strtab offset, strtab size, type, callingconv, isproto,
1542 // linkage, paramattrs, alignment, section, visibility, gc,
1543 // unnamed_addr, prologuedata, dllstorageclass, comdat,
1544 // prefixdata, personalityfn, DSO_Local, addrspace]
1545 Vals
.push_back(addToStrtab(F
.getName()));
1546 Vals
.push_back(F
.getName().size());
1547 Vals
.push_back(VE
.getTypeID(F
.getFunctionType()));
1548 Vals
.push_back(F
.getCallingConv());
1549 Vals
.push_back(F
.isDeclaration());
1550 Vals
.push_back(getEncodedLinkage(F
));
1551 Vals
.push_back(VE
.getAttributeListID(F
.getAttributes()));
1552 Vals
.push_back(getEncodedAlign(F
.getAlign()));
1553 Vals
.push_back(F
.hasSection() ? SectionMap
[std::string(F
.getSection())]
1555 Vals
.push_back(getEncodedVisibility(F
));
1556 Vals
.push_back(F
.hasGC() ? GCMap
[F
.getGC()] : 0);
1557 Vals
.push_back(getEncodedUnnamedAddr(F
));
1558 Vals
.push_back(F
.hasPrologueData() ? (VE
.getValueID(F
.getPrologueData()) + 1)
1560 Vals
.push_back(getEncodedDLLStorageClass(F
));
1561 Vals
.push_back(F
.hasComdat() ? VE
.getComdatID(F
.getComdat()) : 0);
1562 Vals
.push_back(F
.hasPrefixData() ? (VE
.getValueID(F
.getPrefixData()) + 1)
1565 F
.hasPersonalityFn() ? (VE
.getValueID(F
.getPersonalityFn()) + 1) : 0);
1567 Vals
.push_back(F
.isDSOLocal());
1568 Vals
.push_back(F
.getAddressSpace());
1569 Vals
.push_back(addToStrtab(F
.getPartition()));
1570 Vals
.push_back(F
.getPartition().size());
1572 unsigned AbbrevToUse
= 0;
1573 Stream
.EmitRecord(bitc::MODULE_CODE_FUNCTION
, Vals
, AbbrevToUse
);
1577 // Emit the alias information.
1578 for (const GlobalAlias
&A
: M
.aliases()) {
1579 // ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage,
1580 // visibility, dllstorageclass, threadlocal, unnamed_addr,
1582 Vals
.push_back(addToStrtab(A
.getName()));
1583 Vals
.push_back(A
.getName().size());
1584 Vals
.push_back(VE
.getTypeID(A
.getValueType()));
1585 Vals
.push_back(A
.getType()->getAddressSpace());
1586 Vals
.push_back(VE
.getValueID(A
.getAliasee()));
1587 Vals
.push_back(getEncodedLinkage(A
));
1588 Vals
.push_back(getEncodedVisibility(A
));
1589 Vals
.push_back(getEncodedDLLStorageClass(A
));
1590 Vals
.push_back(getEncodedThreadLocalMode(A
));
1591 Vals
.push_back(getEncodedUnnamedAddr(A
));
1592 Vals
.push_back(A
.isDSOLocal());
1593 Vals
.push_back(addToStrtab(A
.getPartition()));
1594 Vals
.push_back(A
.getPartition().size());
1596 unsigned AbbrevToUse
= 0;
1597 Stream
.EmitRecord(bitc::MODULE_CODE_ALIAS
, Vals
, AbbrevToUse
);
1601 // Emit the ifunc information.
1602 for (const GlobalIFunc
&I
: M
.ifuncs()) {
1603 // IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver
1604 // val#, linkage, visibility, DSO_Local]
1605 Vals
.push_back(addToStrtab(I
.getName()));
1606 Vals
.push_back(I
.getName().size());
1607 Vals
.push_back(VE
.getTypeID(I
.getValueType()));
1608 Vals
.push_back(I
.getType()->getAddressSpace());
1609 Vals
.push_back(VE
.getValueID(I
.getResolver()));
1610 Vals
.push_back(getEncodedLinkage(I
));
1611 Vals
.push_back(getEncodedVisibility(I
));
1612 Vals
.push_back(I
.isDSOLocal());
1613 Vals
.push_back(addToStrtab(I
.getPartition()));
1614 Vals
.push_back(I
.getPartition().size());
1615 Stream
.EmitRecord(bitc::MODULE_CODE_IFUNC
, Vals
);
1619 writeValueSymbolTableForwardDecl();
1622 static uint64_t getOptimizationFlags(const Value
*V
) {
1625 if (const auto *OBO
= dyn_cast
<OverflowingBinaryOperator
>(V
)) {
1626 if (OBO
->hasNoSignedWrap())
1627 Flags
|= 1 << bitc::OBO_NO_SIGNED_WRAP
;
1628 if (OBO
->hasNoUnsignedWrap())
1629 Flags
|= 1 << bitc::OBO_NO_UNSIGNED_WRAP
;
1630 } else if (const auto *PEO
= dyn_cast
<PossiblyExactOperator
>(V
)) {
1632 Flags
|= 1 << bitc::PEO_EXACT
;
1633 } else if (const auto *PDI
= dyn_cast
<PossiblyDisjointInst
>(V
)) {
1634 if (PDI
->isDisjoint())
1635 Flags
|= 1 << bitc::PDI_DISJOINT
;
1636 } else if (const auto *FPMO
= dyn_cast
<FPMathOperator
>(V
)) {
1637 if (FPMO
->hasAllowReassoc())
1638 Flags
|= bitc::AllowReassoc
;
1639 if (FPMO
->hasNoNaNs())
1640 Flags
|= bitc::NoNaNs
;
1641 if (FPMO
->hasNoInfs())
1642 Flags
|= bitc::NoInfs
;
1643 if (FPMO
->hasNoSignedZeros())
1644 Flags
|= bitc::NoSignedZeros
;
1645 if (FPMO
->hasAllowReciprocal())
1646 Flags
|= bitc::AllowReciprocal
;
1647 if (FPMO
->hasAllowContract())
1648 Flags
|= bitc::AllowContract
;
1649 if (FPMO
->hasApproxFunc())
1650 Flags
|= bitc::ApproxFunc
;
1651 } else if (const auto *NNI
= dyn_cast
<PossiblyNonNegInst
>(V
)) {
1652 if (NNI
->hasNonNeg())
1653 Flags
|= 1 << bitc::PNNI_NON_NEG
;
1654 } else if (const auto *TI
= dyn_cast
<TruncInst
>(V
)) {
1655 if (TI
->hasNoSignedWrap())
1656 Flags
|= 1 << bitc::TIO_NO_SIGNED_WRAP
;
1657 if (TI
->hasNoUnsignedWrap())
1658 Flags
|= 1 << bitc::TIO_NO_UNSIGNED_WRAP
;
1664 void ModuleBitcodeWriter::writeValueAsMetadata(
1665 const ValueAsMetadata
*MD
, SmallVectorImpl
<uint64_t> &Record
) {
1666 // Mimic an MDNode with a value as one operand.
1667 Value
*V
= MD
->getValue();
1668 Record
.push_back(VE
.getTypeID(V
->getType()));
1669 Record
.push_back(VE
.getValueID(V
));
1670 Stream
.EmitRecord(bitc::METADATA_VALUE
, Record
, 0);
1674 void ModuleBitcodeWriter::writeMDTuple(const MDTuple
*N
,
1675 SmallVectorImpl
<uint64_t> &Record
,
1677 for (const MDOperand
&MDO
: N
->operands()) {
1679 assert(!(MD
&& isa
<LocalAsMetadata
>(MD
)) &&
1680 "Unexpected function-local metadata");
1681 Record
.push_back(VE
.getMetadataOrNullID(MD
));
1683 Stream
.EmitRecord(N
->isDistinct() ? bitc::METADATA_DISTINCT_NODE
1684 : bitc::METADATA_NODE
,
1689 unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
1690 // Assume the column is usually under 128, and always output the inlined-at
1691 // location (it's never more expensive than building an array size 1).
1692 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
1693 Abbv
->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION
));
1694 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 1));
1695 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6));
1696 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8));
1697 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6));
1698 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6));
1699 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 1));
1700 return Stream
.EmitAbbrev(std::move(Abbv
));
1703 void ModuleBitcodeWriter::writeDILocation(const DILocation
*N
,
1704 SmallVectorImpl
<uint64_t> &Record
,
1707 Abbrev
= createDILocationAbbrev();
1709 Record
.push_back(N
->isDistinct());
1710 Record
.push_back(N
->getLine());
1711 Record
.push_back(N
->getColumn());
1712 Record
.push_back(VE
.getMetadataID(N
->getScope()));
1713 Record
.push_back(VE
.getMetadataOrNullID(N
->getInlinedAt()));
1714 Record
.push_back(N
->isImplicitCode());
1716 Stream
.EmitRecord(bitc::METADATA_LOCATION
, Record
, Abbrev
);
1720 unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
1721 // Assume the column is usually under 128, and always output the inlined-at
1722 // location (it's never more expensive than building an array size 1).
1723 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
1724 Abbv
->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG
));
1725 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 1));
1726 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6));
1727 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 1));
1728 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6));
1729 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
1730 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6));
1731 return Stream
.EmitAbbrev(std::move(Abbv
));
1734 void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode
*N
,
1735 SmallVectorImpl
<uint64_t> &Record
,
1738 Abbrev
= createGenericDINodeAbbrev();
1740 Record
.push_back(N
->isDistinct());
1741 Record
.push_back(N
->getTag());
1742 Record
.push_back(0); // Per-tag version field; unused for now.
1744 for (auto &I
: N
->operands())
1745 Record
.push_back(VE
.getMetadataOrNullID(I
));
1747 Stream
.EmitRecord(bitc::METADATA_GENERIC_DEBUG
, Record
, Abbrev
);
1751 void ModuleBitcodeWriter::writeDISubrange(const DISubrange
*N
,
1752 SmallVectorImpl
<uint64_t> &Record
,
1754 const uint64_t Version
= 2 << 1;
1755 Record
.push_back((uint64_t)N
->isDistinct() | Version
);
1756 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawCountNode()));
1757 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawLowerBound()));
1758 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawUpperBound()));
1759 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawStride()));
1761 Stream
.EmitRecord(bitc::METADATA_SUBRANGE
, Record
, Abbrev
);
1765 void ModuleBitcodeWriter::writeDIGenericSubrange(
1766 const DIGenericSubrange
*N
, SmallVectorImpl
<uint64_t> &Record
,
1768 Record
.push_back((uint64_t)N
->isDistinct());
1769 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawCountNode()));
1770 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawLowerBound()));
1771 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawUpperBound()));
1772 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawStride()));
1774 Stream
.EmitRecord(bitc::METADATA_GENERIC_SUBRANGE
, Record
, Abbrev
);
1778 void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator
*N
,
1779 SmallVectorImpl
<uint64_t> &Record
,
1781 const uint64_t IsBigInt
= 1 << 2;
1782 Record
.push_back(IsBigInt
| (N
->isUnsigned() << 1) | N
->isDistinct());
1783 Record
.push_back(N
->getValue().getBitWidth());
1784 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawName()));
1785 emitWideAPInt(Record
, N
->getValue());
1787 Stream
.EmitRecord(bitc::METADATA_ENUMERATOR
, Record
, Abbrev
);
1791 void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType
*N
,
1792 SmallVectorImpl
<uint64_t> &Record
,
1794 Record
.push_back(N
->isDistinct());
1795 Record
.push_back(N
->getTag());
1796 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawName()));
1797 Record
.push_back(N
->getSizeInBits());
1798 Record
.push_back(N
->getAlignInBits());
1799 Record
.push_back(N
->getEncoding());
1800 Record
.push_back(N
->getFlags());
1802 Stream
.EmitRecord(bitc::METADATA_BASIC_TYPE
, Record
, Abbrev
);
1806 void ModuleBitcodeWriter::writeDIStringType(const DIStringType
*N
,
1807 SmallVectorImpl
<uint64_t> &Record
,
1809 Record
.push_back(N
->isDistinct());
1810 Record
.push_back(N
->getTag());
1811 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawName()));
1812 Record
.push_back(VE
.getMetadataOrNullID(N
->getStringLength()));
1813 Record
.push_back(VE
.getMetadataOrNullID(N
->getStringLengthExp()));
1814 Record
.push_back(VE
.getMetadataOrNullID(N
->getStringLocationExp()));
1815 Record
.push_back(N
->getSizeInBits());
1816 Record
.push_back(N
->getAlignInBits());
1817 Record
.push_back(N
->getEncoding());
1819 Stream
.EmitRecord(bitc::METADATA_STRING_TYPE
, Record
, Abbrev
);
1823 void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType
*N
,
1824 SmallVectorImpl
<uint64_t> &Record
,
1826 Record
.push_back(N
->isDistinct());
1827 Record
.push_back(N
->getTag());
1828 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawName()));
1829 Record
.push_back(VE
.getMetadataOrNullID(N
->getFile()));
1830 Record
.push_back(N
->getLine());
1831 Record
.push_back(VE
.getMetadataOrNullID(N
->getScope()));
1832 Record
.push_back(VE
.getMetadataOrNullID(N
->getBaseType()));
1833 Record
.push_back(N
->getSizeInBits());
1834 Record
.push_back(N
->getAlignInBits());
1835 Record
.push_back(N
->getOffsetInBits());
1836 Record
.push_back(N
->getFlags());
1837 Record
.push_back(VE
.getMetadataOrNullID(N
->getExtraData()));
1839 // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
1840 // that there is no DWARF address space associated with DIDerivedType.
1841 if (const auto &DWARFAddressSpace
= N
->getDWARFAddressSpace())
1842 Record
.push_back(*DWARFAddressSpace
+ 1);
1844 Record
.push_back(0);
1846 Record
.push_back(VE
.getMetadataOrNullID(N
->getAnnotations().get()));
1848 if (auto PtrAuthData
= N
->getPtrAuthData())
1849 Record
.push_back(PtrAuthData
->RawData
);
1851 Record
.push_back(0);
1853 Stream
.EmitRecord(bitc::METADATA_DERIVED_TYPE
, Record
, Abbrev
);
1857 void ModuleBitcodeWriter::writeDICompositeType(
1858 const DICompositeType
*N
, SmallVectorImpl
<uint64_t> &Record
,
1860 const unsigned IsNotUsedInOldTypeRef
= 0x2;
1861 Record
.push_back(IsNotUsedInOldTypeRef
| (unsigned)N
->isDistinct());
1862 Record
.push_back(N
->getTag());
1863 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawName()));
1864 Record
.push_back(VE
.getMetadataOrNullID(N
->getFile()));
1865 Record
.push_back(N
->getLine());
1866 Record
.push_back(VE
.getMetadataOrNullID(N
->getScope()));
1867 Record
.push_back(VE
.getMetadataOrNullID(N
->getBaseType()));
1868 Record
.push_back(N
->getSizeInBits());
1869 Record
.push_back(N
->getAlignInBits());
1870 Record
.push_back(N
->getOffsetInBits());
1871 Record
.push_back(N
->getFlags());
1872 Record
.push_back(VE
.getMetadataOrNullID(N
->getElements().get()));
1873 Record
.push_back(N
->getRuntimeLang());
1874 Record
.push_back(VE
.getMetadataOrNullID(N
->getVTableHolder()));
1875 Record
.push_back(VE
.getMetadataOrNullID(N
->getTemplateParams().get()));
1876 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawIdentifier()));
1877 Record
.push_back(VE
.getMetadataOrNullID(N
->getDiscriminator()));
1878 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawDataLocation()));
1879 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawAssociated()));
1880 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawAllocated()));
1881 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawRank()));
1882 Record
.push_back(VE
.getMetadataOrNullID(N
->getAnnotations().get()));
1884 Stream
.EmitRecord(bitc::METADATA_COMPOSITE_TYPE
, Record
, Abbrev
);
1888 void ModuleBitcodeWriter::writeDISubroutineType(
1889 const DISubroutineType
*N
, SmallVectorImpl
<uint64_t> &Record
,
1891 const unsigned HasNoOldTypeRefs
= 0x2;
1892 Record
.push_back(HasNoOldTypeRefs
| (unsigned)N
->isDistinct());
1893 Record
.push_back(N
->getFlags());
1894 Record
.push_back(VE
.getMetadataOrNullID(N
->getTypeArray().get()));
1895 Record
.push_back(N
->getCC());
1897 Stream
.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE
, Record
, Abbrev
);
1901 void ModuleBitcodeWriter::writeDIFile(const DIFile
*N
,
1902 SmallVectorImpl
<uint64_t> &Record
,
1904 Record
.push_back(N
->isDistinct());
1905 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawFilename()));
1906 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawDirectory()));
1907 if (N
->getRawChecksum()) {
1908 Record
.push_back(N
->getRawChecksum()->Kind
);
1909 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawChecksum()->Value
));
1911 // Maintain backwards compatibility with the old internal representation of
1912 // CSK_None in ChecksumKind by writing nulls here when Checksum is None.
1913 Record
.push_back(0);
1914 Record
.push_back(VE
.getMetadataOrNullID(nullptr));
1916 auto Source
= N
->getRawSource();
1918 Record
.push_back(VE
.getMetadataOrNullID(Source
));
1920 Stream
.EmitRecord(bitc::METADATA_FILE
, Record
, Abbrev
);
1924 void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit
*N
,
1925 SmallVectorImpl
<uint64_t> &Record
,
1927 assert(N
->isDistinct() && "Expected distinct compile units");
1928 Record
.push_back(/* IsDistinct */ true);
1929 Record
.push_back(N
->getSourceLanguage());
1930 Record
.push_back(VE
.getMetadataOrNullID(N
->getFile()));
1931 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawProducer()));
1932 Record
.push_back(N
->isOptimized());
1933 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawFlags()));
1934 Record
.push_back(N
->getRuntimeVersion());
1935 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawSplitDebugFilename()));
1936 Record
.push_back(N
->getEmissionKind());
1937 Record
.push_back(VE
.getMetadataOrNullID(N
->getEnumTypes().get()));
1938 Record
.push_back(VE
.getMetadataOrNullID(N
->getRetainedTypes().get()));
1939 Record
.push_back(/* subprograms */ 0);
1940 Record
.push_back(VE
.getMetadataOrNullID(N
->getGlobalVariables().get()));
1941 Record
.push_back(VE
.getMetadataOrNullID(N
->getImportedEntities().get()));
1942 Record
.push_back(N
->getDWOId());
1943 Record
.push_back(VE
.getMetadataOrNullID(N
->getMacros().get()));
1944 Record
.push_back(N
->getSplitDebugInlining());
1945 Record
.push_back(N
->getDebugInfoForProfiling());
1946 Record
.push_back((unsigned)N
->getNameTableKind());
1947 Record
.push_back(N
->getRangesBaseAddress());
1948 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawSysRoot()));
1949 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawSDK()));
1951 Stream
.EmitRecord(bitc::METADATA_COMPILE_UNIT
, Record
, Abbrev
);
1955 void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram
*N
,
1956 SmallVectorImpl
<uint64_t> &Record
,
1958 const uint64_t HasUnitFlag
= 1 << 1;
1959 const uint64_t HasSPFlagsFlag
= 1 << 2;
1960 Record
.push_back(uint64_t(N
->isDistinct()) | HasUnitFlag
| HasSPFlagsFlag
);
1961 Record
.push_back(VE
.getMetadataOrNullID(N
->getScope()));
1962 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawName()));
1963 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawLinkageName()));
1964 Record
.push_back(VE
.getMetadataOrNullID(N
->getFile()));
1965 Record
.push_back(N
->getLine());
1966 Record
.push_back(VE
.getMetadataOrNullID(N
->getType()));
1967 Record
.push_back(N
->getScopeLine());
1968 Record
.push_back(VE
.getMetadataOrNullID(N
->getContainingType()));
1969 Record
.push_back(N
->getSPFlags());
1970 Record
.push_back(N
->getVirtualIndex());
1971 Record
.push_back(N
->getFlags());
1972 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawUnit()));
1973 Record
.push_back(VE
.getMetadataOrNullID(N
->getTemplateParams().get()));
1974 Record
.push_back(VE
.getMetadataOrNullID(N
->getDeclaration()));
1975 Record
.push_back(VE
.getMetadataOrNullID(N
->getRetainedNodes().get()));
1976 Record
.push_back(N
->getThisAdjustment());
1977 Record
.push_back(VE
.getMetadataOrNullID(N
->getThrownTypes().get()));
1978 Record
.push_back(VE
.getMetadataOrNullID(N
->getAnnotations().get()));
1979 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawTargetFuncName()));
1981 Stream
.EmitRecord(bitc::METADATA_SUBPROGRAM
, Record
, Abbrev
);
1985 void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock
*N
,
1986 SmallVectorImpl
<uint64_t> &Record
,
1988 Record
.push_back(N
->isDistinct());
1989 Record
.push_back(VE
.getMetadataOrNullID(N
->getScope()));
1990 Record
.push_back(VE
.getMetadataOrNullID(N
->getFile()));
1991 Record
.push_back(N
->getLine());
1992 Record
.push_back(N
->getColumn());
1994 Stream
.EmitRecord(bitc::METADATA_LEXICAL_BLOCK
, Record
, Abbrev
);
1998 void ModuleBitcodeWriter::writeDILexicalBlockFile(
1999 const DILexicalBlockFile
*N
, SmallVectorImpl
<uint64_t> &Record
,
2001 Record
.push_back(N
->isDistinct());
2002 Record
.push_back(VE
.getMetadataOrNullID(N
->getScope()));
2003 Record
.push_back(VE
.getMetadataOrNullID(N
->getFile()));
2004 Record
.push_back(N
->getDiscriminator());
2006 Stream
.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE
, Record
, Abbrev
);
2010 void ModuleBitcodeWriter::writeDICommonBlock(const DICommonBlock
*N
,
2011 SmallVectorImpl
<uint64_t> &Record
,
2013 Record
.push_back(N
->isDistinct());
2014 Record
.push_back(VE
.getMetadataOrNullID(N
->getScope()));
2015 Record
.push_back(VE
.getMetadataOrNullID(N
->getDecl()));
2016 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawName()));
2017 Record
.push_back(VE
.getMetadataOrNullID(N
->getFile()));
2018 Record
.push_back(N
->getLineNo());
2020 Stream
.EmitRecord(bitc::METADATA_COMMON_BLOCK
, Record
, Abbrev
);
2024 void ModuleBitcodeWriter::writeDINamespace(const DINamespace
*N
,
2025 SmallVectorImpl
<uint64_t> &Record
,
2027 Record
.push_back(N
->isDistinct() | N
->getExportSymbols() << 1);
2028 Record
.push_back(VE
.getMetadataOrNullID(N
->getScope()));
2029 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawName()));
2031 Stream
.EmitRecord(bitc::METADATA_NAMESPACE
, Record
, Abbrev
);
2035 void ModuleBitcodeWriter::writeDIMacro(const DIMacro
*N
,
2036 SmallVectorImpl
<uint64_t> &Record
,
2038 Record
.push_back(N
->isDistinct());
2039 Record
.push_back(N
->getMacinfoType());
2040 Record
.push_back(N
->getLine());
2041 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawName()));
2042 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawValue()));
2044 Stream
.EmitRecord(bitc::METADATA_MACRO
, Record
, Abbrev
);
2048 void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile
*N
,
2049 SmallVectorImpl
<uint64_t> &Record
,
2051 Record
.push_back(N
->isDistinct());
2052 Record
.push_back(N
->getMacinfoType());
2053 Record
.push_back(N
->getLine());
2054 Record
.push_back(VE
.getMetadataOrNullID(N
->getFile()));
2055 Record
.push_back(VE
.getMetadataOrNullID(N
->getElements().get()));
2057 Stream
.EmitRecord(bitc::METADATA_MACRO_FILE
, Record
, Abbrev
);
2061 void ModuleBitcodeWriter::writeDIArgList(const DIArgList
*N
,
2062 SmallVectorImpl
<uint64_t> &Record
) {
2063 Record
.reserve(N
->getArgs().size());
2064 for (ValueAsMetadata
*MD
: N
->getArgs())
2065 Record
.push_back(VE
.getMetadataID(MD
));
2067 Stream
.EmitRecord(bitc::METADATA_ARG_LIST
, Record
);
2071 void ModuleBitcodeWriter::writeDIModule(const DIModule
*N
,
2072 SmallVectorImpl
<uint64_t> &Record
,
2074 Record
.push_back(N
->isDistinct());
2075 for (auto &I
: N
->operands())
2076 Record
.push_back(VE
.getMetadataOrNullID(I
));
2077 Record
.push_back(N
->getLineNo());
2078 Record
.push_back(N
->getIsDecl());
2080 Stream
.EmitRecord(bitc::METADATA_MODULE
, Record
, Abbrev
);
2084 void ModuleBitcodeWriter::writeDIAssignID(const DIAssignID
*N
,
2085 SmallVectorImpl
<uint64_t> &Record
,
2087 // There are no arguments for this metadata type.
2088 Record
.push_back(N
->isDistinct());
2089 Stream
.EmitRecord(bitc::METADATA_ASSIGN_ID
, Record
, Abbrev
);
2093 void ModuleBitcodeWriter::writeDITemplateTypeParameter(
2094 const DITemplateTypeParameter
*N
, SmallVectorImpl
<uint64_t> &Record
,
2096 Record
.push_back(N
->isDistinct());
2097 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawName()));
2098 Record
.push_back(VE
.getMetadataOrNullID(N
->getType()));
2099 Record
.push_back(N
->isDefault());
2101 Stream
.EmitRecord(bitc::METADATA_TEMPLATE_TYPE
, Record
, Abbrev
);
2105 void ModuleBitcodeWriter::writeDITemplateValueParameter(
2106 const DITemplateValueParameter
*N
, SmallVectorImpl
<uint64_t> &Record
,
2108 Record
.push_back(N
->isDistinct());
2109 Record
.push_back(N
->getTag());
2110 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawName()));
2111 Record
.push_back(VE
.getMetadataOrNullID(N
->getType()));
2112 Record
.push_back(N
->isDefault());
2113 Record
.push_back(VE
.getMetadataOrNullID(N
->getValue()));
2115 Stream
.EmitRecord(bitc::METADATA_TEMPLATE_VALUE
, Record
, Abbrev
);
2119 void ModuleBitcodeWriter::writeDIGlobalVariable(
2120 const DIGlobalVariable
*N
, SmallVectorImpl
<uint64_t> &Record
,
2122 const uint64_t Version
= 2 << 1;
2123 Record
.push_back((uint64_t)N
->isDistinct() | Version
);
2124 Record
.push_back(VE
.getMetadataOrNullID(N
->getScope()));
2125 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawName()));
2126 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawLinkageName()));
2127 Record
.push_back(VE
.getMetadataOrNullID(N
->getFile()));
2128 Record
.push_back(N
->getLine());
2129 Record
.push_back(VE
.getMetadataOrNullID(N
->getType()));
2130 Record
.push_back(N
->isLocalToUnit());
2131 Record
.push_back(N
->isDefinition());
2132 Record
.push_back(VE
.getMetadataOrNullID(N
->getStaticDataMemberDeclaration()));
2133 Record
.push_back(VE
.getMetadataOrNullID(N
->getTemplateParams()));
2134 Record
.push_back(N
->getAlignInBits());
2135 Record
.push_back(VE
.getMetadataOrNullID(N
->getAnnotations().get()));
2137 Stream
.EmitRecord(bitc::METADATA_GLOBAL_VAR
, Record
, Abbrev
);
2141 void ModuleBitcodeWriter::writeDILocalVariable(
2142 const DILocalVariable
*N
, SmallVectorImpl
<uint64_t> &Record
,
2144 // In order to support all possible bitcode formats in BitcodeReader we need
2145 // to distinguish the following cases:
2146 // 1) Record has no artificial tag (Record[1]),
2147 // has no obsolete inlinedAt field (Record[9]).
2148 // In this case Record size will be 8, HasAlignment flag is false.
2149 // 2) Record has artificial tag (Record[1]),
2150 // has no obsolete inlignedAt field (Record[9]).
2151 // In this case Record size will be 9, HasAlignment flag is false.
2152 // 3) Record has both artificial tag (Record[1]) and
2153 // obsolete inlignedAt field (Record[9]).
2154 // In this case Record size will be 10, HasAlignment flag is false.
2155 // 4) Record has neither artificial tag, nor inlignedAt field, but
2156 // HasAlignment flag is true and Record[8] contains alignment value.
2157 const uint64_t HasAlignmentFlag
= 1 << 1;
2158 Record
.push_back((uint64_t)N
->isDistinct() | HasAlignmentFlag
);
2159 Record
.push_back(VE
.getMetadataOrNullID(N
->getScope()));
2160 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawName()));
2161 Record
.push_back(VE
.getMetadataOrNullID(N
->getFile()));
2162 Record
.push_back(N
->getLine());
2163 Record
.push_back(VE
.getMetadataOrNullID(N
->getType()));
2164 Record
.push_back(N
->getArg());
2165 Record
.push_back(N
->getFlags());
2166 Record
.push_back(N
->getAlignInBits());
2167 Record
.push_back(VE
.getMetadataOrNullID(N
->getAnnotations().get()));
2169 Stream
.EmitRecord(bitc::METADATA_LOCAL_VAR
, Record
, Abbrev
);
2173 void ModuleBitcodeWriter::writeDILabel(
2174 const DILabel
*N
, SmallVectorImpl
<uint64_t> &Record
,
2176 Record
.push_back((uint64_t)N
->isDistinct());
2177 Record
.push_back(VE
.getMetadataOrNullID(N
->getScope()));
2178 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawName()));
2179 Record
.push_back(VE
.getMetadataOrNullID(N
->getFile()));
2180 Record
.push_back(N
->getLine());
2182 Stream
.EmitRecord(bitc::METADATA_LABEL
, Record
, Abbrev
);
2186 void ModuleBitcodeWriter::writeDIExpression(const DIExpression
*N
,
2187 SmallVectorImpl
<uint64_t> &Record
,
2189 Record
.reserve(N
->getElements().size() + 1);
2190 const uint64_t Version
= 3 << 1;
2191 Record
.push_back((uint64_t)N
->isDistinct() | Version
);
2192 Record
.append(N
->elements_begin(), N
->elements_end());
2194 Stream
.EmitRecord(bitc::METADATA_EXPRESSION
, Record
, Abbrev
);
2198 void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
2199 const DIGlobalVariableExpression
*N
, SmallVectorImpl
<uint64_t> &Record
,
2201 Record
.push_back(N
->isDistinct());
2202 Record
.push_back(VE
.getMetadataOrNullID(N
->getVariable()));
2203 Record
.push_back(VE
.getMetadataOrNullID(N
->getExpression()));
2205 Stream
.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR
, Record
, Abbrev
);
2209 void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty
*N
,
2210 SmallVectorImpl
<uint64_t> &Record
,
2212 Record
.push_back(N
->isDistinct());
2213 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawName()));
2214 Record
.push_back(VE
.getMetadataOrNullID(N
->getFile()));
2215 Record
.push_back(N
->getLine());
2216 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawSetterName()));
2217 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawGetterName()));
2218 Record
.push_back(N
->getAttributes());
2219 Record
.push_back(VE
.getMetadataOrNullID(N
->getType()));
2221 Stream
.EmitRecord(bitc::METADATA_OBJC_PROPERTY
, Record
, Abbrev
);
2225 void ModuleBitcodeWriter::writeDIImportedEntity(
2226 const DIImportedEntity
*N
, SmallVectorImpl
<uint64_t> &Record
,
2228 Record
.push_back(N
->isDistinct());
2229 Record
.push_back(N
->getTag());
2230 Record
.push_back(VE
.getMetadataOrNullID(N
->getScope()));
2231 Record
.push_back(VE
.getMetadataOrNullID(N
->getEntity()));
2232 Record
.push_back(N
->getLine());
2233 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawName()));
2234 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawFile()));
2235 Record
.push_back(VE
.getMetadataOrNullID(N
->getElements().get()));
2237 Stream
.EmitRecord(bitc::METADATA_IMPORTED_ENTITY
, Record
, Abbrev
);
2241 unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
2242 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
2243 Abbv
->Add(BitCodeAbbrevOp(bitc::METADATA_NAME
));
2244 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
2245 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 8));
2246 return Stream
.EmitAbbrev(std::move(Abbv
));
2249 void ModuleBitcodeWriter::writeNamedMetadata(
2250 SmallVectorImpl
<uint64_t> &Record
) {
2251 if (M
.named_metadata_empty())
2254 unsigned Abbrev
= createNamedMetadataAbbrev();
2255 for (const NamedMDNode
&NMD
: M
.named_metadata()) {
2257 StringRef Str
= NMD
.getName();
2258 Record
.append(Str
.bytes_begin(), Str
.bytes_end());
2259 Stream
.EmitRecord(bitc::METADATA_NAME
, Record
, Abbrev
);
2262 // Write named metadata operands.
2263 for (const MDNode
*N
: NMD
.operands())
2264 Record
.push_back(VE
.getMetadataID(N
));
2265 Stream
.EmitRecord(bitc::METADATA_NAMED_NODE
, Record
, 0);
2270 unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
2271 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
2272 Abbv
->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS
));
2273 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6)); // # of strings
2274 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6)); // offset to chars
2275 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob
));
2276 return Stream
.EmitAbbrev(std::move(Abbv
));
2279 /// Write out a record for MDString.
2281 /// All the metadata strings in a metadata block are emitted in a single
2282 /// record. The sizes and strings themselves are shoved into a blob.
2283 void ModuleBitcodeWriter::writeMetadataStrings(
2284 ArrayRef
<const Metadata
*> Strings
, SmallVectorImpl
<uint64_t> &Record
) {
2285 if (Strings
.empty())
2288 // Start the record with the number of strings.
2289 Record
.push_back(bitc::METADATA_STRINGS
);
2290 Record
.push_back(Strings
.size());
2292 // Emit the sizes of the strings in the blob.
2293 SmallString
<256> Blob
;
2295 BitstreamWriter
W(Blob
);
2296 for (const Metadata
*MD
: Strings
)
2297 W
.EmitVBR(cast
<MDString
>(MD
)->getLength(), 6);
2301 // Add the offset to the strings to the record.
2302 Record
.push_back(Blob
.size());
2304 // Add the strings to the blob.
2305 for (const Metadata
*MD
: Strings
)
2306 Blob
.append(cast
<MDString
>(MD
)->getString());
2308 // Emit the final record.
2309 Stream
.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record
, Blob
);
2313 // Generates an enum to use as an index in the Abbrev array of Metadata record.
2314 enum MetadataAbbrev
: unsigned {
2315 #define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
2316 #include "llvm/IR/Metadata.def"
2320 void ModuleBitcodeWriter::writeMetadataRecords(
2321 ArrayRef
<const Metadata
*> MDs
, SmallVectorImpl
<uint64_t> &Record
,
2322 std::vector
<unsigned> *MDAbbrevs
, std::vector
<uint64_t> *IndexPos
) {
2326 // Initialize MDNode abbreviations.
2327 #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
2328 #include "llvm/IR/Metadata.def"
2330 for (const Metadata
*MD
: MDs
) {
2332 IndexPos
->push_back(Stream
.GetCurrentBitNo());
2333 if (const MDNode
*N
= dyn_cast
<MDNode
>(MD
)) {
2334 assert(N
->isResolved() && "Expected forward references to be resolved");
2336 switch (N
->getMetadataID()) {
2338 llvm_unreachable("Invalid MDNode subclass");
2339 #define HANDLE_MDNODE_LEAF(CLASS) \
2340 case Metadata::CLASS##Kind: \
2342 write##CLASS(cast<CLASS>(N), Record, \
2343 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
2345 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
2347 #include "llvm/IR/Metadata.def"
2350 if (auto *AL
= dyn_cast
<DIArgList
>(MD
)) {
2351 writeDIArgList(AL
, Record
);
2354 writeValueAsMetadata(cast
<ValueAsMetadata
>(MD
), Record
);
2358 void ModuleBitcodeWriter::writeModuleMetadata() {
2359 if (!VE
.hasMDs() && M
.named_metadata_empty())
2362 Stream
.EnterSubblock(bitc::METADATA_BLOCK_ID
, 4);
2363 SmallVector
<uint64_t, 64> Record
;
2365 // Emit all abbrevs upfront, so that the reader can jump in the middle of the
2366 // block and load any metadata.
2367 std::vector
<unsigned> MDAbbrevs
;
2369 MDAbbrevs
.resize(MetadataAbbrev::LastPlusOne
);
2370 MDAbbrevs
[MetadataAbbrev::DILocationAbbrevID
] = createDILocationAbbrev();
2371 MDAbbrevs
[MetadataAbbrev::GenericDINodeAbbrevID
] =
2372 createGenericDINodeAbbrev();
2374 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
2375 Abbv
->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX_OFFSET
));
2376 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 32));
2377 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 32));
2378 unsigned OffsetAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
2380 Abbv
= std::make_shared
<BitCodeAbbrev
>();
2381 Abbv
->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX
));
2382 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
2383 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6));
2384 unsigned IndexAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
2386 // Emit MDStrings together upfront.
2387 writeMetadataStrings(VE
.getMDStrings(), Record
);
2389 // We only emit an index for the metadata record if we have more than a given
2390 // (naive) threshold of metadatas, otherwise it is not worth it.
2391 if (VE
.getNonMDStrings().size() > IndexThreshold
) {
2392 // Write a placeholder value in for the offset of the metadata index,
2393 // which is written after the records, so that it can include
2394 // the offset of each entry. The placeholder offset will be
2395 // updated after all records are emitted.
2396 uint64_t Vals
[] = {0, 0};
2397 Stream
.EmitRecord(bitc::METADATA_INDEX_OFFSET
, Vals
, OffsetAbbrev
);
2400 // Compute and save the bit offset to the current position, which will be
2401 // patched when we emit the index later. We can simply subtract the 64-bit
2402 // fixed size from the current bit number to get the location to backpatch.
2403 uint64_t IndexOffsetRecordBitPos
= Stream
.GetCurrentBitNo();
2405 // This index will contain the bitpos for each individual record.
2406 std::vector
<uint64_t> IndexPos
;
2407 IndexPos
.reserve(VE
.getNonMDStrings().size());
2409 // Write all the records
2410 writeMetadataRecords(VE
.getNonMDStrings(), Record
, &MDAbbrevs
, &IndexPos
);
2412 if (VE
.getNonMDStrings().size() > IndexThreshold
) {
2413 // Now that we have emitted all the records we will emit the index. But
2415 // backpatch the forward reference so that the reader can skip the records
2417 Stream
.BackpatchWord64(IndexOffsetRecordBitPos
- 64,
2418 Stream
.GetCurrentBitNo() - IndexOffsetRecordBitPos
);
2420 // Delta encode the index.
2421 uint64_t PreviousValue
= IndexOffsetRecordBitPos
;
2422 for (auto &Elt
: IndexPos
) {
2423 auto EltDelta
= Elt
- PreviousValue
;
2424 PreviousValue
= Elt
;
2427 // Emit the index record.
2428 Stream
.EmitRecord(bitc::METADATA_INDEX
, IndexPos
, IndexAbbrev
);
2432 // Write the named metadata now.
2433 writeNamedMetadata(Record
);
2435 auto AddDeclAttachedMetadata
= [&](const GlobalObject
&GO
) {
2436 SmallVector
<uint64_t, 4> Record
;
2437 Record
.push_back(VE
.getValueID(&GO
));
2438 pushGlobalMetadataAttachment(Record
, GO
);
2439 Stream
.EmitRecord(bitc::METADATA_GLOBAL_DECL_ATTACHMENT
, Record
);
2441 for (const Function
&F
: M
)
2442 if (F
.isDeclaration() && F
.hasMetadata())
2443 AddDeclAttachedMetadata(F
);
2444 // FIXME: Only store metadata for declarations here, and move data for global
2445 // variable definitions to a separate block (PR28134).
2446 for (const GlobalVariable
&GV
: M
.globals())
2447 if (GV
.hasMetadata())
2448 AddDeclAttachedMetadata(GV
);
2453 void ModuleBitcodeWriter::writeFunctionMetadata(const Function
&F
) {
2457 Stream
.EnterSubblock(bitc::METADATA_BLOCK_ID
, 3);
2458 SmallVector
<uint64_t, 64> Record
;
2459 writeMetadataStrings(VE
.getMDStrings(), Record
);
2460 writeMetadataRecords(VE
.getNonMDStrings(), Record
);
2464 void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
2465 SmallVectorImpl
<uint64_t> &Record
, const GlobalObject
&GO
) {
2466 // [n x [id, mdnode]]
2467 SmallVector
<std::pair
<unsigned, MDNode
*>, 4> MDs
;
2468 GO
.getAllMetadata(MDs
);
2469 for (const auto &I
: MDs
) {
2470 Record
.push_back(I
.first
);
2471 Record
.push_back(VE
.getMetadataID(I
.second
));
2475 void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function
&F
) {
2476 Stream
.EnterSubblock(bitc::METADATA_ATTACHMENT_ID
, 3);
2478 SmallVector
<uint64_t, 64> Record
;
2480 if (F
.hasMetadata()) {
2481 pushGlobalMetadataAttachment(Record
, F
);
2482 Stream
.EmitRecord(bitc::METADATA_ATTACHMENT
, Record
, 0);
2486 // Write metadata attachments
2487 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
2488 SmallVector
<std::pair
<unsigned, MDNode
*>, 4> MDs
;
2489 for (const BasicBlock
&BB
: F
)
2490 for (const Instruction
&I
: BB
) {
2492 I
.getAllMetadataOtherThanDebugLoc(MDs
);
2494 // If no metadata, ignore instruction.
2495 if (MDs
.empty()) continue;
2497 Record
.push_back(VE
.getInstructionID(&I
));
2499 for (unsigned i
= 0, e
= MDs
.size(); i
!= e
; ++i
) {
2500 Record
.push_back(MDs
[i
].first
);
2501 Record
.push_back(VE
.getMetadataID(MDs
[i
].second
));
2503 Stream
.EmitRecord(bitc::METADATA_ATTACHMENT
, Record
, 0);
2510 void ModuleBitcodeWriter::writeModuleMetadataKinds() {
2511 SmallVector
<uint64_t, 64> Record
;
2513 // Write metadata kinds
2514 // METADATA_KIND - [n x [id, name]]
2515 SmallVector
<StringRef
, 8> Names
;
2516 M
.getMDKindNames(Names
);
2518 if (Names
.empty()) return;
2520 Stream
.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID
, 3);
2522 for (unsigned MDKindID
= 0, e
= Names
.size(); MDKindID
!= e
; ++MDKindID
) {
2523 Record
.push_back(MDKindID
);
2524 StringRef KName
= Names
[MDKindID
];
2525 Record
.append(KName
.begin(), KName
.end());
2527 Stream
.EmitRecord(bitc::METADATA_KIND
, Record
, 0);
2534 void ModuleBitcodeWriter::writeOperandBundleTags() {
2535 // Write metadata kinds
2537 // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
2539 // OPERAND_BUNDLE_TAG - [strchr x N]
2541 SmallVector
<StringRef
, 8> Tags
;
2542 M
.getOperandBundleTags(Tags
);
2547 Stream
.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID
, 3);
2549 SmallVector
<uint64_t, 64> Record
;
2551 for (auto Tag
: Tags
) {
2552 Record
.append(Tag
.begin(), Tag
.end());
2554 Stream
.EmitRecord(bitc::OPERAND_BUNDLE_TAG
, Record
, 0);
2561 void ModuleBitcodeWriter::writeSyncScopeNames() {
2562 SmallVector
<StringRef
, 8> SSNs
;
2563 M
.getContext().getSyncScopeNames(SSNs
);
2567 Stream
.EnterSubblock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID
, 2);
2569 SmallVector
<uint64_t, 64> Record
;
2570 for (auto SSN
: SSNs
) {
2571 Record
.append(SSN
.begin(), SSN
.end());
2572 Stream
.EmitRecord(bitc::SYNC_SCOPE_NAME
, Record
, 0);
2579 void ModuleBitcodeWriter::writeConstants(unsigned FirstVal
, unsigned LastVal
,
2581 if (FirstVal
== LastVal
) return;
2583 Stream
.EnterSubblock(bitc::CONSTANTS_BLOCK_ID
, 4);
2585 unsigned AggregateAbbrev
= 0;
2586 unsigned String8Abbrev
= 0;
2587 unsigned CString7Abbrev
= 0;
2588 unsigned CString6Abbrev
= 0;
2589 // If this is a constant pool for the module, emit module-specific abbrevs.
2591 // Abbrev for CST_CODE_AGGREGATE.
2592 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
2593 Abbv
->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE
));
2594 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
2595 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, Log2_32_Ceil(LastVal
+1)));
2596 AggregateAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
2598 // Abbrev for CST_CODE_STRING.
2599 Abbv
= std::make_shared
<BitCodeAbbrev
>();
2600 Abbv
->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING
));
2601 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
2602 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 8));
2603 String8Abbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
2604 // Abbrev for CST_CODE_CSTRING.
2605 Abbv
= std::make_shared
<BitCodeAbbrev
>();
2606 Abbv
->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING
));
2607 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
2608 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 7));
2609 CString7Abbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
2610 // Abbrev for CST_CODE_CSTRING.
2611 Abbv
= std::make_shared
<BitCodeAbbrev
>();
2612 Abbv
->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING
));
2613 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
2614 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6
));
2615 CString6Abbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
2618 SmallVector
<uint64_t, 64> Record
;
2620 const ValueEnumerator::ValueList
&Vals
= VE
.getValues();
2621 Type
*LastTy
= nullptr;
2622 for (unsigned i
= FirstVal
; i
!= LastVal
; ++i
) {
2623 const Value
*V
= Vals
[i
].first
;
2624 // If we need to switch types, do so now.
2625 if (V
->getType() != LastTy
) {
2626 LastTy
= V
->getType();
2627 Record
.push_back(VE
.getTypeID(LastTy
));
2628 Stream
.EmitRecord(bitc::CST_CODE_SETTYPE
, Record
,
2629 CONSTANTS_SETTYPE_ABBREV
);
2633 if (const InlineAsm
*IA
= dyn_cast
<InlineAsm
>(V
)) {
2634 Record
.push_back(VE
.getTypeID(IA
->getFunctionType()));
2636 unsigned(IA
->hasSideEffects()) | unsigned(IA
->isAlignStack()) << 1 |
2637 unsigned(IA
->getDialect() & 1) << 2 | unsigned(IA
->canThrow()) << 3);
2639 // Add the asm string.
2640 const std::string
&AsmStr
= IA
->getAsmString();
2641 Record
.push_back(AsmStr
.size());
2642 Record
.append(AsmStr
.begin(), AsmStr
.end());
2644 // Add the constraint string.
2645 const std::string
&ConstraintStr
= IA
->getConstraintString();
2646 Record
.push_back(ConstraintStr
.size());
2647 Record
.append(ConstraintStr
.begin(), ConstraintStr
.end());
2648 Stream
.EmitRecord(bitc::CST_CODE_INLINEASM
, Record
);
2652 const Constant
*C
= cast
<Constant
>(V
);
2653 unsigned Code
= -1U;
2654 unsigned AbbrevToUse
= 0;
2655 if (C
->isNullValue()) {
2656 Code
= bitc::CST_CODE_NULL
;
2657 } else if (isa
<PoisonValue
>(C
)) {
2658 Code
= bitc::CST_CODE_POISON
;
2659 } else if (isa
<UndefValue
>(C
)) {
2660 Code
= bitc::CST_CODE_UNDEF
;
2661 } else if (const ConstantInt
*IV
= dyn_cast
<ConstantInt
>(C
)) {
2662 if (IV
->getBitWidth() <= 64) {
2663 uint64_t V
= IV
->getSExtValue();
2664 emitSignedInt64(Record
, V
);
2665 Code
= bitc::CST_CODE_INTEGER
;
2666 AbbrevToUse
= CONSTANTS_INTEGER_ABBREV
;
2667 } else { // Wide integers, > 64 bits in size.
2668 emitWideAPInt(Record
, IV
->getValue());
2669 Code
= bitc::CST_CODE_WIDE_INTEGER
;
2671 } else if (const ConstantFP
*CFP
= dyn_cast
<ConstantFP
>(C
)) {
2672 Code
= bitc::CST_CODE_FLOAT
;
2673 Type
*Ty
= CFP
->getType()->getScalarType();
2674 if (Ty
->isHalfTy() || Ty
->isBFloatTy() || Ty
->isFloatTy() ||
2676 Record
.push_back(CFP
->getValueAPF().bitcastToAPInt().getZExtValue());
2677 } else if (Ty
->isX86_FP80Ty()) {
2678 // api needed to prevent premature destruction
2679 // bits are not in the same order as a normal i80 APInt, compensate.
2680 APInt api
= CFP
->getValueAPF().bitcastToAPInt();
2681 const uint64_t *p
= api
.getRawData();
2682 Record
.push_back((p
[1] << 48) | (p
[0] >> 16));
2683 Record
.push_back(p
[0] & 0xffffLL
);
2684 } else if (Ty
->isFP128Ty() || Ty
->isPPC_FP128Ty()) {
2685 APInt api
= CFP
->getValueAPF().bitcastToAPInt();
2686 const uint64_t *p
= api
.getRawData();
2687 Record
.push_back(p
[0]);
2688 Record
.push_back(p
[1]);
2690 assert(0 && "Unknown FP type!");
2692 } else if (isa
<ConstantDataSequential
>(C
) &&
2693 cast
<ConstantDataSequential
>(C
)->isString()) {
2694 const ConstantDataSequential
*Str
= cast
<ConstantDataSequential
>(C
);
2695 // Emit constant strings specially.
2696 unsigned NumElts
= Str
->getNumElements();
2697 // If this is a null-terminated string, use the denser CSTRING encoding.
2698 if (Str
->isCString()) {
2699 Code
= bitc::CST_CODE_CSTRING
;
2700 --NumElts
; // Don't encode the null, which isn't allowed by char6.
2702 Code
= bitc::CST_CODE_STRING
;
2703 AbbrevToUse
= String8Abbrev
;
2705 bool isCStr7
= Code
== bitc::CST_CODE_CSTRING
;
2706 bool isCStrChar6
= Code
== bitc::CST_CODE_CSTRING
;
2707 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
2708 unsigned char V
= Str
->getElementAsInteger(i
);
2709 Record
.push_back(V
);
2710 isCStr7
&= (V
& 128) == 0;
2712 isCStrChar6
= BitCodeAbbrevOp::isChar6(V
);
2716 AbbrevToUse
= CString6Abbrev
;
2718 AbbrevToUse
= CString7Abbrev
;
2719 } else if (const ConstantDataSequential
*CDS
=
2720 dyn_cast
<ConstantDataSequential
>(C
)) {
2721 Code
= bitc::CST_CODE_DATA
;
2722 Type
*EltTy
= CDS
->getElementType();
2723 if (isa
<IntegerType
>(EltTy
)) {
2724 for (unsigned i
= 0, e
= CDS
->getNumElements(); i
!= e
; ++i
)
2725 Record
.push_back(CDS
->getElementAsInteger(i
));
2727 for (unsigned i
= 0, e
= CDS
->getNumElements(); i
!= e
; ++i
)
2729 CDS
->getElementAsAPFloat(i
).bitcastToAPInt().getLimitedValue());
2731 } else if (isa
<ConstantAggregate
>(C
)) {
2732 Code
= bitc::CST_CODE_AGGREGATE
;
2733 for (const Value
*Op
: C
->operands())
2734 Record
.push_back(VE
.getValueID(Op
));
2735 AbbrevToUse
= AggregateAbbrev
;
2736 } else if (const ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(C
)) {
2737 switch (CE
->getOpcode()) {
2739 if (Instruction::isCast(CE
->getOpcode())) {
2740 Code
= bitc::CST_CODE_CE_CAST
;
2741 Record
.push_back(getEncodedCastOpcode(CE
->getOpcode()));
2742 Record
.push_back(VE
.getTypeID(C
->getOperand(0)->getType()));
2743 Record
.push_back(VE
.getValueID(C
->getOperand(0)));
2744 AbbrevToUse
= CONSTANTS_CE_CAST_Abbrev
;
2746 assert(CE
->getNumOperands() == 2 && "Unknown constant expr!");
2747 Code
= bitc::CST_CODE_CE_BINOP
;
2748 Record
.push_back(getEncodedBinaryOpcode(CE
->getOpcode()));
2749 Record
.push_back(VE
.getValueID(C
->getOperand(0)));
2750 Record
.push_back(VE
.getValueID(C
->getOperand(1)));
2751 uint64_t Flags
= getOptimizationFlags(CE
);
2753 Record
.push_back(Flags
);
2756 case Instruction::FNeg
: {
2757 assert(CE
->getNumOperands() == 1 && "Unknown constant expr!");
2758 Code
= bitc::CST_CODE_CE_UNOP
;
2759 Record
.push_back(getEncodedUnaryOpcode(CE
->getOpcode()));
2760 Record
.push_back(VE
.getValueID(C
->getOperand(0)));
2761 uint64_t Flags
= getOptimizationFlags(CE
);
2763 Record
.push_back(Flags
);
2766 case Instruction::GetElementPtr
: {
2767 Code
= bitc::CST_CODE_CE_GEP
;
2768 const auto *GO
= cast
<GEPOperator
>(C
);
2769 Record
.push_back(VE
.getTypeID(GO
->getSourceElementType()));
2770 if (std::optional
<ConstantRange
> Range
= GO
->getInRange()) {
2771 Code
= bitc::CST_CODE_CE_GEP_WITH_INRANGE
;
2772 Record
.push_back(GO
->isInBounds());
2773 emitConstantRange(Record
, *Range
);
2774 } else if (GO
->isInBounds())
2775 Code
= bitc::CST_CODE_CE_INBOUNDS_GEP
;
2776 for (unsigned i
= 0, e
= CE
->getNumOperands(); i
!= e
; ++i
) {
2777 Record
.push_back(VE
.getTypeID(C
->getOperand(i
)->getType()));
2778 Record
.push_back(VE
.getValueID(C
->getOperand(i
)));
2782 case Instruction::ExtractElement
:
2783 Code
= bitc::CST_CODE_CE_EXTRACTELT
;
2784 Record
.push_back(VE
.getTypeID(C
->getOperand(0)->getType()));
2785 Record
.push_back(VE
.getValueID(C
->getOperand(0)));
2786 Record
.push_back(VE
.getTypeID(C
->getOperand(1)->getType()));
2787 Record
.push_back(VE
.getValueID(C
->getOperand(1)));
2789 case Instruction::InsertElement
:
2790 Code
= bitc::CST_CODE_CE_INSERTELT
;
2791 Record
.push_back(VE
.getValueID(C
->getOperand(0)));
2792 Record
.push_back(VE
.getValueID(C
->getOperand(1)));
2793 Record
.push_back(VE
.getTypeID(C
->getOperand(2)->getType()));
2794 Record
.push_back(VE
.getValueID(C
->getOperand(2)));
2796 case Instruction::ShuffleVector
:
2797 // If the return type and argument types are the same, this is a
2798 // standard shufflevector instruction. If the types are different,
2799 // then the shuffle is widening or truncating the input vectors, and
2800 // the argument type must also be encoded.
2801 if (C
->getType() == C
->getOperand(0)->getType()) {
2802 Code
= bitc::CST_CODE_CE_SHUFFLEVEC
;
2804 Code
= bitc::CST_CODE_CE_SHUFVEC_EX
;
2805 Record
.push_back(VE
.getTypeID(C
->getOperand(0)->getType()));
2807 Record
.push_back(VE
.getValueID(C
->getOperand(0)));
2808 Record
.push_back(VE
.getValueID(C
->getOperand(1)));
2809 Record
.push_back(VE
.getValueID(CE
->getShuffleMaskForBitcode()));
2811 case Instruction::ICmp
:
2812 case Instruction::FCmp
:
2813 Code
= bitc::CST_CODE_CE_CMP
;
2814 Record
.push_back(VE
.getTypeID(C
->getOperand(0)->getType()));
2815 Record
.push_back(VE
.getValueID(C
->getOperand(0)));
2816 Record
.push_back(VE
.getValueID(C
->getOperand(1)));
2817 Record
.push_back(CE
->getPredicate());
2820 } else if (const BlockAddress
*BA
= dyn_cast
<BlockAddress
>(C
)) {
2821 Code
= bitc::CST_CODE_BLOCKADDRESS
;
2822 Record
.push_back(VE
.getTypeID(BA
->getFunction()->getType()));
2823 Record
.push_back(VE
.getValueID(BA
->getFunction()));
2824 Record
.push_back(VE
.getGlobalBasicBlockID(BA
->getBasicBlock()));
2825 } else if (const auto *Equiv
= dyn_cast
<DSOLocalEquivalent
>(C
)) {
2826 Code
= bitc::CST_CODE_DSO_LOCAL_EQUIVALENT
;
2827 Record
.push_back(VE
.getTypeID(Equiv
->getGlobalValue()->getType()));
2828 Record
.push_back(VE
.getValueID(Equiv
->getGlobalValue()));
2829 } else if (const auto *NC
= dyn_cast
<NoCFIValue
>(C
)) {
2830 Code
= bitc::CST_CODE_NO_CFI_VALUE
;
2831 Record
.push_back(VE
.getTypeID(NC
->getGlobalValue()->getType()));
2832 Record
.push_back(VE
.getValueID(NC
->getGlobalValue()));
2837 llvm_unreachable("Unknown constant!");
2839 Stream
.EmitRecord(Code
, Record
, AbbrevToUse
);
2846 void ModuleBitcodeWriter::writeModuleConstants() {
2847 const ValueEnumerator::ValueList
&Vals
= VE
.getValues();
2849 // Find the first constant to emit, which is the first non-globalvalue value.
2850 // We know globalvalues have been emitted by WriteModuleInfo.
2851 for (unsigned i
= 0, e
= Vals
.size(); i
!= e
; ++i
) {
2852 if (!isa
<GlobalValue
>(Vals
[i
].first
)) {
2853 writeConstants(i
, Vals
.size(), true);
2859 /// pushValueAndType - The file has to encode both the value and type id for
2860 /// many values, because we need to know what type to create for forward
2861 /// references. However, most operands are not forward references, so this type
2862 /// field is not needed.
2864 /// This function adds V's value ID to Vals. If the value ID is higher than the
2865 /// instruction ID, then it is a forward reference, and it also includes the
2866 /// type ID. The value ID that is written is encoded relative to the InstID.
2867 bool ModuleBitcodeWriter::pushValueAndType(const Value
*V
, unsigned InstID
,
2868 SmallVectorImpl
<unsigned> &Vals
) {
2869 unsigned ValID
= VE
.getValueID(V
);
2870 // Make encoding relative to the InstID.
2871 Vals
.push_back(InstID
- ValID
);
2872 if (ValID
>= InstID
) {
2873 Vals
.push_back(VE
.getTypeID(V
->getType()));
2879 void ModuleBitcodeWriter::writeOperandBundles(const CallBase
&CS
,
2881 SmallVector
<unsigned, 64> Record
;
2882 LLVMContext
&C
= CS
.getContext();
2884 for (unsigned i
= 0, e
= CS
.getNumOperandBundles(); i
!= e
; ++i
) {
2885 const auto &Bundle
= CS
.getOperandBundleAt(i
);
2886 Record
.push_back(C
.getOperandBundleTagID(Bundle
.getTagName()));
2888 for (auto &Input
: Bundle
.Inputs
)
2889 pushValueAndType(Input
, InstID
, Record
);
2891 Stream
.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE
, Record
);
2896 /// pushValue - Like pushValueAndType, but where the type of the value is
2897 /// omitted (perhaps it was already encoded in an earlier operand).
2898 void ModuleBitcodeWriter::pushValue(const Value
*V
, unsigned InstID
,
2899 SmallVectorImpl
<unsigned> &Vals
) {
2900 unsigned ValID
= VE
.getValueID(V
);
2901 Vals
.push_back(InstID
- ValID
);
2904 void ModuleBitcodeWriter::pushValueSigned(const Value
*V
, unsigned InstID
,
2905 SmallVectorImpl
<uint64_t> &Vals
) {
2906 unsigned ValID
= VE
.getValueID(V
);
2907 int64_t diff
= ((int32_t)InstID
- (int32_t)ValID
);
2908 emitSignedInt64(Vals
, diff
);
2911 /// WriteInstruction - Emit an instruction to the specified stream.
2912 void ModuleBitcodeWriter::writeInstruction(const Instruction
&I
,
2914 SmallVectorImpl
<unsigned> &Vals
) {
2916 unsigned AbbrevToUse
= 0;
2917 VE
.setInstructionID(&I
);
2918 switch (I
.getOpcode()) {
2920 if (Instruction::isCast(I
.getOpcode())) {
2921 Code
= bitc::FUNC_CODE_INST_CAST
;
2922 if (!pushValueAndType(I
.getOperand(0), InstID
, Vals
))
2923 AbbrevToUse
= FUNCTION_INST_CAST_ABBREV
;
2924 Vals
.push_back(VE
.getTypeID(I
.getType()));
2925 Vals
.push_back(getEncodedCastOpcode(I
.getOpcode()));
2926 uint64_t Flags
= getOptimizationFlags(&I
);
2928 if (AbbrevToUse
== FUNCTION_INST_CAST_ABBREV
)
2929 AbbrevToUse
= FUNCTION_INST_CAST_FLAGS_ABBREV
;
2930 Vals
.push_back(Flags
);
2933 assert(isa
<BinaryOperator
>(I
) && "Unknown instruction!");
2934 Code
= bitc::FUNC_CODE_INST_BINOP
;
2935 if (!pushValueAndType(I
.getOperand(0), InstID
, Vals
))
2936 AbbrevToUse
= FUNCTION_INST_BINOP_ABBREV
;
2937 pushValue(I
.getOperand(1), InstID
, Vals
);
2938 Vals
.push_back(getEncodedBinaryOpcode(I
.getOpcode()));
2939 uint64_t Flags
= getOptimizationFlags(&I
);
2941 if (AbbrevToUse
== FUNCTION_INST_BINOP_ABBREV
)
2942 AbbrevToUse
= FUNCTION_INST_BINOP_FLAGS_ABBREV
;
2943 Vals
.push_back(Flags
);
2947 case Instruction::FNeg
: {
2948 Code
= bitc::FUNC_CODE_INST_UNOP
;
2949 if (!pushValueAndType(I
.getOperand(0), InstID
, Vals
))
2950 AbbrevToUse
= FUNCTION_INST_UNOP_ABBREV
;
2951 Vals
.push_back(getEncodedUnaryOpcode(I
.getOpcode()));
2952 uint64_t Flags
= getOptimizationFlags(&I
);
2954 if (AbbrevToUse
== FUNCTION_INST_UNOP_ABBREV
)
2955 AbbrevToUse
= FUNCTION_INST_UNOP_FLAGS_ABBREV
;
2956 Vals
.push_back(Flags
);
2960 case Instruction::GetElementPtr
: {
2961 Code
= bitc::FUNC_CODE_INST_GEP
;
2962 AbbrevToUse
= FUNCTION_INST_GEP_ABBREV
;
2963 auto &GEPInst
= cast
<GetElementPtrInst
>(I
);
2964 Vals
.push_back(GEPInst
.isInBounds());
2965 Vals
.push_back(VE
.getTypeID(GEPInst
.getSourceElementType()));
2966 for (unsigned i
= 0, e
= I
.getNumOperands(); i
!= e
; ++i
)
2967 pushValueAndType(I
.getOperand(i
), InstID
, Vals
);
2970 case Instruction::ExtractValue
: {
2971 Code
= bitc::FUNC_CODE_INST_EXTRACTVAL
;
2972 pushValueAndType(I
.getOperand(0), InstID
, Vals
);
2973 const ExtractValueInst
*EVI
= cast
<ExtractValueInst
>(&I
);
2974 Vals
.append(EVI
->idx_begin(), EVI
->idx_end());
2977 case Instruction::InsertValue
: {
2978 Code
= bitc::FUNC_CODE_INST_INSERTVAL
;
2979 pushValueAndType(I
.getOperand(0), InstID
, Vals
);
2980 pushValueAndType(I
.getOperand(1), InstID
, Vals
);
2981 const InsertValueInst
*IVI
= cast
<InsertValueInst
>(&I
);
2982 Vals
.append(IVI
->idx_begin(), IVI
->idx_end());
2985 case Instruction::Select
: {
2986 Code
= bitc::FUNC_CODE_INST_VSELECT
;
2987 pushValueAndType(I
.getOperand(1), InstID
, Vals
);
2988 pushValue(I
.getOperand(2), InstID
, Vals
);
2989 pushValueAndType(I
.getOperand(0), InstID
, Vals
);
2990 uint64_t Flags
= getOptimizationFlags(&I
);
2992 Vals
.push_back(Flags
);
2995 case Instruction::ExtractElement
:
2996 Code
= bitc::FUNC_CODE_INST_EXTRACTELT
;
2997 pushValueAndType(I
.getOperand(0), InstID
, Vals
);
2998 pushValueAndType(I
.getOperand(1), InstID
, Vals
);
3000 case Instruction::InsertElement
:
3001 Code
= bitc::FUNC_CODE_INST_INSERTELT
;
3002 pushValueAndType(I
.getOperand(0), InstID
, Vals
);
3003 pushValue(I
.getOperand(1), InstID
, Vals
);
3004 pushValueAndType(I
.getOperand(2), InstID
, Vals
);
3006 case Instruction::ShuffleVector
:
3007 Code
= bitc::FUNC_CODE_INST_SHUFFLEVEC
;
3008 pushValueAndType(I
.getOperand(0), InstID
, Vals
);
3009 pushValue(I
.getOperand(1), InstID
, Vals
);
3010 pushValue(cast
<ShuffleVectorInst
>(I
).getShuffleMaskForBitcode(), InstID
,
3013 case Instruction::ICmp
:
3014 case Instruction::FCmp
: {
3015 // compare returning Int1Ty or vector of Int1Ty
3016 Code
= bitc::FUNC_CODE_INST_CMP2
;
3017 pushValueAndType(I
.getOperand(0), InstID
, Vals
);
3018 pushValue(I
.getOperand(1), InstID
, Vals
);
3019 Vals
.push_back(cast
<CmpInst
>(I
).getPredicate());
3020 uint64_t Flags
= getOptimizationFlags(&I
);
3022 Vals
.push_back(Flags
);
3026 case Instruction::Ret
:
3028 Code
= bitc::FUNC_CODE_INST_RET
;
3029 unsigned NumOperands
= I
.getNumOperands();
3030 if (NumOperands
== 0)
3031 AbbrevToUse
= FUNCTION_INST_RET_VOID_ABBREV
;
3032 else if (NumOperands
== 1) {
3033 if (!pushValueAndType(I
.getOperand(0), InstID
, Vals
))
3034 AbbrevToUse
= FUNCTION_INST_RET_VAL_ABBREV
;
3036 for (unsigned i
= 0, e
= NumOperands
; i
!= e
; ++i
)
3037 pushValueAndType(I
.getOperand(i
), InstID
, Vals
);
3041 case Instruction::Br
:
3043 Code
= bitc::FUNC_CODE_INST_BR
;
3044 const BranchInst
&II
= cast
<BranchInst
>(I
);
3045 Vals
.push_back(VE
.getValueID(II
.getSuccessor(0)));
3046 if (II
.isConditional()) {
3047 Vals
.push_back(VE
.getValueID(II
.getSuccessor(1)));
3048 pushValue(II
.getCondition(), InstID
, Vals
);
3052 case Instruction::Switch
:
3054 Code
= bitc::FUNC_CODE_INST_SWITCH
;
3055 const SwitchInst
&SI
= cast
<SwitchInst
>(I
);
3056 Vals
.push_back(VE
.getTypeID(SI
.getCondition()->getType()));
3057 pushValue(SI
.getCondition(), InstID
, Vals
);
3058 Vals
.push_back(VE
.getValueID(SI
.getDefaultDest()));
3059 for (auto Case
: SI
.cases()) {
3060 Vals
.push_back(VE
.getValueID(Case
.getCaseValue()));
3061 Vals
.push_back(VE
.getValueID(Case
.getCaseSuccessor()));
3065 case Instruction::IndirectBr
:
3066 Code
= bitc::FUNC_CODE_INST_INDIRECTBR
;
3067 Vals
.push_back(VE
.getTypeID(I
.getOperand(0)->getType()));
3068 // Encode the address operand as relative, but not the basic blocks.
3069 pushValue(I
.getOperand(0), InstID
, Vals
);
3070 for (unsigned i
= 1, e
= I
.getNumOperands(); i
!= e
; ++i
)
3071 Vals
.push_back(VE
.getValueID(I
.getOperand(i
)));
3074 case Instruction::Invoke
: {
3075 const InvokeInst
*II
= cast
<InvokeInst
>(&I
);
3076 const Value
*Callee
= II
->getCalledOperand();
3077 FunctionType
*FTy
= II
->getFunctionType();
3079 if (II
->hasOperandBundles())
3080 writeOperandBundles(*II
, InstID
);
3082 Code
= bitc::FUNC_CODE_INST_INVOKE
;
3084 Vals
.push_back(VE
.getAttributeListID(II
->getAttributes()));
3085 Vals
.push_back(II
->getCallingConv() | 1 << 13);
3086 Vals
.push_back(VE
.getValueID(II
->getNormalDest()));
3087 Vals
.push_back(VE
.getValueID(II
->getUnwindDest()));
3088 Vals
.push_back(VE
.getTypeID(FTy
));
3089 pushValueAndType(Callee
, InstID
, Vals
);
3091 // Emit value #'s for the fixed parameters.
3092 for (unsigned i
= 0, e
= FTy
->getNumParams(); i
!= e
; ++i
)
3093 pushValue(I
.getOperand(i
), InstID
, Vals
); // fixed param.
3095 // Emit type/value pairs for varargs params.
3096 if (FTy
->isVarArg()) {
3097 for (unsigned i
= FTy
->getNumParams(), e
= II
->arg_size(); i
!= e
; ++i
)
3098 pushValueAndType(I
.getOperand(i
), InstID
, Vals
); // vararg
3102 case Instruction::Resume
:
3103 Code
= bitc::FUNC_CODE_INST_RESUME
;
3104 pushValueAndType(I
.getOperand(0), InstID
, Vals
);
3106 case Instruction::CleanupRet
: {
3107 Code
= bitc::FUNC_CODE_INST_CLEANUPRET
;
3108 const auto &CRI
= cast
<CleanupReturnInst
>(I
);
3109 pushValue(CRI
.getCleanupPad(), InstID
, Vals
);
3110 if (CRI
.hasUnwindDest())
3111 Vals
.push_back(VE
.getValueID(CRI
.getUnwindDest()));
3114 case Instruction::CatchRet
: {
3115 Code
= bitc::FUNC_CODE_INST_CATCHRET
;
3116 const auto &CRI
= cast
<CatchReturnInst
>(I
);
3117 pushValue(CRI
.getCatchPad(), InstID
, Vals
);
3118 Vals
.push_back(VE
.getValueID(CRI
.getSuccessor()));
3121 case Instruction::CleanupPad
:
3122 case Instruction::CatchPad
: {
3123 const auto &FuncletPad
= cast
<FuncletPadInst
>(I
);
3124 Code
= isa
<CatchPadInst
>(FuncletPad
) ? bitc::FUNC_CODE_INST_CATCHPAD
3125 : bitc::FUNC_CODE_INST_CLEANUPPAD
;
3126 pushValue(FuncletPad
.getParentPad(), InstID
, Vals
);
3128 unsigned NumArgOperands
= FuncletPad
.arg_size();
3129 Vals
.push_back(NumArgOperands
);
3130 for (unsigned Op
= 0; Op
!= NumArgOperands
; ++Op
)
3131 pushValueAndType(FuncletPad
.getArgOperand(Op
), InstID
, Vals
);
3134 case Instruction::CatchSwitch
: {
3135 Code
= bitc::FUNC_CODE_INST_CATCHSWITCH
;
3136 const auto &CatchSwitch
= cast
<CatchSwitchInst
>(I
);
3138 pushValue(CatchSwitch
.getParentPad(), InstID
, Vals
);
3140 unsigned NumHandlers
= CatchSwitch
.getNumHandlers();
3141 Vals
.push_back(NumHandlers
);
3142 for (const BasicBlock
*CatchPadBB
: CatchSwitch
.handlers())
3143 Vals
.push_back(VE
.getValueID(CatchPadBB
));
3145 if (CatchSwitch
.hasUnwindDest())
3146 Vals
.push_back(VE
.getValueID(CatchSwitch
.getUnwindDest()));
3149 case Instruction::CallBr
: {
3150 const CallBrInst
*CBI
= cast
<CallBrInst
>(&I
);
3151 const Value
*Callee
= CBI
->getCalledOperand();
3152 FunctionType
*FTy
= CBI
->getFunctionType();
3154 if (CBI
->hasOperandBundles())
3155 writeOperandBundles(*CBI
, InstID
);
3157 Code
= bitc::FUNC_CODE_INST_CALLBR
;
3159 Vals
.push_back(VE
.getAttributeListID(CBI
->getAttributes()));
3161 Vals
.push_back(CBI
->getCallingConv() << bitc::CALL_CCONV
|
3162 1 << bitc::CALL_EXPLICIT_TYPE
);
3164 Vals
.push_back(VE
.getValueID(CBI
->getDefaultDest()));
3165 Vals
.push_back(CBI
->getNumIndirectDests());
3166 for (unsigned i
= 0, e
= CBI
->getNumIndirectDests(); i
!= e
; ++i
)
3167 Vals
.push_back(VE
.getValueID(CBI
->getIndirectDest(i
)));
3169 Vals
.push_back(VE
.getTypeID(FTy
));
3170 pushValueAndType(Callee
, InstID
, Vals
);
3172 // Emit value #'s for the fixed parameters.
3173 for (unsigned i
= 0, e
= FTy
->getNumParams(); i
!= e
; ++i
)
3174 pushValue(I
.getOperand(i
), InstID
, Vals
); // fixed param.
3176 // Emit type/value pairs for varargs params.
3177 if (FTy
->isVarArg()) {
3178 for (unsigned i
= FTy
->getNumParams(), e
= CBI
->arg_size(); i
!= e
; ++i
)
3179 pushValueAndType(I
.getOperand(i
), InstID
, Vals
); // vararg
3183 case Instruction::Unreachable
:
3184 Code
= bitc::FUNC_CODE_INST_UNREACHABLE
;
3185 AbbrevToUse
= FUNCTION_INST_UNREACHABLE_ABBREV
;
3188 case Instruction::PHI
: {
3189 const PHINode
&PN
= cast
<PHINode
>(I
);
3190 Code
= bitc::FUNC_CODE_INST_PHI
;
3191 // With the newer instruction encoding, forward references could give
3192 // negative valued IDs. This is most common for PHIs, so we use
3194 SmallVector
<uint64_t, 128> Vals64
;
3195 Vals64
.push_back(VE
.getTypeID(PN
.getType()));
3196 for (unsigned i
= 0, e
= PN
.getNumIncomingValues(); i
!= e
; ++i
) {
3197 pushValueSigned(PN
.getIncomingValue(i
), InstID
, Vals64
);
3198 Vals64
.push_back(VE
.getValueID(PN
.getIncomingBlock(i
)));
3201 uint64_t Flags
= getOptimizationFlags(&I
);
3203 Vals64
.push_back(Flags
);
3205 // Emit a Vals64 vector and exit.
3206 Stream
.EmitRecord(Code
, Vals64
, AbbrevToUse
);
3211 case Instruction::LandingPad
: {
3212 const LandingPadInst
&LP
= cast
<LandingPadInst
>(I
);
3213 Code
= bitc::FUNC_CODE_INST_LANDINGPAD
;
3214 Vals
.push_back(VE
.getTypeID(LP
.getType()));
3215 Vals
.push_back(LP
.isCleanup());
3216 Vals
.push_back(LP
.getNumClauses());
3217 for (unsigned I
= 0, E
= LP
.getNumClauses(); I
!= E
; ++I
) {
3219 Vals
.push_back(LandingPadInst::Catch
);
3221 Vals
.push_back(LandingPadInst::Filter
);
3222 pushValueAndType(LP
.getClause(I
), InstID
, Vals
);
3227 case Instruction::Alloca
: {
3228 Code
= bitc::FUNC_CODE_INST_ALLOCA
;
3229 const AllocaInst
&AI
= cast
<AllocaInst
>(I
);
3230 Vals
.push_back(VE
.getTypeID(AI
.getAllocatedType()));
3231 Vals
.push_back(VE
.getTypeID(I
.getOperand(0)->getType()));
3232 Vals
.push_back(VE
.getValueID(I
.getOperand(0))); // size.
3233 using APV
= AllocaPackedValues
;
3234 unsigned Record
= 0;
3235 unsigned EncodedAlign
= getEncodedAlign(AI
.getAlign());
3236 Bitfield::set
<APV::AlignLower
>(
3237 Record
, EncodedAlign
& ((1 << APV::AlignLower::Bits
) - 1));
3238 Bitfield::set
<APV::AlignUpper
>(Record
,
3239 EncodedAlign
>> APV::AlignLower::Bits
);
3240 Bitfield::set
<APV::UsedWithInAlloca
>(Record
, AI
.isUsedWithInAlloca());
3241 Bitfield::set
<APV::ExplicitType
>(Record
, true);
3242 Bitfield::set
<APV::SwiftError
>(Record
, AI
.isSwiftError());
3243 Vals
.push_back(Record
);
3245 unsigned AS
= AI
.getAddressSpace();
3246 if (AS
!= M
.getDataLayout().getAllocaAddrSpace())
3251 case Instruction::Load
:
3252 if (cast
<LoadInst
>(I
).isAtomic()) {
3253 Code
= bitc::FUNC_CODE_INST_LOADATOMIC
;
3254 pushValueAndType(I
.getOperand(0), InstID
, Vals
);
3256 Code
= bitc::FUNC_CODE_INST_LOAD
;
3257 if (!pushValueAndType(I
.getOperand(0), InstID
, Vals
)) // ptr
3258 AbbrevToUse
= FUNCTION_INST_LOAD_ABBREV
;
3260 Vals
.push_back(VE
.getTypeID(I
.getType()));
3261 Vals
.push_back(getEncodedAlign(cast
<LoadInst
>(I
).getAlign()));
3262 Vals
.push_back(cast
<LoadInst
>(I
).isVolatile());
3263 if (cast
<LoadInst
>(I
).isAtomic()) {
3264 Vals
.push_back(getEncodedOrdering(cast
<LoadInst
>(I
).getOrdering()));
3265 Vals
.push_back(getEncodedSyncScopeID(cast
<LoadInst
>(I
).getSyncScopeID()));
3268 case Instruction::Store
:
3269 if (cast
<StoreInst
>(I
).isAtomic())
3270 Code
= bitc::FUNC_CODE_INST_STOREATOMIC
;
3272 Code
= bitc::FUNC_CODE_INST_STORE
;
3273 pushValueAndType(I
.getOperand(1), InstID
, Vals
); // ptrty + ptr
3274 pushValueAndType(I
.getOperand(0), InstID
, Vals
); // valty + val
3275 Vals
.push_back(getEncodedAlign(cast
<StoreInst
>(I
).getAlign()));
3276 Vals
.push_back(cast
<StoreInst
>(I
).isVolatile());
3277 if (cast
<StoreInst
>(I
).isAtomic()) {
3278 Vals
.push_back(getEncodedOrdering(cast
<StoreInst
>(I
).getOrdering()));
3280 getEncodedSyncScopeID(cast
<StoreInst
>(I
).getSyncScopeID()));
3283 case Instruction::AtomicCmpXchg
:
3284 Code
= bitc::FUNC_CODE_INST_CMPXCHG
;
3285 pushValueAndType(I
.getOperand(0), InstID
, Vals
); // ptrty + ptr
3286 pushValueAndType(I
.getOperand(1), InstID
, Vals
); // cmp.
3287 pushValue(I
.getOperand(2), InstID
, Vals
); // newval.
3288 Vals
.push_back(cast
<AtomicCmpXchgInst
>(I
).isVolatile());
3290 getEncodedOrdering(cast
<AtomicCmpXchgInst
>(I
).getSuccessOrdering()));
3292 getEncodedSyncScopeID(cast
<AtomicCmpXchgInst
>(I
).getSyncScopeID()));
3294 getEncodedOrdering(cast
<AtomicCmpXchgInst
>(I
).getFailureOrdering()));
3295 Vals
.push_back(cast
<AtomicCmpXchgInst
>(I
).isWeak());
3296 Vals
.push_back(getEncodedAlign(cast
<AtomicCmpXchgInst
>(I
).getAlign()));
3298 case Instruction::AtomicRMW
:
3299 Code
= bitc::FUNC_CODE_INST_ATOMICRMW
;
3300 pushValueAndType(I
.getOperand(0), InstID
, Vals
); // ptrty + ptr
3301 pushValueAndType(I
.getOperand(1), InstID
, Vals
); // valty + val
3303 getEncodedRMWOperation(cast
<AtomicRMWInst
>(I
).getOperation()));
3304 Vals
.push_back(cast
<AtomicRMWInst
>(I
).isVolatile());
3305 Vals
.push_back(getEncodedOrdering(cast
<AtomicRMWInst
>(I
).getOrdering()));
3307 getEncodedSyncScopeID(cast
<AtomicRMWInst
>(I
).getSyncScopeID()));
3308 Vals
.push_back(getEncodedAlign(cast
<AtomicRMWInst
>(I
).getAlign()));
3310 case Instruction::Fence
:
3311 Code
= bitc::FUNC_CODE_INST_FENCE
;
3312 Vals
.push_back(getEncodedOrdering(cast
<FenceInst
>(I
).getOrdering()));
3313 Vals
.push_back(getEncodedSyncScopeID(cast
<FenceInst
>(I
).getSyncScopeID()));
3315 case Instruction::Call
: {
3316 const CallInst
&CI
= cast
<CallInst
>(I
);
3317 FunctionType
*FTy
= CI
.getFunctionType();
3319 if (CI
.hasOperandBundles())
3320 writeOperandBundles(CI
, InstID
);
3322 Code
= bitc::FUNC_CODE_INST_CALL
;
3324 Vals
.push_back(VE
.getAttributeListID(CI
.getAttributes()));
3326 unsigned Flags
= getOptimizationFlags(&I
);
3327 Vals
.push_back(CI
.getCallingConv() << bitc::CALL_CCONV
|
3328 unsigned(CI
.isTailCall()) << bitc::CALL_TAIL
|
3329 unsigned(CI
.isMustTailCall()) << bitc::CALL_MUSTTAIL
|
3330 1 << bitc::CALL_EXPLICIT_TYPE
|
3331 unsigned(CI
.isNoTailCall()) << bitc::CALL_NOTAIL
|
3332 unsigned(Flags
!= 0) << bitc::CALL_FMF
);
3334 Vals
.push_back(Flags
);
3336 Vals
.push_back(VE
.getTypeID(FTy
));
3337 pushValueAndType(CI
.getCalledOperand(), InstID
, Vals
); // Callee
3339 // Emit value #'s for the fixed parameters.
3340 for (unsigned i
= 0, e
= FTy
->getNumParams(); i
!= e
; ++i
) {
3341 // Check for labels (can happen with asm labels).
3342 if (FTy
->getParamType(i
)->isLabelTy())
3343 Vals
.push_back(VE
.getValueID(CI
.getArgOperand(i
)));
3345 pushValue(CI
.getArgOperand(i
), InstID
, Vals
); // fixed param.
3348 // Emit type/value pairs for varargs params.
3349 if (FTy
->isVarArg()) {
3350 for (unsigned i
= FTy
->getNumParams(), e
= CI
.arg_size(); i
!= e
; ++i
)
3351 pushValueAndType(CI
.getArgOperand(i
), InstID
, Vals
); // varargs
3355 case Instruction::VAArg
:
3356 Code
= bitc::FUNC_CODE_INST_VAARG
;
3357 Vals
.push_back(VE
.getTypeID(I
.getOperand(0)->getType())); // valistty
3358 pushValue(I
.getOperand(0), InstID
, Vals
); // valist.
3359 Vals
.push_back(VE
.getTypeID(I
.getType())); // restype.
3361 case Instruction::Freeze
:
3362 Code
= bitc::FUNC_CODE_INST_FREEZE
;
3363 pushValueAndType(I
.getOperand(0), InstID
, Vals
);
3367 Stream
.EmitRecord(Code
, Vals
, AbbrevToUse
);
3371 /// Write a GlobalValue VST to the module. The purpose of this data structure is
3372 /// to allow clients to efficiently find the function body.
3373 void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
3374 DenseMap
<const Function
*, uint64_t> &FunctionToBitcodeIndex
) {
3375 // Get the offset of the VST we are writing, and backpatch it into
3376 // the VST forward declaration record.
3377 uint64_t VSTOffset
= Stream
.GetCurrentBitNo();
3378 // The BitcodeStartBit was the stream offset of the identification block.
3379 VSTOffset
-= bitcodeStartBit();
3380 assert((VSTOffset
& 31) == 0 && "VST block not 32-bit aligned");
3381 // Note that we add 1 here because the offset is relative to one word
3382 // before the start of the identification block, which was historically
3383 // always the start of the regular bitcode header.
3384 Stream
.BackpatchWord(VSTOffsetPlaceholder
, VSTOffset
/ 32 + 1);
3386 Stream
.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID
, 4);
3388 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
3389 Abbv
->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY
));
3390 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // value id
3391 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // funcoffset
3392 unsigned FnEntryAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
3394 for (const Function
&F
: M
) {
3397 if (F
.isDeclaration())
3400 Record
[0] = VE
.getValueID(&F
);
3402 // Save the word offset of the function (from the start of the
3403 // actual bitcode written to the stream).
3404 uint64_t BitcodeIndex
= FunctionToBitcodeIndex
[&F
] - bitcodeStartBit();
3405 assert((BitcodeIndex
& 31) == 0 && "function block not 32-bit aligned");
3406 // Note that we add 1 here because the offset is relative to one word
3407 // before the start of the identification block, which was historically
3408 // always the start of the regular bitcode header.
3409 Record
[1] = BitcodeIndex
/ 32 + 1;
3411 Stream
.EmitRecord(bitc::VST_CODE_FNENTRY
, Record
, FnEntryAbbrev
);
3417 /// Emit names for arguments, instructions and basic blocks in a function.
3418 void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
3419 const ValueSymbolTable
&VST
) {
3423 Stream
.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID
, 4);
3425 // FIXME: Set up the abbrev, we know how many values there are!
3426 // FIXME: We know if the type names can use 7-bit ascii.
3427 SmallVector
<uint64_t, 64> NameVals
;
3429 for (const ValueName
&Name
: VST
) {
3430 // Figure out the encoding to use for the name.
3431 StringEncoding Bits
= getStringEncoding(Name
.getKey());
3433 unsigned AbbrevToUse
= VST_ENTRY_8_ABBREV
;
3434 NameVals
.push_back(VE
.getValueID(Name
.getValue()));
3436 // VST_CODE_ENTRY: [valueid, namechar x N]
3437 // VST_CODE_BBENTRY: [bbid, namechar x N]
3439 if (isa
<BasicBlock
>(Name
.getValue())) {
3440 Code
= bitc::VST_CODE_BBENTRY
;
3441 if (Bits
== SE_Char6
)
3442 AbbrevToUse
= VST_BBENTRY_6_ABBREV
;
3444 Code
= bitc::VST_CODE_ENTRY
;
3445 if (Bits
== SE_Char6
)
3446 AbbrevToUse
= VST_ENTRY_6_ABBREV
;
3447 else if (Bits
== SE_Fixed7
)
3448 AbbrevToUse
= VST_ENTRY_7_ABBREV
;
3451 for (const auto P
: Name
.getKey())
3452 NameVals
.push_back((unsigned char)P
);
3454 // Emit the finished record.
3455 Stream
.EmitRecord(Code
, NameVals
, AbbrevToUse
);
3462 void ModuleBitcodeWriter::writeUseList(UseListOrder
&&Order
) {
3463 assert(Order
.Shuffle
.size() >= 2 && "Shuffle too small");
3465 if (isa
<BasicBlock
>(Order
.V
))
3466 Code
= bitc::USELIST_CODE_BB
;
3468 Code
= bitc::USELIST_CODE_DEFAULT
;
3470 SmallVector
<uint64_t, 64> Record(Order
.Shuffle
.begin(), Order
.Shuffle
.end());
3471 Record
.push_back(VE
.getValueID(Order
.V
));
3472 Stream
.EmitRecord(Code
, Record
);
3475 void ModuleBitcodeWriter::writeUseListBlock(const Function
*F
) {
3476 assert(VE
.shouldPreserveUseListOrder() &&
3477 "Expected to be preserving use-list order");
3479 auto hasMore
= [&]() {
3480 return !VE
.UseListOrders
.empty() && VE
.UseListOrders
.back().F
== F
;
3486 Stream
.EnterSubblock(bitc::USELIST_BLOCK_ID
, 3);
3488 writeUseList(std::move(VE
.UseListOrders
.back()));
3489 VE
.UseListOrders
.pop_back();
3494 /// Emit a function body to the module stream.
3495 void ModuleBitcodeWriter::writeFunction(
3497 DenseMap
<const Function
*, uint64_t> &FunctionToBitcodeIndex
) {
3498 // Save the bitcode index of the start of this function block for recording
3500 FunctionToBitcodeIndex
[&F
] = Stream
.GetCurrentBitNo();
3502 Stream
.EnterSubblock(bitc::FUNCTION_BLOCK_ID
, 4);
3503 VE
.incorporateFunction(F
);
3505 SmallVector
<unsigned, 64> Vals
;
3507 // Emit the number of basic blocks, so the reader can create them ahead of
3509 Vals
.push_back(VE
.getBasicBlocks().size());
3510 Stream
.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS
, Vals
);
3513 // If there are function-local constants, emit them now.
3514 unsigned CstStart
, CstEnd
;
3515 VE
.getFunctionConstantRange(CstStart
, CstEnd
);
3516 writeConstants(CstStart
, CstEnd
, false);
3518 // If there is function-local metadata, emit it now.
3519 writeFunctionMetadata(F
);
3521 // Keep a running idea of what the instruction ID is.
3522 unsigned InstID
= CstEnd
;
3524 bool NeedsMetadataAttachment
= F
.hasMetadata();
3526 DILocation
*LastDL
= nullptr;
3527 SmallSetVector
<Function
*, 4> BlockAddressUsers
;
3529 // Finally, emit all the instructions, in order.
3530 for (const BasicBlock
&BB
: F
) {
3531 for (const Instruction
&I
: BB
) {
3532 writeInstruction(I
, InstID
, Vals
);
3534 if (!I
.getType()->isVoidTy())
3537 // If the instruction has metadata, write a metadata attachment later.
3538 NeedsMetadataAttachment
|= I
.hasMetadataOtherThanDebugLoc();
3540 // If the instruction has a debug location, emit it.
3541 if (DILocation
*DL
= I
.getDebugLoc()) {
3543 // Just repeat the same debug loc as last time.
3544 Stream
.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN
, Vals
);
3546 Vals
.push_back(DL
->getLine());
3547 Vals
.push_back(DL
->getColumn());
3548 Vals
.push_back(VE
.getMetadataOrNullID(DL
->getScope()));
3549 Vals
.push_back(VE
.getMetadataOrNullID(DL
->getInlinedAt()));
3550 Vals
.push_back(DL
->isImplicitCode());
3551 Stream
.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC
, Vals
);
3557 // If the instruction has DbgRecords attached to it, emit them. Note that
3558 // they come after the instruction so that it's easy to attach them again
3559 // when reading the bitcode, even though conceptually the debug locations
3560 // start "before" the instruction.
3561 if (I
.hasDbgRecords() && WriteNewDbgInfoFormatToBitcode
) {
3562 /// Try to push the value only (unwrapped), otherwise push the
3563 /// metadata wrapped value. Returns true if the value was pushed
3564 /// without the ValueAsMetadata wrapper.
3565 auto PushValueOrMetadata
= [&Vals
, InstID
,
3566 this](Metadata
*RawLocation
) {
3567 assert(RawLocation
&&
3568 "RawLocation unexpectedly null in DbgVariableRecord");
3569 if (ValueAsMetadata
*VAM
= dyn_cast
<ValueAsMetadata
>(RawLocation
)) {
3570 SmallVector
<unsigned, 2> ValAndType
;
3571 // If the value is a fwd-ref the type is also pushed. We don't
3572 // want the type, so fwd-refs are kept wrapped (pushValueAndType
3573 // returns false if the value is pushed without type).
3574 if (!pushValueAndType(VAM
->getValue(), InstID
, ValAndType
)) {
3575 Vals
.push_back(ValAndType
[0]);
3579 // The metadata is a DIArgList, or ValueAsMetadata wrapping a
3580 // fwd-ref. Push the metadata ID.
3581 Vals
.push_back(VE
.getMetadataID(RawLocation
));
3585 // Write out non-instruction debug information attached to this
3586 // instruction. Write it after the instruction so that it's easy to
3587 // re-attach to the instruction reading the records in.
3588 for (DbgRecord
&DR
: I
.DebugMarker
->getDbgRecordRange()) {
3589 if (DbgLabelRecord
*DLR
= dyn_cast
<DbgLabelRecord
>(&DR
)) {
3590 Vals
.push_back(VE
.getMetadataID(&*DLR
->getDebugLoc()));
3591 Vals
.push_back(VE
.getMetadataID(DLR
->getLabel()));
3592 Stream
.EmitRecord(bitc::FUNC_CODE_DEBUG_RECORD_LABEL
, Vals
);
3597 // First 3 fields are common to all kinds:
3598 // DILocation, DILocalVariable, DIExpression
3599 // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE)
3600 // ..., LocationMetadata
3601 // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE - abbrev'd)
3603 // dbg_declare (FUNC_CODE_DEBUG_RECORD_DECLARE)
3604 // ..., LocationMetadata
3605 // dbg_assign (FUNC_CODE_DEBUG_RECORD_ASSIGN)
3606 // ..., LocationMetadata, DIAssignID, DIExpression, LocationMetadata
3607 DbgVariableRecord
&DVR
= cast
<DbgVariableRecord
>(DR
);
3608 Vals
.push_back(VE
.getMetadataID(&*DVR
.getDebugLoc()));
3609 Vals
.push_back(VE
.getMetadataID(DVR
.getVariable()));
3610 Vals
.push_back(VE
.getMetadataID(DVR
.getExpression()));
3611 if (DVR
.isDbgValue()) {
3612 if (PushValueOrMetadata(DVR
.getRawLocation()))
3613 Stream
.EmitRecord(bitc::FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE
, Vals
,
3614 FUNCTION_DEBUG_RECORD_VALUE_ABBREV
);
3616 Stream
.EmitRecord(bitc::FUNC_CODE_DEBUG_RECORD_VALUE
, Vals
);
3617 } else if (DVR
.isDbgDeclare()) {
3618 Vals
.push_back(VE
.getMetadataID(DVR
.getRawLocation()));
3619 Stream
.EmitRecord(bitc::FUNC_CODE_DEBUG_RECORD_DECLARE
, Vals
);
3621 assert(DVR
.isDbgAssign() && "Unexpected DbgRecord kind");
3622 Vals
.push_back(VE
.getMetadataID(DVR
.getRawLocation()));
3623 Vals
.push_back(VE
.getMetadataID(DVR
.getAssignID()));
3624 Vals
.push_back(VE
.getMetadataID(DVR
.getAddressExpression()));
3625 Vals
.push_back(VE
.getMetadataID(DVR
.getRawAddress()));
3626 Stream
.EmitRecord(bitc::FUNC_CODE_DEBUG_RECORD_ASSIGN
, Vals
);
3633 if (BlockAddress
*BA
= BlockAddress::lookup(&BB
)) {
3634 SmallVector
<Value
*> Worklist
{BA
};
3635 SmallPtrSet
<Value
*, 8> Visited
{BA
};
3636 while (!Worklist
.empty()) {
3637 Value
*V
= Worklist
.pop_back_val();
3638 for (User
*U
: V
->users()) {
3639 if (auto *I
= dyn_cast
<Instruction
>(U
)) {
3640 Function
*P
= I
->getFunction();
3642 BlockAddressUsers
.insert(P
);
3643 } else if (isa
<Constant
>(U
) && !isa
<GlobalValue
>(U
) &&
3644 Visited
.insert(U
).second
)
3645 Worklist
.push_back(U
);
3651 if (!BlockAddressUsers
.empty()) {
3652 Vals
.resize(BlockAddressUsers
.size());
3653 for (auto I
: llvm::enumerate(BlockAddressUsers
))
3654 Vals
[I
.index()] = VE
.getValueID(I
.value());
3655 Stream
.EmitRecord(bitc::FUNC_CODE_BLOCKADDR_USERS
, Vals
);
3659 // Emit names for all the instructions etc.
3660 if (auto *Symtab
= F
.getValueSymbolTable())
3661 writeFunctionLevelValueSymbolTable(*Symtab
);
3663 if (NeedsMetadataAttachment
)
3664 writeFunctionMetadataAttachment(F
);
3665 if (VE
.shouldPreserveUseListOrder())
3666 writeUseListBlock(&F
);
3671 // Emit blockinfo, which defines the standard abbreviations etc.
3672 void ModuleBitcodeWriter::writeBlockInfo() {
3673 // We only want to emit block info records for blocks that have multiple
3674 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
3675 // Other blocks can define their abbrevs inline.
3676 Stream
.EnterBlockInfoBlock();
3678 { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
3679 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
3680 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 3));
3681 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8));
3682 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
3683 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 8));
3684 if (Stream
.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID
, Abbv
) !=
3686 llvm_unreachable("Unexpected abbrev ordering!");
3689 { // 7-bit fixed width VST_CODE_ENTRY strings.
3690 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
3691 Abbv
->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY
));
3692 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8));
3693 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
3694 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 7));
3695 if (Stream
.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID
, Abbv
) !=
3697 llvm_unreachable("Unexpected abbrev ordering!");
3699 { // 6-bit char6 VST_CODE_ENTRY strings.
3700 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
3701 Abbv
->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY
));
3702 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8));
3703 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
3704 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6
));
3705 if (Stream
.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID
, Abbv
) !=
3707 llvm_unreachable("Unexpected abbrev ordering!");
3709 { // 6-bit char6 VST_CODE_BBENTRY strings.
3710 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
3711 Abbv
->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY
));
3712 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8));
3713 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
3714 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6
));
3715 if (Stream
.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID
, Abbv
) !=
3716 VST_BBENTRY_6_ABBREV
)
3717 llvm_unreachable("Unexpected abbrev ordering!");
3720 { // SETTYPE abbrev for CONSTANTS_BLOCK.
3721 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
3722 Abbv
->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE
));
3723 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
,
3724 VE
.computeBitsRequiredForTypeIndicies()));
3725 if (Stream
.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID
, Abbv
) !=
3726 CONSTANTS_SETTYPE_ABBREV
)
3727 llvm_unreachable("Unexpected abbrev ordering!");
3730 { // INTEGER abbrev for CONSTANTS_BLOCK.
3731 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
3732 Abbv
->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER
));
3733 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8));
3734 if (Stream
.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID
, Abbv
) !=
3735 CONSTANTS_INTEGER_ABBREV
)
3736 llvm_unreachable("Unexpected abbrev ordering!");
3739 { // CE_CAST abbrev for CONSTANTS_BLOCK.
3740 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
3741 Abbv
->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST
));
3742 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 4)); // cast opc
3743 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, // typeid
3744 VE
.computeBitsRequiredForTypeIndicies()));
3745 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // value id
3747 if (Stream
.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID
, Abbv
) !=
3748 CONSTANTS_CE_CAST_Abbrev
)
3749 llvm_unreachable("Unexpected abbrev ordering!");
3751 { // NULL abbrev for CONSTANTS_BLOCK.
3752 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
3753 Abbv
->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL
));
3754 if (Stream
.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID
, Abbv
) !=
3755 CONSTANTS_NULL_Abbrev
)
3756 llvm_unreachable("Unexpected abbrev ordering!");
3759 // FIXME: This should only use space for first class types!
3761 { // INST_LOAD abbrev for FUNCTION_BLOCK.
3762 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
3763 Abbv
->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD
));
3764 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6)); // Ptr
3765 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, // dest ty
3766 VE
.computeBitsRequiredForTypeIndicies()));
3767 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 4)); // Align
3768 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 1)); // volatile
3769 if (Stream
.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID
, Abbv
) !=
3770 FUNCTION_INST_LOAD_ABBREV
)
3771 llvm_unreachable("Unexpected abbrev ordering!");
3773 { // INST_UNOP abbrev for FUNCTION_BLOCK.
3774 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
3775 Abbv
->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP
));
3776 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6)); // LHS
3777 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 4)); // opc
3778 if (Stream
.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID
, Abbv
) !=
3779 FUNCTION_INST_UNOP_ABBREV
)
3780 llvm_unreachable("Unexpected abbrev ordering!");
3782 { // INST_UNOP_FLAGS abbrev for FUNCTION_BLOCK.
3783 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
3784 Abbv
->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP
));
3785 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6)); // LHS
3786 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 4)); // opc
3787 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 8)); // flags
3788 if (Stream
.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID
, Abbv
) !=
3789 FUNCTION_INST_UNOP_FLAGS_ABBREV
)
3790 llvm_unreachable("Unexpected abbrev ordering!");
3792 { // INST_BINOP abbrev for FUNCTION_BLOCK.
3793 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
3794 Abbv
->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP
));
3795 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6)); // LHS
3796 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6)); // RHS
3797 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 4)); // opc
3798 if (Stream
.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID
, Abbv
) !=
3799 FUNCTION_INST_BINOP_ABBREV
)
3800 llvm_unreachable("Unexpected abbrev ordering!");
3802 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
3803 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
3804 Abbv
->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP
));
3805 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6)); // LHS
3806 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6)); // RHS
3807 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 4)); // opc
3808 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 8)); // flags
3809 if (Stream
.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID
, Abbv
) !=
3810 FUNCTION_INST_BINOP_FLAGS_ABBREV
)
3811 llvm_unreachable("Unexpected abbrev ordering!");
3813 { // INST_CAST abbrev for FUNCTION_BLOCK.
3814 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
3815 Abbv
->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST
));
3816 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6)); // OpVal
3817 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, // dest ty
3818 VE
.computeBitsRequiredForTypeIndicies()));
3819 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 4)); // opc
3820 if (Stream
.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID
, Abbv
) !=
3821 FUNCTION_INST_CAST_ABBREV
)
3822 llvm_unreachable("Unexpected abbrev ordering!");
3824 { // INST_CAST_FLAGS abbrev for FUNCTION_BLOCK.
3825 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
3826 Abbv
->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST
));
3827 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6)); // OpVal
3828 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, // dest ty
3829 VE
.computeBitsRequiredForTypeIndicies()));
3830 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 4)); // opc
3831 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 8)); // flags
3832 if (Stream
.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID
, Abbv
) !=
3833 FUNCTION_INST_CAST_FLAGS_ABBREV
)
3834 llvm_unreachable("Unexpected abbrev ordering!");
3837 { // INST_RET abbrev for FUNCTION_BLOCK.
3838 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
3839 Abbv
->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET
));
3840 if (Stream
.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID
, Abbv
) !=
3841 FUNCTION_INST_RET_VOID_ABBREV
)
3842 llvm_unreachable("Unexpected abbrev ordering!");
3844 { // INST_RET abbrev for FUNCTION_BLOCK.
3845 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
3846 Abbv
->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET
));
3847 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6)); // ValID
3848 if (Stream
.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID
, Abbv
) !=
3849 FUNCTION_INST_RET_VAL_ABBREV
)
3850 llvm_unreachable("Unexpected abbrev ordering!");
3852 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
3853 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
3854 Abbv
->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE
));
3855 if (Stream
.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID
, Abbv
) !=
3856 FUNCTION_INST_UNREACHABLE_ABBREV
)
3857 llvm_unreachable("Unexpected abbrev ordering!");
3860 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
3861 Abbv
->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP
));
3862 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 1));
3863 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, // dest ty
3864 Log2_32_Ceil(VE
.getTypes().size() + 1)));
3865 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
3866 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6));
3867 if (Stream
.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID
, Abbv
) !=
3868 FUNCTION_INST_GEP_ABBREV
)
3869 llvm_unreachable("Unexpected abbrev ordering!");
3872 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
3873 Abbv
->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE
));
3874 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 7)); // dbgloc
3875 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 7)); // var
3876 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 7)); // expr
3877 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6)); // val
3878 if (Stream
.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID
, Abbv
) !=
3879 FUNCTION_DEBUG_RECORD_VALUE_ABBREV
)
3880 llvm_unreachable("Unexpected abbrev ordering! 1");
3885 /// Write the module path strings, currently only used when generating
3886 /// a combined index file.
3887 void IndexBitcodeWriter::writeModStrings() {
3888 Stream
.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID
, 3);
3890 // TODO: See which abbrev sizes we actually need to emit
3892 // 8-bit fixed-width MST_ENTRY strings.
3893 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
3894 Abbv
->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY
));
3895 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8));
3896 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
3897 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 8));
3898 unsigned Abbrev8Bit
= Stream
.EmitAbbrev(std::move(Abbv
));
3900 // 7-bit fixed width MST_ENTRY strings.
3901 Abbv
= std::make_shared
<BitCodeAbbrev
>();
3902 Abbv
->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY
));
3903 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8));
3904 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
3905 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 7));
3906 unsigned Abbrev7Bit
= Stream
.EmitAbbrev(std::move(Abbv
));
3908 // 6-bit char6 MST_ENTRY strings.
3909 Abbv
= std::make_shared
<BitCodeAbbrev
>();
3910 Abbv
->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY
));
3911 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8));
3912 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
3913 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6
));
3914 unsigned Abbrev6Bit
= Stream
.EmitAbbrev(std::move(Abbv
));
3916 // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
3917 Abbv
= std::make_shared
<BitCodeAbbrev
>();
3918 Abbv
->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH
));
3919 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 32));
3920 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 32));
3921 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 32));
3922 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 32));
3923 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 32));
3924 unsigned AbbrevHash
= Stream
.EmitAbbrev(std::move(Abbv
));
3926 SmallVector
<unsigned, 64> Vals
;
3927 forEachModule([&](const StringMapEntry
<ModuleHash
> &MPSE
) {
3928 StringRef Key
= MPSE
.getKey();
3929 const auto &Hash
= MPSE
.getValue();
3930 StringEncoding Bits
= getStringEncoding(Key
);
3931 unsigned AbbrevToUse
= Abbrev8Bit
;
3932 if (Bits
== SE_Char6
)
3933 AbbrevToUse
= Abbrev6Bit
;
3934 else if (Bits
== SE_Fixed7
)
3935 AbbrevToUse
= Abbrev7Bit
;
3937 auto ModuleId
= ModuleIdMap
.size();
3938 ModuleIdMap
[Key
] = ModuleId
;
3939 Vals
.push_back(ModuleId
);
3940 Vals
.append(Key
.begin(), Key
.end());
3942 // Emit the finished record.
3943 Stream
.EmitRecord(bitc::MST_CODE_ENTRY
, Vals
, AbbrevToUse
);
3945 // Emit an optional hash for the module now
3946 if (llvm::any_of(Hash
, [](uint32_t H
) { return H
; })) {
3947 Vals
.assign(Hash
.begin(), Hash
.end());
3948 // Emit the hash record.
3949 Stream
.EmitRecord(bitc::MST_CODE_HASH
, Vals
, AbbrevHash
);
3957 /// Write the function type metadata related records that need to appear before
3958 /// a function summary entry (whether per-module or combined).
3959 template <typename Fn
>
3960 static void writeFunctionTypeMetadataRecords(BitstreamWriter
&Stream
,
3961 FunctionSummary
*FS
,
3963 if (!FS
->type_tests().empty())
3964 Stream
.EmitRecord(bitc::FS_TYPE_TESTS
, FS
->type_tests());
3966 SmallVector
<uint64_t, 64> Record
;
3968 auto WriteVFuncIdVec
= [&](uint64_t Ty
,
3969 ArrayRef
<FunctionSummary::VFuncId
> VFs
) {
3973 for (auto &VF
: VFs
) {
3974 Record
.push_back(VF
.GUID
);
3975 Record
.push_back(VF
.Offset
);
3977 Stream
.EmitRecord(Ty
, Record
);
3980 WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS
,
3981 FS
->type_test_assume_vcalls());
3982 WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS
,
3983 FS
->type_checked_load_vcalls());
3985 auto WriteConstVCallVec
= [&](uint64_t Ty
,
3986 ArrayRef
<FunctionSummary::ConstVCall
> VCs
) {
3987 for (auto &VC
: VCs
) {
3989 Record
.push_back(VC
.VFunc
.GUID
);
3990 Record
.push_back(VC
.VFunc
.Offset
);
3991 llvm::append_range(Record
, VC
.Args
);
3992 Stream
.EmitRecord(Ty
, Record
);
3996 WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL
,
3997 FS
->type_test_assume_const_vcalls());
3998 WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL
,
3999 FS
->type_checked_load_const_vcalls());
4001 auto WriteRange
= [&](ConstantRange Range
) {
4002 Range
= Range
.sextOrTrunc(FunctionSummary::ParamAccess::RangeWidth
);
4003 assert(Range
.getLower().getNumWords() == 1);
4004 assert(Range
.getUpper().getNumWords() == 1);
4005 emitSignedInt64(Record
, *Range
.getLower().getRawData());
4006 emitSignedInt64(Record
, *Range
.getUpper().getRawData());
4009 if (!FS
->paramAccesses().empty()) {
4011 for (auto &Arg
: FS
->paramAccesses()) {
4012 size_t UndoSize
= Record
.size();
4013 Record
.push_back(Arg
.ParamNo
);
4014 WriteRange(Arg
.Use
);
4015 Record
.push_back(Arg
.Calls
.size());
4016 for (auto &Call
: Arg
.Calls
) {
4017 Record
.push_back(Call
.ParamNo
);
4018 std::optional
<unsigned> ValueID
= GetValueID(Call
.Callee
);
4020 // If ValueID is unknown we can't drop just this call, we must drop
4021 // entire parameter.
4022 Record
.resize(UndoSize
);
4025 Record
.push_back(*ValueID
);
4026 WriteRange(Call
.Offsets
);
4029 if (!Record
.empty())
4030 Stream
.EmitRecord(bitc::FS_PARAM_ACCESS
, Record
);
4034 /// Collect type IDs from type tests used by function.
4036 getReferencedTypeIds(FunctionSummary
*FS
,
4037 std::set
<GlobalValue::GUID
> &ReferencedTypeIds
) {
4038 if (!FS
->type_tests().empty())
4039 for (auto &TT
: FS
->type_tests())
4040 ReferencedTypeIds
.insert(TT
);
4042 auto GetReferencedTypesFromVFuncIdVec
=
4043 [&](ArrayRef
<FunctionSummary::VFuncId
> VFs
) {
4044 for (auto &VF
: VFs
)
4045 ReferencedTypeIds
.insert(VF
.GUID
);
4048 GetReferencedTypesFromVFuncIdVec(FS
->type_test_assume_vcalls());
4049 GetReferencedTypesFromVFuncIdVec(FS
->type_checked_load_vcalls());
4051 auto GetReferencedTypesFromConstVCallVec
=
4052 [&](ArrayRef
<FunctionSummary::ConstVCall
> VCs
) {
4053 for (auto &VC
: VCs
)
4054 ReferencedTypeIds
.insert(VC
.VFunc
.GUID
);
4057 GetReferencedTypesFromConstVCallVec(FS
->type_test_assume_const_vcalls());
4058 GetReferencedTypesFromConstVCallVec(FS
->type_checked_load_const_vcalls());
4061 static void writeWholeProgramDevirtResolutionByArg(
4062 SmallVector
<uint64_t, 64> &NameVals
, const std::vector
<uint64_t> &args
,
4063 const WholeProgramDevirtResolution::ByArg
&ByArg
) {
4064 NameVals
.push_back(args
.size());
4065 llvm::append_range(NameVals
, args
);
4067 NameVals
.push_back(ByArg
.TheKind
);
4068 NameVals
.push_back(ByArg
.Info
);
4069 NameVals
.push_back(ByArg
.Byte
);
4070 NameVals
.push_back(ByArg
.Bit
);
4073 static void writeWholeProgramDevirtResolution(
4074 SmallVector
<uint64_t, 64> &NameVals
, StringTableBuilder
&StrtabBuilder
,
4075 uint64_t Id
, const WholeProgramDevirtResolution
&Wpd
) {
4076 NameVals
.push_back(Id
);
4078 NameVals
.push_back(Wpd
.TheKind
);
4079 NameVals
.push_back(StrtabBuilder
.add(Wpd
.SingleImplName
));
4080 NameVals
.push_back(Wpd
.SingleImplName
.size());
4082 NameVals
.push_back(Wpd
.ResByArg
.size());
4083 for (auto &A
: Wpd
.ResByArg
)
4084 writeWholeProgramDevirtResolutionByArg(NameVals
, A
.first
, A
.second
);
4087 static void writeTypeIdSummaryRecord(SmallVector
<uint64_t, 64> &NameVals
,
4088 StringTableBuilder
&StrtabBuilder
,
4089 const std::string
&Id
,
4090 const TypeIdSummary
&Summary
) {
4091 NameVals
.push_back(StrtabBuilder
.add(Id
));
4092 NameVals
.push_back(Id
.size());
4094 NameVals
.push_back(Summary
.TTRes
.TheKind
);
4095 NameVals
.push_back(Summary
.TTRes
.SizeM1BitWidth
);
4096 NameVals
.push_back(Summary
.TTRes
.AlignLog2
);
4097 NameVals
.push_back(Summary
.TTRes
.SizeM1
);
4098 NameVals
.push_back(Summary
.TTRes
.BitMask
);
4099 NameVals
.push_back(Summary
.TTRes
.InlineBits
);
4101 for (auto &W
: Summary
.WPDRes
)
4102 writeWholeProgramDevirtResolution(NameVals
, StrtabBuilder
, W
.first
,
4106 static void writeTypeIdCompatibleVtableSummaryRecord(
4107 SmallVector
<uint64_t, 64> &NameVals
, StringTableBuilder
&StrtabBuilder
,
4108 const std::string
&Id
, const TypeIdCompatibleVtableInfo
&Summary
,
4109 ValueEnumerator
&VE
) {
4110 NameVals
.push_back(StrtabBuilder
.add(Id
));
4111 NameVals
.push_back(Id
.size());
4113 for (auto &P
: Summary
) {
4114 NameVals
.push_back(P
.AddressPointOffset
);
4115 NameVals
.push_back(VE
.getValueID(P
.VTableVI
.getValue()));
4119 static void writeFunctionHeapProfileRecords(
4120 BitstreamWriter
&Stream
, FunctionSummary
*FS
, unsigned CallsiteAbbrev
,
4121 unsigned AllocAbbrev
, bool PerModule
,
4122 std::function
<unsigned(const ValueInfo
&VI
)> GetValueID
,
4123 std::function
<unsigned(unsigned)> GetStackIndex
) {
4124 SmallVector
<uint64_t> Record
;
4126 for (auto &CI
: FS
->callsites()) {
4128 // Per module callsite clones should always have a single entry of
4130 assert(!PerModule
|| (CI
.Clones
.size() == 1 && CI
.Clones
[0] == 0));
4131 Record
.push_back(GetValueID(CI
.Callee
));
4133 Record
.push_back(CI
.StackIdIndices
.size());
4134 Record
.push_back(CI
.Clones
.size());
4136 for (auto Id
: CI
.StackIdIndices
)
4137 Record
.push_back(GetStackIndex(Id
));
4139 for (auto V
: CI
.Clones
)
4140 Record
.push_back(V
);
4142 Stream
.EmitRecord(PerModule
? bitc::FS_PERMODULE_CALLSITE_INFO
4143 : bitc::FS_COMBINED_CALLSITE_INFO
,
4144 Record
, CallsiteAbbrev
);
4147 for (auto &AI
: FS
->allocs()) {
4149 // Per module alloc versions should always have a single entry of
4151 assert(!PerModule
|| (AI
.Versions
.size() == 1 && AI
.Versions
[0] == 0));
4153 Record
.push_back(AI
.MIBs
.size());
4154 Record
.push_back(AI
.Versions
.size());
4156 for (auto &MIB
: AI
.MIBs
) {
4157 Record
.push_back((uint8_t)MIB
.AllocType
);
4158 Record
.push_back(MIB
.StackIdIndices
.size());
4159 for (auto Id
: MIB
.StackIdIndices
)
4160 Record
.push_back(GetStackIndex(Id
));
4163 for (auto V
: AI
.Versions
)
4164 Record
.push_back(V
);
4166 Stream
.EmitRecord(PerModule
? bitc::FS_PERMODULE_ALLOC_INFO
4167 : bitc::FS_COMBINED_ALLOC_INFO
,
4168 Record
, AllocAbbrev
);
4172 // Helper to emit a single function summary record.
4173 void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
4174 SmallVector
<uint64_t, 64> &NameVals
, GlobalValueSummary
*Summary
,
4175 unsigned ValueID
, unsigned FSCallsRelBFAbbrev
,
4176 unsigned FSCallsProfileAbbrev
, unsigned CallsiteAbbrev
,
4177 unsigned AllocAbbrev
, const Function
&F
) {
4178 NameVals
.push_back(ValueID
);
4180 FunctionSummary
*FS
= cast
<FunctionSummary
>(Summary
);
4182 writeFunctionTypeMetadataRecords(
4183 Stream
, FS
, [&](const ValueInfo
&VI
) -> std::optional
<unsigned> {
4184 return {VE
.getValueID(VI
.getValue())};
4187 writeFunctionHeapProfileRecords(
4188 Stream
, FS
, CallsiteAbbrev
, AllocAbbrev
,
4190 /*GetValueId*/ [&](const ValueInfo
&VI
) { return getValueId(VI
); },
4191 /*GetStackIndex*/ [&](unsigned I
) { return I
; });
4193 auto SpecialRefCnts
= FS
->specialRefCounts();
4194 NameVals
.push_back(getEncodedGVSummaryFlags(FS
->flags()));
4195 NameVals
.push_back(FS
->instCount());
4196 NameVals
.push_back(getEncodedFFlags(FS
->fflags()));
4197 NameVals
.push_back(FS
->refs().size());
4198 NameVals
.push_back(SpecialRefCnts
.first
); // rorefcnt
4199 NameVals
.push_back(SpecialRefCnts
.second
); // worefcnt
4201 for (auto &RI
: FS
->refs())
4202 NameVals
.push_back(getValueId(RI
));
4204 const bool UseRelBFRecord
=
4205 WriteRelBFToSummary
&& !F
.hasProfileData() &&
4206 ForceSummaryEdgesCold
== FunctionSummary::FSHT_None
;
4207 for (auto &ECI
: FS
->calls()) {
4208 NameVals
.push_back(getValueId(ECI
.first
));
4210 NameVals
.push_back(getEncodedRelBFCallEdgeInfo(ECI
.second
));
4212 NameVals
.push_back(getEncodedHotnessCallEdgeInfo(ECI
.second
));
4216 (UseRelBFRecord
? FSCallsRelBFAbbrev
: FSCallsProfileAbbrev
);
4218 (UseRelBFRecord
? bitc::FS_PERMODULE_RELBF
: bitc::FS_PERMODULE_PROFILE
);
4220 // Emit the finished record.
4221 Stream
.EmitRecord(Code
, NameVals
, FSAbbrev
);
4225 // Collect the global value references in the given variable's initializer,
4226 // and emit them in a summary record.
4227 void ModuleBitcodeWriterBase::writeModuleLevelReferences(
4228 const GlobalVariable
&V
, SmallVector
<uint64_t, 64> &NameVals
,
4229 unsigned FSModRefsAbbrev
, unsigned FSModVTableRefsAbbrev
) {
4230 auto VI
= Index
->getValueInfo(V
.getGUID());
4231 if (!VI
|| VI
.getSummaryList().empty()) {
4232 // Only declarations should not have a summary (a declaration might however
4233 // have a summary if the def was in module level asm).
4234 assert(V
.isDeclaration());
4237 auto *Summary
= VI
.getSummaryList()[0].get();
4238 NameVals
.push_back(VE
.getValueID(&V
));
4239 GlobalVarSummary
*VS
= cast
<GlobalVarSummary
>(Summary
);
4240 NameVals
.push_back(getEncodedGVSummaryFlags(VS
->flags()));
4241 NameVals
.push_back(getEncodedGVarFlags(VS
->varflags()));
4243 auto VTableFuncs
= VS
->vTableFuncs();
4244 if (!VTableFuncs
.empty())
4245 NameVals
.push_back(VS
->refs().size());
4247 unsigned SizeBeforeRefs
= NameVals
.size();
4248 for (auto &RI
: VS
->refs())
4249 NameVals
.push_back(VE
.getValueID(RI
.getValue()));
4250 // Sort the refs for determinism output, the vector returned by FS->refs() has
4251 // been initialized from a DenseSet.
4252 llvm::sort(drop_begin(NameVals
, SizeBeforeRefs
));
4254 if (VTableFuncs
.empty())
4255 Stream
.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS
, NameVals
,
4258 // VTableFuncs pairs should already be sorted by offset.
4259 for (auto &P
: VTableFuncs
) {
4260 NameVals
.push_back(VE
.getValueID(P
.FuncVI
.getValue()));
4261 NameVals
.push_back(P
.VTableOffset
);
4264 Stream
.EmitRecord(bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS
, NameVals
,
4265 FSModVTableRefsAbbrev
);
4270 /// Emit the per-module summary section alongside the rest of
4271 /// the module's bitcode.
4272 void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
4273 // By default we compile with ThinLTO if the module has a summary, but the
4274 // client can request full LTO with a module flag.
4275 bool IsThinLTO
= true;
4277 mdconst::extract_or_null
<ConstantInt
>(M
.getModuleFlag("ThinLTO")))
4278 IsThinLTO
= MD
->getZExtValue();
4279 Stream
.EnterSubblock(IsThinLTO
? bitc::GLOBALVAL_SUMMARY_BLOCK_ID
4280 : bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID
,
4285 ArrayRef
<uint64_t>{ModuleSummaryIndex::BitcodeSummaryVersion
});
4287 // Write the index flags.
4289 // Bits 1-3 are set only in the combined index, skip them.
4290 if (Index
->enableSplitLTOUnit())
4292 if (Index
->hasUnifiedLTO())
4295 Stream
.EmitRecord(bitc::FS_FLAGS
, ArrayRef
<uint64_t>{Flags
});
4297 if (Index
->begin() == Index
->end()) {
4302 for (const auto &GVI
: valueIds()) {
4303 Stream
.EmitRecord(bitc::FS_VALUE_GUID
,
4304 ArrayRef
<uint64_t>{GVI
.second
, GVI
.first
});
4307 if (!Index
->stackIds().empty()) {
4308 auto StackIdAbbv
= std::make_shared
<BitCodeAbbrev
>();
4309 StackIdAbbv
->Add(BitCodeAbbrevOp(bitc::FS_STACK_IDS
));
4311 StackIdAbbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
4312 StackIdAbbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8));
4313 unsigned StackIdAbbvId
= Stream
.EmitAbbrev(std::move(StackIdAbbv
));
4314 Stream
.EmitRecord(bitc::FS_STACK_IDS
, Index
->stackIds(), StackIdAbbvId
);
4317 // Abbrev for FS_PERMODULE_PROFILE.
4318 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
4319 Abbv
->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE
));
4320 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // valueid
4321 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // flags
4322 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // instcount
4323 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 4)); // fflags
4324 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 4)); // numrefs
4325 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 4)); // rorefcnt
4326 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 4)); // worefcnt
4327 // numrefs x valueid, n x (valueid, hotness+tailcall flags)
4328 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
4329 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8));
4330 unsigned FSCallsProfileAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
4332 // Abbrev for FS_PERMODULE_RELBF.
4333 Abbv
= std::make_shared
<BitCodeAbbrev
>();
4334 Abbv
->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_RELBF
));
4335 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // valueid
4336 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6)); // flags
4337 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // instcount
4338 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 4)); // fflags
4339 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 4)); // numrefs
4340 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 4)); // rorefcnt
4341 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 4)); // worefcnt
4342 // numrefs x valueid, n x (valueid, rel_block_freq+tailcall])
4343 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
4344 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8));
4345 unsigned FSCallsRelBFAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
4347 // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
4348 Abbv
= std::make_shared
<BitCodeAbbrev
>();
4349 Abbv
->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS
));
4350 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // valueid
4351 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6)); // flags
4352 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
)); // valueids
4353 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8));
4354 unsigned FSModRefsAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
4356 // Abbrev for FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS.
4357 Abbv
= std::make_shared
<BitCodeAbbrev
>();
4358 Abbv
->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS
));
4359 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // valueid
4360 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6)); // flags
4361 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 4)); // numrefs
4362 // numrefs x valueid, n x (valueid , offset)
4363 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
4364 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8));
4365 unsigned FSModVTableRefsAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
4367 // Abbrev for FS_ALIAS.
4368 Abbv
= std::make_shared
<BitCodeAbbrev
>();
4369 Abbv
->Add(BitCodeAbbrevOp(bitc::FS_ALIAS
));
4370 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // valueid
4371 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6)); // flags
4372 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // valueid
4373 unsigned FSAliasAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
4375 // Abbrev for FS_TYPE_ID_METADATA
4376 Abbv
= std::make_shared
<BitCodeAbbrev
>();
4377 Abbv
->Add(BitCodeAbbrevOp(bitc::FS_TYPE_ID_METADATA
));
4378 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // typeid strtab index
4379 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // typeid length
4380 // n x (valueid , offset)
4381 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
4382 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8));
4383 unsigned TypeIdCompatibleVtableAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
4385 Abbv
= std::make_shared
<BitCodeAbbrev
>();
4386 Abbv
->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_CALLSITE_INFO
));
4387 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // valueid
4389 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
4390 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8));
4391 unsigned CallsiteAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
4393 Abbv
= std::make_shared
<BitCodeAbbrev
>();
4394 Abbv
->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_ALLOC_INFO
));
4395 // n x (alloc type, numstackids, numstackids x stackidindex)
4396 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
4397 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8));
4398 unsigned AllocAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
4400 SmallVector
<uint64_t, 64> NameVals
;
4401 // Iterate over the list of functions instead of the Index to
4402 // ensure the ordering is stable.
4403 for (const Function
&F
: M
) {
4404 // Summary emission does not support anonymous functions, they have to
4405 // renamed using the anonymous function renaming pass.
4407 report_fatal_error("Unexpected anonymous function when writing summary");
4409 ValueInfo VI
= Index
->getValueInfo(F
.getGUID());
4410 if (!VI
|| VI
.getSummaryList().empty()) {
4411 // Only declarations should not have a summary (a declaration might
4412 // however have a summary if the def was in module level asm).
4413 assert(F
.isDeclaration());
4416 auto *Summary
= VI
.getSummaryList()[0].get();
4417 writePerModuleFunctionSummaryRecord(
4418 NameVals
, Summary
, VE
.getValueID(&F
), FSCallsRelBFAbbrev
,
4419 FSCallsProfileAbbrev
, CallsiteAbbrev
, AllocAbbrev
, F
);
4422 // Capture references from GlobalVariable initializers, which are outside
4423 // of a function scope.
4424 for (const GlobalVariable
&G
: M
.globals())
4425 writeModuleLevelReferences(G
, NameVals
, FSModRefsAbbrev
,
4426 FSModVTableRefsAbbrev
);
4428 for (const GlobalAlias
&A
: M
.aliases()) {
4429 auto *Aliasee
= A
.getAliaseeObject();
4430 // Skip ifunc and nameless functions which don't have an entry in the
4432 if (!Aliasee
->hasName() || isa
<GlobalIFunc
>(Aliasee
))
4434 auto AliasId
= VE
.getValueID(&A
);
4435 auto AliaseeId
= VE
.getValueID(Aliasee
);
4436 NameVals
.push_back(AliasId
);
4437 auto *Summary
= Index
->getGlobalValueSummary(A
);
4438 AliasSummary
*AS
= cast
<AliasSummary
>(Summary
);
4439 NameVals
.push_back(getEncodedGVSummaryFlags(AS
->flags()));
4440 NameVals
.push_back(AliaseeId
);
4441 Stream
.EmitRecord(bitc::FS_ALIAS
, NameVals
, FSAliasAbbrev
);
4445 for (auto &S
: Index
->typeIdCompatibleVtableMap()) {
4446 writeTypeIdCompatibleVtableSummaryRecord(NameVals
, StrtabBuilder
, S
.first
,
4448 Stream
.EmitRecord(bitc::FS_TYPE_ID_METADATA
, NameVals
,
4449 TypeIdCompatibleVtableAbbrev
);
4453 if (Index
->getBlockCount())
4454 Stream
.EmitRecord(bitc::FS_BLOCK_COUNT
,
4455 ArrayRef
<uint64_t>{Index
->getBlockCount()});
4460 /// Emit the combined summary section into the combined index file.
4461 void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
4462 Stream
.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID
, 4);
4465 ArrayRef
<uint64_t>{ModuleSummaryIndex::BitcodeSummaryVersion
});
4467 // Write the index flags.
4468 Stream
.EmitRecord(bitc::FS_FLAGS
, ArrayRef
<uint64_t>{Index
.getFlags()});
4470 for (const auto &GVI
: valueIds()) {
4471 Stream
.EmitRecord(bitc::FS_VALUE_GUID
,
4472 ArrayRef
<uint64_t>{GVI
.second
, GVI
.first
});
4475 if (!StackIdIndices
.empty()) {
4476 auto StackIdAbbv
= std::make_shared
<BitCodeAbbrev
>();
4477 StackIdAbbv
->Add(BitCodeAbbrevOp(bitc::FS_STACK_IDS
));
4479 StackIdAbbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
4480 StackIdAbbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8));
4481 unsigned StackIdAbbvId
= Stream
.EmitAbbrev(std::move(StackIdAbbv
));
4482 // Write the stack ids used by this index, which will be a subset of those in
4483 // the full index in the case of distributed indexes.
4484 std::vector
<uint64_t> StackIds
;
4485 for (auto &I
: StackIdIndices
)
4486 StackIds
.push_back(Index
.getStackIdAtIndex(I
));
4487 Stream
.EmitRecord(bitc::FS_STACK_IDS
, StackIds
, StackIdAbbvId
);
4490 // Abbrev for FS_COMBINED_PROFILE.
4491 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
4492 Abbv
->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE
));
4493 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // valueid
4494 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // modid
4495 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6)); // flags
4496 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // instcount
4497 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 4)); // fflags
4498 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // entrycount
4499 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 4)); // numrefs
4500 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 4)); // rorefcnt
4501 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 4)); // worefcnt
4502 // numrefs x valueid, n x (valueid, hotness+tailcall flags)
4503 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
4504 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8));
4505 unsigned FSCallsProfileAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
4507 // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
4508 Abbv
= std::make_shared
<BitCodeAbbrev
>();
4509 Abbv
->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS
));
4510 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // valueid
4511 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // modid
4512 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6)); // flags
4513 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
)); // valueids
4514 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8));
4515 unsigned FSModRefsAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
4517 // Abbrev for FS_COMBINED_ALIAS.
4518 Abbv
= std::make_shared
<BitCodeAbbrev
>();
4519 Abbv
->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS
));
4520 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // valueid
4521 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // modid
4522 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6)); // flags
4523 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // valueid
4524 unsigned FSAliasAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
4526 Abbv
= std::make_shared
<BitCodeAbbrev
>();
4527 Abbv
->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_CALLSITE_INFO
));
4528 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // valueid
4529 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 4)); // numstackindices
4530 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 4)); // numver
4531 // numstackindices x stackidindex, numver x version
4532 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
4533 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8));
4534 unsigned CallsiteAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
4536 Abbv
= std::make_shared
<BitCodeAbbrev
>();
4537 Abbv
->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALLOC_INFO
));
4538 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 4)); // nummib
4539 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 4)); // numver
4540 // nummib x (alloc type, numstackids, numstackids x stackidindex),
4542 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
4543 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8));
4544 unsigned AllocAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
4546 // The aliases are emitted as a post-pass, and will point to the value
4547 // id of the aliasee. Save them in a vector for post-processing.
4548 SmallVector
<AliasSummary
*, 64> Aliases
;
4550 // Save the value id for each summary for alias emission.
4551 DenseMap
<const GlobalValueSummary
*, unsigned> SummaryToValueIdMap
;
4553 SmallVector
<uint64_t, 64> NameVals
;
4555 // Set that will be populated during call to writeFunctionTypeMetadataRecords
4556 // with the type ids referenced by this index file.
4557 std::set
<GlobalValue::GUID
> ReferencedTypeIds
;
4559 // For local linkage, we also emit the original name separately
4560 // immediately after the record.
4561 auto MaybeEmitOriginalName
= [&](GlobalValueSummary
&S
) {
4562 // We don't need to emit the original name if we are writing the index for
4563 // distributed backends (in which case ModuleToSummariesForIndex is
4564 // non-null). The original name is only needed during the thin link, since
4565 // for SamplePGO the indirect call targets for local functions have
4566 // have the original name annotated in profile.
4567 // Continue to emit it when writing out the entire combined index, which is
4568 // used in testing the thin link via llvm-lto.
4569 if (ModuleToSummariesForIndex
|| !GlobalValue::isLocalLinkage(S
.linkage()))
4571 NameVals
.push_back(S
.getOriginalName());
4572 Stream
.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME
, NameVals
);
4576 std::set
<GlobalValue::GUID
> DefOrUseGUIDs
;
4577 forEachSummary([&](GVInfo I
, bool IsAliasee
) {
4578 GlobalValueSummary
*S
= I
.second
;
4580 DefOrUseGUIDs
.insert(I
.first
);
4581 for (const ValueInfo
&VI
: S
->refs())
4582 DefOrUseGUIDs
.insert(VI
.getGUID());
4584 auto ValueId
= getValueId(I
.first
);
4586 SummaryToValueIdMap
[S
] = *ValueId
;
4588 // If this is invoked for an aliasee, we want to record the above
4589 // mapping, but then not emit a summary entry (if the aliasee is
4590 // to be imported, we will invoke this separately with IsAliasee=false).
4594 if (auto *AS
= dyn_cast
<AliasSummary
>(S
)) {
4595 // Will process aliases as a post-pass because the reader wants all
4596 // global to be loaded first.
4597 Aliases
.push_back(AS
);
4601 if (auto *VS
= dyn_cast
<GlobalVarSummary
>(S
)) {
4602 NameVals
.push_back(*ValueId
);
4603 assert(ModuleIdMap
.count(VS
->modulePath()));
4604 NameVals
.push_back(ModuleIdMap
[VS
->modulePath()]);
4605 NameVals
.push_back(getEncodedGVSummaryFlags(VS
->flags()));
4606 NameVals
.push_back(getEncodedGVarFlags(VS
->varflags()));
4607 for (auto &RI
: VS
->refs()) {
4608 auto RefValueId
= getValueId(RI
.getGUID());
4611 NameVals
.push_back(*RefValueId
);
4614 // Emit the finished record.
4615 Stream
.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS
, NameVals
,
4618 MaybeEmitOriginalName(*S
);
4622 auto GetValueId
= [&](const ValueInfo
&VI
) -> std::optional
<unsigned> {
4624 return std::nullopt
;
4625 return getValueId(VI
.getGUID());
4628 auto *FS
= cast
<FunctionSummary
>(S
);
4629 writeFunctionTypeMetadataRecords(Stream
, FS
, GetValueId
);
4630 getReferencedTypeIds(FS
, ReferencedTypeIds
);
4632 writeFunctionHeapProfileRecords(
4633 Stream
, FS
, CallsiteAbbrev
, AllocAbbrev
,
4634 /*PerModule*/ false,
4635 /*GetValueId*/ [&](const ValueInfo
&VI
) -> unsigned {
4636 std::optional
<unsigned> ValueID
= GetValueId(VI
);
4637 // This can happen in shared index files for distributed ThinLTO if
4638 // the callee function summary is not included. Record 0 which we
4639 // will have to deal with conservatively when doing any kind of
4640 // validation in the ThinLTO backends.
4645 /*GetStackIndex*/ [&](unsigned I
) {
4646 // Get the corresponding index into the list of StackIdIndices
4647 // actually being written for this combined index (which may be a
4648 // subset in the case of distributed indexes).
4649 auto Lower
= llvm::lower_bound(StackIdIndices
, I
);
4650 return std::distance(StackIdIndices
.begin(), Lower
);
4653 NameVals
.push_back(*ValueId
);
4654 assert(ModuleIdMap
.count(FS
->modulePath()));
4655 NameVals
.push_back(ModuleIdMap
[FS
->modulePath()]);
4656 NameVals
.push_back(getEncodedGVSummaryFlags(FS
->flags()));
4657 NameVals
.push_back(FS
->instCount());
4658 NameVals
.push_back(getEncodedFFlags(FS
->fflags()));
4659 NameVals
.push_back(FS
->entryCount());
4662 NameVals
.push_back(0); // numrefs
4663 NameVals
.push_back(0); // rorefcnt
4664 NameVals
.push_back(0); // worefcnt
4666 unsigned Count
= 0, RORefCnt
= 0, WORefCnt
= 0;
4667 for (auto &RI
: FS
->refs()) {
4668 auto RefValueId
= getValueId(RI
.getGUID());
4671 NameVals
.push_back(*RefValueId
);
4672 if (RI
.isReadOnly())
4674 else if (RI
.isWriteOnly())
4678 NameVals
[6] = Count
;
4679 NameVals
[7] = RORefCnt
;
4680 NameVals
[8] = WORefCnt
;
4682 for (auto &EI
: FS
->calls()) {
4683 // If this GUID doesn't have a value id, it doesn't have a function
4684 // summary and we don't need to record any calls to it.
4685 std::optional
<unsigned> CallValueId
= GetValueId(EI
.first
);
4688 NameVals
.push_back(*CallValueId
);
4689 NameVals
.push_back(getEncodedHotnessCallEdgeInfo(EI
.second
));
4692 // Emit the finished record.
4693 Stream
.EmitRecord(bitc::FS_COMBINED_PROFILE
, NameVals
,
4694 FSCallsProfileAbbrev
);
4696 MaybeEmitOriginalName(*S
);
4699 for (auto *AS
: Aliases
) {
4700 auto AliasValueId
= SummaryToValueIdMap
[AS
];
4701 assert(AliasValueId
);
4702 NameVals
.push_back(AliasValueId
);
4703 assert(ModuleIdMap
.count(AS
->modulePath()));
4704 NameVals
.push_back(ModuleIdMap
[AS
->modulePath()]);
4705 NameVals
.push_back(getEncodedGVSummaryFlags(AS
->flags()));
4706 auto AliaseeValueId
= SummaryToValueIdMap
[&AS
->getAliasee()];
4707 assert(AliaseeValueId
);
4708 NameVals
.push_back(AliaseeValueId
);
4710 // Emit the finished record.
4711 Stream
.EmitRecord(bitc::FS_COMBINED_ALIAS
, NameVals
, FSAliasAbbrev
);
4713 MaybeEmitOriginalName(*AS
);
4715 if (auto *FS
= dyn_cast
<FunctionSummary
>(&AS
->getAliasee()))
4716 getReferencedTypeIds(FS
, ReferencedTypeIds
);
4719 if (!Index
.cfiFunctionDefs().empty()) {
4720 for (auto &S
: Index
.cfiFunctionDefs()) {
4721 if (DefOrUseGUIDs
.count(
4722 GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(S
)))) {
4723 NameVals
.push_back(StrtabBuilder
.add(S
));
4724 NameVals
.push_back(S
.size());
4727 if (!NameVals
.empty()) {
4728 Stream
.EmitRecord(bitc::FS_CFI_FUNCTION_DEFS
, NameVals
);
4733 if (!Index
.cfiFunctionDecls().empty()) {
4734 for (auto &S
: Index
.cfiFunctionDecls()) {
4735 if (DefOrUseGUIDs
.count(
4736 GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(S
)))) {
4737 NameVals
.push_back(StrtabBuilder
.add(S
));
4738 NameVals
.push_back(S
.size());
4741 if (!NameVals
.empty()) {
4742 Stream
.EmitRecord(bitc::FS_CFI_FUNCTION_DECLS
, NameVals
);
4747 // Walk the GUIDs that were referenced, and write the
4748 // corresponding type id records.
4749 for (auto &T
: ReferencedTypeIds
) {
4750 auto TidIter
= Index
.typeIds().equal_range(T
);
4751 for (auto It
= TidIter
.first
; It
!= TidIter
.second
; ++It
) {
4752 writeTypeIdSummaryRecord(NameVals
, StrtabBuilder
, It
->second
.first
,
4754 Stream
.EmitRecord(bitc::FS_TYPE_ID
, NameVals
);
4759 if (Index
.getBlockCount())
4760 Stream
.EmitRecord(bitc::FS_BLOCK_COUNT
,
4761 ArrayRef
<uint64_t>{Index
.getBlockCount()});
4766 /// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
4767 /// current llvm version, and a record for the epoch number.
4768 static void writeIdentificationBlock(BitstreamWriter
&Stream
) {
4769 Stream
.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID
, 5);
4771 // Write the "user readable" string identifying the bitcode producer
4772 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
4773 Abbv
->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING
));
4774 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
4775 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6
));
4776 auto StringAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
4777 writeStringRecord(Stream
, bitc::IDENTIFICATION_CODE_STRING
,
4778 "LLVM" LLVM_VERSION_STRING
, StringAbbrev
);
4780 // Write the epoch version
4781 Abbv
= std::make_shared
<BitCodeAbbrev
>();
4782 Abbv
->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH
));
4783 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6));
4784 auto EpochAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
4785 constexpr std::array
<unsigned, 1> Vals
= {{bitc::BITCODE_CURRENT_EPOCH
}};
4786 Stream
.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH
, Vals
, EpochAbbrev
);
4790 void ModuleBitcodeWriter::writeModuleHash(size_t BlockStartPos
) {
4791 // Emit the module's hash.
4792 // MODULE_CODE_HASH: [5*i32]
4795 Hasher
.update(ArrayRef
<uint8_t>((const uint8_t *)&(Buffer
)[BlockStartPos
],
4796 Buffer
.size() - BlockStartPos
));
4797 std::array
<uint8_t, 20> Hash
= Hasher
.result();
4798 for (int Pos
= 0; Pos
< 20; Pos
+= 4) {
4799 Vals
[Pos
/ 4] = support::endian::read32be(Hash
.data() + Pos
);
4802 // Emit the finished record.
4803 Stream
.EmitRecord(bitc::MODULE_CODE_HASH
, Vals
);
4806 // Save the written hash value.
4807 llvm::copy(Vals
, std::begin(*ModHash
));
4811 void ModuleBitcodeWriter::write() {
4812 writeIdentificationBlock(Stream
);
4814 Stream
.EnterSubblock(bitc::MODULE_BLOCK_ID
, 3);
4815 size_t BlockStartPos
= Buffer
.size();
4817 writeModuleVersion();
4819 // Emit blockinfo, which defines the standard abbreviations etc.
4822 // Emit information describing all of the types in the module.
4825 // Emit information about attribute groups.
4826 writeAttributeGroupTable();
4828 // Emit information about parameter attributes.
4829 writeAttributeTable();
4833 // Emit top-level description of module, including target triple, inline asm,
4834 // descriptors for global variables, and function prototype info.
4838 writeModuleConstants();
4840 // Emit metadata kind names.
4841 writeModuleMetadataKinds();
4844 writeModuleMetadata();
4846 // Emit module-level use-lists.
4847 if (VE
.shouldPreserveUseListOrder())
4848 writeUseListBlock(nullptr);
4850 writeOperandBundleTags();
4851 writeSyncScopeNames();
4853 // Emit function bodies.
4854 DenseMap
<const Function
*, uint64_t> FunctionToBitcodeIndex
;
4855 for (const Function
&F
: M
)
4856 if (!F
.isDeclaration())
4857 writeFunction(F
, FunctionToBitcodeIndex
);
4859 // Need to write after the above call to WriteFunction which populates
4860 // the summary information in the index.
4862 writePerModuleGlobalValueSummary();
4864 writeGlobalValueSymbolTable(FunctionToBitcodeIndex
);
4866 writeModuleHash(BlockStartPos
);
4871 static void writeInt32ToBuffer(uint32_t Value
, SmallVectorImpl
<char> &Buffer
,
4872 uint32_t &Position
) {
4873 support::endian::write32le(&Buffer
[Position
], Value
);
4877 /// If generating a bc file on darwin, we have to emit a
4878 /// header and trailer to make it compatible with the system archiver. To do
4879 /// this we emit the following header, and then emit a trailer that pads the
4880 /// file out to be a multiple of 16 bytes.
4882 /// struct bc_header {
4883 /// uint32_t Magic; // 0x0B17C0DE
4884 /// uint32_t Version; // Version, currently always 0.
4885 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
4886 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
4887 /// uint32_t CPUType; // CPU specifier.
4888 /// ... potentially more later ...
4890 static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl
<char> &Buffer
,
4892 unsigned CPUType
= ~0U;
4894 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
4895 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
4896 // number from /usr/include/mach/machine.h. It is ok to reproduce the
4897 // specific constants here because they are implicitly part of the Darwin ABI.
4899 DARWIN_CPU_ARCH_ABI64
= 0x01000000,
4900 DARWIN_CPU_TYPE_X86
= 7,
4901 DARWIN_CPU_TYPE_ARM
= 12,
4902 DARWIN_CPU_TYPE_POWERPC
= 18
4905 Triple::ArchType Arch
= TT
.getArch();
4906 if (Arch
== Triple::x86_64
)
4907 CPUType
= DARWIN_CPU_TYPE_X86
| DARWIN_CPU_ARCH_ABI64
;
4908 else if (Arch
== Triple::x86
)
4909 CPUType
= DARWIN_CPU_TYPE_X86
;
4910 else if (Arch
== Triple::ppc
)
4911 CPUType
= DARWIN_CPU_TYPE_POWERPC
;
4912 else if (Arch
== Triple::ppc64
)
4913 CPUType
= DARWIN_CPU_TYPE_POWERPC
| DARWIN_CPU_ARCH_ABI64
;
4914 else if (Arch
== Triple::arm
|| Arch
== Triple::thumb
)
4915 CPUType
= DARWIN_CPU_TYPE_ARM
;
4917 // Traditional Bitcode starts after header.
4918 assert(Buffer
.size() >= BWH_HeaderSize
&&
4919 "Expected header size to be reserved");
4920 unsigned BCOffset
= BWH_HeaderSize
;
4921 unsigned BCSize
= Buffer
.size() - BWH_HeaderSize
;
4923 // Write the magic and version.
4924 unsigned Position
= 0;
4925 writeInt32ToBuffer(0x0B17C0DE, Buffer
, Position
);
4926 writeInt32ToBuffer(0, Buffer
, Position
); // Version.
4927 writeInt32ToBuffer(BCOffset
, Buffer
, Position
);
4928 writeInt32ToBuffer(BCSize
, Buffer
, Position
);
4929 writeInt32ToBuffer(CPUType
, Buffer
, Position
);
4931 // If the file is not a multiple of 16 bytes, insert dummy padding.
4932 while (Buffer
.size() & 15)
4933 Buffer
.push_back(0);
4936 /// Helper to write the header common to all bitcode files.
4937 static void writeBitcodeHeader(BitstreamWriter
&Stream
) {
4938 // Emit the file header.
4939 Stream
.Emit((unsigned)'B', 8);
4940 Stream
.Emit((unsigned)'C', 8);
4941 Stream
.Emit(0x0, 4);
4942 Stream
.Emit(0xC, 4);
4943 Stream
.Emit(0xE, 4);
4944 Stream
.Emit(0xD, 4);
4947 BitcodeWriter::BitcodeWriter(SmallVectorImpl
<char> &Buffer
, raw_fd_stream
*FS
)
4948 : Buffer(Buffer
), Stream(new BitstreamWriter(Buffer
, FS
, FlushThreshold
)) {
4949 writeBitcodeHeader(*Stream
);
4952 BitcodeWriter::~BitcodeWriter() { assert(WroteStrtab
); }
4954 void BitcodeWriter::writeBlob(unsigned Block
, unsigned Record
, StringRef Blob
) {
4955 Stream
->EnterSubblock(Block
, 3);
4957 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
4958 Abbv
->Add(BitCodeAbbrevOp(Record
));
4959 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob
));
4960 auto AbbrevNo
= Stream
->EmitAbbrev(std::move(Abbv
));
4962 Stream
->EmitRecordWithBlob(AbbrevNo
, ArrayRef
<uint64_t>{Record
}, Blob
);
4964 Stream
->ExitBlock();
4967 void BitcodeWriter::writeSymtab() {
4968 assert(!WroteStrtab
&& !WroteSymtab
);
4970 // If any module has module-level inline asm, we will require a registered asm
4971 // parser for the target so that we can create an accurate symbol table for
4973 for (Module
*M
: Mods
) {
4974 if (M
->getModuleInlineAsm().empty())
4978 const Triple
TT(M
->getTargetTriple());
4979 const Target
*T
= TargetRegistry::lookupTarget(TT
.str(), Err
);
4980 if (!T
|| !T
->hasMCAsmParser())
4985 SmallVector
<char, 0> Symtab
;
4986 // The irsymtab::build function may be unable to create a symbol table if the
4987 // module is malformed (e.g. it contains an invalid alias). Writing a symbol
4988 // table is not required for correctness, but we still want to be able to
4989 // write malformed modules to bitcode files, so swallow the error.
4990 if (Error E
= irsymtab::build(Mods
, Symtab
, StrtabBuilder
, Alloc
)) {
4991 consumeError(std::move(E
));
4995 writeBlob(bitc::SYMTAB_BLOCK_ID
, bitc::SYMTAB_BLOB
,
4996 {Symtab
.data(), Symtab
.size()});
4999 void BitcodeWriter::writeStrtab() {
5000 assert(!WroteStrtab
);
5002 std::vector
<char> Strtab
;
5003 StrtabBuilder
.finalizeInOrder();
5004 Strtab
.resize(StrtabBuilder
.getSize());
5005 StrtabBuilder
.write((uint8_t *)Strtab
.data());
5007 writeBlob(bitc::STRTAB_BLOCK_ID
, bitc::STRTAB_BLOB
,
5008 {Strtab
.data(), Strtab
.size()});
5013 void BitcodeWriter::copyStrtab(StringRef Strtab
) {
5014 writeBlob(bitc::STRTAB_BLOCK_ID
, bitc::STRTAB_BLOB
, Strtab
);
5018 void BitcodeWriter::writeModule(const Module
&M
,
5019 bool ShouldPreserveUseListOrder
,
5020 const ModuleSummaryIndex
*Index
,
5021 bool GenerateHash
, ModuleHash
*ModHash
) {
5022 assert(!WroteStrtab
);
5024 // The Mods vector is used by irsymtab::build, which requires non-const
5025 // Modules in case it needs to materialize metadata. But the bitcode writer
5026 // requires that the module is materialized, so we can cast to non-const here,
5027 // after checking that it is in fact materialized.
5028 assert(M
.isMaterialized());
5029 Mods
.push_back(const_cast<Module
*>(&M
));
5031 ModuleBitcodeWriter
ModuleWriter(M
, Buffer
, StrtabBuilder
, *Stream
,
5032 ShouldPreserveUseListOrder
, Index
,
5033 GenerateHash
, ModHash
);
5034 ModuleWriter
.write();
5037 void BitcodeWriter::writeIndex(
5038 const ModuleSummaryIndex
*Index
,
5039 const std::map
<std::string
, GVSummaryMapTy
> *ModuleToSummariesForIndex
) {
5040 IndexBitcodeWriter
IndexWriter(*Stream
, StrtabBuilder
, *Index
,
5041 ModuleToSummariesForIndex
);
5042 IndexWriter
.write();
5045 /// Write the specified module to the specified output stream.
5046 void llvm::WriteBitcodeToFile(const Module
&M
, raw_ostream
&Out
,
5047 bool ShouldPreserveUseListOrder
,
5048 const ModuleSummaryIndex
*Index
,
5049 bool GenerateHash
, ModuleHash
*ModHash
) {
5050 SmallVector
<char, 0> Buffer
;
5051 Buffer
.reserve(256*1024);
5053 // If this is darwin or another generic macho target, reserve space for the
5055 Triple
TT(M
.getTargetTriple());
5056 if (TT
.isOSDarwin() || TT
.isOSBinFormatMachO())
5057 Buffer
.insert(Buffer
.begin(), BWH_HeaderSize
, 0);
5059 BitcodeWriter
Writer(Buffer
, dyn_cast
<raw_fd_stream
>(&Out
));
5060 Writer
.writeModule(M
, ShouldPreserveUseListOrder
, Index
, GenerateHash
,
5062 Writer
.writeSymtab();
5063 Writer
.writeStrtab();
5065 if (TT
.isOSDarwin() || TT
.isOSBinFormatMachO())
5066 emitDarwinBCHeaderAndTrailer(Buffer
, TT
);
5068 // Write the generated bitstream to "Out".
5069 if (!Buffer
.empty())
5070 Out
.write((char *)&Buffer
.front(), Buffer
.size());
5073 void IndexBitcodeWriter::write() {
5074 Stream
.EnterSubblock(bitc::MODULE_BLOCK_ID
, 3);
5076 writeModuleVersion();
5078 // Write the module paths in the combined index.
5081 // Write the summary combined index records.
5082 writeCombinedGlobalValueSummary();
5087 // Write the specified module summary index to the given raw output stream,
5088 // where it will be written in a new bitcode block. This is used when
5089 // writing the combined index file for ThinLTO. When writing a subset of the
5090 // index for a distributed backend, provide a \p ModuleToSummariesForIndex map.
5091 void llvm::writeIndexToFile(
5092 const ModuleSummaryIndex
&Index
, raw_ostream
&Out
,
5093 const std::map
<std::string
, GVSummaryMapTy
> *ModuleToSummariesForIndex
) {
5094 SmallVector
<char, 0> Buffer
;
5095 Buffer
.reserve(256 * 1024);
5097 BitcodeWriter
Writer(Buffer
);
5098 Writer
.writeIndex(&Index
, ModuleToSummariesForIndex
);
5099 Writer
.writeStrtab();
5101 Out
.write((char *)&Buffer
.front(), Buffer
.size());
5106 /// Class to manage the bitcode writing for a thin link bitcode file.
5107 class ThinLinkBitcodeWriter
: public ModuleBitcodeWriterBase
{
5108 /// ModHash is for use in ThinLTO incremental build, generated while writing
5109 /// the module bitcode file.
5110 const ModuleHash
*ModHash
;
5113 ThinLinkBitcodeWriter(const Module
&M
, StringTableBuilder
&StrtabBuilder
,
5114 BitstreamWriter
&Stream
,
5115 const ModuleSummaryIndex
&Index
,
5116 const ModuleHash
&ModHash
)
5117 : ModuleBitcodeWriterBase(M
, StrtabBuilder
, Stream
,
5118 /*ShouldPreserveUseListOrder=*/false, &Index
),
5119 ModHash(&ModHash
) {}
5124 void writeSimplifiedModuleInfo();
5127 } // end anonymous namespace
5129 // This function writes a simpilified module info for thin link bitcode file.
5130 // It only contains the source file name along with the name(the offset and
5131 // size in strtab) and linkage for global values. For the global value info
5132 // entry, in order to keep linkage at offset 5, there are three zeros used
5134 void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {
5135 SmallVector
<unsigned, 64> Vals
;
5136 // Emit the module's source file name.
5138 StringEncoding Bits
= getStringEncoding(M
.getSourceFileName());
5139 BitCodeAbbrevOp AbbrevOpToUse
= BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 8);
5140 if (Bits
== SE_Char6
)
5141 AbbrevOpToUse
= BitCodeAbbrevOp(BitCodeAbbrevOp::Char6
);
5142 else if (Bits
== SE_Fixed7
)
5143 AbbrevOpToUse
= BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 7);
5145 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
5146 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
5147 Abbv
->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME
));
5148 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
5149 Abbv
->Add(AbbrevOpToUse
);
5150 unsigned FilenameAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
5152 for (const auto P
: M
.getSourceFileName())
5153 Vals
.push_back((unsigned char)P
);
5155 Stream
.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME
, Vals
, FilenameAbbrev
);
5159 // Emit the global variable information.
5160 for (const GlobalVariable
&GV
: M
.globals()) {
5161 // GLOBALVAR: [strtab offset, strtab size, 0, 0, 0, linkage]
5162 Vals
.push_back(StrtabBuilder
.add(GV
.getName()));
5163 Vals
.push_back(GV
.getName().size());
5167 Vals
.push_back(getEncodedLinkage(GV
));
5169 Stream
.EmitRecord(bitc::MODULE_CODE_GLOBALVAR
, Vals
);
5173 // Emit the function proto information.
5174 for (const Function
&F
: M
) {
5175 // FUNCTION: [strtab offset, strtab size, 0, 0, 0, linkage]
5176 Vals
.push_back(StrtabBuilder
.add(F
.getName()));
5177 Vals
.push_back(F
.getName().size());
5181 Vals
.push_back(getEncodedLinkage(F
));
5183 Stream
.EmitRecord(bitc::MODULE_CODE_FUNCTION
, Vals
);
5187 // Emit the alias information.
5188 for (const GlobalAlias
&A
: M
.aliases()) {
5189 // ALIAS: [strtab offset, strtab size, 0, 0, 0, linkage]
5190 Vals
.push_back(StrtabBuilder
.add(A
.getName()));
5191 Vals
.push_back(A
.getName().size());
5195 Vals
.push_back(getEncodedLinkage(A
));
5197 Stream
.EmitRecord(bitc::MODULE_CODE_ALIAS
, Vals
);
5201 // Emit the ifunc information.
5202 for (const GlobalIFunc
&I
: M
.ifuncs()) {
5203 // IFUNC: [strtab offset, strtab size, 0, 0, 0, linkage]
5204 Vals
.push_back(StrtabBuilder
.add(I
.getName()));
5205 Vals
.push_back(I
.getName().size());
5209 Vals
.push_back(getEncodedLinkage(I
));
5211 Stream
.EmitRecord(bitc::MODULE_CODE_IFUNC
, Vals
);
5216 void ThinLinkBitcodeWriter::write() {
5217 Stream
.EnterSubblock(bitc::MODULE_BLOCK_ID
, 3);
5219 writeModuleVersion();
5221 writeSimplifiedModuleInfo();
5223 writePerModuleGlobalValueSummary();
5225 // Write module hash.
5226 Stream
.EmitRecord(bitc::MODULE_CODE_HASH
, ArrayRef
<uint32_t>(*ModHash
));
5231 void BitcodeWriter::writeThinLinkBitcode(const Module
&M
,
5232 const ModuleSummaryIndex
&Index
,
5233 const ModuleHash
&ModHash
) {
5234 assert(!WroteStrtab
);
5236 // The Mods vector is used by irsymtab::build, which requires non-const
5237 // Modules in case it needs to materialize metadata. But the bitcode writer
5238 // requires that the module is materialized, so we can cast to non-const here,
5239 // after checking that it is in fact materialized.
5240 assert(M
.isMaterialized());
5241 Mods
.push_back(const_cast<Module
*>(&M
));
5243 ThinLinkBitcodeWriter
ThinLinkWriter(M
, StrtabBuilder
, *Stream
, Index
,
5245 ThinLinkWriter
.write();
5248 // Write the specified thin link bitcode file to the given raw output stream,
5249 // where it will be written in a new bitcode block. This is used when
5250 // writing the per-module index file for ThinLTO.
5251 void llvm::writeThinLinkBitcodeToFile(const Module
&M
, raw_ostream
&Out
,
5252 const ModuleSummaryIndex
&Index
,
5253 const ModuleHash
&ModHash
) {
5254 SmallVector
<char, 0> Buffer
;
5255 Buffer
.reserve(256 * 1024);
5257 BitcodeWriter
Writer(Buffer
);
5258 Writer
.writeThinLinkBitcode(M
, Index
, ModHash
);
5259 Writer
.writeSymtab();
5260 Writer
.writeStrtab();
5262 Out
.write((char *)&Buffer
.front(), Buffer
.size());
5265 static const char *getSectionNameForBitcode(const Triple
&T
) {
5266 switch (T
.getObjectFormat()) {
5268 return "__LLVM,__bitcode";
5272 case Triple::UnknownObjectFormat
:
5275 llvm_unreachable("GOFF is not yet implemented");
5278 llvm_unreachable("SPIRV is not yet implemented");
5281 llvm_unreachable("XCOFF is not yet implemented");
5283 case Triple::DXContainer
:
5284 llvm_unreachable("DXContainer is not yet implemented");
5287 llvm_unreachable("Unimplemented ObjectFormatType");
5290 static const char *getSectionNameForCommandline(const Triple
&T
) {
5291 switch (T
.getObjectFormat()) {
5293 return "__LLVM,__cmdline";
5297 case Triple::UnknownObjectFormat
:
5300 llvm_unreachable("GOFF is not yet implemented");
5303 llvm_unreachable("SPIRV is not yet implemented");
5306 llvm_unreachable("XCOFF is not yet implemented");
5308 case Triple::DXContainer
:
5309 llvm_unreachable("DXC is not yet implemented");
5312 llvm_unreachable("Unimplemented ObjectFormatType");
5315 void llvm::embedBitcodeInModule(llvm::Module
&M
, llvm::MemoryBufferRef Buf
,
5316 bool EmbedBitcode
, bool EmbedCmdline
,
5317 const std::vector
<uint8_t> &CmdArgs
) {
5318 // Save llvm.compiler.used and remove it.
5319 SmallVector
<Constant
*, 2> UsedArray
;
5320 SmallVector
<GlobalValue
*, 4> UsedGlobals
;
5321 Type
*UsedElementType
= PointerType::getUnqual(M
.getContext());
5322 GlobalVariable
*Used
= collectUsedGlobalVariables(M
, UsedGlobals
, true);
5323 for (auto *GV
: UsedGlobals
) {
5324 if (GV
->getName() != "llvm.embedded.module" &&
5325 GV
->getName() != "llvm.cmdline")
5326 UsedArray
.push_back(
5327 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV
, UsedElementType
));
5330 Used
->eraseFromParent();
5332 // Embed the bitcode for the llvm module.
5334 ArrayRef
<uint8_t> ModuleData
;
5335 Triple
T(M
.getTargetTriple());
5338 if (Buf
.getBufferSize() == 0 ||
5339 !isBitcode((const unsigned char *)Buf
.getBufferStart(),
5340 (const unsigned char *)Buf
.getBufferEnd())) {
5341 // If the input is LLVM Assembly, bitcode is produced by serializing
5342 // the module. Use-lists order need to be preserved in this case.
5343 llvm::raw_string_ostream
OS(Data
);
5344 llvm::WriteBitcodeToFile(M
, OS
, /* ShouldPreserveUseListOrder */ true);
5346 ArrayRef
<uint8_t>((const uint8_t *)OS
.str().data(), OS
.str().size());
5348 // If the input is LLVM bitcode, write the input byte stream directly.
5349 ModuleData
= ArrayRef
<uint8_t>((const uint8_t *)Buf
.getBufferStart(),
5350 Buf
.getBufferSize());
5352 llvm::Constant
*ModuleConstant
=
5353 llvm::ConstantDataArray::get(M
.getContext(), ModuleData
);
5354 llvm::GlobalVariable
*GV
= new llvm::GlobalVariable(
5355 M
, ModuleConstant
->getType(), true, llvm::GlobalValue::PrivateLinkage
,
5357 GV
->setSection(getSectionNameForBitcode(T
));
5358 // Set alignment to 1 to prevent padding between two contributions from input
5359 // sections after linking.
5360 GV
->setAlignment(Align(1));
5361 UsedArray
.push_back(
5362 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV
, UsedElementType
));
5363 if (llvm::GlobalVariable
*Old
=
5364 M
.getGlobalVariable("llvm.embedded.module", true)) {
5365 assert(Old
->hasZeroLiveUses() &&
5366 "llvm.embedded.module can only be used once in llvm.compiler.used");
5368 Old
->eraseFromParent();
5370 GV
->setName("llvm.embedded.module");
5373 // Skip if only bitcode needs to be embedded.
5375 // Embed command-line options.
5376 ArrayRef
<uint8_t> CmdData(const_cast<uint8_t *>(CmdArgs
.data()),
5378 llvm::Constant
*CmdConstant
=
5379 llvm::ConstantDataArray::get(M
.getContext(), CmdData
);
5380 GV
= new llvm::GlobalVariable(M
, CmdConstant
->getType(), true,
5381 llvm::GlobalValue::PrivateLinkage
,
5383 GV
->setSection(getSectionNameForCommandline(T
));
5384 GV
->setAlignment(Align(1));
5385 UsedArray
.push_back(
5386 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV
, UsedElementType
));
5387 if (llvm::GlobalVariable
*Old
= M
.getGlobalVariable("llvm.cmdline", true)) {
5388 assert(Old
->hasZeroLiveUses() &&
5389 "llvm.cmdline can only be used once in llvm.compiler.used");
5391 Old
->eraseFromParent();
5393 GV
->setName("llvm.cmdline");
5397 if (UsedArray
.empty())
5400 // Recreate llvm.compiler.used.
5401 ArrayType
*ATy
= ArrayType::get(UsedElementType
, UsedArray
.size());
5402 auto *NewUsed
= new GlobalVariable(
5403 M
, ATy
, false, llvm::GlobalValue::AppendingLinkage
,
5404 llvm::ConstantArray::get(ATy
, UsedArray
), "llvm.compiler.used");
5405 NewUsed
->setSection("llvm.metadata");