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