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/None.h"
20 #include "llvm/ADT/Optional.h"
21 #include "llvm/ADT/STLExtras.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/ADT/Triple.h"
27 #include "llvm/Bitstream/BitCodes.h"
28 #include "llvm/Bitstream/BitstreamWriter.h"
29 #include "llvm/Bitcode/LLVMBitCodes.h"
30 #include "llvm/Config/llvm-config.h"
31 #include "llvm/IR/Attributes.h"
32 #include "llvm/IR/BasicBlock.h"
33 #include "llvm/IR/CallSite.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/Object/IRSymtab.h"
61 #include "llvm/Support/AtomicOrdering.h"
62 #include "llvm/Support/Casting.h"
63 #include "llvm/Support/CommandLine.h"
64 #include "llvm/Support/Endian.h"
65 #include "llvm/Support/Error.h"
66 #include "llvm/Support/ErrorHandling.h"
67 #include "llvm/Support/MathExtras.h"
68 #include "llvm/Support/SHA1.h"
69 #include "llvm/Support/TargetRegistry.h"
70 #include "llvm/Support/raw_ostream.h"
84 static cl::opt
<unsigned>
85 IndexThreshold("bitcode-mdindex-threshold", cl::Hidden
, cl::init(25),
86 cl::desc("Number of metadatas above which we emit an index "
87 "to enable lazy-loading"));
89 cl::opt
<bool> WriteRelBFToSummary(
90 "write-relbf-to-summary", cl::Hidden
, cl::init(false),
91 cl::desc("Write relative block frequency to function summary "));
93 extern FunctionSummary::ForceSummaryHotnessType ForceSummaryEdgesCold
;
97 /// These are manifest constants used by the bitcode writer. They do not need to
98 /// be kept in sync with the reader, but need to be consistent within this file.
100 // VALUE_SYMTAB_BLOCK abbrev id's.
101 VST_ENTRY_8_ABBREV
= bitc::FIRST_APPLICATION_ABBREV
,
104 VST_BBENTRY_6_ABBREV
,
106 // CONSTANTS_BLOCK abbrev id's.
107 CONSTANTS_SETTYPE_ABBREV
= bitc::FIRST_APPLICATION_ABBREV
,
108 CONSTANTS_INTEGER_ABBREV
,
109 CONSTANTS_CE_CAST_Abbrev
,
110 CONSTANTS_NULL_Abbrev
,
112 // FUNCTION_BLOCK abbrev id's.
113 FUNCTION_INST_LOAD_ABBREV
= bitc::FIRST_APPLICATION_ABBREV
,
114 FUNCTION_INST_UNOP_ABBREV
,
115 FUNCTION_INST_UNOP_FLAGS_ABBREV
,
116 FUNCTION_INST_BINOP_ABBREV
,
117 FUNCTION_INST_BINOP_FLAGS_ABBREV
,
118 FUNCTION_INST_CAST_ABBREV
,
119 FUNCTION_INST_RET_VOID_ABBREV
,
120 FUNCTION_INST_RET_VAL_ABBREV
,
121 FUNCTION_INST_UNREACHABLE_ABBREV
,
122 FUNCTION_INST_GEP_ABBREV
,
125 /// Abstract class to manage the bitcode writing, subclassed for each bitcode
127 class BitcodeWriterBase
{
129 /// The stream created and owned by the client.
130 BitstreamWriter
&Stream
;
132 StringTableBuilder
&StrtabBuilder
;
135 /// Constructs a BitcodeWriterBase object that writes to the provided
137 BitcodeWriterBase(BitstreamWriter
&Stream
, StringTableBuilder
&StrtabBuilder
)
138 : Stream(Stream
), StrtabBuilder(StrtabBuilder
) {}
141 void writeBitcodeHeader();
142 void writeModuleVersion();
145 void BitcodeWriterBase::writeModuleVersion() {
146 // VERSION: [version#]
147 Stream
.EmitRecord(bitc::MODULE_CODE_VERSION
, ArrayRef
<uint64_t>{2});
150 /// Base class to manage the module bitcode writing, currently subclassed for
151 /// ModuleBitcodeWriter and ThinLinkBitcodeWriter.
152 class ModuleBitcodeWriterBase
: public BitcodeWriterBase
{
154 /// The Module to write to bitcode.
157 /// Enumerates ids for all values in the module.
160 /// Optional per-module index to write for ThinLTO.
161 const ModuleSummaryIndex
*Index
;
163 /// Map that holds the correspondence between GUIDs in the summary index,
164 /// that came from indirect call profiles, and a value id generated by this
165 /// class to use in the VST and summary block records.
166 std::map
<GlobalValue::GUID
, unsigned> GUIDToValueIdMap
;
168 /// Tracks the last value id recorded in the GUIDToValueMap.
169 unsigned GlobalValueId
;
171 /// Saves the offset of the VSTOffset record that must eventually be
172 /// backpatched with the offset of the actual VST.
173 uint64_t VSTOffsetPlaceholder
= 0;
176 /// Constructs a ModuleBitcodeWriterBase object for the given Module,
177 /// writing to the provided \p Buffer.
178 ModuleBitcodeWriterBase(const Module
&M
, StringTableBuilder
&StrtabBuilder
,
179 BitstreamWriter
&Stream
,
180 bool ShouldPreserveUseListOrder
,
181 const ModuleSummaryIndex
*Index
)
182 : BitcodeWriterBase(Stream
, StrtabBuilder
), M(M
),
183 VE(M
, ShouldPreserveUseListOrder
), Index(Index
) {
184 // Assign ValueIds to any callee values in the index that came from
185 // indirect call profiles and were recorded as a GUID not a Value*
186 // (which would have been assigned an ID by the ValueEnumerator).
187 // The starting ValueId is just after the number of values in the
188 // ValueEnumerator, so that they can be emitted in the VST.
189 GlobalValueId
= VE
.getValues().size();
192 for (const auto &GUIDSummaryLists
: *Index
)
193 // Examine all summaries for this GUID.
194 for (auto &Summary
: GUIDSummaryLists
.second
.SummaryList
)
195 if (auto FS
= dyn_cast
<FunctionSummary
>(Summary
.get()))
196 // For each call in the function summary, see if the call
197 // is to a GUID (which means it is for an indirect call,
198 // otherwise we would have a Value for it). If so, synthesize
200 for (auto &CallEdge
: FS
->calls())
201 if (!CallEdge
.first
.haveGVs() || !CallEdge
.first
.getValue())
202 assignValueId(CallEdge
.first
.getGUID());
206 void writePerModuleGlobalValueSummary();
209 void writePerModuleFunctionSummaryRecord(SmallVector
<uint64_t, 64> &NameVals
,
210 GlobalValueSummary
*Summary
,
212 unsigned FSCallsAbbrev
,
213 unsigned FSCallsProfileAbbrev
,
215 void writeModuleLevelReferences(const GlobalVariable
&V
,
216 SmallVector
<uint64_t, 64> &NameVals
,
217 unsigned FSModRefsAbbrev
,
218 unsigned FSModVTableRefsAbbrev
);
220 void assignValueId(GlobalValue::GUID ValGUID
) {
221 GUIDToValueIdMap
[ValGUID
] = ++GlobalValueId
;
224 unsigned getValueId(GlobalValue::GUID ValGUID
) {
225 const auto &VMI
= GUIDToValueIdMap
.find(ValGUID
);
226 // Expect that any GUID value had a value Id assigned by an
227 // earlier call to assignValueId.
228 assert(VMI
!= GUIDToValueIdMap
.end() &&
229 "GUID does not have assigned value Id");
233 // Helper to get the valueId for the type of value recorded in VI.
234 unsigned getValueId(ValueInfo VI
) {
235 if (!VI
.haveGVs() || !VI
.getValue())
236 return getValueId(VI
.getGUID());
237 return VE
.getValueID(VI
.getValue());
240 std::map
<GlobalValue::GUID
, unsigned> &valueIds() { return GUIDToValueIdMap
; }
243 /// Class to manage the bitcode writing for a module.
244 class ModuleBitcodeWriter
: public ModuleBitcodeWriterBase
{
245 /// Pointer to the buffer allocated by caller for bitcode writing.
246 const SmallVectorImpl
<char> &Buffer
;
248 /// True if a module hash record should be written.
251 /// If non-null, when GenerateHash is true, the resulting hash is written
257 /// The start bit of the identification block.
258 uint64_t BitcodeStartBit
;
261 /// Constructs a ModuleBitcodeWriter object for the given Module,
262 /// writing to the provided \p Buffer.
263 ModuleBitcodeWriter(const Module
&M
, SmallVectorImpl
<char> &Buffer
,
264 StringTableBuilder
&StrtabBuilder
,
265 BitstreamWriter
&Stream
, bool ShouldPreserveUseListOrder
,
266 const ModuleSummaryIndex
*Index
, bool GenerateHash
,
267 ModuleHash
*ModHash
= nullptr)
268 : ModuleBitcodeWriterBase(M
, StrtabBuilder
, Stream
,
269 ShouldPreserveUseListOrder
, Index
),
270 Buffer(Buffer
), GenerateHash(GenerateHash
), ModHash(ModHash
),
271 BitcodeStartBit(Stream
.GetCurrentBitNo()) {}
273 /// Emit the current module to the bitstream.
277 uint64_t bitcodeStartBit() { return BitcodeStartBit
; }
279 size_t addToStrtab(StringRef Str
);
281 void writeAttributeGroupTable();
282 void writeAttributeTable();
283 void writeTypeTable();
285 void writeValueSymbolTableForwardDecl();
286 void writeModuleInfo();
287 void writeValueAsMetadata(const ValueAsMetadata
*MD
,
288 SmallVectorImpl
<uint64_t> &Record
);
289 void writeMDTuple(const MDTuple
*N
, SmallVectorImpl
<uint64_t> &Record
,
291 unsigned createDILocationAbbrev();
292 void writeDILocation(const DILocation
*N
, SmallVectorImpl
<uint64_t> &Record
,
294 unsigned createGenericDINodeAbbrev();
295 void writeGenericDINode(const GenericDINode
*N
,
296 SmallVectorImpl
<uint64_t> &Record
, unsigned &Abbrev
);
297 void writeDISubrange(const DISubrange
*N
, SmallVectorImpl
<uint64_t> &Record
,
299 void writeDIEnumerator(const DIEnumerator
*N
,
300 SmallVectorImpl
<uint64_t> &Record
, unsigned Abbrev
);
301 void writeDIBasicType(const DIBasicType
*N
, SmallVectorImpl
<uint64_t> &Record
,
303 void writeDIDerivedType(const DIDerivedType
*N
,
304 SmallVectorImpl
<uint64_t> &Record
, unsigned Abbrev
);
305 void writeDICompositeType(const DICompositeType
*N
,
306 SmallVectorImpl
<uint64_t> &Record
, unsigned Abbrev
);
307 void writeDISubroutineType(const DISubroutineType
*N
,
308 SmallVectorImpl
<uint64_t> &Record
,
310 void writeDIFile(const DIFile
*N
, SmallVectorImpl
<uint64_t> &Record
,
312 void writeDICompileUnit(const DICompileUnit
*N
,
313 SmallVectorImpl
<uint64_t> &Record
, unsigned Abbrev
);
314 void writeDISubprogram(const DISubprogram
*N
,
315 SmallVectorImpl
<uint64_t> &Record
, unsigned Abbrev
);
316 void writeDILexicalBlock(const DILexicalBlock
*N
,
317 SmallVectorImpl
<uint64_t> &Record
, unsigned Abbrev
);
318 void writeDILexicalBlockFile(const DILexicalBlockFile
*N
,
319 SmallVectorImpl
<uint64_t> &Record
,
321 void writeDICommonBlock(const DICommonBlock
*N
,
322 SmallVectorImpl
<uint64_t> &Record
, unsigned Abbrev
);
323 void writeDINamespace(const DINamespace
*N
, SmallVectorImpl
<uint64_t> &Record
,
325 void writeDIMacro(const DIMacro
*N
, SmallVectorImpl
<uint64_t> &Record
,
327 void writeDIMacroFile(const DIMacroFile
*N
, SmallVectorImpl
<uint64_t> &Record
,
329 void writeDIModule(const DIModule
*N
, SmallVectorImpl
<uint64_t> &Record
,
331 void writeDITemplateTypeParameter(const DITemplateTypeParameter
*N
,
332 SmallVectorImpl
<uint64_t> &Record
,
334 void writeDITemplateValueParameter(const DITemplateValueParameter
*N
,
335 SmallVectorImpl
<uint64_t> &Record
,
337 void writeDIGlobalVariable(const DIGlobalVariable
*N
,
338 SmallVectorImpl
<uint64_t> &Record
,
340 void writeDILocalVariable(const DILocalVariable
*N
,
341 SmallVectorImpl
<uint64_t> &Record
, unsigned Abbrev
);
342 void writeDILabel(const DILabel
*N
,
343 SmallVectorImpl
<uint64_t> &Record
, unsigned Abbrev
);
344 void writeDIExpression(const DIExpression
*N
,
345 SmallVectorImpl
<uint64_t> &Record
, unsigned Abbrev
);
346 void writeDIGlobalVariableExpression(const DIGlobalVariableExpression
*N
,
347 SmallVectorImpl
<uint64_t> &Record
,
349 void writeDIObjCProperty(const DIObjCProperty
*N
,
350 SmallVectorImpl
<uint64_t> &Record
, unsigned Abbrev
);
351 void writeDIImportedEntity(const DIImportedEntity
*N
,
352 SmallVectorImpl
<uint64_t> &Record
,
354 unsigned createNamedMetadataAbbrev();
355 void writeNamedMetadata(SmallVectorImpl
<uint64_t> &Record
);
356 unsigned createMetadataStringsAbbrev();
357 void writeMetadataStrings(ArrayRef
<const Metadata
*> Strings
,
358 SmallVectorImpl
<uint64_t> &Record
);
359 void writeMetadataRecords(ArrayRef
<const Metadata
*> MDs
,
360 SmallVectorImpl
<uint64_t> &Record
,
361 std::vector
<unsigned> *MDAbbrevs
= nullptr,
362 std::vector
<uint64_t> *IndexPos
= nullptr);
363 void writeModuleMetadata();
364 void writeFunctionMetadata(const Function
&F
);
365 void writeFunctionMetadataAttachment(const Function
&F
);
366 void writeGlobalVariableMetadataAttachment(const GlobalVariable
&GV
);
367 void pushGlobalMetadataAttachment(SmallVectorImpl
<uint64_t> &Record
,
368 const GlobalObject
&GO
);
369 void writeModuleMetadataKinds();
370 void writeOperandBundleTags();
371 void writeSyncScopeNames();
372 void writeConstants(unsigned FirstVal
, unsigned LastVal
, bool isGlobal
);
373 void writeModuleConstants();
374 bool pushValueAndType(const Value
*V
, unsigned InstID
,
375 SmallVectorImpl
<unsigned> &Vals
);
376 void writeOperandBundles(ImmutableCallSite CS
, unsigned InstID
);
377 void pushValue(const Value
*V
, unsigned InstID
,
378 SmallVectorImpl
<unsigned> &Vals
);
379 void pushValueSigned(const Value
*V
, unsigned InstID
,
380 SmallVectorImpl
<uint64_t> &Vals
);
381 void writeInstruction(const Instruction
&I
, unsigned InstID
,
382 SmallVectorImpl
<unsigned> &Vals
);
383 void writeFunctionLevelValueSymbolTable(const ValueSymbolTable
&VST
);
384 void writeGlobalValueSymbolTable(
385 DenseMap
<const Function
*, uint64_t> &FunctionToBitcodeIndex
);
386 void writeUseList(UseListOrder
&&Order
);
387 void writeUseListBlock(const Function
*F
);
389 writeFunction(const Function
&F
,
390 DenseMap
<const Function
*, uint64_t> &FunctionToBitcodeIndex
);
391 void writeBlockInfo();
392 void writeModuleHash(size_t BlockStartPos
);
394 unsigned getEncodedSyncScopeID(SyncScope::ID SSID
) {
395 return unsigned(SSID
);
399 /// Class to manage the bitcode writing for a combined index.
400 class IndexBitcodeWriter
: public BitcodeWriterBase
{
401 /// The combined index to write to bitcode.
402 const ModuleSummaryIndex
&Index
;
404 /// When writing a subset of the index for distributed backends, client
405 /// provides a map of modules to the corresponding GUIDs/summaries to write.
406 const std::map
<std::string
, GVSummaryMapTy
> *ModuleToSummariesForIndex
;
408 /// Map that holds the correspondence between the GUID used in the combined
409 /// index and a value id generated by this class to use in references.
410 std::map
<GlobalValue::GUID
, unsigned> GUIDToValueIdMap
;
412 /// Tracks the last value id recorded in the GUIDToValueMap.
413 unsigned GlobalValueId
= 0;
416 /// Constructs a IndexBitcodeWriter object for the given combined index,
417 /// writing to the provided \p Buffer. When writing a subset of the index
418 /// for a distributed backend, provide a \p ModuleToSummariesForIndex map.
419 IndexBitcodeWriter(BitstreamWriter
&Stream
, StringTableBuilder
&StrtabBuilder
,
420 const ModuleSummaryIndex
&Index
,
421 const std::map
<std::string
, GVSummaryMapTy
>
422 *ModuleToSummariesForIndex
= nullptr)
423 : BitcodeWriterBase(Stream
, StrtabBuilder
), Index(Index
),
424 ModuleToSummariesForIndex(ModuleToSummariesForIndex
) {
425 // Assign unique value ids to all summaries to be written, for use
426 // in writing out the call graph edges. Save the mapping from GUID
427 // to the new global value id to use when writing those edges, which
428 // are currently saved in the index in terms of GUID.
429 forEachSummary([&](GVInfo I
, bool) {
430 GUIDToValueIdMap
[I
.first
] = ++GlobalValueId
;
434 /// The below iterator returns the GUID and associated summary.
435 using GVInfo
= std::pair
<GlobalValue::GUID
, GlobalValueSummary
*>;
437 /// Calls the callback for each value GUID and summary to be written to
438 /// bitcode. This hides the details of whether they are being pulled from the
439 /// entire index or just those in a provided ModuleToSummariesForIndex map.
440 template<typename Functor
>
441 void forEachSummary(Functor Callback
) {
442 if (ModuleToSummariesForIndex
) {
443 for (auto &M
: *ModuleToSummariesForIndex
)
444 for (auto &Summary
: M
.second
) {
445 Callback(Summary
, false);
446 // Ensure aliasee is handled, e.g. for assigning a valueId,
447 // even if we are not importing the aliasee directly (the
448 // imported alias will contain a copy of aliasee).
449 if (auto *AS
= dyn_cast
<AliasSummary
>(Summary
.getSecond()))
450 Callback({AS
->getAliaseeGUID(), &AS
->getAliasee()}, true);
453 for (auto &Summaries
: Index
)
454 for (auto &Summary
: Summaries
.second
.SummaryList
)
455 Callback({Summaries
.first
, Summary
.get()}, false);
459 /// Calls the callback for each entry in the modulePaths StringMap that
460 /// should be written to the module path string table. This hides the details
461 /// of whether they are being pulled from the entire index or just those in a
462 /// provided ModuleToSummariesForIndex map.
463 template <typename Functor
> void forEachModule(Functor Callback
) {
464 if (ModuleToSummariesForIndex
) {
465 for (const auto &M
: *ModuleToSummariesForIndex
) {
466 const auto &MPI
= Index
.modulePaths().find(M
.first
);
467 if (MPI
== Index
.modulePaths().end()) {
468 // This should only happen if the bitcode file was empty, in which
469 // case we shouldn't be importing (the ModuleToSummariesForIndex
470 // would only include the module we are writing and index for).
471 assert(ModuleToSummariesForIndex
->size() == 1);
477 for (const auto &MPSE
: Index
.modulePaths())
482 /// Main entry point for writing a combined index to bitcode.
486 void writeModStrings();
487 void writeCombinedGlobalValueSummary();
489 Optional
<unsigned> getValueId(GlobalValue::GUID ValGUID
) {
490 auto VMI
= GUIDToValueIdMap
.find(ValGUID
);
491 if (VMI
== GUIDToValueIdMap
.end())
496 std::map
<GlobalValue::GUID
, unsigned> &valueIds() { return GUIDToValueIdMap
; }
499 } // end anonymous namespace
501 static unsigned getEncodedCastOpcode(unsigned Opcode
) {
503 default: llvm_unreachable("Unknown cast instruction!");
504 case Instruction::Trunc
: return bitc::CAST_TRUNC
;
505 case Instruction::ZExt
: return bitc::CAST_ZEXT
;
506 case Instruction::SExt
: return bitc::CAST_SEXT
;
507 case Instruction::FPToUI
: return bitc::CAST_FPTOUI
;
508 case Instruction::FPToSI
: return bitc::CAST_FPTOSI
;
509 case Instruction::UIToFP
: return bitc::CAST_UITOFP
;
510 case Instruction::SIToFP
: return bitc::CAST_SITOFP
;
511 case Instruction::FPTrunc
: return bitc::CAST_FPTRUNC
;
512 case Instruction::FPExt
: return bitc::CAST_FPEXT
;
513 case Instruction::PtrToInt
: return bitc::CAST_PTRTOINT
;
514 case Instruction::IntToPtr
: return bitc::CAST_INTTOPTR
;
515 case Instruction::BitCast
: return bitc::CAST_BITCAST
;
516 case Instruction::AddrSpaceCast
: return bitc::CAST_ADDRSPACECAST
;
520 static unsigned getEncodedUnaryOpcode(unsigned Opcode
) {
522 default: llvm_unreachable("Unknown binary instruction!");
523 case Instruction::FNeg
: return bitc::UNOP_NEG
;
527 static unsigned getEncodedBinaryOpcode(unsigned Opcode
) {
529 default: llvm_unreachable("Unknown binary instruction!");
530 case Instruction::Add
:
531 case Instruction::FAdd
: return bitc::BINOP_ADD
;
532 case Instruction::Sub
:
533 case Instruction::FSub
: return bitc::BINOP_SUB
;
534 case Instruction::Mul
:
535 case Instruction::FMul
: return bitc::BINOP_MUL
;
536 case Instruction::UDiv
: return bitc::BINOP_UDIV
;
537 case Instruction::FDiv
:
538 case Instruction::SDiv
: return bitc::BINOP_SDIV
;
539 case Instruction::URem
: return bitc::BINOP_UREM
;
540 case Instruction::FRem
:
541 case Instruction::SRem
: return bitc::BINOP_SREM
;
542 case Instruction::Shl
: return bitc::BINOP_SHL
;
543 case Instruction::LShr
: return bitc::BINOP_LSHR
;
544 case Instruction::AShr
: return bitc::BINOP_ASHR
;
545 case Instruction::And
: return bitc::BINOP_AND
;
546 case Instruction::Or
: return bitc::BINOP_OR
;
547 case Instruction::Xor
: return bitc::BINOP_XOR
;
551 static unsigned getEncodedRMWOperation(AtomicRMWInst::BinOp Op
) {
553 default: llvm_unreachable("Unknown RMW operation!");
554 case AtomicRMWInst::Xchg
: return bitc::RMW_XCHG
;
555 case AtomicRMWInst::Add
: return bitc::RMW_ADD
;
556 case AtomicRMWInst::Sub
: return bitc::RMW_SUB
;
557 case AtomicRMWInst::And
: return bitc::RMW_AND
;
558 case AtomicRMWInst::Nand
: return bitc::RMW_NAND
;
559 case AtomicRMWInst::Or
: return bitc::RMW_OR
;
560 case AtomicRMWInst::Xor
: return bitc::RMW_XOR
;
561 case AtomicRMWInst::Max
: return bitc::RMW_MAX
;
562 case AtomicRMWInst::Min
: return bitc::RMW_MIN
;
563 case AtomicRMWInst::UMax
: return bitc::RMW_UMAX
;
564 case AtomicRMWInst::UMin
: return bitc::RMW_UMIN
;
565 case AtomicRMWInst::FAdd
: return bitc::RMW_FADD
;
566 case AtomicRMWInst::FSub
: return bitc::RMW_FSUB
;
570 static unsigned getEncodedOrdering(AtomicOrdering Ordering
) {
572 case AtomicOrdering::NotAtomic
: return bitc::ORDERING_NOTATOMIC
;
573 case AtomicOrdering::Unordered
: return bitc::ORDERING_UNORDERED
;
574 case AtomicOrdering::Monotonic
: return bitc::ORDERING_MONOTONIC
;
575 case AtomicOrdering::Acquire
: return bitc::ORDERING_ACQUIRE
;
576 case AtomicOrdering::Release
: return bitc::ORDERING_RELEASE
;
577 case AtomicOrdering::AcquireRelease
: return bitc::ORDERING_ACQREL
;
578 case AtomicOrdering::SequentiallyConsistent
: return bitc::ORDERING_SEQCST
;
580 llvm_unreachable("Invalid ordering");
583 static void writeStringRecord(BitstreamWriter
&Stream
, unsigned Code
,
584 StringRef Str
, unsigned AbbrevToUse
) {
585 SmallVector
<unsigned, 64> Vals
;
587 // Code: [strchar x N]
588 for (unsigned i
= 0, e
= Str
.size(); i
!= e
; ++i
) {
589 if (AbbrevToUse
&& !BitCodeAbbrevOp::isChar6(Str
[i
]))
591 Vals
.push_back(Str
[i
]);
594 // Emit the finished record.
595 Stream
.EmitRecord(Code
, Vals
, AbbrevToUse
);
598 static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind
) {
600 case Attribute::Alignment
:
601 return bitc::ATTR_KIND_ALIGNMENT
;
602 case Attribute::AllocSize
:
603 return bitc::ATTR_KIND_ALLOC_SIZE
;
604 case Attribute::AlwaysInline
:
605 return bitc::ATTR_KIND_ALWAYS_INLINE
;
606 case Attribute::ArgMemOnly
:
607 return bitc::ATTR_KIND_ARGMEMONLY
;
608 case Attribute::Builtin
:
609 return bitc::ATTR_KIND_BUILTIN
;
610 case Attribute::ByVal
:
611 return bitc::ATTR_KIND_BY_VAL
;
612 case Attribute::Convergent
:
613 return bitc::ATTR_KIND_CONVERGENT
;
614 case Attribute::InAlloca
:
615 return bitc::ATTR_KIND_IN_ALLOCA
;
616 case Attribute::Cold
:
617 return bitc::ATTR_KIND_COLD
;
618 case Attribute::InaccessibleMemOnly
:
619 return bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY
;
620 case Attribute::InaccessibleMemOrArgMemOnly
:
621 return bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY
;
622 case Attribute::InlineHint
:
623 return bitc::ATTR_KIND_INLINE_HINT
;
624 case Attribute::InReg
:
625 return bitc::ATTR_KIND_IN_REG
;
626 case Attribute::JumpTable
:
627 return bitc::ATTR_KIND_JUMP_TABLE
;
628 case Attribute::MinSize
:
629 return bitc::ATTR_KIND_MIN_SIZE
;
630 case Attribute::Naked
:
631 return bitc::ATTR_KIND_NAKED
;
632 case Attribute::Nest
:
633 return bitc::ATTR_KIND_NEST
;
634 case Attribute::NoAlias
:
635 return bitc::ATTR_KIND_NO_ALIAS
;
636 case Attribute::NoBuiltin
:
637 return bitc::ATTR_KIND_NO_BUILTIN
;
638 case Attribute::NoCapture
:
639 return bitc::ATTR_KIND_NO_CAPTURE
;
640 case Attribute::NoDuplicate
:
641 return bitc::ATTR_KIND_NO_DUPLICATE
;
642 case Attribute::NoFree
:
643 return bitc::ATTR_KIND_NOFREE
;
644 case Attribute::NoImplicitFloat
:
645 return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT
;
646 case Attribute::NoInline
:
647 return bitc::ATTR_KIND_NO_INLINE
;
648 case Attribute::NoRecurse
:
649 return bitc::ATTR_KIND_NO_RECURSE
;
650 case Attribute::NonLazyBind
:
651 return bitc::ATTR_KIND_NON_LAZY_BIND
;
652 case Attribute::NonNull
:
653 return bitc::ATTR_KIND_NON_NULL
;
654 case Attribute::Dereferenceable
:
655 return bitc::ATTR_KIND_DEREFERENCEABLE
;
656 case Attribute::DereferenceableOrNull
:
657 return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL
;
658 case Attribute::NoRedZone
:
659 return bitc::ATTR_KIND_NO_RED_ZONE
;
660 case Attribute::NoReturn
:
661 return bitc::ATTR_KIND_NO_RETURN
;
662 case Attribute::NoSync
:
663 return bitc::ATTR_KIND_NOSYNC
;
664 case Attribute::NoCfCheck
:
665 return bitc::ATTR_KIND_NOCF_CHECK
;
666 case Attribute::NoUnwind
:
667 return bitc::ATTR_KIND_NO_UNWIND
;
668 case Attribute::OptForFuzzing
:
669 return bitc::ATTR_KIND_OPT_FOR_FUZZING
;
670 case Attribute::OptimizeForSize
:
671 return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE
;
672 case Attribute::OptimizeNone
:
673 return bitc::ATTR_KIND_OPTIMIZE_NONE
;
674 case Attribute::ReadNone
:
675 return bitc::ATTR_KIND_READ_NONE
;
676 case Attribute::ReadOnly
:
677 return bitc::ATTR_KIND_READ_ONLY
;
678 case Attribute::Returned
:
679 return bitc::ATTR_KIND_RETURNED
;
680 case Attribute::ReturnsTwice
:
681 return bitc::ATTR_KIND_RETURNS_TWICE
;
682 case Attribute::SExt
:
683 return bitc::ATTR_KIND_S_EXT
;
684 case Attribute::Speculatable
:
685 return bitc::ATTR_KIND_SPECULATABLE
;
686 case Attribute::StackAlignment
:
687 return bitc::ATTR_KIND_STACK_ALIGNMENT
;
688 case Attribute::StackProtect
:
689 return bitc::ATTR_KIND_STACK_PROTECT
;
690 case Attribute::StackProtectReq
:
691 return bitc::ATTR_KIND_STACK_PROTECT_REQ
;
692 case Attribute::StackProtectStrong
:
693 return bitc::ATTR_KIND_STACK_PROTECT_STRONG
;
694 case Attribute::SafeStack
:
695 return bitc::ATTR_KIND_SAFESTACK
;
696 case Attribute::ShadowCallStack
:
697 return bitc::ATTR_KIND_SHADOWCALLSTACK
;
698 case Attribute::StrictFP
:
699 return bitc::ATTR_KIND_STRICT_FP
;
700 case Attribute::StructRet
:
701 return bitc::ATTR_KIND_STRUCT_RET
;
702 case Attribute::SanitizeAddress
:
703 return bitc::ATTR_KIND_SANITIZE_ADDRESS
;
704 case Attribute::SanitizeHWAddress
:
705 return bitc::ATTR_KIND_SANITIZE_HWADDRESS
;
706 case Attribute::SanitizeThread
:
707 return bitc::ATTR_KIND_SANITIZE_THREAD
;
708 case Attribute::SanitizeMemory
:
709 return bitc::ATTR_KIND_SANITIZE_MEMORY
;
710 case Attribute::SpeculativeLoadHardening
:
711 return bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING
;
712 case Attribute::SwiftError
:
713 return bitc::ATTR_KIND_SWIFT_ERROR
;
714 case Attribute::SwiftSelf
:
715 return bitc::ATTR_KIND_SWIFT_SELF
;
716 case Attribute::UWTable
:
717 return bitc::ATTR_KIND_UW_TABLE
;
718 case Attribute::WillReturn
:
719 return bitc::ATTR_KIND_WILLRETURN
;
720 case Attribute::WriteOnly
:
721 return bitc::ATTR_KIND_WRITEONLY
;
722 case Attribute::ZExt
:
723 return bitc::ATTR_KIND_Z_EXT
;
724 case Attribute::ImmArg
:
725 return bitc::ATTR_KIND_IMMARG
;
726 case Attribute::EndAttrKinds
:
727 llvm_unreachable("Can not encode end-attribute kinds marker.");
728 case Attribute::None
:
729 llvm_unreachable("Can not encode none-attribute.");
732 llvm_unreachable("Trying to encode unknown attribute");
735 void ModuleBitcodeWriter::writeAttributeGroupTable() {
736 const std::vector
<ValueEnumerator::IndexAndAttrSet
> &AttrGrps
=
737 VE
.getAttributeGroups();
738 if (AttrGrps
.empty()) return;
740 Stream
.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID
, 3);
742 SmallVector
<uint64_t, 64> Record
;
743 for (ValueEnumerator::IndexAndAttrSet Pair
: AttrGrps
) {
744 unsigned AttrListIndex
= Pair
.first
;
745 AttributeSet AS
= Pair
.second
;
746 Record
.push_back(VE
.getAttributeGroupID(Pair
));
747 Record
.push_back(AttrListIndex
);
749 for (Attribute Attr
: AS
) {
750 if (Attr
.isEnumAttribute()) {
752 Record
.push_back(getAttrKindEncoding(Attr
.getKindAsEnum()));
753 } else if (Attr
.isIntAttribute()) {
755 Record
.push_back(getAttrKindEncoding(Attr
.getKindAsEnum()));
756 Record
.push_back(Attr
.getValueAsInt());
757 } else if (Attr
.isStringAttribute()) {
758 StringRef Kind
= Attr
.getKindAsString();
759 StringRef Val
= Attr
.getValueAsString();
761 Record
.push_back(Val
.empty() ? 3 : 4);
762 Record
.append(Kind
.begin(), Kind
.end());
765 Record
.append(Val
.begin(), Val
.end());
769 assert(Attr
.isTypeAttribute());
770 Type
*Ty
= Attr
.getValueAsType();
771 Record
.push_back(Ty
? 6 : 5);
772 Record
.push_back(getAttrKindEncoding(Attr
.getKindAsEnum()));
774 Record
.push_back(VE
.getTypeID(Attr
.getValueAsType()));
778 Stream
.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY
, Record
);
785 void ModuleBitcodeWriter::writeAttributeTable() {
786 const std::vector
<AttributeList
> &Attrs
= VE
.getAttributeLists();
787 if (Attrs
.empty()) return;
789 Stream
.EnterSubblock(bitc::PARAMATTR_BLOCK_ID
, 3);
791 SmallVector
<uint64_t, 64> Record
;
792 for (unsigned i
= 0, e
= Attrs
.size(); i
!= e
; ++i
) {
793 AttributeList AL
= Attrs
[i
];
794 for (unsigned i
= AL
.index_begin(), e
= AL
.index_end(); i
!= e
; ++i
) {
795 AttributeSet AS
= AL
.getAttributes(i
);
796 if (AS
.hasAttributes())
797 Record
.push_back(VE
.getAttributeGroupID({i
, AS
}));
800 Stream
.EmitRecord(bitc::PARAMATTR_CODE_ENTRY
, Record
);
807 /// WriteTypeTable - Write out the type table for a module.
808 void ModuleBitcodeWriter::writeTypeTable() {
809 const ValueEnumerator::TypeList
&TypeList
= VE
.getTypes();
811 Stream
.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW
, 4 /*count from # abbrevs */);
812 SmallVector
<uint64_t, 64> TypeVals
;
814 uint64_t NumBits
= VE
.computeBitsRequiredForTypeIndicies();
816 // Abbrev for TYPE_CODE_POINTER.
817 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
818 Abbv
->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER
));
819 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, NumBits
));
820 Abbv
->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
821 unsigned PtrAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
823 // Abbrev for TYPE_CODE_FUNCTION.
824 Abbv
= std::make_shared
<BitCodeAbbrev
>();
825 Abbv
->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION
));
826 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 1)); // isvararg
827 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
828 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, NumBits
));
829 unsigned FunctionAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
831 // Abbrev for TYPE_CODE_STRUCT_ANON.
832 Abbv
= std::make_shared
<BitCodeAbbrev
>();
833 Abbv
->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON
));
834 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 1)); // ispacked
835 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
836 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, NumBits
));
837 unsigned StructAnonAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
839 // Abbrev for TYPE_CODE_STRUCT_NAME.
840 Abbv
= std::make_shared
<BitCodeAbbrev
>();
841 Abbv
->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME
));
842 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
843 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6
));
844 unsigned StructNameAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
846 // Abbrev for TYPE_CODE_STRUCT_NAMED.
847 Abbv
= std::make_shared
<BitCodeAbbrev
>();
848 Abbv
->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED
));
849 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 1)); // ispacked
850 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
851 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, NumBits
));
852 unsigned StructNamedAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
854 // Abbrev for TYPE_CODE_ARRAY.
855 Abbv
= std::make_shared
<BitCodeAbbrev
>();
856 Abbv
->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY
));
857 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // size
858 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, NumBits
));
859 unsigned ArrayAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
861 // Emit an entry count so the reader can reserve space.
862 TypeVals
.push_back(TypeList
.size());
863 Stream
.EmitRecord(bitc::TYPE_CODE_NUMENTRY
, TypeVals
);
866 // Loop over all of the types, emitting each in turn.
867 for (unsigned i
= 0, e
= TypeList
.size(); i
!= e
; ++i
) {
868 Type
*T
= TypeList
[i
];
872 switch (T
->getTypeID()) {
873 case Type::VoidTyID
: Code
= bitc::TYPE_CODE_VOID
; break;
874 case Type::HalfTyID
: Code
= bitc::TYPE_CODE_HALF
; break;
875 case Type::FloatTyID
: Code
= bitc::TYPE_CODE_FLOAT
; break;
876 case Type::DoubleTyID
: Code
= bitc::TYPE_CODE_DOUBLE
; break;
877 case Type::X86_FP80TyID
: Code
= bitc::TYPE_CODE_X86_FP80
; break;
878 case Type::FP128TyID
: Code
= bitc::TYPE_CODE_FP128
; break;
879 case Type::PPC_FP128TyID
: Code
= bitc::TYPE_CODE_PPC_FP128
; break;
880 case Type::LabelTyID
: Code
= bitc::TYPE_CODE_LABEL
; break;
881 case Type::MetadataTyID
: Code
= bitc::TYPE_CODE_METADATA
; break;
882 case Type::X86_MMXTyID
: Code
= bitc::TYPE_CODE_X86_MMX
; break;
883 case Type::TokenTyID
: Code
= bitc::TYPE_CODE_TOKEN
; break;
884 case Type::IntegerTyID
:
886 Code
= bitc::TYPE_CODE_INTEGER
;
887 TypeVals
.push_back(cast
<IntegerType
>(T
)->getBitWidth());
889 case Type::PointerTyID
: {
890 PointerType
*PTy
= cast
<PointerType
>(T
);
891 // POINTER: [pointee type, address space]
892 Code
= bitc::TYPE_CODE_POINTER
;
893 TypeVals
.push_back(VE
.getTypeID(PTy
->getElementType()));
894 unsigned AddressSpace
= PTy
->getAddressSpace();
895 TypeVals
.push_back(AddressSpace
);
896 if (AddressSpace
== 0) AbbrevToUse
= PtrAbbrev
;
899 case Type::FunctionTyID
: {
900 FunctionType
*FT
= cast
<FunctionType
>(T
);
901 // FUNCTION: [isvararg, retty, paramty x N]
902 Code
= bitc::TYPE_CODE_FUNCTION
;
903 TypeVals
.push_back(FT
->isVarArg());
904 TypeVals
.push_back(VE
.getTypeID(FT
->getReturnType()));
905 for (unsigned i
= 0, e
= FT
->getNumParams(); i
!= e
; ++i
)
906 TypeVals
.push_back(VE
.getTypeID(FT
->getParamType(i
)));
907 AbbrevToUse
= FunctionAbbrev
;
910 case Type::StructTyID
: {
911 StructType
*ST
= cast
<StructType
>(T
);
912 // STRUCT: [ispacked, eltty x N]
913 TypeVals
.push_back(ST
->isPacked());
914 // Output all of the element types.
915 for (StructType::element_iterator I
= ST
->element_begin(),
916 E
= ST
->element_end(); I
!= E
; ++I
)
917 TypeVals
.push_back(VE
.getTypeID(*I
));
919 if (ST
->isLiteral()) {
920 Code
= bitc::TYPE_CODE_STRUCT_ANON
;
921 AbbrevToUse
= StructAnonAbbrev
;
923 if (ST
->isOpaque()) {
924 Code
= bitc::TYPE_CODE_OPAQUE
;
926 Code
= bitc::TYPE_CODE_STRUCT_NAMED
;
927 AbbrevToUse
= StructNamedAbbrev
;
930 // Emit the name if it is present.
931 if (!ST
->getName().empty())
932 writeStringRecord(Stream
, bitc::TYPE_CODE_STRUCT_NAME
, ST
->getName(),
937 case Type::ArrayTyID
: {
938 ArrayType
*AT
= cast
<ArrayType
>(T
);
939 // ARRAY: [numelts, eltty]
940 Code
= bitc::TYPE_CODE_ARRAY
;
941 TypeVals
.push_back(AT
->getNumElements());
942 TypeVals
.push_back(VE
.getTypeID(AT
->getElementType()));
943 AbbrevToUse
= ArrayAbbrev
;
946 case Type::VectorTyID
: {
947 VectorType
*VT
= cast
<VectorType
>(T
);
948 // VECTOR [numelts, eltty] or
949 // [numelts, eltty, scalable]
950 Code
= bitc::TYPE_CODE_VECTOR
;
951 TypeVals
.push_back(VT
->getNumElements());
952 TypeVals
.push_back(VE
.getTypeID(VT
->getElementType()));
953 if (VT
->isScalable())
954 TypeVals
.push_back(VT
->isScalable());
959 // Emit the finished record.
960 Stream
.EmitRecord(Code
, TypeVals
, AbbrevToUse
);
967 static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage
) {
969 case GlobalValue::ExternalLinkage
:
971 case GlobalValue::WeakAnyLinkage
:
973 case GlobalValue::AppendingLinkage
:
975 case GlobalValue::InternalLinkage
:
977 case GlobalValue::LinkOnceAnyLinkage
:
979 case GlobalValue::ExternalWeakLinkage
:
981 case GlobalValue::CommonLinkage
:
983 case GlobalValue::PrivateLinkage
:
985 case GlobalValue::WeakODRLinkage
:
987 case GlobalValue::LinkOnceODRLinkage
:
989 case GlobalValue::AvailableExternallyLinkage
:
992 llvm_unreachable("Invalid linkage");
995 static unsigned getEncodedLinkage(const GlobalValue
&GV
) {
996 return getEncodedLinkage(GV
.getLinkage());
999 static uint64_t getEncodedFFlags(FunctionSummary::FFlags Flags
) {
1000 uint64_t RawFlags
= 0;
1001 RawFlags
|= Flags
.ReadNone
;
1002 RawFlags
|= (Flags
.ReadOnly
<< 1);
1003 RawFlags
|= (Flags
.NoRecurse
<< 2);
1004 RawFlags
|= (Flags
.ReturnDoesNotAlias
<< 3);
1005 RawFlags
|= (Flags
.NoInline
<< 4);
1009 // Decode the flags for GlobalValue in the summary
1010 static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags
) {
1011 uint64_t RawFlags
= 0;
1013 RawFlags
|= Flags
.NotEligibleToImport
; // bool
1014 RawFlags
|= (Flags
.Live
<< 1);
1015 RawFlags
|= (Flags
.DSOLocal
<< 2);
1016 RawFlags
|= (Flags
.CanAutoHide
<< 3);
1018 // Linkage don't need to be remapped at that time for the summary. Any future
1019 // change to the getEncodedLinkage() function will need to be taken into
1020 // account here as well.
1021 RawFlags
= (RawFlags
<< 4) | Flags
.Linkage
; // 4 bits
1026 static uint64_t getEncodedGVarFlags(GlobalVarSummary::GVarFlags Flags
) {
1027 uint64_t RawFlags
= Flags
.MaybeReadOnly
| (Flags
.MaybeWriteOnly
<< 1);
1031 static unsigned getEncodedVisibility(const GlobalValue
&GV
) {
1032 switch (GV
.getVisibility()) {
1033 case GlobalValue::DefaultVisibility
: return 0;
1034 case GlobalValue::HiddenVisibility
: return 1;
1035 case GlobalValue::ProtectedVisibility
: return 2;
1037 llvm_unreachable("Invalid visibility");
1040 static unsigned getEncodedDLLStorageClass(const GlobalValue
&GV
) {
1041 switch (GV
.getDLLStorageClass()) {
1042 case GlobalValue::DefaultStorageClass
: return 0;
1043 case GlobalValue::DLLImportStorageClass
: return 1;
1044 case GlobalValue::DLLExportStorageClass
: return 2;
1046 llvm_unreachable("Invalid DLL storage class");
1049 static unsigned getEncodedThreadLocalMode(const GlobalValue
&GV
) {
1050 switch (GV
.getThreadLocalMode()) {
1051 case GlobalVariable::NotThreadLocal
: return 0;
1052 case GlobalVariable::GeneralDynamicTLSModel
: return 1;
1053 case GlobalVariable::LocalDynamicTLSModel
: return 2;
1054 case GlobalVariable::InitialExecTLSModel
: return 3;
1055 case GlobalVariable::LocalExecTLSModel
: return 4;
1057 llvm_unreachable("Invalid TLS model");
1060 static unsigned getEncodedComdatSelectionKind(const Comdat
&C
) {
1061 switch (C
.getSelectionKind()) {
1063 return bitc::COMDAT_SELECTION_KIND_ANY
;
1064 case Comdat::ExactMatch
:
1065 return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH
;
1066 case Comdat::Largest
:
1067 return bitc::COMDAT_SELECTION_KIND_LARGEST
;
1068 case Comdat::NoDuplicates
:
1069 return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES
;
1070 case Comdat::SameSize
:
1071 return bitc::COMDAT_SELECTION_KIND_SAME_SIZE
;
1073 llvm_unreachable("Invalid selection kind");
1076 static unsigned getEncodedUnnamedAddr(const GlobalValue
&GV
) {
1077 switch (GV
.getUnnamedAddr()) {
1078 case GlobalValue::UnnamedAddr::None
: return 0;
1079 case GlobalValue::UnnamedAddr::Local
: return 2;
1080 case GlobalValue::UnnamedAddr::Global
: return 1;
1082 llvm_unreachable("Invalid unnamed_addr");
1085 size_t ModuleBitcodeWriter::addToStrtab(StringRef Str
) {
1088 return StrtabBuilder
.add(Str
);
1091 void ModuleBitcodeWriter::writeComdats() {
1092 SmallVector
<unsigned, 64> Vals
;
1093 for (const Comdat
*C
: VE
.getComdats()) {
1094 // COMDAT: [strtab offset, strtab size, selection_kind]
1095 Vals
.push_back(addToStrtab(C
->getName()));
1096 Vals
.push_back(C
->getName().size());
1097 Vals
.push_back(getEncodedComdatSelectionKind(*C
));
1098 Stream
.EmitRecord(bitc::MODULE_CODE_COMDAT
, Vals
, /*AbbrevToUse=*/0);
1103 /// Write a record that will eventually hold the word offset of the
1104 /// module-level VST. For now the offset is 0, which will be backpatched
1105 /// after the real VST is written. Saves the bit offset to backpatch.
1106 void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
1107 // Write a placeholder value in for the offset of the real VST,
1108 // which is written after the function blocks so that it can include
1109 // the offset of each function. The placeholder offset will be
1110 // updated when the real VST is written.
1111 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
1112 Abbv
->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET
));
1113 // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
1114 // hold the real VST offset. Must use fixed instead of VBR as we don't
1115 // know how many VBR chunks to reserve ahead of time.
1116 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 32));
1117 unsigned VSTOffsetAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
1119 // Emit the placeholder
1120 uint64_t Vals
[] = {bitc::MODULE_CODE_VSTOFFSET
, 0};
1121 Stream
.EmitRecordWithAbbrev(VSTOffsetAbbrev
, Vals
);
1123 // Compute and save the bit offset to the placeholder, which will be
1124 // patched when the real VST is written. We can simply subtract the 32-bit
1125 // fixed size from the current bit number to get the location to backpatch.
1126 VSTOffsetPlaceholder
= Stream
.GetCurrentBitNo() - 32;
1129 enum StringEncoding
{ SE_Char6
, SE_Fixed7
, SE_Fixed8
};
1131 /// Determine the encoding to use for the given string name and length.
1132 static StringEncoding
getStringEncoding(StringRef Str
) {
1133 bool isChar6
= true;
1134 for (char C
: Str
) {
1136 isChar6
= BitCodeAbbrevOp::isChar6(C
);
1137 if ((unsigned char)C
& 128)
1138 // don't bother scanning the rest.
1146 /// Emit top-level description of module, including target triple, inline asm,
1147 /// descriptors for global variables, and function prototype info.
1148 /// Returns the bit offset to backpatch with the location of the real VST.
1149 void ModuleBitcodeWriter::writeModuleInfo() {
1150 // Emit various pieces of data attached to a module.
1151 if (!M
.getTargetTriple().empty())
1152 writeStringRecord(Stream
, bitc::MODULE_CODE_TRIPLE
, M
.getTargetTriple(),
1154 const std::string
&DL
= M
.getDataLayoutStr();
1156 writeStringRecord(Stream
, bitc::MODULE_CODE_DATALAYOUT
, DL
, 0 /*TODO*/);
1157 if (!M
.getModuleInlineAsm().empty())
1158 writeStringRecord(Stream
, bitc::MODULE_CODE_ASM
, M
.getModuleInlineAsm(),
1161 // Emit information about sections and GC, computing how many there are. Also
1162 // compute the maximum alignment value.
1163 std::map
<std::string
, unsigned> SectionMap
;
1164 std::map
<std::string
, unsigned> GCMap
;
1165 unsigned MaxAlignment
= 0;
1166 unsigned MaxGlobalType
= 0;
1167 for (const GlobalValue
&GV
: M
.globals()) {
1168 MaxAlignment
= std::max(MaxAlignment
, GV
.getAlignment());
1169 MaxGlobalType
= std::max(MaxGlobalType
, VE
.getTypeID(GV
.getValueType()));
1170 if (GV
.hasSection()) {
1171 // Give section names unique ID's.
1172 unsigned &Entry
= SectionMap
[GV
.getSection()];
1174 writeStringRecord(Stream
, bitc::MODULE_CODE_SECTIONNAME
, GV
.getSection(),
1176 Entry
= SectionMap
.size();
1180 for (const Function
&F
: M
) {
1181 MaxAlignment
= std::max(MaxAlignment
, F
.getAlignment());
1182 if (F
.hasSection()) {
1183 // Give section names unique ID's.
1184 unsigned &Entry
= SectionMap
[F
.getSection()];
1186 writeStringRecord(Stream
, bitc::MODULE_CODE_SECTIONNAME
, F
.getSection(),
1188 Entry
= SectionMap
.size();
1192 // Same for GC names.
1193 unsigned &Entry
= GCMap
[F
.getGC()];
1195 writeStringRecord(Stream
, bitc::MODULE_CODE_GCNAME
, F
.getGC(),
1197 Entry
= GCMap
.size();
1202 // Emit abbrev for globals, now that we know # sections and max alignment.
1203 unsigned SimpleGVarAbbrev
= 0;
1204 if (!M
.global_empty()) {
1205 // Add an abbrev for common globals with no visibility or thread localness.
1206 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
1207 Abbv
->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR
));
1208 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8));
1209 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8));
1210 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
,
1211 Log2_32_Ceil(MaxGlobalType
+1)));
1212 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6)); // AddrSpace << 2
1213 //| explicitType << 1
1215 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6)); // Initializer.
1216 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 5)); // Linkage.
1217 if (MaxAlignment
== 0) // Alignment.
1218 Abbv
->Add(BitCodeAbbrevOp(0));
1220 unsigned MaxEncAlignment
= Log2_32(MaxAlignment
)+1;
1221 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
,
1222 Log2_32_Ceil(MaxEncAlignment
+1)));
1224 if (SectionMap
.empty()) // Section.
1225 Abbv
->Add(BitCodeAbbrevOp(0));
1227 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
,
1228 Log2_32_Ceil(SectionMap
.size()+1)));
1229 // Don't bother emitting vis + thread local.
1230 SimpleGVarAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
1233 SmallVector
<unsigned, 64> Vals
;
1234 // Emit the module's source file name.
1236 StringEncoding Bits
= getStringEncoding(M
.getSourceFileName());
1237 BitCodeAbbrevOp AbbrevOpToUse
= BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 8);
1238 if (Bits
== SE_Char6
)
1239 AbbrevOpToUse
= BitCodeAbbrevOp(BitCodeAbbrevOp::Char6
);
1240 else if (Bits
== SE_Fixed7
)
1241 AbbrevOpToUse
= BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 7);
1243 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
1244 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
1245 Abbv
->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME
));
1246 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
1247 Abbv
->Add(AbbrevOpToUse
);
1248 unsigned FilenameAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
1250 for (const auto P
: M
.getSourceFileName())
1251 Vals
.push_back((unsigned char)P
);
1253 // Emit the finished record.
1254 Stream
.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME
, Vals
, FilenameAbbrev
);
1258 // Emit the global variable information.
1259 for (const GlobalVariable
&GV
: M
.globals()) {
1260 unsigned AbbrevToUse
= 0;
1262 // GLOBALVAR: [strtab offset, strtab size, type, isconst, initid,
1263 // linkage, alignment, section, visibility, threadlocal,
1264 // unnamed_addr, externally_initialized, dllstorageclass,
1265 // comdat, attributes, DSO_Local]
1266 Vals
.push_back(addToStrtab(GV
.getName()));
1267 Vals
.push_back(GV
.getName().size());
1268 Vals
.push_back(VE
.getTypeID(GV
.getValueType()));
1269 Vals
.push_back(GV
.getType()->getAddressSpace() << 2 | 2 | GV
.isConstant());
1270 Vals
.push_back(GV
.isDeclaration() ? 0 :
1271 (VE
.getValueID(GV
.getInitializer()) + 1));
1272 Vals
.push_back(getEncodedLinkage(GV
));
1273 Vals
.push_back(Log2_32(GV
.getAlignment())+1);
1274 Vals
.push_back(GV
.hasSection() ? SectionMap
[GV
.getSection()] : 0);
1275 if (GV
.isThreadLocal() ||
1276 GV
.getVisibility() != GlobalValue::DefaultVisibility
||
1277 GV
.getUnnamedAddr() != GlobalValue::UnnamedAddr::None
||
1278 GV
.isExternallyInitialized() ||
1279 GV
.getDLLStorageClass() != GlobalValue::DefaultStorageClass
||
1281 GV
.hasAttributes() ||
1283 GV
.hasPartition()) {
1284 Vals
.push_back(getEncodedVisibility(GV
));
1285 Vals
.push_back(getEncodedThreadLocalMode(GV
));
1286 Vals
.push_back(getEncodedUnnamedAddr(GV
));
1287 Vals
.push_back(GV
.isExternallyInitialized());
1288 Vals
.push_back(getEncodedDLLStorageClass(GV
));
1289 Vals
.push_back(GV
.hasComdat() ? VE
.getComdatID(GV
.getComdat()) : 0);
1291 auto AL
= GV
.getAttributesAsList(AttributeList::FunctionIndex
);
1292 Vals
.push_back(VE
.getAttributeListID(AL
));
1294 Vals
.push_back(GV
.isDSOLocal());
1295 Vals
.push_back(addToStrtab(GV
.getPartition()));
1296 Vals
.push_back(GV
.getPartition().size());
1298 AbbrevToUse
= SimpleGVarAbbrev
;
1301 Stream
.EmitRecord(bitc::MODULE_CODE_GLOBALVAR
, Vals
, AbbrevToUse
);
1305 // Emit the function proto information.
1306 for (const Function
&F
: M
) {
1307 // FUNCTION: [strtab offset, strtab size, type, callingconv, isproto,
1308 // linkage, paramattrs, alignment, section, visibility, gc,
1309 // unnamed_addr, prologuedata, dllstorageclass, comdat,
1310 // prefixdata, personalityfn, DSO_Local, addrspace]
1311 Vals
.push_back(addToStrtab(F
.getName()));
1312 Vals
.push_back(F
.getName().size());
1313 Vals
.push_back(VE
.getTypeID(F
.getFunctionType()));
1314 Vals
.push_back(F
.getCallingConv());
1315 Vals
.push_back(F
.isDeclaration());
1316 Vals
.push_back(getEncodedLinkage(F
));
1317 Vals
.push_back(VE
.getAttributeListID(F
.getAttributes()));
1318 Vals
.push_back(Log2_32(F
.getAlignment())+1);
1319 Vals
.push_back(F
.hasSection() ? SectionMap
[F
.getSection()] : 0);
1320 Vals
.push_back(getEncodedVisibility(F
));
1321 Vals
.push_back(F
.hasGC() ? GCMap
[F
.getGC()] : 0);
1322 Vals
.push_back(getEncodedUnnamedAddr(F
));
1323 Vals
.push_back(F
.hasPrologueData() ? (VE
.getValueID(F
.getPrologueData()) + 1)
1325 Vals
.push_back(getEncodedDLLStorageClass(F
));
1326 Vals
.push_back(F
.hasComdat() ? VE
.getComdatID(F
.getComdat()) : 0);
1327 Vals
.push_back(F
.hasPrefixData() ? (VE
.getValueID(F
.getPrefixData()) + 1)
1330 F
.hasPersonalityFn() ? (VE
.getValueID(F
.getPersonalityFn()) + 1) : 0);
1332 Vals
.push_back(F
.isDSOLocal());
1333 Vals
.push_back(F
.getAddressSpace());
1334 Vals
.push_back(addToStrtab(F
.getPartition()));
1335 Vals
.push_back(F
.getPartition().size());
1337 unsigned AbbrevToUse
= 0;
1338 Stream
.EmitRecord(bitc::MODULE_CODE_FUNCTION
, Vals
, AbbrevToUse
);
1342 // Emit the alias information.
1343 for (const GlobalAlias
&A
: M
.aliases()) {
1344 // ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage,
1345 // visibility, dllstorageclass, threadlocal, unnamed_addr,
1347 Vals
.push_back(addToStrtab(A
.getName()));
1348 Vals
.push_back(A
.getName().size());
1349 Vals
.push_back(VE
.getTypeID(A
.getValueType()));
1350 Vals
.push_back(A
.getType()->getAddressSpace());
1351 Vals
.push_back(VE
.getValueID(A
.getAliasee()));
1352 Vals
.push_back(getEncodedLinkage(A
));
1353 Vals
.push_back(getEncodedVisibility(A
));
1354 Vals
.push_back(getEncodedDLLStorageClass(A
));
1355 Vals
.push_back(getEncodedThreadLocalMode(A
));
1356 Vals
.push_back(getEncodedUnnamedAddr(A
));
1357 Vals
.push_back(A
.isDSOLocal());
1358 Vals
.push_back(addToStrtab(A
.getPartition()));
1359 Vals
.push_back(A
.getPartition().size());
1361 unsigned AbbrevToUse
= 0;
1362 Stream
.EmitRecord(bitc::MODULE_CODE_ALIAS
, Vals
, AbbrevToUse
);
1366 // Emit the ifunc information.
1367 for (const GlobalIFunc
&I
: M
.ifuncs()) {
1368 // IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver
1369 // val#, linkage, visibility, DSO_Local]
1370 Vals
.push_back(addToStrtab(I
.getName()));
1371 Vals
.push_back(I
.getName().size());
1372 Vals
.push_back(VE
.getTypeID(I
.getValueType()));
1373 Vals
.push_back(I
.getType()->getAddressSpace());
1374 Vals
.push_back(VE
.getValueID(I
.getResolver()));
1375 Vals
.push_back(getEncodedLinkage(I
));
1376 Vals
.push_back(getEncodedVisibility(I
));
1377 Vals
.push_back(I
.isDSOLocal());
1378 Vals
.push_back(addToStrtab(I
.getPartition()));
1379 Vals
.push_back(I
.getPartition().size());
1380 Stream
.EmitRecord(bitc::MODULE_CODE_IFUNC
, Vals
);
1384 writeValueSymbolTableForwardDecl();
1387 static uint64_t getOptimizationFlags(const Value
*V
) {
1390 if (const auto *OBO
= dyn_cast
<OverflowingBinaryOperator
>(V
)) {
1391 if (OBO
->hasNoSignedWrap())
1392 Flags
|= 1 << bitc::OBO_NO_SIGNED_WRAP
;
1393 if (OBO
->hasNoUnsignedWrap())
1394 Flags
|= 1 << bitc::OBO_NO_UNSIGNED_WRAP
;
1395 } else if (const auto *PEO
= dyn_cast
<PossiblyExactOperator
>(V
)) {
1397 Flags
|= 1 << bitc::PEO_EXACT
;
1398 } else if (const auto *FPMO
= dyn_cast
<FPMathOperator
>(V
)) {
1399 if (FPMO
->hasAllowReassoc())
1400 Flags
|= bitc::AllowReassoc
;
1401 if (FPMO
->hasNoNaNs())
1402 Flags
|= bitc::NoNaNs
;
1403 if (FPMO
->hasNoInfs())
1404 Flags
|= bitc::NoInfs
;
1405 if (FPMO
->hasNoSignedZeros())
1406 Flags
|= bitc::NoSignedZeros
;
1407 if (FPMO
->hasAllowReciprocal())
1408 Flags
|= bitc::AllowReciprocal
;
1409 if (FPMO
->hasAllowContract())
1410 Flags
|= bitc::AllowContract
;
1411 if (FPMO
->hasApproxFunc())
1412 Flags
|= bitc::ApproxFunc
;
1418 void ModuleBitcodeWriter::writeValueAsMetadata(
1419 const ValueAsMetadata
*MD
, SmallVectorImpl
<uint64_t> &Record
) {
1420 // Mimic an MDNode with a value as one operand.
1421 Value
*V
= MD
->getValue();
1422 Record
.push_back(VE
.getTypeID(V
->getType()));
1423 Record
.push_back(VE
.getValueID(V
));
1424 Stream
.EmitRecord(bitc::METADATA_VALUE
, Record
, 0);
1428 void ModuleBitcodeWriter::writeMDTuple(const MDTuple
*N
,
1429 SmallVectorImpl
<uint64_t> &Record
,
1431 for (unsigned i
= 0, e
= N
->getNumOperands(); i
!= e
; ++i
) {
1432 Metadata
*MD
= N
->getOperand(i
);
1433 assert(!(MD
&& isa
<LocalAsMetadata
>(MD
)) &&
1434 "Unexpected function-local metadata");
1435 Record
.push_back(VE
.getMetadataOrNullID(MD
));
1437 Stream
.EmitRecord(N
->isDistinct() ? bitc::METADATA_DISTINCT_NODE
1438 : bitc::METADATA_NODE
,
1443 unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
1444 // Assume the column is usually under 128, and always output the inlined-at
1445 // location (it's never more expensive than building an array size 1).
1446 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
1447 Abbv
->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION
));
1448 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 1));
1449 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6));
1450 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8));
1451 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6));
1452 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6));
1453 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 1));
1454 return Stream
.EmitAbbrev(std::move(Abbv
));
1457 void ModuleBitcodeWriter::writeDILocation(const DILocation
*N
,
1458 SmallVectorImpl
<uint64_t> &Record
,
1461 Abbrev
= createDILocationAbbrev();
1463 Record
.push_back(N
->isDistinct());
1464 Record
.push_back(N
->getLine());
1465 Record
.push_back(N
->getColumn());
1466 Record
.push_back(VE
.getMetadataID(N
->getScope()));
1467 Record
.push_back(VE
.getMetadataOrNullID(N
->getInlinedAt()));
1468 Record
.push_back(N
->isImplicitCode());
1470 Stream
.EmitRecord(bitc::METADATA_LOCATION
, Record
, Abbrev
);
1474 unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
1475 // Assume the column is usually under 128, and always output the inlined-at
1476 // location (it's never more expensive than building an array size 1).
1477 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
1478 Abbv
->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG
));
1479 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 1));
1480 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6));
1481 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 1));
1482 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6));
1483 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
1484 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6));
1485 return Stream
.EmitAbbrev(std::move(Abbv
));
1488 void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode
*N
,
1489 SmallVectorImpl
<uint64_t> &Record
,
1492 Abbrev
= createGenericDINodeAbbrev();
1494 Record
.push_back(N
->isDistinct());
1495 Record
.push_back(N
->getTag());
1496 Record
.push_back(0); // Per-tag version field; unused for now.
1498 for (auto &I
: N
->operands())
1499 Record
.push_back(VE
.getMetadataOrNullID(I
));
1501 Stream
.EmitRecord(bitc::METADATA_GENERIC_DEBUG
, Record
, Abbrev
);
1505 static uint64_t rotateSign(int64_t I
) {
1507 return I
< 0 ? ~(U
<< 1) : U
<< 1;
1510 void ModuleBitcodeWriter::writeDISubrange(const DISubrange
*N
,
1511 SmallVectorImpl
<uint64_t> &Record
,
1513 const uint64_t Version
= 1 << 1;
1514 Record
.push_back((uint64_t)N
->isDistinct() | Version
);
1515 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawCountNode()));
1516 Record
.push_back(rotateSign(N
->getLowerBound()));
1518 Stream
.EmitRecord(bitc::METADATA_SUBRANGE
, Record
, Abbrev
);
1522 void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator
*N
,
1523 SmallVectorImpl
<uint64_t> &Record
,
1525 Record
.push_back((N
->isUnsigned() << 1) | N
->isDistinct());
1526 Record
.push_back(rotateSign(N
->getValue()));
1527 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawName()));
1529 Stream
.EmitRecord(bitc::METADATA_ENUMERATOR
, Record
, Abbrev
);
1533 void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType
*N
,
1534 SmallVectorImpl
<uint64_t> &Record
,
1536 Record
.push_back(N
->isDistinct());
1537 Record
.push_back(N
->getTag());
1538 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawName()));
1539 Record
.push_back(N
->getSizeInBits());
1540 Record
.push_back(N
->getAlignInBits());
1541 Record
.push_back(N
->getEncoding());
1542 Record
.push_back(N
->getFlags());
1544 Stream
.EmitRecord(bitc::METADATA_BASIC_TYPE
, Record
, Abbrev
);
1548 void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType
*N
,
1549 SmallVectorImpl
<uint64_t> &Record
,
1551 Record
.push_back(N
->isDistinct());
1552 Record
.push_back(N
->getTag());
1553 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawName()));
1554 Record
.push_back(VE
.getMetadataOrNullID(N
->getFile()));
1555 Record
.push_back(N
->getLine());
1556 Record
.push_back(VE
.getMetadataOrNullID(N
->getScope()));
1557 Record
.push_back(VE
.getMetadataOrNullID(N
->getBaseType()));
1558 Record
.push_back(N
->getSizeInBits());
1559 Record
.push_back(N
->getAlignInBits());
1560 Record
.push_back(N
->getOffsetInBits());
1561 Record
.push_back(N
->getFlags());
1562 Record
.push_back(VE
.getMetadataOrNullID(N
->getExtraData()));
1564 // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
1565 // that there is no DWARF address space associated with DIDerivedType.
1566 if (const auto &DWARFAddressSpace
= N
->getDWARFAddressSpace())
1567 Record
.push_back(*DWARFAddressSpace
+ 1);
1569 Record
.push_back(0);
1571 Stream
.EmitRecord(bitc::METADATA_DERIVED_TYPE
, Record
, Abbrev
);
1575 void ModuleBitcodeWriter::writeDICompositeType(
1576 const DICompositeType
*N
, SmallVectorImpl
<uint64_t> &Record
,
1578 const unsigned IsNotUsedInOldTypeRef
= 0x2;
1579 Record
.push_back(IsNotUsedInOldTypeRef
| (unsigned)N
->isDistinct());
1580 Record
.push_back(N
->getTag());
1581 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawName()));
1582 Record
.push_back(VE
.getMetadataOrNullID(N
->getFile()));
1583 Record
.push_back(N
->getLine());
1584 Record
.push_back(VE
.getMetadataOrNullID(N
->getScope()));
1585 Record
.push_back(VE
.getMetadataOrNullID(N
->getBaseType()));
1586 Record
.push_back(N
->getSizeInBits());
1587 Record
.push_back(N
->getAlignInBits());
1588 Record
.push_back(N
->getOffsetInBits());
1589 Record
.push_back(N
->getFlags());
1590 Record
.push_back(VE
.getMetadataOrNullID(N
->getElements().get()));
1591 Record
.push_back(N
->getRuntimeLang());
1592 Record
.push_back(VE
.getMetadataOrNullID(N
->getVTableHolder()));
1593 Record
.push_back(VE
.getMetadataOrNullID(N
->getTemplateParams().get()));
1594 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawIdentifier()));
1595 Record
.push_back(VE
.getMetadataOrNullID(N
->getDiscriminator()));
1597 Stream
.EmitRecord(bitc::METADATA_COMPOSITE_TYPE
, Record
, Abbrev
);
1601 void ModuleBitcodeWriter::writeDISubroutineType(
1602 const DISubroutineType
*N
, SmallVectorImpl
<uint64_t> &Record
,
1604 const unsigned HasNoOldTypeRefs
= 0x2;
1605 Record
.push_back(HasNoOldTypeRefs
| (unsigned)N
->isDistinct());
1606 Record
.push_back(N
->getFlags());
1607 Record
.push_back(VE
.getMetadataOrNullID(N
->getTypeArray().get()));
1608 Record
.push_back(N
->getCC());
1610 Stream
.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE
, Record
, Abbrev
);
1614 void ModuleBitcodeWriter::writeDIFile(const DIFile
*N
,
1615 SmallVectorImpl
<uint64_t> &Record
,
1617 Record
.push_back(N
->isDistinct());
1618 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawFilename()));
1619 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawDirectory()));
1620 if (N
->getRawChecksum()) {
1621 Record
.push_back(N
->getRawChecksum()->Kind
);
1622 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawChecksum()->Value
));
1624 // Maintain backwards compatibility with the old internal representation of
1625 // CSK_None in ChecksumKind by writing nulls here when Checksum is None.
1626 Record
.push_back(0);
1627 Record
.push_back(VE
.getMetadataOrNullID(nullptr));
1629 auto Source
= N
->getRawSource();
1631 Record
.push_back(VE
.getMetadataOrNullID(*Source
));
1633 Stream
.EmitRecord(bitc::METADATA_FILE
, Record
, Abbrev
);
1637 void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit
*N
,
1638 SmallVectorImpl
<uint64_t> &Record
,
1640 assert(N
->isDistinct() && "Expected distinct compile units");
1641 Record
.push_back(/* IsDistinct */ true);
1642 Record
.push_back(N
->getSourceLanguage());
1643 Record
.push_back(VE
.getMetadataOrNullID(N
->getFile()));
1644 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawProducer()));
1645 Record
.push_back(N
->isOptimized());
1646 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawFlags()));
1647 Record
.push_back(N
->getRuntimeVersion());
1648 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawSplitDebugFilename()));
1649 Record
.push_back(N
->getEmissionKind());
1650 Record
.push_back(VE
.getMetadataOrNullID(N
->getEnumTypes().get()));
1651 Record
.push_back(VE
.getMetadataOrNullID(N
->getRetainedTypes().get()));
1652 Record
.push_back(/* subprograms */ 0);
1653 Record
.push_back(VE
.getMetadataOrNullID(N
->getGlobalVariables().get()));
1654 Record
.push_back(VE
.getMetadataOrNullID(N
->getImportedEntities().get()));
1655 Record
.push_back(N
->getDWOId());
1656 Record
.push_back(VE
.getMetadataOrNullID(N
->getMacros().get()));
1657 Record
.push_back(N
->getSplitDebugInlining());
1658 Record
.push_back(N
->getDebugInfoForProfiling());
1659 Record
.push_back((unsigned)N
->getNameTableKind());
1661 Stream
.EmitRecord(bitc::METADATA_COMPILE_UNIT
, Record
, Abbrev
);
1665 void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram
*N
,
1666 SmallVectorImpl
<uint64_t> &Record
,
1668 const uint64_t HasUnitFlag
= 1 << 1;
1669 const uint64_t HasSPFlagsFlag
= 1 << 2;
1670 Record
.push_back(uint64_t(N
->isDistinct()) | HasUnitFlag
| HasSPFlagsFlag
);
1671 Record
.push_back(VE
.getMetadataOrNullID(N
->getScope()));
1672 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawName()));
1673 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawLinkageName()));
1674 Record
.push_back(VE
.getMetadataOrNullID(N
->getFile()));
1675 Record
.push_back(N
->getLine());
1676 Record
.push_back(VE
.getMetadataOrNullID(N
->getType()));
1677 Record
.push_back(N
->getScopeLine());
1678 Record
.push_back(VE
.getMetadataOrNullID(N
->getContainingType()));
1679 Record
.push_back(N
->getSPFlags());
1680 Record
.push_back(N
->getVirtualIndex());
1681 Record
.push_back(N
->getFlags());
1682 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawUnit()));
1683 Record
.push_back(VE
.getMetadataOrNullID(N
->getTemplateParams().get()));
1684 Record
.push_back(VE
.getMetadataOrNullID(N
->getDeclaration()));
1685 Record
.push_back(VE
.getMetadataOrNullID(N
->getRetainedNodes().get()));
1686 Record
.push_back(N
->getThisAdjustment());
1687 Record
.push_back(VE
.getMetadataOrNullID(N
->getThrownTypes().get()));
1689 Stream
.EmitRecord(bitc::METADATA_SUBPROGRAM
, Record
, Abbrev
);
1693 void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock
*N
,
1694 SmallVectorImpl
<uint64_t> &Record
,
1696 Record
.push_back(N
->isDistinct());
1697 Record
.push_back(VE
.getMetadataOrNullID(N
->getScope()));
1698 Record
.push_back(VE
.getMetadataOrNullID(N
->getFile()));
1699 Record
.push_back(N
->getLine());
1700 Record
.push_back(N
->getColumn());
1702 Stream
.EmitRecord(bitc::METADATA_LEXICAL_BLOCK
, Record
, Abbrev
);
1706 void ModuleBitcodeWriter::writeDILexicalBlockFile(
1707 const DILexicalBlockFile
*N
, SmallVectorImpl
<uint64_t> &Record
,
1709 Record
.push_back(N
->isDistinct());
1710 Record
.push_back(VE
.getMetadataOrNullID(N
->getScope()));
1711 Record
.push_back(VE
.getMetadataOrNullID(N
->getFile()));
1712 Record
.push_back(N
->getDiscriminator());
1714 Stream
.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE
, Record
, Abbrev
);
1718 void ModuleBitcodeWriter::writeDICommonBlock(const DICommonBlock
*N
,
1719 SmallVectorImpl
<uint64_t> &Record
,
1721 Record
.push_back(N
->isDistinct());
1722 Record
.push_back(VE
.getMetadataOrNullID(N
->getScope()));
1723 Record
.push_back(VE
.getMetadataOrNullID(N
->getDecl()));
1724 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawName()));
1725 Record
.push_back(VE
.getMetadataOrNullID(N
->getFile()));
1726 Record
.push_back(N
->getLineNo());
1728 Stream
.EmitRecord(bitc::METADATA_COMMON_BLOCK
, Record
, Abbrev
);
1732 void ModuleBitcodeWriter::writeDINamespace(const DINamespace
*N
,
1733 SmallVectorImpl
<uint64_t> &Record
,
1735 Record
.push_back(N
->isDistinct() | N
->getExportSymbols() << 1);
1736 Record
.push_back(VE
.getMetadataOrNullID(N
->getScope()));
1737 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawName()));
1739 Stream
.EmitRecord(bitc::METADATA_NAMESPACE
, Record
, Abbrev
);
1743 void ModuleBitcodeWriter::writeDIMacro(const DIMacro
*N
,
1744 SmallVectorImpl
<uint64_t> &Record
,
1746 Record
.push_back(N
->isDistinct());
1747 Record
.push_back(N
->getMacinfoType());
1748 Record
.push_back(N
->getLine());
1749 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawName()));
1750 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawValue()));
1752 Stream
.EmitRecord(bitc::METADATA_MACRO
, Record
, Abbrev
);
1756 void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile
*N
,
1757 SmallVectorImpl
<uint64_t> &Record
,
1759 Record
.push_back(N
->isDistinct());
1760 Record
.push_back(N
->getMacinfoType());
1761 Record
.push_back(N
->getLine());
1762 Record
.push_back(VE
.getMetadataOrNullID(N
->getFile()));
1763 Record
.push_back(VE
.getMetadataOrNullID(N
->getElements().get()));
1765 Stream
.EmitRecord(bitc::METADATA_MACRO_FILE
, Record
, Abbrev
);
1769 void ModuleBitcodeWriter::writeDIModule(const DIModule
*N
,
1770 SmallVectorImpl
<uint64_t> &Record
,
1772 Record
.push_back(N
->isDistinct());
1773 for (auto &I
: N
->operands())
1774 Record
.push_back(VE
.getMetadataOrNullID(I
));
1776 Stream
.EmitRecord(bitc::METADATA_MODULE
, Record
, Abbrev
);
1780 void ModuleBitcodeWriter::writeDITemplateTypeParameter(
1781 const DITemplateTypeParameter
*N
, SmallVectorImpl
<uint64_t> &Record
,
1783 Record
.push_back(N
->isDistinct());
1784 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawName()));
1785 Record
.push_back(VE
.getMetadataOrNullID(N
->getType()));
1787 Stream
.EmitRecord(bitc::METADATA_TEMPLATE_TYPE
, Record
, Abbrev
);
1791 void ModuleBitcodeWriter::writeDITemplateValueParameter(
1792 const DITemplateValueParameter
*N
, 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(VE
.getMetadataOrNullID(N
->getType()));
1798 Record
.push_back(VE
.getMetadataOrNullID(N
->getValue()));
1800 Stream
.EmitRecord(bitc::METADATA_TEMPLATE_VALUE
, Record
, Abbrev
);
1804 void ModuleBitcodeWriter::writeDIGlobalVariable(
1805 const DIGlobalVariable
*N
, SmallVectorImpl
<uint64_t> &Record
,
1807 const uint64_t Version
= 2 << 1;
1808 Record
.push_back((uint64_t)N
->isDistinct() | Version
);
1809 Record
.push_back(VE
.getMetadataOrNullID(N
->getScope()));
1810 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawName()));
1811 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawLinkageName()));
1812 Record
.push_back(VE
.getMetadataOrNullID(N
->getFile()));
1813 Record
.push_back(N
->getLine());
1814 Record
.push_back(VE
.getMetadataOrNullID(N
->getType()));
1815 Record
.push_back(N
->isLocalToUnit());
1816 Record
.push_back(N
->isDefinition());
1817 Record
.push_back(VE
.getMetadataOrNullID(N
->getStaticDataMemberDeclaration()));
1818 Record
.push_back(VE
.getMetadataOrNullID(N
->getTemplateParams()));
1819 Record
.push_back(N
->getAlignInBits());
1821 Stream
.EmitRecord(bitc::METADATA_GLOBAL_VAR
, Record
, Abbrev
);
1825 void ModuleBitcodeWriter::writeDILocalVariable(
1826 const DILocalVariable
*N
, SmallVectorImpl
<uint64_t> &Record
,
1828 // In order to support all possible bitcode formats in BitcodeReader we need
1829 // to distinguish the following cases:
1830 // 1) Record has no artificial tag (Record[1]),
1831 // has no obsolete inlinedAt field (Record[9]).
1832 // In this case Record size will be 8, HasAlignment flag is false.
1833 // 2) Record has artificial tag (Record[1]),
1834 // has no obsolete inlignedAt field (Record[9]).
1835 // In this case Record size will be 9, HasAlignment flag is false.
1836 // 3) Record has both artificial tag (Record[1]) and
1837 // obsolete inlignedAt field (Record[9]).
1838 // In this case Record size will be 10, HasAlignment flag is false.
1839 // 4) Record has neither artificial tag, nor inlignedAt field, but
1840 // HasAlignment flag is true and Record[8] contains alignment value.
1841 const uint64_t HasAlignmentFlag
= 1 << 1;
1842 Record
.push_back((uint64_t)N
->isDistinct() | HasAlignmentFlag
);
1843 Record
.push_back(VE
.getMetadataOrNullID(N
->getScope()));
1844 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawName()));
1845 Record
.push_back(VE
.getMetadataOrNullID(N
->getFile()));
1846 Record
.push_back(N
->getLine());
1847 Record
.push_back(VE
.getMetadataOrNullID(N
->getType()));
1848 Record
.push_back(N
->getArg());
1849 Record
.push_back(N
->getFlags());
1850 Record
.push_back(N
->getAlignInBits());
1852 Stream
.EmitRecord(bitc::METADATA_LOCAL_VAR
, Record
, Abbrev
);
1856 void ModuleBitcodeWriter::writeDILabel(
1857 const DILabel
*N
, SmallVectorImpl
<uint64_t> &Record
,
1859 Record
.push_back((uint64_t)N
->isDistinct());
1860 Record
.push_back(VE
.getMetadataOrNullID(N
->getScope()));
1861 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawName()));
1862 Record
.push_back(VE
.getMetadataOrNullID(N
->getFile()));
1863 Record
.push_back(N
->getLine());
1865 Stream
.EmitRecord(bitc::METADATA_LABEL
, Record
, Abbrev
);
1869 void ModuleBitcodeWriter::writeDIExpression(const DIExpression
*N
,
1870 SmallVectorImpl
<uint64_t> &Record
,
1872 Record
.reserve(N
->getElements().size() + 1);
1873 const uint64_t Version
= 3 << 1;
1874 Record
.push_back((uint64_t)N
->isDistinct() | Version
);
1875 Record
.append(N
->elements_begin(), N
->elements_end());
1877 Stream
.EmitRecord(bitc::METADATA_EXPRESSION
, Record
, Abbrev
);
1881 void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
1882 const DIGlobalVariableExpression
*N
, SmallVectorImpl
<uint64_t> &Record
,
1884 Record
.push_back(N
->isDistinct());
1885 Record
.push_back(VE
.getMetadataOrNullID(N
->getVariable()));
1886 Record
.push_back(VE
.getMetadataOrNullID(N
->getExpression()));
1888 Stream
.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR
, Record
, Abbrev
);
1892 void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty
*N
,
1893 SmallVectorImpl
<uint64_t> &Record
,
1895 Record
.push_back(N
->isDistinct());
1896 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawName()));
1897 Record
.push_back(VE
.getMetadataOrNullID(N
->getFile()));
1898 Record
.push_back(N
->getLine());
1899 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawSetterName()));
1900 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawGetterName()));
1901 Record
.push_back(N
->getAttributes());
1902 Record
.push_back(VE
.getMetadataOrNullID(N
->getType()));
1904 Stream
.EmitRecord(bitc::METADATA_OBJC_PROPERTY
, Record
, Abbrev
);
1908 void ModuleBitcodeWriter::writeDIImportedEntity(
1909 const DIImportedEntity
*N
, SmallVectorImpl
<uint64_t> &Record
,
1911 Record
.push_back(N
->isDistinct());
1912 Record
.push_back(N
->getTag());
1913 Record
.push_back(VE
.getMetadataOrNullID(N
->getScope()));
1914 Record
.push_back(VE
.getMetadataOrNullID(N
->getEntity()));
1915 Record
.push_back(N
->getLine());
1916 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawName()));
1917 Record
.push_back(VE
.getMetadataOrNullID(N
->getRawFile()));
1919 Stream
.EmitRecord(bitc::METADATA_IMPORTED_ENTITY
, Record
, Abbrev
);
1923 unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
1924 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
1925 Abbv
->Add(BitCodeAbbrevOp(bitc::METADATA_NAME
));
1926 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
1927 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 8));
1928 return Stream
.EmitAbbrev(std::move(Abbv
));
1931 void ModuleBitcodeWriter::writeNamedMetadata(
1932 SmallVectorImpl
<uint64_t> &Record
) {
1933 if (M
.named_metadata_empty())
1936 unsigned Abbrev
= createNamedMetadataAbbrev();
1937 for (const NamedMDNode
&NMD
: M
.named_metadata()) {
1939 StringRef Str
= NMD
.getName();
1940 Record
.append(Str
.bytes_begin(), Str
.bytes_end());
1941 Stream
.EmitRecord(bitc::METADATA_NAME
, Record
, Abbrev
);
1944 // Write named metadata operands.
1945 for (const MDNode
*N
: NMD
.operands())
1946 Record
.push_back(VE
.getMetadataID(N
));
1947 Stream
.EmitRecord(bitc::METADATA_NAMED_NODE
, Record
, 0);
1952 unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
1953 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
1954 Abbv
->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS
));
1955 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6)); // # of strings
1956 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6)); // offset to chars
1957 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob
));
1958 return Stream
.EmitAbbrev(std::move(Abbv
));
1961 /// Write out a record for MDString.
1963 /// All the metadata strings in a metadata block are emitted in a single
1964 /// record. The sizes and strings themselves are shoved into a blob.
1965 void ModuleBitcodeWriter::writeMetadataStrings(
1966 ArrayRef
<const Metadata
*> Strings
, SmallVectorImpl
<uint64_t> &Record
) {
1967 if (Strings
.empty())
1970 // Start the record with the number of strings.
1971 Record
.push_back(bitc::METADATA_STRINGS
);
1972 Record
.push_back(Strings
.size());
1974 // Emit the sizes of the strings in the blob.
1975 SmallString
<256> Blob
;
1977 BitstreamWriter
W(Blob
);
1978 for (const Metadata
*MD
: Strings
)
1979 W
.EmitVBR(cast
<MDString
>(MD
)->getLength(), 6);
1983 // Add the offset to the strings to the record.
1984 Record
.push_back(Blob
.size());
1986 // Add the strings to the blob.
1987 for (const Metadata
*MD
: Strings
)
1988 Blob
.append(cast
<MDString
>(MD
)->getString());
1990 // Emit the final record.
1991 Stream
.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record
, Blob
);
1995 // Generates an enum to use as an index in the Abbrev array of Metadata record.
1996 enum MetadataAbbrev
: unsigned {
1997 #define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
1998 #include "llvm/IR/Metadata.def"
2002 void ModuleBitcodeWriter::writeMetadataRecords(
2003 ArrayRef
<const Metadata
*> MDs
, SmallVectorImpl
<uint64_t> &Record
,
2004 std::vector
<unsigned> *MDAbbrevs
, std::vector
<uint64_t> *IndexPos
) {
2008 // Initialize MDNode abbreviations.
2009 #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
2010 #include "llvm/IR/Metadata.def"
2012 for (const Metadata
*MD
: MDs
) {
2014 IndexPos
->push_back(Stream
.GetCurrentBitNo());
2015 if (const MDNode
*N
= dyn_cast
<MDNode
>(MD
)) {
2016 assert(N
->isResolved() && "Expected forward references to be resolved");
2018 switch (N
->getMetadataID()) {
2020 llvm_unreachable("Invalid MDNode subclass");
2021 #define HANDLE_MDNODE_LEAF(CLASS) \
2022 case Metadata::CLASS##Kind: \
2024 write##CLASS(cast<CLASS>(N), Record, \
2025 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
2027 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
2029 #include "llvm/IR/Metadata.def"
2032 writeValueAsMetadata(cast
<ValueAsMetadata
>(MD
), Record
);
2036 void ModuleBitcodeWriter::writeModuleMetadata() {
2037 if (!VE
.hasMDs() && M
.named_metadata_empty())
2040 Stream
.EnterSubblock(bitc::METADATA_BLOCK_ID
, 4);
2041 SmallVector
<uint64_t, 64> Record
;
2043 // Emit all abbrevs upfront, so that the reader can jump in the middle of the
2044 // block and load any metadata.
2045 std::vector
<unsigned> MDAbbrevs
;
2047 MDAbbrevs
.resize(MetadataAbbrev::LastPlusOne
);
2048 MDAbbrevs
[MetadataAbbrev::DILocationAbbrevID
] = createDILocationAbbrev();
2049 MDAbbrevs
[MetadataAbbrev::GenericDINodeAbbrevID
] =
2050 createGenericDINodeAbbrev();
2052 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
2053 Abbv
->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX_OFFSET
));
2054 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 32));
2055 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 32));
2056 unsigned OffsetAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
2058 Abbv
= std::make_shared
<BitCodeAbbrev
>();
2059 Abbv
->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX
));
2060 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
2061 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6));
2062 unsigned IndexAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
2064 // Emit MDStrings together upfront.
2065 writeMetadataStrings(VE
.getMDStrings(), Record
);
2067 // We only emit an index for the metadata record if we have more than a given
2068 // (naive) threshold of metadatas, otherwise it is not worth it.
2069 if (VE
.getNonMDStrings().size() > IndexThreshold
) {
2070 // Write a placeholder value in for the offset of the metadata index,
2071 // which is written after the records, so that it can include
2072 // the offset of each entry. The placeholder offset will be
2073 // updated after all records are emitted.
2074 uint64_t Vals
[] = {0, 0};
2075 Stream
.EmitRecord(bitc::METADATA_INDEX_OFFSET
, Vals
, OffsetAbbrev
);
2078 // Compute and save the bit offset to the current position, which will be
2079 // patched when we emit the index later. We can simply subtract the 64-bit
2080 // fixed size from the current bit number to get the location to backpatch.
2081 uint64_t IndexOffsetRecordBitPos
= Stream
.GetCurrentBitNo();
2083 // This index will contain the bitpos for each individual record.
2084 std::vector
<uint64_t> IndexPos
;
2085 IndexPos
.reserve(VE
.getNonMDStrings().size());
2087 // Write all the records
2088 writeMetadataRecords(VE
.getNonMDStrings(), Record
, &MDAbbrevs
, &IndexPos
);
2090 if (VE
.getNonMDStrings().size() > IndexThreshold
) {
2091 // Now that we have emitted all the records we will emit the index. But
2093 // backpatch the forward reference so that the reader can skip the records
2095 Stream
.BackpatchWord64(IndexOffsetRecordBitPos
- 64,
2096 Stream
.GetCurrentBitNo() - IndexOffsetRecordBitPos
);
2098 // Delta encode the index.
2099 uint64_t PreviousValue
= IndexOffsetRecordBitPos
;
2100 for (auto &Elt
: IndexPos
) {
2101 auto EltDelta
= Elt
- PreviousValue
;
2102 PreviousValue
= Elt
;
2105 // Emit the index record.
2106 Stream
.EmitRecord(bitc::METADATA_INDEX
, IndexPos
, IndexAbbrev
);
2110 // Write the named metadata now.
2111 writeNamedMetadata(Record
);
2113 auto AddDeclAttachedMetadata
= [&](const GlobalObject
&GO
) {
2114 SmallVector
<uint64_t, 4> Record
;
2115 Record
.push_back(VE
.getValueID(&GO
));
2116 pushGlobalMetadataAttachment(Record
, GO
);
2117 Stream
.EmitRecord(bitc::METADATA_GLOBAL_DECL_ATTACHMENT
, Record
);
2119 for (const Function
&F
: M
)
2120 if (F
.isDeclaration() && F
.hasMetadata())
2121 AddDeclAttachedMetadata(F
);
2122 // FIXME: Only store metadata for declarations here, and move data for global
2123 // variable definitions to a separate block (PR28134).
2124 for (const GlobalVariable
&GV
: M
.globals())
2125 if (GV
.hasMetadata())
2126 AddDeclAttachedMetadata(GV
);
2131 void ModuleBitcodeWriter::writeFunctionMetadata(const Function
&F
) {
2135 Stream
.EnterSubblock(bitc::METADATA_BLOCK_ID
, 3);
2136 SmallVector
<uint64_t, 64> Record
;
2137 writeMetadataStrings(VE
.getMDStrings(), Record
);
2138 writeMetadataRecords(VE
.getNonMDStrings(), Record
);
2142 void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
2143 SmallVectorImpl
<uint64_t> &Record
, const GlobalObject
&GO
) {
2144 // [n x [id, mdnode]]
2145 SmallVector
<std::pair
<unsigned, MDNode
*>, 4> MDs
;
2146 GO
.getAllMetadata(MDs
);
2147 for (const auto &I
: MDs
) {
2148 Record
.push_back(I
.first
);
2149 Record
.push_back(VE
.getMetadataID(I
.second
));
2153 void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function
&F
) {
2154 Stream
.EnterSubblock(bitc::METADATA_ATTACHMENT_ID
, 3);
2156 SmallVector
<uint64_t, 64> Record
;
2158 if (F
.hasMetadata()) {
2159 pushGlobalMetadataAttachment(Record
, F
);
2160 Stream
.EmitRecord(bitc::METADATA_ATTACHMENT
, Record
, 0);
2164 // Write metadata attachments
2165 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
2166 SmallVector
<std::pair
<unsigned, MDNode
*>, 4> MDs
;
2167 for (const BasicBlock
&BB
: F
)
2168 for (const Instruction
&I
: BB
) {
2170 I
.getAllMetadataOtherThanDebugLoc(MDs
);
2172 // If no metadata, ignore instruction.
2173 if (MDs
.empty()) continue;
2175 Record
.push_back(VE
.getInstructionID(&I
));
2177 for (unsigned i
= 0, e
= MDs
.size(); i
!= e
; ++i
) {
2178 Record
.push_back(MDs
[i
].first
);
2179 Record
.push_back(VE
.getMetadataID(MDs
[i
].second
));
2181 Stream
.EmitRecord(bitc::METADATA_ATTACHMENT
, Record
, 0);
2188 void ModuleBitcodeWriter::writeModuleMetadataKinds() {
2189 SmallVector
<uint64_t, 64> Record
;
2191 // Write metadata kinds
2192 // METADATA_KIND - [n x [id, name]]
2193 SmallVector
<StringRef
, 8> Names
;
2194 M
.getMDKindNames(Names
);
2196 if (Names
.empty()) return;
2198 Stream
.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID
, 3);
2200 for (unsigned MDKindID
= 0, e
= Names
.size(); MDKindID
!= e
; ++MDKindID
) {
2201 Record
.push_back(MDKindID
);
2202 StringRef KName
= Names
[MDKindID
];
2203 Record
.append(KName
.begin(), KName
.end());
2205 Stream
.EmitRecord(bitc::METADATA_KIND
, Record
, 0);
2212 void ModuleBitcodeWriter::writeOperandBundleTags() {
2213 // Write metadata kinds
2215 // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
2217 // OPERAND_BUNDLE_TAG - [strchr x N]
2219 SmallVector
<StringRef
, 8> Tags
;
2220 M
.getOperandBundleTags(Tags
);
2225 Stream
.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID
, 3);
2227 SmallVector
<uint64_t, 64> Record
;
2229 for (auto Tag
: Tags
) {
2230 Record
.append(Tag
.begin(), Tag
.end());
2232 Stream
.EmitRecord(bitc::OPERAND_BUNDLE_TAG
, Record
, 0);
2239 void ModuleBitcodeWriter::writeSyncScopeNames() {
2240 SmallVector
<StringRef
, 8> SSNs
;
2241 M
.getContext().getSyncScopeNames(SSNs
);
2245 Stream
.EnterSubblock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID
, 2);
2247 SmallVector
<uint64_t, 64> Record
;
2248 for (auto SSN
: SSNs
) {
2249 Record
.append(SSN
.begin(), SSN
.end());
2250 Stream
.EmitRecord(bitc::SYNC_SCOPE_NAME
, Record
, 0);
2257 static void emitSignedInt64(SmallVectorImpl
<uint64_t> &Vals
, uint64_t V
) {
2258 if ((int64_t)V
>= 0)
2259 Vals
.push_back(V
<< 1);
2261 Vals
.push_back((-V
<< 1) | 1);
2264 void ModuleBitcodeWriter::writeConstants(unsigned FirstVal
, unsigned LastVal
,
2266 if (FirstVal
== LastVal
) return;
2268 Stream
.EnterSubblock(bitc::CONSTANTS_BLOCK_ID
, 4);
2270 unsigned AggregateAbbrev
= 0;
2271 unsigned String8Abbrev
= 0;
2272 unsigned CString7Abbrev
= 0;
2273 unsigned CString6Abbrev
= 0;
2274 // If this is a constant pool for the module, emit module-specific abbrevs.
2276 // Abbrev for CST_CODE_AGGREGATE.
2277 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
2278 Abbv
->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE
));
2279 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
2280 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, Log2_32_Ceil(LastVal
+1)));
2281 AggregateAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
2283 // Abbrev for CST_CODE_STRING.
2284 Abbv
= std::make_shared
<BitCodeAbbrev
>();
2285 Abbv
->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING
));
2286 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
2287 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 8));
2288 String8Abbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
2289 // Abbrev for CST_CODE_CSTRING.
2290 Abbv
= std::make_shared
<BitCodeAbbrev
>();
2291 Abbv
->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING
));
2292 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
2293 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 7));
2294 CString7Abbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
2295 // Abbrev for CST_CODE_CSTRING.
2296 Abbv
= std::make_shared
<BitCodeAbbrev
>();
2297 Abbv
->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING
));
2298 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
2299 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6
));
2300 CString6Abbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
2303 SmallVector
<uint64_t, 64> Record
;
2305 const ValueEnumerator::ValueList
&Vals
= VE
.getValues();
2306 Type
*LastTy
= nullptr;
2307 for (unsigned i
= FirstVal
; i
!= LastVal
; ++i
) {
2308 const Value
*V
= Vals
[i
].first
;
2309 // If we need to switch types, do so now.
2310 if (V
->getType() != LastTy
) {
2311 LastTy
= V
->getType();
2312 Record
.push_back(VE
.getTypeID(LastTy
));
2313 Stream
.EmitRecord(bitc::CST_CODE_SETTYPE
, Record
,
2314 CONSTANTS_SETTYPE_ABBREV
);
2318 if (const InlineAsm
*IA
= dyn_cast
<InlineAsm
>(V
)) {
2319 Record
.push_back(unsigned(IA
->hasSideEffects()) |
2320 unsigned(IA
->isAlignStack()) << 1 |
2321 unsigned(IA
->getDialect()&1) << 2);
2323 // Add the asm string.
2324 const std::string
&AsmStr
= IA
->getAsmString();
2325 Record
.push_back(AsmStr
.size());
2326 Record
.append(AsmStr
.begin(), AsmStr
.end());
2328 // Add the constraint string.
2329 const std::string
&ConstraintStr
= IA
->getConstraintString();
2330 Record
.push_back(ConstraintStr
.size());
2331 Record
.append(ConstraintStr
.begin(), ConstraintStr
.end());
2332 Stream
.EmitRecord(bitc::CST_CODE_INLINEASM
, Record
);
2336 const Constant
*C
= cast
<Constant
>(V
);
2337 unsigned Code
= -1U;
2338 unsigned AbbrevToUse
= 0;
2339 if (C
->isNullValue()) {
2340 Code
= bitc::CST_CODE_NULL
;
2341 } else if (isa
<UndefValue
>(C
)) {
2342 Code
= bitc::CST_CODE_UNDEF
;
2343 } else if (const ConstantInt
*IV
= dyn_cast
<ConstantInt
>(C
)) {
2344 if (IV
->getBitWidth() <= 64) {
2345 uint64_t V
= IV
->getSExtValue();
2346 emitSignedInt64(Record
, V
);
2347 Code
= bitc::CST_CODE_INTEGER
;
2348 AbbrevToUse
= CONSTANTS_INTEGER_ABBREV
;
2349 } else { // Wide integers, > 64 bits in size.
2350 // We have an arbitrary precision integer value to write whose
2351 // bit width is > 64. However, in canonical unsigned integer
2352 // format it is likely that the high bits are going to be zero.
2353 // So, we only write the number of active words.
2354 unsigned NWords
= IV
->getValue().getActiveWords();
2355 const uint64_t *RawWords
= IV
->getValue().getRawData();
2356 for (unsigned i
= 0; i
!= NWords
; ++i
) {
2357 emitSignedInt64(Record
, RawWords
[i
]);
2359 Code
= bitc::CST_CODE_WIDE_INTEGER
;
2361 } else if (const ConstantFP
*CFP
= dyn_cast
<ConstantFP
>(C
)) {
2362 Code
= bitc::CST_CODE_FLOAT
;
2363 Type
*Ty
= CFP
->getType();
2364 if (Ty
->isHalfTy() || Ty
->isFloatTy() || Ty
->isDoubleTy()) {
2365 Record
.push_back(CFP
->getValueAPF().bitcastToAPInt().getZExtValue());
2366 } else if (Ty
->isX86_FP80Ty()) {
2367 // api needed to prevent premature destruction
2368 // bits are not in the same order as a normal i80 APInt, compensate.
2369 APInt api
= CFP
->getValueAPF().bitcastToAPInt();
2370 const uint64_t *p
= api
.getRawData();
2371 Record
.push_back((p
[1] << 48) | (p
[0] >> 16));
2372 Record
.push_back(p
[0] & 0xffffLL
);
2373 } else if (Ty
->isFP128Ty() || Ty
->isPPC_FP128Ty()) {
2374 APInt api
= CFP
->getValueAPF().bitcastToAPInt();
2375 const uint64_t *p
= api
.getRawData();
2376 Record
.push_back(p
[0]);
2377 Record
.push_back(p
[1]);
2379 assert(0 && "Unknown FP type!");
2381 } else if (isa
<ConstantDataSequential
>(C
) &&
2382 cast
<ConstantDataSequential
>(C
)->isString()) {
2383 const ConstantDataSequential
*Str
= cast
<ConstantDataSequential
>(C
);
2384 // Emit constant strings specially.
2385 unsigned NumElts
= Str
->getNumElements();
2386 // If this is a null-terminated string, use the denser CSTRING encoding.
2387 if (Str
->isCString()) {
2388 Code
= bitc::CST_CODE_CSTRING
;
2389 --NumElts
; // Don't encode the null, which isn't allowed by char6.
2391 Code
= bitc::CST_CODE_STRING
;
2392 AbbrevToUse
= String8Abbrev
;
2394 bool isCStr7
= Code
== bitc::CST_CODE_CSTRING
;
2395 bool isCStrChar6
= Code
== bitc::CST_CODE_CSTRING
;
2396 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
2397 unsigned char V
= Str
->getElementAsInteger(i
);
2398 Record
.push_back(V
);
2399 isCStr7
&= (V
& 128) == 0;
2401 isCStrChar6
= BitCodeAbbrevOp::isChar6(V
);
2405 AbbrevToUse
= CString6Abbrev
;
2407 AbbrevToUse
= CString7Abbrev
;
2408 } else if (const ConstantDataSequential
*CDS
=
2409 dyn_cast
<ConstantDataSequential
>(C
)) {
2410 Code
= bitc::CST_CODE_DATA
;
2411 Type
*EltTy
= CDS
->getType()->getElementType();
2412 if (isa
<IntegerType
>(EltTy
)) {
2413 for (unsigned i
= 0, e
= CDS
->getNumElements(); i
!= e
; ++i
)
2414 Record
.push_back(CDS
->getElementAsInteger(i
));
2416 for (unsigned i
= 0, e
= CDS
->getNumElements(); i
!= e
; ++i
)
2418 CDS
->getElementAsAPFloat(i
).bitcastToAPInt().getLimitedValue());
2420 } else if (isa
<ConstantAggregate
>(C
)) {
2421 Code
= bitc::CST_CODE_AGGREGATE
;
2422 for (const Value
*Op
: C
->operands())
2423 Record
.push_back(VE
.getValueID(Op
));
2424 AbbrevToUse
= AggregateAbbrev
;
2425 } else if (const ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(C
)) {
2426 switch (CE
->getOpcode()) {
2428 if (Instruction::isCast(CE
->getOpcode())) {
2429 Code
= bitc::CST_CODE_CE_CAST
;
2430 Record
.push_back(getEncodedCastOpcode(CE
->getOpcode()));
2431 Record
.push_back(VE
.getTypeID(C
->getOperand(0)->getType()));
2432 Record
.push_back(VE
.getValueID(C
->getOperand(0)));
2433 AbbrevToUse
= CONSTANTS_CE_CAST_Abbrev
;
2435 assert(CE
->getNumOperands() == 2 && "Unknown constant expr!");
2436 Code
= bitc::CST_CODE_CE_BINOP
;
2437 Record
.push_back(getEncodedBinaryOpcode(CE
->getOpcode()));
2438 Record
.push_back(VE
.getValueID(C
->getOperand(0)));
2439 Record
.push_back(VE
.getValueID(C
->getOperand(1)));
2440 uint64_t Flags
= getOptimizationFlags(CE
);
2442 Record
.push_back(Flags
);
2445 case Instruction::FNeg
: {
2446 assert(CE
->getNumOperands() == 1 && "Unknown constant expr!");
2447 Code
= bitc::CST_CODE_CE_UNOP
;
2448 Record
.push_back(getEncodedUnaryOpcode(CE
->getOpcode()));
2449 Record
.push_back(VE
.getValueID(C
->getOperand(0)));
2450 uint64_t Flags
= getOptimizationFlags(CE
);
2452 Record
.push_back(Flags
);
2455 case Instruction::GetElementPtr
: {
2456 Code
= bitc::CST_CODE_CE_GEP
;
2457 const auto *GO
= cast
<GEPOperator
>(C
);
2458 Record
.push_back(VE
.getTypeID(GO
->getSourceElementType()));
2459 if (Optional
<unsigned> Idx
= GO
->getInRangeIndex()) {
2460 Code
= bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX
;
2461 Record
.push_back((*Idx
<< 1) | GO
->isInBounds());
2462 } else if (GO
->isInBounds())
2463 Code
= bitc::CST_CODE_CE_INBOUNDS_GEP
;
2464 for (unsigned i
= 0, e
= CE
->getNumOperands(); i
!= e
; ++i
) {
2465 Record
.push_back(VE
.getTypeID(C
->getOperand(i
)->getType()));
2466 Record
.push_back(VE
.getValueID(C
->getOperand(i
)));
2470 case Instruction::Select
:
2471 Code
= bitc::CST_CODE_CE_SELECT
;
2472 Record
.push_back(VE
.getValueID(C
->getOperand(0)));
2473 Record
.push_back(VE
.getValueID(C
->getOperand(1)));
2474 Record
.push_back(VE
.getValueID(C
->getOperand(2)));
2476 case Instruction::ExtractElement
:
2477 Code
= bitc::CST_CODE_CE_EXTRACTELT
;
2478 Record
.push_back(VE
.getTypeID(C
->getOperand(0)->getType()));
2479 Record
.push_back(VE
.getValueID(C
->getOperand(0)));
2480 Record
.push_back(VE
.getTypeID(C
->getOperand(1)->getType()));
2481 Record
.push_back(VE
.getValueID(C
->getOperand(1)));
2483 case Instruction::InsertElement
:
2484 Code
= bitc::CST_CODE_CE_INSERTELT
;
2485 Record
.push_back(VE
.getValueID(C
->getOperand(0)));
2486 Record
.push_back(VE
.getValueID(C
->getOperand(1)));
2487 Record
.push_back(VE
.getTypeID(C
->getOperand(2)->getType()));
2488 Record
.push_back(VE
.getValueID(C
->getOperand(2)));
2490 case Instruction::ShuffleVector
:
2491 // If the return type and argument types are the same, this is a
2492 // standard shufflevector instruction. If the types are different,
2493 // then the shuffle is widening or truncating the input vectors, and
2494 // the argument type must also be encoded.
2495 if (C
->getType() == C
->getOperand(0)->getType()) {
2496 Code
= bitc::CST_CODE_CE_SHUFFLEVEC
;
2498 Code
= bitc::CST_CODE_CE_SHUFVEC_EX
;
2499 Record
.push_back(VE
.getTypeID(C
->getOperand(0)->getType()));
2501 Record
.push_back(VE
.getValueID(C
->getOperand(0)));
2502 Record
.push_back(VE
.getValueID(C
->getOperand(1)));
2503 Record
.push_back(VE
.getValueID(C
->getOperand(2)));
2505 case Instruction::ICmp
:
2506 case Instruction::FCmp
:
2507 Code
= bitc::CST_CODE_CE_CMP
;
2508 Record
.push_back(VE
.getTypeID(C
->getOperand(0)->getType()));
2509 Record
.push_back(VE
.getValueID(C
->getOperand(0)));
2510 Record
.push_back(VE
.getValueID(C
->getOperand(1)));
2511 Record
.push_back(CE
->getPredicate());
2514 } else if (const BlockAddress
*BA
= dyn_cast
<BlockAddress
>(C
)) {
2515 Code
= bitc::CST_CODE_BLOCKADDRESS
;
2516 Record
.push_back(VE
.getTypeID(BA
->getFunction()->getType()));
2517 Record
.push_back(VE
.getValueID(BA
->getFunction()));
2518 Record
.push_back(VE
.getGlobalBasicBlockID(BA
->getBasicBlock()));
2523 llvm_unreachable("Unknown constant!");
2525 Stream
.EmitRecord(Code
, Record
, AbbrevToUse
);
2532 void ModuleBitcodeWriter::writeModuleConstants() {
2533 const ValueEnumerator::ValueList
&Vals
= VE
.getValues();
2535 // Find the first constant to emit, which is the first non-globalvalue value.
2536 // We know globalvalues have been emitted by WriteModuleInfo.
2537 for (unsigned i
= 0, e
= Vals
.size(); i
!= e
; ++i
) {
2538 if (!isa
<GlobalValue
>(Vals
[i
].first
)) {
2539 writeConstants(i
, Vals
.size(), true);
2545 /// pushValueAndType - The file has to encode both the value and type id for
2546 /// many values, because we need to know what type to create for forward
2547 /// references. However, most operands are not forward references, so this type
2548 /// field is not needed.
2550 /// This function adds V's value ID to Vals. If the value ID is higher than the
2551 /// instruction ID, then it is a forward reference, and it also includes the
2552 /// type ID. The value ID that is written is encoded relative to the InstID.
2553 bool ModuleBitcodeWriter::pushValueAndType(const Value
*V
, unsigned InstID
,
2554 SmallVectorImpl
<unsigned> &Vals
) {
2555 unsigned ValID
= VE
.getValueID(V
);
2556 // Make encoding relative to the InstID.
2557 Vals
.push_back(InstID
- ValID
);
2558 if (ValID
>= InstID
) {
2559 Vals
.push_back(VE
.getTypeID(V
->getType()));
2565 void ModuleBitcodeWriter::writeOperandBundles(ImmutableCallSite CS
,
2567 SmallVector
<unsigned, 64> Record
;
2568 LLVMContext
&C
= CS
.getInstruction()->getContext();
2570 for (unsigned i
= 0, e
= CS
.getNumOperandBundles(); i
!= e
; ++i
) {
2571 const auto &Bundle
= CS
.getOperandBundleAt(i
);
2572 Record
.push_back(C
.getOperandBundleTagID(Bundle
.getTagName()));
2574 for (auto &Input
: Bundle
.Inputs
)
2575 pushValueAndType(Input
, InstID
, Record
);
2577 Stream
.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE
, Record
);
2582 /// pushValue - Like pushValueAndType, but where the type of the value is
2583 /// omitted (perhaps it was already encoded in an earlier operand).
2584 void ModuleBitcodeWriter::pushValue(const Value
*V
, unsigned InstID
,
2585 SmallVectorImpl
<unsigned> &Vals
) {
2586 unsigned ValID
= VE
.getValueID(V
);
2587 Vals
.push_back(InstID
- ValID
);
2590 void ModuleBitcodeWriter::pushValueSigned(const Value
*V
, unsigned InstID
,
2591 SmallVectorImpl
<uint64_t> &Vals
) {
2592 unsigned ValID
= VE
.getValueID(V
);
2593 int64_t diff
= ((int32_t)InstID
- (int32_t)ValID
);
2594 emitSignedInt64(Vals
, diff
);
2597 /// WriteInstruction - Emit an instruction to the specified stream.
2598 void ModuleBitcodeWriter::writeInstruction(const Instruction
&I
,
2600 SmallVectorImpl
<unsigned> &Vals
) {
2602 unsigned AbbrevToUse
= 0;
2603 VE
.setInstructionID(&I
);
2604 switch (I
.getOpcode()) {
2606 if (Instruction::isCast(I
.getOpcode())) {
2607 Code
= bitc::FUNC_CODE_INST_CAST
;
2608 if (!pushValueAndType(I
.getOperand(0), InstID
, Vals
))
2609 AbbrevToUse
= FUNCTION_INST_CAST_ABBREV
;
2610 Vals
.push_back(VE
.getTypeID(I
.getType()));
2611 Vals
.push_back(getEncodedCastOpcode(I
.getOpcode()));
2613 assert(isa
<BinaryOperator
>(I
) && "Unknown instruction!");
2614 Code
= bitc::FUNC_CODE_INST_BINOP
;
2615 if (!pushValueAndType(I
.getOperand(0), InstID
, Vals
))
2616 AbbrevToUse
= FUNCTION_INST_BINOP_ABBREV
;
2617 pushValue(I
.getOperand(1), InstID
, Vals
);
2618 Vals
.push_back(getEncodedBinaryOpcode(I
.getOpcode()));
2619 uint64_t Flags
= getOptimizationFlags(&I
);
2621 if (AbbrevToUse
== FUNCTION_INST_BINOP_ABBREV
)
2622 AbbrevToUse
= FUNCTION_INST_BINOP_FLAGS_ABBREV
;
2623 Vals
.push_back(Flags
);
2627 case Instruction::FNeg
: {
2628 Code
= bitc::FUNC_CODE_INST_UNOP
;
2629 if (!pushValueAndType(I
.getOperand(0), InstID
, Vals
))
2630 AbbrevToUse
= FUNCTION_INST_UNOP_ABBREV
;
2631 Vals
.push_back(getEncodedUnaryOpcode(I
.getOpcode()));
2632 uint64_t Flags
= getOptimizationFlags(&I
);
2634 if (AbbrevToUse
== FUNCTION_INST_UNOP_ABBREV
)
2635 AbbrevToUse
= FUNCTION_INST_UNOP_FLAGS_ABBREV
;
2636 Vals
.push_back(Flags
);
2640 case Instruction::GetElementPtr
: {
2641 Code
= bitc::FUNC_CODE_INST_GEP
;
2642 AbbrevToUse
= FUNCTION_INST_GEP_ABBREV
;
2643 auto &GEPInst
= cast
<GetElementPtrInst
>(I
);
2644 Vals
.push_back(GEPInst
.isInBounds());
2645 Vals
.push_back(VE
.getTypeID(GEPInst
.getSourceElementType()));
2646 for (unsigned i
= 0, e
= I
.getNumOperands(); i
!= e
; ++i
)
2647 pushValueAndType(I
.getOperand(i
), InstID
, Vals
);
2650 case Instruction::ExtractValue
: {
2651 Code
= bitc::FUNC_CODE_INST_EXTRACTVAL
;
2652 pushValueAndType(I
.getOperand(0), InstID
, Vals
);
2653 const ExtractValueInst
*EVI
= cast
<ExtractValueInst
>(&I
);
2654 Vals
.append(EVI
->idx_begin(), EVI
->idx_end());
2657 case Instruction::InsertValue
: {
2658 Code
= bitc::FUNC_CODE_INST_INSERTVAL
;
2659 pushValueAndType(I
.getOperand(0), InstID
, Vals
);
2660 pushValueAndType(I
.getOperand(1), InstID
, Vals
);
2661 const InsertValueInst
*IVI
= cast
<InsertValueInst
>(&I
);
2662 Vals
.append(IVI
->idx_begin(), IVI
->idx_end());
2665 case Instruction::Select
: {
2666 Code
= bitc::FUNC_CODE_INST_VSELECT
;
2667 pushValueAndType(I
.getOperand(1), InstID
, Vals
);
2668 pushValue(I
.getOperand(2), InstID
, Vals
);
2669 pushValueAndType(I
.getOperand(0), InstID
, Vals
);
2670 uint64_t Flags
= getOptimizationFlags(&I
);
2672 Vals
.push_back(Flags
);
2675 case Instruction::ExtractElement
:
2676 Code
= bitc::FUNC_CODE_INST_EXTRACTELT
;
2677 pushValueAndType(I
.getOperand(0), InstID
, Vals
);
2678 pushValueAndType(I
.getOperand(1), InstID
, Vals
);
2680 case Instruction::InsertElement
:
2681 Code
= bitc::FUNC_CODE_INST_INSERTELT
;
2682 pushValueAndType(I
.getOperand(0), InstID
, Vals
);
2683 pushValue(I
.getOperand(1), InstID
, Vals
);
2684 pushValueAndType(I
.getOperand(2), InstID
, Vals
);
2686 case Instruction::ShuffleVector
:
2687 Code
= bitc::FUNC_CODE_INST_SHUFFLEVEC
;
2688 pushValueAndType(I
.getOperand(0), InstID
, Vals
);
2689 pushValue(I
.getOperand(1), InstID
, Vals
);
2690 pushValue(I
.getOperand(2), InstID
, Vals
);
2692 case Instruction::ICmp
:
2693 case Instruction::FCmp
: {
2694 // compare returning Int1Ty or vector of Int1Ty
2695 Code
= bitc::FUNC_CODE_INST_CMP2
;
2696 pushValueAndType(I
.getOperand(0), InstID
, Vals
);
2697 pushValue(I
.getOperand(1), InstID
, Vals
);
2698 Vals
.push_back(cast
<CmpInst
>(I
).getPredicate());
2699 uint64_t Flags
= getOptimizationFlags(&I
);
2701 Vals
.push_back(Flags
);
2705 case Instruction::Ret
:
2707 Code
= bitc::FUNC_CODE_INST_RET
;
2708 unsigned NumOperands
= I
.getNumOperands();
2709 if (NumOperands
== 0)
2710 AbbrevToUse
= FUNCTION_INST_RET_VOID_ABBREV
;
2711 else if (NumOperands
== 1) {
2712 if (!pushValueAndType(I
.getOperand(0), InstID
, Vals
))
2713 AbbrevToUse
= FUNCTION_INST_RET_VAL_ABBREV
;
2715 for (unsigned i
= 0, e
= NumOperands
; i
!= e
; ++i
)
2716 pushValueAndType(I
.getOperand(i
), InstID
, Vals
);
2720 case Instruction::Br
:
2722 Code
= bitc::FUNC_CODE_INST_BR
;
2723 const BranchInst
&II
= cast
<BranchInst
>(I
);
2724 Vals
.push_back(VE
.getValueID(II
.getSuccessor(0)));
2725 if (II
.isConditional()) {
2726 Vals
.push_back(VE
.getValueID(II
.getSuccessor(1)));
2727 pushValue(II
.getCondition(), InstID
, Vals
);
2731 case Instruction::Switch
:
2733 Code
= bitc::FUNC_CODE_INST_SWITCH
;
2734 const SwitchInst
&SI
= cast
<SwitchInst
>(I
);
2735 Vals
.push_back(VE
.getTypeID(SI
.getCondition()->getType()));
2736 pushValue(SI
.getCondition(), InstID
, Vals
);
2737 Vals
.push_back(VE
.getValueID(SI
.getDefaultDest()));
2738 for (auto Case
: SI
.cases()) {
2739 Vals
.push_back(VE
.getValueID(Case
.getCaseValue()));
2740 Vals
.push_back(VE
.getValueID(Case
.getCaseSuccessor()));
2744 case Instruction::IndirectBr
:
2745 Code
= bitc::FUNC_CODE_INST_INDIRECTBR
;
2746 Vals
.push_back(VE
.getTypeID(I
.getOperand(0)->getType()));
2747 // Encode the address operand as relative, but not the basic blocks.
2748 pushValue(I
.getOperand(0), InstID
, Vals
);
2749 for (unsigned i
= 1, e
= I
.getNumOperands(); i
!= e
; ++i
)
2750 Vals
.push_back(VE
.getValueID(I
.getOperand(i
)));
2753 case Instruction::Invoke
: {
2754 const InvokeInst
*II
= cast
<InvokeInst
>(&I
);
2755 const Value
*Callee
= II
->getCalledValue();
2756 FunctionType
*FTy
= II
->getFunctionType();
2758 if (II
->hasOperandBundles())
2759 writeOperandBundles(II
, InstID
);
2761 Code
= bitc::FUNC_CODE_INST_INVOKE
;
2763 Vals
.push_back(VE
.getAttributeListID(II
->getAttributes()));
2764 Vals
.push_back(II
->getCallingConv() | 1 << 13);
2765 Vals
.push_back(VE
.getValueID(II
->getNormalDest()));
2766 Vals
.push_back(VE
.getValueID(II
->getUnwindDest()));
2767 Vals
.push_back(VE
.getTypeID(FTy
));
2768 pushValueAndType(Callee
, InstID
, Vals
);
2770 // Emit value #'s for the fixed parameters.
2771 for (unsigned i
= 0, e
= FTy
->getNumParams(); i
!= e
; ++i
)
2772 pushValue(I
.getOperand(i
), InstID
, Vals
); // fixed param.
2774 // Emit type/value pairs for varargs params.
2775 if (FTy
->isVarArg()) {
2776 for (unsigned i
= FTy
->getNumParams(), e
= II
->getNumArgOperands();
2778 pushValueAndType(I
.getOperand(i
), InstID
, Vals
); // vararg
2782 case Instruction::Resume
:
2783 Code
= bitc::FUNC_CODE_INST_RESUME
;
2784 pushValueAndType(I
.getOperand(0), InstID
, Vals
);
2786 case Instruction::CleanupRet
: {
2787 Code
= bitc::FUNC_CODE_INST_CLEANUPRET
;
2788 const auto &CRI
= cast
<CleanupReturnInst
>(I
);
2789 pushValue(CRI
.getCleanupPad(), InstID
, Vals
);
2790 if (CRI
.hasUnwindDest())
2791 Vals
.push_back(VE
.getValueID(CRI
.getUnwindDest()));
2794 case Instruction::CatchRet
: {
2795 Code
= bitc::FUNC_CODE_INST_CATCHRET
;
2796 const auto &CRI
= cast
<CatchReturnInst
>(I
);
2797 pushValue(CRI
.getCatchPad(), InstID
, Vals
);
2798 Vals
.push_back(VE
.getValueID(CRI
.getSuccessor()));
2801 case Instruction::CleanupPad
:
2802 case Instruction::CatchPad
: {
2803 const auto &FuncletPad
= cast
<FuncletPadInst
>(I
);
2804 Code
= isa
<CatchPadInst
>(FuncletPad
) ? bitc::FUNC_CODE_INST_CATCHPAD
2805 : bitc::FUNC_CODE_INST_CLEANUPPAD
;
2806 pushValue(FuncletPad
.getParentPad(), InstID
, Vals
);
2808 unsigned NumArgOperands
= FuncletPad
.getNumArgOperands();
2809 Vals
.push_back(NumArgOperands
);
2810 for (unsigned Op
= 0; Op
!= NumArgOperands
; ++Op
)
2811 pushValueAndType(FuncletPad
.getArgOperand(Op
), InstID
, Vals
);
2814 case Instruction::CatchSwitch
: {
2815 Code
= bitc::FUNC_CODE_INST_CATCHSWITCH
;
2816 const auto &CatchSwitch
= cast
<CatchSwitchInst
>(I
);
2818 pushValue(CatchSwitch
.getParentPad(), InstID
, Vals
);
2820 unsigned NumHandlers
= CatchSwitch
.getNumHandlers();
2821 Vals
.push_back(NumHandlers
);
2822 for (const BasicBlock
*CatchPadBB
: CatchSwitch
.handlers())
2823 Vals
.push_back(VE
.getValueID(CatchPadBB
));
2825 if (CatchSwitch
.hasUnwindDest())
2826 Vals
.push_back(VE
.getValueID(CatchSwitch
.getUnwindDest()));
2829 case Instruction::CallBr
: {
2830 const CallBrInst
*CBI
= cast
<CallBrInst
>(&I
);
2831 const Value
*Callee
= CBI
->getCalledValue();
2832 FunctionType
*FTy
= CBI
->getFunctionType();
2834 if (CBI
->hasOperandBundles())
2835 writeOperandBundles(CBI
, InstID
);
2837 Code
= bitc::FUNC_CODE_INST_CALLBR
;
2839 Vals
.push_back(VE
.getAttributeListID(CBI
->getAttributes()));
2841 Vals
.push_back(CBI
->getCallingConv() << bitc::CALL_CCONV
|
2842 1 << bitc::CALL_EXPLICIT_TYPE
);
2844 Vals
.push_back(VE
.getValueID(CBI
->getDefaultDest()));
2845 Vals
.push_back(CBI
->getNumIndirectDests());
2846 for (unsigned i
= 0, e
= CBI
->getNumIndirectDests(); i
!= e
; ++i
)
2847 Vals
.push_back(VE
.getValueID(CBI
->getIndirectDest(i
)));
2849 Vals
.push_back(VE
.getTypeID(FTy
));
2850 pushValueAndType(Callee
, InstID
, Vals
);
2852 // Emit value #'s for the fixed parameters.
2853 for (unsigned i
= 0, e
= FTy
->getNumParams(); i
!= e
; ++i
)
2854 pushValue(I
.getOperand(i
), InstID
, Vals
); // fixed param.
2856 // Emit type/value pairs for varargs params.
2857 if (FTy
->isVarArg()) {
2858 for (unsigned i
= FTy
->getNumParams(), e
= CBI
->getNumArgOperands();
2860 pushValueAndType(I
.getOperand(i
), InstID
, Vals
); // vararg
2864 case Instruction::Unreachable
:
2865 Code
= bitc::FUNC_CODE_INST_UNREACHABLE
;
2866 AbbrevToUse
= FUNCTION_INST_UNREACHABLE_ABBREV
;
2869 case Instruction::PHI
: {
2870 const PHINode
&PN
= cast
<PHINode
>(I
);
2871 Code
= bitc::FUNC_CODE_INST_PHI
;
2872 // With the newer instruction encoding, forward references could give
2873 // negative valued IDs. This is most common for PHIs, so we use
2875 SmallVector
<uint64_t, 128> Vals64
;
2876 Vals64
.push_back(VE
.getTypeID(PN
.getType()));
2877 for (unsigned i
= 0, e
= PN
.getNumIncomingValues(); i
!= e
; ++i
) {
2878 pushValueSigned(PN
.getIncomingValue(i
), InstID
, Vals64
);
2879 Vals64
.push_back(VE
.getValueID(PN
.getIncomingBlock(i
)));
2881 // Emit a Vals64 vector and exit.
2882 Stream
.EmitRecord(Code
, Vals64
, AbbrevToUse
);
2887 case Instruction::LandingPad
: {
2888 const LandingPadInst
&LP
= cast
<LandingPadInst
>(I
);
2889 Code
= bitc::FUNC_CODE_INST_LANDINGPAD
;
2890 Vals
.push_back(VE
.getTypeID(LP
.getType()));
2891 Vals
.push_back(LP
.isCleanup());
2892 Vals
.push_back(LP
.getNumClauses());
2893 for (unsigned I
= 0, E
= LP
.getNumClauses(); I
!= E
; ++I
) {
2895 Vals
.push_back(LandingPadInst::Catch
);
2897 Vals
.push_back(LandingPadInst::Filter
);
2898 pushValueAndType(LP
.getClause(I
), InstID
, Vals
);
2903 case Instruction::Alloca
: {
2904 Code
= bitc::FUNC_CODE_INST_ALLOCA
;
2905 const AllocaInst
&AI
= cast
<AllocaInst
>(I
);
2906 Vals
.push_back(VE
.getTypeID(AI
.getAllocatedType()));
2907 Vals
.push_back(VE
.getTypeID(I
.getOperand(0)->getType()));
2908 Vals
.push_back(VE
.getValueID(I
.getOperand(0))); // size.
2909 unsigned AlignRecord
= Log2_32(AI
.getAlignment()) + 1;
2910 assert(Log2_32(Value::MaximumAlignment
) + 1 < 1 << 5 &&
2911 "not enough bits for maximum alignment");
2912 assert(AlignRecord
< 1 << 5 && "alignment greater than 1 << 64");
2913 AlignRecord
|= AI
.isUsedWithInAlloca() << 5;
2914 AlignRecord
|= 1 << 6;
2915 AlignRecord
|= AI
.isSwiftError() << 7;
2916 Vals
.push_back(AlignRecord
);
2920 case Instruction::Load
:
2921 if (cast
<LoadInst
>(I
).isAtomic()) {
2922 Code
= bitc::FUNC_CODE_INST_LOADATOMIC
;
2923 pushValueAndType(I
.getOperand(0), InstID
, Vals
);
2925 Code
= bitc::FUNC_CODE_INST_LOAD
;
2926 if (!pushValueAndType(I
.getOperand(0), InstID
, Vals
)) // ptr
2927 AbbrevToUse
= FUNCTION_INST_LOAD_ABBREV
;
2929 Vals
.push_back(VE
.getTypeID(I
.getType()));
2930 Vals
.push_back(Log2_32(cast
<LoadInst
>(I
).getAlignment())+1);
2931 Vals
.push_back(cast
<LoadInst
>(I
).isVolatile());
2932 if (cast
<LoadInst
>(I
).isAtomic()) {
2933 Vals
.push_back(getEncodedOrdering(cast
<LoadInst
>(I
).getOrdering()));
2934 Vals
.push_back(getEncodedSyncScopeID(cast
<LoadInst
>(I
).getSyncScopeID()));
2937 case Instruction::Store
:
2938 if (cast
<StoreInst
>(I
).isAtomic())
2939 Code
= bitc::FUNC_CODE_INST_STOREATOMIC
;
2941 Code
= bitc::FUNC_CODE_INST_STORE
;
2942 pushValueAndType(I
.getOperand(1), InstID
, Vals
); // ptrty + ptr
2943 pushValueAndType(I
.getOperand(0), InstID
, Vals
); // valty + val
2944 Vals
.push_back(Log2_32(cast
<StoreInst
>(I
).getAlignment())+1);
2945 Vals
.push_back(cast
<StoreInst
>(I
).isVolatile());
2946 if (cast
<StoreInst
>(I
).isAtomic()) {
2947 Vals
.push_back(getEncodedOrdering(cast
<StoreInst
>(I
).getOrdering()));
2949 getEncodedSyncScopeID(cast
<StoreInst
>(I
).getSyncScopeID()));
2952 case Instruction::AtomicCmpXchg
:
2953 Code
= bitc::FUNC_CODE_INST_CMPXCHG
;
2954 pushValueAndType(I
.getOperand(0), InstID
, Vals
); // ptrty + ptr
2955 pushValueAndType(I
.getOperand(1), InstID
, Vals
); // cmp.
2956 pushValue(I
.getOperand(2), InstID
, Vals
); // newval.
2957 Vals
.push_back(cast
<AtomicCmpXchgInst
>(I
).isVolatile());
2959 getEncodedOrdering(cast
<AtomicCmpXchgInst
>(I
).getSuccessOrdering()));
2961 getEncodedSyncScopeID(cast
<AtomicCmpXchgInst
>(I
).getSyncScopeID()));
2963 getEncodedOrdering(cast
<AtomicCmpXchgInst
>(I
).getFailureOrdering()));
2964 Vals
.push_back(cast
<AtomicCmpXchgInst
>(I
).isWeak());
2966 case Instruction::AtomicRMW
:
2967 Code
= bitc::FUNC_CODE_INST_ATOMICRMW
;
2968 pushValueAndType(I
.getOperand(0), InstID
, Vals
); // ptrty + ptr
2969 pushValue(I
.getOperand(1), InstID
, Vals
); // val.
2971 getEncodedRMWOperation(cast
<AtomicRMWInst
>(I
).getOperation()));
2972 Vals
.push_back(cast
<AtomicRMWInst
>(I
).isVolatile());
2973 Vals
.push_back(getEncodedOrdering(cast
<AtomicRMWInst
>(I
).getOrdering()));
2975 getEncodedSyncScopeID(cast
<AtomicRMWInst
>(I
).getSyncScopeID()));
2977 case Instruction::Fence
:
2978 Code
= bitc::FUNC_CODE_INST_FENCE
;
2979 Vals
.push_back(getEncodedOrdering(cast
<FenceInst
>(I
).getOrdering()));
2980 Vals
.push_back(getEncodedSyncScopeID(cast
<FenceInst
>(I
).getSyncScopeID()));
2982 case Instruction::Call
: {
2983 const CallInst
&CI
= cast
<CallInst
>(I
);
2984 FunctionType
*FTy
= CI
.getFunctionType();
2986 if (CI
.hasOperandBundles())
2987 writeOperandBundles(&CI
, InstID
);
2989 Code
= bitc::FUNC_CODE_INST_CALL
;
2991 Vals
.push_back(VE
.getAttributeListID(CI
.getAttributes()));
2993 unsigned Flags
= getOptimizationFlags(&I
);
2994 Vals
.push_back(CI
.getCallingConv() << bitc::CALL_CCONV
|
2995 unsigned(CI
.isTailCall()) << bitc::CALL_TAIL
|
2996 unsigned(CI
.isMustTailCall()) << bitc::CALL_MUSTTAIL
|
2997 1 << bitc::CALL_EXPLICIT_TYPE
|
2998 unsigned(CI
.isNoTailCall()) << bitc::CALL_NOTAIL
|
2999 unsigned(Flags
!= 0) << bitc::CALL_FMF
);
3001 Vals
.push_back(Flags
);
3003 Vals
.push_back(VE
.getTypeID(FTy
));
3004 pushValueAndType(CI
.getCalledValue(), InstID
, Vals
); // Callee
3006 // Emit value #'s for the fixed parameters.
3007 for (unsigned i
= 0, e
= FTy
->getNumParams(); i
!= e
; ++i
) {
3008 // Check for labels (can happen with asm labels).
3009 if (FTy
->getParamType(i
)->isLabelTy())
3010 Vals
.push_back(VE
.getValueID(CI
.getArgOperand(i
)));
3012 pushValue(CI
.getArgOperand(i
), InstID
, Vals
); // fixed param.
3015 // Emit type/value pairs for varargs params.
3016 if (FTy
->isVarArg()) {
3017 for (unsigned i
= FTy
->getNumParams(), e
= CI
.getNumArgOperands();
3019 pushValueAndType(CI
.getArgOperand(i
), InstID
, Vals
); // varargs
3023 case Instruction::VAArg
:
3024 Code
= bitc::FUNC_CODE_INST_VAARG
;
3025 Vals
.push_back(VE
.getTypeID(I
.getOperand(0)->getType())); // valistty
3026 pushValue(I
.getOperand(0), InstID
, Vals
); // valist.
3027 Vals
.push_back(VE
.getTypeID(I
.getType())); // restype.
3031 Stream
.EmitRecord(Code
, Vals
, AbbrevToUse
);
3035 /// Write a GlobalValue VST to the module. The purpose of this data structure is
3036 /// to allow clients to efficiently find the function body.
3037 void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
3038 DenseMap
<const Function
*, uint64_t> &FunctionToBitcodeIndex
) {
3039 // Get the offset of the VST we are writing, and backpatch it into
3040 // the VST forward declaration record.
3041 uint64_t VSTOffset
= Stream
.GetCurrentBitNo();
3042 // The BitcodeStartBit was the stream offset of the identification block.
3043 VSTOffset
-= bitcodeStartBit();
3044 assert((VSTOffset
& 31) == 0 && "VST block not 32-bit aligned");
3045 // Note that we add 1 here because the offset is relative to one word
3046 // before the start of the identification block, which was historically
3047 // always the start of the regular bitcode header.
3048 Stream
.BackpatchWord(VSTOffsetPlaceholder
, VSTOffset
/ 32 + 1);
3050 Stream
.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID
, 4);
3052 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
3053 Abbv
->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY
));
3054 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // value id
3055 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // funcoffset
3056 unsigned FnEntryAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
3058 for (const Function
&F
: M
) {
3061 if (F
.isDeclaration())
3064 Record
[0] = VE
.getValueID(&F
);
3066 // Save the word offset of the function (from the start of the
3067 // actual bitcode written to the stream).
3068 uint64_t BitcodeIndex
= FunctionToBitcodeIndex
[&F
] - bitcodeStartBit();
3069 assert((BitcodeIndex
& 31) == 0 && "function block not 32-bit aligned");
3070 // Note that we add 1 here because the offset is relative to one word
3071 // before the start of the identification block, which was historically
3072 // always the start of the regular bitcode header.
3073 Record
[1] = BitcodeIndex
/ 32 + 1;
3075 Stream
.EmitRecord(bitc::VST_CODE_FNENTRY
, Record
, FnEntryAbbrev
);
3081 /// Emit names for arguments, instructions and basic blocks in a function.
3082 void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
3083 const ValueSymbolTable
&VST
) {
3087 Stream
.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID
, 4);
3089 // FIXME: Set up the abbrev, we know how many values there are!
3090 // FIXME: We know if the type names can use 7-bit ascii.
3091 SmallVector
<uint64_t, 64> NameVals
;
3093 for (const ValueName
&Name
: VST
) {
3094 // Figure out the encoding to use for the name.
3095 StringEncoding Bits
= getStringEncoding(Name
.getKey());
3097 unsigned AbbrevToUse
= VST_ENTRY_8_ABBREV
;
3098 NameVals
.push_back(VE
.getValueID(Name
.getValue()));
3100 // VST_CODE_ENTRY: [valueid, namechar x N]
3101 // VST_CODE_BBENTRY: [bbid, namechar x N]
3103 if (isa
<BasicBlock
>(Name
.getValue())) {
3104 Code
= bitc::VST_CODE_BBENTRY
;
3105 if (Bits
== SE_Char6
)
3106 AbbrevToUse
= VST_BBENTRY_6_ABBREV
;
3108 Code
= bitc::VST_CODE_ENTRY
;
3109 if (Bits
== SE_Char6
)
3110 AbbrevToUse
= VST_ENTRY_6_ABBREV
;
3111 else if (Bits
== SE_Fixed7
)
3112 AbbrevToUse
= VST_ENTRY_7_ABBREV
;
3115 for (const auto P
: Name
.getKey())
3116 NameVals
.push_back((unsigned char)P
);
3118 // Emit the finished record.
3119 Stream
.EmitRecord(Code
, NameVals
, AbbrevToUse
);
3126 void ModuleBitcodeWriter::writeUseList(UseListOrder
&&Order
) {
3127 assert(Order
.Shuffle
.size() >= 2 && "Shuffle too small");
3129 if (isa
<BasicBlock
>(Order
.V
))
3130 Code
= bitc::USELIST_CODE_BB
;
3132 Code
= bitc::USELIST_CODE_DEFAULT
;
3134 SmallVector
<uint64_t, 64> Record(Order
.Shuffle
.begin(), Order
.Shuffle
.end());
3135 Record
.push_back(VE
.getValueID(Order
.V
));
3136 Stream
.EmitRecord(Code
, Record
);
3139 void ModuleBitcodeWriter::writeUseListBlock(const Function
*F
) {
3140 assert(VE
.shouldPreserveUseListOrder() &&
3141 "Expected to be preserving use-list order");
3143 auto hasMore
= [&]() {
3144 return !VE
.UseListOrders
.empty() && VE
.UseListOrders
.back().F
== F
;
3150 Stream
.EnterSubblock(bitc::USELIST_BLOCK_ID
, 3);
3152 writeUseList(std::move(VE
.UseListOrders
.back()));
3153 VE
.UseListOrders
.pop_back();
3158 /// Emit a function body to the module stream.
3159 void ModuleBitcodeWriter::writeFunction(
3161 DenseMap
<const Function
*, uint64_t> &FunctionToBitcodeIndex
) {
3162 // Save the bitcode index of the start of this function block for recording
3164 FunctionToBitcodeIndex
[&F
] = Stream
.GetCurrentBitNo();
3166 Stream
.EnterSubblock(bitc::FUNCTION_BLOCK_ID
, 4);
3167 VE
.incorporateFunction(F
);
3169 SmallVector
<unsigned, 64> Vals
;
3171 // Emit the number of basic blocks, so the reader can create them ahead of
3173 Vals
.push_back(VE
.getBasicBlocks().size());
3174 Stream
.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS
, Vals
);
3177 // If there are function-local constants, emit them now.
3178 unsigned CstStart
, CstEnd
;
3179 VE
.getFunctionConstantRange(CstStart
, CstEnd
);
3180 writeConstants(CstStart
, CstEnd
, false);
3182 // If there is function-local metadata, emit it now.
3183 writeFunctionMetadata(F
);
3185 // Keep a running idea of what the instruction ID is.
3186 unsigned InstID
= CstEnd
;
3188 bool NeedsMetadataAttachment
= F
.hasMetadata();
3190 DILocation
*LastDL
= nullptr;
3191 // Finally, emit all the instructions, in order.
3192 for (Function::const_iterator BB
= F
.begin(), E
= F
.end(); BB
!= E
; ++BB
)
3193 for (BasicBlock::const_iterator I
= BB
->begin(), E
= BB
->end();
3195 writeInstruction(*I
, InstID
, Vals
);
3197 if (!I
->getType()->isVoidTy())
3200 // If the instruction has metadata, write a metadata attachment later.
3201 NeedsMetadataAttachment
|= I
->hasMetadataOtherThanDebugLoc();
3203 // If the instruction has a debug location, emit it.
3204 DILocation
*DL
= I
->getDebugLoc();
3209 // Just repeat the same debug loc as last time.
3210 Stream
.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN
, Vals
);
3214 Vals
.push_back(DL
->getLine());
3215 Vals
.push_back(DL
->getColumn());
3216 Vals
.push_back(VE
.getMetadataOrNullID(DL
->getScope()));
3217 Vals
.push_back(VE
.getMetadataOrNullID(DL
->getInlinedAt()));
3218 Vals
.push_back(DL
->isImplicitCode());
3219 Stream
.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC
, Vals
);
3225 // Emit names for all the instructions etc.
3226 if (auto *Symtab
= F
.getValueSymbolTable())
3227 writeFunctionLevelValueSymbolTable(*Symtab
);
3229 if (NeedsMetadataAttachment
)
3230 writeFunctionMetadataAttachment(F
);
3231 if (VE
.shouldPreserveUseListOrder())
3232 writeUseListBlock(&F
);
3237 // Emit blockinfo, which defines the standard abbreviations etc.
3238 void ModuleBitcodeWriter::writeBlockInfo() {
3239 // We only want to emit block info records for blocks that have multiple
3240 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
3241 // Other blocks can define their abbrevs inline.
3242 Stream
.EnterBlockInfoBlock();
3244 { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
3245 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
3246 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 3));
3247 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8));
3248 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
3249 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 8));
3250 if (Stream
.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID
, Abbv
) !=
3252 llvm_unreachable("Unexpected abbrev ordering!");
3255 { // 7-bit fixed width VST_CODE_ENTRY strings.
3256 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
3257 Abbv
->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY
));
3258 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8));
3259 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
3260 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 7));
3261 if (Stream
.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID
, Abbv
) !=
3263 llvm_unreachable("Unexpected abbrev ordering!");
3265 { // 6-bit char6 VST_CODE_ENTRY strings.
3266 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
3267 Abbv
->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY
));
3268 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8));
3269 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
3270 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6
));
3271 if (Stream
.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID
, Abbv
) !=
3273 llvm_unreachable("Unexpected abbrev ordering!");
3275 { // 6-bit char6 VST_CODE_BBENTRY strings.
3276 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
3277 Abbv
->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY
));
3278 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8));
3279 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
3280 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6
));
3281 if (Stream
.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID
, Abbv
) !=
3282 VST_BBENTRY_6_ABBREV
)
3283 llvm_unreachable("Unexpected abbrev ordering!");
3286 { // SETTYPE abbrev for CONSTANTS_BLOCK.
3287 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
3288 Abbv
->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE
));
3289 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
,
3290 VE
.computeBitsRequiredForTypeIndicies()));
3291 if (Stream
.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID
, Abbv
) !=
3292 CONSTANTS_SETTYPE_ABBREV
)
3293 llvm_unreachable("Unexpected abbrev ordering!");
3296 { // INTEGER abbrev for CONSTANTS_BLOCK.
3297 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
3298 Abbv
->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER
));
3299 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8));
3300 if (Stream
.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID
, Abbv
) !=
3301 CONSTANTS_INTEGER_ABBREV
)
3302 llvm_unreachable("Unexpected abbrev ordering!");
3305 { // CE_CAST abbrev for CONSTANTS_BLOCK.
3306 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
3307 Abbv
->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST
));
3308 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 4)); // cast opc
3309 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, // typeid
3310 VE
.computeBitsRequiredForTypeIndicies()));
3311 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // value id
3313 if (Stream
.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID
, Abbv
) !=
3314 CONSTANTS_CE_CAST_Abbrev
)
3315 llvm_unreachable("Unexpected abbrev ordering!");
3317 { // NULL abbrev for CONSTANTS_BLOCK.
3318 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
3319 Abbv
->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL
));
3320 if (Stream
.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID
, Abbv
) !=
3321 CONSTANTS_NULL_Abbrev
)
3322 llvm_unreachable("Unexpected abbrev ordering!");
3325 // FIXME: This should only use space for first class types!
3327 { // INST_LOAD abbrev for FUNCTION_BLOCK.
3328 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
3329 Abbv
->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD
));
3330 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6)); // Ptr
3331 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, // dest ty
3332 VE
.computeBitsRequiredForTypeIndicies()));
3333 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 4)); // Align
3334 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 1)); // volatile
3335 if (Stream
.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID
, Abbv
) !=
3336 FUNCTION_INST_LOAD_ABBREV
)
3337 llvm_unreachable("Unexpected abbrev ordering!");
3339 { // INST_UNOP abbrev for FUNCTION_BLOCK.
3340 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
3341 Abbv
->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP
));
3342 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6)); // LHS
3343 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 4)); // opc
3344 if (Stream
.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID
, Abbv
) !=
3345 FUNCTION_INST_UNOP_ABBREV
)
3346 llvm_unreachable("Unexpected abbrev ordering!");
3348 { // INST_UNOP_FLAGS abbrev for FUNCTION_BLOCK.
3349 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
3350 Abbv
->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP
));
3351 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6)); // LHS
3352 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 4)); // opc
3353 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 8)); // flags
3354 if (Stream
.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID
, Abbv
) !=
3355 FUNCTION_INST_UNOP_FLAGS_ABBREV
)
3356 llvm_unreachable("Unexpected abbrev ordering!");
3358 { // INST_BINOP abbrev for FUNCTION_BLOCK.
3359 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
3360 Abbv
->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP
));
3361 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6)); // LHS
3362 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6)); // RHS
3363 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 4)); // opc
3364 if (Stream
.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID
, Abbv
) !=
3365 FUNCTION_INST_BINOP_ABBREV
)
3366 llvm_unreachable("Unexpected abbrev ordering!");
3368 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
3369 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
3370 Abbv
->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP
));
3371 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6)); // LHS
3372 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6)); // RHS
3373 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 4)); // opc
3374 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 8)); // flags
3375 if (Stream
.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID
, Abbv
) !=
3376 FUNCTION_INST_BINOP_FLAGS_ABBREV
)
3377 llvm_unreachable("Unexpected abbrev ordering!");
3379 { // INST_CAST abbrev for FUNCTION_BLOCK.
3380 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
3381 Abbv
->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST
));
3382 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6)); // OpVal
3383 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, // dest ty
3384 VE
.computeBitsRequiredForTypeIndicies()));
3385 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 4)); // opc
3386 if (Stream
.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID
, Abbv
) !=
3387 FUNCTION_INST_CAST_ABBREV
)
3388 llvm_unreachable("Unexpected abbrev ordering!");
3391 { // INST_RET abbrev for FUNCTION_BLOCK.
3392 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
3393 Abbv
->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET
));
3394 if (Stream
.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID
, Abbv
) !=
3395 FUNCTION_INST_RET_VOID_ABBREV
)
3396 llvm_unreachable("Unexpected abbrev ordering!");
3398 { // INST_RET abbrev for FUNCTION_BLOCK.
3399 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
3400 Abbv
->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET
));
3401 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6)); // ValID
3402 if (Stream
.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID
, Abbv
) !=
3403 FUNCTION_INST_RET_VAL_ABBREV
)
3404 llvm_unreachable("Unexpected abbrev ordering!");
3406 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
3407 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
3408 Abbv
->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE
));
3409 if (Stream
.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID
, Abbv
) !=
3410 FUNCTION_INST_UNREACHABLE_ABBREV
)
3411 llvm_unreachable("Unexpected abbrev ordering!");
3414 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
3415 Abbv
->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP
));
3416 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 1));
3417 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, // dest ty
3418 Log2_32_Ceil(VE
.getTypes().size() + 1)));
3419 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
3420 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6));
3421 if (Stream
.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID
, Abbv
) !=
3422 FUNCTION_INST_GEP_ABBREV
)
3423 llvm_unreachable("Unexpected abbrev ordering!");
3429 /// Write the module path strings, currently only used when generating
3430 /// a combined index file.
3431 void IndexBitcodeWriter::writeModStrings() {
3432 Stream
.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID
, 3);
3434 // TODO: See which abbrev sizes we actually need to emit
3436 // 8-bit fixed-width MST_ENTRY strings.
3437 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
3438 Abbv
->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY
));
3439 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8));
3440 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
3441 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 8));
3442 unsigned Abbrev8Bit
= Stream
.EmitAbbrev(std::move(Abbv
));
3444 // 7-bit fixed width MST_ENTRY strings.
3445 Abbv
= std::make_shared
<BitCodeAbbrev
>();
3446 Abbv
->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY
));
3447 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8));
3448 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
3449 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 7));
3450 unsigned Abbrev7Bit
= Stream
.EmitAbbrev(std::move(Abbv
));
3452 // 6-bit char6 MST_ENTRY strings.
3453 Abbv
= std::make_shared
<BitCodeAbbrev
>();
3454 Abbv
->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY
));
3455 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8));
3456 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
3457 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6
));
3458 unsigned Abbrev6Bit
= Stream
.EmitAbbrev(std::move(Abbv
));
3460 // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
3461 Abbv
= std::make_shared
<BitCodeAbbrev
>();
3462 Abbv
->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH
));
3463 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 32));
3464 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 32));
3465 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 32));
3466 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 32));
3467 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 32));
3468 unsigned AbbrevHash
= Stream
.EmitAbbrev(std::move(Abbv
));
3470 SmallVector
<unsigned, 64> Vals
;
3472 [&](const StringMapEntry
<std::pair
<uint64_t, ModuleHash
>> &MPSE
) {
3473 StringRef Key
= MPSE
.getKey();
3474 const auto &Value
= MPSE
.getValue();
3475 StringEncoding Bits
= getStringEncoding(Key
);
3476 unsigned AbbrevToUse
= Abbrev8Bit
;
3477 if (Bits
== SE_Char6
)
3478 AbbrevToUse
= Abbrev6Bit
;
3479 else if (Bits
== SE_Fixed7
)
3480 AbbrevToUse
= Abbrev7Bit
;
3482 Vals
.push_back(Value
.first
);
3483 Vals
.append(Key
.begin(), Key
.end());
3485 // Emit the finished record.
3486 Stream
.EmitRecord(bitc::MST_CODE_ENTRY
, Vals
, AbbrevToUse
);
3488 // Emit an optional hash for the module now
3489 const auto &Hash
= Value
.second
;
3490 if (llvm::any_of(Hash
, [](uint32_t H
) { return H
; })) {
3491 Vals
.assign(Hash
.begin(), Hash
.end());
3492 // Emit the hash record.
3493 Stream
.EmitRecord(bitc::MST_CODE_HASH
, Vals
, AbbrevHash
);
3501 /// Write the function type metadata related records that need to appear before
3502 /// a function summary entry (whether per-module or combined).
3503 static void writeFunctionTypeMetadataRecords(BitstreamWriter
&Stream
,
3504 FunctionSummary
*FS
) {
3505 if (!FS
->type_tests().empty())
3506 Stream
.EmitRecord(bitc::FS_TYPE_TESTS
, FS
->type_tests());
3508 SmallVector
<uint64_t, 64> Record
;
3510 auto WriteVFuncIdVec
= [&](uint64_t Ty
,
3511 ArrayRef
<FunctionSummary::VFuncId
> VFs
) {
3515 for (auto &VF
: VFs
) {
3516 Record
.push_back(VF
.GUID
);
3517 Record
.push_back(VF
.Offset
);
3519 Stream
.EmitRecord(Ty
, Record
);
3522 WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS
,
3523 FS
->type_test_assume_vcalls());
3524 WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS
,
3525 FS
->type_checked_load_vcalls());
3527 auto WriteConstVCallVec
= [&](uint64_t Ty
,
3528 ArrayRef
<FunctionSummary::ConstVCall
> VCs
) {
3529 for (auto &VC
: VCs
) {
3531 Record
.push_back(VC
.VFunc
.GUID
);
3532 Record
.push_back(VC
.VFunc
.Offset
);
3533 Record
.insert(Record
.end(), VC
.Args
.begin(), VC
.Args
.end());
3534 Stream
.EmitRecord(Ty
, Record
);
3538 WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL
,
3539 FS
->type_test_assume_const_vcalls());
3540 WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL
,
3541 FS
->type_checked_load_const_vcalls());
3544 /// Collect type IDs from type tests used by function.
3546 getReferencedTypeIds(FunctionSummary
*FS
,
3547 std::set
<GlobalValue::GUID
> &ReferencedTypeIds
) {
3548 if (!FS
->type_tests().empty())
3549 for (auto &TT
: FS
->type_tests())
3550 ReferencedTypeIds
.insert(TT
);
3552 auto GetReferencedTypesFromVFuncIdVec
=
3553 [&](ArrayRef
<FunctionSummary::VFuncId
> VFs
) {
3554 for (auto &VF
: VFs
)
3555 ReferencedTypeIds
.insert(VF
.GUID
);
3558 GetReferencedTypesFromVFuncIdVec(FS
->type_test_assume_vcalls());
3559 GetReferencedTypesFromVFuncIdVec(FS
->type_checked_load_vcalls());
3561 auto GetReferencedTypesFromConstVCallVec
=
3562 [&](ArrayRef
<FunctionSummary::ConstVCall
> VCs
) {
3563 for (auto &VC
: VCs
)
3564 ReferencedTypeIds
.insert(VC
.VFunc
.GUID
);
3567 GetReferencedTypesFromConstVCallVec(FS
->type_test_assume_const_vcalls());
3568 GetReferencedTypesFromConstVCallVec(FS
->type_checked_load_const_vcalls());
3571 static void writeWholeProgramDevirtResolutionByArg(
3572 SmallVector
<uint64_t, 64> &NameVals
, const std::vector
<uint64_t> &args
,
3573 const WholeProgramDevirtResolution::ByArg
&ByArg
) {
3574 NameVals
.push_back(args
.size());
3575 NameVals
.insert(NameVals
.end(), args
.begin(), args
.end());
3577 NameVals
.push_back(ByArg
.TheKind
);
3578 NameVals
.push_back(ByArg
.Info
);
3579 NameVals
.push_back(ByArg
.Byte
);
3580 NameVals
.push_back(ByArg
.Bit
);
3583 static void writeWholeProgramDevirtResolution(
3584 SmallVector
<uint64_t, 64> &NameVals
, StringTableBuilder
&StrtabBuilder
,
3585 uint64_t Id
, const WholeProgramDevirtResolution
&Wpd
) {
3586 NameVals
.push_back(Id
);
3588 NameVals
.push_back(Wpd
.TheKind
);
3589 NameVals
.push_back(StrtabBuilder
.add(Wpd
.SingleImplName
));
3590 NameVals
.push_back(Wpd
.SingleImplName
.size());
3592 NameVals
.push_back(Wpd
.ResByArg
.size());
3593 for (auto &A
: Wpd
.ResByArg
)
3594 writeWholeProgramDevirtResolutionByArg(NameVals
, A
.first
, A
.second
);
3597 static void writeTypeIdSummaryRecord(SmallVector
<uint64_t, 64> &NameVals
,
3598 StringTableBuilder
&StrtabBuilder
,
3599 const std::string
&Id
,
3600 const TypeIdSummary
&Summary
) {
3601 NameVals
.push_back(StrtabBuilder
.add(Id
));
3602 NameVals
.push_back(Id
.size());
3604 NameVals
.push_back(Summary
.TTRes
.TheKind
);
3605 NameVals
.push_back(Summary
.TTRes
.SizeM1BitWidth
);
3606 NameVals
.push_back(Summary
.TTRes
.AlignLog2
);
3607 NameVals
.push_back(Summary
.TTRes
.SizeM1
);
3608 NameVals
.push_back(Summary
.TTRes
.BitMask
);
3609 NameVals
.push_back(Summary
.TTRes
.InlineBits
);
3611 for (auto &W
: Summary
.WPDRes
)
3612 writeWholeProgramDevirtResolution(NameVals
, StrtabBuilder
, W
.first
,
3616 static void writeTypeIdCompatibleVtableSummaryRecord(
3617 SmallVector
<uint64_t, 64> &NameVals
, StringTableBuilder
&StrtabBuilder
,
3618 const std::string
&Id
, const TypeIdCompatibleVtableInfo
&Summary
,
3619 ValueEnumerator
&VE
) {
3620 NameVals
.push_back(StrtabBuilder
.add(Id
));
3621 NameVals
.push_back(Id
.size());
3623 for (auto &P
: Summary
) {
3624 NameVals
.push_back(P
.AddressPointOffset
);
3625 NameVals
.push_back(VE
.getValueID(P
.VTableVI
.getValue()));
3629 // Helper to emit a single function summary record.
3630 void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
3631 SmallVector
<uint64_t, 64> &NameVals
, GlobalValueSummary
*Summary
,
3632 unsigned ValueID
, unsigned FSCallsAbbrev
, unsigned FSCallsProfileAbbrev
,
3633 const Function
&F
) {
3634 NameVals
.push_back(ValueID
);
3636 FunctionSummary
*FS
= cast
<FunctionSummary
>(Summary
);
3637 writeFunctionTypeMetadataRecords(Stream
, FS
);
3639 auto SpecialRefCnts
= FS
->specialRefCounts();
3640 NameVals
.push_back(getEncodedGVSummaryFlags(FS
->flags()));
3641 NameVals
.push_back(FS
->instCount());
3642 NameVals
.push_back(getEncodedFFlags(FS
->fflags()));
3643 NameVals
.push_back(FS
->refs().size());
3644 NameVals
.push_back(SpecialRefCnts
.first
); // rorefcnt
3645 NameVals
.push_back(SpecialRefCnts
.second
); // worefcnt
3647 for (auto &RI
: FS
->refs())
3648 NameVals
.push_back(VE
.getValueID(RI
.getValue()));
3650 bool HasProfileData
=
3651 F
.hasProfileData() || ForceSummaryEdgesCold
!= FunctionSummary::FSHT_None
;
3652 for (auto &ECI
: FS
->calls()) {
3653 NameVals
.push_back(getValueId(ECI
.first
));
3655 NameVals
.push_back(static_cast<uint8_t>(ECI
.second
.Hotness
));
3656 else if (WriteRelBFToSummary
)
3657 NameVals
.push_back(ECI
.second
.RelBlockFreq
);
3660 unsigned FSAbbrev
= (HasProfileData
? FSCallsProfileAbbrev
: FSCallsAbbrev
);
3662 (HasProfileData
? bitc::FS_PERMODULE_PROFILE
3663 : (WriteRelBFToSummary
? bitc::FS_PERMODULE_RELBF
3664 : bitc::FS_PERMODULE
));
3666 // Emit the finished record.
3667 Stream
.EmitRecord(Code
, NameVals
, FSAbbrev
);
3671 // Collect the global value references in the given variable's initializer,
3672 // and emit them in a summary record.
3673 void ModuleBitcodeWriterBase::writeModuleLevelReferences(
3674 const GlobalVariable
&V
, SmallVector
<uint64_t, 64> &NameVals
,
3675 unsigned FSModRefsAbbrev
, unsigned FSModVTableRefsAbbrev
) {
3676 auto VI
= Index
->getValueInfo(V
.getGUID());
3677 if (!VI
|| VI
.getSummaryList().empty()) {
3678 // Only declarations should not have a summary (a declaration might however
3679 // have a summary if the def was in module level asm).
3680 assert(V
.isDeclaration());
3683 auto *Summary
= VI
.getSummaryList()[0].get();
3684 NameVals
.push_back(VE
.getValueID(&V
));
3685 GlobalVarSummary
*VS
= cast
<GlobalVarSummary
>(Summary
);
3686 NameVals
.push_back(getEncodedGVSummaryFlags(VS
->flags()));
3687 NameVals
.push_back(getEncodedGVarFlags(VS
->varflags()));
3689 auto VTableFuncs
= VS
->vTableFuncs();
3690 if (!VTableFuncs
.empty())
3691 NameVals
.push_back(VS
->refs().size());
3693 unsigned SizeBeforeRefs
= NameVals
.size();
3694 for (auto &RI
: VS
->refs())
3695 NameVals
.push_back(VE
.getValueID(RI
.getValue()));
3696 // Sort the refs for determinism output, the vector returned by FS->refs() has
3697 // been initialized from a DenseSet.
3698 llvm::sort(NameVals
.begin() + SizeBeforeRefs
, NameVals
.end());
3700 if (VTableFuncs
.empty())
3701 Stream
.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS
, NameVals
,
3704 // VTableFuncs pairs should already be sorted by offset.
3705 for (auto &P
: VTableFuncs
) {
3706 NameVals
.push_back(VE
.getValueID(P
.FuncVI
.getValue()));
3707 NameVals
.push_back(P
.VTableOffset
);
3710 Stream
.EmitRecord(bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS
, NameVals
,
3711 FSModVTableRefsAbbrev
);
3716 // Current version for the summary.
3717 // This is bumped whenever we introduce changes in the way some record are
3718 // interpreted, like flags for instance.
3719 static const uint64_t INDEX_VERSION
= 7;
3721 /// Emit the per-module summary section alongside the rest of
3722 /// the module's bitcode.
3723 void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
3724 // By default we compile with ThinLTO if the module has a summary, but the
3725 // client can request full LTO with a module flag.
3726 bool IsThinLTO
= true;
3728 mdconst::extract_or_null
<ConstantInt
>(M
.getModuleFlag("ThinLTO")))
3729 IsThinLTO
= MD
->getZExtValue();
3730 Stream
.EnterSubblock(IsThinLTO
? bitc::GLOBALVAL_SUMMARY_BLOCK_ID
3731 : bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID
,
3734 Stream
.EmitRecord(bitc::FS_VERSION
, ArrayRef
<uint64_t>{INDEX_VERSION
});
3736 // Write the index flags.
3738 // Bits 1-3 are set only in the combined index, skip them.
3739 if (Index
->enableSplitLTOUnit())
3741 Stream
.EmitRecord(bitc::FS_FLAGS
, ArrayRef
<uint64_t>{Flags
});
3743 if (Index
->begin() == Index
->end()) {
3748 for (const auto &GVI
: valueIds()) {
3749 Stream
.EmitRecord(bitc::FS_VALUE_GUID
,
3750 ArrayRef
<uint64_t>{GVI
.second
, GVI
.first
});
3753 // Abbrev for FS_PERMODULE_PROFILE.
3754 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
3755 Abbv
->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE
));
3756 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // valueid
3757 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6)); // flags
3758 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // instcount
3759 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 4)); // fflags
3760 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 4)); // numrefs
3761 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 4)); // rorefcnt
3762 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 4)); // worefcnt
3763 // numrefs x valueid, n x (valueid, hotness)
3764 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
3765 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8));
3766 unsigned FSCallsProfileAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
3768 // Abbrev for FS_PERMODULE or FS_PERMODULE_RELBF.
3769 Abbv
= std::make_shared
<BitCodeAbbrev
>();
3770 if (WriteRelBFToSummary
)
3771 Abbv
->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_RELBF
));
3773 Abbv
->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE
));
3774 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // valueid
3775 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6)); // flags
3776 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // instcount
3777 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 4)); // fflags
3778 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 4)); // numrefs
3779 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 4)); // rorefcnt
3780 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 4)); // worefcnt
3781 // numrefs x valueid, n x (valueid [, rel_block_freq])
3782 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
3783 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8));
3784 unsigned FSCallsAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
3786 // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
3787 Abbv
= std::make_shared
<BitCodeAbbrev
>();
3788 Abbv
->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS
));
3789 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // valueid
3790 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6)); // flags
3791 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
)); // valueids
3792 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8));
3793 unsigned FSModRefsAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
3795 // Abbrev for FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS.
3796 Abbv
= std::make_shared
<BitCodeAbbrev
>();
3797 Abbv
->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS
));
3798 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // valueid
3799 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6)); // flags
3800 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 4)); // numrefs
3801 // numrefs x valueid, n x (valueid , offset)
3802 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
3803 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8));
3804 unsigned FSModVTableRefsAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
3806 // Abbrev for FS_ALIAS.
3807 Abbv
= std::make_shared
<BitCodeAbbrev
>();
3808 Abbv
->Add(BitCodeAbbrevOp(bitc::FS_ALIAS
));
3809 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // valueid
3810 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6)); // flags
3811 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // valueid
3812 unsigned FSAliasAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
3814 // Abbrev for FS_TYPE_ID_METADATA
3815 Abbv
= std::make_shared
<BitCodeAbbrev
>();
3816 Abbv
->Add(BitCodeAbbrevOp(bitc::FS_TYPE_ID_METADATA
));
3817 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // typeid strtab index
3818 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // typeid length
3819 // n x (valueid , offset)
3820 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
3821 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8));
3822 unsigned TypeIdCompatibleVtableAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
3824 SmallVector
<uint64_t, 64> NameVals
;
3825 // Iterate over the list of functions instead of the Index to
3826 // ensure the ordering is stable.
3827 for (const Function
&F
: M
) {
3828 // Summary emission does not support anonymous functions, they have to
3829 // renamed using the anonymous function renaming pass.
3831 report_fatal_error("Unexpected anonymous function when writing summary");
3833 ValueInfo VI
= Index
->getValueInfo(F
.getGUID());
3834 if (!VI
|| VI
.getSummaryList().empty()) {
3835 // Only declarations should not have a summary (a declaration might
3836 // however have a summary if the def was in module level asm).
3837 assert(F
.isDeclaration());
3840 auto *Summary
= VI
.getSummaryList()[0].get();
3841 writePerModuleFunctionSummaryRecord(NameVals
, Summary
, VE
.getValueID(&F
),
3842 FSCallsAbbrev
, FSCallsProfileAbbrev
, F
);
3845 // Capture references from GlobalVariable initializers, which are outside
3846 // of a function scope.
3847 for (const GlobalVariable
&G
: M
.globals())
3848 writeModuleLevelReferences(G
, NameVals
, FSModRefsAbbrev
,
3849 FSModVTableRefsAbbrev
);
3851 for (const GlobalAlias
&A
: M
.aliases()) {
3852 auto *Aliasee
= A
.getBaseObject();
3853 if (!Aliasee
->hasName())
3854 // Nameless function don't have an entry in the summary, skip it.
3856 auto AliasId
= VE
.getValueID(&A
);
3857 auto AliaseeId
= VE
.getValueID(Aliasee
);
3858 NameVals
.push_back(AliasId
);
3859 auto *Summary
= Index
->getGlobalValueSummary(A
);
3860 AliasSummary
*AS
= cast
<AliasSummary
>(Summary
);
3861 NameVals
.push_back(getEncodedGVSummaryFlags(AS
->flags()));
3862 NameVals
.push_back(AliaseeId
);
3863 Stream
.EmitRecord(bitc::FS_ALIAS
, NameVals
, FSAliasAbbrev
);
3867 for (auto &S
: Index
->typeIdCompatibleVtableMap()) {
3868 writeTypeIdCompatibleVtableSummaryRecord(NameVals
, StrtabBuilder
, S
.first
,
3870 Stream
.EmitRecord(bitc::FS_TYPE_ID_METADATA
, NameVals
,
3871 TypeIdCompatibleVtableAbbrev
);
3878 /// Emit the combined summary section into the combined index file.
3879 void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
3880 Stream
.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID
, 3);
3881 Stream
.EmitRecord(bitc::FS_VERSION
, ArrayRef
<uint64_t>{INDEX_VERSION
});
3883 // Write the index flags.
3885 if (Index
.withGlobalValueDeadStripping())
3887 if (Index
.skipModuleByDistributedBackend())
3889 if (Index
.hasSyntheticEntryCounts())
3891 if (Index
.enableSplitLTOUnit())
3893 if (Index
.partiallySplitLTOUnits())
3895 Stream
.EmitRecord(bitc::FS_FLAGS
, ArrayRef
<uint64_t>{Flags
});
3897 for (const auto &GVI
: valueIds()) {
3898 Stream
.EmitRecord(bitc::FS_VALUE_GUID
,
3899 ArrayRef
<uint64_t>{GVI
.second
, GVI
.first
});
3902 // Abbrev for FS_COMBINED.
3903 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
3904 Abbv
->Add(BitCodeAbbrevOp(bitc::FS_COMBINED
));
3905 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // valueid
3906 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // modid
3907 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6)); // flags
3908 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // instcount
3909 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 4)); // fflags
3910 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // entrycount
3911 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 4)); // numrefs
3912 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 4)); // rorefcnt
3913 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 4)); // worefcnt
3914 // numrefs x valueid, n x (valueid)
3915 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
3916 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8));
3917 unsigned FSCallsAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
3919 // Abbrev for FS_COMBINED_PROFILE.
3920 Abbv
= std::make_shared
<BitCodeAbbrev
>();
3921 Abbv
->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE
));
3922 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // valueid
3923 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // modid
3924 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6)); // flags
3925 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // instcount
3926 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 4)); // fflags
3927 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // entrycount
3928 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 4)); // numrefs
3929 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 4)); // rorefcnt
3930 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 4)); // worefcnt
3931 // numrefs x valueid, n x (valueid, hotness)
3932 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
3933 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8));
3934 unsigned FSCallsProfileAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
3936 // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
3937 Abbv
= std::make_shared
<BitCodeAbbrev
>();
3938 Abbv
->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS
));
3939 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // valueid
3940 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // modid
3941 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6)); // flags
3942 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
)); // valueids
3943 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8));
3944 unsigned FSModRefsAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
3946 // Abbrev for FS_COMBINED_ALIAS.
3947 Abbv
= std::make_shared
<BitCodeAbbrev
>();
3948 Abbv
->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS
));
3949 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // valueid
3950 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // modid
3951 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6)); // flags
3952 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 8)); // valueid
3953 unsigned FSAliasAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
3955 // The aliases are emitted as a post-pass, and will point to the value
3956 // id of the aliasee. Save them in a vector for post-processing.
3957 SmallVector
<AliasSummary
*, 64> Aliases
;
3959 // Save the value id for each summary for alias emission.
3960 DenseMap
<const GlobalValueSummary
*, unsigned> SummaryToValueIdMap
;
3962 SmallVector
<uint64_t, 64> NameVals
;
3964 // Set that will be populated during call to writeFunctionTypeMetadataRecords
3965 // with the type ids referenced by this index file.
3966 std::set
<GlobalValue::GUID
> ReferencedTypeIds
;
3968 // For local linkage, we also emit the original name separately
3969 // immediately after the record.
3970 auto MaybeEmitOriginalName
= [&](GlobalValueSummary
&S
) {
3971 if (!GlobalValue::isLocalLinkage(S
.linkage()))
3973 NameVals
.push_back(S
.getOriginalName());
3974 Stream
.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME
, NameVals
);
3978 std::set
<GlobalValue::GUID
> DefOrUseGUIDs
;
3979 forEachSummary([&](GVInfo I
, bool IsAliasee
) {
3980 GlobalValueSummary
*S
= I
.second
;
3982 DefOrUseGUIDs
.insert(I
.first
);
3983 for (const ValueInfo
&VI
: S
->refs())
3984 DefOrUseGUIDs
.insert(VI
.getGUID());
3986 auto ValueId
= getValueId(I
.first
);
3988 SummaryToValueIdMap
[S
] = *ValueId
;
3990 // If this is invoked for an aliasee, we want to record the above
3991 // mapping, but then not emit a summary entry (if the aliasee is
3992 // to be imported, we will invoke this separately with IsAliasee=false).
3996 if (auto *AS
= dyn_cast
<AliasSummary
>(S
)) {
3997 // Will process aliases as a post-pass because the reader wants all
3998 // global to be loaded first.
3999 Aliases
.push_back(AS
);
4003 if (auto *VS
= dyn_cast
<GlobalVarSummary
>(S
)) {
4004 NameVals
.push_back(*ValueId
);
4005 NameVals
.push_back(Index
.getModuleId(VS
->modulePath()));
4006 NameVals
.push_back(getEncodedGVSummaryFlags(VS
->flags()));
4007 NameVals
.push_back(getEncodedGVarFlags(VS
->varflags()));
4008 for (auto &RI
: VS
->refs()) {
4009 auto RefValueId
= getValueId(RI
.getGUID());
4012 NameVals
.push_back(*RefValueId
);
4015 // Emit the finished record.
4016 Stream
.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS
, NameVals
,
4019 MaybeEmitOriginalName(*S
);
4023 auto *FS
= cast
<FunctionSummary
>(S
);
4024 writeFunctionTypeMetadataRecords(Stream
, FS
);
4025 getReferencedTypeIds(FS
, ReferencedTypeIds
);
4027 NameVals
.push_back(*ValueId
);
4028 NameVals
.push_back(Index
.getModuleId(FS
->modulePath()));
4029 NameVals
.push_back(getEncodedGVSummaryFlags(FS
->flags()));
4030 NameVals
.push_back(FS
->instCount());
4031 NameVals
.push_back(getEncodedFFlags(FS
->fflags()));
4032 NameVals
.push_back(FS
->entryCount());
4035 NameVals
.push_back(0); // numrefs
4036 NameVals
.push_back(0); // rorefcnt
4037 NameVals
.push_back(0); // worefcnt
4039 unsigned Count
= 0, RORefCnt
= 0, WORefCnt
= 0;
4040 for (auto &RI
: FS
->refs()) {
4041 auto RefValueId
= getValueId(RI
.getGUID());
4044 NameVals
.push_back(*RefValueId
);
4045 if (RI
.isReadOnly())
4047 else if (RI
.isWriteOnly())
4051 NameVals
[6] = Count
;
4052 NameVals
[7] = RORefCnt
;
4053 NameVals
[8] = WORefCnt
;
4055 bool HasProfileData
= false;
4056 for (auto &EI
: FS
->calls()) {
4058 EI
.second
.getHotness() != CalleeInfo::HotnessType::Unknown
;
4063 for (auto &EI
: FS
->calls()) {
4064 // If this GUID doesn't have a value id, it doesn't have a function
4065 // summary and we don't need to record any calls to it.
4066 GlobalValue::GUID GUID
= EI
.first
.getGUID();
4067 auto CallValueId
= getValueId(GUID
);
4069 // For SamplePGO, the indirect call targets for local functions will
4070 // have its original name annotated in profile. We try to find the
4071 // corresponding PGOFuncName as the GUID.
4072 GUID
= Index
.getGUIDFromOriginalID(GUID
);
4075 CallValueId
= getValueId(GUID
);
4078 // The mapping from OriginalId to GUID may return a GUID
4079 // that corresponds to a static variable. Filter it out here.
4080 // This can happen when
4081 // 1) There is a call to a library function which does not have
4083 // 2) There is a static variable with the OriginalGUID identical
4084 // to the GUID of the library function in 1);
4085 // When this happens, the logic for SamplePGO kicks in and
4086 // the static variable in 2) will be found, which needs to be
4088 auto *GVSum
= Index
.getGlobalValueSummary(GUID
, false);
4090 GVSum
->getSummaryKind() == GlobalValueSummary::GlobalVarKind
)
4093 NameVals
.push_back(*CallValueId
);
4095 NameVals
.push_back(static_cast<uint8_t>(EI
.second
.Hotness
));
4098 unsigned FSAbbrev
= (HasProfileData
? FSCallsProfileAbbrev
: FSCallsAbbrev
);
4100 (HasProfileData
? bitc::FS_COMBINED_PROFILE
: bitc::FS_COMBINED
);
4102 // Emit the finished record.
4103 Stream
.EmitRecord(Code
, NameVals
, FSAbbrev
);
4105 MaybeEmitOriginalName(*S
);
4108 for (auto *AS
: Aliases
) {
4109 auto AliasValueId
= SummaryToValueIdMap
[AS
];
4110 assert(AliasValueId
);
4111 NameVals
.push_back(AliasValueId
);
4112 NameVals
.push_back(Index
.getModuleId(AS
->modulePath()));
4113 NameVals
.push_back(getEncodedGVSummaryFlags(AS
->flags()));
4114 auto AliaseeValueId
= SummaryToValueIdMap
[&AS
->getAliasee()];
4115 assert(AliaseeValueId
);
4116 NameVals
.push_back(AliaseeValueId
);
4118 // Emit the finished record.
4119 Stream
.EmitRecord(bitc::FS_COMBINED_ALIAS
, NameVals
, FSAliasAbbrev
);
4121 MaybeEmitOriginalName(*AS
);
4123 if (auto *FS
= dyn_cast
<FunctionSummary
>(&AS
->getAliasee()))
4124 getReferencedTypeIds(FS
, ReferencedTypeIds
);
4127 if (!Index
.cfiFunctionDefs().empty()) {
4128 for (auto &S
: Index
.cfiFunctionDefs()) {
4129 if (DefOrUseGUIDs
.count(
4130 GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(S
)))) {
4131 NameVals
.push_back(StrtabBuilder
.add(S
));
4132 NameVals
.push_back(S
.size());
4135 if (!NameVals
.empty()) {
4136 Stream
.EmitRecord(bitc::FS_CFI_FUNCTION_DEFS
, NameVals
);
4141 if (!Index
.cfiFunctionDecls().empty()) {
4142 for (auto &S
: Index
.cfiFunctionDecls()) {
4143 if (DefOrUseGUIDs
.count(
4144 GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(S
)))) {
4145 NameVals
.push_back(StrtabBuilder
.add(S
));
4146 NameVals
.push_back(S
.size());
4149 if (!NameVals
.empty()) {
4150 Stream
.EmitRecord(bitc::FS_CFI_FUNCTION_DECLS
, NameVals
);
4155 // Walk the GUIDs that were referenced, and write the
4156 // corresponding type id records.
4157 for (auto &T
: ReferencedTypeIds
) {
4158 auto TidIter
= Index
.typeIds().equal_range(T
);
4159 for (auto It
= TidIter
.first
; It
!= TidIter
.second
; ++It
) {
4160 writeTypeIdSummaryRecord(NameVals
, StrtabBuilder
, It
->second
.first
,
4162 Stream
.EmitRecord(bitc::FS_TYPE_ID
, NameVals
);
4170 /// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
4171 /// current llvm version, and a record for the epoch number.
4172 static void writeIdentificationBlock(BitstreamWriter
&Stream
) {
4173 Stream
.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID
, 5);
4175 // Write the "user readable" string identifying the bitcode producer
4176 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
4177 Abbv
->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING
));
4178 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
4179 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6
));
4180 auto StringAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
4181 writeStringRecord(Stream
, bitc::IDENTIFICATION_CODE_STRING
,
4182 "LLVM" LLVM_VERSION_STRING
, StringAbbrev
);
4184 // Write the epoch version
4185 Abbv
= std::make_shared
<BitCodeAbbrev
>();
4186 Abbv
->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH
));
4187 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR
, 6));
4188 auto EpochAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
4189 SmallVector
<unsigned, 1> Vals
= {bitc::BITCODE_CURRENT_EPOCH
};
4190 Stream
.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH
, Vals
, EpochAbbrev
);
4194 void ModuleBitcodeWriter::writeModuleHash(size_t BlockStartPos
) {
4195 // Emit the module's hash.
4196 // MODULE_CODE_HASH: [5*i32]
4199 Hasher
.update(ArrayRef
<uint8_t>((const uint8_t *)&(Buffer
)[BlockStartPos
],
4200 Buffer
.size() - BlockStartPos
));
4201 StringRef Hash
= Hasher
.result();
4202 for (int Pos
= 0; Pos
< 20; Pos
+= 4) {
4203 Vals
[Pos
/ 4] = support::endian::read32be(Hash
.data() + Pos
);
4206 // Emit the finished record.
4207 Stream
.EmitRecord(bitc::MODULE_CODE_HASH
, Vals
);
4210 // Save the written hash value.
4211 llvm::copy(Vals
, std::begin(*ModHash
));
4215 void ModuleBitcodeWriter::write() {
4216 writeIdentificationBlock(Stream
);
4218 Stream
.EnterSubblock(bitc::MODULE_BLOCK_ID
, 3);
4219 size_t BlockStartPos
= Buffer
.size();
4221 writeModuleVersion();
4223 // Emit blockinfo, which defines the standard abbreviations etc.
4226 // Emit information describing all of the types in the module.
4229 // Emit information about attribute groups.
4230 writeAttributeGroupTable();
4232 // Emit information about parameter attributes.
4233 writeAttributeTable();
4237 // Emit top-level description of module, including target triple, inline asm,
4238 // descriptors for global variables, and function prototype info.
4242 writeModuleConstants();
4244 // Emit metadata kind names.
4245 writeModuleMetadataKinds();
4248 writeModuleMetadata();
4250 // Emit module-level use-lists.
4251 if (VE
.shouldPreserveUseListOrder())
4252 writeUseListBlock(nullptr);
4254 writeOperandBundleTags();
4255 writeSyncScopeNames();
4257 // Emit function bodies.
4258 DenseMap
<const Function
*, uint64_t> FunctionToBitcodeIndex
;
4259 for (Module::const_iterator F
= M
.begin(), E
= M
.end(); F
!= E
; ++F
)
4260 if (!F
->isDeclaration())
4261 writeFunction(*F
, FunctionToBitcodeIndex
);
4263 // Need to write after the above call to WriteFunction which populates
4264 // the summary information in the index.
4266 writePerModuleGlobalValueSummary();
4268 writeGlobalValueSymbolTable(FunctionToBitcodeIndex
);
4270 writeModuleHash(BlockStartPos
);
4275 static void writeInt32ToBuffer(uint32_t Value
, SmallVectorImpl
<char> &Buffer
,
4276 uint32_t &Position
) {
4277 support::endian::write32le(&Buffer
[Position
], Value
);
4281 /// If generating a bc file on darwin, we have to emit a
4282 /// header and trailer to make it compatible with the system archiver. To do
4283 /// this we emit the following header, and then emit a trailer that pads the
4284 /// file out to be a multiple of 16 bytes.
4286 /// struct bc_header {
4287 /// uint32_t Magic; // 0x0B17C0DE
4288 /// uint32_t Version; // Version, currently always 0.
4289 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
4290 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
4291 /// uint32_t CPUType; // CPU specifier.
4292 /// ... potentially more later ...
4294 static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl
<char> &Buffer
,
4296 unsigned CPUType
= ~0U;
4298 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
4299 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
4300 // number from /usr/include/mach/machine.h. It is ok to reproduce the
4301 // specific constants here because they are implicitly part of the Darwin ABI.
4303 DARWIN_CPU_ARCH_ABI64
= 0x01000000,
4304 DARWIN_CPU_TYPE_X86
= 7,
4305 DARWIN_CPU_TYPE_ARM
= 12,
4306 DARWIN_CPU_TYPE_POWERPC
= 18
4309 Triple::ArchType Arch
= TT
.getArch();
4310 if (Arch
== Triple::x86_64
)
4311 CPUType
= DARWIN_CPU_TYPE_X86
| DARWIN_CPU_ARCH_ABI64
;
4312 else if (Arch
== Triple::x86
)
4313 CPUType
= DARWIN_CPU_TYPE_X86
;
4314 else if (Arch
== Triple::ppc
)
4315 CPUType
= DARWIN_CPU_TYPE_POWERPC
;
4316 else if (Arch
== Triple::ppc64
)
4317 CPUType
= DARWIN_CPU_TYPE_POWERPC
| DARWIN_CPU_ARCH_ABI64
;
4318 else if (Arch
== Triple::arm
|| Arch
== Triple::thumb
)
4319 CPUType
= DARWIN_CPU_TYPE_ARM
;
4321 // Traditional Bitcode starts after header.
4322 assert(Buffer
.size() >= BWH_HeaderSize
&&
4323 "Expected header size to be reserved");
4324 unsigned BCOffset
= BWH_HeaderSize
;
4325 unsigned BCSize
= Buffer
.size() - BWH_HeaderSize
;
4327 // Write the magic and version.
4328 unsigned Position
= 0;
4329 writeInt32ToBuffer(0x0B17C0DE, Buffer
, Position
);
4330 writeInt32ToBuffer(0, Buffer
, Position
); // Version.
4331 writeInt32ToBuffer(BCOffset
, Buffer
, Position
);
4332 writeInt32ToBuffer(BCSize
, Buffer
, Position
);
4333 writeInt32ToBuffer(CPUType
, Buffer
, Position
);
4335 // If the file is not a multiple of 16 bytes, insert dummy padding.
4336 while (Buffer
.size() & 15)
4337 Buffer
.push_back(0);
4340 /// Helper to write the header common to all bitcode files.
4341 static void writeBitcodeHeader(BitstreamWriter
&Stream
) {
4342 // Emit the file header.
4343 Stream
.Emit((unsigned)'B', 8);
4344 Stream
.Emit((unsigned)'C', 8);
4345 Stream
.Emit(0x0, 4);
4346 Stream
.Emit(0xC, 4);
4347 Stream
.Emit(0xE, 4);
4348 Stream
.Emit(0xD, 4);
4351 BitcodeWriter::BitcodeWriter(SmallVectorImpl
<char> &Buffer
)
4352 : Buffer(Buffer
), Stream(new BitstreamWriter(Buffer
)) {
4353 writeBitcodeHeader(*Stream
);
4356 BitcodeWriter::~BitcodeWriter() { assert(WroteStrtab
); }
4358 void BitcodeWriter::writeBlob(unsigned Block
, unsigned Record
, StringRef Blob
) {
4359 Stream
->EnterSubblock(Block
, 3);
4361 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
4362 Abbv
->Add(BitCodeAbbrevOp(Record
));
4363 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob
));
4364 auto AbbrevNo
= Stream
->EmitAbbrev(std::move(Abbv
));
4366 Stream
->EmitRecordWithBlob(AbbrevNo
, ArrayRef
<uint64_t>{Record
}, Blob
);
4368 Stream
->ExitBlock();
4371 void BitcodeWriter::writeSymtab() {
4372 assert(!WroteStrtab
&& !WroteSymtab
);
4374 // If any module has module-level inline asm, we will require a registered asm
4375 // parser for the target so that we can create an accurate symbol table for
4377 for (Module
*M
: Mods
) {
4378 if (M
->getModuleInlineAsm().empty())
4382 const Triple
TT(M
->getTargetTriple());
4383 const Target
*T
= TargetRegistry::lookupTarget(TT
.str(), Err
);
4384 if (!T
|| !T
->hasMCAsmParser())
4389 SmallVector
<char, 0> Symtab
;
4390 // The irsymtab::build function may be unable to create a symbol table if the
4391 // module is malformed (e.g. it contains an invalid alias). Writing a symbol
4392 // table is not required for correctness, but we still want to be able to
4393 // write malformed modules to bitcode files, so swallow the error.
4394 if (Error E
= irsymtab::build(Mods
, Symtab
, StrtabBuilder
, Alloc
)) {
4395 consumeError(std::move(E
));
4399 writeBlob(bitc::SYMTAB_BLOCK_ID
, bitc::SYMTAB_BLOB
,
4400 {Symtab
.data(), Symtab
.size()});
4403 void BitcodeWriter::writeStrtab() {
4404 assert(!WroteStrtab
);
4406 std::vector
<char> Strtab
;
4407 StrtabBuilder
.finalizeInOrder();
4408 Strtab
.resize(StrtabBuilder
.getSize());
4409 StrtabBuilder
.write((uint8_t *)Strtab
.data());
4411 writeBlob(bitc::STRTAB_BLOCK_ID
, bitc::STRTAB_BLOB
,
4412 {Strtab
.data(), Strtab
.size()});
4417 void BitcodeWriter::copyStrtab(StringRef Strtab
) {
4418 writeBlob(bitc::STRTAB_BLOCK_ID
, bitc::STRTAB_BLOB
, Strtab
);
4422 void BitcodeWriter::writeModule(const Module
&M
,
4423 bool ShouldPreserveUseListOrder
,
4424 const ModuleSummaryIndex
*Index
,
4425 bool GenerateHash
, ModuleHash
*ModHash
) {
4426 assert(!WroteStrtab
);
4428 // The Mods vector is used by irsymtab::build, which requires non-const
4429 // Modules in case it needs to materialize metadata. But the bitcode writer
4430 // requires that the module is materialized, so we can cast to non-const here,
4431 // after checking that it is in fact materialized.
4432 assert(M
.isMaterialized());
4433 Mods
.push_back(const_cast<Module
*>(&M
));
4435 ModuleBitcodeWriter
ModuleWriter(M
, Buffer
, StrtabBuilder
, *Stream
,
4436 ShouldPreserveUseListOrder
, Index
,
4437 GenerateHash
, ModHash
);
4438 ModuleWriter
.write();
4441 void BitcodeWriter::writeIndex(
4442 const ModuleSummaryIndex
*Index
,
4443 const std::map
<std::string
, GVSummaryMapTy
> *ModuleToSummariesForIndex
) {
4444 IndexBitcodeWriter
IndexWriter(*Stream
, StrtabBuilder
, *Index
,
4445 ModuleToSummariesForIndex
);
4446 IndexWriter
.write();
4449 /// Write the specified module to the specified output stream.
4450 void llvm::WriteBitcodeToFile(const Module
&M
, raw_ostream
&Out
,
4451 bool ShouldPreserveUseListOrder
,
4452 const ModuleSummaryIndex
*Index
,
4453 bool GenerateHash
, ModuleHash
*ModHash
) {
4454 SmallVector
<char, 0> Buffer
;
4455 Buffer
.reserve(256*1024);
4457 // If this is darwin or another generic macho target, reserve space for the
4459 Triple
TT(M
.getTargetTriple());
4460 if (TT
.isOSDarwin() || TT
.isOSBinFormatMachO())
4461 Buffer
.insert(Buffer
.begin(), BWH_HeaderSize
, 0);
4463 BitcodeWriter
Writer(Buffer
);
4464 Writer
.writeModule(M
, ShouldPreserveUseListOrder
, Index
, GenerateHash
,
4466 Writer
.writeSymtab();
4467 Writer
.writeStrtab();
4469 if (TT
.isOSDarwin() || TT
.isOSBinFormatMachO())
4470 emitDarwinBCHeaderAndTrailer(Buffer
, TT
);
4472 // Write the generated bitstream to "Out".
4473 Out
.write((char*)&Buffer
.front(), Buffer
.size());
4476 void IndexBitcodeWriter::write() {
4477 Stream
.EnterSubblock(bitc::MODULE_BLOCK_ID
, 3);
4479 writeModuleVersion();
4481 // Write the module paths in the combined index.
4484 // Write the summary combined index records.
4485 writeCombinedGlobalValueSummary();
4490 // Write the specified module summary index to the given raw output stream,
4491 // where it will be written in a new bitcode block. This is used when
4492 // writing the combined index file for ThinLTO. When writing a subset of the
4493 // index for a distributed backend, provide a \p ModuleToSummariesForIndex map.
4494 void llvm::WriteIndexToFile(
4495 const ModuleSummaryIndex
&Index
, raw_ostream
&Out
,
4496 const std::map
<std::string
, GVSummaryMapTy
> *ModuleToSummariesForIndex
) {
4497 SmallVector
<char, 0> Buffer
;
4498 Buffer
.reserve(256 * 1024);
4500 BitcodeWriter
Writer(Buffer
);
4501 Writer
.writeIndex(&Index
, ModuleToSummariesForIndex
);
4502 Writer
.writeStrtab();
4504 Out
.write((char *)&Buffer
.front(), Buffer
.size());
4509 /// Class to manage the bitcode writing for a thin link bitcode file.
4510 class ThinLinkBitcodeWriter
: public ModuleBitcodeWriterBase
{
4511 /// ModHash is for use in ThinLTO incremental build, generated while writing
4512 /// the module bitcode file.
4513 const ModuleHash
*ModHash
;
4516 ThinLinkBitcodeWriter(const Module
&M
, StringTableBuilder
&StrtabBuilder
,
4517 BitstreamWriter
&Stream
,
4518 const ModuleSummaryIndex
&Index
,
4519 const ModuleHash
&ModHash
)
4520 : ModuleBitcodeWriterBase(M
, StrtabBuilder
, Stream
,
4521 /*ShouldPreserveUseListOrder=*/false, &Index
),
4522 ModHash(&ModHash
) {}
4527 void writeSimplifiedModuleInfo();
4530 } // end anonymous namespace
4532 // This function writes a simpilified module info for thin link bitcode file.
4533 // It only contains the source file name along with the name(the offset and
4534 // size in strtab) and linkage for global values. For the global value info
4535 // entry, in order to keep linkage at offset 5, there are three zeros used
4537 void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {
4538 SmallVector
<unsigned, 64> Vals
;
4539 // Emit the module's source file name.
4541 StringEncoding Bits
= getStringEncoding(M
.getSourceFileName());
4542 BitCodeAbbrevOp AbbrevOpToUse
= BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 8);
4543 if (Bits
== SE_Char6
)
4544 AbbrevOpToUse
= BitCodeAbbrevOp(BitCodeAbbrevOp::Char6
);
4545 else if (Bits
== SE_Fixed7
)
4546 AbbrevOpToUse
= BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed
, 7);
4548 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
4549 auto Abbv
= std::make_shared
<BitCodeAbbrev
>();
4550 Abbv
->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME
));
4551 Abbv
->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array
));
4552 Abbv
->Add(AbbrevOpToUse
);
4553 unsigned FilenameAbbrev
= Stream
.EmitAbbrev(std::move(Abbv
));
4555 for (const auto P
: M
.getSourceFileName())
4556 Vals
.push_back((unsigned char)P
);
4558 Stream
.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME
, Vals
, FilenameAbbrev
);
4562 // Emit the global variable information.
4563 for (const GlobalVariable
&GV
: M
.globals()) {
4564 // GLOBALVAR: [strtab offset, strtab size, 0, 0, 0, linkage]
4565 Vals
.push_back(StrtabBuilder
.add(GV
.getName()));
4566 Vals
.push_back(GV
.getName().size());
4570 Vals
.push_back(getEncodedLinkage(GV
));
4572 Stream
.EmitRecord(bitc::MODULE_CODE_GLOBALVAR
, Vals
);
4576 // Emit the function proto information.
4577 for (const Function
&F
: M
) {
4578 // FUNCTION: [strtab offset, strtab size, 0, 0, 0, linkage]
4579 Vals
.push_back(StrtabBuilder
.add(F
.getName()));
4580 Vals
.push_back(F
.getName().size());
4584 Vals
.push_back(getEncodedLinkage(F
));
4586 Stream
.EmitRecord(bitc::MODULE_CODE_FUNCTION
, Vals
);
4590 // Emit the alias information.
4591 for (const GlobalAlias
&A
: M
.aliases()) {
4592 // ALIAS: [strtab offset, strtab size, 0, 0, 0, linkage]
4593 Vals
.push_back(StrtabBuilder
.add(A
.getName()));
4594 Vals
.push_back(A
.getName().size());
4598 Vals
.push_back(getEncodedLinkage(A
));
4600 Stream
.EmitRecord(bitc::MODULE_CODE_ALIAS
, Vals
);
4604 // Emit the ifunc information.
4605 for (const GlobalIFunc
&I
: M
.ifuncs()) {
4606 // IFUNC: [strtab offset, strtab size, 0, 0, 0, linkage]
4607 Vals
.push_back(StrtabBuilder
.add(I
.getName()));
4608 Vals
.push_back(I
.getName().size());
4612 Vals
.push_back(getEncodedLinkage(I
));
4614 Stream
.EmitRecord(bitc::MODULE_CODE_IFUNC
, Vals
);
4619 void ThinLinkBitcodeWriter::write() {
4620 Stream
.EnterSubblock(bitc::MODULE_BLOCK_ID
, 3);
4622 writeModuleVersion();
4624 writeSimplifiedModuleInfo();
4626 writePerModuleGlobalValueSummary();
4628 // Write module hash.
4629 Stream
.EmitRecord(bitc::MODULE_CODE_HASH
, ArrayRef
<uint32_t>(*ModHash
));
4634 void BitcodeWriter::writeThinLinkBitcode(const Module
&M
,
4635 const ModuleSummaryIndex
&Index
,
4636 const ModuleHash
&ModHash
) {
4637 assert(!WroteStrtab
);
4639 // The Mods vector is used by irsymtab::build, which requires non-const
4640 // Modules in case it needs to materialize metadata. But the bitcode writer
4641 // requires that the module is materialized, so we can cast to non-const here,
4642 // after checking that it is in fact materialized.
4643 assert(M
.isMaterialized());
4644 Mods
.push_back(const_cast<Module
*>(&M
));
4646 ThinLinkBitcodeWriter
ThinLinkWriter(M
, StrtabBuilder
, *Stream
, Index
,
4648 ThinLinkWriter
.write();
4651 // Write the specified thin link bitcode file to the given raw output stream,
4652 // where it will be written in a new bitcode block. This is used when
4653 // writing the per-module index file for ThinLTO.
4654 void llvm::WriteThinLinkBitcodeToFile(const Module
&M
, raw_ostream
&Out
,
4655 const ModuleSummaryIndex
&Index
,
4656 const ModuleHash
&ModHash
) {
4657 SmallVector
<char, 0> Buffer
;
4658 Buffer
.reserve(256 * 1024);
4660 BitcodeWriter
Writer(Buffer
);
4661 Writer
.writeThinLinkBitcode(M
, Index
, ModHash
);
4662 Writer
.writeSymtab();
4663 Writer
.writeStrtab();
4665 Out
.write((char *)&Buffer
.front(), Buffer
.size());