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