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