LLVM 24.0.0git
BitcodeWriter.cpp
Go to the documentation of this file.
1//===- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Bitcode writer implementation.
10//
11//===----------------------------------------------------------------------===//
12
14#include "BitWriterOptions.h"
15#include "ValueEnumerator.h"
16#include "llvm/ADT/APFloat.h"
17#include "llvm/ADT/APInt.h"
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/DenseMap.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/SetVector.h"
25#include "llvm/ADT/StringMap.h"
26#include "llvm/ADT/StringRef.h"
34#include "llvm/Config/llvm-config.h"
35#include "llvm/IR/Attributes.h"
36#include "llvm/IR/BasicBlock.h"
37#include "llvm/IR/Comdat.h"
38#include "llvm/IR/Constant.h"
40#include "llvm/IR/Constants.h"
42#include "llvm/IR/DebugLoc.h"
44#include "llvm/IR/Function.h"
45#include "llvm/IR/GlobalAlias.h"
46#include "llvm/IR/GlobalIFunc.h"
48#include "llvm/IR/GlobalValue.h"
50#include "llvm/IR/InlineAsm.h"
51#include "llvm/IR/InstrTypes.h"
52#include "llvm/IR/Instruction.h"
54#include "llvm/IR/LLVMContext.h"
55#include "llvm/IR/Metadata.h"
56#include "llvm/IR/Module.h"
58#include "llvm/IR/Operator.h"
59#include "llvm/IR/Type.h"
61#include "llvm/IR/Value.h"
72#include "llvm/Support/Endian.h"
73#include "llvm/Support/Error.h"
76#include "llvm/Support/SHA1.h"
79#include <algorithm>
80#include <cassert>
81#include <cstddef>
82#include <cstdint>
83#include <iterator>
84#include <map>
85#include <memory>
86#include <optional>
87#include <string>
88#include <utility>
89#include <vector>
90
91using namespace llvm;
92using namespace llvm::memprof;
93
94// Since we only use the context information in the memprof summary records in
95// the LTO backends to do assertion checking, save time and space by only
96// serializing the context for non-NDEBUG builds.
97// TODO: Currently this controls writing context of the allocation info records,
98// which are larger and more expensive, but we should do this for the callsite
99// records as well.
100// FIXME: Convert to a const once this has undergone more sigificant testing.
101static cl::opt<bool>
102 CombinedIndexMemProfContext("combined-index-memprof-context", cl::Hidden,
103#ifdef NDEBUG
104 cl::init(false),
105#else
106 cl::init(true),
107#endif
108 cl::desc(""));
109
110namespace {
111
112/// These are manifest constants used by the bitcode writer. They do not need to
113/// be kept in sync with the reader, but need to be consistent within this file.
114enum {
115 // VALUE_SYMTAB_BLOCK abbrev id's.
116 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
117 VST_ENTRY_7_ABBREV,
118 VST_ENTRY_6_ABBREV,
119 VST_BBENTRY_6_ABBREV,
120
121 // CONSTANTS_BLOCK abbrev id's.
122 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
123 CONSTANTS_INTEGER_ABBREV,
124 CONSTANTS_BYTE_ABBREV,
125 CONSTANTS_CE_CAST_Abbrev,
126 CONSTANTS_NULL_Abbrev,
127
128 // FUNCTION_BLOCK abbrev id's.
129 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
130 FUNCTION_INST_STORE_ABBREV,
131 FUNCTION_INST_UNOP_ABBREV,
132 FUNCTION_INST_UNOP_FLAGS_ABBREV,
133 FUNCTION_INST_BINOP_ABBREV,
134 FUNCTION_INST_BINOP_FLAGS_ABBREV,
135 FUNCTION_INST_CAST_ABBREV,
136 FUNCTION_INST_CAST_FLAGS_ABBREV,
137 FUNCTION_INST_RET_VOID_ABBREV,
138 FUNCTION_INST_RET_VAL_ABBREV,
139 FUNCTION_INST_BR_UNCOND_ABBREV,
140 FUNCTION_INST_BR_COND_ABBREV,
141 FUNCTION_INST_UNREACHABLE_ABBREV,
142 FUNCTION_INST_GEP_ABBREV,
143 FUNCTION_INST_CMP_ABBREV,
144 FUNCTION_INST_CMP_FLAGS_ABBREV,
145 FUNCTION_DEBUG_RECORD_VALUE_ABBREV,
146 FUNCTION_DEBUG_LOC_ABBREV,
147 FUNCTION_DEBUG_LOC_LAYERS_ABBREV,
148};
149
150/// Abstract class to manage the bitcode writing, subclassed for each bitcode
151/// file type.
152class BitcodeWriterBase {
153protected:
154 /// The stream created and owned by the client.
155 BitstreamWriter &Stream;
156
157 StringTableBuilder &StrtabBuilder;
158
159public:
160 /// Constructs a BitcodeWriterBase object that writes to the provided
161 /// \p Stream.
162 BitcodeWriterBase(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder)
163 : Stream(Stream), StrtabBuilder(StrtabBuilder) {}
164
165protected:
166 void writeModuleVersion();
167};
168
169void BitcodeWriterBase::writeModuleVersion() {
170 // VERSION: [version#]
171 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, ArrayRef<uint64_t>{2});
172}
173
174/// Base class to manage the module bitcode writing, currently subclassed for
175/// ModuleBitcodeWriter and ThinLinkBitcodeWriter.
176class ModuleBitcodeWriterBase : public BitcodeWriterBase {
177protected:
178 const BitWriterOptions &Opts;
179
180 /// The Module to write to bitcode.
181 const Module &M;
182
183 /// Enumerates ids for all values in the module.
184 ValueEnumerator VE;
185
186 /// Optional per-module index to write for ThinLTO.
187 const ModuleSummaryIndex *Index;
188
189 /// Map that holds the correspondence between GUIDs in the summary index,
190 /// that came from indirect call profiles, and a value id generated by this
191 /// class to use in the VST and summary block records.
192 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
193
194 /// Tracks the last value id recorded in the GUIDToValueMap.
195 unsigned GlobalValueId;
196
197 /// Saves the offset of the VSTOffset record that must eventually be
198 /// backpatched with the offset of the actual VST.
199 uint64_t VSTOffsetPlaceholder = 0;
200
201public:
202 /// Constructs a ModuleBitcodeWriterBase object for the given Module,
203 /// writing to the provided \p Buffer.
204 ModuleBitcodeWriterBase(const Module &M, StringTableBuilder &StrtabBuilder,
205 BitstreamWriter &Stream,
206 bool ShouldPreserveUseListOrder,
207 const ModuleSummaryIndex *Index)
208 : BitcodeWriterBase(Stream, StrtabBuilder),
210 VE(M,
211 valueOr(Opts.preserve_bc_uselistorder, ShouldPreserveUseListOrder)),
212 Index(Index) {
213 // Assign ValueIds to any callee values in the index that came from
214 // indirect call profiles and were recorded as a GUID not a Value*
215 // (which would have been assigned an ID by the ValueEnumerator).
216 // The starting ValueId is just after the number of values in the
217 // ValueEnumerator, so that they can be emitted in the VST.
218 GlobalValueId = VE.getValues().size();
219 if (!Index)
220 return;
221 // Sort by GUID for deterministic value ID assignment.
222 for (const auto &GUIDSummaryLists :
223 Index->sortedGlobalValueSummariesRange())
224 // Examine all summaries for this GUID.
225 for (auto &Summary : GUIDSummaryLists.second.getSummaryList())
226 if (auto *FS = dyn_cast<FunctionSummary>(Summary.get())) {
227 // For each call in the function summary, see if the call
228 // is to a GUID (which means it is for an indirect call,
229 // otherwise we would have a Value for it). If so, synthesize
230 // a value id.
231 for (auto &CallEdge : FS->calls())
232 if (!CallEdge.first.haveGVs() || !CallEdge.first.getValue())
233 assignValueId(CallEdge.first.getGUID());
234
235 // For each referenced variables in the function summary, see if the
236 // variable is represented by a GUID (as opposed to a symbol to
237 // declarations or definitions in the module). If so, synthesize a
238 // value id.
239 for (auto &RefEdge : FS->refs())
240 if (!RefEdge.haveGVs() || !RefEdge.getValue())
241 assignValueId(RefEdge.getGUID());
242 }
243 }
244
245protected:
246 void writePerModuleGlobalValueSummary();
247 void writeGUIDList();
248
249private:
250 void writePerModuleFunctionSummaryRecord(
251 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
252 unsigned ValueID, unsigned FSCallsProfileAbbrev, unsigned CallsiteAbbrev,
253 unsigned AllocAbbrev, unsigned ContextIdAbbvId, const Function &F,
254 DenseMap<CallStackId, LinearCallStackId> &CallStackPos,
255 CallStackId &CallStackCount);
256 void writeModuleLevelReferences(const GlobalVariable &V,
257 SmallVector<uint64_t, 64> &NameVals,
258 unsigned FSModRefsAbbrev,
259 unsigned FSModVTableRefsAbbrev);
260
261 void assignValueId(GlobalValue::GUID ValGUID) {
262 GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
263 }
264
265 unsigned getValueId(GlobalValue::GUID ValGUID) {
266 const auto &VMI = GUIDToValueIdMap.find(ValGUID);
267 // Expect that any GUID value had a value Id assigned by an
268 // earlier call to assignValueId.
269 assert(VMI != GUIDToValueIdMap.end() &&
270 "GUID does not have assigned value Id");
271 return VMI->second;
272 }
273
274 // Helper to get the valueId for the type of value recorded in VI.
275 unsigned getValueId(ValueInfo VI) {
276 if (!VI.haveGVs() || !VI.getValue())
277 return getValueId(VI.getGUID());
278 return VE.getValueID(VI.getValue());
279 }
280
281 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
282};
283
284/// Class to manage the bitcode writing for a module.
285class ModuleBitcodeWriter : public ModuleBitcodeWriterBase {
286 /// True if a module hash record should be written.
287 bool GenerateHash;
288
289 /// If non-null, when GenerateHash is true, the resulting hash is written
290 /// into ModHash.
291 ModuleHash *ModHash;
292
293 SHA1 Hasher;
294
295 /// The start bit of the identification block.
296 uint64_t BitcodeStartBit;
297
298 /// Abbrev for DILocations that carry an irlayers operand. Locations without
299 /// layers use the shorter abbrev threaded through writeDILocation's \p
300 /// Abbrev parameter, so they pay nothing for a field they do not use.
301 unsigned DILocationLayersAbbrev = 0;
302
303public:
304 /// Constructs a ModuleBitcodeWriter object for the given Module,
305 /// writing to the provided \p Buffer.
306 ModuleBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder,
307 BitstreamWriter &Stream, bool ShouldPreserveUseListOrder,
308 const ModuleSummaryIndex *Index, bool GenerateHash,
309 ModuleHash *ModHash = nullptr)
310 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
311 ShouldPreserveUseListOrder, Index),
312 GenerateHash(GenerateHash), ModHash(ModHash),
313 BitcodeStartBit(Stream.GetCurrentBitNo()) {}
314
315 /// Emit the current module to the bitstream.
316 void write();
317
318private:
319 uint64_t bitcodeStartBit() { return BitcodeStartBit; }
320
321 size_t addToStrtab(StringRef Str);
322
323 void writeAttributeGroupTable();
324 void writeAttributeTable();
325 void writeTypeTable();
326 void writeComdats();
327 void writeValueSymbolTableForwardDecl();
328 void writeModuleInfo();
329 void writeValueAsMetadata(const ValueAsMetadata *MD,
330 SmallVectorImpl<uint64_t> &Record);
331 void writeMDTuple(const MDTuple *N, SmallVectorImpl<uint64_t> &Record,
332 unsigned Abbrev);
333 unsigned createDILocationAbbrev(bool WithIRLayers);
334 void writeDILocation(const DILocation *N, SmallVectorImpl<uint64_t> &Record,
335 unsigned &Abbrev);
336 void writeDILayerLoc(const DILayerLoc *N, SmallVectorImpl<uint64_t> &Record,
337 unsigned Abbrev);
338 void writeDILayerLocList(const DILayerLocList *N,
339 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
340 void writeMDFunctionLocalContext(const MDFunctionLocalContext *N,
341 SmallVectorImpl<uint64_t> &Record,
342 unsigned &Abbrev);
343 unsigned createGenericDINodeAbbrev();
344 void writeGenericDINode(const GenericDINode *N,
345 SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev);
346 void writeDISubrange(const DISubrange *N, SmallVectorImpl<uint64_t> &Record,
347 unsigned Abbrev);
348 void writeDIGenericSubrange(const DIGenericSubrange *N,
349 SmallVectorImpl<uint64_t> &Record,
350 unsigned Abbrev);
351 void writeDIEnumerator(const DIEnumerator *N,
352 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
353 void writeDIBasicType(const DIBasicType *N, SmallVectorImpl<uint64_t> &Record,
354 unsigned Abbrev);
355 void writeDIFixedPointType(const DIFixedPointType *N,
356 SmallVectorImpl<uint64_t> &Record,
357 unsigned Abbrev);
358 void writeDIStringType(const DIStringType *N,
359 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
360 void writeDIDerivedType(const DIDerivedType *N,
361 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
362 void writeDISubrangeType(const DISubrangeType *N,
363 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
364 void writeDICompositeType(const DICompositeType *N,
365 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
366 void writeDISubroutineType(const DISubroutineType *N,
367 SmallVectorImpl<uint64_t> &Record,
368 unsigned Abbrev);
369 void writeDIFile(const DIFile *N, SmallVectorImpl<uint64_t> &Record,
370 unsigned Abbrev);
371 void writeDICompileUnit(const DICompileUnit *N,
372 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
373 void writeDISubprogram(const DISubprogram *N,
374 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
375 void writeDILexicalBlock(const DILexicalBlock *N,
376 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
377 void writeDILexicalBlockFile(const DILexicalBlockFile *N,
378 SmallVectorImpl<uint64_t> &Record,
379 unsigned Abbrev);
380 void writeDICommonBlock(const DICommonBlock *N,
381 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
382 void writeDINamespace(const DINamespace *N, SmallVectorImpl<uint64_t> &Record,
383 unsigned Abbrev);
384 void writeDIMacro(const DIMacro *N, SmallVectorImpl<uint64_t> &Record,
385 unsigned Abbrev);
386 void writeDIMacroFile(const DIMacroFile *N, SmallVectorImpl<uint64_t> &Record,
387 unsigned Abbrev);
388 void writeDIArgList(const DIArgList *N, SmallVectorImpl<uint64_t> &Record);
389 void writeDIModule(const DIModule *N, SmallVectorImpl<uint64_t> &Record,
390 unsigned Abbrev);
391 void writeDIAssignID(const DIAssignID *N, SmallVectorImpl<uint64_t> &Record,
392 unsigned Abbrev);
393 void writeDITemplateTypeParameter(const DITemplateTypeParameter *N,
394 SmallVectorImpl<uint64_t> &Record,
395 unsigned Abbrev);
396 void writeDITemplateValueParameter(const DITemplateValueParameter *N,
397 SmallVectorImpl<uint64_t> &Record,
398 unsigned Abbrev);
399 void writeDIGlobalVariable(const DIGlobalVariable *N,
400 SmallVectorImpl<uint64_t> &Record,
401 unsigned Abbrev);
402 void writeDILocalVariable(const DILocalVariable *N,
403 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
404 void writeDILabel(const DILabel *N,
405 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
406 void writeDIExpression(const DIExpression *N,
407 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
408 void writeDIGlobalVariableExpression(const DIGlobalVariableExpression *N,
409 SmallVectorImpl<uint64_t> &Record,
410 unsigned Abbrev);
411 void writeDIObjCProperty(const DIObjCProperty *N,
412 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
413 void writeDIProperty(const DIProperty *N, SmallVectorImpl<uint64_t> &Record,
414 unsigned Abbrev);
415 void writeDIImportedEntity(const DIImportedEntity *N,
416 SmallVectorImpl<uint64_t> &Record,
417 unsigned Abbrev);
418 unsigned createNamedMetadataAbbrev();
419 void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
420 unsigned createMetadataStringsAbbrev();
421 void writeMetadataStrings(ArrayRef<const Metadata *> Strings,
422 SmallVectorImpl<uint64_t> &Record);
423 void writeMetadataRecords(ArrayRef<const Metadata *> MDs,
424 SmallVectorImpl<uint64_t> &Record,
425 std::vector<unsigned> *MDAbbrevs = nullptr,
426 std::vector<uint64_t> *IndexPos = nullptr);
427 void writeModuleMetadata();
428 void writeFunctionMetadata(const Function &F);
429 void writeFunctionMetadataAttachment(const Function &F);
430 void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
431 const GlobalObject &GO);
432 void writeModuleMetadataKinds();
433 void writeOperandBundleTags();
434 void writeSyncScopeNames();
435 void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal);
436 void writeModuleConstants();
437 bool pushValueAndType(const Value *V, unsigned InstID,
438 SmallVectorImpl<unsigned> &Vals);
439 bool pushValueOrMetadata(const Value *V, unsigned InstID,
440 SmallVectorImpl<unsigned> &Vals);
441 void writeOperandBundles(const CallBase &CB, unsigned InstID);
442 void pushValue(const Value *V, unsigned InstID,
443 SmallVectorImpl<unsigned> &Vals);
444 void pushValueSigned(const Value *V, unsigned InstID,
445 SmallVectorImpl<uint64_t> &Vals);
446 void writeInstruction(const Instruction &I, unsigned InstID,
447 SmallVectorImpl<unsigned> &Vals);
448 void writeFunctionLevelValueSymbolTable(const ValueSymbolTable &VST);
449 void writeGlobalValueSymbolTable(
450 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
451 void writeUseList(UseListOrder &&Order);
452 void writeUseListBlock(const Function *F);
453 void
454 writeFunction(const Function &F,
455 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
456 void writeBlockInfo();
457 void writeModuleHash(StringRef View);
458
459 unsigned getEncodedSyncScopeID(SyncScope::ID SSID) {
460 return unsigned(SSID);
461 }
462
463 unsigned getEncodedAlign(MaybeAlign Alignment) { return encode(Alignment); }
464};
465
466/// Class to manage the bitcode writing for a combined index.
467class IndexBitcodeWriter : public BitcodeWriterBase {
468 /// The combined index to write to bitcode.
469 const ModuleSummaryIndex &Index;
470
471 /// When writing combined summaries, provides the set of global value
472 /// summaries for which the value (function, function alias, etc) should be
473 /// imported as a declaration.
474 const GVSummaryPtrSet *DecSummaries = nullptr;
475
476 /// When writing a subset of the index for distributed backends, client
477 /// provides a map of modules to the corresponding GUIDs/summaries to write.
478 const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex;
479
480 /// The summaries in ModuleToSummariesForIndex, sorted by GUID. The
481 /// per-module maps are DenseMaps whose iteration order depends on insertion
482 /// order, which can change with unrelated modules in the link. Writing in
483 /// this order makes logically identical indexes byte-identical.
485 SortedSummariesForIndex;
486
487 /// Map that holds the correspondence between the GUID used in the combined
488 /// index and a value id generated by this class to use in references.
489 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
490
491 // The stack ids used by this index, which will be a subset of those in
492 // the full index in the case of distributed indexes.
493 std::vector<uint64_t> StackIds;
494
495 // Keep a map of the stack id indices used by records being written for this
496 // index to the index of the corresponding stack id in the above StackIds
497 // vector. Ensures we write each referenced stack id once.
498 DenseMap<unsigned, unsigned> StackIdIndicesToIndex;
499
500 /// Tracks the last value id recorded in the GUIDToValueMap.
501 unsigned GlobalValueId = 0;
502
503 /// Tracks the assignment of module paths in the module path string table to
504 /// an id assigned for use in summary references to the module path.
505 DenseMap<StringRef, uint64_t> ModuleIdMap;
506
507public:
508 /// Constructs a IndexBitcodeWriter object for the given combined index,
509 /// writing to the provided \p Buffer. When writing a subset of the index
510 /// for a distributed backend, provide a \p ModuleToSummariesForIndex map.
511 /// If provided, \p DecSummaries specifies the set of summaries for which
512 /// the corresponding functions or aliased functions should be imported as a
513 /// declaration (but not definition) for each module.
514 IndexBitcodeWriter(
515 BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder,
516 const ModuleSummaryIndex &Index,
517 const GVSummaryPtrSet *DecSummaries = nullptr,
518 const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex = nullptr)
519 : BitcodeWriterBase(Stream, StrtabBuilder), Index(Index),
520 DecSummaries(DecSummaries),
521 ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
522 if (ModuleToSummariesForIndex) {
523 for (const auto &[ModPath, Summaries] : *ModuleToSummariesForIndex)
524 llvm::append_range(SortedSummariesForIndex, Summaries);
525 // Each module's summaries are in DenseMap order, which depends on
526 // insertion order. Sort by GUID for byte-identical output. A GUID may
527 // appear under more than one module; the stable sort keeps those in the
528 // std::map's module path order.
529 llvm::stable_sort(SortedSummariesForIndex, llvm::less_first());
530 }
531
532 // See if the StackIdIndex was already added to the StackId map and
533 // vector. If not, record it.
534 auto RecordStackIdReference = [&](unsigned StackIdIndex) {
535 // If the StackIdIndex is not yet in the map, the below insert ensures
536 // that it will point to the new StackIds vector entry we push to just
537 // below.
538 auto Inserted =
539 StackIdIndicesToIndex.insert({StackIdIndex, StackIds.size()});
540 if (Inserted.second)
541 StackIds.push_back(Index.getStackIdAtIndex(StackIdIndex));
542 };
543
544 // Assign unique value ids to all summaries to be written, for use
545 // in writing out the call graph edges. Save the mapping from GUID
546 // to the new global value id to use when writing those edges, which
547 // are currently saved in the index in terms of GUID.
548 forEachSummary([&](GVInfo I, bool IsAliasee) {
549 GUIDToValueIdMap[I.first] = ++GlobalValueId;
550 // If this is invoked for an aliasee, we want to record the above mapping,
551 // but not the information needed for its summary entry (if the aliasee is
552 // to be imported, we will invoke this separately with IsAliasee=false).
553 if (IsAliasee)
554 return;
555 auto *FS = dyn_cast<FunctionSummary>(I.second);
556 if (!FS)
557 return;
558 // Record all stack id indices actually used in the summary entries being
559 // written, so that we can compact them in the case of distributed ThinLTO
560 // indexes.
561 for (auto &CI : FS->callsites()) {
562 // If the stack id list is empty, this callsite info was synthesized for
563 // a missing tail call frame. Ensure that the callee's GUID gets a value
564 // id. Normally we only generate these for defined summaries, which in
565 // the case of distributed ThinLTO is only the functions already defined
566 // in the module or that we want to import. We don't bother to include
567 // all the callee symbols as they aren't normally needed in the backend.
568 // However, for the synthesized callsite infos we do need the callee
569 // GUID in the backend so that we can correlate the identified callee
570 // with this callsite info (which for non-tail calls is done by the
571 // ordering of the callsite infos and verified via stack ids).
572 if (CI.StackIdIndices.empty()) {
573 GUIDToValueIdMap[CI.Callee.getGUID()] = ++GlobalValueId;
574 continue;
575 }
576 for (auto Idx : CI.StackIdIndices)
577 RecordStackIdReference(Idx);
578 }
580 for (auto &AI : FS->allocs())
581 for (auto &MIB : AI.MIBs)
582 for (auto Idx : MIB.StackIdIndices)
583 RecordStackIdReference(Idx);
584 }
585 });
586 }
587
588 /// The below iterator returns the GUID and associated summary.
589 using GVInfo = std::pair<GlobalValue::GUID, GlobalValueSummary *>;
590
591 /// Calls the callback for each value GUID and summary to be written to
592 /// bitcode. This hides the details of whether they are being pulled from the
593 /// entire index or just those in a provided ModuleToSummariesForIndex map.
594 template<typename Functor>
595 void forEachSummary(Functor Callback) {
596 if (ModuleToSummariesForIndex) {
597 for (auto &[GUID, GVS] : SortedSummariesForIndex) {
598 Callback({GUID, GVS}, false);
599 // Ensure aliasee is handled, e.g. for assigning a valueId,
600 // even if we are not importing the aliasee directly (the
601 // imported alias will contain a copy of aliasee).
602 if (auto *AS = dyn_cast<AliasSummary>(GVS))
603 Callback({AS->getAliaseeGUID(), &AS->getAliasee()}, true);
604 }
605 } else {
606 // Sort by GUID for deterministic output.
607 for (const auto &Summaries : Index.sortedGlobalValueSummariesRange())
608 for (auto &Summary : Summaries.second.getSummaryList())
609 Callback({Summaries.first, Summary.get()}, false);
610 }
611 }
612
613 /// Calls the callback for each entry in the modulePaths StringMap that
614 /// should be written to the module path string table. This hides the details
615 /// of whether they are being pulled from the entire index or just those in a
616 /// provided ModuleToSummariesForIndex map.
617 template <typename Functor> void forEachModule(Functor Callback) {
618 if (ModuleToSummariesForIndex) {
619 for (const auto &M : *ModuleToSummariesForIndex) {
620 const auto &MPI = Index.modulePaths().find(M.first);
621 if (MPI == Index.modulePaths().end()) {
622 // This should only happen if the bitcode file was empty, in which
623 // case we shouldn't be importing (the ModuleToSummariesForIndex
624 // would only include the module we are writing and index for).
625 assert(ModuleToSummariesForIndex->size() == 1);
626 continue;
627 }
628 Callback(*MPI);
629 }
630 } else {
631 // Since StringMap iteration order isn't guaranteed, order by path string
632 // first.
633 // FIXME: Make this a vector of StringMapEntry instead to avoid the later
634 // map lookup.
635 std::vector<StringRef> ModulePaths;
636 for (auto &[ModPath, _] : Index.modulePaths())
637 ModulePaths.push_back(ModPath);
638 llvm::sort(ModulePaths);
639 for (auto &ModPath : ModulePaths)
640 Callback(*Index.modulePaths().find(ModPath));
641 }
642 }
643
644 /// Main entry point for writing a combined index to bitcode.
645 void write();
646
647private:
648 void writeModStrings();
649 void writeCombinedGlobalValueSummary();
650
651 std::optional<unsigned> getValueId(GlobalValue::GUID ValGUID) {
652 auto VMI = GUIDToValueIdMap.find(ValGUID);
653 if (VMI == GUIDToValueIdMap.end())
654 return std::nullopt;
655 return VMI->second;
656 }
657
658 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
659};
660
661} // end anonymous namespace
662
663static unsigned getEncodedCastOpcode(unsigned Opcode) {
664 switch (Opcode) {
665 default: llvm_unreachable("Unknown cast instruction!");
666 case Instruction::Trunc : return bitc::CAST_TRUNC;
667 case Instruction::ZExt : return bitc::CAST_ZEXT;
668 case Instruction::SExt : return bitc::CAST_SEXT;
669 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
670 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
671 case Instruction::UIToFP : return bitc::CAST_UITOFP;
672 case Instruction::SIToFP : return bitc::CAST_SITOFP;
673 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
674 case Instruction::FPExt : return bitc::CAST_FPEXT;
675 case Instruction::PtrToAddr: return bitc::CAST_PTRTOADDR;
676 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
677 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
678 case Instruction::BitCast : return bitc::CAST_BITCAST;
679 case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
680 }
681}
682
683static unsigned getEncodedUnaryOpcode(unsigned Opcode) {
684 switch (Opcode) {
685 default: llvm_unreachable("Unknown binary instruction!");
686 case Instruction::FNeg: return bitc::UNOP_FNEG;
687 }
688}
689
690static unsigned getEncodedBinaryOpcode(unsigned Opcode) {
691 switch (Opcode) {
692 default: llvm_unreachable("Unknown binary instruction!");
693 case Instruction::Add:
694 case Instruction::FAdd: return bitc::BINOP_ADD;
695 case Instruction::Sub:
696 case Instruction::FSub: return bitc::BINOP_SUB;
697 case Instruction::Mul:
698 case Instruction::FMul: return bitc::BINOP_MUL;
699 case Instruction::UDiv: return bitc::BINOP_UDIV;
700 case Instruction::FDiv:
701 case Instruction::SDiv: return bitc::BINOP_SDIV;
702 case Instruction::URem: return bitc::BINOP_UREM;
703 case Instruction::FRem:
704 case Instruction::SRem: return bitc::BINOP_SREM;
705 case Instruction::Shl: return bitc::BINOP_SHL;
706 case Instruction::LShr: return bitc::BINOP_LSHR;
707 case Instruction::AShr: return bitc::BINOP_ASHR;
708 case Instruction::And: return bitc::BINOP_AND;
709 case Instruction::Or: return bitc::BINOP_OR;
710 case Instruction::Xor: return bitc::BINOP_XOR;
711 }
712}
713
714static unsigned getEncodedRMWOperation(const AtomicRMWInst &I) {
715 unsigned Encoding = 0;
716 switch (I.getOperation()) {
717 default: llvm_unreachable("Unknown RMW operation!");
719 Encoding = bitc::RMW_XCHG;
720 break;
722 Encoding = bitc::RMW_ADD;
723 break;
725 Encoding = bitc::RMW_SUB;
726 break;
728 Encoding = bitc::RMW_AND;
729 break;
731 Encoding = bitc::RMW_NAND;
732 break;
734 Encoding = bitc::RMW_OR;
735 break;
737 Encoding = bitc::RMW_XOR;
738 break;
740 Encoding = bitc::RMW_MAX;
741 break;
743 Encoding = bitc::RMW_MIN;
744 break;
746 Encoding = bitc::RMW_UMAX;
747 break;
749 Encoding = bitc::RMW_UMIN;
750 break;
752 Encoding = bitc::RMW_FADD;
753 break;
755 Encoding = bitc::RMW_FSUB;
756 break;
758 Encoding = bitc::RMW_FMAX;
759 break;
761 Encoding = bitc::RMW_FMIN;
762 break;
764 Encoding = bitc::RMW_FMAXIMUM;
765 break;
767 Encoding = bitc::RMW_FMINIMUM;
768 break;
770 Encoding = bitc::RMW_FMAXIMUMNUM;
771 break;
773 Encoding = bitc::RMW_FMINIMUMNUM;
774 break;
776 Encoding = bitc::RMW_UINC_WRAP;
777 break;
779 Encoding = bitc::RMW_UDEC_WRAP;
780 break;
782 Encoding = bitc::RMW_USUB_COND;
783 break;
785 Encoding = bitc::RMW_USUB_SAT;
786 break;
787 }
788
789 if (I.isElementwise())
790 Encoding |= bitc::RMW_ELEMENTWISE_FLAG;
791 return Encoding;
792}
793
806
807static void writeStringRecord(BitstreamWriter &Stream, unsigned Code,
808 StringRef Str, unsigned AbbrevToUse) {
810
811 // Code: [strchar x N]
812 for (char C : Str) {
813 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(C))
814 AbbrevToUse = 0;
815 Vals.push_back(C);
816 }
817
818 // Emit the finished record.
819 Stream.EmitRecord(Code, Vals, AbbrevToUse);
820}
821
823 switch (Kind) {
824 case Attribute::Alignment:
826 case Attribute::AllocAlign:
828 case Attribute::AllocSize:
830 case Attribute::AlwaysInline:
832 case Attribute::Builtin:
834 case Attribute::ByVal:
836 case Attribute::Convergent:
838 case Attribute::InAlloca:
840 case Attribute::Cold:
842 case Attribute::DisableSanitizerInstrumentation:
844 case Attribute::FnRetThunkExtern:
846 case Attribute::Flatten:
848 case Attribute::Hot:
849 return bitc::ATTR_KIND_HOT;
850 case Attribute::ElementType:
852 case Attribute::HybridPatchable:
854 case Attribute::InlineHint:
856 case Attribute::InReg:
858 case Attribute::JumpTable:
860 case Attribute::MinSize:
862 case Attribute::AllocatedPointer:
864 case Attribute::AllocKind:
866 case Attribute::Memory:
868 case Attribute::NoFPClass:
870 case Attribute::Naked:
872 case Attribute::Nest:
874 case Attribute::NoAlias:
876 case Attribute::NoBuiltin:
878 case Attribute::NoCallback:
880 case Attribute::NoDivergenceSource:
882 case Attribute::AlwaysUniform:
884 case Attribute::NoDuplicate:
886 case Attribute::NoFree:
888 case Attribute::NoFreeObj:
890 case Attribute::NoImplicitFloat:
892 case Attribute::NoInline:
894 case Attribute::NoRecurse:
896 case Attribute::NoMerge:
898 case Attribute::NonLazyBind:
900 case Attribute::NonNull:
902 case Attribute::Dereferenceable:
904 case Attribute::DereferenceableOrNull:
906 case Attribute::NoRedZone:
908 case Attribute::NoReturn:
910 case Attribute::NoSync:
912 case Attribute::NoCfCheck:
914 case Attribute::NoProfile:
916 case Attribute::SkipProfile:
918 case Attribute::NoUnwind:
920 case Attribute::NoSanitizeBounds:
922 case Attribute::NoSanitizeCoverage:
924 case Attribute::NullPointerIsValid:
926 case Attribute::OptimizeForDebugging:
928 case Attribute::OptForFuzzing:
930 case Attribute::OptimizeForSize:
932 case Attribute::OptimizeNone:
934 case Attribute::ReadNone:
936 case Attribute::ReadOnly:
938 case Attribute::Returned:
940 case Attribute::ReturnsTwice:
942 case Attribute::SExt:
944 case Attribute::Speculatable:
946 case Attribute::StackAlignment:
948 case Attribute::StackProtect:
950 case Attribute::StackProtectReq:
952 case Attribute::StackProtectStrong:
954 case Attribute::SafeStack:
956 case Attribute::ShadowCallStack:
958 case Attribute::StrictFP:
960 case Attribute::StructRet:
962 case Attribute::SanitizeAddress:
964 case Attribute::SanitizeAllocToken:
966 case Attribute::SanitizeHWAddress:
968 case Attribute::SanitizeThread:
970 case Attribute::SanitizeConcurrency:
972 case Attribute::SanitizeType:
974 case Attribute::SanitizeMemory:
976 case Attribute::SanitizeNumericalStability:
978 case Attribute::SanitizeRealtime:
980 case Attribute::SanitizeRealtimeBlocking:
982 case Attribute::SpeculativeLoadHardening:
984 case Attribute::SwiftError:
986 case Attribute::SwiftSelf:
988 case Attribute::SwiftAsync:
990 case Attribute::UWTable:
992 case Attribute::VScaleRange:
994 case Attribute::WillReturn:
996 case Attribute::WriteOnly:
998 case Attribute::ZExt:
1000 case Attribute::ImmArg:
1002 case Attribute::SanitizeMemTag:
1004 case Attribute::Preallocated:
1006 case Attribute::NoUndef:
1008 case Attribute::ByRef:
1009 return bitc::ATTR_KIND_BYREF;
1010 case Attribute::MustProgress:
1012 case Attribute::PresplitCoroutine:
1014 case Attribute::Writable:
1016 case Attribute::CoroDestroyOnlyWhenComplete:
1018 case Attribute::CoroElideSafe:
1020 case Attribute::DeadOnUnwind:
1022 case Attribute::Range:
1023 return bitc::ATTR_KIND_RANGE;
1024 case Attribute::Initializes:
1026 case Attribute::NoExt:
1028 case Attribute::Captures:
1030 case Attribute::DeadOnReturn:
1032 case Attribute::NoCreateUndefOrPoison:
1034 case Attribute::DenormalFPEnv:
1036 case Attribute::NoOutline:
1038 case Attribute::NoIPA:
1039 return bitc::ATTR_KIND_NOIPA;
1040 case Attribute::LikelyModuleLocal:
1043 llvm_unreachable("Can not encode end-attribute kinds marker.");
1044 case Attribute::None:
1045 llvm_unreachable("Can not encode none-attribute.");
1046 }
1047
1048 llvm_unreachable("Trying to encode unknown attribute");
1049}
1050
1052 if ((int64_t)V >= 0)
1053 Vals.push_back(V << 1);
1054 else
1055 Vals.push_back((-V << 1) | 1);
1056}
1057
1059 // We have an arbitrary precision integer value to write whose
1060 // bit width is > 64. However, in canonical unsigned integer
1061 // format it is likely that the high bits are going to be zero.
1062 // So, we only write the number of active words.
1063 unsigned NumWords = A.getActiveWords();
1064 const uint64_t *RawData = A.getRawData();
1065 for (unsigned i = 0; i < NumWords; i++)
1066 emitSignedInt64(Vals, RawData[i]);
1067}
1068
1070 const ConstantRange &CR, bool EmitBitWidth) {
1071 unsigned BitWidth = CR.getBitWidth();
1072 if (EmitBitWidth)
1073 Record.push_back(BitWidth);
1074 if (BitWidth > 64) {
1075 Record.push_back(CR.getLower().getActiveWords() |
1076 (uint64_t(CR.getUpper().getActiveWords()) << 32));
1079 } else {
1082 }
1083}
1084
1085void ModuleBitcodeWriter::writeAttributeGroupTable() {
1086 const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
1087 VE.getAttributeGroups();
1088 if (AttrGrps.empty()) return;
1089
1091
1092 SmallVector<uint64_t, 64> Record;
1093 for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) {
1094 unsigned AttrListIndex = Pair.first;
1095 AttributeSet AS = Pair.second;
1096 Record.push_back(VE.getAttributeGroupID(Pair));
1097 Record.push_back(AttrListIndex);
1098
1099 for (Attribute Attr : AS) {
1100 if (Attr.isEnumAttribute()) {
1101 Record.push_back(0);
1102 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
1103 } else if (Attr.isIntAttribute()) {
1104 Record.push_back(1);
1105 Attribute::AttrKind Kind = Attr.getKindAsEnum();
1106 Record.push_back(getAttrKindEncoding(Kind));
1107 if (Kind == Attribute::Memory) {
1108 // Version field for upgrading old memory effects.
1109 const uint64_t Version = 2;
1110 Record.push_back((Version << 56) | Attr.getValueAsInt());
1111 } else {
1112 Record.push_back(Attr.getValueAsInt());
1113 }
1114 } else if (Attr.isStringAttribute()) {
1115 StringRef Kind = Attr.getKindAsString();
1116 StringRef Val = Attr.getValueAsString();
1117
1118 Record.push_back(Val.empty() ? 3 : 4);
1119 Record.append(Kind.begin(), Kind.end());
1120 Record.push_back(0);
1121 if (!Val.empty()) {
1122 Record.append(Val.begin(), Val.end());
1123 Record.push_back(0);
1124 }
1125 } else if (Attr.isTypeAttribute()) {
1126 Type *Ty = Attr.getValueAsType();
1127 Record.push_back(Ty ? 6 : 5);
1128 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
1129 if (Ty)
1130 Record.push_back(VE.getTypeID(Attr.getValueAsType()));
1131 } else if (Attr.isConstantRangeAttribute()) {
1132 Record.push_back(7);
1133 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
1134 emitConstantRange(Record, Attr.getValueAsConstantRange(),
1135 /*EmitBitWidth=*/true);
1136 } else {
1137 assert(Attr.isConstantRangeListAttribute());
1138 Record.push_back(8);
1139 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
1140 ArrayRef<ConstantRange> Val = Attr.getValueAsConstantRangeList();
1141 Record.push_back(Val.size());
1142 Record.push_back(Val[0].getBitWidth());
1143 for (auto &CR : Val)
1144 emitConstantRange(Record, CR, /*EmitBitWidth=*/false);
1145 }
1146 }
1147
1149 Record.clear();
1150 }
1151
1152 Stream.ExitBlock();
1153}
1154
1155void ModuleBitcodeWriter::writeAttributeTable() {
1156 const std::vector<AttributeList> &Attrs = VE.getAttributeLists();
1157 if (Attrs.empty()) return;
1158
1160
1161 SmallVector<uint64_t, 64> Record;
1162 for (const AttributeList &AL : Attrs) {
1163 for (unsigned i : AL.indexes()) {
1164 AttributeSet AS = AL.getAttributes(i);
1165 if (AS.hasAttributes())
1166 Record.push_back(VE.getAttributeGroupID({i, AS}));
1167 }
1168
1169 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
1170 Record.clear();
1171 }
1172
1173 Stream.ExitBlock();
1174}
1175
1176/// WriteTypeTable - Write out the type table for a module.
1177void ModuleBitcodeWriter::writeTypeTable() {
1178 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
1179
1180 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
1181 SmallVector<uint64_t, 64> TypeVals;
1182
1184
1185 // Abbrev for TYPE_CODE_OPAQUE_POINTER.
1186 auto Abbv = std::make_shared<BitCodeAbbrev>();
1187 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_OPAQUE_POINTER));
1188 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
1189 unsigned OpaquePtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1190
1191 // Abbrev for TYPE_CODE_FUNCTION.
1192 Abbv = std::make_shared<BitCodeAbbrev>();
1193 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
1194 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
1195 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1196 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
1197 unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1198
1199 // Abbrev for TYPE_CODE_STRUCT_ANON.
1200 Abbv = std::make_shared<BitCodeAbbrev>();
1201 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
1202 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
1203 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1204 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
1205 unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1206
1207 // Abbrev for TYPE_CODE_STRUCT_NAME.
1208 Abbv = std::make_shared<BitCodeAbbrev>();
1209 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
1210 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1211 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1212 unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1213
1214 // Abbrev for TYPE_CODE_STRUCT_NAMED.
1215 Abbv = std::make_shared<BitCodeAbbrev>();
1216 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
1217 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
1218 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1219 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
1220 unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1221
1222 // Abbrev for TYPE_CODE_ARRAY.
1223 Abbv = std::make_shared<BitCodeAbbrev>();
1224 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
1225 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
1226 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
1227 unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1228
1229 // Emit an entry count so the reader can reserve space.
1230 TypeVals.push_back(TypeList.size());
1231 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
1232 TypeVals.clear();
1233
1234 // Loop over all of the types, emitting each in turn.
1235 for (Type *T : TypeList) {
1236 int AbbrevToUse = 0;
1237 unsigned Code = 0;
1238
1239 switch (T->getTypeID()) {
1240 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
1241 case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break;
1242 case Type::BFloatTyID: Code = bitc::TYPE_CODE_BFLOAT; break;
1243 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
1244 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
1245 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
1246 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
1247 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
1248 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
1249 case Type::MetadataTyID:
1251 break;
1252 case Type::X86_AMXTyID: Code = bitc::TYPE_CODE_X86_AMX; break;
1253 case Type::TokenTyID: Code = bitc::TYPE_CODE_TOKEN; break;
1254 case Type::ByteTyID:
1255 // BYTE: [width]
1257 TypeVals.push_back(T->getByteBitWidth());
1258 break;
1259 case Type::IntegerTyID:
1260 // INTEGER: [width]
1263 break;
1264 case Type::PointerTyID: {
1266 unsigned AddressSpace = PTy->getAddressSpace();
1267 // OPAQUE_POINTER: [address space]
1269 TypeVals.push_back(AddressSpace);
1270 if (AddressSpace == 0)
1271 AbbrevToUse = OpaquePtrAbbrev;
1272 break;
1273 }
1274 case Type::FunctionTyID: {
1275 FunctionType *FT = cast<FunctionType>(T);
1276 // FUNCTION: [isvararg, retty, paramty x N]
1278 TypeVals.push_back(FT->isVarArg());
1279 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
1280 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
1281 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
1282 AbbrevToUse = FunctionAbbrev;
1283 break;
1284 }
1285 case Type::StructTyID: {
1286 StructType *ST = cast<StructType>(T);
1287 // STRUCT: [ispacked, eltty x N]
1288 TypeVals.push_back(ST->isPacked());
1289 // Output all of the element types.
1290 for (Type *ET : ST->elements())
1291 TypeVals.push_back(VE.getTypeID(ET));
1292
1293 if (ST->isLiteral()) {
1295 AbbrevToUse = StructAnonAbbrev;
1296 } else {
1297 if (ST->isOpaque()) {
1299 } else {
1301 AbbrevToUse = StructNamedAbbrev;
1302 }
1303
1304 // Emit the name if it is present.
1305 if (!ST->getName().empty())
1307 StructNameAbbrev);
1308 }
1309 break;
1310 }
1311 case Type::ArrayTyID: {
1313 // ARRAY: [numelts, eltty]
1315 TypeVals.push_back(AT->getNumElements());
1316 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
1317 AbbrevToUse = ArrayAbbrev;
1318 break;
1319 }
1320 case Type::FixedVectorTyID:
1321 case Type::ScalableVectorTyID: {
1323 // VECTOR [numelts, eltty] or
1324 // [numelts, eltty, scalable]
1326 TypeVals.push_back(VT->getElementCount().getKnownMinValue());
1327 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
1329 TypeVals.push_back(true);
1330 break;
1331 }
1332 case Type::TargetExtTyID: {
1333 TargetExtType *TET = cast<TargetExtType>(T);
1336 StructNameAbbrev);
1337 TypeVals.push_back(TET->getNumTypeParameters());
1338 for (Type *InnerTy : TET->type_params())
1339 TypeVals.push_back(VE.getTypeID(InnerTy));
1340 llvm::append_range(TypeVals, TET->int_params());
1341 break;
1342 }
1343 case Type::TypedPointerTyID:
1344 llvm_unreachable("Typed pointers cannot be added to IR modules");
1345 }
1346
1347 // Emit the finished record.
1348 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
1349 TypeVals.clear();
1350 }
1351
1352 Stream.ExitBlock();
1353}
1354
1356 switch (Linkage) {
1358 return 0;
1360 return 16;
1362 return 2;
1364 return 3;
1366 return 18;
1368 return 7;
1370 return 8;
1372 return 9;
1374 return 17;
1376 return 19;
1378 return 12;
1379 }
1380 llvm_unreachable("Invalid linkage");
1381}
1382
1383static unsigned getEncodedLinkage(const GlobalValue &GV) {
1384 return getEncodedLinkage(GV.getLinkage());
1385}
1386
1388 uint64_t RawFlags = 0;
1389 RawFlags |= Flags.ReadNone;
1390 RawFlags |= (Flags.ReadOnly << 1);
1391 RawFlags |= (Flags.NoRecurse << 2);
1392 RawFlags |= (Flags.ReturnDoesNotAlias << 3);
1393 RawFlags |= (Flags.NoInline << 4);
1394 RawFlags |= (Flags.AlwaysInline << 5);
1395 RawFlags |= (Flags.NoUnwind << 6);
1396 RawFlags |= (Flags.MayThrow << 7);
1397 RawFlags |= (Flags.HasUnknownCall << 8);
1398 RawFlags |= (Flags.MustBeUnreachable << 9);
1399 RawFlags |= (Flags.HasEscapingBlockAddress << 10);
1400 return RawFlags;
1401}
1402
1403// Decode the flags for GlobalValue in the summary. See getDecodedGVSummaryFlags
1404// in BitcodeReader.cpp.
1406 bool ImportAsDecl = false) {
1407 uint64_t RawFlags = 0;
1408
1409 RawFlags |= Flags.NotEligibleToImport; // bool
1410 RawFlags |= (Flags.Live << 1);
1411 RawFlags |= (Flags.DSOLocal << 2);
1412 RawFlags |= (Flags.CanAutoHide << 3);
1413
1414 // Linkage don't need to be remapped at that time for the summary. Any future
1415 // change to the getEncodedLinkage() function will need to be taken into
1416 // account here as well.
1417 RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits
1418
1419 RawFlags |= (Flags.Visibility << 8); // 2 bits
1420
1421 unsigned ImportType = Flags.ImportType | ImportAsDecl;
1422 RawFlags |= (ImportType << 10); // 1 bit
1423
1424 RawFlags |= (Flags.NoRenameOnPromotion << 11); // 1 bit
1425
1426 return RawFlags;
1427}
1428
1430 uint64_t RawFlags = Flags.MaybeReadOnly | (Flags.MaybeWriteOnly << 1) |
1431 (Flags.Constant << 2) | Flags.VCallVisibility << 3;
1432 return RawFlags;
1433}
1434
1436 uint64_t RawFlags = 0;
1437
1438 RawFlags |= CI.Hotness; // 3 bits
1439 RawFlags |= (CI.HasTailCall << 3); // 1 bit
1440 RawFlags |= (CI.HasIndirectCall << 4); // 1 bit
1441
1442 return RawFlags;
1443}
1444
1445static unsigned getEncodedVisibility(const GlobalValue &GV) {
1446 switch (GV.getVisibility()) {
1447 case GlobalValue::DefaultVisibility: return 0;
1448 case GlobalValue::HiddenVisibility: return 1;
1449 case GlobalValue::ProtectedVisibility: return 2;
1450 }
1451 llvm_unreachable("Invalid visibility");
1452}
1453
1454static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
1455 switch (GV.getDLLStorageClass()) {
1456 case GlobalValue::DefaultStorageClass: return 0;
1459 }
1460 llvm_unreachable("Invalid DLL storage class");
1461}
1462
1463static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
1464 switch (GV.getThreadLocalMode()) {
1465 case GlobalVariable::NotThreadLocal: return 0;
1469 case GlobalVariable::LocalExecTLSModel: return 4;
1470 }
1471 llvm_unreachable("Invalid TLS model");
1472}
1473
1474static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
1475 switch (C.getSelectionKind()) {
1476 case Comdat::Any:
1478 case Comdat::ExactMatch:
1480 case Comdat::Largest:
1484 case Comdat::SameSize:
1486 }
1487 llvm_unreachable("Invalid selection kind");
1488}
1489
1490static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) {
1491 switch (GV.getUnnamedAddr()) {
1492 case GlobalValue::UnnamedAddr::None: return 0;
1493 case GlobalValue::UnnamedAddr::Local: return 2;
1494 case GlobalValue::UnnamedAddr::Global: return 1;
1495 }
1496 llvm_unreachable("Invalid unnamed_addr");
1497}
1498
1499size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) {
1500 if (GenerateHash)
1501 Hasher.update(Str);
1502 return StrtabBuilder.add(Str);
1503}
1504
1505void ModuleBitcodeWriter::writeComdats() {
1507 for (const Comdat *C : VE.getComdats()) {
1508 // COMDAT: [strtab offset, strtab size, selection_kind]
1509 Vals.push_back(addToStrtab(C->getName()));
1510 Vals.push_back(C->getName().size());
1512 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
1513 Vals.clear();
1514 }
1515}
1516
1517/// Write a record that will eventually hold the word offset of the
1518/// module-level VST. For now the offset is 0, which will be backpatched
1519/// after the real VST is written. Saves the bit offset to backpatch.
1520void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
1521 // Write a placeholder value in for the offset of the real VST,
1522 // which is written after the function blocks so that it can include
1523 // the offset of each function. The placeholder offset will be
1524 // updated when the real VST is written.
1525 auto Abbv = std::make_shared<BitCodeAbbrev>();
1526 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET));
1527 // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
1528 // hold the real VST offset. Must use fixed instead of VBR as we don't
1529 // know how many VBR chunks to reserve ahead of time.
1530 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1531 unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1532
1533 // Emit the placeholder
1535 Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
1536
1537 // Compute and save the bit offset to the placeholder, which will be
1538 // patched when the real VST is written. We can simply subtract the 32-bit
1539 // fixed size from the current bit number to get the location to backpatch.
1540 VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32;
1541}
1542
1544
1545/// Determine the encoding to use for the given string name and length.
1547 bool isChar6 = true;
1548 for (char C : Str) {
1549 if (isChar6)
1550 isChar6 = BitCodeAbbrevOp::isChar6(C);
1551 if ((unsigned char)C & 128)
1552 // don't bother scanning the rest.
1553 return SE_Fixed8;
1554 }
1555 if (isChar6)
1556 return SE_Char6;
1557 return SE_Fixed7;
1558}
1559
1560static_assert(sizeof(GlobalValue::SanitizerMetadata) <= sizeof(unsigned),
1561 "Sanitizer Metadata is too large for naive serialization.");
1562static unsigned
1564 return Meta.NoAddress | (Meta.NoHWAddress << 1) |
1565 (Meta.Memtag << 2) | (Meta.IsDynInit << 3);
1566}
1567
1568/// Emit top-level description of module, including target triple, inline asm,
1569/// descriptors for global variables, and function prototype info.
1570/// Returns the bit offset to backpatch with the location of the real VST.
1571void ModuleBitcodeWriter::writeModuleInfo() {
1572 // Emit various pieces of data attached to a module.
1573 if (!M.getTargetTriple().empty())
1575 M.getTargetTriple().str(), 0 /*TODO*/);
1576 const std::string &DL = M.getDataLayoutStr();
1577 if (!DL.empty())
1579
1580 for (const Module::GlobalAsmFragment &Frag : M.getModuleInlineAsm()) {
1582 Frag.Props.getAsStrings();
1583 for (auto [Key, Value] : Props) {
1585 Record.append(Key.begin(), Key.end());
1586 Record.push_back(0);
1587 Record.append(Value.begin(), Value.end());
1589 }
1590 writeStringRecord(Stream, bitc::MODULE_CODE_ASM, Frag.Asm, 0 /*TODO*/);
1591 }
1592
1593 // Emit information about sections and GC, computing how many there are. Also
1594 // compute the maximum alignment value.
1595 std::map<std::string, unsigned> SectionMap;
1596 std::map<std::string, unsigned> GCMap;
1597 MaybeAlign MaxGVarAlignment;
1598 unsigned MaxGlobalType = 0;
1599 for (const GlobalVariable &GV : M.globals()) {
1600 if (MaybeAlign A = GV.getAlign())
1601 MaxGVarAlignment = !MaxGVarAlignment ? *A : std::max(*MaxGVarAlignment, *A);
1602 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
1603 if (GV.hasSection()) {
1604 // Give section names unique ID's.
1605 unsigned &Entry = SectionMap[std::string(GV.getSection())];
1606 if (!Entry) {
1607 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
1608 0 /*TODO*/);
1609 Entry = SectionMap.size();
1610 }
1611 }
1612 }
1613 for (const Function &F : M) {
1614 if (F.hasSection()) {
1615 // Give section names unique ID's.
1616 unsigned &Entry = SectionMap[std::string(F.getSection())];
1617 if (!Entry) {
1619 0 /*TODO*/);
1620 Entry = SectionMap.size();
1621 }
1622 }
1623 if (F.hasGC()) {
1624 // Same for GC names.
1625 unsigned &Entry = GCMap[F.getGC()];
1626 if (!Entry) {
1628 0 /*TODO*/);
1629 Entry = GCMap.size();
1630 }
1631 }
1632 }
1633
1634 // Emit abbrev for globals, now that we know # sections and max alignment.
1635 unsigned SimpleGVarAbbrev = 0;
1636 if (!M.global_empty()) {
1637 // Add an abbrev for common globals with no visibility or thread localness.
1638 auto Abbv = std::make_shared<BitCodeAbbrev>();
1639 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
1640 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1641 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1642 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1643 Log2_32_Ceil(MaxGlobalType+1)));
1644 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2
1645 //| explicitType << 1
1646 //| constant
1647 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
1648 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
1649 if (!MaxGVarAlignment) // Alignment.
1650 Abbv->Add(BitCodeAbbrevOp(0));
1651 else {
1652 unsigned MaxEncAlignment = getEncodedAlign(MaxGVarAlignment);
1653 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1654 Log2_32_Ceil(MaxEncAlignment+1)));
1655 }
1656 if (SectionMap.empty()) // Section.
1657 Abbv->Add(BitCodeAbbrevOp(0));
1658 else
1659 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1660 Log2_32_Ceil(SectionMap.size()+1)));
1661 // Don't bother emitting vis + thread local.
1662 SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1663 }
1664
1666 // Emit the module's source file name.
1667 {
1668 StringEncoding Bits = getStringEncoding(M.getSourceFileName());
1669 BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
1670 if (Bits == SE_Char6)
1671 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
1672 else if (Bits == SE_Fixed7)
1673 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
1674
1675 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
1676 auto Abbv = std::make_shared<BitCodeAbbrev>();
1677 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
1678 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1679 Abbv->Add(AbbrevOpToUse);
1680 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1681
1682 for (const auto P : M.getSourceFileName())
1683 Vals.push_back((unsigned char)P);
1684
1685 // Emit the finished record.
1686 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
1687 Vals.clear();
1688 }
1689
1690 writeGUIDList();
1691
1692 // Emit the global variable information.
1693 for (const GlobalVariable &GV : M.globals()) {
1694 unsigned AbbrevToUse = 0;
1695
1696 // GLOBALVAR: [strtab offset, strtab size, type, isconst, initid,
1697 // linkage, alignment, section, visibility, threadlocal,
1698 // unnamed_addr, externally_initialized, dllstorageclass,
1699 // comdat, attributes, DSO_Local, GlobalSanitizer, code_model]
1700 Vals.push_back(addToStrtab(GV.getName()));
1701 Vals.push_back(GV.getName().size());
1702 Vals.push_back(VE.getTypeID(GV.getValueType()));
1703 Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
1704 Vals.push_back(GV.isDeclaration() ? 0 :
1705 (VE.getValueID(GV.getInitializer()) + 1));
1706 Vals.push_back(getEncodedLinkage(GV));
1707 Vals.push_back(getEncodedAlign(GV.getAlign()));
1708 Vals.push_back(GV.hasSection() ? SectionMap[std::string(GV.getSection())]
1709 : 0);
1710 if (GV.isThreadLocal() ||
1711 GV.getVisibility() != GlobalValue::DefaultVisibility ||
1712 GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1713 GV.isExternallyInitialized() ||
1714 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
1715 GV.hasComdat() || GV.hasAttributes() || GV.isDSOLocal() ||
1716 GV.hasPartition() || GV.hasSanitizerMetadata() || GV.getCodeModel()) {
1720 Vals.push_back(GV.isExternallyInitialized());
1722 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
1723
1724 auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
1725 Vals.push_back(VE.getAttributeListID(AL));
1726
1727 Vals.push_back(GV.isDSOLocal());
1728 Vals.push_back(addToStrtab(GV.getPartition()));
1729 Vals.push_back(GV.getPartition().size());
1730
1731 Vals.push_back((GV.hasSanitizerMetadata() ? serializeSanitizerMetadata(
1732 GV.getSanitizerMetadata())
1733 : 0));
1734 Vals.push_back(GV.getCodeModelRaw());
1735 } else {
1736 AbbrevToUse = SimpleGVarAbbrev;
1737 }
1738
1739 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
1740 Vals.clear();
1741 }
1742
1743 // Emit the function proto information.
1744 for (const Function &F : M) {
1745 // FUNCTION: [strtab offset, strtab size, type, callingconv, isproto,
1746 // linkage, paramattrs, alignment, section, visibility, gc,
1747 // unnamed_addr, prologuedata, dllstorageclass, comdat,
1748 // prefixdata, personalityfn, DSO_Local, addrspace,
1749 // partition_strtab, partition_size, prefalign]
1750 Vals.push_back(addToStrtab(F.getName()));
1751 Vals.push_back(F.getName().size());
1752 Vals.push_back(VE.getTypeID(F.getFunctionType()));
1753 Vals.push_back(F.getCallingConv());
1754 Vals.push_back(F.isDeclaration());
1756 Vals.push_back(VE.getAttributeListID(F.getAttributes()));
1757 Vals.push_back(getEncodedAlign(F.getAlign()));
1758 Vals.push_back(F.hasSection() ? SectionMap[std::string(F.getSection())]
1759 : 0);
1761 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
1763 Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
1764 : 0);
1766 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
1767 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
1768 : 0);
1769 Vals.push_back(
1770 F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
1771
1772 Vals.push_back(F.isDSOLocal());
1773 Vals.push_back(F.getAddressSpace());
1774 Vals.push_back(addToStrtab(F.getPartition()));
1775 Vals.push_back(F.getPartition().size());
1776 Vals.push_back(getEncodedAlign(F.getPreferredAlignment()));
1777
1778 unsigned AbbrevToUse = 0;
1779 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
1780 Vals.clear();
1781 }
1782
1783 // Emit the alias information.
1784 for (const GlobalAlias &A : M.aliases()) {
1785 // ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage,
1786 // visibility, dllstorageclass, threadlocal, unnamed_addr,
1787 // DSO_Local]
1788 Vals.push_back(addToStrtab(A.getName()));
1789 Vals.push_back(A.getName().size());
1790 Vals.push_back(VE.getTypeID(A.getValueType()));
1791 Vals.push_back(A.getType()->getAddressSpace());
1792 Vals.push_back(VE.getValueID(A.getAliasee()));
1798 Vals.push_back(A.isDSOLocal());
1799 Vals.push_back(addToStrtab(A.getPartition()));
1800 Vals.push_back(A.getPartition().size());
1801
1802 unsigned AbbrevToUse = 0;
1803 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
1804 Vals.clear();
1805 }
1806
1807 // Emit the ifunc information.
1808 for (const GlobalIFunc &I : M.ifuncs()) {
1809 // IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver
1810 // val#, linkage, visibility, DSO_Local]
1811 Vals.push_back(addToStrtab(I.getName()));
1812 Vals.push_back(I.getName().size());
1813 Vals.push_back(VE.getTypeID(I.getValueType()));
1814 Vals.push_back(I.getType()->getAddressSpace());
1815 Vals.push_back(VE.getValueID(I.getResolver()));
1818 Vals.push_back(I.isDSOLocal());
1819 Vals.push_back(addToStrtab(I.getPartition()));
1820 Vals.push_back(I.getPartition().size());
1821 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
1822 Vals.clear();
1823 }
1824
1825 writeValueSymbolTableForwardDecl();
1826}
1827
1829 uint64_t Flags = 0;
1830
1831 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
1832 if (OBO->hasNoSignedWrap())
1833 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
1834 if (OBO->hasNoUnsignedWrap())
1835 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
1836 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
1837 if (PEO->isExact())
1838 Flags |= 1 << bitc::PEO_EXACT;
1839 } else if (const auto *PDI = dyn_cast<PossiblyDisjointInst>(V)) {
1840 if (PDI->isDisjoint())
1841 Flags |= 1 << bitc::PDI_DISJOINT;
1842 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
1843 if (FPMO->hasAllowReassoc())
1844 Flags |= bitc::AllowReassoc;
1845 if (FPMO->hasNoNaNs())
1846 Flags |= bitc::NoNaNs;
1847 if (FPMO->hasNoInfs())
1848 Flags |= bitc::NoInfs;
1849 if (FPMO->hasNoSignedZeros())
1850 Flags |= bitc::NoSignedZeros;
1851 if (FPMO->hasAllowReciprocal())
1852 Flags |= bitc::AllowReciprocal;
1853 if (FPMO->hasAllowContract())
1854 Flags |= bitc::AllowContract;
1855 if (FPMO->hasApproxFunc())
1856 Flags |= bitc::ApproxFunc;
1857
1858 // Handle uitofp.
1859 if (const auto *NNI = dyn_cast<PossiblyNonNegInst>(V)) {
1860 Flags <<= 1;
1861 if (NNI->hasNonNeg())
1862 Flags |= 1 << bitc::PNNI_NON_NEG;
1863 }
1864 } else if (const auto *NNI = dyn_cast<PossiblyNonNegInst>(V)) {
1865 if (NNI->hasNonNeg())
1866 Flags |= 1 << bitc::PNNI_NON_NEG;
1867 } else if (const auto *TI = dyn_cast<TruncInst>(V)) {
1868 if (TI->hasNoSignedWrap())
1869 Flags |= 1 << bitc::TIO_NO_SIGNED_WRAP;
1870 if (TI->hasNoUnsignedWrap())
1871 Flags |= 1 << bitc::TIO_NO_UNSIGNED_WRAP;
1872 } else if (const auto *GEP = dyn_cast<GEPOperator>(V)) {
1873 if (GEP->isInBounds())
1874 Flags |= 1 << bitc::GEP_INBOUNDS;
1875 if (GEP->hasNoUnsignedSignedWrap())
1876 Flags |= 1 << bitc::GEP_NUSW;
1877 if (GEP->hasNoUnsignedWrap())
1878 Flags |= 1 << bitc::GEP_NUW;
1879 } else if (const auto *ICmp = dyn_cast<ICmpInst>(V)) {
1880 if (ICmp->hasSameSign())
1881 Flags |= 1 << bitc::ICMP_SAME_SIGN;
1882 } else if (const auto *ASC = dyn_cast<AddrSpaceCastInst>(V)) {
1883 if (ASC->hasNonNull())
1884 Flags |= 1 << bitc::ASCI_NON_NULL;
1885 }
1886
1887 return Flags;
1888}
1889
1890void ModuleBitcodeWriter::writeValueAsMetadata(
1891 const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
1892 // Mimic an MDNode with a value as one operand.
1893 Value *V = MD->getValue();
1894 Record.push_back(VE.getTypeID(V->getType()));
1895 Record.push_back(VE.getValueID(V));
1896 Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
1897 Record.clear();
1898}
1899
1900void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N,
1901 SmallVectorImpl<uint64_t> &Record,
1902 unsigned Abbrev) {
1903 for (const MDOperand &MDO : N->operands()) {
1904 Metadata *MD = MDO;
1905 assert(!(MD && isa<LocalAsMetadata>(MD)) &&
1906 "Unexpected function-local metadata");
1907 Record.push_back(VE.getMetadataOrNullID(MD));
1908 }
1909 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
1911 Record, Abbrev);
1912 Record.clear();
1913}
1914
1915void ModuleBitcodeWriter::writeMDFunctionLocalContext(
1916 const MDFunctionLocalContext *N, SmallVectorImpl<uint64_t> &Record,
1917 unsigned &Abbrev) {
1918 // Don't record distinctness, since MDFunctionLocalContext is always distinct,
1919 // but use a spare bit in the version record to record isNonDebug.
1920 const uint64_t Version = 1 << 1;
1921 Record.push_back((uint64_t)N->isNonDebug() | Version);
1922 // Also do not record MaxAtomGroup, as it is a transient field.
1923 // Print each array separately, leading with a length-field. Since we have no
1924 // abbreviation, each record uses the default VBR6, and therefore we aim to
1925 // keep the representation simple here, writing each field separately.
1926
1927 // We don't write Scopes or SrcLocs for nodebug contexts.
1928 if (!N->isNonDebug()) {
1929 // Scopes
1930 Record.push_back(N->getScopes().size());
1931 for (const FLScope &Scope : N->getScopes())
1932 Record.push_back(VE.getMetadataID(Scope.get()));
1933 // SrcLocs
1934 Record.push_back(N->getSrcLocs().size());
1935 for (const FLSrcLoc &SrcLoc : N->getSrcLocs()) {
1936 Record.push_back(SrcLoc.Line);
1937 Record.push_back(SrcLoc.Column);
1938 // Raw FLIndex is more efficiently encoded than the underlying value.
1939 Record.push_back(SrcLoc.ScopeIdx.asRaw());
1940 }
1941 }
1942 // InlinedCalls
1943 Record.push_back(N->getInlinedCalls().size());
1944 for (const FLInlinedCall &InlinedCall : N->getInlinedCalls()) {
1945 Record.push_back(InlinedCall.SrcLocIdx.asRaw());
1946 // Since Uniquable is 1 bit of information, but we can't use an abbreviation
1947 // to give it a fixed 1-bit record, we instead share the InlinedAt and
1948 // Uniquable fields in a single record; InlinedAt is the most likely field
1949 // to fit in 4 bits, which gives a good chance that we can store both in a
1950 // single record, and at worst we use the same number of records as the
1951 // split version.
1952 uint32_t InlinedAtUniquable =
1953 ((uint32_t)InlinedCall.InlinedAtIdx.asRaw() << 1) |
1954 InlinedCall.Uniquable;
1955 Record.push_back(InlinedAtUniquable);
1956 // Don't record MaxAtomGroup, as it is a transient field.
1957 Record.push_back(VE.getMetadataID(InlinedCall.InlineeContext));
1958 }
1959 Stream.EmitRecord(bitc::METADATA_FLMD, Record, Abbrev);
1960 Record.clear();
1961}
1962
1963unsigned ModuleBitcodeWriter::createDILocationAbbrev(bool WithIRLayers) {
1964 // Assume the column is usually under 128, and always output the inlined-at
1965 // location (it's never more expensive than building an array size 1).
1966 //
1967 // Separate abbrev so a location without layers does not spend a VBR chunk
1968 // encoding a zero; writeDILocation picks between the two per record.
1969 auto Abbv = std::make_shared<BitCodeAbbrev>();
1970 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
1971 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isDistinct
1972 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // line
1973 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // column
1974 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // scope
1975 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // inlinedAt
1976 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isImplicitCode
1977 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // atomGroup
1978 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // atomRank
1979 if (WithIRLayers)
1980 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // irlayers
1981 return Stream.EmitAbbrev(std::move(Abbv));
1982}
1983
1984void ModuleBitcodeWriter::writeDILocation(const DILocation *N,
1985 SmallVectorImpl<uint64_t> &Record,
1986 unsigned &Abbrev) {
1987 if (!Abbrev)
1988 Abbrev = createDILocationAbbrev(/*WithIRLayers=*/false);
1989
1990 Record.push_back(N->isDistinct());
1991 Record.push_back(N->getLine());
1992 Record.push_back(N->getColumn());
1993 Record.push_back(VE.getMetadataID(N->getScope()));
1994 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
1995 Record.push_back(N->isImplicitCode());
1996 Record.push_back(N->getAtomGroup());
1997 Record.push_back(N->getAtomRank());
1998
1999 unsigned AbbrevToUse = Abbrev;
2000 if (DILayerLocList *IRLayers = N->getIRLayers()) {
2001 if (!DILocationLayersAbbrev)
2002 DILocationLayersAbbrev = createDILocationAbbrev(/*WithIRLayers=*/true);
2003 AbbrevToUse = DILocationLayersAbbrev;
2004 Record.push_back(VE.getMetadataOrNullID(IRLayers));
2005 }
2006
2007 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, AbbrevToUse);
2008 Record.clear();
2009}
2010
2011void ModuleBitcodeWriter::writeDILayerLoc(const DILayerLoc *N,
2012 SmallVectorImpl<uint64_t> &Record,
2013 unsigned Abbrev) {
2014 Record.push_back(N->isDistinct());
2015 Record.push_back(N->getLine());
2016 Record.push_back(N->getColumn());
2017 Record.push_back(VE.getMetadataID(N->getRawFile()));
2018 Record.push_back(VE.getMetadataID(N->getRawKind()));
2019 Stream.EmitRecord(bitc::METADATA_LAYERLOC, Record, Abbrev);
2020 Record.clear();
2021}
2022
2023void ModuleBitcodeWriter::writeDILayerLocList(const DILayerLocList *N,
2024 SmallVectorImpl<uint64_t> &Record,
2025 unsigned Abbrev) {
2026 Record.push_back(N->isDistinct());
2027 for (const MDOperand &Op : N->layers())
2028 Record.push_back(VE.getMetadataID(Op.get()));
2029 Stream.EmitRecord(bitc::METADATA_LAYERLOCLIST, Record, Abbrev);
2030 Record.clear();
2031}
2032
2033unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
2034 // Assume the column is usually under 128, and always output the inlined-at
2035 // location (it's never more expensive than building an array size 1).
2036 auto Abbv = std::make_shared<BitCodeAbbrev>();
2037 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
2038 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
2039 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2040 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
2041 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2042 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2043 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2044 return Stream.EmitAbbrev(std::move(Abbv));
2045}
2046
2047void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N,
2048 SmallVectorImpl<uint64_t> &Record,
2049 unsigned &Abbrev) {
2050 if (!Abbrev)
2051 Abbrev = createGenericDINodeAbbrev();
2052
2053 Record.push_back(N->isDistinct());
2054 Record.push_back(N->getTag());
2055 Record.push_back(0); // Per-tag version field; unused for now.
2056
2057 for (auto &I : N->operands())
2058 Record.push_back(VE.getMetadataOrNullID(I));
2059
2060 Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
2061 Record.clear();
2062}
2063
2064void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N,
2065 SmallVectorImpl<uint64_t> &Record,
2066 unsigned Abbrev) {
2067 const uint64_t Version = 2 << 1;
2068 Record.push_back((uint64_t)N->isDistinct() | Version);
2069 Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
2070 Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
2071 Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
2072 Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
2073
2074 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
2075 Record.clear();
2076}
2077
2078void ModuleBitcodeWriter::writeDIGenericSubrange(
2079 const DIGenericSubrange *N, SmallVectorImpl<uint64_t> &Record,
2080 unsigned Abbrev) {
2081 Record.push_back((uint64_t)N->isDistinct());
2082 Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
2083 Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
2084 Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
2085 Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
2086
2087 Stream.EmitRecord(bitc::METADATA_GENERIC_SUBRANGE, Record, Abbrev);
2088 Record.clear();
2089}
2090
2091void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,
2092 SmallVectorImpl<uint64_t> &Record,
2093 unsigned Abbrev) {
2094 const uint64_t IsBigInt = 1 << 2;
2095 Record.push_back(IsBigInt | (N->isUnsigned() << 1) | N->isDistinct());
2096 Record.push_back(N->getValue().getBitWidth());
2097 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2098 emitWideAPInt(Record, N->getValue());
2099
2100 Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
2101 Record.clear();
2102}
2103
2104void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N,
2105 SmallVectorImpl<uint64_t> &Record,
2106 unsigned Abbrev) {
2107 const unsigned SizeIsMetadata = 0x2;
2108 Record.push_back(SizeIsMetadata | (unsigned)N->isDistinct());
2109 Record.push_back(N->getTag());
2110 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2111 Record.push_back(VE.getMetadataOrNullID(N->getRawSizeInBits()));
2112 Record.push_back(N->getAlignInBits());
2113 Record.push_back(N->getEncoding());
2114 Record.push_back(N->getFlags());
2115 Record.push_back(N->getNumExtraInhabitants());
2116 Record.push_back(N->getDataSizeInBits());
2117 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2118 Record.push_back(N->getLine());
2119 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2120
2121 Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
2122 Record.clear();
2123}
2124
2125void ModuleBitcodeWriter::writeDIFixedPointType(
2126 const DIFixedPointType *N, SmallVectorImpl<uint64_t> &Record,
2127 unsigned Abbrev) {
2128 const unsigned SizeIsMetadata = 0x2;
2129 Record.push_back(SizeIsMetadata | (unsigned)N->isDistinct());
2130 Record.push_back(N->getTag());
2131 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2132 Record.push_back(VE.getMetadataOrNullID(N->getRawSizeInBits()));
2133 Record.push_back(N->getAlignInBits());
2134 Record.push_back(N->getEncoding());
2135 Record.push_back(N->getFlags());
2136 Record.push_back(N->getKind());
2137 Record.push_back(N->getFactorRaw());
2138
2139 auto WriteWideInt = [&](const APInt &Value) {
2140 // Write an encoded word that holds the number of active words and
2141 // the number of bits.
2142 uint64_t NumWords = Value.getActiveWords();
2143 uint64_t Encoded = (NumWords << 32) | Value.getBitWidth();
2144 Record.push_back(Encoded);
2145 emitWideAPInt(Record, Value);
2146 };
2147
2148 WriteWideInt(N->getNumeratorRaw());
2149 WriteWideInt(N->getDenominatorRaw());
2150
2151 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2152 Record.push_back(N->getLine());
2153 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2154
2155 Stream.EmitRecord(bitc::METADATA_FIXED_POINT_TYPE, Record, Abbrev);
2156 Record.clear();
2157}
2158
2159void ModuleBitcodeWriter::writeDIStringType(const DIStringType *N,
2160 SmallVectorImpl<uint64_t> &Record,
2161 unsigned Abbrev) {
2162 const unsigned SizeIsMetadata = 0x2;
2163 Record.push_back(SizeIsMetadata | (unsigned)N->isDistinct());
2164 Record.push_back(N->getTag());
2165 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2166 Record.push_back(VE.getMetadataOrNullID(N->getStringLength()));
2167 Record.push_back(VE.getMetadataOrNullID(N->getStringLengthExp()));
2168 Record.push_back(VE.getMetadataOrNullID(N->getStringLocationExp()));
2169 Record.push_back(VE.getMetadataOrNullID(N->getRawSizeInBits()));
2170 Record.push_back(N->getAlignInBits());
2171 Record.push_back(N->getEncoding());
2172 Record.push_back(VE.getMetadataOrNullID(N->getRawCharType()));
2173
2174 Stream.EmitRecord(bitc::METADATA_STRING_TYPE, Record, Abbrev);
2175 Record.clear();
2176}
2177
2178void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,
2179 SmallVectorImpl<uint64_t> &Record,
2180 unsigned Abbrev) {
2181 const unsigned SizeIsMetadata = 0x2;
2182 Record.push_back(SizeIsMetadata | (unsigned)N->isDistinct());
2183 Record.push_back(N->getTag());
2184 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2185 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2186 Record.push_back(N->getLine());
2187 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2188 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
2189 Record.push_back(VE.getMetadataOrNullID(N->getRawSizeInBits()));
2190 Record.push_back(N->getAlignInBits());
2191 Record.push_back(VE.getMetadataOrNullID(N->getRawOffsetInBits()));
2192 Record.push_back(N->getFlags());
2193 Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
2194
2195 // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
2196 // that there is no DWARF address space associated with DIDerivedType.
2197 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
2198 Record.push_back(*DWARFAddressSpace + 1);
2199 else
2200 Record.push_back(0);
2201
2202 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2203
2204 if (auto PtrAuthData = N->getPtrAuthData())
2205 Record.push_back(PtrAuthData->RawData);
2206 else
2207 Record.push_back(0);
2208
2209 Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
2210 Record.clear();
2211}
2212
2213void ModuleBitcodeWriter::writeDISubrangeType(const DISubrangeType *N,
2214 SmallVectorImpl<uint64_t> &Record,
2215 unsigned Abbrev) {
2216 const unsigned SizeIsMetadata = 0x2;
2217 Record.push_back(SizeIsMetadata | (unsigned)N->isDistinct());
2218 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2219 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2220 Record.push_back(N->getLine());
2221 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2222 Record.push_back(VE.getMetadataOrNullID(N->getRawSizeInBits()));
2223 Record.push_back(N->getAlignInBits());
2224 Record.push_back(N->getFlags());
2225 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
2226 Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
2227 Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
2228 Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
2229 Record.push_back(VE.getMetadataOrNullID(N->getRawBias()));
2230
2231 Stream.EmitRecord(bitc::METADATA_SUBRANGE_TYPE, Record, Abbrev);
2232 Record.clear();
2233}
2234
2235void ModuleBitcodeWriter::writeDICompositeType(
2236 const DICompositeType *N, SmallVectorImpl<uint64_t> &Record,
2237 unsigned Abbrev) {
2238 const unsigned IsNotUsedInOldTypeRef = 0x2;
2239 const unsigned SizeIsMetadata = 0x4;
2240 Record.push_back(SizeIsMetadata | IsNotUsedInOldTypeRef |
2241 (unsigned)N->isDistinct());
2242 Record.push_back(N->getTag());
2243 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2244 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2245 Record.push_back(N->getLine());
2246 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2247 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
2248 Record.push_back(VE.getMetadataOrNullID(N->getRawSizeInBits()));
2249 Record.push_back(N->getAlignInBits());
2250 Record.push_back(VE.getMetadataOrNullID(N->getRawOffsetInBits()));
2251 Record.push_back(N->getFlags());
2252 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
2253 Record.push_back(N->getRuntimeLang());
2254 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
2255 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
2256 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
2257 Record.push_back(VE.getMetadataOrNullID(N->getDiscriminator()));
2258 Record.push_back(VE.getMetadataOrNullID(N->getRawDataLocation()));
2259 Record.push_back(VE.getMetadataOrNullID(N->getRawAssociated()));
2260 Record.push_back(VE.getMetadataOrNullID(N->getRawAllocated()));
2261 Record.push_back(VE.getMetadataOrNullID(N->getRawRank()));
2262 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2263 Record.push_back(N->getNumExtraInhabitants());
2264 Record.push_back(VE.getMetadataOrNullID(N->getRawSpecification()));
2265 Record.push_back(
2266 N->getEnumKind().value_or(dwarf::DW_APPLE_ENUM_KIND_invalid));
2267 Record.push_back(VE.getMetadataOrNullID(N->getRawBitStride()));
2268
2269 Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
2270 Record.clear();
2271}
2272
2273void ModuleBitcodeWriter::writeDISubroutineType(
2274 const DISubroutineType *N, SmallVectorImpl<uint64_t> &Record,
2275 unsigned Abbrev) {
2276 const unsigned HasNoOldTypeRefs = 0x2;
2277 Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
2278 Record.push_back(N->getFlags());
2279 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
2280 Record.push_back(N->getCC());
2281
2282 Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
2283 Record.clear();
2284}
2285
2286void ModuleBitcodeWriter::writeDIFile(const DIFile *N,
2287 SmallVectorImpl<uint64_t> &Record,
2288 unsigned Abbrev) {
2289 Record.push_back(N->isDistinct());
2290 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
2291 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
2292 if (N->getRawChecksum()) {
2293 Record.push_back(N->getRawChecksum()->Kind);
2294 Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()->Value));
2295 } else {
2296 // Maintain backwards compatibility with the old internal representation of
2297 // CSK_None in ChecksumKind by writing nulls here when Checksum is None.
2298 Record.push_back(0);
2299 Record.push_back(VE.getMetadataOrNullID(nullptr));
2300 }
2301 auto Source = N->getRawSource();
2302 if (Source)
2303 Record.push_back(VE.getMetadataOrNullID(Source));
2304
2305 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
2306 Record.clear();
2307}
2308
2309void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
2310 SmallVectorImpl<uint64_t> &Record,
2311 unsigned Abbrev) {
2312 assert(N->isDistinct() && "Expected distinct compile units");
2313 Record.push_back(/* IsDistinct */ true);
2314
2315 auto Lang = N->getSourceLanguage();
2316 Record.push_back(Lang.getName());
2317 // Set bit so the MetadataLoader can distniguish between versioned and
2318 // unversioned names.
2319 if (Lang.hasVersionedName())
2320 Record.back() ^= (uint64_t(1) << 63);
2321
2322 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2323 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
2324 Record.push_back(N->isOptimized());
2325 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
2326 Record.push_back(N->getRuntimeVersion());
2327 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
2328 Record.push_back(N->getEmissionKind());
2329 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
2330 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
2331 Record.push_back(/* subprograms */ 0);
2332 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
2333 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
2334 Record.push_back(N->getDWOId());
2335 Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
2336 Record.push_back(N->getSplitDebugInlining());
2337 Record.push_back(N->getDebugInfoForProfiling());
2338 Record.push_back((unsigned)N->getNameTableKind());
2339 Record.push_back(N->getRangesBaseAddress());
2340 Record.push_back(VE.getMetadataOrNullID(N->getRawSysRoot()));
2341 Record.push_back(VE.getMetadataOrNullID(N->getRawSDK()));
2342 Record.push_back(Lang.hasVersionedName() ? Lang.getVersion() : 0);
2343 Record.push_back(Lang.getDialect());
2344
2345 Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
2346 Record.clear();
2347}
2348
2349void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,
2350 SmallVectorImpl<uint64_t> &Record,
2351 unsigned Abbrev) {
2352 const uint64_t HasUnitFlag = 1 << 1;
2353 const uint64_t HasSPFlagsFlag = 1 << 2;
2354 Record.push_back(uint64_t(N->isDistinct()) | HasUnitFlag | HasSPFlagsFlag);
2355 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2356 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2357 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
2358 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2359 Record.push_back(N->getLine());
2360 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2361 Record.push_back(N->getScopeLine());
2362 Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
2363 Record.push_back(N->getSPFlags());
2364 Record.push_back(N->getVirtualIndex());
2365 Record.push_back(N->getFlags());
2366 Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
2367 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
2368 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
2369 Record.push_back(VE.getMetadataOrNullID(N->getRetainedNodes().get()));
2370 Record.push_back(N->getThisAdjustment());
2371 Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get()));
2372 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2373 Record.push_back(VE.getMetadataOrNullID(N->getRawTargetFuncName()));
2374 Record.push_back(N->getKeyInstructionsEnabled());
2375
2376 Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
2377 Record.clear();
2378}
2379
2380void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
2381 SmallVectorImpl<uint64_t> &Record,
2382 unsigned Abbrev) {
2383 Record.push_back(N->isDistinct());
2384 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2385 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2386 Record.push_back(N->getLine());
2387 Record.push_back(N->getColumn());
2388
2389 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
2390 Record.clear();
2391}
2392
2393void ModuleBitcodeWriter::writeDILexicalBlockFile(
2394 const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record,
2395 unsigned Abbrev) {
2396 Record.push_back(N->isDistinct());
2397 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2398 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2399 Record.push_back(N->getDiscriminator());
2400
2401 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
2402 Record.clear();
2403}
2404
2405void ModuleBitcodeWriter::writeDICommonBlock(const DICommonBlock *N,
2406 SmallVectorImpl<uint64_t> &Record,
2407 unsigned Abbrev) {
2408 Record.push_back(N->isDistinct());
2409 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2410 Record.push_back(VE.getMetadataOrNullID(N->getDecl()));
2411 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2412 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2413 Record.push_back(N->getLineNo());
2414
2415 Stream.EmitRecord(bitc::METADATA_COMMON_BLOCK, Record, Abbrev);
2416 Record.clear();
2417}
2418
2419void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,
2420 SmallVectorImpl<uint64_t> &Record,
2421 unsigned Abbrev) {
2422 Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
2423 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2424 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2425
2426 Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
2427 Record.clear();
2428}
2429
2430void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,
2431 SmallVectorImpl<uint64_t> &Record,
2432 unsigned Abbrev) {
2433 Record.push_back(N->isDistinct());
2434 Record.push_back(N->getMacinfoType());
2435 Record.push_back(N->getLine());
2436 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2437 Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
2438
2439 Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
2440 Record.clear();
2441}
2442
2443void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,
2444 SmallVectorImpl<uint64_t> &Record,
2445 unsigned Abbrev) {
2446 Record.push_back(N->isDistinct());
2447 Record.push_back(N->getMacinfoType());
2448 Record.push_back(N->getLine());
2449 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2450 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
2451
2452 Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
2453 Record.clear();
2454}
2455
2456void ModuleBitcodeWriter::writeDIArgList(const DIArgList *N,
2457 SmallVectorImpl<uint64_t> &Record) {
2458 Record.reserve(N->getArgs().size());
2459 for (ValueAsMetadata *MD : N->getArgs())
2460 Record.push_back(VE.getMetadataID(MD));
2461
2462 Stream.EmitRecord(bitc::METADATA_ARG_LIST, Record);
2463 Record.clear();
2464}
2465
2466void ModuleBitcodeWriter::writeDIModule(const DIModule *N,
2467 SmallVectorImpl<uint64_t> &Record,
2468 unsigned Abbrev) {
2469 Record.push_back(N->isDistinct());
2470 for (auto &I : N->operands())
2471 Record.push_back(VE.getMetadataOrNullID(I));
2472 Record.push_back(N->getLineNo());
2473 Record.push_back(N->getIsDecl());
2474
2475 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
2476 Record.clear();
2477}
2478
2479void ModuleBitcodeWriter::writeDIAssignID(const DIAssignID *N,
2480 SmallVectorImpl<uint64_t> &Record,
2481 unsigned Abbrev) {
2482 // There are no arguments for this metadata type.
2483 Record.push_back(N->isDistinct());
2484 Stream.EmitRecord(bitc::METADATA_ASSIGN_ID, Record, Abbrev);
2485 Record.clear();
2486}
2487
2488void ModuleBitcodeWriter::writeDITemplateTypeParameter(
2489 const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record,
2490 unsigned Abbrev) {
2491 Record.push_back(N->isDistinct());
2492 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2493 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2494 Record.push_back(N->isDefault());
2495
2496 Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
2497 Record.clear();
2498}
2499
2500void ModuleBitcodeWriter::writeDITemplateValueParameter(
2501 const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record,
2502 unsigned Abbrev) {
2503 Record.push_back(N->isDistinct());
2504 Record.push_back(N->getTag());
2505 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2506 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2507 Record.push_back(N->isDefault());
2508 Record.push_back(VE.getMetadataOrNullID(N->getValue()));
2509
2510 Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
2511 Record.clear();
2512}
2513
2514void ModuleBitcodeWriter::writeDIGlobalVariable(
2515 const DIGlobalVariable *N, SmallVectorImpl<uint64_t> &Record,
2516 unsigned Abbrev) {
2517 const uint64_t Version = 2 << 1;
2518 Record.push_back((uint64_t)N->isDistinct() | Version);
2519 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2520 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2521 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
2522 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2523 Record.push_back(N->getLine());
2524 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2525 Record.push_back(N->isLocalToUnit());
2526 Record.push_back(N->isDefinition());
2527 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
2528 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams()));
2529 Record.push_back(N->getAlignInBits());
2530 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2531
2532 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
2533 Record.clear();
2534}
2535
2536void ModuleBitcodeWriter::writeDILocalVariable(
2537 const DILocalVariable *N, SmallVectorImpl<uint64_t> &Record,
2538 unsigned Abbrev) {
2539 // In order to support all possible bitcode formats in BitcodeReader we need
2540 // to distinguish the following cases:
2541 // 1) Record has no artificial tag (Record[1]),
2542 // has no obsolete inlinedAt field (Record[9]).
2543 // In this case Record size will be 8, HasAlignment flag is false.
2544 // 2) Record has artificial tag (Record[1]),
2545 // has no obsolete inlignedAt field (Record[9]).
2546 // In this case Record size will be 9, HasAlignment flag is false.
2547 // 3) Record has both artificial tag (Record[1]) and
2548 // obsolete inlignedAt field (Record[9]).
2549 // In this case Record size will be 10, HasAlignment flag is false.
2550 // 4) Record has neither artificial tag, nor inlignedAt field, but
2551 // HasAlignment flag is true and Record[8] contains alignment value.
2552 const uint64_t HasAlignmentFlag = 1 << 1;
2553 Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
2554 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2555 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2556 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2557 Record.push_back(N->getLine());
2558 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2559 Record.push_back(N->getArg());
2560 Record.push_back(N->getFlags());
2561 Record.push_back(N->getAlignInBits());
2562 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2563
2564 Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
2565 Record.clear();
2566}
2567
2568void ModuleBitcodeWriter::writeDILabel(
2569 const DILabel *N, SmallVectorImpl<uint64_t> &Record,
2570 unsigned Abbrev) {
2571 uint64_t IsArtificialFlag = uint64_t(N->isArtificial()) << 1;
2572 Record.push_back((uint64_t)N->isDistinct() | IsArtificialFlag);
2573 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2574 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2575 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2576 Record.push_back(N->getLine());
2577 Record.push_back(N->getColumn());
2578 Record.push_back(N->getCoroSuspendIdx().has_value()
2579 ? (uint64_t)N->getCoroSuspendIdx().value()
2580 : std::numeric_limits<uint64_t>::max());
2581
2582 Stream.EmitRecord(bitc::METADATA_LABEL, Record, Abbrev);
2583 Record.clear();
2584}
2585
2586void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,
2587 SmallVectorImpl<uint64_t> &Record,
2588 unsigned Abbrev) {
2589 Record.reserve(N->getElements().size() + 1);
2590 const uint64_t Version = 3 << 1;
2591 Record.push_back((uint64_t)N->isDistinct() | Version);
2592 Record.append(N->elements_begin(), N->elements_end());
2593
2594 Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
2595 Record.clear();
2596}
2597
2598void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
2599 const DIGlobalVariableExpression *N, SmallVectorImpl<uint64_t> &Record,
2600 unsigned Abbrev) {
2601 Record.push_back(N->isDistinct());
2602 Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
2603 Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
2604
2605 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR, Record, Abbrev);
2606 Record.clear();
2607}
2608
2609void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
2610 SmallVectorImpl<uint64_t> &Record,
2611 unsigned Abbrev) {
2612 Record.push_back(N->isDistinct());
2613 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2614 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2615 Record.push_back(N->getLine());
2616 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
2617 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
2618 Record.push_back(N->getAttributes());
2619 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2620
2621 Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
2622 Record.clear();
2623}
2624
2625void ModuleBitcodeWriter::writeDIProperty(const DIProperty *N,
2626 SmallVectorImpl<uint64_t> &Record,
2627 unsigned Abbrev) {
2628 Record.push_back(N->isDistinct());
2629 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2630 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2631 Record.push_back(N->getLine());
2632 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2633 Record.push_back(VE.getMetadataOrNullID(N->getBackingStorage()));
2634
2635 Stream.EmitRecord(bitc::METADATA_PROPERTY, Record, Abbrev);
2636 Record.clear();
2637}
2638
2639void ModuleBitcodeWriter::writeDIImportedEntity(
2640 const DIImportedEntity *N, SmallVectorImpl<uint64_t> &Record,
2641 unsigned Abbrev) {
2642 Record.push_back(N->isDistinct());
2643 Record.push_back(N->getTag());
2644 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2645 Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
2646 Record.push_back(N->getLine());
2647 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2648 Record.push_back(VE.getMetadataOrNullID(N->getRawFile()));
2649 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
2650
2651 Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
2652 Record.clear();
2653}
2654
2655unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
2656 auto Abbv = std::make_shared<BitCodeAbbrev>();
2657 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
2658 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2659 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2660 return Stream.EmitAbbrev(std::move(Abbv));
2661}
2662
2663void ModuleBitcodeWriter::writeNamedMetadata(
2664 SmallVectorImpl<uint64_t> &Record) {
2665 if (M.named_metadata_empty())
2666 return;
2667
2668 unsigned Abbrev = createNamedMetadataAbbrev();
2669 for (const NamedMDNode &NMD : M.named_metadata()) {
2670 // Write name.
2671 StringRef Str = NMD.getName();
2672 Record.append(Str.bytes_begin(), Str.bytes_end());
2673 Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
2674 Record.clear();
2675
2676 // Write named metadata operands.
2677 for (const MDNode *N : NMD.operands())
2678 Record.push_back(VE.getMetadataID(N));
2679 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
2680 Record.clear();
2681 }
2682}
2683
2684unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
2685 auto Abbv = std::make_shared<BitCodeAbbrev>();
2686 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS));
2687 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
2688 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
2689 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2690 return Stream.EmitAbbrev(std::move(Abbv));
2691}
2692
2693/// Write out a record for MDString.
2694///
2695/// All the metadata strings in a metadata block are emitted in a single
2696/// record. The sizes and strings themselves are shoved into a blob.
2697void ModuleBitcodeWriter::writeMetadataStrings(
2698 ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) {
2699 if (Strings.empty())
2700 return;
2701
2702 // Start the record with the number of strings.
2703 Record.push_back(bitc::METADATA_STRINGS);
2704 Record.push_back(Strings.size());
2705
2706 // Emit the sizes of the strings in the blob.
2707 SmallString<256> Blob;
2708 {
2709 BitstreamWriter W(Blob);
2710 for (const Metadata *MD : Strings)
2711 W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
2712 W.FlushToWord();
2713 }
2714
2715 // Add the offset to the strings to the record.
2716 Record.push_back(Blob.size());
2717
2718 // Add the strings to the blob.
2719 for (const Metadata *MD : Strings)
2720 Blob.append(cast<MDString>(MD)->getString());
2721
2722 // Emit the final record.
2723 Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
2724 Record.clear();
2725}
2726
2727// Generates an enum to use as an index in the Abbrev array of Metadata record.
2728enum MetadataAbbrev : unsigned {
2729#define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
2730#include "llvm/IR/Metadata.def"
2732};
2733
2734void ModuleBitcodeWriter::writeMetadataRecords(
2735 ArrayRef<const Metadata *> MDs, SmallVectorImpl<uint64_t> &Record,
2736 std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
2737 if (MDs.empty())
2738 return;
2739
2740 // Initialize MDNode abbreviations.
2741#define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
2742#include "llvm/IR/Metadata.def"
2743
2744 for (const Metadata *MD : MDs) {
2745 if (IndexPos)
2746 IndexPos->push_back(Stream.GetCurrentBitNo());
2747 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
2748 assert(N->isResolved() && "Expected forward references to be resolved");
2749
2750 switch (N->getMetadataID()) {
2751 default:
2752 llvm_unreachable("Invalid MDNode subclass");
2753#define HANDLE_MDNODE_LEAF(CLASS) \
2754 case Metadata::CLASS##Kind: \
2755 if (MDAbbrevs) \
2756 write##CLASS(cast<CLASS>(N), Record, \
2757 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
2758 else \
2759 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
2760 continue;
2761#include "llvm/IR/Metadata.def"
2762 }
2763 }
2764 if (auto *AL = dyn_cast<DIArgList>(MD)) {
2766 continue;
2767 }
2768 writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
2769 }
2770}
2771
2772void ModuleBitcodeWriter::writeModuleMetadata() {
2773 if (!VE.hasMDs() && M.named_metadata_empty())
2774 return;
2775
2777 SmallVector<uint64_t, 64> Record;
2778
2779 // Emit all abbrevs upfront, so that the reader can jump in the middle of the
2780 // block and load any metadata.
2781 std::vector<unsigned> MDAbbrevs;
2782
2783 MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
2784 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] =
2785 createDILocationAbbrev(/*WithIRLayers=*/false);
2786 DILocationLayersAbbrev = createDILocationAbbrev(/*WithIRLayers=*/true);
2787 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
2788 createGenericDINodeAbbrev();
2789
2790 auto Abbv = std::make_shared<BitCodeAbbrev>();
2791 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX_OFFSET));
2792 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2793 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2794 unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2795
2796 Abbv = std::make_shared<BitCodeAbbrev>();
2797 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX));
2798 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2799 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2800 unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2801
2802 // Emit MDStrings together upfront.
2803 writeMetadataStrings(VE.getMDStrings(), Record);
2804
2805 // We only emit an index for the metadata record if we have more than a given
2806 // (naive) threshold of metadatas, otherwise it is not worth it.
2807 if (VE.getNonMDStrings().size() > Opts.bitcode_mdindex_threshold) {
2808 // Write a placeholder value in for the offset of the metadata index,
2809 // which is written after the records, so that it can include
2810 // the offset of each entry. The placeholder offset will be
2811 // updated after all records are emitted.
2812 uint64_t Vals[] = {0, 0};
2813 Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
2814 }
2815
2816 // Compute and save the bit offset to the current position, which will be
2817 // patched when we emit the index later. We can simply subtract the 64-bit
2818 // fixed size from the current bit number to get the location to backpatch.
2819 uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
2820
2821 // This index will contain the bitpos for each individual record.
2822 std::vector<uint64_t> IndexPos;
2823 IndexPos.reserve(VE.getNonMDStrings().size());
2824
2825 // Write all the records
2826 writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
2827
2828 if (VE.getNonMDStrings().size() > Opts.bitcode_mdindex_threshold) {
2829 // Now that we have emitted all the records we will emit the index. But
2830 // first
2831 // backpatch the forward reference so that the reader can skip the records
2832 // efficiently.
2833 Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
2834 Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
2835
2836 // Delta encode the index.
2837 uint64_t PreviousValue = IndexOffsetRecordBitPos;
2838 for (auto &Elt : IndexPos) {
2839 auto EltDelta = Elt - PreviousValue;
2840 PreviousValue = Elt;
2841 Elt = EltDelta;
2842 }
2843 // Emit the index record.
2844 Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
2845 IndexPos.clear();
2846 }
2847
2848 // Write the named metadata now.
2849 writeNamedMetadata(Record);
2850
2851 auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
2852 SmallVector<uint64_t, 4> Record;
2853 Record.push_back(VE.getValueID(&GO));
2854 pushGlobalMetadataAttachment(Record, GO);
2856 };
2857 for (const Function &F : M)
2858 if (F.isDeclaration() && F.hasMetadata())
2859 AddDeclAttachedMetadata(F);
2860 for (const GlobalIFunc &GI : M.ifuncs())
2861 if (GI.hasMetadata())
2862 AddDeclAttachedMetadata(GI);
2863 // FIXME: Only store metadata for declarations here, and move data for global
2864 // variable definitions to a separate block (PR28134).
2865 for (const GlobalVariable &GV : M.globals())
2866 if (GV.hasMetadata())
2867 AddDeclAttachedMetadata(GV);
2868
2869 Stream.ExitBlock();
2870}
2871
2872void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
2873 if (!VE.hasMDs())
2874 return;
2875
2877 // New block, new abbrev id space. Unlike the module block this one is not
2878 // randomly accessed, so the irlayers abbrev can be created on first use.
2879 DILocationLayersAbbrev = 0;
2880 SmallVector<uint64_t, 64> Record;
2881 writeMetadataStrings(VE.getMDStrings(), Record);
2882 writeMetadataRecords(VE.getNonMDStrings(), Record);
2883 Stream.ExitBlock();
2884}
2885
2886void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
2887 SmallVectorImpl<uint64_t> &Record, const GlobalObject &GO) {
2888 // [n x [id, mdnode]]
2890 GO.getAllMetadata(MDs);
2891 for (const auto &I : MDs) {
2892 Record.push_back(I.first);
2893 Record.push_back(VE.getMetadataID(I.second));
2894 }
2895}
2896
2897void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
2899
2900 SmallVector<uint64_t, 64> Record;
2901
2902 if (F.hasMetadata()) {
2903 pushGlobalMetadataAttachment(Record, F);
2904 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
2905 Record.clear();
2906 }
2907
2908 // Write metadata attachments
2909 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
2911 for (const BasicBlock &BB : F)
2912 for (const Instruction &I : BB) {
2913 MDs.clear();
2914 I.getAllMetadataOtherThanDebugLoc(MDs);
2915
2916 // If no metadata, ignore instruction.
2917 if (MDs.empty()) continue;
2918
2919 Record.push_back(VE.getInstructionID(&I));
2920
2921 for (const auto &[ID, MD] : MDs) {
2922 Record.push_back(ID);
2923 Record.push_back(VE.getMetadataID(MD));
2924 }
2925 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
2926 Record.clear();
2927 }
2928
2929 Stream.ExitBlock();
2930}
2931
2932void ModuleBitcodeWriter::writeModuleMetadataKinds() {
2933 SmallVector<uint64_t, 64> Record;
2934
2935 // Write metadata kinds
2936 // METADATA_KIND - [n x [id, name]]
2938 M.getMDKindNames(Names);
2939
2940 if (Names.empty()) return;
2941
2943
2944 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
2945 Record.push_back(MDKindID);
2946 StringRef KName = Names[MDKindID];
2947 Record.append(KName.begin(), KName.end());
2948
2949 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
2950 Record.clear();
2951 }
2952
2953 Stream.ExitBlock();
2954}
2955
2956void ModuleBitcodeWriter::writeOperandBundleTags() {
2957 // Write metadata kinds
2958 //
2959 // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
2960 //
2961 // OPERAND_BUNDLE_TAG - [strchr x N]
2962
2964 M.getOperandBundleTags(Tags);
2965
2966 if (Tags.empty())
2967 return;
2968
2970
2971 SmallVector<uint64_t, 64> Record;
2972
2973 for (auto Tag : Tags) {
2974 Record.append(Tag.begin(), Tag.end());
2975
2976 Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
2977 Record.clear();
2978 }
2979
2980 Stream.ExitBlock();
2981}
2982
2983void ModuleBitcodeWriter::writeSyncScopeNames() {
2985 M.getContext().getSyncScopeNames(SSNs);
2986 if (SSNs.empty())
2987 return;
2988
2990
2991 SmallVector<uint64_t, 64> Record;
2992 for (auto SSN : SSNs) {
2993 Record.append(SSN.begin(), SSN.end());
2994 Stream.EmitRecord(bitc::SYNC_SCOPE_NAME, Record, 0);
2995 Record.clear();
2996 }
2997
2998 Stream.ExitBlock();
2999}
3000
3001void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
3002 bool isGlobal) {
3003 if (FirstVal == LastVal) return;
3004
3006
3007 unsigned AggregateAbbrev = 0;
3008 unsigned String8Abbrev = 0;
3009 unsigned CString7Abbrev = 0;
3010 unsigned CString6Abbrev = 0;
3011 // If this is a constant pool for the module, emit module-specific abbrevs.
3012 if (isGlobal) {
3013 // Abbrev for CST_CODE_AGGREGATE.
3014 auto Abbv = std::make_shared<BitCodeAbbrev>();
3015 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
3016 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3017 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
3018 AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3019
3020 // Abbrev for CST_CODE_STRING.
3021 Abbv = std::make_shared<BitCodeAbbrev>();
3022 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
3023 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3024 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
3025 String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
3026 // Abbrev for CST_CODE_CSTRING.
3027 Abbv = std::make_shared<BitCodeAbbrev>();
3028 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
3029 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3030 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
3031 CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
3032 // Abbrev for CST_CODE_CSTRING.
3033 Abbv = std::make_shared<BitCodeAbbrev>();
3034 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
3035 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3036 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3037 CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
3038 }
3039
3040 SmallVector<uint64_t, 64> Record;
3041
3042 const ValueEnumerator::ValueList &Vals = VE.getValues();
3043 Type *LastTy = nullptr;
3044 for (unsigned i = FirstVal; i != LastVal; ++i) {
3045 const Value *V = Vals[i].first;
3046 // If we need to switch types, do so now.
3047 if (V->getType() != LastTy) {
3048 LastTy = V->getType();
3049 Record.push_back(VE.getTypeID(LastTy));
3050 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
3051 CONSTANTS_SETTYPE_ABBREV);
3052 Record.clear();
3053 }
3054
3055 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
3056 Record.push_back(VE.getTypeID(IA->getFunctionType()));
3057 Record.push_back(
3058 unsigned(IA->hasSideEffects()) | unsigned(IA->isAlignStack()) << 1 |
3059 unsigned(IA->getDialect() & 1) << 2 | unsigned(IA->canThrow()) << 3);
3060
3061 // Add the asm string.
3062 StringRef AsmStr = IA->getAsmString();
3063 Record.push_back(AsmStr.size());
3064 Record.append(AsmStr.begin(), AsmStr.end());
3065
3066 // Add the constraint string.
3067 StringRef ConstraintStr = IA->getConstraintString();
3068 Record.push_back(ConstraintStr.size());
3069 Record.append(ConstraintStr.begin(), ConstraintStr.end());
3070 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
3071 Record.clear();
3072 continue;
3073 }
3074 const Constant *C = cast<Constant>(V);
3075 unsigned Code = -1U;
3076 unsigned AbbrevToUse = 0;
3077 if (C->isNullValue()) {
3079 } else if (isa<PoisonValue>(C)) {
3081 } else if (isa<UndefValue>(C)) {
3083 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
3084 if (IV->getBitWidth() <= 64) {
3085 uint64_t V = IV->getSExtValue();
3086 emitSignedInt64(Record, V);
3088 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
3089 } else { // Wide integers, > 64 bits in size.
3090 emitWideAPInt(Record, IV->getValue());
3092 }
3093 } else if (const ConstantByte *BV = dyn_cast<ConstantByte>(C)) {
3094 if (BV->getBitWidth() <= 64) {
3095 uint64_t V = BV->getSExtValue();
3096 emitSignedInt64(Record, V);
3098 AbbrevToUse = CONSTANTS_BYTE_ABBREV;
3099 } else { // Wide bytes, > 64 bits in size.
3100 emitWideAPInt(Record, BV->getValue());
3102 }
3103 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3105 Type *Ty = CFP->getType()->getScalarType();
3106 if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() ||
3107 Ty->isDoubleTy()) {
3108 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
3109 } else if (Ty->isX86_FP80Ty()) {
3110 // api needed to prevent premature destruction
3111 // bits are not in the same order as a normal i80 APInt, compensate.
3112 APInt api = CFP->getValueAPF().bitcastToAPInt();
3113 const uint64_t *p = api.getRawData();
3114 Record.push_back((p[1] << 48) | (p[0] >> 16));
3115 Record.push_back(p[0] & 0xffffLL);
3116 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
3117 APInt api = CFP->getValueAPF().bitcastToAPInt();
3118 const uint64_t *p = api.getRawData();
3119 Record.push_back(p[0]);
3120 Record.push_back(p[1]);
3121 } else {
3122 assert(0 && "Unknown FP type!");
3123 }
3124 } else if (isa<ConstantDataSequential>(C) &&
3125 cast<ConstantDataSequential>(C)->isString()) {
3126 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
3127 // Emit constant strings specially.
3128 uint64_t NumElts = Str->getNumElements();
3129 // If this is a null-terminated string, use the denser CSTRING encoding.
3130 if (Str->isCString()) {
3132 --NumElts; // Don't encode the null, which isn't allowed by char6.
3133 } else {
3135 AbbrevToUse = String8Abbrev;
3136 }
3137 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
3138 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
3139 for (uint64_t i = 0; i != NumElts; ++i) {
3140 unsigned char V = Str->getElementAsInteger(i);
3141 Record.push_back(V);
3142 isCStr7 &= (V & 128) == 0;
3143 if (isCStrChar6)
3144 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
3145 }
3146
3147 if (isCStrChar6)
3148 AbbrevToUse = CString6Abbrev;
3149 else if (isCStr7)
3150 AbbrevToUse = CString7Abbrev;
3151 } else if (const ConstantDataSequential *CDS =
3154 Type *EltTy = CDS->getElementType();
3155 if (isa<IntegerType>(EltTy) || isa<ByteType>(EltTy)) {
3156 for (uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i)
3157 Record.push_back(CDS->getElementAsInteger(i));
3158 } else {
3159 for (uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i)
3160 Record.push_back(
3161 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
3162 }
3163 } else if (isa<ConstantAggregate>(C)) {
3165 for (const Value *Op : C->operands())
3166 Record.push_back(VE.getValueID(Op));
3167 AbbrevToUse = AggregateAbbrev;
3168 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
3169 switch (CE->getOpcode()) {
3170 default:
3171 if (Instruction::isCast(CE->getOpcode())) {
3173 Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
3174 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
3175 Record.push_back(VE.getValueID(C->getOperand(0)));
3176 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
3177 } else {
3178 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
3180 Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
3181 Record.push_back(VE.getValueID(C->getOperand(0)));
3182 Record.push_back(VE.getValueID(C->getOperand(1)));
3184 if (Flags != 0)
3185 Record.push_back(Flags);
3186 }
3187 break;
3188 case Instruction::GetElementPtr: {
3190 const auto *GO = cast<GEPOperator>(C);
3191 Record.push_back(VE.getTypeID(GO->getSourceElementType()));
3192 Record.push_back(getOptimizationFlags(GO));
3193 if (std::optional<ConstantRange> Range = GO->getInRange()) {
3195 emitConstantRange(Record, *Range, /*EmitBitWidth=*/true);
3196 }
3197 for (const Value *Op : CE->operands()) {
3198 Record.push_back(VE.getTypeID(Op->getType()));
3199 Record.push_back(VE.getValueID(Op));
3200 }
3201 break;
3202 }
3203 case Instruction::ExtractElement:
3205 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
3206 Record.push_back(VE.getValueID(C->getOperand(0)));
3207 Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
3208 Record.push_back(VE.getValueID(C->getOperand(1)));
3209 break;
3210 case Instruction::InsertElement:
3212 Record.push_back(VE.getValueID(C->getOperand(0)));
3213 Record.push_back(VE.getValueID(C->getOperand(1)));
3214 Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
3215 Record.push_back(VE.getValueID(C->getOperand(2)));
3216 break;
3217 case Instruction::ShuffleVector:
3218 // If the return type and argument types are the same, this is a
3219 // standard shufflevector instruction. If the types are different,
3220 // then the shuffle is widening or truncating the input vectors, and
3221 // the argument type must also be encoded.
3222 if (C->getType() == C->getOperand(0)->getType()) {
3224 } else {
3226 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
3227 }
3228 Record.push_back(VE.getValueID(C->getOperand(0)));
3229 Record.push_back(VE.getValueID(C->getOperand(1)));
3230 Record.push_back(VE.getValueID(CE->getShuffleMaskForBitcode()));
3231 break;
3232 }
3233 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
3235 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
3236 Record.push_back(VE.getValueID(BA->getFunction()));
3237 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
3238 } else if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) {
3240 Record.push_back(VE.getTypeID(Equiv->getGlobalValue()->getType()));
3241 Record.push_back(VE.getValueID(Equiv->getGlobalValue()));
3242 } else if (const auto *NC = dyn_cast<NoCFIValue>(C)) {
3244 Record.push_back(VE.getTypeID(NC->getGlobalValue()->getType()));
3245 Record.push_back(VE.getValueID(NC->getGlobalValue()));
3246 } else if (const auto *CPA = dyn_cast<ConstantPtrAuth>(C)) {
3248 Record.push_back(VE.getValueID(CPA->getPointer()));
3249 Record.push_back(VE.getValueID(CPA->getKey()));
3250 Record.push_back(VE.getValueID(CPA->getDiscriminator()));
3251 Record.push_back(VE.getValueID(CPA->getAddrDiscriminator()));
3252 Record.push_back(VE.getValueID(CPA->getDeactivationSymbol()));
3253 } else {
3254#ifndef NDEBUG
3255 C->dump();
3256#endif
3257 llvm_unreachable("Unknown constant!");
3258 }
3259 Stream.EmitRecord(Code, Record, AbbrevToUse);
3260 Record.clear();
3261 }
3262
3263 Stream.ExitBlock();
3264}
3265
3266void ModuleBitcodeWriter::writeModuleConstants() {
3267 const ValueEnumerator::ValueList &Vals = VE.getValues();
3268
3269 // Find the first constant to emit, which is the first non-globalvalue value.
3270 // We know globalvalues have been emitted by WriteModuleInfo.
3271 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
3272 if (!isa<GlobalValue>(Vals[i].first)) {
3273 writeConstants(i, Vals.size(), true);
3274 return;
3275 }
3276 }
3277}
3278
3279/// pushValueAndType - The file has to encode both the value and type id for
3280/// many values, because we need to know what type to create for forward
3281/// references. However, most operands are not forward references, so this type
3282/// field is not needed.
3283///
3284/// This function adds V's value ID to Vals. If the value ID is higher than the
3285/// instruction ID, then it is a forward reference, and it also includes the
3286/// type ID. The value ID that is written is encoded relative to the InstID.
3287bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
3288 SmallVectorImpl<unsigned> &Vals) {
3289 unsigned ValID = VE.getValueID(V);
3290 // Make encoding relative to the InstID.
3291 Vals.push_back(InstID - ValID);
3292 if (ValID >= InstID) {
3293 Vals.push_back(VE.getTypeID(V->getType()));
3294 return true;
3295 }
3296 return false;
3297}
3298
3299bool ModuleBitcodeWriter::pushValueOrMetadata(const Value *V, unsigned InstID,
3300 SmallVectorImpl<unsigned> &Vals) {
3301 bool IsMetadata = V->getType()->isMetadataTy();
3302 if (IsMetadata) {
3304 Metadata *MD = cast<MetadataAsValue>(V)->getMetadata();
3305 unsigned ValID = VE.getMetadataID(MD);
3306 Vals.push_back(InstID - ValID);
3307 return false;
3308 }
3309 return pushValueAndType(V, InstID, Vals);
3310}
3311
3312void ModuleBitcodeWriter::writeOperandBundles(const CallBase &CS,
3313 unsigned InstID) {
3315 LLVMContext &C = CS.getContext();
3316
3317 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
3318 const auto &Bundle = CS.getOperandBundleAt(i);
3319 Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
3320
3321 for (auto &Input : Bundle.Inputs)
3322 pushValueOrMetadata(Input, InstID, Record);
3323
3325 Record.clear();
3326 }
3327}
3328
3329/// pushValue - Like pushValueAndType, but where the type of the value is
3330/// omitted (perhaps it was already encoded in an earlier operand).
3331void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
3332 SmallVectorImpl<unsigned> &Vals) {
3333 unsigned ValID = VE.getValueID(V);
3334 Vals.push_back(InstID - ValID);
3335}
3336
3337void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
3338 SmallVectorImpl<uint64_t> &Vals) {
3339 unsigned ValID = VE.getValueID(V);
3340 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
3341 emitSignedInt64(Vals, diff);
3342}
3343
3344/// WriteInstruction - Emit an instruction to the specified stream.
3345void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
3346 unsigned InstID,
3347 SmallVectorImpl<unsigned> &Vals) {
3348 unsigned Code = 0;
3349 unsigned AbbrevToUse = 0;
3350 VE.setInstructionID(&I);
3351 switch (I.getOpcode()) {
3352 default:
3353 if (Instruction::isCast(I.getOpcode())) {
3355 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
3356 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
3357 Vals.push_back(VE.getTypeID(I.getType()));
3358 Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
3360 if (Flags != 0) {
3361 if (AbbrevToUse == FUNCTION_INST_CAST_ABBREV)
3362 AbbrevToUse = FUNCTION_INST_CAST_FLAGS_ABBREV;
3363 Vals.push_back(Flags);
3364 }
3365 } else {
3366 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
3368 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
3369 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
3370 pushValue(I.getOperand(1), InstID, Vals);
3371 Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
3373 if (Flags != 0) {
3374 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
3375 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
3376 Vals.push_back(Flags);
3377 }
3378 }
3379 break;
3380 case Instruction::FNeg: {
3382 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
3383 AbbrevToUse = FUNCTION_INST_UNOP_ABBREV;
3384 Vals.push_back(getEncodedUnaryOpcode(I.getOpcode()));
3386 if (Flags != 0) {
3387 if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV)
3388 AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV;
3389 Vals.push_back(Flags);
3390 }
3391 break;
3392 }
3393 case Instruction::GetElementPtr: {
3395 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
3396 auto &GEPInst = cast<GetElementPtrInst>(I);
3398 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
3399 for (const Value *Op : I.operands())
3400 pushValueAndType(Op, InstID, Vals);
3401 break;
3402 }
3403 case Instruction::ExtractValue: {
3405 pushValueAndType(I.getOperand(0), InstID, Vals);
3406 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
3407 Vals.append(EVI->idx_begin(), EVI->idx_end());
3408 break;
3409 }
3410 case Instruction::InsertValue: {
3412 pushValueAndType(I.getOperand(0), InstID, Vals);
3413 pushValueAndType(I.getOperand(1), InstID, Vals);
3414 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
3415 Vals.append(IVI->idx_begin(), IVI->idx_end());
3416 break;
3417 }
3418 case Instruction::Select: {
3420 pushValueAndType(I.getOperand(1), InstID, Vals);
3421 pushValue(I.getOperand(2), InstID, Vals);
3422 pushValueAndType(I.getOperand(0), InstID, Vals);
3424 if (Flags != 0)
3425 Vals.push_back(Flags);
3426 break;
3427 }
3428 case Instruction::ExtractElement:
3430 pushValueAndType(I.getOperand(0), InstID, Vals);
3431 pushValueAndType(I.getOperand(1), InstID, Vals);
3432 break;
3433 case Instruction::InsertElement:
3435 pushValueAndType(I.getOperand(0), InstID, Vals);
3436 pushValue(I.getOperand(1), InstID, Vals);
3437 pushValueAndType(I.getOperand(2), InstID, Vals);
3438 break;
3439 case Instruction::BitExtract:
3441 Vals.push_back(VE.getTypeID(I.getType()));
3442 pushValueAndType(I.getOperand(0), InstID, Vals);
3443 pushValueAndType(I.getOperand(1), InstID, Vals);
3444 break;
3445 case Instruction::BitInsert:
3447 pushValueAndType(I.getOperand(0), InstID, Vals);
3448 pushValueAndType(I.getOperand(1), InstID, Vals);
3449 pushValueAndType(I.getOperand(2), InstID, Vals);
3450 break;
3451 case Instruction::ShuffleVector:
3453 pushValueAndType(I.getOperand(0), InstID, Vals);
3454 pushValue(I.getOperand(1), InstID, Vals);
3455 pushValue(cast<ShuffleVectorInst>(I).getShuffleMaskForBitcode(), InstID,
3456 Vals);
3457 break;
3458 case Instruction::ICmp:
3459 case Instruction::FCmp: {
3460 // compare returning Int1Ty or vector of Int1Ty
3462 AbbrevToUse = FUNCTION_INST_CMP_ABBREV;
3463 if (pushValueAndType(I.getOperand(0), InstID, Vals))
3464 AbbrevToUse = 0;
3465 pushValue(I.getOperand(1), InstID, Vals);
3468 if (Flags != 0) {
3469 Vals.push_back(Flags);
3470 if (AbbrevToUse)
3471 AbbrevToUse = FUNCTION_INST_CMP_FLAGS_ABBREV;
3472 }
3473 break;
3474 }
3475
3476 case Instruction::Ret:
3477 {
3479 unsigned NumOperands = I.getNumOperands();
3480 if (NumOperands == 0)
3481 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
3482 else if (NumOperands == 1) {
3483 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
3484 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
3485 } else {
3486 for (const Value *Op : I.operands())
3487 pushValueAndType(Op, InstID, Vals);
3488 }
3489 }
3490 break;
3491 case Instruction::UncondBr: {
3493 AbbrevToUse = FUNCTION_INST_BR_UNCOND_ABBREV;
3494 const UncondBrInst &II = cast<UncondBrInst>(I);
3495 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
3496 } break;
3497 case Instruction::CondBr: {
3499 AbbrevToUse = FUNCTION_INST_BR_COND_ABBREV;
3500 const CondBrInst &II = cast<CondBrInst>(I);
3501 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
3502 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
3503 pushValue(II.getCondition(), InstID, Vals);
3504 } break;
3505 case Instruction::Switch:
3506 {
3508 const SwitchInst &SI = cast<SwitchInst>(I);
3509 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
3510 pushValue(SI.getCondition(), InstID, Vals);
3511 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
3512 for (auto Case : SI.cases()) {
3513 Vals.push_back(VE.getValueID(Case.getCaseValue()));
3514 Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
3515 }
3516 }
3517 break;
3518 case Instruction::IndirectBr:
3520 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
3521 // Encode the address operand as relative, but not the basic blocks.
3522 pushValue(I.getOperand(0), InstID, Vals);
3523 for (const Value *Op : drop_begin(I.operands()))
3524 Vals.push_back(VE.getValueID(Op));
3525 break;
3526
3527 case Instruction::Invoke: {
3528 const InvokeInst *II = cast<InvokeInst>(&I);
3529 const Value *Callee = II->getCalledOperand();
3530 FunctionType *FTy = II->getFunctionType();
3531
3532 if (II->hasOperandBundles())
3533 writeOperandBundles(*II, InstID);
3534
3536
3537 Vals.push_back(VE.getAttributeListID(II->getAttributes()));
3538 Vals.push_back(II->getCallingConv() | 1 << 13);
3539 Vals.push_back(VE.getValueID(II->getNormalDest()));
3540 Vals.push_back(VE.getValueID(II->getUnwindDest()));
3541 Vals.push_back(VE.getTypeID(FTy));
3542 pushValueAndType(Callee, InstID, Vals);
3543
3544 // Emit value #'s for the fixed parameters.
3545 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3546 pushValue(I.getOperand(i), InstID, Vals); // fixed param.
3547
3548 // Emit type/value pairs for varargs params.
3549 if (FTy->isVarArg()) {
3550 for (unsigned i = FTy->getNumParams(), e = II->arg_size(); i != e; ++i)
3551 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
3552 }
3553 break;
3554 }
3555 case Instruction::Resume:
3557 pushValueAndType(I.getOperand(0), InstID, Vals);
3558 break;
3559 case Instruction::CleanupRet: {
3561 const auto &CRI = cast<CleanupReturnInst>(I);
3562 pushValue(CRI.getCleanupPad(), InstID, Vals);
3563 if (CRI.hasUnwindDest())
3564 Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
3565 break;
3566 }
3567 case Instruction::CatchRet: {
3569 const auto &CRI = cast<CatchReturnInst>(I);
3570 pushValue(CRI.getCatchPad(), InstID, Vals);
3571 Vals.push_back(VE.getValueID(CRI.getSuccessor()));
3572 break;
3573 }
3574 case Instruction::CleanupPad:
3575 case Instruction::CatchPad: {
3576 const auto &FuncletPad = cast<FuncletPadInst>(I);
3579 pushValue(FuncletPad.getParentPad(), InstID, Vals);
3580
3581 unsigned NumArgOperands = FuncletPad.arg_size();
3582 Vals.push_back(NumArgOperands);
3583 for (unsigned Op = 0; Op != NumArgOperands; ++Op)
3584 pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
3585 break;
3586 }
3587 case Instruction::CatchSwitch: {
3589 const auto &CatchSwitch = cast<CatchSwitchInst>(I);
3590
3591 pushValue(CatchSwitch.getParentPad(), InstID, Vals);
3592
3593 unsigned NumHandlers = CatchSwitch.getNumHandlers();
3594 Vals.push_back(NumHandlers);
3595 for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
3596 Vals.push_back(VE.getValueID(CatchPadBB));
3597
3598 if (CatchSwitch.hasUnwindDest())
3599 Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
3600 break;
3601 }
3602 case Instruction::CallBr: {
3603 const CallBrInst *CBI = cast<CallBrInst>(&I);
3604 const Value *Callee = CBI->getCalledOperand();
3605 FunctionType *FTy = CBI->getFunctionType();
3606
3607 if (CBI->hasOperandBundles())
3608 writeOperandBundles(*CBI, InstID);
3609
3611
3613
3616
3617 Vals.push_back(VE.getValueID(CBI->getDefaultDest()));
3618 Vals.push_back(CBI->getNumIndirectDests());
3619 for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i)
3620 Vals.push_back(VE.getValueID(CBI->getIndirectDest(i)));
3621
3622 Vals.push_back(VE.getTypeID(FTy));
3623 pushValueAndType(Callee, InstID, Vals);
3624
3625 // Emit value #'s for the fixed parameters.
3626 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3627 pushValue(I.getOperand(i), InstID, Vals); // fixed param.
3628
3629 // Emit type/value pairs for varargs params.
3630 if (FTy->isVarArg()) {
3631 for (unsigned i = FTy->getNumParams(), e = CBI->arg_size(); i != e; ++i)
3632 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
3633 }
3634 break;
3635 }
3636 case Instruction::Unreachable:
3638 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
3639 break;
3640
3641 case Instruction::PHI: {
3642 const PHINode &PN = cast<PHINode>(I);
3644 // With the newer instruction encoding, forward references could give
3645 // negative valued IDs. This is most common for PHIs, so we use
3646 // signed VBRs.
3648 Vals64.push_back(VE.getTypeID(PN.getType()));
3649 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
3650 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
3651 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
3652 }
3653
3655 if (Flags != 0)
3656 Vals64.push_back(Flags);
3657
3658 // Emit a Vals64 vector and exit.
3659 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
3660 Vals64.clear();
3661 return;
3662 }
3663
3664 case Instruction::LandingPad: {
3665 const LandingPadInst &LP = cast<LandingPadInst>(I);
3667 Vals.push_back(VE.getTypeID(LP.getType()));
3668 Vals.push_back(LP.isCleanup());
3669 Vals.push_back(LP.getNumClauses());
3670 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
3671 if (LP.isCatch(I))
3673 else
3675 pushValueAndType(LP.getClause(I), InstID, Vals);
3676 }
3677 break;
3678 }
3679
3680 case Instruction::Alloca: {
3682 const AllocaInst &AI = cast<AllocaInst>(I);
3683 Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
3684 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
3685 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
3686 using APV = AllocaPackedValues;
3687 unsigned Record = 0;
3688 unsigned EncodedAlign = getEncodedAlign(AI.getAlign());
3690 Record, EncodedAlign & ((1 << APV::AlignLower::Bits) - 1));
3692 EncodedAlign >> APV::AlignLower::Bits);
3696 Vals.push_back(Record);
3697
3698 unsigned AS = AI.getAddressSpace();
3699 if (AS != M.getDataLayout().getAllocaAddrSpace())
3700 Vals.push_back(AS);
3701 break;
3702 }
3703
3704 case Instruction::Load: {
3705 const auto &LI = cast<LoadInst>(I);
3706 if (LI.isAtomic()) {
3708 pushValueAndType(LI.getOperand(0), InstID, Vals);
3709 } else {
3711 if (!pushValueAndType(LI.getOperand(0), InstID, Vals)) // ptr
3712 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
3713 }
3714 Vals.push_back(VE.getTypeID(LI.getType()));
3715 Vals.push_back(getEncodedAlign(LI.getAlign()));
3716 Vals.push_back(LI.isVolatile());
3717 if (LI.isAtomic()) {
3718 Vals.push_back(getEncodedOrdering(LI.getOrdering()));
3719 Vals.push_back(getEncodedSyncScopeID(LI.getSyncScopeID()));
3720 if (LI.isElementwise())
3721 Vals.push_back(1);
3722 }
3723 break;
3724 }
3725
3726 case Instruction::Store: {
3727 const auto &SI = cast<StoreInst>(I);
3728 if (SI.isAtomic()) {
3730 } else {
3732 AbbrevToUse = FUNCTION_INST_STORE_ABBREV;
3733 }
3734 if (pushValueAndType(I.getOperand(1), InstID, Vals)) // ptrty + ptr
3735 AbbrevToUse = 0;
3736 if (pushValueAndType(I.getOperand(0), InstID, Vals)) // valty + val
3737 AbbrevToUse = 0;
3738 Vals.push_back(getEncodedAlign(SI.getAlign()));
3739 Vals.push_back(SI.isVolatile());
3740 if (SI.isAtomic()) {
3741 Vals.push_back(getEncodedOrdering(SI.getOrdering()));
3742 Vals.push_back(getEncodedSyncScopeID(SI.getSyncScopeID()));
3743 if (SI.isElementwise())
3744 Vals.push_back(1);
3745 }
3746 break;
3747 }
3748
3749 case Instruction::AtomicCmpXchg:
3751 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
3752 pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
3753 pushValue(I.getOperand(2), InstID, Vals); // newval.
3754 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
3755 Vals.push_back(
3756 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
3757 Vals.push_back(
3758 getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID()));
3759 Vals.push_back(
3760 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
3761 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
3762 Vals.push_back(getEncodedAlign(cast<AtomicCmpXchgInst>(I).getAlign()));
3763 break;
3764 case Instruction::AtomicRMW:
3766 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
3767 pushValueAndType(I.getOperand(1), InstID, Vals); // valty + val
3769 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
3770 Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
3771 Vals.push_back(
3772 getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID()));
3773 Vals.push_back(getEncodedAlign(cast<AtomicRMWInst>(I).getAlign()));
3774 break;
3775 case Instruction::Fence:
3777 Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
3778 Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID()));
3779 break;
3780 case Instruction::Call: {
3781 const CallInst &CI = cast<CallInst>(I);
3782 FunctionType *FTy = CI.getFunctionType();
3783
3784 if (CI.hasOperandBundles())
3785 writeOperandBundles(CI, InstID);
3786
3788
3790
3791 unsigned Flags = getOptimizationFlags(&I);
3793 unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
3794 unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
3796 unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
3797 unsigned(Flags != 0) << bitc::CALL_FMF);
3798 if (Flags != 0)
3799 Vals.push_back(Flags);
3800
3801 Vals.push_back(VE.getTypeID(FTy));
3802 pushValueAndType(CI.getCalledOperand(), InstID, Vals); // Callee
3803
3804 // Emit value #'s for the fixed parameters.
3805 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3806 pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
3807
3808 // Emit type/value pairs for varargs params.
3809 if (FTy->isVarArg()) {
3810 for (unsigned i = FTy->getNumParams(), e = CI.arg_size(); i != e; ++i)
3811 pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
3812 }
3813 break;
3814 }
3815 case Instruction::VAArg:
3817 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
3818 pushValue(I.getOperand(0), InstID, Vals); // valist.
3819 Vals.push_back(VE.getTypeID(I.getType())); // restype.
3820 break;
3821 case Instruction::Freeze:
3823 pushValueAndType(I.getOperand(0), InstID, Vals);
3824 break;
3825 }
3826
3827 Stream.EmitRecord(Code, Vals, AbbrevToUse);
3828 Vals.clear();
3829}
3830
3831/// Write a GlobalValue VST to the module. The purpose of this data structure is
3832/// to allow clients to efficiently find the function body.
3833void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
3834 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3835 // Get the offset of the VST we are writing, and backpatch it into
3836 // the VST forward declaration record.
3837 uint64_t VSTOffset = Stream.GetCurrentBitNo();
3838 // The BitcodeStartBit was the stream offset of the identification block.
3839 VSTOffset -= bitcodeStartBit();
3840 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
3841 // Note that we add 1 here because the offset is relative to one word
3842 // before the start of the identification block, which was historically
3843 // always the start of the regular bitcode header.
3844 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
3845
3847
3848 auto Abbv = std::make_shared<BitCodeAbbrev>();
3849 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
3850 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3851 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
3852 unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3853
3854 for (const Function &F : M) {
3855 uint64_t Record[2];
3856
3857 if (F.isDeclaration())
3858 continue;
3859
3860 Record[0] = VE.getValueID(&F);
3861
3862 // Save the word offset of the function (from the start of the
3863 // actual bitcode written to the stream).
3864 uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit();
3865 assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
3866 // Note that we add 1 here because the offset is relative to one word
3867 // before the start of the identification block, which was historically
3868 // always the start of the regular bitcode header.
3869 Record[1] = BitcodeIndex / 32 + 1;
3870
3871 Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev);
3872 }
3873
3874 Stream.ExitBlock();
3875}
3876
3877/// Emit names for arguments, instructions and basic blocks in a function.
3878void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
3879 const ValueSymbolTable &VST) {
3880 if (VST.empty())
3881 return;
3882
3884
3885 // FIXME: Set up the abbrev, we know how many values there are!
3886 // FIXME: We know if the type names can use 7-bit ascii.
3887 SmallVector<uint64_t, 64> NameVals;
3888
3889 for (const ValueName &Name : VST) {
3890 // Figure out the encoding to use for the name.
3892
3893 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
3894 NameVals.push_back(VE.getValueID(Name.getValue()));
3895
3896 // VST_CODE_ENTRY: [valueid, namechar x N]
3897 // VST_CODE_BBENTRY: [bbid, namechar x N]
3898 unsigned Code;
3899 if (isa<BasicBlock>(Name.getValue())) {
3901 if (Bits == SE_Char6)
3902 AbbrevToUse = VST_BBENTRY_6_ABBREV;
3903 } else {
3905 if (Bits == SE_Char6)
3906 AbbrevToUse = VST_ENTRY_6_ABBREV;
3907 else if (Bits == SE_Fixed7)
3908 AbbrevToUse = VST_ENTRY_7_ABBREV;
3909 }
3910
3911 for (const auto P : Name.getKey())
3912 NameVals.push_back((unsigned char)P);
3913
3914 // Emit the finished record.
3915 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
3916 NameVals.clear();
3917 }
3918
3919 Stream.ExitBlock();
3920}
3921
3922void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
3923 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
3924 unsigned Code;
3925 if (isa<BasicBlock>(Order.V))
3927 else
3929
3930 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
3931 Record.push_back(VE.getValueID(Order.V));
3932 Stream.EmitRecord(Code, Record);
3933}
3934
3935void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
3937 "Expected to be preserving use-list order");
3938
3939 auto hasMore = [&]() {
3940 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
3941 };
3942 if (!hasMore())
3943 // Nothing to do.
3944 return;
3945
3947 while (hasMore()) {
3948 writeUseList(std::move(VE.UseListOrders.back()));
3949 VE.UseListOrders.pop_back();
3950 }
3951 Stream.ExitBlock();
3952}
3953
3954/// Emit a function body to the module stream.
3955void ModuleBitcodeWriter::writeFunction(
3956 const Function &F,
3957 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3958 // Save the bitcode index of the start of this function block for recording
3959 // in the VST.
3960 FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
3961
3964
3966
3967 // Emit the number of basic blocks, so the reader can create them ahead of
3968 // time.
3969 Vals.push_back(VE.getBasicBlocks().size());
3971 Vals.clear();
3972
3973 // If there are function-local constants, emit them now.
3974 unsigned CstStart, CstEnd;
3975 VE.getFunctionConstantRange(CstStart, CstEnd);
3976 writeConstants(CstStart, CstEnd, false);
3977
3978 // If there is function-local metadata, emit it now.
3979 writeFunctionMetadata(F);
3980
3981 // Keep a running idea of what the instruction ID is.
3982 unsigned InstID = CstEnd;
3983
3984 bool NeedsMetadataAttachment = F.hasMetadata();
3985
3986 DILocation *LastDL = nullptr;
3987 SmallSetVector<Function *, 4> BlockAddressUsers;
3988
3989 // Finally, emit all the instructions, in order.
3990 for (const BasicBlock &BB : F) {
3991 for (const Instruction &I : BB) {
3992 writeInstruction(I, InstID, Vals);
3993
3994 if (!I.getType()->isVoidTy())
3995 ++InstID;
3996
3997 // If the instruction has metadata, write a metadata attachment later.
3998 NeedsMetadataAttachment |= I.hasMetadataOtherThanDebugLoc();
3999
4000 // If the instruction has a debug location, emit it.
4001 if (DILocation *DL = I.getDebugLoc()) {
4002 if (DL == LastDL) {
4003 // Just repeat the same debug loc as last time.
4005 } else {
4006 Vals.push_back(DL->getLine());
4007 Vals.push_back(DL->getColumn());
4008 Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
4009 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
4010 Vals.push_back(DL->isImplicitCode());
4011 Vals.push_back(DL->getAtomGroup());
4012 Vals.push_back(DL->getAtomRank());
4013
4014 unsigned DLAbbrev = FUNCTION_DEBUG_LOC_ABBREV;
4015 if (DILayerLocList *IRLayers = DL->getIRLayers()) {
4016 DLAbbrev = FUNCTION_DEBUG_LOC_LAYERS_ABBREV;
4017 Vals.push_back(VE.getMetadataOrNullID(IRLayers));
4018 }
4019
4020 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals, DLAbbrev);
4021 Vals.clear();
4022 LastDL = DL;
4023 }
4024 }
4025
4026 // If the instruction has DbgRecords attached to it, emit them. Note that
4027 // they come after the instruction so that it's easy to attach them again
4028 // when reading the bitcode, even though conceptually the debug locations
4029 // start "before" the instruction.
4030 if (I.hasDbgRecords()) {
4031 /// Try to push the value only (unwrapped), otherwise push the
4032 /// metadata wrapped value. Returns true if the value was pushed
4033 /// without the ValueAsMetadata wrapper.
4034 auto PushValueOrMetadata = [&Vals, InstID,
4035 this](Metadata *RawLocation) {
4036 assert(RawLocation &&
4037 "RawLocation unexpectedly null in DbgVariableRecord");
4038 if (ValueAsMetadata *VAM = dyn_cast<ValueAsMetadata>(RawLocation)) {
4039 SmallVector<unsigned, 2> ValAndType;
4040 // If the value is a fwd-ref the type is also pushed. We don't
4041 // want the type, so fwd-refs are kept wrapped (pushValueAndType
4042 // returns false if the value is pushed without type).
4043 if (!pushValueAndType(VAM->getValue(), InstID, ValAndType)) {
4044 Vals.push_back(ValAndType[0]);
4045 return true;
4046 }
4047 }
4048 // The metadata is a DIArgList, or ValueAsMetadata wrapping a
4049 // fwd-ref. Push the metadata ID.
4050 Vals.push_back(VE.getMetadataID(RawLocation));
4051 return false;
4052 };
4053
4054 // Write out non-instruction debug information attached to this
4055 // instruction. Write it after the instruction so that it's easy to
4056 // re-attach to the instruction reading the records in.
4057 for (DbgRecord &DR : I.getDbgMarker()->getDbgRecordRange()) {
4058 if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) {
4059 Vals.push_back(VE.getMetadataID(&*DLR->getDebugLoc()));
4060 Vals.push_back(VE.getMetadataID(DLR->getLabel()));
4062 Vals.clear();
4063 continue;
4064 }
4065
4066 // First 3 fields are common to all kinds:
4067 // DILocation, DILocalVariable, DIExpression
4068 // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE)
4069 // ..., LocationMetadata
4070 // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE - abbrev'd)
4071 // ..., Value
4072 // dbg_declare (FUNC_CODE_DEBUG_RECORD_DECLARE)
4073 // ..., LocationMetadata
4074 // dbg_assign (FUNC_CODE_DEBUG_RECORD_ASSIGN)
4075 // ..., LocationMetadata, DIAssignID, DIExpression, LocationMetadata
4076 DbgVariableRecord &DVR = cast<DbgVariableRecord>(DR);
4077 Vals.push_back(VE.getMetadataID(&*DVR.getDebugLoc()));
4078 Vals.push_back(VE.getMetadataID(DVR.getVariable()));
4079 Vals.push_back(VE.getMetadataID(DVR.getExpression()));
4080 if (DVR.isDbgValue()) {
4081 if (PushValueOrMetadata(DVR.getRawLocation()))
4083 FUNCTION_DEBUG_RECORD_VALUE_ABBREV);
4084 else
4086 } else if (DVR.isDbgDeclare()) {
4087 Vals.push_back(VE.getMetadataID(DVR.getRawLocation()));
4089 } else if (DVR.isDbgDeclareValue()) {
4090 Vals.push_back(VE.getMetadataID(DVR.getRawLocation()));
4092 } else {
4093 assert(DVR.isDbgAssign() && "Unexpected DbgRecord kind");
4094 Vals.push_back(VE.getMetadataID(DVR.getRawLocation()));
4095 Vals.push_back(VE.getMetadataID(DVR.getAssignID()));
4097 Vals.push_back(VE.getMetadataID(DVR.getRawAddress()));
4099 }
4100 Vals.clear();
4101 }
4102 }
4103 }
4104
4105 if (BlockAddress *BA = BlockAddress::lookup(&BB)) {
4106 SmallVector<Value *> Worklist{BA};
4107 SmallPtrSet<Value *, 8> Visited{BA};
4108 while (!Worklist.empty()) {
4109 Value *V = Worklist.pop_back_val();
4110 for (User *U : V->users()) {
4111 if (auto *I = dyn_cast<Instruction>(U)) {
4112 Function *P = I->getFunction();
4113 if (P != &F)
4114 BlockAddressUsers.insert(P);
4115 } else if (isa<Constant>(U) && !isa<GlobalValue>(U) &&
4116 Visited.insert(U).second)
4117 Worklist.push_back(U);
4118 }
4119 }
4120 }
4121 }
4122
4123 if (!BlockAddressUsers.empty()) {
4124 Vals.resize(BlockAddressUsers.size());
4125 for (auto I : llvm::enumerate(BlockAddressUsers))
4126 Vals[I.index()] = VE.getValueID(I.value());
4128 Vals.clear();
4129 }
4130
4131 // Emit names for all the instructions etc.
4132 if (auto *Symtab = F.getValueSymbolTable())
4133 writeFunctionLevelValueSymbolTable(*Symtab);
4134
4135 if (NeedsMetadataAttachment)
4136 writeFunctionMetadataAttachment(F);
4138 writeUseListBlock(&F);
4139 VE.purgeFunction();
4140 Stream.ExitBlock();
4141}
4142
4143// Emit blockinfo, which defines the standard abbreviations etc.
4144void ModuleBitcodeWriter::writeBlockInfo() {
4145 // We only want to emit block info records for blocks that have multiple
4146 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
4147 // Other blocks can define their abbrevs inline.
4148 Stream.EnterBlockInfoBlock();
4149
4150 // Encode type indices using fixed size based on number of types.
4151 BitCodeAbbrevOp TypeAbbrevOp(BitCodeAbbrevOp::Fixed,
4153 // Encode value indices as 6-bit VBR.
4154 BitCodeAbbrevOp ValAbbrevOp(BitCodeAbbrevOp::VBR, 6);
4155
4156 { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
4157 auto Abbv = std::make_shared<BitCodeAbbrev>();
4158 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
4159 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4160 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4161 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
4163 VST_ENTRY_8_ABBREV)
4164 llvm_unreachable("Unexpected abbrev ordering!");
4165 }
4166
4167 { // 7-bit fixed width VST_CODE_ENTRY strings.
4168 auto Abbv = std::make_shared<BitCodeAbbrev>();
4169 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
4170 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4171 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4172 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
4174 VST_ENTRY_7_ABBREV)
4175 llvm_unreachable("Unexpected abbrev ordering!");
4176 }
4177 { // 6-bit char6 VST_CODE_ENTRY strings.
4178 auto Abbv = std::make_shared<BitCodeAbbrev>();
4179 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
4180 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4181 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4182 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
4184 VST_ENTRY_6_ABBREV)
4185 llvm_unreachable("Unexpected abbrev ordering!");
4186 }
4187 { // 6-bit char6 VST_CODE_BBENTRY strings.
4188 auto Abbv = std::make_shared<BitCodeAbbrev>();
4189 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
4190 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4191 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4192 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
4194 VST_BBENTRY_6_ABBREV)
4195 llvm_unreachable("Unexpected abbrev ordering!");
4196 }
4197
4198 { // SETTYPE abbrev for CONSTANTS_BLOCK.
4199 auto Abbv = std::make_shared<BitCodeAbbrev>();
4200 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
4201 Abbv->Add(TypeAbbrevOp);
4203 CONSTANTS_SETTYPE_ABBREV)
4204 llvm_unreachable("Unexpected abbrev ordering!");
4205 }
4206
4207 { // INTEGER abbrev for CONSTANTS_BLOCK.
4208 auto Abbv = std::make_shared<BitCodeAbbrev>();
4209 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
4210 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4212 CONSTANTS_INTEGER_ABBREV)
4213 llvm_unreachable("Unexpected abbrev ordering!");
4214 }
4215
4216 { // BYTE abbrev for CONSTANTS_BLOCK.
4217 auto Abbv = std::make_shared<BitCodeAbbrev>();
4218 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_BYTE));
4219 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4221 CONSTANTS_BYTE_ABBREV)
4222 llvm_unreachable("Unexpected abbrev ordering!");
4223 }
4224
4225 { // CE_CAST abbrev for CONSTANTS_BLOCK.
4226 auto Abbv = std::make_shared<BitCodeAbbrev>();
4227 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
4228 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
4229 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
4231 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
4232
4234 CONSTANTS_CE_CAST_Abbrev)
4235 llvm_unreachable("Unexpected abbrev ordering!");
4236 }
4237 { // NULL abbrev for CONSTANTS_BLOCK.
4238 auto Abbv = std::make_shared<BitCodeAbbrev>();
4239 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
4241 CONSTANTS_NULL_Abbrev)
4242 llvm_unreachable("Unexpected abbrev ordering!");
4243 }
4244
4245 // FIXME: This should only use space for first class types!
4246
4247 { // INST_LOAD abbrev for FUNCTION_BLOCK.
4248 auto Abbv = std::make_shared<BitCodeAbbrev>();
4249 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
4250 Abbv->Add(ValAbbrevOp); // Ptr
4251 Abbv->Add(TypeAbbrevOp); // dest ty
4252 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
4253 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
4254 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4255 FUNCTION_INST_LOAD_ABBREV)
4256 llvm_unreachable("Unexpected abbrev ordering!");
4257 }
4258 {
4259 auto Abbv = std::make_shared<BitCodeAbbrev>();
4260 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_STORE));
4261 Abbv->Add(ValAbbrevOp); // op1
4262 Abbv->Add(ValAbbrevOp); // op0
4263 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // align
4264 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
4265 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4266 FUNCTION_INST_STORE_ABBREV)
4267 llvm_unreachable("Unexpected abbrev ordering!");
4268 }
4269 { // INST_UNOP abbrev for FUNCTION_BLOCK.
4270 auto Abbv = std::make_shared<BitCodeAbbrev>();
4271 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP));
4272 Abbv->Add(ValAbbrevOp); // LHS
4273 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
4274 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4275 FUNCTION_INST_UNOP_ABBREV)
4276 llvm_unreachable("Unexpected abbrev ordering!");
4277 }
4278 { // INST_UNOP_FLAGS abbrev for FUNCTION_BLOCK.
4279 auto Abbv = std::make_shared<BitCodeAbbrev>();
4280 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP));
4281 Abbv->Add(ValAbbrevOp); // LHS
4282 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
4283 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
4284 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4285 FUNCTION_INST_UNOP_FLAGS_ABBREV)
4286 llvm_unreachable("Unexpected abbrev ordering!");
4287 }
4288 { // INST_BINOP abbrev for FUNCTION_BLOCK.
4289 auto Abbv = std::make_shared<BitCodeAbbrev>();
4290 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
4291 Abbv->Add(ValAbbrevOp); // LHS
4292 Abbv->Add(ValAbbrevOp); // RHS
4293 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
4294 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4295 FUNCTION_INST_BINOP_ABBREV)
4296 llvm_unreachable("Unexpected abbrev ordering!");
4297 }
4298 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
4299 auto Abbv = std::make_shared<BitCodeAbbrev>();
4300 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
4301 Abbv->Add(ValAbbrevOp); // LHS
4302 Abbv->Add(ValAbbrevOp); // RHS
4303 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
4304 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
4305 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4306 FUNCTION_INST_BINOP_FLAGS_ABBREV)
4307 llvm_unreachable("Unexpected abbrev ordering!");
4308 }
4309 { // INST_CAST abbrev for FUNCTION_BLOCK.
4310 auto Abbv = std::make_shared<BitCodeAbbrev>();
4311 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
4312 Abbv->Add(ValAbbrevOp); // OpVal
4313 Abbv->Add(TypeAbbrevOp); // dest ty
4314 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
4315 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4316 FUNCTION_INST_CAST_ABBREV)
4317 llvm_unreachable("Unexpected abbrev ordering!");
4318 }
4319 { // INST_CAST_FLAGS abbrev for FUNCTION_BLOCK.
4320 auto Abbv = std::make_shared<BitCodeAbbrev>();
4321 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
4322 Abbv->Add(ValAbbrevOp); // OpVal
4323 Abbv->Add(TypeAbbrevOp); // dest ty
4324 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
4325 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 9)); // flags
4326 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4327 FUNCTION_INST_CAST_FLAGS_ABBREV)
4328 llvm_unreachable("Unexpected abbrev ordering!");
4329 }
4330
4331 { // INST_RET abbrev for FUNCTION_BLOCK.
4332 auto Abbv = std::make_shared<BitCodeAbbrev>();
4333 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
4334 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4335 FUNCTION_INST_RET_VOID_ABBREV)
4336 llvm_unreachable("Unexpected abbrev ordering!");
4337 }
4338 { // INST_RET abbrev for FUNCTION_BLOCK.
4339 auto Abbv = std::make_shared<BitCodeAbbrev>();
4340 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
4341 Abbv->Add(ValAbbrevOp);
4342 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4343 FUNCTION_INST_RET_VAL_ABBREV)
4344 llvm_unreachable("Unexpected abbrev ordering!");
4345 }
4346 {
4347 auto Abbv = std::make_shared<BitCodeAbbrev>();
4348 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BR));
4349 // TODO: Use different abbrev for absolute value reference (succ0)?
4350 Abbv->Add(ValAbbrevOp); // succ0
4351 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4352 FUNCTION_INST_BR_UNCOND_ABBREV)
4353 llvm_unreachable("Unexpected abbrev ordering!");
4354 }
4355 {
4356 auto Abbv = std::make_shared<BitCodeAbbrev>();
4357 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BR));
4358 // TODO: Use different abbrev for absolute value references (succ0, succ1)?
4359 Abbv->Add(ValAbbrevOp); // succ0
4360 Abbv->Add(ValAbbrevOp); // succ1
4361 Abbv->Add(ValAbbrevOp); // cond
4362 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4363 FUNCTION_INST_BR_COND_ABBREV)
4364 llvm_unreachable("Unexpected abbrev ordering!");
4365 }
4366 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
4367 auto Abbv = std::make_shared<BitCodeAbbrev>();
4368 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
4369 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4370 FUNCTION_INST_UNREACHABLE_ABBREV)
4371 llvm_unreachable("Unexpected abbrev ordering!");
4372 }
4373 {
4374 auto Abbv = std::make_shared<BitCodeAbbrev>();
4375 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
4376 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // flags
4377 Abbv->Add(TypeAbbrevOp); // dest ty
4378 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4379 Abbv->Add(ValAbbrevOp);
4380 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4381 FUNCTION_INST_GEP_ABBREV)
4382 llvm_unreachable("Unexpected abbrev ordering!");
4383 }
4384 {
4385 auto Abbv = std::make_shared<BitCodeAbbrev>();
4386 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CMP2));
4387 Abbv->Add(ValAbbrevOp); // op0
4388 Abbv->Add(ValAbbrevOp); // op1
4389 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 6)); // pred
4390 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4391 FUNCTION_INST_CMP_ABBREV)
4392 llvm_unreachable("Unexpected abbrev ordering!");
4393 }
4394 {
4395 auto Abbv = std::make_shared<BitCodeAbbrev>();
4396 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CMP2));
4397 Abbv->Add(ValAbbrevOp); // op0
4398 Abbv->Add(ValAbbrevOp); // op1
4399 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 6)); // pred
4400 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
4401 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4402 FUNCTION_INST_CMP_FLAGS_ABBREV)
4403 llvm_unreachable("Unexpected abbrev ordering!");
4404 }
4405 {
4406 auto Abbv = std::make_shared<BitCodeAbbrev>();
4407 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE));
4408 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // dbgloc
4409 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // var
4410 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // expr
4411 Abbv->Add(ValAbbrevOp); // val
4412 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4413 FUNCTION_DEBUG_RECORD_VALUE_ABBREV)
4414 llvm_unreachable("Unexpected abbrev ordering! 1");
4415 }
4416 {
4417 auto Abbv = std::make_shared<BitCodeAbbrev>();
4418 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_DEBUG_LOC));
4419 // NOTE: No IsDistinct field for FUNC_CODE_DEBUG_LOC.
4420 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4421 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4422 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4423 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4424 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
4425 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Atom group.
4426 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3)); // Atom rank.
4427 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4428 FUNCTION_DEBUG_LOC_ABBREV)
4429 llvm_unreachable("Unexpected abbrev ordering!");
4430 }
4431 { // DEBUG_LOC abbrev for FUNCTION_BLOCK, irlayers variant.
4432 // Separate abbrev so a location without layers does not spend a VBR chunk
4433 // encoding a zero; writeInstruction picks between the two per record.
4434 auto Abbv = std::make_shared<BitCodeAbbrev>();
4435 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_DEBUG_LOC));
4436 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4437 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4438 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4439 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4440 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
4441 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Atom group.
4442 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3)); // Atom rank.
4443 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // irlayers.
4444 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4445 FUNCTION_DEBUG_LOC_LAYERS_ABBREV)
4446 llvm_unreachable("Unexpected abbrev ordering!");
4447 }
4448 Stream.ExitBlock();
4449}
4450
4451/// Write the module path strings, currently only used when generating
4452/// a combined index file.
4453void IndexBitcodeWriter::writeModStrings() {
4455
4456 // TODO: See which abbrev sizes we actually need to emit
4457
4458 // 8-bit fixed-width MST_ENTRY strings.
4459 auto Abbv = std::make_shared<BitCodeAbbrev>();
4460 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
4461 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4462 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4463 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
4464 unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
4465
4466 // 7-bit fixed width MST_ENTRY strings.
4467 Abbv = std::make_shared<BitCodeAbbrev>();
4468 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
4469 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4470 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4471 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
4472 unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
4473
4474 // 6-bit char6 MST_ENTRY strings.
4475 Abbv = std::make_shared<BitCodeAbbrev>();
4476 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
4477 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4478 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4479 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
4480 unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
4481
4482 // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
4483 Abbv = std::make_shared<BitCodeAbbrev>();
4484 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH));
4485 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4486 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4487 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4488 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4489 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4490 unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
4491
4493 forEachModule([&](const StringMapEntry<ModuleHash> &MPSE) {
4494 StringRef Key = MPSE.getKey();
4495 const auto &Hash = MPSE.getValue();
4497 unsigned AbbrevToUse = Abbrev8Bit;
4498 if (Bits == SE_Char6)
4499 AbbrevToUse = Abbrev6Bit;
4500 else if (Bits == SE_Fixed7)
4501 AbbrevToUse = Abbrev7Bit;
4502
4503 auto ModuleId = ModuleIdMap.size();
4504 ModuleIdMap[Key] = ModuleId;
4505 Vals.push_back(ModuleId);
4506 // Use bytes_begin/end() for unsigned char iteration.
4507 Vals.append(Key.bytes_begin(), Key.bytes_end());
4508
4509 // Emit the finished record.
4510 Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
4511
4512 // Emit an optional hash for the module now
4513 if (llvm::any_of(Hash, [](uint32_t H) { return H; })) {
4514 Vals.assign(Hash.begin(), Hash.end());
4515 // Emit the hash record.
4516 Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
4517 }
4518
4519 Vals.clear();
4520 });
4521 Stream.ExitBlock();
4522}
4523
4524/// Write the function type metadata related records that need to appear before
4525/// a function summary entry (whether per-module or combined).
4526template <typename Fn>
4528 FunctionSummary *FS,
4529 Fn GetValueID) {
4530 if (!FS->type_tests().empty())
4531 Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
4532
4534
4535 auto WriteVFuncIdVec = [&](uint64_t Ty,
4537 if (VFs.empty())
4538 return;
4539 Record.clear();
4540 for (auto &VF : VFs) {
4541 Record.push_back(VF.GUID);
4542 Record.push_back(VF.Offset);
4543 }
4544 Stream.EmitRecord(Ty, Record);
4545 };
4546
4547 WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
4548 FS->type_test_assume_vcalls());
4549 WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
4550 FS->type_checked_load_vcalls());
4551
4552 auto WriteConstVCallVec = [&](uint64_t Ty,
4554 for (auto &VC : VCs) {
4555 Record.clear();
4556 Record.push_back(VC.VFunc.GUID);
4557 Record.push_back(VC.VFunc.Offset);
4558 llvm::append_range(Record, VC.Args);
4559 Stream.EmitRecord(Ty, Record);
4560 }
4561 };
4562
4563 WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
4564 FS->type_test_assume_const_vcalls());
4565 WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
4566 FS->type_checked_load_const_vcalls());
4567
4568 auto WriteRange = [&](ConstantRange Range) {
4570 assert(Range.getLower().getNumWords() == 1);
4571 assert(Range.getUpper().getNumWords() == 1);
4572 emitSignedInt64(Record, *Range.getLower().getRawData());
4573 emitSignedInt64(Record, *Range.getUpper().getRawData());
4574 };
4575
4576 if (!FS->paramAccesses().empty()) {
4577 Record.clear();
4578 for (auto &Arg : FS->paramAccesses()) {
4579 size_t UndoSize = Record.size();
4580 Record.push_back(Arg.ParamNo);
4581 WriteRange(Arg.Use);
4582 Record.push_back(Arg.Calls.size());
4583 for (auto &Call : Arg.Calls) {
4584 Record.push_back(Call.ParamNo);
4585 std::optional<unsigned> ValueID = GetValueID(Call.Callee);
4586 if (!ValueID) {
4587 // If ValueID is unknown we can't drop just this call, we must drop
4588 // entire parameter.
4589 Record.resize(UndoSize);
4590 break;
4591 }
4592 Record.push_back(*ValueID);
4593 WriteRange(Call.Offsets);
4594 }
4595 }
4596 if (!Record.empty())
4598 }
4599}
4600
4601/// Collect type IDs from type tests used by function.
4602static void
4604 std::set<GlobalValue::GUID> &ReferencedTypeIds) {
4605 if (!FS->type_tests().empty())
4606 for (auto &TT : FS->type_tests())
4607 ReferencedTypeIds.insert(TT);
4608
4609 auto GetReferencedTypesFromVFuncIdVec =
4611 for (auto &VF : VFs)
4612 ReferencedTypeIds.insert(VF.GUID);
4613 };
4614
4615 GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls());
4616 GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls());
4617
4618 auto GetReferencedTypesFromConstVCallVec =
4620 for (auto &VC : VCs)
4621 ReferencedTypeIds.insert(VC.VFunc.GUID);
4622 };
4623
4624 GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls());
4625 GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls());
4626}
4627
4629 SmallVector<uint64_t, 64> &NameVals, const std::vector<uint64_t> &args,
4631 NameVals.push_back(args.size());
4632 llvm::append_range(NameVals, args);
4633
4634 NameVals.push_back(ByArg.TheKind);
4635 NameVals.push_back(ByArg.Info);
4636 NameVals.push_back(ByArg.Byte);
4637 NameVals.push_back(ByArg.Bit);
4638}
4639
4641 SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
4642 uint64_t Id, const WholeProgramDevirtResolution &Wpd) {
4643 NameVals.push_back(Id);
4644
4645 NameVals.push_back(Wpd.TheKind);
4646 NameVals.push_back(StrtabBuilder.add(Wpd.SingleImplName));
4647 NameVals.push_back(Wpd.SingleImplName.size());
4648
4649 NameVals.push_back(Wpd.ResByArg.size());
4650 for (auto &A : Wpd.ResByArg)
4651 writeWholeProgramDevirtResolutionByArg(NameVals, A.first, A.second);
4652}
4653
4655 StringTableBuilder &StrtabBuilder,
4656 StringRef Id,
4657 const TypeIdSummary &Summary) {
4658 NameVals.push_back(StrtabBuilder.add(Id));
4659 NameVals.push_back(Id.size());
4660
4661 NameVals.push_back(Summary.TTRes.TheKind);
4662 NameVals.push_back(Summary.TTRes.SizeM1BitWidth);
4663 NameVals.push_back(Summary.TTRes.AlignLog2);
4664 NameVals.push_back(Summary.TTRes.SizeM1);
4665 NameVals.push_back(Summary.TTRes.BitMask);
4666 NameVals.push_back(Summary.TTRes.InlineBits);
4667
4668 for (auto &W : Summary.WPDRes)
4669 writeWholeProgramDevirtResolution(NameVals, StrtabBuilder, W.first,
4670 W.second);
4671}
4672
4674 SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
4675 StringRef Id, const TypeIdCompatibleVtableInfo &Summary,
4677 NameVals.push_back(StrtabBuilder.add(Id));
4678 NameVals.push_back(Id.size());
4679
4680 for (auto &P : Summary) {
4681 NameVals.push_back(P.AddressPointOffset);
4682 NameVals.push_back(VE.getValueID(P.VTableVI.getValue()));
4683 }
4684}
4685
4686// Adds the allocation contexts to the CallStacks map. We simply use the
4687// size at the time the context was added as the CallStackId. This works because
4688// when we look up the call stacks later on we process the function summaries
4689// and their allocation records in the same exact order.
4691 FunctionSummary *FS, std::function<LinearFrameId(unsigned)> GetStackIndex,
4693 // The interfaces in ProfileData/MemProf.h use a type alias for a stack frame
4694 // id offset into the index of the full stack frames. The ModuleSummaryIndex
4695 // currently uses unsigned. Make sure these stay in sync.
4696 static_assert(std::is_same_v<LinearFrameId, unsigned>);
4697 for (auto &AI : FS->allocs()) {
4698 for (auto &MIB : AI.MIBs) {
4699 SmallVector<unsigned> StackIdIndices;
4700 StackIdIndices.reserve(MIB.StackIdIndices.size());
4701 for (auto Id : MIB.StackIdIndices)
4702 StackIdIndices.push_back(GetStackIndex(Id));
4703 // The CallStackId is the size at the time this context was inserted.
4704 CallStacks.insert({CallStacks.size(), StackIdIndices});
4705 }
4706 }
4707}
4708
4709// Build the radix tree from the accumulated CallStacks, write out the resulting
4710// linearized radix tree array, and return the map of call stack positions into
4711// this array for use when writing the allocation records. The returned map is
4712// indexed by a CallStackId which in this case is implicitly determined by the
4713// order of function summaries and their allocation infos being written.
4716 BitstreamWriter &Stream, unsigned RadixAbbrev) {
4717 assert(!CallStacks.empty());
4718 DenseMap<unsigned, FrameStat> FrameHistogram =
4721 // We don't need a MemProfFrameIndexes map as we have already converted the
4722 // full stack id hash to a linear offset into the StackIds array.
4723 Builder.build(std::move(CallStacks), /*MemProfFrameIndexes=*/nullptr,
4724 FrameHistogram);
4725 Stream.EmitRecord(bitc::FS_CONTEXT_RADIX_TREE_ARRAY, Builder.getRadixArray(),
4726 RadixAbbrev);
4727 return Builder.takeCallStackPos();
4728}
4729
4731 BitstreamWriter &Stream, FunctionSummary *FS, unsigned CallsiteAbbrev,
4732 unsigned AllocAbbrev, unsigned ContextIdAbbvId, bool PerModule,
4733 std::function<unsigned(const ValueInfo &VI)> GetValueID,
4734 std::function<unsigned(unsigned)> GetStackIndex,
4735 bool WriteContextSizeInfoIndex,
4737 CallStackId &CallStackCount) {
4739
4740 for (auto &CI : FS->callsites()) {
4741 Record.clear();
4742 // Per module callsite clones should always have a single entry of
4743 // value 0.
4744 assert(!PerModule || (CI.Clones.size() == 1 && CI.Clones[0] == 0));
4745 Record.push_back(GetValueID(CI.Callee));
4746 if (!PerModule) {
4747 Record.push_back(CI.StackIdIndices.size());
4748 Record.push_back(CI.Clones.size());
4749 }
4750 for (auto Id : CI.StackIdIndices)
4751 Record.push_back(GetStackIndex(Id));
4752 if (!PerModule)
4753 llvm::append_range(Record, CI.Clones);
4756 Record, CallsiteAbbrev);
4757 }
4758
4759 for (auto &AI : FS->allocs()) {
4760 Record.clear();
4761 // Per module alloc versions should always have a single entry of
4762 // value 0.
4763 assert(!PerModule || (AI.Versions.size() == 1 && AI.Versions[0] == 0));
4764 Record.push_back(AI.MIBs.size());
4765 if (!PerModule)
4766 Record.push_back(AI.Versions.size());
4767 for (auto &MIB : AI.MIBs) {
4768 Record.push_back((uint8_t)MIB.AllocType);
4769 // The per-module summary always needs to include the alloc context, as we
4770 // use it during the thin link. For the combined index it is optional (see
4771 // comments where CombinedIndexMemProfContext is defined).
4772 if (PerModule || CombinedIndexMemProfContext) {
4773 // Record the index into the radix tree array for this context.
4774 assert(CallStackCount <= CallStackPos.size());
4775 Record.push_back(CallStackPos[CallStackCount++]);
4776 }
4777 }
4778 if (!PerModule)
4779 llvm::append_range(Record, AI.Versions);
4780 assert(AI.ContextSizeInfos.empty() ||
4781 AI.ContextSizeInfos.size() == AI.MIBs.size());
4782 // Optionally emit the context size information if it exists.
4783 if (WriteContextSizeInfoIndex && !AI.ContextSizeInfos.empty()) {
4784 // The abbreviation id for the context ids record should have been created
4785 // if we are emitting the per-module index, which is where we write this
4786 // info.
4787 assert(ContextIdAbbvId);
4788 SmallVector<uint32_t> ContextIds;
4789 // At least one context id per ContextSizeInfos entry (MIB), broken into 2
4790 // halves.
4791 ContextIds.reserve(AI.ContextSizeInfos.size() * 2);
4792 for (auto &Infos : AI.ContextSizeInfos) {
4793 Record.push_back(Infos.size());
4794 for (auto [FullStackId, TotalSize] : Infos) {
4795 // The context ids are emitted separately as a fixed width array,
4796 // which is more efficient than a VBR given that these hashes are
4797 // typically close to 64-bits. The max fixed width entry is 32 bits so
4798 // it is split into 2.
4799 ContextIds.push_back(static_cast<uint32_t>(FullStackId >> 32));
4800 ContextIds.push_back(static_cast<uint32_t>(FullStackId));
4801 Record.push_back(TotalSize);
4802 }
4803 }
4804 // The context ids are expected by the reader to immediately precede the
4805 // associated alloc info record.
4806 Stream.EmitRecord(bitc::FS_ALLOC_CONTEXT_IDS, ContextIds,
4807 ContextIdAbbvId);
4808 }
4809 Stream.EmitRecord(PerModule
4814 Record, AllocAbbrev);
4815 }
4816}
4817
4818// Helper to emit a single function summary record.
4819void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
4820 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
4821 unsigned ValueID, unsigned FSCallsProfileAbbrev, unsigned CallsiteAbbrev,
4822 unsigned AllocAbbrev, unsigned ContextIdAbbvId, const Function &F,
4823 DenseMap<CallStackId, LinearCallStackId> &CallStackPos,
4824 CallStackId &CallStackCount) {
4825 NameVals.push_back(ValueID);
4826
4827 FunctionSummary *FS = cast<FunctionSummary>(Summary);
4828
4830 Stream, FS, [&](const ValueInfo &VI) -> std::optional<unsigned> {
4831 return {VE.getValueID(VI.getValue())};
4832 });
4833
4834 auto SpecialRefCnts = FS->specialRefCounts();
4835 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
4836 NameVals.push_back(FS->instCount());
4837 NameVals.push_back(getEncodedFFlags(FS->fflags()));
4838 NameVals.push_back(FS->refs().size());
4839 NameVals.push_back(SpecialRefCnts.first); // rorefcnt
4840 NameVals.push_back(SpecialRefCnts.second); // worefcnt
4841
4842 for (auto &RI : FS->refs())
4843 NameVals.push_back(getValueId(RI));
4844
4845 for (auto &ECI : FS->calls()) {
4846 NameVals.push_back(getValueId(ECI.first));
4847 NameVals.push_back(getEncodedHotnessCallEdgeInfo(ECI.second));
4848 }
4849
4850 // Emit the finished record.
4851 Stream.EmitRecord(bitc::FS_PERMODULE_PROFILE, NameVals, FSCallsProfileAbbrev);
4852 NameVals.clear();
4853
4855 Stream, FS, CallsiteAbbrev, AllocAbbrev, ContextIdAbbvId,
4856 /*PerModule*/ true,
4857 /*GetValueId*/ [&](const ValueInfo &VI) { return getValueId(VI); },
4858 /*GetStackIndex*/ [&](unsigned I) { return I; },
4859 /*WriteContextSizeInfoIndex*/ true, CallStackPos, CallStackCount);
4860}
4861
4862// Collect the global value references in the given variable's initializer,
4863// and emit them in a summary record.
4864void ModuleBitcodeWriterBase::writeModuleLevelReferences(
4865 const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
4866 unsigned FSModRefsAbbrev, unsigned FSModVTableRefsAbbrev) {
4867 // Be a little lenient here, to accomodate older files without GUIDs
4868 // already computed and assigned as metadata.
4869 GlobalValue::GUID GUID = V.getGUIDOrFallback();
4870
4871 auto VI = Index->getValueInfo(GUID);
4872 if (!VI || VI.getSummaryList().empty()) {
4873 // Only declarations should not have a summary (a declaration might however
4874 // have a summary if the def was in module level asm).
4875 assert(V.isDeclaration());
4876 return;
4877 }
4878 auto *Summary = VI.getSummaryList()[0].get();
4879 NameVals.push_back(VE.getValueID(&V));
4880 GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
4881 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
4882 NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
4883
4884 auto VTableFuncs = VS->vTableFuncs();
4885 if (!VTableFuncs.empty())
4886 NameVals.push_back(VS->refs().size());
4887
4888 unsigned SizeBeforeRefs = NameVals.size();
4889 for (auto &RI : VS->refs())
4890 NameVals.push_back(VE.getValueID(RI.getValue()));
4891 // Sort the refs for determinism output, the vector returned by FS->refs() has
4892 // been initialized from a DenseSet.
4893 llvm::sort(drop_begin(NameVals, SizeBeforeRefs));
4894
4895 if (VTableFuncs.empty())
4897 FSModRefsAbbrev);
4898 else {
4899 // VTableFuncs pairs should already be sorted by offset.
4900 for (auto &P : VTableFuncs) {
4901 NameVals.push_back(VE.getValueID(P.FuncVI.getValue()));
4902 NameVals.push_back(P.VTableOffset);
4903 }
4904
4906 FSModVTableRefsAbbrev);
4907 }
4908 NameVals.clear();
4909}
4910
4911/// Emit the per-module summary section alongside the rest of
4912/// the module's bitcode.
4913void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
4914 // By default we compile with ThinLTO if the module has a summary, but the
4915 // client can request full LTO with a module flag.
4916 bool IsThinLTO = true;
4917 if (auto *MD =
4918 mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
4919 IsThinLTO = MD->getZExtValue();
4922 4);
4923
4924 Stream.EmitRecord(
4926 ArrayRef<uint64_t>{ModuleSummaryIndex::BitcodeSummaryVersion});
4927
4928 // Write the index flags.
4929 uint64_t Flags = 0;
4930 // Bits 1-3 are set only in the combined index, skip them.
4931 if (Index->enableSplitLTOUnit())
4932 Flags |= 0x8;
4933 if (Index->hasUnifiedLTO())
4934 Flags |= 0x200;
4935
4936 Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Flags});
4937
4938 if (Index->begin() == Index->end()) {
4939 Stream.ExitBlock();
4940 return;
4941 }
4942
4943 auto Abbv = std::make_shared<BitCodeAbbrev>();
4944 Abbv->Add(BitCodeAbbrevOp(bitc::FS_VALUE_GUID));
4945 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4946 // GUIDS often use up most of 64-bits, so encode as two Fixed 32.
4947 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4948 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4949 unsigned ValueGuidAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4950
4951 for (const auto &GVI : valueIds()) {
4953 ArrayRef<uint32_t>{GVI.second,
4954 static_cast<uint32_t>(GVI.first >> 32),
4955 static_cast<uint32_t>(GVI.first)},
4956 ValueGuidAbbrev);
4957 }
4958
4959 if (!Index->stackIds().empty()) {
4960 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
4961 StackIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_STACK_IDS));
4962 // numids x stackid
4963 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4964 // The stack ids are hashes that are close to 64 bits in size, so emitting
4965 // as a pair of 32-bit fixed-width values is more efficient than a VBR.
4966 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4967 unsigned StackIdAbbvId = Stream.EmitAbbrev(std::move(StackIdAbbv));
4968 SmallVector<uint32_t> Vals;
4969 Vals.reserve(Index->stackIds().size() * 2);
4970 for (auto Id : Index->stackIds()) {
4971 Vals.push_back(static_cast<uint32_t>(Id >> 32));
4972 Vals.push_back(static_cast<uint32_t>(Id));
4973 }
4974 Stream.EmitRecord(bitc::FS_STACK_IDS, Vals, StackIdAbbvId);
4975 }
4976
4977 unsigned ContextIdAbbvId = 0;
4979 // n x context id
4980 auto ContextIdAbbv = std::make_shared<BitCodeAbbrev>();
4981 ContextIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_ALLOC_CONTEXT_IDS));
4982 ContextIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4983 // The context ids are hashes that are close to 64 bits in size, so emitting
4984 // as a pair of 32-bit fixed-width values is more efficient than a VBR if we
4985 // are emitting them for all MIBs. Otherwise we use VBR to better compress 0
4986 // values that are expected to more frequently occur in an alloc's memprof
4987 // summary.
4989 ContextIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4990 else
4991 ContextIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4992 ContextIdAbbvId = Stream.EmitAbbrev(std::move(ContextIdAbbv));
4993 }
4994
4995 // Abbrev for FS_PERMODULE_PROFILE.
4996 Abbv = std::make_shared<BitCodeAbbrev>();
4997 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));
4998 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4999 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // flags
5000 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
5001 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
5002 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
5003 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
5004 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
5005 // numrefs x valueid, n x (valueid, hotness+tailcall+indirectcall flags)
5006 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5007 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
5008 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5009
5010 // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
5011 Abbv = std::make_shared<BitCodeAbbrev>();
5012 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));
5013 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
5014 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
5015 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
5016 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
5017 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5018
5019 // Abbrev for FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS.
5020 Abbv = std::make_shared<BitCodeAbbrev>();
5021 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS));
5022 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
5023 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
5024 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
5025 // numrefs x valueid, n x (valueid , offset)
5026 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5027 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
5028 unsigned FSModVTableRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5029
5030 // Abbrev for FS_ALIAS.
5031 Abbv = std::make_shared<BitCodeAbbrev>();
5032 Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
5033 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
5034 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
5035 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
5036 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5037
5038 // Abbrev for FS_TYPE_ID_METADATA
5039 Abbv = std::make_shared<BitCodeAbbrev>();
5040 Abbv->Add(BitCodeAbbrevOp(bitc::FS_TYPE_ID_METADATA));
5041 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid strtab index
5042 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid length
5043 // n x (valueid , offset)
5044 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5045 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
5046 unsigned TypeIdCompatibleVtableAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5047
5048 Abbv = std::make_shared<BitCodeAbbrev>();
5049 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_CALLSITE_INFO));
5050 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
5051 // n x stackidindex
5052 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5053 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
5054 unsigned CallsiteAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5055
5056 Abbv = std::make_shared<BitCodeAbbrev>();
5057 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_ALLOC_INFO));
5058 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // nummib
5059 // n x (alloc type, context radix tree index)
5060 // optional: nummib x (numcontext x total size)
5061 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5062 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
5063 unsigned AllocAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5064
5065 Abbv = std::make_shared<BitCodeAbbrev>();
5066 Abbv->Add(BitCodeAbbrevOp(bitc::FS_CONTEXT_RADIX_TREE_ARRAY));
5067 // n x entry
5068 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5069 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
5070 unsigned RadixAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5071
5072 // First walk through all the functions and collect the allocation contexts in
5073 // their associated summaries, for use in constructing a radix tree of
5074 // contexts. Note that we need to do this in the same order as the functions
5075 // are processed further below since the call stack positions in the resulting
5076 // radix tree array are identified based on this order.
5077 MapVector<CallStackId, llvm::SmallVector<LinearFrameId>> CallStacks;
5078 for (const Function &F : M) {
5079 // Summary emission does not support anonymous functions, they have to be
5080 // renamed using the anonymous function renaming pass.
5081 if (!F.hasName())
5082 report_fatal_error("Unexpected anonymous function when writing summary");
5083
5084 // Be a little lenient here, to accomodate older files without GUIDs
5085 // already computed and assigned as metadata.
5086 GlobalValue::GUID GUID = F.getGUIDOrFallback();
5087
5088 ValueInfo VI = Index->getValueInfo(GUID);
5089 if (!VI || VI.getSummaryList().empty()) {
5090 // Only declarations should not have a summary (a declaration might
5091 // however have a summary if the def was in module level asm).
5092 if (!F.isDeclaration())
5093 reportFatalUsageError("expected function definition " + F.getName() +
5094 " to have an associated value info.");
5095 continue;
5096 }
5097 auto *Summary = VI.getSummaryList()[0].get();
5098 FunctionSummary *FS = cast<FunctionSummary>(Summary);
5100 FS, /*GetStackIndex*/ [](unsigned I) { return I; }, CallStacks);
5101 }
5102 // Finalize the radix tree, write it out, and get the map of positions in the
5103 // linearized tree array.
5104 DenseMap<CallStackId, LinearCallStackId> CallStackPos;
5105 if (!CallStacks.empty()) {
5106 CallStackPos =
5107 writeMemoryProfileRadixTree(std::move(CallStacks), Stream, RadixAbbrev);
5108 }
5109
5110 // Keep track of the current index into the CallStackPos map.
5111 CallStackId CallStackCount = 0;
5112
5113 SmallVector<uint64_t, 64> NameVals;
5114 // Iterate over the list of functions instead of the Index to
5115 // ensure the ordering is stable.
5116 for (const Function &F : M) {
5117 // Summary emission does not support anonymous functions, they have to
5118 // renamed using the anonymous function renaming pass.
5119 if (!F.hasName())
5120 report_fatal_error("Unexpected anonymous function when writing summary");
5121
5122 GlobalValue::GUID GUID = F.getGUIDOrFallback();
5123
5124 ValueInfo VI = Index->getValueInfo(GUID);
5125 if (!VI || VI.getSummaryList().empty()) {
5126 // Only declarations should not have a summary (a declaration might
5127 // however have a summary if the def was in module level asm).
5128 assert(F.isDeclaration());
5129 continue;
5130 }
5131 auto *Summary = VI.getSummaryList()[0].get();
5132 writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.getValueID(&F),
5133 FSCallsProfileAbbrev, CallsiteAbbrev,
5134 AllocAbbrev, ContextIdAbbvId, F,
5135 CallStackPos, CallStackCount);
5136 }
5137
5138 // Capture references from GlobalVariable initializers, which are outside
5139 // of a function scope.
5140 for (const GlobalVariable &G : M.globals())
5141 writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev,
5142 FSModVTableRefsAbbrev);
5143
5144 for (const GlobalAlias &A : M.aliases()) {
5145 auto *Aliasee = A.getAliaseeObject();
5146 // Skip ifunc and nameless functions which don't have an entry in the
5147 // summary.
5148 if (!Aliasee->hasName() || isa<GlobalIFunc>(Aliasee))
5149 continue;
5150 auto AliasId = VE.getValueID(&A);
5151 auto AliaseeId = VE.getValueID(Aliasee);
5152 NameVals.push_back(AliasId);
5153 auto *Summary = Index->getGlobalValueSummary(A);
5154 AliasSummary *AS = cast<AliasSummary>(Summary);
5155 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
5156 NameVals.push_back(AliaseeId);
5157 Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
5158 NameVals.clear();
5159 }
5160
5161 for (auto &S : Index->typeIdCompatibleVtableMap()) {
5162 writeTypeIdCompatibleVtableSummaryRecord(NameVals, StrtabBuilder, S.first,
5163 S.second, VE);
5164 Stream.EmitRecord(bitc::FS_TYPE_ID_METADATA, NameVals,
5165 TypeIdCompatibleVtableAbbrev);
5166 NameVals.clear();
5167 }
5168
5169 if (Index->getBlockCount())
5171 ArrayRef<uint64_t>{Index->getBlockCount()});
5172
5173 Stream.ExitBlock();
5174}
5175
5176void ModuleBitcodeWriterBase::writeGUIDList() {
5178 for (const GlobalValue &GV : M.global_values()) {
5179 auto MaybeGUID = GV.getGUIDIfAssigned();
5180 if (!MaybeGUID || *MaybeGUID == 0)
5181 continue;
5182 const auto ValueID = VE.getValueID(&GV);
5183 if (ValueID >= GUIDs.size())
5184 GUIDs.resize(ValueID + 1);
5185 GUIDs[ValueID] = *MaybeGUID;
5186 }
5187
5188 auto Abbv = std::make_shared<BitCodeAbbrev>();
5189 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GUIDLIST));
5190 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5191 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
5192 unsigned GUIDListAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5193
5194 SmallVector<uint32_t> RecordVals;
5195 RecordVals.reserve(GUIDs.size() * 2);
5196 for (auto GUID : GUIDs) {
5197 RecordVals.push_back(static_cast<uint32_t>(GUID >> 32));
5198 RecordVals.push_back(static_cast<uint32_t>(GUID));
5199 }
5200
5201 Stream.EmitRecord(bitc::MODULE_CODE_GUIDLIST, RecordVals, GUIDListAbbrev);
5202}
5203
5204/// Emit the combined summary section into the combined index file.
5205void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
5207 Stream.EmitRecord(
5209 ArrayRef<uint64_t>{ModuleSummaryIndex::BitcodeSummaryVersion});
5210
5211 // Write the index flags.
5212 Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Index.getFlags()});
5213
5214 auto Abbv = std::make_shared<BitCodeAbbrev>();
5215 Abbv->Add(BitCodeAbbrevOp(bitc::FS_VALUE_GUID));
5216 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
5217 // GUIDS often use up most of 64-bits, so encode as two Fixed 32.
5218 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
5219 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
5220 unsigned ValueGuidAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5221
5222 for (const auto &GVI : valueIds()) {
5224 ArrayRef<uint32_t>{GVI.second,
5225 static_cast<uint32_t>(GVI.first >> 32),
5226 static_cast<uint32_t>(GVI.first)},
5227 ValueGuidAbbrev);
5228 }
5229
5230 // Write the stack ids used by this index, which will be a subset of those in
5231 // the full index in the case of distributed indexes.
5232 if (!StackIds.empty()) {
5233 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
5234 StackIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_STACK_IDS));
5235 // numids x stackid
5236 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5237 // The stack ids are hashes that are close to 64 bits in size, so emitting
5238 // as a pair of 32-bit fixed-width values is more efficient than a VBR.
5239 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
5240 unsigned StackIdAbbvId = Stream.EmitAbbrev(std::move(StackIdAbbv));
5241 SmallVector<uint32_t> Vals;
5242 Vals.reserve(StackIds.size() * 2);
5243 for (auto Id : StackIds) {
5244 Vals.push_back(static_cast<uint32_t>(Id >> 32));
5245 Vals.push_back(static_cast<uint32_t>(Id));
5246 }
5247 Stream.EmitRecord(bitc::FS_STACK_IDS, Vals, StackIdAbbvId);
5248 }
5249
5250 // Abbrev for FS_COMBINED_PROFILE.
5251 Abbv = std::make_shared<BitCodeAbbrev>();
5252 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));
5253 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
5254 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
5255 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
5256 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
5257 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
5258 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // entrycount
5259 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
5260 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
5261 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
5262 // numrefs x valueid, n x (valueid, hotness+tailcall+indirectcall flags)
5263 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5264 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
5265 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5266
5267 // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
5268 Abbv = std::make_shared<BitCodeAbbrev>();
5269 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));
5270 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
5271 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
5272 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
5273 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
5274 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
5275 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5276
5277 // Abbrev for FS_COMBINED_ALIAS.
5278 Abbv = std::make_shared<BitCodeAbbrev>();
5279 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS));
5280 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
5281 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
5282 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
5283 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
5284 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5285
5286 Abbv = std::make_shared<BitCodeAbbrev>();
5287 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_CALLSITE_INFO));
5288 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
5289 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numstackindices
5290 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numver
5291 // numstackindices x stackidindex, numver x version
5292 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5293 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
5294 unsigned CallsiteAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5295
5296 Abbv = std::make_shared<BitCodeAbbrev>();
5297 Abbv->Add(BitCodeAbbrevOp(CombinedIndexMemProfContext
5300 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // nummib
5301 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numver
5302 // nummib x (alloc type, context radix tree index),
5303 // numver x version
5304 // optional: nummib x total size
5305 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5306 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
5307 unsigned AllocAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5308
5309 auto shouldImportValueAsDecl = [&](GlobalValueSummary *GVS) -> bool {
5310 if (DecSummaries == nullptr)
5311 return false;
5312 return DecSummaries->count(GVS);
5313 };
5314
5315 // The aliases are emitted as a post-pass, and will point to the value
5316 // id of the aliasee. Save them in a vector for post-processing.
5318
5319 // Save the value id for each summary for alias emission.
5320 DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
5321
5322 SmallVector<uint64_t, 64> NameVals;
5323
5324 // Set that will be populated during call to writeFunctionTypeMetadataRecords
5325 // with the type ids referenced by this index file.
5326 std::set<GlobalValue::GUID> ReferencedTypeIds;
5327
5328 // For local linkage, we also emit the original name separately
5329 // immediately after the record.
5330 auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
5331 // We don't need to emit the original name if we are writing the index for
5332 // distributed backends (in which case ModuleToSummariesForIndex is
5333 // non-null). The original name is only needed during the thin link, since
5334 // for SamplePGO the indirect call targets for local functions have
5335 // have the original name annotated in profile.
5336 // Continue to emit it when writing out the entire combined index, which is
5337 // used in testing the thin link via llvm-lto.
5338 if (ModuleToSummariesForIndex || !GlobalValue::isLocalLinkage(S.linkage()))
5339 return;
5340 NameVals.push_back(S.getOriginalName());
5342 NameVals.clear();
5343 };
5344
5345 DenseMap<CallStackId, LinearCallStackId> CallStackPos;
5347 Abbv = std::make_shared<BitCodeAbbrev>();
5348 Abbv->Add(BitCodeAbbrevOp(bitc::FS_CONTEXT_RADIX_TREE_ARRAY));
5349 // n x entry
5350 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5351 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
5352 unsigned RadixAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5353
5354 // First walk through all the functions and collect the allocation contexts
5355 // in their associated summaries, for use in constructing a radix tree of
5356 // contexts. Note that we need to do this in the same order as the functions
5357 // are processed further below since the call stack positions in the
5358 // resulting radix tree array are identified based on this order.
5359 MapVector<CallStackId, llvm::SmallVector<LinearFrameId>> CallStacks;
5360 forEachSummary([&](GVInfo I, bool IsAliasee) {
5361 // Don't collect this when invoked for an aliasee, as it is not needed for
5362 // the alias summary. If the aliasee is to be imported, we will invoke
5363 // this separately with IsAliasee=false.
5364 if (IsAliasee)
5365 return;
5366 GlobalValueSummary *S = I.second;
5367 assert(S);
5368 auto *FS = dyn_cast<FunctionSummary>(S);
5369 if (!FS)
5370 return;
5372 FS,
5373 /*GetStackIndex*/
5374 [&](unsigned I) {
5375 // Get the corresponding index into the list of StackIds actually
5376 // being written for this combined index (which may be a subset in
5377 // the case of distributed indexes).
5378 assert(StackIdIndicesToIndex.contains(I));
5379 return StackIdIndicesToIndex[I];
5380 },
5381 CallStacks);
5382 });
5383 // Finalize the radix tree, write it out, and get the map of positions in
5384 // the linearized tree array.
5385 if (!CallStacks.empty()) {
5386 CallStackPos = writeMemoryProfileRadixTree(std::move(CallStacks), Stream,
5387 RadixAbbrev);
5388 }
5389 }
5390
5391 // Keep track of the current index into the CallStackPos map. Not used if
5392 // CombinedIndexMemProfContext is false.
5393 CallStackId CallStackCount = 0;
5394
5395 DenseSet<GlobalValue::GUID> DefOrUseGUIDs;
5396 forEachSummary([&](GVInfo I, bool IsAliasee) {
5397 GlobalValueSummary *S = I.second;
5398 assert(S);
5399 DefOrUseGUIDs.insert(I.first);
5400 for (const ValueInfo &VI : S->refs())
5401 DefOrUseGUIDs.insert(VI.getGUID());
5402
5403 auto ValueId = getValueId(I.first);
5404 assert(ValueId);
5405 SummaryToValueIdMap[S] = *ValueId;
5406
5407 // If this is invoked for an aliasee, we want to record the above
5408 // mapping, but then not emit a summary entry (if the aliasee is
5409 // to be imported, we will invoke this separately with IsAliasee=false).
5410 if (IsAliasee)
5411 return;
5412
5413 if (auto *AS = dyn_cast<AliasSummary>(S)) {
5414 // Will process aliases as a post-pass because the reader wants all
5415 // global to be loaded first.
5416 Aliases.push_back(AS);
5417 return;
5418 }
5419
5420 if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
5421 NameVals.push_back(*ValueId);
5422 assert(ModuleIdMap.count(VS->modulePath()));
5423 NameVals.push_back(ModuleIdMap[VS->modulePath()]);
5424 NameVals.push_back(
5425 getEncodedGVSummaryFlags(VS->flags(), shouldImportValueAsDecl(VS)));
5426 NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
5427 for (auto &RI : VS->refs()) {
5428 auto RefValueId = getValueId(RI.getGUID());
5429 if (!RefValueId)
5430 continue;
5431 NameVals.push_back(*RefValueId);
5432 }
5433
5434 // Emit the finished record.
5436 FSModRefsAbbrev);
5437 NameVals.clear();
5438 MaybeEmitOriginalName(*S);
5439 return;
5440 }
5441
5442 auto GetValueId = [&](const ValueInfo &VI) -> std::optional<unsigned> {
5443 if (!VI)
5444 return std::nullopt;
5445 return getValueId(VI.getGUID());
5446 };
5447
5448 auto *FS = cast<FunctionSummary>(S);
5449 writeFunctionTypeMetadataRecords(Stream, FS, GetValueId);
5450 getReferencedTypeIds(FS, ReferencedTypeIds);
5451
5452 NameVals.push_back(*ValueId);
5453 assert(ModuleIdMap.count(FS->modulePath()));
5454 NameVals.push_back(ModuleIdMap[FS->modulePath()]);
5455 NameVals.push_back(
5456 getEncodedGVSummaryFlags(FS->flags(), shouldImportValueAsDecl(FS)));
5457 NameVals.push_back(FS->instCount());
5458 NameVals.push_back(getEncodedFFlags(FS->fflags()));
5459 // TODO: Stop writing entry count and bump bitcode version.
5460 NameVals.push_back(0 /* EntryCount */);
5461
5462 // Fill in below
5463 NameVals.push_back(0); // numrefs
5464 NameVals.push_back(0); // rorefcnt
5465 NameVals.push_back(0); // worefcnt
5466
5467 unsigned Count = 0, RORefCnt = 0, WORefCnt = 0;
5468 for (auto &RI : FS->refs()) {
5469 auto RefValueId = getValueId(RI.getGUID());
5470 if (!RefValueId)
5471 continue;
5472 NameVals.push_back(*RefValueId);
5473 if (RI.isReadOnly())
5474 RORefCnt++;
5475 else if (RI.isWriteOnly())
5476 WORefCnt++;
5477 Count++;
5478 }
5479 NameVals[6] = Count;
5480 NameVals[7] = RORefCnt;
5481 NameVals[8] = WORefCnt;
5482
5483 for (auto &EI : FS->calls()) {
5484 // If this GUID doesn't have a value id, it doesn't have a function
5485 // summary and we don't need to record any calls to it.
5486 std::optional<unsigned> CallValueId = GetValueId(EI.first);
5487 if (!CallValueId)
5488 continue;
5489 NameVals.push_back(*CallValueId);
5490 NameVals.push_back(getEncodedHotnessCallEdgeInfo(EI.second));
5491 }
5492
5493 // Emit the finished record.
5494 Stream.EmitRecord(bitc::FS_COMBINED_PROFILE, NameVals,
5495 FSCallsProfileAbbrev);
5496 NameVals.clear();
5497
5499 Stream, FS, CallsiteAbbrev, AllocAbbrev, /*ContextIdAbbvId*/ 0,
5500 /*PerModule*/ false,
5501 /*GetValueId*/
5502 [&](const ValueInfo &VI) -> unsigned {
5503 std::optional<unsigned> ValueID = GetValueId(VI);
5504 // This can happen in shared index files for distributed ThinLTO if
5505 // the callee function summary is not included. Record 0 which we
5506 // will have to deal with conservatively when doing any kind of
5507 // validation in the ThinLTO backends.
5508 if (!ValueID)
5509 return 0;
5510 return *ValueID;
5511 },
5512 /*GetStackIndex*/
5513 [&](unsigned I) {
5514 // Get the corresponding index into the list of StackIds actually
5515 // being written for this combined index (which may be a subset in
5516 // the case of distributed indexes).
5517 assert(StackIdIndicesToIndex.contains(I));
5518 return StackIdIndicesToIndex[I];
5519 },
5520 /*WriteContextSizeInfoIndex*/ false, CallStackPos, CallStackCount);
5521
5522 MaybeEmitOriginalName(*S);
5523 });
5524
5525 for (auto *AS : Aliases) {
5526 auto AliasValueId = SummaryToValueIdMap[AS];
5527 assert(AliasValueId);
5528 NameVals.push_back(AliasValueId);
5529 assert(ModuleIdMap.count(AS->modulePath()));
5530 NameVals.push_back(ModuleIdMap[AS->modulePath()]);
5531 NameVals.push_back(
5532 getEncodedGVSummaryFlags(AS->flags(), shouldImportValueAsDecl(AS)));
5533 // Set value id to 0 when an alias is imported but the aliasee summary is
5534 // not contained in the index.
5535 auto AliaseeValueId =
5536 AS->hasAliasee() ? SummaryToValueIdMap[&AS->getAliasee()] : 0;
5537 NameVals.push_back(AliaseeValueId);
5538
5539 // Emit the finished record.
5540 Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
5541 NameVals.clear();
5542 MaybeEmitOriginalName(*AS);
5543
5544 if (AS->hasAliasee())
5545 if (auto *FS = dyn_cast<FunctionSummary>(&AS->getAliasee()))
5546 getReferencedTypeIds(FS, ReferencedTypeIds);
5547 }
5548
5550 auto EmitCfiFunctions = [&](const CfiFunctionIndex &CfiIndex,
5552 if (CfiIndex.empty())
5553 return;
5554 for (GlobalValue::GUID GUID : DefOrUseGUIDs) {
5555 auto Names = CfiIndex.getNamesForGUID(GUID);
5556 for (StringRef Name : Names)
5557 Functions.push_back({Name, GUID});
5558 }
5559 if (Functions.empty())
5560 return;
5561 llvm::sort(Functions);
5562 for (const auto &Record : Functions) {
5563 NameVals.push_back(Record.second);
5564 NameVals.push_back(StrtabBuilder.add(Record.first));
5565 NameVals.push_back(Record.first.size());
5566 }
5567 Stream.EmitRecord(Code, NameVals);
5568 NameVals.clear();
5569 Functions.clear();
5570 };
5571
5572 EmitCfiFunctions(Index.cfiFunctionDefs(), bitc::FS_CFI_FUNCTION_DEFS);
5573 EmitCfiFunctions(Index.cfiFunctionDecls(), bitc::FS_CFI_FUNCTION_DECLS);
5574
5575 // Walk the GUIDs that were referenced, and write the
5576 // corresponding type id records.
5577 for (auto &T : ReferencedTypeIds) {
5578 auto TidIter = Index.typeIds().equal_range(T);
5579 for (const auto &[GUID, TypeIdPair] : make_range(TidIter)) {
5580 writeTypeIdSummaryRecord(NameVals, StrtabBuilder, TypeIdPair.first,
5581 TypeIdPair.second);
5582 Stream.EmitRecord(bitc::FS_TYPE_ID, NameVals);
5583 NameVals.clear();
5584 }
5585 }
5586
5587 if (Index.getBlockCount())
5589 ArrayRef<uint64_t>{Index.getBlockCount()});
5590
5591 Stream.ExitBlock();
5592}
5593
5594/// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
5595/// current llvm version, and a record for the epoch number.
5598
5599 // Write the "user readable" string identifying the bitcode producer
5600 auto Abbv = std::make_shared<BitCodeAbbrev>();
5604 auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5606 "LLVM" LLVM_VERSION_STRING, StringAbbrev);
5607
5608 // Write the epoch version
5609 Abbv = std::make_shared<BitCodeAbbrev>();
5612 auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5613 constexpr std::array<unsigned, 1> Vals = {{bitc::BITCODE_CURRENT_EPOCH}};
5614 Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
5615 Stream.ExitBlock();
5616}
5617
5618void ModuleBitcodeWriter::writeModuleHash(StringRef View) {
5619 // Emit the module's hash.
5620 // MODULE_CODE_HASH: [5*i32]
5621 if (GenerateHash) {
5622 uint32_t Vals[5];
5623 Hasher.update(ArrayRef<uint8_t>(
5624 reinterpret_cast<const uint8_t *>(View.data()), View.size()));
5625 std::array<uint8_t, 20> Hash = Hasher.result();
5626 for (int Pos = 0; Pos < 20; Pos += 4) {
5627 Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);
5628 }
5629
5630 // Emit the finished record.
5631 Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
5632
5633 if (ModHash)
5634 // Save the written hash value.
5635 llvm::copy(Vals, std::begin(*ModHash));
5636 }
5637}
5638
5639void ModuleBitcodeWriter::write() {
5641
5643 // We will want to write the module hash at this point. Block any flushing so
5644 // we can have access to the whole underlying data later.
5645 Stream.markAndBlockFlushing();
5646
5647 writeModuleVersion();
5648
5649 // Emit blockinfo, which defines the standard abbreviations etc.
5650 writeBlockInfo();
5651
5652 // Emit information describing all of the types in the module.
5653 writeTypeTable();
5654
5655 // Emit information about attribute groups.
5656 writeAttributeGroupTable();
5657
5658 // Emit information about parameter attributes.
5659 writeAttributeTable();
5660
5661 writeComdats();
5662
5663 // Emit top-level description of module, including target triple, inline asm,
5664 // descriptors for global variables, and function prototype info.
5665 writeModuleInfo();
5666
5667 // Emit constants.
5668 writeModuleConstants();
5669
5670 // Emit metadata kind names.
5671 writeModuleMetadataKinds();
5672
5673 // Emit metadata.
5674 writeModuleMetadata();
5675
5676 // Emit module-level use-lists.
5678 writeUseListBlock(nullptr);
5679
5680 writeOperandBundleTags();
5681 writeSyncScopeNames();
5682
5683 // Emit function bodies.
5684 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
5685 for (const Function &F : M)
5686 if (!F.isDeclaration())
5687 writeFunction(F, FunctionToBitcodeIndex);
5688
5689 // Need to write after the above call to WriteFunction which populates
5690 // the summary information in the index.
5691 if (Index)
5692 writePerModuleGlobalValueSummary();
5693
5694 writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
5695
5696 writeModuleHash(Stream.getMarkedBufferAndResumeFlushing());
5697
5698 Stream.ExitBlock();
5699}
5700
5702 uint32_t &Position) {
5703 support::endian::write32le(&Buffer[Position], Value);
5704 Position += 4;
5705}
5706
5707/// If generating a bc file on darwin, we have to emit a
5708/// header and trailer to make it compatible with the system archiver. To do
5709/// this we emit the following header, and then emit a trailer that pads the
5710/// file out to be a multiple of 16 bytes.
5711///
5712/// struct bc_header {
5713/// uint32_t Magic; // 0x0B17C0DE
5714/// uint32_t Version; // Version, currently always 0.
5715/// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
5716/// uint32_t BitcodeSize; // Size of traditional bitcode file.
5717/// uint32_t CPUType; // CPU specifier.
5718/// ... potentially more later ...
5719/// };
5721 const Triple &TT) {
5722 unsigned CPUType = ~0U;
5723
5724 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
5725 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
5726 // number from /usr/include/mach/machine.h. It is ok to reproduce the
5727 // specific constants here because they are implicitly part of the Darwin ABI.
5728 enum {
5729 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
5730 DARWIN_CPU_TYPE_X86 = 7,
5731 DARWIN_CPU_TYPE_ARM = 12,
5732 DARWIN_CPU_TYPE_POWERPC = 18
5733 };
5734
5735 Triple::ArchType Arch = TT.getArch();
5736 if (Arch == Triple::x86_64)
5737 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
5738 else if (Arch == Triple::x86)
5739 CPUType = DARWIN_CPU_TYPE_X86;
5740 else if (Arch == Triple::ppc)
5741 CPUType = DARWIN_CPU_TYPE_POWERPC;
5742 else if (Arch == Triple::ppc64)
5743 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
5744 else if (Arch == Triple::arm || Arch == Triple::thumb)
5745 CPUType = DARWIN_CPU_TYPE_ARM;
5746
5747 // Traditional Bitcode starts after header.
5748 assert(Buffer.size() >= BWH_HeaderSize &&
5749 "Expected header size to be reserved");
5750 unsigned BCOffset = BWH_HeaderSize;
5751 unsigned BCSize = Buffer.size() - BWH_HeaderSize;
5752
5753 // Write the magic and version.
5754 unsigned Position = 0;
5755 writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
5756 writeInt32ToBuffer(0, Buffer, Position); // Version.
5757 writeInt32ToBuffer(BCOffset, Buffer, Position);
5758 writeInt32ToBuffer(BCSize, Buffer, Position);
5759 writeInt32ToBuffer(CPUType, Buffer, Position);
5760
5761 // If the file is not a multiple of 16 bytes, insert dummy padding.
5762 while (Buffer.size() & 15)
5763 Buffer.push_back(0);
5764}
5765
5766/// Helper to write the header common to all bitcode files.
5768 // Emit the file header.
5769 Stream.Emit((unsigned)'B', 8);
5770 Stream.Emit((unsigned)'C', 8);
5771 Stream.Emit(0x0, 4);
5772 Stream.Emit(0xC, 4);
5773 Stream.Emit(0xE, 4);
5774 Stream.Emit(0xD, 4);
5775}
5776
5778 : Stream(new BitstreamWriter(Buffer)) {
5779 writeBitcodeHeader(*Stream);
5780}
5781
5783 : Stream(new BitstreamWriter(FS, FlushThreshold)) {
5784 writeBitcodeHeader(*Stream);
5785}
5786
5788
5789void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) {
5790 Stream->EnterSubblock(Block, 3);
5791
5792 auto Abbv = std::make_shared<BitCodeAbbrev>();
5793 Abbv->Add(BitCodeAbbrevOp(Record));
5795 auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv));
5796
5797 Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob);
5798
5799 Stream->ExitBlock();
5800}
5801
5803 assert(!WroteStrtab && !WroteSymtab);
5804
5805 // If any module has module-level inline asm, we will require a registered asm
5806 // parser for the target so that we can create an accurate symbol table for
5807 // the module.
5808 for (Module *M : Mods) {
5809 if (M->getModuleInlineAsm().empty())
5810 continue;
5811
5812 std::string Err;
5813 const Triple TT(M->getTargetTriple());
5814 const Target *T = TargetRegistry::lookupTarget(TT, Err);
5815 if (!T || !T->hasMCAsmParser())
5816 return;
5817 }
5818
5819 WroteSymtab = true;
5820 SmallVector<char, 0> Symtab;
5821 // The irsymtab::build function may be unable to create a symbol table if the
5822 // module is malformed (e.g. it contains an invalid alias). Writing a symbol
5823 // table is not required for correctness, but we still want to be able to
5824 // write malformed modules to bitcode files, so swallow the error.
5825 if (Error E = irsymtab::build(Mods, Symtab, StrtabBuilder, Alloc)) {
5826 consumeError(std::move(E));
5827 return;
5828 }
5829
5831 {Symtab.data(), Symtab.size()});
5832}
5833
5835 assert(!WroteStrtab);
5836
5837 std::vector<char> Strtab;
5838 StrtabBuilder.finalizeInOrder();
5839 Strtab.resize(StrtabBuilder.getSize());
5840 StrtabBuilder.write((uint8_t *)Strtab.data());
5841
5843 {Strtab.data(), Strtab.size()});
5844
5845 WroteStrtab = true;
5846}
5847
5849 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab);
5850 WroteStrtab = true;
5851}
5852
5854 bool ShouldPreserveUseListOrder,
5855 const ModuleSummaryIndex *Index,
5856 bool GenerateHash, ModuleHash *ModHash) {
5857 assert(!WroteStrtab);
5858
5859 // The Mods vector is used by irsymtab::build, which requires non-const
5860 // Modules in case it needs to materialize metadata. But the bitcode writer
5861 // requires that the module is materialized, so we can cast to non-const here,
5862 // after checking that it is in fact materialized.
5863 assert(M.isMaterialized());
5864 Mods.push_back(const_cast<Module *>(&M));
5865
5866 ModuleBitcodeWriter ModuleWriter(M, StrtabBuilder, *Stream,
5867 ShouldPreserveUseListOrder, Index,
5868 GenerateHash, ModHash);
5869 ModuleWriter.write();
5870}
5871
5873 const ModuleSummaryIndex *Index,
5874 const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex,
5875 const GVSummaryPtrSet *DecSummaries) {
5876 IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index, DecSummaries,
5877 ModuleToSummariesForIndex);
5878 IndexWriter.write();
5879}
5880
5881/// Write the specified module to the specified output stream.
5883 bool ShouldPreserveUseListOrder,
5884 const ModuleSummaryIndex *Index,
5885 bool GenerateHash, ModuleHash *ModHash) {
5886 auto Write = [&](BitcodeWriter &Writer) {
5887 Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
5888 ModHash);
5889 Writer.writeSymtab();
5890 Writer.writeStrtab();
5891 };
5892 Triple TT(M.getTargetTriple());
5893 if (TT.isOSDarwin() || TT.isOSBinFormatMachO()) {
5894 // If this is darwin or another generic macho target, reserve space for the
5895 // header. Note that the header is computed *after* the output is known, so
5896 // we currently explicitly use a buffer, write to it, and then subsequently
5897 // flush to Out.
5898 SmallVector<char, 0> Buffer;
5899 Buffer.reserve(256 * 1024);
5900 Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
5901 BitcodeWriter Writer(Buffer);
5902 Write(Writer);
5903 emitDarwinBCHeaderAndTrailer(Buffer, TT);
5904 Out.write(Buffer.data(), Buffer.size());
5905 } else {
5906 BitcodeWriter Writer(
5907 Out, getBitWriterOptions(M.getContext()).bitcode_flush_threshold);
5908 Write(Writer);
5909 }
5910}
5911
5912void IndexBitcodeWriter::write() {
5914
5915 writeModuleVersion();
5916
5917 // Write the module paths in the combined index.
5918 writeModStrings();
5919
5920 // Write the summary combined index records.
5921 writeCombinedGlobalValueSummary();
5922
5923 Stream.ExitBlock();
5924}
5925
5926// Write the specified module summary index to the given raw output stream,
5927// where it will be written in a new bitcode block. This is used when
5928// writing the combined index file for ThinLTO. When writing a subset of the
5929// index for a distributed backend, provide a \p ModuleToSummariesForIndex map.
5931 const ModuleSummaryIndex &Index, raw_ostream &Out,
5932 const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex,
5933 const GVSummaryPtrSet *DecSummaries) {
5934 SmallVector<char, 0> Buffer;
5935 Buffer.reserve(256 * 1024);
5936
5937 BitcodeWriter Writer(Buffer);
5938 Writer.writeIndex(&Index, ModuleToSummariesForIndex, DecSummaries);
5939 Writer.writeStrtab();
5940
5941 Out.write((char *)&Buffer.front(), Buffer.size());
5942}
5943
5944namespace {
5945
5946/// Class to manage the bitcode writing for a thin link bitcode file.
5947class ThinLinkBitcodeWriter : public ModuleBitcodeWriterBase {
5948 /// ModHash is for use in ThinLTO incremental build, generated while writing
5949 /// the module bitcode file.
5950 const ModuleHash *ModHash;
5951
5952public:
5953 ThinLinkBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder,
5954 BitstreamWriter &Stream,
5955 const ModuleSummaryIndex &Index,
5956 const ModuleHash &ModHash)
5957 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
5958 /*ShouldPreserveUseListOrder=*/false, &Index),
5959 ModHash(&ModHash) {}
5960
5961 void write();
5962
5963private:
5964 void writeSimplifiedModuleInfo();
5965};
5966
5967} // end anonymous namespace
5968
5969// This function writes a simpilified module info for thin link bitcode file.
5970// It only contains the source file name along with the name(the offset and
5971// size in strtab) and linkage for global values. For the global value info
5972// entry, in order to keep linkage at offset 5, there are three zeros used
5973// as padding.
5974void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {
5976 // Emit the module's source file name.
5977 {
5978 StringEncoding Bits = getStringEncoding(M.getSourceFileName());
5980 if (Bits == SE_Char6)
5981 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
5982 else if (Bits == SE_Fixed7)
5983 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
5984
5985 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
5986 auto Abbv = std::make_shared<BitCodeAbbrev>();
5989 Abbv->Add(AbbrevOpToUse);
5990 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5991
5992 for (const auto P : M.getSourceFileName())
5993 Vals.push_back((unsigned char)P);
5994
5995 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
5996 Vals.clear();
5997 }
5998
5999 writeGUIDList();
6000
6001 // Emit the global variable information.
6002 for (const GlobalVariable &GV : M.globals()) {
6003 // GLOBALVAR: [strtab offset, strtab size, 0, 0, 0, linkage]
6004 Vals.push_back(StrtabBuilder.add(GV.getName()));
6005 Vals.push_back(GV.getName().size());
6006 Vals.push_back(0);
6007 Vals.push_back(0);
6008 Vals.push_back(0);
6009 Vals.push_back(getEncodedLinkage(GV));
6010
6012 Vals.clear();
6013 }
6014
6015 // Emit the function proto information.
6016 for (const Function &F : M) {
6017 // FUNCTION: [strtab offset, strtab size, 0, 0, 0, linkage]
6018 Vals.push_back(StrtabBuilder.add(F.getName()));
6019 Vals.push_back(F.getName().size());
6020 Vals.push_back(0);
6021 Vals.push_back(0);
6022 Vals.push_back(0);
6024
6026 Vals.clear();
6027 }
6028
6029 // Emit the alias information.
6030 for (const GlobalAlias &A : M.aliases()) {
6031 // ALIAS: [strtab offset, strtab size, 0, 0, 0, linkage]
6032 Vals.push_back(StrtabBuilder.add(A.getName()));
6033 Vals.push_back(A.getName().size());
6034 Vals.push_back(0);
6035 Vals.push_back(0);
6036 Vals.push_back(0);
6038
6039 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals);
6040 Vals.clear();
6041 }
6042
6043 // Emit the ifunc information.
6044 for (const GlobalIFunc &I : M.ifuncs()) {
6045 // IFUNC: [strtab offset, strtab size, 0, 0, 0, linkage]
6046 Vals.push_back(StrtabBuilder.add(I.getName()));
6047 Vals.push_back(I.getName().size());
6048 Vals.push_back(0);
6049 Vals.push_back(0);
6050 Vals.push_back(0);
6052
6053 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
6054 Vals.clear();
6055 }
6056}
6057
6058void ThinLinkBitcodeWriter::write() {
6060
6061 writeModuleVersion();
6062
6063 writeSimplifiedModuleInfo();
6064
6065 writePerModuleGlobalValueSummary();
6066
6067 // Write module hash.
6069
6070 Stream.ExitBlock();
6071}
6072
6074 const ModuleSummaryIndex &Index,
6075 const ModuleHash &ModHash) {
6076 assert(!WroteStrtab);
6077
6078 // The Mods vector is used by irsymtab::build, which requires non-const
6079 // Modules in case it needs to materialize metadata. But the bitcode writer
6080 // requires that the module is materialized, so we can cast to non-const here,
6081 // after checking that it is in fact materialized.
6082 assert(M.isMaterialized());
6083 Mods.push_back(const_cast<Module *>(&M));
6084
6085 ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index,
6086 ModHash);
6087 ThinLinkWriter.write();
6088}
6089
6090// Write the specified thin link bitcode file to the given raw output stream,
6091// where it will be written in a new bitcode block. This is used when
6092// writing the per-module index file for ThinLTO.
6094 const ModuleSummaryIndex &Index,
6095 const ModuleHash &ModHash) {
6096 SmallVector<char, 0> Buffer;
6097 Buffer.reserve(256 * 1024);
6098
6099 BitcodeWriter Writer(Buffer);
6100 Writer.writeThinLinkBitcode(M, Index, ModHash);
6101 Writer.writeSymtab();
6102 Writer.writeStrtab();
6103
6104 Out.write((char *)&Buffer.front(), Buffer.size());
6105}
6106
6107static const char *getSectionNameForBitcode(const Triple &T) {
6108 switch (T.getObjectFormat()) {
6109 case Triple::MachO:
6110 return "__LLVM,__bitcode";
6111 case Triple::COFF:
6112 case Triple::ELF:
6113 case Triple::Wasm:
6115 return ".llvmbc";
6116 case Triple::GOFF:
6117 llvm_unreachable("GOFF is not yet implemented");
6118 break;
6119 case Triple::SPIRV:
6120 if (T.getVendor() == Triple::AMD)
6121 return ".llvmbc";
6122 llvm_unreachable("SPIRV is not yet implemented");
6123 break;
6124 case Triple::XCOFF:
6125 llvm_unreachable("XCOFF is not yet implemented");
6126 break;
6128 llvm_unreachable("DXContainer is not yet implemented");
6129 break;
6130 }
6131 llvm_unreachable("Unimplemented ObjectFormatType");
6132}
6133
6134static const char *getSectionNameForCommandline(const Triple &T) {
6135 switch (T.getObjectFormat()) {
6136 case Triple::MachO:
6137 return "__LLVM,__cmdline";
6138 case Triple::COFF:
6139 case Triple::ELF:
6140 case Triple::Wasm:
6142 return ".llvmcmd";
6143 case Triple::GOFF:
6144 llvm_unreachable("GOFF is not yet implemented");
6145 break;
6146 case Triple::SPIRV:
6147 if (T.getVendor() == Triple::AMD)
6148 return ".llvmcmd";
6149 llvm_unreachable("SPIRV is not yet implemented");
6150 break;
6151 case Triple::XCOFF:
6152 llvm_unreachable("XCOFF is not yet implemented");
6153 break;
6155 llvm_unreachable("DXC is not yet implemented");
6156 break;
6157 }
6158 llvm_unreachable("Unimplemented ObjectFormatType");
6159}
6160
6162 bool EmbedBitcode, bool EmbedCmdline,
6163 const std::vector<uint8_t> &CmdArgs) {
6164 // Save llvm.compiler.used and remove it.
6167 GlobalVariable *Used = collectUsedGlobalVariables(M, UsedGlobals, true);
6168 Type *UsedElementType = Used ? Used->getValueType()->getArrayElementType()
6169 : PointerType::getUnqual(M.getContext());
6170 for (auto *GV : UsedGlobals) {
6171 if (GV->getName() != "llvm.embedded.module" &&
6172 GV->getName() != "llvm.cmdline")
6173 UsedArray.push_back(
6175 }
6176 if (Used)
6177 Used->eraseFromParent();
6178
6179 // Embed the bitcode for the llvm module.
6180 std::string Data;
6181 ArrayRef<uint8_t> ModuleData;
6182 Triple T(M.getTargetTriple());
6183
6184 if (EmbedBitcode) {
6185 if (Buf.getBufferSize() == 0 ||
6186 !isBitcode((const unsigned char *)Buf.getBufferStart(),
6187 (const unsigned char *)Buf.getBufferEnd())) {
6188 // If the input is LLVM Assembly, bitcode is produced by serializing
6189 // the module. Use-lists order need to be preserved in this case.
6191 llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true);
6192 ModuleData =
6193 ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
6194 } else
6195 // If the input is LLVM bitcode, write the input byte stream directly.
6196 ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
6197 Buf.getBufferSize());
6198 }
6199 llvm::Constant *ModuleConstant =
6200 llvm::ConstantDataArray::get(M.getContext(), ModuleData);
6202 M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
6203 ModuleConstant);
6205 // Set alignment to 1 to prevent padding between two contributions from input
6206 // sections after linking.
6207 GV->setAlignment(Align(1));
6208 UsedArray.push_back(
6210 if (llvm::GlobalVariable *Old =
6211 M.getGlobalVariable("llvm.embedded.module", true)) {
6212 assert(Old->hasZeroLiveUses() &&
6213 "llvm.embedded.module can only be used once in llvm.compiler.used");
6214 GV->takeName(Old);
6215 Old->eraseFromParent();
6216 } else {
6217 GV->setName("llvm.embedded.module");
6218 }
6219
6220 // Skip if only bitcode needs to be embedded.
6221 if (EmbedCmdline) {
6222 // Embed command-line options.
6223 ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CmdArgs.data()),
6224 CmdArgs.size());
6225 llvm::Constant *CmdConstant =
6226 llvm::ConstantDataArray::get(M.getContext(), CmdData);
6227 GV = new llvm::GlobalVariable(M, CmdConstant->getType(), true,
6229 CmdConstant);
6231 GV->setAlignment(Align(1));
6232 UsedArray.push_back(
6234 if (llvm::GlobalVariable *Old = M.getGlobalVariable("llvm.cmdline", true)) {
6235 assert(Old->hasZeroLiveUses() &&
6236 "llvm.cmdline can only be used once in llvm.compiler.used");
6237 GV->takeName(Old);
6238 Old->eraseFromParent();
6239 } else {
6240 GV->setName("llvm.cmdline");
6241 }
6242 }
6243
6244 if (UsedArray.empty())
6245 return;
6246
6247 // Recreate llvm.compiler.used.
6248 ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
6249 auto *NewUsed = new GlobalVariable(
6251 llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
6252 NewUsed->setSection("llvm.metadata");
6253}
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the StringMap class.
uint64_t uint64_t
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static void writeDIMacro(raw_ostream &Out, const DIMacro *N, AsmWriterContext &WriterCtx)
static void writeDIGlobalVariableExpression(raw_ostream &Out, const DIGlobalVariableExpression *N, AsmWriterContext &WriterCtx)
static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N, AsmWriterContext &WriterCtx)
static void writeDIFixedPointType(raw_ostream &Out, const DIFixedPointType *N, AsmWriterContext &WriterCtx)
static void writeDISubrangeType(raw_ostream &Out, const DISubrangeType *N, AsmWriterContext &WriterCtx)
static void writeDIStringType(raw_ostream &Out, const DIStringType *N, AsmWriterContext &WriterCtx)
static void writeDILayerLocList(raw_ostream &Out, const DILayerLocList *N, AsmWriterContext &WriterCtx)
static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N, AsmWriterContext &WriterCtx)
static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N, AsmWriterContext &WriterCtx)
static void writeDILayerLoc(raw_ostream &Out, const DILayerLoc *N, AsmWriterContext &WriterCtx)
static void writeDIModule(raw_ostream &Out, const DIModule *N, AsmWriterContext &WriterCtx)
static void writeDIFile(raw_ostream &Out, const DIFile *N, AsmWriterContext &)
static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N, AsmWriterContext &WriterCtx)
static void writeDILabel(raw_ostream &Out, const DILabel *N, AsmWriterContext &WriterCtx)
static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N, AsmWriterContext &WriterCtx)
static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N, AsmWriterContext &WriterCtx)
static void writeMDFunctionLocalContext(raw_ostream &Out, const MDFunctionLocalContext *FLMD, AsmWriterContext &WriterCtx)
static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N, AsmWriterContext &WriterCtx)
static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N, AsmWriterContext &WriterCtx)
static void writeDILocation(raw_ostream &Out, const DILocation *DL, AsmWriterContext &WriterCtx)
static void writeDINamespace(raw_ostream &Out, const DINamespace *N, AsmWriterContext &WriterCtx)
static void writeDICommonBlock(raw_ostream &Out, const DICommonBlock *N, AsmWriterContext &WriterCtx)
static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N, AsmWriterContext &WriterCtx)
static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N, AsmWriterContext &WriterCtx)
static void writeDITemplateTypeParameter(raw_ostream &Out, const DITemplateTypeParameter *N, AsmWriterContext &WriterCtx)
static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N, AsmWriterContext &WriterCtx)
static void writeDIGenericSubrange(raw_ostream &Out, const DIGenericSubrange *N, AsmWriterContext &WriterCtx)
static void writeDISubrange(raw_ostream &Out, const DISubrange *N, AsmWriterContext &WriterCtx)
static void writeDIProperty(raw_ostream &Out, const DIProperty *N, AsmWriterContext &WriterCtx)
static void writeDILexicalBlockFile(raw_ostream &Out, const DILexicalBlockFile *N, AsmWriterContext &WriterCtx)
static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N, AsmWriterContext &)
static void writeMDTuple(raw_ostream &Out, const MDTuple *Node, AsmWriterContext &WriterCtx)
static void writeDIExpression(raw_ostream &Out, const DIExpression *N, AsmWriterContext &WriterCtx)
static void writeDIAssignID(raw_ostream &Out, const DIAssignID *DL, AsmWriterContext &WriterCtx)
static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N, AsmWriterContext &WriterCtx)
static void writeDIArgList(raw_ostream &Out, const DIArgList *N, AsmWriterContext &WriterCtx, bool FromValue=false)
static void writeDITemplateValueParameter(raw_ostream &Out, const DITemplateValueParameter *N, AsmWriterContext &WriterCtx)
static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N, AsmWriterContext &WriterCtx)
Atomic ordering constants.
This file contains the simple types necessary to represent the attributes associated with functions a...
static void writeFunctionHeapProfileRecords(BitstreamWriter &Stream, FunctionSummary *FS, unsigned CallsiteAbbrev, unsigned AllocAbbrev, unsigned ContextIdAbbvId, bool PerModule, std::function< unsigned(const ValueInfo &VI)> GetValueID, std::function< unsigned(unsigned)> GetStackIndex, bool WriteContextSizeInfoIndex, DenseMap< CallStackId, LinearCallStackId > &CallStackPos, CallStackId &CallStackCount)
static unsigned serializeSanitizerMetadata(const GlobalValue::SanitizerMetadata &Meta)
static void writeTypeIdCompatibleVtableSummaryRecord(SmallVector< uint64_t, 64 > &NameVals, StringTableBuilder &StrtabBuilder, StringRef Id, const TypeIdCompatibleVtableInfo &Summary, ValueEnumerator &VE)
static void getReferencedTypeIds(FunctionSummary *FS, std::set< GlobalValue::GUID > &ReferencedTypeIds)
Collect type IDs from type tests used by function.
static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind)
static void collectMemProfCallStacks(FunctionSummary *FS, std::function< LinearFrameId(unsigned)> GetStackIndex, MapVector< CallStackId, llvm::SmallVector< LinearFrameId > > &CallStacks)
static unsigned getEncodedUnaryOpcode(unsigned Opcode)
static void emitSignedInt64(SmallVectorImpl< uint64_t > &Vals, uint64_t V)
StringEncoding
@ SE_Char6
@ SE_Fixed7
@ SE_Fixed8
static unsigned getEncodedVisibility(const GlobalValue &GV)
static uint64_t getOptimizationFlags(const Value *V)
static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage)
static unsigned getEncodedThreadLocalMode(const GlobalValue &GV)
static DenseMap< CallStackId, LinearCallStackId > writeMemoryProfileRadixTree(MapVector< CallStackId, llvm::SmallVector< LinearFrameId > > &&CallStacks, BitstreamWriter &Stream, unsigned RadixAbbrev)
static void writeIdentificationBlock(BitstreamWriter &Stream)
Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the current llvm version,...
static unsigned getEncodedCastOpcode(unsigned Opcode)
static unsigned getEncodedOrdering(AtomicOrdering Ordering)
static unsigned getEncodedUnnamedAddr(const GlobalValue &GV)
static unsigned getEncodedComdatSelectionKind(const Comdat &C)
static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags, bool ImportAsDecl=false)
static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl< char > &Buffer, const Triple &TT)
If generating a bc file on darwin, we have to emit a header and trailer to make it compatible with th...
static void writeBitcodeHeader(BitstreamWriter &Stream)
Helper to write the header common to all bitcode files.
static void writeWholeProgramDevirtResolutionByArg(SmallVector< uint64_t, 64 > &NameVals, const std::vector< uint64_t > &args, const WholeProgramDevirtResolution::ByArg &ByArg)
static void emitConstantRange(SmallVectorImpl< uint64_t > &Record, const ConstantRange &CR, bool EmitBitWidth)
static StringEncoding getStringEncoding(StringRef Str)
Determine the encoding to use for the given string name and length.
static uint64_t getEncodedGVarFlags(GlobalVarSummary::GVarFlags Flags)
static const char * getSectionNameForCommandline(const Triple &T)
static void writeTypeIdSummaryRecord(SmallVector< uint64_t, 64 > &NameVals, StringTableBuilder &StrtabBuilder, StringRef Id, const TypeIdSummary &Summary)
static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream, FunctionSummary *FS, Fn GetValueID)
Write the function type metadata related records that need to appear before a function summary entry ...
static uint64_t getEncodedHotnessCallEdgeInfo(const CalleeInfo &CI)
static void emitWideAPInt(SmallVectorImpl< uint64_t > &Vals, const APInt &A)
static void writeStringRecord(BitstreamWriter &Stream, unsigned Code, StringRef Str, unsigned AbbrevToUse)
static unsigned getEncodedRMWOperation(const AtomicRMWInst &I)
static void writeWholeProgramDevirtResolution(SmallVector< uint64_t, 64 > &NameVals, StringTableBuilder &StrtabBuilder, uint64_t Id, const WholeProgramDevirtResolution &Wpd)
static unsigned getEncodedDLLStorageClass(const GlobalValue &GV)
static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl< char > &Buffer, uint32_t &Position)
MetadataAbbrev
@ LastPlusOne
static const char * getSectionNameForBitcode(const Triple &T)
static cl::opt< bool > CombinedIndexMemProfContext("combined-index-memprof-context", cl::Hidden, cl::init(true), cl::desc(""))
static unsigned getEncodedBinaryOpcode(unsigned Opcode)
static uint64_t getEncodedFFlags(FunctionSummary::FFlags Flags)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
DXIL Finalize Linkage
dxil translate DXIL Translate Metadata
This file defines the DenseMap class.
This file contains constants used for implementing Dwarf debug support.
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
Hexagon Common GEP
#define _
static MaybeAlign getAlign(Value *Ptr)
Module.h This file contains the declarations for the Module class.
static cl::opt< LTOBitcodeEmbedding > EmbedBitcode("lto-embed-bitcode", cl::init(LTOBitcodeEmbedding::DoNotEmbed), cl::values(clEnumValN(LTOBitcodeEmbedding::DoNotEmbed, "none", "Do not embed"), clEnumValN(LTOBitcodeEmbedding::EmbedOptimized, "optimized", "Embed after all optimization passes"), clEnumValN(LTOBitcodeEmbedding::EmbedPostMergePreOptimized, "post-merge-pre-opt", "Embed post merge, but before optimizations")), cl::desc("Embed LLVM bitcode in object files produced by LTO"))
if(!TBB||Cond.size()< 1) return false
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
#define H(x, y, z)
Definition MD5.cpp:56
Machine Check Debug Module
This file contains the declarations for metadata subclasses.
#define T
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
nvptx lower args
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
This file contains some templates that are useful if you are working with the STL at all.
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallString class.
This file defines the SmallVector class.
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static const uint32_t IV[8]
Definition blake3_impl.h:83
Class for arbitrary precision integers.
Definition APInt.h:78
unsigned getActiveWords() const
Compute the number of active words in the value of this APInt.
Definition APInt.h:1538
const uint64_t * getRawData() const
This function returns a pointer to the internal storage of the APInt.
Definition APInt.h:571
int64_t getSExtValue() const
Get sign extended value.
Definition APInt.h:1582
const GlobalValueSummary & getAliasee() const
bool isSwiftError() const
Return true if this alloca is used as a swifterror argument to a call.
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
bool isUsedWithInAlloca() const
Return true if this alloca is used as an inalloca argument to a call.
unsigned getAddressSpace() const
Return the address space for the allocation.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
Class to represent array types.
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
an instruction that atomically reads a memory location, combines it with another value,...
@ Add
*p = old + v
@ FAdd
*p = old + v
@ USubCond
Subtract only if no unsigned overflow.
@ FMinimum
*p = minimum(old, v) minimum matches the behavior of llvm.minimum.
@ Min
*p = old <signed v ? old : v
@ Sub
*p = old - v
@ And
*p = old & v
@ Xor
*p = old ^ v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ FMaximum
*p = maximum(old, v) maximum matches the behavior of llvm.maximum.
@ FSub
*p = old - v
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMaximumNum
*p = maximumnum(old, v) maximumnum matches the behavior of llvm.maximumnum.
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
@ FMinimumNum
*p = minimumnum(old, v) minimumnum matches the behavior of llvm.minimumnum.
@ Nand
*p = ~(old & v)
bool hasAttributes() const
Return true if attributes exists in this set.
Definition Attributes.h:526
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:125
@ None
No attributes have been set.
Definition Attributes.h:127
@ EndAttrKinds
Sentinel value useful for loops.
Definition Attributes.h:130
BitCodeAbbrevOp - This describes one or more operands in an abbreviation.
Definition BitCodes.h:34
static bool isChar6(char C)
isChar6 - Return true if this character is legal in the Char6 encoding.
Definition BitCodes.h:88
LLVM_ABI void writeThinLinkBitcode(const Module &M, const ModuleSummaryIndex &Index, const ModuleHash &ModHash)
Write the specified thin link bitcode file (i.e., the minimized bitcode file) to the buffer specified...
LLVM_ABI void writeIndex(const ModuleSummaryIndex *Index, const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex, const GVSummaryPtrSet *DecSummaries)
LLVM_ABI void copyStrtab(StringRef Strtab)
Copy the string table for another module into this bitcode file.
LLVM_ABI void writeStrtab()
Write the bitcode file's string table.
LLVM_ABI void writeSymtab()
Attempt to write a symbol table to the bitcode file.
LLVM_ABI void writeModule(const Module &M, bool ShouldPreserveUseListOrder=false, const ModuleSummaryIndex *Index=nullptr, bool GenerateHash=false, ModuleHash *ModHash=nullptr)
Write the specified module to the buffer specified at construction time.
LLVM_ABI BitcodeWriter(SmallVectorImpl< char > &Buffer)
Create a BitcodeWriter that writes to Buffer.
unsigned EmitAbbrev(std::shared_ptr< BitCodeAbbrev > Abbv)
Emits the abbreviation Abbv to the stream.
void markAndBlockFlushing()
For scenarios where the user wants to access a section of the stream to (for example) compute some ch...
StringRef getMarkedBufferAndResumeFlushing()
resumes flushing, but does not flush, and returns the section in the internal buffer starting from th...
void EmitRecord(unsigned Code, const Container &Vals, unsigned Abbrev=0)
EmitRecord - Emit the specified record to the stream, using an abbrev if we have one to compress the ...
void Emit(uint32_t Val, unsigned NumBits)
void EmitRecordWithBlob(unsigned Abbrev, const Container &Vals, StringRef Blob)
EmitRecordWithBlob - Emit the specified record to the stream, using an abbrev that includes a blob at...
unsigned EmitBlockInfoAbbrev(unsigned BlockID, std::shared_ptr< BitCodeAbbrev > Abbv)
EmitBlockInfoAbbrev - Emit a DEFINE_ABBREV record for the specified BlockID.
void EnterBlockInfoBlock()
EnterBlockInfoBlock - Start emitting the BLOCKINFO_BLOCK.
void BackpatchWord(uint64_t BitNo, unsigned Val)
void BackpatchWord64(uint64_t BitNo, uint64_t Val)
void EnterSubblock(unsigned BlockID, unsigned CodeLen)
uint64_t GetCurrentBitNo() const
Retrieve the current position in the stream, in bits.
void EmitRecordWithAbbrev(unsigned Abbrev, const Container &Vals)
EmitRecordWithAbbrev - Emit a record with the specified abbreviation.
static LLVM_ABI BlockAddress * lookup(const BasicBlock *BB)
Lookup an existing BlockAddress constant for the given BasicBlock.
OperandBundleUse getOperandBundleAt(unsigned Index) const
Return the operand bundle at a specific index.
unsigned getNumOperandBundles() const
Return the number of operand bundles associated with this User.
CallingConv::ID getCallingConv() const
Value * getCalledOperand() const
Value * getArgOperand(unsigned i) const
FunctionType * getFunctionType() const
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
bool hasOperandBundles() const
Return true if this User has any operand bundles.
BasicBlock * getIndirectDest(unsigned i) const
BasicBlock * getDefaultDest() const
unsigned getNumIndirectDests() const
Return the number of callbr indirect dest labels.
bool isNoTailCall() const
bool isTailCall() const
bool isMustTailCall() const
auto getNamesForGUID(GlobalValue::GUID GUID) const
get the name(s) associated with a given ThinLTO GUID.
@ Largest
The linker will choose the largest COMDAT.
Definition Comdat.h:39
@ SameSize
The data referenced by the COMDAT must be the same size.
Definition Comdat.h:41
@ Any
The linker may choose any COMDAT.
Definition Comdat.h:37
@ NoDeduplicate
No deduplication is performed.
Definition Comdat.h:40
@ ExactMatch
The data referenced by the COMDAT must be the same.
Definition Comdat.h:38
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)
get() constructor - Return a constant with array type with an element count and element type matching...
Definition Constants.h:878
static LLVM_ABI Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
This class represents a range of values.
const APInt & getLower() const
Return the lower value for this range.
const APInt & getUpper() const
Return the upper value for this range.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
This is an important base class in LLVM.
Definition Constant.h:44
DebugLoc getDebugLoc() const
LLVM_ABI DIAssignID * getAssignID() const
DIExpression * getExpression() const
DILocalVariable * getVariable() const
Metadata * getRawLocation() const
Returns the metadata operand for the first location description.
DIExpression * getAddressExpression() const
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:757
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:762
unsigned size() const
Definition DenseMap.h:717
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
idx_iterator idx_end() const
idx_iterator idx_begin() const
Function summary information to aid decisions and implementation of importing.
LLVM_ABI void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode * > > &MDs) const
Appends all metadata attached to this value to MDs, sorting by KindID.
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
Definition Globals.cpp:348
GVFlags flags() const
Get the flags for this GlobalValue (see struct GVFlags).
StringRef modulePath() const
Get the path to the module containing this function.
ArrayRef< ValueInfo > refs() const
Return the list of values referenced by this global value definition.
VisibilityTypes getVisibility() const
static bool isLocalLinkage(LinkageTypes Linkage)
LinkageTypes getLinkage() const
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
ThreadLocalMode getThreadLocalMode() const
@ DLLExportStorageClass
Function to be accessible from DLL.
Definition GlobalValue.h:77
@ DLLImportStorageClass
Function to be imported from DLL.
Definition GlobalValue.h:76
@ DefaultVisibility
The GV is visible.
Definition GlobalValue.h:68
@ HiddenVisibility
The GV is hidden.
Definition GlobalValue.h:69
@ ProtectedVisibility
The GV is protected.
Definition GlobalValue.h:70
UnnamedAddr getUnnamedAddr() const
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition GlobalValue.h:52
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition GlobalValue.h:61
@ CommonLinkage
Tentative definitions.
Definition GlobalValue.h:63
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
Definition GlobalValue.h:55
@ WeakODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:58
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition GlobalValue.h:57
@ AppendingLinkage
Special purpose, only applies to global arrays.
Definition GlobalValue.h:59
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition GlobalValue.h:54
@ ExternalWeakLinkage
ExternalWeak linkage description.
Definition GlobalValue.h:62
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:56
DLLStorageClassTypes getDLLStorageClass() const
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
idx_iterator idx_end() const
idx_iterator idx_begin() const
bool isCast() const
bool isCleanup() const
Return 'true' if this landingpad instruction is a cleanup.
unsigned getNumClauses() const
Get the number of clauses for this landing pad.
bool isCatch(unsigned Idx) const
Return 'true' if the clause and index Idx is a catch clause.
Constant * getClause(unsigned Idx) const
Get the value of the clause at index Idx.
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:39
bool empty() const
Definition MapVector.h:80
size_t getBufferSize() const
const char * getBufferStart() const
const char * getBufferEnd() const
Class to hold module path string table and global value map, and encapsulate methods for operating on...
static constexpr uint64_t BitcodeSummaryVersion
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
LLVM_ABI void update(ArrayRef< uint8_t > Data)
Digest more data.
Definition SHA1.cpp:208
LLVM_ABI std::array< uint8_t, 20 > result()
Return the current raw 160-bits SHA1 for the digested data since the last call to init().
Definition SHA1.cpp:288
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
bool empty() const
Determine if the SetVector is empty or not.
Definition SetVector.h:100
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
void append(StringRef RHS)
Append from a StringRef.
Definition SmallString.h:70
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void assign(size_type NumElts, ValueParamT Elt)
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
iterator insert(iterator I, T &&Elt)
void resize(size_type N)
void push_back(const T &Elt)
pointer data()
Return a pointer to the vector's buffer, even if empty().
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
const ValueTy & getValue() const
StringRef getKey() const
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
iterator begin() const
Definition StringRef.h:114
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
iterator end() const
Definition StringRef.h:116
Utility for building string tables with deduplicated suffixes.
size_t add(CachedHashStringRef S, uint8_t Priority=0)
Add a string to the builder.
Target - Wrapper for Target specific information.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
@ UnknownObjectFormat
Definition Triple.h:425
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isX86_FP80Ty() const
Return true if this is x86 long double.
Definition Type.h:161
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:155
bool isBFloatTy() const
Return true if this is 'bfloat', a 16-bit bfloat type.
Definition Type.h:147
bool isPPC_FP128Ty() const
Return true if this is powerpc long double.
Definition Type.h:167
bool isFP128Ty() const
Return true if this is 'fp128'.
Definition Type.h:164
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:370
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition Type.h:144
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
Definition Type.h:158
Value * getValue() const
Definition Metadata.h:511
std::vector< std::pair< const Value *, unsigned > > ValueList
unsigned getTypeID(Type *T) const
unsigned getMetadataID(const Metadata *MD) const
UseListOrderStack UseListOrders
ArrayRef< const Metadata * > getNonMDStrings() const
Get the non-MDString metadata for this block.
unsigned getInstructionID(const Instruction *I) const
unsigned getAttributeListID(AttributeList PAL) const
void incorporateFunction(const Function &F)
incorporateFunction/purgeFunction - If you'd like to deal with a function, use these two methods to g...
void getFunctionConstantRange(unsigned &Start, unsigned &End) const
getFunctionConstantRange - Return the range of values that corresponds to function-local constants.
unsigned getAttributeGroupID(IndexAndAttrSet Group) const
bool hasMDs() const
Check whether the current block has any metadata to emit.
unsigned getComdatID(const Comdat *C) const
uint64_t computeBitsRequiredForTypeIndices() const
unsigned getValueID(const Value *V) const
unsigned getMetadataOrNullID(const Metadata *MD) const
const std::vector< IndexAndAttrSet > & getAttributeGroups() const
const ValueList & getValues() const
unsigned getGlobalBasicBlockID(const BasicBlock *BB) const
getGlobalBasicBlockID - This returns the function-specific ID for the specified basic block.
void setInstructionID(const Instruction *I)
const std::vector< const BasicBlock * > & getBasicBlocks() const
const std::vector< AttributeList > & getAttributeLists() const
bool shouldPreserveUseListOrder() const
const ComdatSetType & getComdats() const
std::vector< Type * > TypeList
ArrayRef< const Metadata * > getMDStrings() const
Get the MDString metadata for this block.
std::pair< unsigned, AttributeSet > IndexAndAttrSet
Attribute groups as encoded in bitcode are almost AttributeSets, but they include the AttributeList i...
const TypeList & getTypes() const
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:389
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:395
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
void build(llvm::MapVector< CallStackId, llvm::SmallVector< FrameIdTy > > &&MemProfCallStackData, const llvm::DenseMap< FrameIdTy, LinearFrameId > *MemProfFrameIndexes, llvm::DenseMap< FrameIdTy, FrameStat > &FrameHistogram)
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
CallInst * Call
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
@ Entry
Definition COFF.h:862
Predicate getPredicate(unsigned Condition, unsigned Hint)
Return predicate consisting of specified condition and hint bits.
@ CE
Windows NT (Windows on ARM)
Definition MCAsmInfo.h:51
@ TYPE_CODE_TARGET_TYPE
@ TYPE_CODE_STRUCT_ANON
@ TYPE_CODE_STRUCT_NAME
@ TYPE_CODE_OPAQUE_POINTER
@ TYPE_CODE_STRUCT_NAMED
@ METADATA_COMMON_BLOCK
@ METADATA_TEMPLATE_VALUE
@ METADATA_LEXICAL_BLOCK_FILE
@ METADATA_INDEX_OFFSET
@ METADATA_LEXICAL_BLOCK
@ METADATA_SUBROUTINE_TYPE
@ METADATA_GLOBAL_DECL_ATTACHMENT
@ METADATA_OBJC_PROPERTY
@ METADATA_IMPORTED_ENTITY
@ METADATA_GENERIC_SUBRANGE
@ METADATA_COMPILE_UNIT
@ METADATA_COMPOSITE_TYPE
@ METADATA_FIXED_POINT_TYPE
@ METADATA_LAYERLOCLIST
@ METADATA_DERIVED_TYPE
@ METADATA_SUBRANGE_TYPE
@ METADATA_TEMPLATE_TYPE
@ METADATA_GLOBAL_VAR_EXPR
@ METADATA_DISTINCT_NODE
@ METADATA_GENERIC_DEBUG
GlobalValueSummarySymtabCodes
@ FS_CONTEXT_RADIX_TREE_ARRAY
@ FS_COMBINED_GLOBALVAR_INIT_REFS
@ FS_TYPE_CHECKED_LOAD_VCALLS
@ FS_COMBINED_ORIGINAL_NAME
@ FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS
@ FS_TYPE_TEST_ASSUME_CONST_VCALL
@ FS_PERMODULE_GLOBALVAR_INIT_REFS
@ FS_TYPE_TEST_ASSUME_VCALLS
@ FS_COMBINED_ALLOC_INFO_NO_CONTEXT
@ FS_CFI_FUNCTION_DECLS
@ FS_COMBINED_CALLSITE_INFO
@ FS_COMBINED_ALLOC_INFO
@ FS_PERMODULE_CALLSITE_INFO
@ FS_PERMODULE_ALLOC_INFO
@ FS_TYPE_CHECKED_LOAD_CONST_VCALL
@ BITCODE_CURRENT_EPOCH
@ IDENTIFICATION_CODE_EPOCH
@ IDENTIFICATION_CODE_STRING
@ CST_CODE_BLOCKADDRESS
@ CST_CODE_NO_CFI_VALUE
@ CST_CODE_CE_SHUFVEC_EX
@ CST_CODE_CE_EXTRACTELT
@ CST_CODE_CE_SHUFFLEVEC
@ CST_CODE_WIDE_INTEGER
@ CST_CODE_DSO_LOCAL_EQUIVALENT
@ CST_CODE_CE_INSERTELT
@ CST_CODE_CE_GEP_WITH_INRANGE
@ COMDAT_SELECTION_KIND_LARGEST
@ COMDAT_SELECTION_KIND_ANY
@ COMDAT_SELECTION_KIND_SAME_SIZE
@ COMDAT_SELECTION_KIND_EXACT_MATCH
@ COMDAT_SELECTION_KIND_NO_DUPLICATES
@ ATTR_KIND_STACK_PROTECT
@ ATTR_KIND_STACK_PROTECT_STRONG
@ ATTR_KIND_SANITIZE_MEMORY
@ ATTR_KIND_OPTIMIZE_FOR_SIZE
@ ATTR_KIND_SWIFT_ERROR
@ ATTR_KIND_NO_CALLBACK
@ ATTR_KIND_FNRETTHUNK_EXTERN
@ ATTR_KIND_NO_DIVERGENCE_SOURCE
@ ATTR_KIND_SANITIZE_ADDRESS
@ ATTR_KIND_NO_IMPLICIT_FLOAT
@ ATTR_KIND_DEAD_ON_UNWIND
@ ATTR_KIND_STACK_ALIGNMENT
@ ATTR_KIND_STACK_PROTECT_REQ
@ ATTR_KIND_INLINE_HINT
@ ATTR_KIND_NULL_POINTER_IS_VALID
@ ATTR_KIND_SANITIZE_HWADDRESS
@ ATTR_KIND_MUSTPROGRESS
@ ATTR_KIND_RETURNS_TWICE
@ ATTR_KIND_SHADOWCALLSTACK
@ ATTR_KIND_OPT_FOR_FUZZING
@ ATTR_KIND_DENORMAL_FPENV
@ ATTR_KIND_SANITIZE_NUMERICAL_STABILITY
@ ATTR_KIND_SANITIZE_CONCURRENCY
@ ATTR_KIND_INITIALIZES
@ ATTR_KIND_ALLOCATED_POINTER
@ ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION
@ ATTR_KIND_SKIP_PROFILE
@ ATTR_KIND_ELEMENTTYPE
@ ATTR_KIND_CORO_ELIDE_SAFE
@ ATTR_KIND_NO_DUPLICATE
@ ATTR_KIND_ALLOC_ALIGN
@ ATTR_KIND_NON_LAZY_BIND
@ ATTR_KIND_DEREFERENCEABLE
@ ATTR_KIND_ALWAYS_UNIFORM
@ ATTR_KIND_LIKELY_MODULE_LOCAL
@ ATTR_KIND_OPTIMIZE_NONE
@ ATTR_KIND_HYBRID_PATCHABLE
@ ATTR_KIND_NO_RED_ZONE
@ ATTR_KIND_DEREFERENCEABLE_OR_NULL
@ ATTR_KIND_SANITIZE_REALTIME
@ ATTR_KIND_SPECULATIVE_LOAD_HARDENING
@ ATTR_KIND_ALWAYS_INLINE
@ ATTR_KIND_SANITIZE_TYPE
@ ATTR_KIND_PRESPLIT_COROUTINE
@ ATTR_KIND_VSCALE_RANGE
@ ATTR_KIND_SANITIZE_ALLOC_TOKEN
@ ATTR_KIND_NO_SANITIZE_COVERAGE
@ ATTR_KIND_NO_CREATE_UNDEF_OR_POISON
@ ATTR_KIND_SPECULATABLE
@ ATTR_KIND_DEAD_ON_RETURN
@ ATTR_KIND_SANITIZE_REALTIME_BLOCKING
@ ATTR_KIND_NO_SANITIZE_BOUNDS
@ ATTR_KIND_SANITIZE_MEMTAG
@ ATTR_KIND_CORO_ONLY_DESTROY_WHEN_COMPLETE
@ ATTR_KIND_SANITIZE_THREAD
@ ATTR_KIND_OPTIMIZE_FOR_DEBUGGING
@ ATTR_KIND_PREALLOCATED
@ ATTR_KIND_SWIFT_ASYNC
@ SYNC_SCOPE_NAMES_BLOCK_ID
@ PARAMATTR_GROUP_BLOCK_ID
@ METADATA_KIND_BLOCK_ID
@ IDENTIFICATION_BLOCK_ID
@ GLOBALVAL_SUMMARY_BLOCK_ID
@ METADATA_ATTACHMENT_ID
@ FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID
@ MODULE_STRTAB_BLOCK_ID
@ VALUE_SYMTAB_BLOCK_ID
@ OPERAND_BUNDLE_TAGS_BLOCK_ID
@ MODULE_CODE_VERSION
@ MODULE_CODE_SOURCE_FILENAME
@ MODULE_CODE_SECTIONNAME
@ MODULE_CODE_DATALAYOUT
@ MODULE_CODE_GLOBALVAR
@ MODULE_CODE_VSTOFFSET
@ MODULE_CODE_ASM_PROPERTY
@ FUNC_CODE_INST_CATCHRET
@ FUNC_CODE_INST_LANDINGPAD
@ FUNC_CODE_INST_EXTRACTVAL
@ FUNC_CODE_INST_CATCHPAD
@ FUNC_CODE_INST_RESUME
@ FUNC_CODE_INST_CALLBR
@ FUNC_CODE_INST_CATCHSWITCH
@ FUNC_CODE_INST_VSELECT
@ FUNC_CODE_INST_CLEANUPRET
@ FUNC_CODE_DEBUG_RECORD_VALUE
@ FUNC_CODE_INST_LOADATOMIC
@ FUNC_CODE_DEBUG_RECORD_ASSIGN
@ FUNC_CODE_INST_STOREATOMIC
@ FUNC_CODE_INST_BITEXTRACT
@ FUNC_CODE_INST_ATOMICRMW
@ FUNC_CODE_DEBUG_RECORD_DECLARE_VALUE
@ FUNC_CODE_DEBUG_LOC_AGAIN
@ FUNC_CODE_INST_EXTRACTELT
@ FUNC_CODE_INST_INDIRECTBR
@ FUNC_CODE_INST_INVOKE
@ FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE
@ FUNC_CODE_INST_INSERTVAL
@ FUNC_CODE_DECLAREBLOCKS
@ FUNC_CODE_DEBUG_RECORD_LABEL
@ FUNC_CODE_INST_SWITCH
@ FUNC_CODE_INST_ALLOCA
@ FUNC_CODE_INST_INSERTELT
@ FUNC_CODE_BLOCKADDR_USERS
@ FUNC_CODE_INST_CLEANUPPAD
@ FUNC_CODE_INST_SHUFFLEVEC
@ FUNC_CODE_INST_FREEZE
@ FUNC_CODE_INST_CMPXCHG
@ FUNC_CODE_INST_UNREACHABLE
@ FUNC_CODE_INST_BITINSERT
@ FUNC_CODE_DEBUG_RECORD_DECLARE
@ FUNC_CODE_OPERAND_BUNDLE
@ FIRST_APPLICATION_ABBREV
@ PARAMATTR_GRP_CODE_ENTRY
initializer< Ty > init(const Ty &Val)
@ DW_APPLE_ENUM_KIND_invalid
Enum kind for invalid results.
Definition Dwarf.h:51
LLVM_ABI Error build(ArrayRef< Module * > Mods, SmallVector< char, 0 > &Symtab, StringTableBuilder &StrtabBuilder, BumpPtrAllocator &Alloc)
Fills in Symtab and StrtabBuilder with a valid symbol and string table for Mods.
Definition IRSymtab.cpp:348
llvm::unique_function< void(llvm::Expected< T >)> Callback
A Callback<T> is a void function that accepts Expected<T>.
Definition Transport.h:132
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract_or_null(Y &&MD)
Extract a Value from Metadata, allowing null.
Definition Metadata.h:695
LLVM_ABI bool metadataIncludesAllContextSizeInfo()
Whether the alloc memeprof metadata will include context size info for all MIBs.
template LLVM_ABI llvm::DenseMap< LinearFrameId, FrameStat > computeFrameHistogram< LinearFrameId >(llvm::MapVector< CallStackId, llvm::SmallVector< LinearFrameId > > &MemProfCallStackData)
LLVM_ABI bool metadataMayIncludeContextSizeInfo()
Whether the alloc memprof metadata may include context size info for some MIBs (but possibly not all)...
uint32_t LinearFrameId
Definition MemProf.h:236
uint64_t CallStackId
Definition MemProf.h:353
NodeAddr< CodeNode * > Code
Definition RDFGraph.h:388
void write32le(void *P, uint32_t V)
Definition Endian.h:455
uint32_t read32be(const void *P)
Definition Endian.h:421
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
Definition MathExtras.h:339
void stable_sort(R &&Range)
Definition STLExtras.h:2132
StringMapEntry< Value * > ValueName
Definition Value.h:56
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
unsigned encode(MaybeAlign A)
Returns a representation of the alignment that encodes undefined as 0.
Definition Alignment.h:211
LLVM_ABI void WriteBitcodeToFile(const Module &M, raw_ostream &Out, bool ShouldPreserveUseListOrder=false, const ModuleSummaryIndex *Index=nullptr, bool GenerateHash=false, ModuleHash *ModHash=nullptr)
Write the specified module to the specified raw output stream.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
LLVM_ABI void writeThinLinkBitcodeToFile(const Module &M, raw_ostream &Out, const ModuleSummaryIndex &Index, const ModuleHash &ModHash)
Write the specified thin link bitcode file (i.e., the minimized bitcode file) to the given raw output...
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
@ BWH_HeaderSize
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI void writeIndexToFile(const ModuleSummaryIndex &Index, raw_ostream &Out, const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex=nullptr, const GVSummaryPtrSet *DecSummaries=nullptr)
Write the specified module summary index to the given raw output stream, where it will be written in ...
LLVM_ABI void embedBitcodeInModule(Module &M, MemoryBufferRef Buf, bool EmbedBitcode, bool EmbedCmdline, const std::vector< uint8_t > &CmdArgs)
If EmbedBitcode is set, save a copy of the llvm IR as data in the __LLVM,__bitcode section (....
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
const BitWriterOptions & getBitWriterOptions(const LLVMContext &C)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
std::map< std::string, GVSummaryMapTy, std::less<> > ModuleToSummariesForIndexTy
Map of a module name to the GUIDs and summaries we will import from that module.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
AtomicOrdering
Atomic ordering for LLVM's memory model.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
OutputIt copy(R &&Range, OutputIt Out)
Definition STLExtras.h:1901
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
constexpr bool valueOr(BoolOrDefault X, bool Default)
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
bool isBitcode(const unsigned char *BufPtr, const unsigned char *BufEnd)
isBitcode - Return true if the given bytes are the magic bytes for LLVM IR bitcode,...
SmallPtrSet< GlobalValueSummary *, 0 > GVSummaryPtrSet
A set of global value summary pointers.
void consumeError(Error Err)
Consume a Error without doing anything.
Definition Error.h:1106
LLVM_ABI Error write(DWPWriter &Out, ArrayRef< std::string > Inputs, OnCuIndexOverflow OverflowOptValue, Dwarf64StrOffsetsPromotion StrOffsetsOptValue, raw_pwrite_stream *OS=nullptr)
Definition DWP.cpp:746
LLVM_ABI GlobalVariable * collectUsedGlobalVariables(const Module &M, SmallVectorImpl< GlobalValue * > &Vec, bool CompilerUsed)
Given "llvm.used" or "llvm.compiler.used" as a global name, collect the initializer elements of that ...
Definition Module.cpp:991
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
#define N
#define NC
Definition regutils.h:42
#define NDEBUG
Definition regutils.h:48
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
static void set(StorageType &Packed, typename Bitfield::Type Value)
Sets the typed value in the provided Packed value.
Definition Bitfields.h:223
Class to accumulate and hold information about a callee.
Flags specific to function summaries.
static constexpr uint32_t RangeWidth
Group flags (Linkage, NotEligibleToImport, etc.) as a bitfield.
static LLVM_ABI const Target * lookupTarget(const Triple &TheTriple, std::string &Error)
lookupTarget - Lookup a target based on a target triple.
Struct that holds a reference to a particular GUID in a global value summary.
uint64_t Info
Additional information for the resolution:
enum llvm::WholeProgramDevirtResolution::ByArg::Kind TheKind
enum llvm::WholeProgramDevirtResolution::Kind TheKind
std::map< std::vector< uint64_t >, ByArg > ResByArg
Resolutions for calls with all constant integer arguments (excluding the first argument,...