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.SummaryList)
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.SummaryList)
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
1929 Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
1930 Record.clear();
1931}
1932
1933void ModuleBitcodeWriter::writeDIFixedPointType(
1934 const DIFixedPointType *N, SmallVectorImpl<uint64_t> &Record,
1935 unsigned Abbrev) {
1936 const unsigned SizeIsMetadata = 0x2;
1937 Record.push_back(SizeIsMetadata | (unsigned)N->isDistinct());
1938 Record.push_back(N->getTag());
1939 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1940 Record.push_back(VE.getMetadataOrNullID(N->getRawSizeInBits()));
1941 Record.push_back(N->getAlignInBits());
1942 Record.push_back(N->getEncoding());
1943 Record.push_back(N->getFlags());
1944 Record.push_back(N->getKind());
1945 Record.push_back(N->getFactorRaw());
1946
1947 auto WriteWideInt = [&](const APInt &Value) {
1948 // Write an encoded word that holds the number of active words and
1949 // the number of bits.
1950 uint64_t NumWords = Value.getActiveWords();
1951 uint64_t Encoded = (NumWords << 32) | Value.getBitWidth();
1952 Record.push_back(Encoded);
1953 emitWideAPInt(Record, Value);
1954 };
1955
1956 WriteWideInt(N->getNumeratorRaw());
1957 WriteWideInt(N->getDenominatorRaw());
1958
1959 Stream.EmitRecord(bitc::METADATA_FIXED_POINT_TYPE, Record, Abbrev);
1960 Record.clear();
1961}
1962
1963void ModuleBitcodeWriter::writeDIStringType(const DIStringType *N,
1964 SmallVectorImpl<uint64_t> &Record,
1965 unsigned Abbrev) {
1966 const unsigned SizeIsMetadata = 0x2;
1967 Record.push_back(SizeIsMetadata | (unsigned)N->isDistinct());
1968 Record.push_back(N->getTag());
1969 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1970 Record.push_back(VE.getMetadataOrNullID(N->getStringLength()));
1971 Record.push_back(VE.getMetadataOrNullID(N->getStringLengthExp()));
1972 Record.push_back(VE.getMetadataOrNullID(N->getStringLocationExp()));
1973 Record.push_back(VE.getMetadataOrNullID(N->getRawSizeInBits()));
1974 Record.push_back(N->getAlignInBits());
1975 Record.push_back(N->getEncoding());
1976
1977 Stream.EmitRecord(bitc::METADATA_STRING_TYPE, Record, Abbrev);
1978 Record.clear();
1979}
1980
1981void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,
1982 SmallVectorImpl<uint64_t> &Record,
1983 unsigned Abbrev) {
1984 const unsigned SizeIsMetadata = 0x2;
1985 Record.push_back(SizeIsMetadata | (unsigned)N->isDistinct());
1986 Record.push_back(N->getTag());
1987 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1988 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1989 Record.push_back(N->getLine());
1990 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1991 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1992 Record.push_back(VE.getMetadataOrNullID(N->getRawSizeInBits()));
1993 Record.push_back(N->getAlignInBits());
1994 Record.push_back(VE.getMetadataOrNullID(N->getRawOffsetInBits()));
1995 Record.push_back(N->getFlags());
1996 Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
1997
1998 // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
1999 // that there is no DWARF address space associated with DIDerivedType.
2000 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
2001 Record.push_back(*DWARFAddressSpace + 1);
2002 else
2003 Record.push_back(0);
2004
2005 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2006
2007 if (auto PtrAuthData = N->getPtrAuthData())
2008 Record.push_back(PtrAuthData->RawData);
2009 else
2010 Record.push_back(0);
2011
2012 Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
2013 Record.clear();
2014}
2015
2016void ModuleBitcodeWriter::writeDISubrangeType(const DISubrangeType *N,
2017 SmallVectorImpl<uint64_t> &Record,
2018 unsigned Abbrev) {
2019 const unsigned SizeIsMetadata = 0x2;
2020 Record.push_back(SizeIsMetadata | (unsigned)N->isDistinct());
2021 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2022 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2023 Record.push_back(N->getLine());
2024 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2025 Record.push_back(VE.getMetadataOrNullID(N->getRawSizeInBits()));
2026 Record.push_back(N->getAlignInBits());
2027 Record.push_back(N->getFlags());
2028 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
2029 Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
2030 Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
2031 Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
2032 Record.push_back(VE.getMetadataOrNullID(N->getRawBias()));
2033
2034 Stream.EmitRecord(bitc::METADATA_SUBRANGE_TYPE, Record, Abbrev);
2035 Record.clear();
2036}
2037
2038void ModuleBitcodeWriter::writeDICompositeType(
2039 const DICompositeType *N, SmallVectorImpl<uint64_t> &Record,
2040 unsigned Abbrev) {
2041 const unsigned IsNotUsedInOldTypeRef = 0x2;
2042 const unsigned SizeIsMetadata = 0x4;
2043 Record.push_back(SizeIsMetadata | IsNotUsedInOldTypeRef |
2044 (unsigned)N->isDistinct());
2045 Record.push_back(N->getTag());
2046 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2047 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2048 Record.push_back(N->getLine());
2049 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2050 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
2051 Record.push_back(VE.getMetadataOrNullID(N->getRawSizeInBits()));
2052 Record.push_back(N->getAlignInBits());
2053 Record.push_back(VE.getMetadataOrNullID(N->getRawOffsetInBits()));
2054 Record.push_back(N->getFlags());
2055 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
2056 Record.push_back(N->getRuntimeLang());
2057 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
2058 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
2059 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
2060 Record.push_back(VE.getMetadataOrNullID(N->getDiscriminator()));
2061 Record.push_back(VE.getMetadataOrNullID(N->getRawDataLocation()));
2062 Record.push_back(VE.getMetadataOrNullID(N->getRawAssociated()));
2063 Record.push_back(VE.getMetadataOrNullID(N->getRawAllocated()));
2064 Record.push_back(VE.getMetadataOrNullID(N->getRawRank()));
2065 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2066 Record.push_back(N->getNumExtraInhabitants());
2067 Record.push_back(VE.getMetadataOrNullID(N->getRawSpecification()));
2068 Record.push_back(
2069 N->getEnumKind().value_or(dwarf::DW_APPLE_ENUM_KIND_invalid));
2070 Record.push_back(VE.getMetadataOrNullID(N->getRawBitStride()));
2071
2072 Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
2073 Record.clear();
2074}
2075
2076void ModuleBitcodeWriter::writeDISubroutineType(
2077 const DISubroutineType *N, SmallVectorImpl<uint64_t> &Record,
2078 unsigned Abbrev) {
2079 const unsigned HasNoOldTypeRefs = 0x2;
2080 Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
2081 Record.push_back(N->getFlags());
2082 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
2083 Record.push_back(N->getCC());
2084
2085 Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
2086 Record.clear();
2087}
2088
2089void ModuleBitcodeWriter::writeDIFile(const DIFile *N,
2090 SmallVectorImpl<uint64_t> &Record,
2091 unsigned Abbrev) {
2092 Record.push_back(N->isDistinct());
2093 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
2094 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
2095 if (N->getRawChecksum()) {
2096 Record.push_back(N->getRawChecksum()->Kind);
2097 Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()->Value));
2098 } else {
2099 // Maintain backwards compatibility with the old internal representation of
2100 // CSK_None in ChecksumKind by writing nulls here when Checksum is None.
2101 Record.push_back(0);
2102 Record.push_back(VE.getMetadataOrNullID(nullptr));
2103 }
2104 auto Source = N->getRawSource();
2105 if (Source)
2106 Record.push_back(VE.getMetadataOrNullID(Source));
2107
2108 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
2109 Record.clear();
2110}
2111
2112void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
2113 SmallVectorImpl<uint64_t> &Record,
2114 unsigned Abbrev) {
2115 assert(N->isDistinct() && "Expected distinct compile units");
2116 Record.push_back(/* IsDistinct */ true);
2117
2118 auto Lang = N->getSourceLanguage();
2119 Record.push_back(Lang.getName());
2120 // Set bit so the MetadataLoader can distniguish between versioned and
2121 // unversioned names.
2122 if (Lang.hasVersionedName())
2123 Record.back() ^= (uint64_t(1) << 63);
2124
2125 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2126 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
2127 Record.push_back(N->isOptimized());
2128 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
2129 Record.push_back(N->getRuntimeVersion());
2130 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
2131 Record.push_back(N->getEmissionKind());
2132 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
2133 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
2134 Record.push_back(/* subprograms */ 0);
2135 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
2136 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
2137 Record.push_back(N->getDWOId());
2138 Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
2139 Record.push_back(N->getSplitDebugInlining());
2140 Record.push_back(N->getDebugInfoForProfiling());
2141 Record.push_back((unsigned)N->getNameTableKind());
2142 Record.push_back(N->getRangesBaseAddress());
2143 Record.push_back(VE.getMetadataOrNullID(N->getRawSysRoot()));
2144 Record.push_back(VE.getMetadataOrNullID(N->getRawSDK()));
2145
2146 Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
2147 Record.clear();
2148}
2149
2150void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,
2151 SmallVectorImpl<uint64_t> &Record,
2152 unsigned Abbrev) {
2153 const uint64_t HasUnitFlag = 1 << 1;
2154 const uint64_t HasSPFlagsFlag = 1 << 2;
2155 Record.push_back(uint64_t(N->isDistinct()) | HasUnitFlag | HasSPFlagsFlag);
2156 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2157 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2158 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
2159 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2160 Record.push_back(N->getLine());
2161 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2162 Record.push_back(N->getScopeLine());
2163 Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
2164 Record.push_back(N->getSPFlags());
2165 Record.push_back(N->getVirtualIndex());
2166 Record.push_back(N->getFlags());
2167 Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
2168 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
2169 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
2170 Record.push_back(VE.getMetadataOrNullID(N->getRetainedNodes().get()));
2171 Record.push_back(N->getThisAdjustment());
2172 Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get()));
2173 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2174 Record.push_back(VE.getMetadataOrNullID(N->getRawTargetFuncName()));
2175 Record.push_back(N->getKeyInstructionsEnabled());
2176
2177 Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
2178 Record.clear();
2179}
2180
2181void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
2182 SmallVectorImpl<uint64_t> &Record,
2183 unsigned Abbrev) {
2184 Record.push_back(N->isDistinct());
2185 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2186 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2187 Record.push_back(N->getLine());
2188 Record.push_back(N->getColumn());
2189
2190 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
2191 Record.clear();
2192}
2193
2194void ModuleBitcodeWriter::writeDILexicalBlockFile(
2195 const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record,
2196 unsigned Abbrev) {
2197 Record.push_back(N->isDistinct());
2198 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2199 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2200 Record.push_back(N->getDiscriminator());
2201
2202 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
2203 Record.clear();
2204}
2205
2206void ModuleBitcodeWriter::writeDICommonBlock(const DICommonBlock *N,
2207 SmallVectorImpl<uint64_t> &Record,
2208 unsigned Abbrev) {
2209 Record.push_back(N->isDistinct());
2210 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2211 Record.push_back(VE.getMetadataOrNullID(N->getDecl()));
2212 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2213 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2214 Record.push_back(N->getLineNo());
2215
2216 Stream.EmitRecord(bitc::METADATA_COMMON_BLOCK, Record, Abbrev);
2217 Record.clear();
2218}
2219
2220void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,
2221 SmallVectorImpl<uint64_t> &Record,
2222 unsigned Abbrev) {
2223 Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
2224 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2225 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2226
2227 Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
2228 Record.clear();
2229}
2230
2231void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,
2232 SmallVectorImpl<uint64_t> &Record,
2233 unsigned Abbrev) {
2234 Record.push_back(N->isDistinct());
2235 Record.push_back(N->getMacinfoType());
2236 Record.push_back(N->getLine());
2237 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2238 Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
2239
2240 Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
2241 Record.clear();
2242}
2243
2244void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,
2245 SmallVectorImpl<uint64_t> &Record,
2246 unsigned Abbrev) {
2247 Record.push_back(N->isDistinct());
2248 Record.push_back(N->getMacinfoType());
2249 Record.push_back(N->getLine());
2250 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2251 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
2252
2253 Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
2254 Record.clear();
2255}
2256
2257void ModuleBitcodeWriter::writeDIArgList(const DIArgList *N,
2258 SmallVectorImpl<uint64_t> &Record) {
2259 Record.reserve(N->getArgs().size());
2260 for (ValueAsMetadata *MD : N->getArgs())
2261 Record.push_back(VE.getMetadataID(MD));
2262
2263 Stream.EmitRecord(bitc::METADATA_ARG_LIST, Record);
2264 Record.clear();
2265}
2266
2267void ModuleBitcodeWriter::writeDIModule(const DIModule *N,
2268 SmallVectorImpl<uint64_t> &Record,
2269 unsigned Abbrev) {
2270 Record.push_back(N->isDistinct());
2271 for (auto &I : N->operands())
2272 Record.push_back(VE.getMetadataOrNullID(I));
2273 Record.push_back(N->getLineNo());
2274 Record.push_back(N->getIsDecl());
2275
2276 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
2277 Record.clear();
2278}
2279
2280void ModuleBitcodeWriter::writeDIAssignID(const DIAssignID *N,
2281 SmallVectorImpl<uint64_t> &Record,
2282 unsigned Abbrev) {
2283 // There are no arguments for this metadata type.
2284 Record.push_back(N->isDistinct());
2285 Stream.EmitRecord(bitc::METADATA_ASSIGN_ID, Record, Abbrev);
2286 Record.clear();
2287}
2288
2289void ModuleBitcodeWriter::writeDITemplateTypeParameter(
2290 const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record,
2291 unsigned Abbrev) {
2292 Record.push_back(N->isDistinct());
2293 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2294 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2295 Record.push_back(N->isDefault());
2296
2297 Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
2298 Record.clear();
2299}
2300
2301void ModuleBitcodeWriter::writeDITemplateValueParameter(
2302 const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record,
2303 unsigned Abbrev) {
2304 Record.push_back(N->isDistinct());
2305 Record.push_back(N->getTag());
2306 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2307 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2308 Record.push_back(N->isDefault());
2309 Record.push_back(VE.getMetadataOrNullID(N->getValue()));
2310
2311 Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
2312 Record.clear();
2313}
2314
2315void ModuleBitcodeWriter::writeDIGlobalVariable(
2316 const DIGlobalVariable *N, SmallVectorImpl<uint64_t> &Record,
2317 unsigned Abbrev) {
2318 const uint64_t Version = 2 << 1;
2319 Record.push_back((uint64_t)N->isDistinct() | Version);
2320 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2321 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2322 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
2323 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2324 Record.push_back(N->getLine());
2325 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2326 Record.push_back(N->isLocalToUnit());
2327 Record.push_back(N->isDefinition());
2328 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
2329 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams()));
2330 Record.push_back(N->getAlignInBits());
2331 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2332
2333 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
2334 Record.clear();
2335}
2336
2337void ModuleBitcodeWriter::writeDILocalVariable(
2338 const DILocalVariable *N, SmallVectorImpl<uint64_t> &Record,
2339 unsigned Abbrev) {
2340 // In order to support all possible bitcode formats in BitcodeReader we need
2341 // to distinguish the following cases:
2342 // 1) Record has no artificial tag (Record[1]),
2343 // has no obsolete inlinedAt field (Record[9]).
2344 // In this case Record size will be 8, HasAlignment flag is false.
2345 // 2) Record has artificial tag (Record[1]),
2346 // has no obsolete inlignedAt field (Record[9]).
2347 // In this case Record size will be 9, HasAlignment flag is false.
2348 // 3) Record has both artificial tag (Record[1]) and
2349 // obsolete inlignedAt field (Record[9]).
2350 // In this case Record size will be 10, HasAlignment flag is false.
2351 // 4) Record has neither artificial tag, nor inlignedAt field, but
2352 // HasAlignment flag is true and Record[8] contains alignment value.
2353 const uint64_t HasAlignmentFlag = 1 << 1;
2354 Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
2355 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2356 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2357 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2358 Record.push_back(N->getLine());
2359 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2360 Record.push_back(N->getArg());
2361 Record.push_back(N->getFlags());
2362 Record.push_back(N->getAlignInBits());
2363 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2364
2365 Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
2366 Record.clear();
2367}
2368
2369void ModuleBitcodeWriter::writeDILabel(
2370 const DILabel *N, SmallVectorImpl<uint64_t> &Record,
2371 unsigned Abbrev) {
2372 uint64_t IsArtificialFlag = uint64_t(N->isArtificial()) << 1;
2373 Record.push_back((uint64_t)N->isDistinct() | IsArtificialFlag);
2374 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2375 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2376 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2377 Record.push_back(N->getLine());
2378 Record.push_back(N->getColumn());
2379 Record.push_back(N->getCoroSuspendIdx().has_value()
2380 ? (uint64_t)N->getCoroSuspendIdx().value()
2381 : std::numeric_limits<uint64_t>::max());
2382
2383 Stream.EmitRecord(bitc::METADATA_LABEL, Record, Abbrev);
2384 Record.clear();
2385}
2386
2387void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,
2388 SmallVectorImpl<uint64_t> &Record,
2389 unsigned Abbrev) {
2390 Record.reserve(N->getElements().size() + 1);
2391 const uint64_t Version = 3 << 1;
2392 Record.push_back((uint64_t)N->isDistinct() | Version);
2393 Record.append(N->elements_begin(), N->elements_end());
2394
2395 Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
2396 Record.clear();
2397}
2398
2399void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
2400 const DIGlobalVariableExpression *N, SmallVectorImpl<uint64_t> &Record,
2401 unsigned Abbrev) {
2402 Record.push_back(N->isDistinct());
2403 Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
2404 Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
2405
2406 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR, Record, Abbrev);
2407 Record.clear();
2408}
2409
2410void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
2411 SmallVectorImpl<uint64_t> &Record,
2412 unsigned Abbrev) {
2413 Record.push_back(N->isDistinct());
2414 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2415 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2416 Record.push_back(N->getLine());
2417 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
2418 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
2419 Record.push_back(N->getAttributes());
2420 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2421
2422 Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
2423 Record.clear();
2424}
2425
2426void ModuleBitcodeWriter::writeDIImportedEntity(
2427 const DIImportedEntity *N, SmallVectorImpl<uint64_t> &Record,
2428 unsigned Abbrev) {
2429 Record.push_back(N->isDistinct());
2430 Record.push_back(N->getTag());
2431 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2432 Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
2433 Record.push_back(N->getLine());
2434 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2435 Record.push_back(VE.getMetadataOrNullID(N->getRawFile()));
2436 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
2437
2438 Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
2439 Record.clear();
2440}
2441
2442unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
2443 auto Abbv = std::make_shared<BitCodeAbbrev>();
2444 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
2445 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2446 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2447 return Stream.EmitAbbrev(std::move(Abbv));
2448}
2449
2450void ModuleBitcodeWriter::writeNamedMetadata(
2451 SmallVectorImpl<uint64_t> &Record) {
2452 if (M.named_metadata_empty())
2453 return;
2454
2455 unsigned Abbrev = createNamedMetadataAbbrev();
2456 for (const NamedMDNode &NMD : M.named_metadata()) {
2457 // Write name.
2458 StringRef Str = NMD.getName();
2459 Record.append(Str.bytes_begin(), Str.bytes_end());
2460 Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
2461 Record.clear();
2462
2463 // Write named metadata operands.
2464 for (const MDNode *N : NMD.operands())
2465 Record.push_back(VE.getMetadataID(N));
2466 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
2467 Record.clear();
2468 }
2469}
2470
2471unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
2472 auto Abbv = std::make_shared<BitCodeAbbrev>();
2473 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS));
2474 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
2475 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
2476 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2477 return Stream.EmitAbbrev(std::move(Abbv));
2478}
2479
2480/// Write out a record for MDString.
2481///
2482/// All the metadata strings in a metadata block are emitted in a single
2483/// record. The sizes and strings themselves are shoved into a blob.
2484void ModuleBitcodeWriter::writeMetadataStrings(
2485 ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) {
2486 if (Strings.empty())
2487 return;
2488
2489 // Start the record with the number of strings.
2491 Record.push_back(Strings.size());
2492
2493 // Emit the sizes of the strings in the blob.
2494 SmallString<256> Blob;
2495 {
2496 BitstreamWriter W(Blob);
2497 for (const Metadata *MD : Strings)
2498 W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
2499 W.FlushToWord();
2500 }
2501
2502 // Add the offset to the strings to the record.
2503 Record.push_back(Blob.size());
2504
2505 // Add the strings to the blob.
2506 for (const Metadata *MD : Strings)
2507 Blob.append(cast<MDString>(MD)->getString());
2508
2509 // Emit the final record.
2510 Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
2511 Record.clear();
2512}
2513
2514// Generates an enum to use as an index in the Abbrev array of Metadata record.
2515enum MetadataAbbrev : unsigned {
2516#define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
2517#include "llvm/IR/Metadata.def"
2519};
2520
2521void ModuleBitcodeWriter::writeMetadataRecords(
2522 ArrayRef<const Metadata *> MDs, SmallVectorImpl<uint64_t> &Record,
2523 std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
2524 if (MDs.empty())
2525 return;
2526
2527 // Initialize MDNode abbreviations.
2528#define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
2529#include "llvm/IR/Metadata.def"
2530
2531 for (const Metadata *MD : MDs) {
2532 if (IndexPos)
2533 IndexPos->push_back(Stream.GetCurrentBitNo());
2534 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
2535 assert(N->isResolved() && "Expected forward references to be resolved");
2536
2537 switch (N->getMetadataID()) {
2538 default:
2539 llvm_unreachable("Invalid MDNode subclass");
2540#define HANDLE_MDNODE_LEAF(CLASS) \
2541 case Metadata::CLASS##Kind: \
2542 if (MDAbbrevs) \
2543 write##CLASS(cast<CLASS>(N), Record, \
2544 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
2545 else \
2546 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
2547 continue;
2548#include "llvm/IR/Metadata.def"
2549 }
2550 }
2551 if (auto *AL = dyn_cast<DIArgList>(MD)) {
2552 writeDIArgList(AL, Record);
2553 continue;
2554 }
2555 writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
2556 }
2557}
2558
2559void ModuleBitcodeWriter::writeModuleMetadata() {
2560 if (!VE.hasMDs() && M.named_metadata_empty())
2561 return;
2562
2564 SmallVector<uint64_t, 64> Record;
2565
2566 // Emit all abbrevs upfront, so that the reader can jump in the middle of the
2567 // block and load any metadata.
2568 std::vector<unsigned> MDAbbrevs;
2569
2570 MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
2571 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
2572 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
2573 createGenericDINodeAbbrev();
2574
2575 auto Abbv = std::make_shared<BitCodeAbbrev>();
2576 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX_OFFSET));
2577 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2578 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2579 unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2580
2581 Abbv = std::make_shared<BitCodeAbbrev>();
2582 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX));
2583 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2584 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2585 unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2586
2587 // Emit MDStrings together upfront.
2588 writeMetadataStrings(VE.getMDStrings(), Record);
2589
2590 // We only emit an index for the metadata record if we have more than a given
2591 // (naive) threshold of metadatas, otherwise it is not worth it.
2592 if (VE.getNonMDStrings().size() > IndexThreshold) {
2593 // Write a placeholder value in for the offset of the metadata index,
2594 // which is written after the records, so that it can include
2595 // the offset of each entry. The placeholder offset will be
2596 // updated after all records are emitted.
2597 uint64_t Vals[] = {0, 0};
2598 Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
2599 }
2600
2601 // Compute and save the bit offset to the current position, which will be
2602 // patched when we emit the index later. We can simply subtract the 64-bit
2603 // fixed size from the current bit number to get the location to backpatch.
2604 uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
2605
2606 // This index will contain the bitpos for each individual record.
2607 std::vector<uint64_t> IndexPos;
2608 IndexPos.reserve(VE.getNonMDStrings().size());
2609
2610 // Write all the records
2611 writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
2612
2613 if (VE.getNonMDStrings().size() > IndexThreshold) {
2614 // Now that we have emitted all the records we will emit the index. But
2615 // first
2616 // backpatch the forward reference so that the reader can skip the records
2617 // efficiently.
2618 Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
2619 Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
2620
2621 // Delta encode the index.
2622 uint64_t PreviousValue = IndexOffsetRecordBitPos;
2623 for (auto &Elt : IndexPos) {
2624 auto EltDelta = Elt - PreviousValue;
2625 PreviousValue = Elt;
2626 Elt = EltDelta;
2627 }
2628 // Emit the index record.
2629 Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
2630 IndexPos.clear();
2631 }
2632
2633 // Write the named metadata now.
2634 writeNamedMetadata(Record);
2635
2636 auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
2637 SmallVector<uint64_t, 4> Record;
2638 Record.push_back(VE.getValueID(&GO));
2639 pushGlobalMetadataAttachment(Record, GO);
2641 };
2642 for (const Function &F : M)
2643 if (F.isDeclaration() && F.hasMetadata())
2644 AddDeclAttachedMetadata(F);
2645 for (const GlobalIFunc &GI : M.ifuncs())
2646 if (GI.hasMetadata())
2647 AddDeclAttachedMetadata(GI);
2648 // FIXME: Only store metadata for declarations here, and move data for global
2649 // variable definitions to a separate block (PR28134).
2650 for (const GlobalVariable &GV : M.globals())
2651 if (GV.hasMetadata())
2652 AddDeclAttachedMetadata(GV);
2653
2654 Stream.ExitBlock();
2655}
2656
2657void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
2658 if (!VE.hasMDs())
2659 return;
2660
2662 SmallVector<uint64_t, 64> Record;
2663 writeMetadataStrings(VE.getMDStrings(), Record);
2664 writeMetadataRecords(VE.getNonMDStrings(), Record);
2665 Stream.ExitBlock();
2666}
2667
2668void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
2669 SmallVectorImpl<uint64_t> &Record, const GlobalObject &GO) {
2670 // [n x [id, mdnode]]
2672 GO.getAllMetadata(MDs);
2673 for (const auto &I : MDs) {
2674 Record.push_back(I.first);
2675 Record.push_back(VE.getMetadataID(I.second));
2676 }
2677}
2678
2679void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
2681
2682 SmallVector<uint64_t, 64> Record;
2683
2684 if (F.hasMetadata()) {
2685 pushGlobalMetadataAttachment(Record, F);
2686 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
2687 Record.clear();
2688 }
2689
2690 // Write metadata attachments
2691 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
2693 for (const BasicBlock &BB : F)
2694 for (const Instruction &I : BB) {
2695 MDs.clear();
2696 I.getAllMetadataOtherThanDebugLoc(MDs);
2697
2698 // If no metadata, ignore instruction.
2699 if (MDs.empty()) continue;
2700
2701 Record.push_back(VE.getInstructionID(&I));
2702
2703 for (const auto &[ID, MD] : MDs) {
2704 Record.push_back(ID);
2705 Record.push_back(VE.getMetadataID(MD));
2706 }
2707 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
2708 Record.clear();
2709 }
2710
2711 Stream.ExitBlock();
2712}
2713
2714void ModuleBitcodeWriter::writeModuleMetadataKinds() {
2715 SmallVector<uint64_t, 64> Record;
2716
2717 // Write metadata kinds
2718 // METADATA_KIND - [n x [id, name]]
2720 M.getMDKindNames(Names);
2721
2722 if (Names.empty()) return;
2723
2725
2726 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
2727 Record.push_back(MDKindID);
2728 StringRef KName = Names[MDKindID];
2729 Record.append(KName.begin(), KName.end());
2730
2731 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
2732 Record.clear();
2733 }
2734
2735 Stream.ExitBlock();
2736}
2737
2738void ModuleBitcodeWriter::writeOperandBundleTags() {
2739 // Write metadata kinds
2740 //
2741 // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
2742 //
2743 // OPERAND_BUNDLE_TAG - [strchr x N]
2744
2746 M.getOperandBundleTags(Tags);
2747
2748 if (Tags.empty())
2749 return;
2750
2752
2753 SmallVector<uint64_t, 64> Record;
2754
2755 for (auto Tag : Tags) {
2756 Record.append(Tag.begin(), Tag.end());
2757
2758 Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
2759 Record.clear();
2760 }
2761
2762 Stream.ExitBlock();
2763}
2764
2765void ModuleBitcodeWriter::writeSyncScopeNames() {
2767 M.getContext().getSyncScopeNames(SSNs);
2768 if (SSNs.empty())
2769 return;
2770
2772
2773 SmallVector<uint64_t, 64> Record;
2774 for (auto SSN : SSNs) {
2775 Record.append(SSN.begin(), SSN.end());
2776 Stream.EmitRecord(bitc::SYNC_SCOPE_NAME, Record, 0);
2777 Record.clear();
2778 }
2779
2780 Stream.ExitBlock();
2781}
2782
2783void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
2784 bool isGlobal) {
2785 if (FirstVal == LastVal) return;
2786
2788
2789 unsigned AggregateAbbrev = 0;
2790 unsigned String8Abbrev = 0;
2791 unsigned CString7Abbrev = 0;
2792 unsigned CString6Abbrev = 0;
2793 // If this is a constant pool for the module, emit module-specific abbrevs.
2794 if (isGlobal) {
2795 // Abbrev for CST_CODE_AGGREGATE.
2796 auto Abbv = std::make_shared<BitCodeAbbrev>();
2797 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
2798 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2799 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
2800 AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2801
2802 // Abbrev for CST_CODE_STRING.
2803 Abbv = std::make_shared<BitCodeAbbrev>();
2804 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
2805 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2806 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2807 String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2808 // Abbrev for CST_CODE_CSTRING.
2809 Abbv = std::make_shared<BitCodeAbbrev>();
2810 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2811 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2812 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2813 CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2814 // Abbrev for CST_CODE_CSTRING.
2815 Abbv = std::make_shared<BitCodeAbbrev>();
2816 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2817 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2818 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2819 CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2820 }
2821
2822 SmallVector<uint64_t, 64> Record;
2823
2824 const ValueEnumerator::ValueList &Vals = VE.getValues();
2825 Type *LastTy = nullptr;
2826 for (unsigned i = FirstVal; i != LastVal; ++i) {
2827 const Value *V = Vals[i].first;
2828 // If we need to switch types, do so now.
2829 if (V->getType() != LastTy) {
2830 LastTy = V->getType();
2831 Record.push_back(VE.getTypeID(LastTy));
2832 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
2833 CONSTANTS_SETTYPE_ABBREV);
2834 Record.clear();
2835 }
2836
2837 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
2838 Record.push_back(VE.getTypeID(IA->getFunctionType()));
2839 Record.push_back(
2840 unsigned(IA->hasSideEffects()) | unsigned(IA->isAlignStack()) << 1 |
2841 unsigned(IA->getDialect() & 1) << 2 | unsigned(IA->canThrow()) << 3);
2842
2843 // Add the asm string.
2844 StringRef AsmStr = IA->getAsmString();
2845 Record.push_back(AsmStr.size());
2846 Record.append(AsmStr.begin(), AsmStr.end());
2847
2848 // Add the constraint string.
2849 StringRef ConstraintStr = IA->getConstraintString();
2850 Record.push_back(ConstraintStr.size());
2851 Record.append(ConstraintStr.begin(), ConstraintStr.end());
2852 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
2853 Record.clear();
2854 continue;
2855 }
2856 const Constant *C = cast<Constant>(V);
2857 unsigned Code = -1U;
2858 unsigned AbbrevToUse = 0;
2859 if (C->isNullValue()) {
2861 } else if (isa<PoisonValue>(C)) {
2863 } else if (isa<UndefValue>(C)) {
2865 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
2866 if (IV->getBitWidth() <= 64) {
2867 uint64_t V = IV->getSExtValue();
2868 emitSignedInt64(Record, V);
2870 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
2871 } else { // Wide integers, > 64 bits in size.
2872 emitWideAPInt(Record, IV->getValue());
2874 }
2875 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
2877 Type *Ty = CFP->getType()->getScalarType();
2878 if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() ||
2879 Ty->isDoubleTy()) {
2880 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
2881 } else if (Ty->isX86_FP80Ty()) {
2882 // api needed to prevent premature destruction
2883 // bits are not in the same order as a normal i80 APInt, compensate.
2884 APInt api = CFP->getValueAPF().bitcastToAPInt();
2885 const uint64_t *p = api.getRawData();
2886 Record.push_back((p[1] << 48) | (p[0] >> 16));
2887 Record.push_back(p[0] & 0xffffLL);
2888 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
2889 APInt api = CFP->getValueAPF().bitcastToAPInt();
2890 const uint64_t *p = api.getRawData();
2891 Record.push_back(p[0]);
2892 Record.push_back(p[1]);
2893 } else {
2894 assert(0 && "Unknown FP type!");
2895 }
2896 } else if (isa<ConstantDataSequential>(C) &&
2897 cast<ConstantDataSequential>(C)->isString()) {
2898 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
2899 // Emit constant strings specially.
2900 uint64_t NumElts = Str->getNumElements();
2901 // If this is a null-terminated string, use the denser CSTRING encoding.
2902 if (Str->isCString()) {
2904 --NumElts; // Don't encode the null, which isn't allowed by char6.
2905 } else {
2907 AbbrevToUse = String8Abbrev;
2908 }
2909 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
2910 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
2911 for (uint64_t i = 0; i != NumElts; ++i) {
2912 unsigned char V = Str->getElementAsInteger(i);
2913 Record.push_back(V);
2914 isCStr7 &= (V & 128) == 0;
2915 if (isCStrChar6)
2916 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
2917 }
2918
2919 if (isCStrChar6)
2920 AbbrevToUse = CString6Abbrev;
2921 else if (isCStr7)
2922 AbbrevToUse = CString7Abbrev;
2923 } else if (const ConstantDataSequential *CDS =
2926 Type *EltTy = CDS->getElementType();
2927 if (isa<IntegerType>(EltTy)) {
2928 for (uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i)
2929 Record.push_back(CDS->getElementAsInteger(i));
2930 } else {
2931 for (uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i)
2932 Record.push_back(
2933 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
2934 }
2935 } else if (isa<ConstantAggregate>(C)) {
2937 for (const Value *Op : C->operands())
2938 Record.push_back(VE.getValueID(Op));
2939 AbbrevToUse = AggregateAbbrev;
2940 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2941 switch (CE->getOpcode()) {
2942 default:
2943 if (Instruction::isCast(CE->getOpcode())) {
2945 Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
2946 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2947 Record.push_back(VE.getValueID(C->getOperand(0)));
2948 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
2949 } else {
2950 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
2952 Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
2953 Record.push_back(VE.getValueID(C->getOperand(0)));
2954 Record.push_back(VE.getValueID(C->getOperand(1)));
2955 uint64_t Flags = getOptimizationFlags(CE);
2956 if (Flags != 0)
2957 Record.push_back(Flags);
2958 }
2959 break;
2960 case Instruction::FNeg: {
2961 assert(CE->getNumOperands() == 1 && "Unknown constant expr!");
2963 Record.push_back(getEncodedUnaryOpcode(CE->getOpcode()));
2964 Record.push_back(VE.getValueID(C->getOperand(0)));
2965 uint64_t Flags = getOptimizationFlags(CE);
2966 if (Flags != 0)
2967 Record.push_back(Flags);
2968 break;
2969 }
2970 case Instruction::GetElementPtr: {
2972 const auto *GO = cast<GEPOperator>(C);
2973 Record.push_back(VE.getTypeID(GO->getSourceElementType()));
2974 Record.push_back(getOptimizationFlags(GO));
2975 if (std::optional<ConstantRange> Range = GO->getInRange()) {
2977 emitConstantRange(Record, *Range, /*EmitBitWidth=*/true);
2978 }
2979 for (const Value *Op : CE->operands()) {
2980 Record.push_back(VE.getTypeID(Op->getType()));
2981 Record.push_back(VE.getValueID(Op));
2982 }
2983 break;
2984 }
2985 case Instruction::ExtractElement:
2987 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2988 Record.push_back(VE.getValueID(C->getOperand(0)));
2989 Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
2990 Record.push_back(VE.getValueID(C->getOperand(1)));
2991 break;
2992 case Instruction::InsertElement:
2994 Record.push_back(VE.getValueID(C->getOperand(0)));
2995 Record.push_back(VE.getValueID(C->getOperand(1)));
2996 Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
2997 Record.push_back(VE.getValueID(C->getOperand(2)));
2998 break;
2999 case Instruction::ShuffleVector:
3000 // If the return type and argument types are the same, this is a
3001 // standard shufflevector instruction. If the types are different,
3002 // then the shuffle is widening or truncating the input vectors, and
3003 // the argument type must also be encoded.
3004 if (C->getType() == C->getOperand(0)->getType()) {
3006 } else {
3008 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
3009 }
3010 Record.push_back(VE.getValueID(C->getOperand(0)));
3011 Record.push_back(VE.getValueID(C->getOperand(1)));
3012 Record.push_back(VE.getValueID(CE->getShuffleMaskForBitcode()));
3013 break;
3014 }
3015 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
3017 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
3018 Record.push_back(VE.getValueID(BA->getFunction()));
3019 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
3020 } else if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) {
3022 Record.push_back(VE.getTypeID(Equiv->getGlobalValue()->getType()));
3023 Record.push_back(VE.getValueID(Equiv->getGlobalValue()));
3024 } else if (const auto *NC = dyn_cast<NoCFIValue>(C)) {
3026 Record.push_back(VE.getTypeID(NC->getGlobalValue()->getType()));
3027 Record.push_back(VE.getValueID(NC->getGlobalValue()));
3028 } else if (const auto *CPA = dyn_cast<ConstantPtrAuth>(C)) {
3030 Record.push_back(VE.getValueID(CPA->getPointer()));
3031 Record.push_back(VE.getValueID(CPA->getKey()));
3032 Record.push_back(VE.getValueID(CPA->getDiscriminator()));
3033 Record.push_back(VE.getValueID(CPA->getAddrDiscriminator()));
3034 } else {
3035#ifndef NDEBUG
3036 C->dump();
3037#endif
3038 llvm_unreachable("Unknown constant!");
3039 }
3040 Stream.EmitRecord(Code, Record, AbbrevToUse);
3041 Record.clear();
3042 }
3043
3044 Stream.ExitBlock();
3045}
3046
3047void ModuleBitcodeWriter::writeModuleConstants() {
3048 const ValueEnumerator::ValueList &Vals = VE.getValues();
3049
3050 // Find the first constant to emit, which is the first non-globalvalue value.
3051 // We know globalvalues have been emitted by WriteModuleInfo.
3052 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
3053 if (!isa<GlobalValue>(Vals[i].first)) {
3054 writeConstants(i, Vals.size(), true);
3055 return;
3056 }
3057 }
3058}
3059
3060/// pushValueAndType - The file has to encode both the value and type id for
3061/// many values, because we need to know what type to create for forward
3062/// references. However, most operands are not forward references, so this type
3063/// field is not needed.
3064///
3065/// This function adds V's value ID to Vals. If the value ID is higher than the
3066/// instruction ID, then it is a forward reference, and it also includes the
3067/// type ID. The value ID that is written is encoded relative to the InstID.
3068bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
3069 SmallVectorImpl<unsigned> &Vals) {
3070 unsigned ValID = VE.getValueID(V);
3071 // Make encoding relative to the InstID.
3072 Vals.push_back(InstID - ValID);
3073 if (ValID >= InstID) {
3074 Vals.push_back(VE.getTypeID(V->getType()));
3075 return true;
3076 }
3077 return false;
3078}
3079
3080bool ModuleBitcodeWriter::pushValueOrMetadata(const Value *V, unsigned InstID,
3081 SmallVectorImpl<unsigned> &Vals) {
3082 bool IsMetadata = V->getType()->isMetadataTy();
3083 if (IsMetadata) {
3085 Metadata *MD = cast<MetadataAsValue>(V)->getMetadata();
3086 unsigned ValID = VE.getMetadataID(MD);
3087 Vals.push_back(InstID - ValID);
3088 return false;
3089 }
3090 return pushValueAndType(V, InstID, Vals);
3091}
3092
3093void ModuleBitcodeWriter::writeOperandBundles(const CallBase &CS,
3094 unsigned InstID) {
3096 LLVMContext &C = CS.getContext();
3097
3098 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
3099 const auto &Bundle = CS.getOperandBundleAt(i);
3100 Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
3101
3102 for (auto &Input : Bundle.Inputs)
3103 pushValueOrMetadata(Input, InstID, Record);
3104
3106 Record.clear();
3107 }
3108}
3109
3110/// pushValue - Like pushValueAndType, but where the type of the value is
3111/// omitted (perhaps it was already encoded in an earlier operand).
3112void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
3113 SmallVectorImpl<unsigned> &Vals) {
3114 unsigned ValID = VE.getValueID(V);
3115 Vals.push_back(InstID - ValID);
3116}
3117
3118void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
3119 SmallVectorImpl<uint64_t> &Vals) {
3120 unsigned ValID = VE.getValueID(V);
3121 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
3122 emitSignedInt64(Vals, diff);
3123}
3124
3125/// WriteInstruction - Emit an instruction to the specified stream.
3126void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
3127 unsigned InstID,
3128 SmallVectorImpl<unsigned> &Vals) {
3129 unsigned Code = 0;
3130 unsigned AbbrevToUse = 0;
3131 VE.setInstructionID(&I);
3132 switch (I.getOpcode()) {
3133 default:
3134 if (Instruction::isCast(I.getOpcode())) {
3136 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
3137 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
3138 Vals.push_back(VE.getTypeID(I.getType()));
3139 Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
3140 uint64_t Flags = getOptimizationFlags(&I);
3141 if (Flags != 0) {
3142 if (AbbrevToUse == FUNCTION_INST_CAST_ABBREV)
3143 AbbrevToUse = FUNCTION_INST_CAST_FLAGS_ABBREV;
3144 Vals.push_back(Flags);
3145 }
3146 } else {
3147 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
3149 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
3150 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
3151 pushValue(I.getOperand(1), InstID, Vals);
3152 Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
3153 uint64_t Flags = getOptimizationFlags(&I);
3154 if (Flags != 0) {
3155 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
3156 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
3157 Vals.push_back(Flags);
3158 }
3159 }
3160 break;
3161 case Instruction::FNeg: {
3163 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
3164 AbbrevToUse = FUNCTION_INST_UNOP_ABBREV;
3165 Vals.push_back(getEncodedUnaryOpcode(I.getOpcode()));
3166 uint64_t Flags = getOptimizationFlags(&I);
3167 if (Flags != 0) {
3168 if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV)
3169 AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV;
3170 Vals.push_back(Flags);
3171 }
3172 break;
3173 }
3174 case Instruction::GetElementPtr: {
3176 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
3177 auto &GEPInst = cast<GetElementPtrInst>(I);
3179 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
3180 for (const Value *Op : I.operands())
3181 pushValueAndType(Op, InstID, Vals);
3182 break;
3183 }
3184 case Instruction::ExtractValue: {
3186 pushValueAndType(I.getOperand(0), InstID, Vals);
3187 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
3188 Vals.append(EVI->idx_begin(), EVI->idx_end());
3189 break;
3190 }
3191 case Instruction::InsertValue: {
3193 pushValueAndType(I.getOperand(0), InstID, Vals);
3194 pushValueAndType(I.getOperand(1), InstID, Vals);
3195 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
3196 Vals.append(IVI->idx_begin(), IVI->idx_end());
3197 break;
3198 }
3199 case Instruction::Select: {
3201 pushValueAndType(I.getOperand(1), InstID, Vals);
3202 pushValue(I.getOperand(2), InstID, Vals);
3203 pushValueAndType(I.getOperand(0), InstID, Vals);
3204 uint64_t Flags = getOptimizationFlags(&I);
3205 if (Flags != 0)
3206 Vals.push_back(Flags);
3207 break;
3208 }
3209 case Instruction::ExtractElement:
3211 pushValueAndType(I.getOperand(0), InstID, Vals);
3212 pushValueAndType(I.getOperand(1), InstID, Vals);
3213 break;
3214 case Instruction::InsertElement:
3216 pushValueAndType(I.getOperand(0), InstID, Vals);
3217 pushValue(I.getOperand(1), InstID, Vals);
3218 pushValueAndType(I.getOperand(2), InstID, Vals);
3219 break;
3220 case Instruction::ShuffleVector:
3222 pushValueAndType(I.getOperand(0), InstID, Vals);
3223 pushValue(I.getOperand(1), InstID, Vals);
3224 pushValue(cast<ShuffleVectorInst>(I).getShuffleMaskForBitcode(), InstID,
3225 Vals);
3226 break;
3227 case Instruction::ICmp:
3228 case Instruction::FCmp: {
3229 // compare returning Int1Ty or vector of Int1Ty
3231 AbbrevToUse = FUNCTION_INST_CMP_ABBREV;
3232 if (pushValueAndType(I.getOperand(0), InstID, Vals))
3233 AbbrevToUse = 0;
3234 pushValue(I.getOperand(1), InstID, Vals);
3236 uint64_t Flags = getOptimizationFlags(&I);
3237 if (Flags != 0) {
3238 Vals.push_back(Flags);
3239 if (AbbrevToUse)
3240 AbbrevToUse = FUNCTION_INST_CMP_FLAGS_ABBREV;
3241 }
3242 break;
3243 }
3244
3245 case Instruction::Ret:
3246 {
3248 unsigned NumOperands = I.getNumOperands();
3249 if (NumOperands == 0)
3250 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
3251 else if (NumOperands == 1) {
3252 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
3253 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
3254 } else {
3255 for (const Value *Op : I.operands())
3256 pushValueAndType(Op, InstID, Vals);
3257 }
3258 }
3259 break;
3260 case Instruction::Br:
3261 {
3263 AbbrevToUse = FUNCTION_INST_BR_UNCOND_ABBREV;
3264 const BranchInst &II = cast<BranchInst>(I);
3265 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
3266 if (II.isConditional()) {
3267 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
3268 pushValue(II.getCondition(), InstID, Vals);
3269 AbbrevToUse = FUNCTION_INST_BR_COND_ABBREV;
3270 }
3271 }
3272 break;
3273 case Instruction::Switch:
3274 {
3276 const SwitchInst &SI = cast<SwitchInst>(I);
3277 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
3278 pushValue(SI.getCondition(), InstID, Vals);
3279 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
3280 for (auto Case : SI.cases()) {
3281 Vals.push_back(VE.getValueID(Case.getCaseValue()));
3282 Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
3283 }
3284 }
3285 break;
3286 case Instruction::IndirectBr:
3288 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
3289 // Encode the address operand as relative, but not the basic blocks.
3290 pushValue(I.getOperand(0), InstID, Vals);
3291 for (const Value *Op : drop_begin(I.operands()))
3292 Vals.push_back(VE.getValueID(Op));
3293 break;
3294
3295 case Instruction::Invoke: {
3296 const InvokeInst *II = cast<InvokeInst>(&I);
3297 const Value *Callee = II->getCalledOperand();
3298 FunctionType *FTy = II->getFunctionType();
3299
3300 if (II->hasOperandBundles())
3301 writeOperandBundles(*II, InstID);
3302
3304
3305 Vals.push_back(VE.getAttributeListID(II->getAttributes()));
3306 Vals.push_back(II->getCallingConv() | 1 << 13);
3307 Vals.push_back(VE.getValueID(II->getNormalDest()));
3308 Vals.push_back(VE.getValueID(II->getUnwindDest()));
3309 Vals.push_back(VE.getTypeID(FTy));
3310 pushValueAndType(Callee, InstID, Vals);
3311
3312 // Emit value #'s for the fixed parameters.
3313 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3314 pushValue(I.getOperand(i), InstID, Vals); // fixed param.
3315
3316 // Emit type/value pairs for varargs params.
3317 if (FTy->isVarArg()) {
3318 for (unsigned i = FTy->getNumParams(), e = II->arg_size(); i != e; ++i)
3319 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
3320 }
3321 break;
3322 }
3323 case Instruction::Resume:
3325 pushValueAndType(I.getOperand(0), InstID, Vals);
3326 break;
3327 case Instruction::CleanupRet: {
3329 const auto &CRI = cast<CleanupReturnInst>(I);
3330 pushValue(CRI.getCleanupPad(), InstID, Vals);
3331 if (CRI.hasUnwindDest())
3332 Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
3333 break;
3334 }
3335 case Instruction::CatchRet: {
3337 const auto &CRI = cast<CatchReturnInst>(I);
3338 pushValue(CRI.getCatchPad(), InstID, Vals);
3339 Vals.push_back(VE.getValueID(CRI.getSuccessor()));
3340 break;
3341 }
3342 case Instruction::CleanupPad:
3343 case Instruction::CatchPad: {
3344 const auto &FuncletPad = cast<FuncletPadInst>(I);
3347 pushValue(FuncletPad.getParentPad(), InstID, Vals);
3348
3349 unsigned NumArgOperands = FuncletPad.arg_size();
3350 Vals.push_back(NumArgOperands);
3351 for (unsigned Op = 0; Op != NumArgOperands; ++Op)
3352 pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
3353 break;
3354 }
3355 case Instruction::CatchSwitch: {
3357 const auto &CatchSwitch = cast<CatchSwitchInst>(I);
3358
3359 pushValue(CatchSwitch.getParentPad(), InstID, Vals);
3360
3361 unsigned NumHandlers = CatchSwitch.getNumHandlers();
3362 Vals.push_back(NumHandlers);
3363 for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
3364 Vals.push_back(VE.getValueID(CatchPadBB));
3365
3366 if (CatchSwitch.hasUnwindDest())
3367 Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
3368 break;
3369 }
3370 case Instruction::CallBr: {
3371 const CallBrInst *CBI = cast<CallBrInst>(&I);
3372 const Value *Callee = CBI->getCalledOperand();
3373 FunctionType *FTy = CBI->getFunctionType();
3374
3375 if (CBI->hasOperandBundles())
3376 writeOperandBundles(*CBI, InstID);
3377
3379
3381
3384
3385 Vals.push_back(VE.getValueID(CBI->getDefaultDest()));
3386 Vals.push_back(CBI->getNumIndirectDests());
3387 for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i)
3388 Vals.push_back(VE.getValueID(CBI->getIndirectDest(i)));
3389
3390 Vals.push_back(VE.getTypeID(FTy));
3391 pushValueAndType(Callee, InstID, Vals);
3392
3393 // Emit value #'s for the fixed parameters.
3394 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3395 pushValue(I.getOperand(i), InstID, Vals); // fixed param.
3396
3397 // Emit type/value pairs for varargs params.
3398 if (FTy->isVarArg()) {
3399 for (unsigned i = FTy->getNumParams(), e = CBI->arg_size(); i != e; ++i)
3400 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
3401 }
3402 break;
3403 }
3404 case Instruction::Unreachable:
3406 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
3407 break;
3408
3409 case Instruction::PHI: {
3410 const PHINode &PN = cast<PHINode>(I);
3412 // With the newer instruction encoding, forward references could give
3413 // negative valued IDs. This is most common for PHIs, so we use
3414 // signed VBRs.
3416 Vals64.push_back(VE.getTypeID(PN.getType()));
3417 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
3418 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
3419 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
3420 }
3421
3422 uint64_t Flags = getOptimizationFlags(&I);
3423 if (Flags != 0)
3424 Vals64.push_back(Flags);
3425
3426 // Emit a Vals64 vector and exit.
3427 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
3428 Vals64.clear();
3429 return;
3430 }
3431
3432 case Instruction::LandingPad: {
3433 const LandingPadInst &LP = cast<LandingPadInst>(I);
3435 Vals.push_back(VE.getTypeID(LP.getType()));
3436 Vals.push_back(LP.isCleanup());
3437 Vals.push_back(LP.getNumClauses());
3438 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
3439 if (LP.isCatch(I))
3441 else
3443 pushValueAndType(LP.getClause(I), InstID, Vals);
3444 }
3445 break;
3446 }
3447
3448 case Instruction::Alloca: {
3450 const AllocaInst &AI = cast<AllocaInst>(I);
3451 Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
3452 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
3453 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
3454 using APV = AllocaPackedValues;
3455 unsigned Record = 0;
3456 unsigned EncodedAlign = getEncodedAlign(AI.getAlign());
3458 Record, EncodedAlign & ((1 << APV::AlignLower::Bits) - 1));
3460 EncodedAlign >> APV::AlignLower::Bits);
3464 Vals.push_back(Record);
3465
3466 unsigned AS = AI.getAddressSpace();
3467 if (AS != M.getDataLayout().getAllocaAddrSpace())
3468 Vals.push_back(AS);
3469 break;
3470 }
3471
3472 case Instruction::Load:
3473 if (cast<LoadInst>(I).isAtomic()) {
3475 pushValueAndType(I.getOperand(0), InstID, Vals);
3476 } else {
3478 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
3479 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
3480 }
3481 Vals.push_back(VE.getTypeID(I.getType()));
3482 Vals.push_back(getEncodedAlign(cast<LoadInst>(I).getAlign()));
3483 Vals.push_back(cast<LoadInst>(I).isVolatile());
3484 if (cast<LoadInst>(I).isAtomic()) {
3485 Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
3486 Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID()));
3487 }
3488 break;
3489 case Instruction::Store:
3490 if (cast<StoreInst>(I).isAtomic()) {
3492 } else {
3494 AbbrevToUse = FUNCTION_INST_STORE_ABBREV;
3495 }
3496 if (pushValueAndType(I.getOperand(1), InstID, Vals)) // ptrty + ptr
3497 AbbrevToUse = 0;
3498 if (pushValueAndType(I.getOperand(0), InstID, Vals)) // valty + val
3499 AbbrevToUse = 0;
3500 Vals.push_back(getEncodedAlign(cast<StoreInst>(I).getAlign()));
3501 Vals.push_back(cast<StoreInst>(I).isVolatile());
3502 if (cast<StoreInst>(I).isAtomic()) {
3503 Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
3504 Vals.push_back(
3505 getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID()));
3506 }
3507 break;
3508 case Instruction::AtomicCmpXchg:
3510 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
3511 pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
3512 pushValue(I.getOperand(2), InstID, Vals); // newval.
3513 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
3514 Vals.push_back(
3515 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
3516 Vals.push_back(
3517 getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID()));
3518 Vals.push_back(
3519 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
3520 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
3521 Vals.push_back(getEncodedAlign(cast<AtomicCmpXchgInst>(I).getAlign()));
3522 break;
3523 case Instruction::AtomicRMW:
3525 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
3526 pushValueAndType(I.getOperand(1), InstID, Vals); // valty + val
3527 Vals.push_back(
3529 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
3530 Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
3531 Vals.push_back(
3532 getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID()));
3533 Vals.push_back(getEncodedAlign(cast<AtomicRMWInst>(I).getAlign()));
3534 break;
3535 case Instruction::Fence:
3537 Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
3538 Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID()));
3539 break;
3540 case Instruction::Call: {
3541 const CallInst &CI = cast<CallInst>(I);
3542 FunctionType *FTy = CI.getFunctionType();
3543
3544 if (CI.hasOperandBundles())
3545 writeOperandBundles(CI, InstID);
3546
3548
3550
3551 unsigned Flags = getOptimizationFlags(&I);
3553 unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
3554 unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
3556 unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
3557 unsigned(Flags != 0) << bitc::CALL_FMF);
3558 if (Flags != 0)
3559 Vals.push_back(Flags);
3560
3561 Vals.push_back(VE.getTypeID(FTy));
3562 pushValueAndType(CI.getCalledOperand(), InstID, Vals); // Callee
3563
3564 // Emit value #'s for the fixed parameters.
3565 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3566 pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
3567
3568 // Emit type/value pairs for varargs params.
3569 if (FTy->isVarArg()) {
3570 for (unsigned i = FTy->getNumParams(), e = CI.arg_size(); i != e; ++i)
3571 pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
3572 }
3573 break;
3574 }
3575 case Instruction::VAArg:
3577 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
3578 pushValue(I.getOperand(0), InstID, Vals); // valist.
3579 Vals.push_back(VE.getTypeID(I.getType())); // restype.
3580 break;
3581 case Instruction::Freeze:
3583 pushValueAndType(I.getOperand(0), InstID, Vals);
3584 break;
3585 }
3586
3587 Stream.EmitRecord(Code, Vals, AbbrevToUse);
3588 Vals.clear();
3589}
3590
3591/// Write a GlobalValue VST to the module. The purpose of this data structure is
3592/// to allow clients to efficiently find the function body.
3593void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
3594 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3595 // Get the offset of the VST we are writing, and backpatch it into
3596 // the VST forward declaration record.
3597 uint64_t VSTOffset = Stream.GetCurrentBitNo();
3598 // The BitcodeStartBit was the stream offset of the identification block.
3599 VSTOffset -= bitcodeStartBit();
3600 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
3601 // Note that we add 1 here because the offset is relative to one word
3602 // before the start of the identification block, which was historically
3603 // always the start of the regular bitcode header.
3604 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
3605
3607
3608 auto Abbv = std::make_shared<BitCodeAbbrev>();
3609 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
3610 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3611 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
3612 unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3613
3614 for (const Function &F : M) {
3615 uint64_t Record[2];
3616
3617 if (F.isDeclaration())
3618 continue;
3619
3620 Record[0] = VE.getValueID(&F);
3621
3622 // Save the word offset of the function (from the start of the
3623 // actual bitcode written to the stream).
3624 uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit();
3625 assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
3626 // Note that we add 1 here because the offset is relative to one word
3627 // before the start of the identification block, which was historically
3628 // always the start of the regular bitcode header.
3629 Record[1] = BitcodeIndex / 32 + 1;
3630
3631 Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev);
3632 }
3633
3634 Stream.ExitBlock();
3635}
3636
3637/// Emit names for arguments, instructions and basic blocks in a function.
3638void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
3639 const ValueSymbolTable &VST) {
3640 if (VST.empty())
3641 return;
3642
3644
3645 // FIXME: Set up the abbrev, we know how many values there are!
3646 // FIXME: We know if the type names can use 7-bit ascii.
3647 SmallVector<uint64_t, 64> NameVals;
3648
3649 for (const ValueName &Name : VST) {
3650 // Figure out the encoding to use for the name.
3652
3653 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
3654 NameVals.push_back(VE.getValueID(Name.getValue()));
3655
3656 // VST_CODE_ENTRY: [valueid, namechar x N]
3657 // VST_CODE_BBENTRY: [bbid, namechar x N]
3658 unsigned Code;
3659 if (isa<BasicBlock>(Name.getValue())) {
3661 if (Bits == SE_Char6)
3662 AbbrevToUse = VST_BBENTRY_6_ABBREV;
3663 } else {
3665 if (Bits == SE_Char6)
3666 AbbrevToUse = VST_ENTRY_6_ABBREV;
3667 else if (Bits == SE_Fixed7)
3668 AbbrevToUse = VST_ENTRY_7_ABBREV;
3669 }
3670
3671 for (const auto P : Name.getKey())
3672 NameVals.push_back((unsigned char)P);
3673
3674 // Emit the finished record.
3675 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
3676 NameVals.clear();
3677 }
3678
3679 Stream.ExitBlock();
3680}
3681
3682void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
3683 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
3684 unsigned Code;
3685 if (isa<BasicBlock>(Order.V))
3687 else
3689
3690 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
3691 Record.push_back(VE.getValueID(Order.V));
3692 Stream.EmitRecord(Code, Record);
3693}
3694
3695void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
3697 "Expected to be preserving use-list order");
3698
3699 auto hasMore = [&]() {
3700 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
3701 };
3702 if (!hasMore())
3703 // Nothing to do.
3704 return;
3705
3707 while (hasMore()) {
3708 writeUseList(std::move(VE.UseListOrders.back()));
3709 VE.UseListOrders.pop_back();
3710 }
3711 Stream.ExitBlock();
3712}
3713
3714/// Emit a function body to the module stream.
3715void ModuleBitcodeWriter::writeFunction(
3716 const Function &F,
3717 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3718 // Save the bitcode index of the start of this function block for recording
3719 // in the VST.
3720 FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
3721
3724
3726
3727 // Emit the number of basic blocks, so the reader can create them ahead of
3728 // time.
3729 Vals.push_back(VE.getBasicBlocks().size());
3731 Vals.clear();
3732
3733 // If there are function-local constants, emit them now.
3734 unsigned CstStart, CstEnd;
3735 VE.getFunctionConstantRange(CstStart, CstEnd);
3736 writeConstants(CstStart, CstEnd, false);
3737
3738 // If there is function-local metadata, emit it now.
3739 writeFunctionMetadata(F);
3740
3741 // Keep a running idea of what the instruction ID is.
3742 unsigned InstID = CstEnd;
3743
3744 bool NeedsMetadataAttachment = F.hasMetadata();
3745
3746 DILocation *LastDL = nullptr;
3747 SmallSetVector<Function *, 4> BlockAddressUsers;
3748
3749 // Finally, emit all the instructions, in order.
3750 for (const BasicBlock &BB : F) {
3751 for (const Instruction &I : BB) {
3752 writeInstruction(I, InstID, Vals);
3753
3754 if (!I.getType()->isVoidTy())
3755 ++InstID;
3756
3757 // If the instruction has metadata, write a metadata attachment later.
3758 NeedsMetadataAttachment |= I.hasMetadataOtherThanDebugLoc();
3759
3760 // If the instruction has a debug location, emit it.
3761 if (DILocation *DL = I.getDebugLoc()) {
3762 if (DL == LastDL) {
3763 // Just repeat the same debug loc as last time.
3765 } else {
3766 Vals.push_back(DL->getLine());
3767 Vals.push_back(DL->getColumn());
3768 Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
3769 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
3770 Vals.push_back(DL->isImplicitCode());
3771 Vals.push_back(DL->getAtomGroup());
3772 Vals.push_back(DL->getAtomRank());
3774 FUNCTION_DEBUG_LOC_ABBREV);
3775 Vals.clear();
3776 LastDL = DL;
3777 }
3778 }
3779
3780 // If the instruction has DbgRecords attached to it, emit them. Note that
3781 // they come after the instruction so that it's easy to attach them again
3782 // when reading the bitcode, even though conceptually the debug locations
3783 // start "before" the instruction.
3784 if (I.hasDbgRecords()) {
3785 /// Try to push the value only (unwrapped), otherwise push the
3786 /// metadata wrapped value. Returns true if the value was pushed
3787 /// without the ValueAsMetadata wrapper.
3788 auto PushValueOrMetadata = [&Vals, InstID,
3789 this](Metadata *RawLocation) {
3790 assert(RawLocation &&
3791 "RawLocation unexpectedly null in DbgVariableRecord");
3792 if (ValueAsMetadata *VAM = dyn_cast<ValueAsMetadata>(RawLocation)) {
3793 SmallVector<unsigned, 2> ValAndType;
3794 // If the value is a fwd-ref the type is also pushed. We don't
3795 // want the type, so fwd-refs are kept wrapped (pushValueAndType
3796 // returns false if the value is pushed without type).
3797 if (!pushValueAndType(VAM->getValue(), InstID, ValAndType)) {
3798 Vals.push_back(ValAndType[0]);
3799 return true;
3800 }
3801 }
3802 // The metadata is a DIArgList, or ValueAsMetadata wrapping a
3803 // fwd-ref. Push the metadata ID.
3804 Vals.push_back(VE.getMetadataID(RawLocation));
3805 return false;
3806 };
3807
3808 // Write out non-instruction debug information attached to this
3809 // instruction. Write it after the instruction so that it's easy to
3810 // re-attach to the instruction reading the records in.
3811 for (DbgRecord &DR : I.DebugMarker->getDbgRecordRange()) {
3812 if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) {
3813 Vals.push_back(VE.getMetadataID(&*DLR->getDebugLoc()));
3814 Vals.push_back(VE.getMetadataID(DLR->getLabel()));
3816 Vals.clear();
3817 continue;
3818 }
3819
3820 // First 3 fields are common to all kinds:
3821 // DILocation, DILocalVariable, DIExpression
3822 // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE)
3823 // ..., LocationMetadata
3824 // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE - abbrev'd)
3825 // ..., Value
3826 // dbg_declare (FUNC_CODE_DEBUG_RECORD_DECLARE)
3827 // ..., LocationMetadata
3828 // dbg_assign (FUNC_CODE_DEBUG_RECORD_ASSIGN)
3829 // ..., LocationMetadata, DIAssignID, DIExpression, LocationMetadata
3830 DbgVariableRecord &DVR = cast<DbgVariableRecord>(DR);
3831 Vals.push_back(VE.getMetadataID(&*DVR.getDebugLoc()));
3832 Vals.push_back(VE.getMetadataID(DVR.getVariable()));
3833 Vals.push_back(VE.getMetadataID(DVR.getExpression()));
3834 if (DVR.isDbgValue()) {
3835 if (PushValueOrMetadata(DVR.getRawLocation()))
3837 FUNCTION_DEBUG_RECORD_VALUE_ABBREV);
3838 else
3840 } else if (DVR.isDbgDeclare()) {
3841 Vals.push_back(VE.getMetadataID(DVR.getRawLocation()));
3843 } else {
3844 assert(DVR.isDbgAssign() && "Unexpected DbgRecord kind");
3845 Vals.push_back(VE.getMetadataID(DVR.getRawLocation()));
3846 Vals.push_back(VE.getMetadataID(DVR.getAssignID()));
3848 Vals.push_back(VE.getMetadataID(DVR.getRawAddress()));
3850 }
3851 Vals.clear();
3852 }
3853 }
3854 }
3855
3856 if (BlockAddress *BA = BlockAddress::lookup(&BB)) {
3857 SmallVector<Value *> Worklist{BA};
3858 SmallPtrSet<Value *, 8> Visited{BA};
3859 while (!Worklist.empty()) {
3860 Value *V = Worklist.pop_back_val();
3861 for (User *U : V->users()) {
3862 if (auto *I = dyn_cast<Instruction>(U)) {
3863 Function *P = I->getFunction();
3864 if (P != &F)
3865 BlockAddressUsers.insert(P);
3866 } else if (isa<Constant>(U) && !isa<GlobalValue>(U) &&
3867 Visited.insert(U).second)
3868 Worklist.push_back(U);
3869 }
3870 }
3871 }
3872 }
3873
3874 if (!BlockAddressUsers.empty()) {
3875 Vals.resize(BlockAddressUsers.size());
3876 for (auto I : llvm::enumerate(BlockAddressUsers))
3877 Vals[I.index()] = VE.getValueID(I.value());
3879 Vals.clear();
3880 }
3881
3882 // Emit names for all the instructions etc.
3883 if (auto *Symtab = F.getValueSymbolTable())
3884 writeFunctionLevelValueSymbolTable(*Symtab);
3885
3886 if (NeedsMetadataAttachment)
3887 writeFunctionMetadataAttachment(F);
3889 writeUseListBlock(&F);
3890 VE.purgeFunction();
3891 Stream.ExitBlock();
3892}
3893
3894// Emit blockinfo, which defines the standard abbreviations etc.
3895void ModuleBitcodeWriter::writeBlockInfo() {
3896 // We only want to emit block info records for blocks that have multiple
3897 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
3898 // Other blocks can define their abbrevs inline.
3899 Stream.EnterBlockInfoBlock();
3900
3901 // Encode type indices using fixed size based on number of types.
3902 BitCodeAbbrevOp TypeAbbrevOp(BitCodeAbbrevOp::Fixed,
3904 // Encode value indices as 6-bit VBR.
3905 BitCodeAbbrevOp ValAbbrevOp(BitCodeAbbrevOp::VBR, 6);
3906
3907 { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
3908 auto Abbv = std::make_shared<BitCodeAbbrev>();
3909 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
3910 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3911 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3912 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
3914 VST_ENTRY_8_ABBREV)
3915 llvm_unreachable("Unexpected abbrev ordering!");
3916 }
3917
3918 { // 7-bit fixed width VST_CODE_ENTRY strings.
3919 auto Abbv = std::make_shared<BitCodeAbbrev>();
3920 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
3921 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3922 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3923 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
3925 VST_ENTRY_7_ABBREV)
3926 llvm_unreachable("Unexpected abbrev ordering!");
3927 }
3928 { // 6-bit char6 VST_CODE_ENTRY strings.
3929 auto Abbv = std::make_shared<BitCodeAbbrev>();
3930 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
3931 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3932 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3933 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3935 VST_ENTRY_6_ABBREV)
3936 llvm_unreachable("Unexpected abbrev ordering!");
3937 }
3938 { // 6-bit char6 VST_CODE_BBENTRY strings.
3939 auto Abbv = std::make_shared<BitCodeAbbrev>();
3940 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
3941 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3942 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3943 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3945 VST_BBENTRY_6_ABBREV)
3946 llvm_unreachable("Unexpected abbrev ordering!");
3947 }
3948
3949 { // SETTYPE abbrev for CONSTANTS_BLOCK.
3950 auto Abbv = std::make_shared<BitCodeAbbrev>();
3951 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
3952 Abbv->Add(TypeAbbrevOp);
3954 CONSTANTS_SETTYPE_ABBREV)
3955 llvm_unreachable("Unexpected abbrev ordering!");
3956 }
3957
3958 { // INTEGER abbrev for CONSTANTS_BLOCK.
3959 auto Abbv = std::make_shared<BitCodeAbbrev>();
3960 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
3961 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3963 CONSTANTS_INTEGER_ABBREV)
3964 llvm_unreachable("Unexpected abbrev ordering!");
3965 }
3966
3967 { // CE_CAST abbrev for CONSTANTS_BLOCK.
3968 auto Abbv = std::make_shared<BitCodeAbbrev>();
3969 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
3970 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
3971 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
3973 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3974
3976 CONSTANTS_CE_CAST_Abbrev)
3977 llvm_unreachable("Unexpected abbrev ordering!");
3978 }
3979 { // NULL abbrev for CONSTANTS_BLOCK.
3980 auto Abbv = std::make_shared<BitCodeAbbrev>();
3981 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
3983 CONSTANTS_NULL_Abbrev)
3984 llvm_unreachable("Unexpected abbrev ordering!");
3985 }
3986
3987 // FIXME: This should only use space for first class types!
3988
3989 { // INST_LOAD abbrev for FUNCTION_BLOCK.
3990 auto Abbv = std::make_shared<BitCodeAbbrev>();
3991 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
3992 Abbv->Add(ValAbbrevOp); // Ptr
3993 Abbv->Add(TypeAbbrevOp); // dest ty
3994 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
3995 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
3996 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3997 FUNCTION_INST_LOAD_ABBREV)
3998 llvm_unreachable("Unexpected abbrev ordering!");
3999 }
4000 {
4001 auto Abbv = std::make_shared<BitCodeAbbrev>();
4002 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_STORE));
4003 Abbv->Add(ValAbbrevOp); // op1
4004 Abbv->Add(ValAbbrevOp); // op0
4005 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // align
4006 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
4007 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4008 FUNCTION_INST_STORE_ABBREV)
4009 llvm_unreachable("Unexpected abbrev ordering!");
4010 }
4011 { // INST_UNOP abbrev for FUNCTION_BLOCK.
4012 auto Abbv = std::make_shared<BitCodeAbbrev>();
4013 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP));
4014 Abbv->Add(ValAbbrevOp); // LHS
4015 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
4016 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4017 FUNCTION_INST_UNOP_ABBREV)
4018 llvm_unreachable("Unexpected abbrev ordering!");
4019 }
4020 { // INST_UNOP_FLAGS abbrev for FUNCTION_BLOCK.
4021 auto Abbv = std::make_shared<BitCodeAbbrev>();
4022 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP));
4023 Abbv->Add(ValAbbrevOp); // LHS
4024 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
4025 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
4026 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4027 FUNCTION_INST_UNOP_FLAGS_ABBREV)
4028 llvm_unreachable("Unexpected abbrev ordering!");
4029 }
4030 { // INST_BINOP abbrev for FUNCTION_BLOCK.
4031 auto Abbv = std::make_shared<BitCodeAbbrev>();
4032 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
4033 Abbv->Add(ValAbbrevOp); // LHS
4034 Abbv->Add(ValAbbrevOp); // RHS
4035 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
4036 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4037 FUNCTION_INST_BINOP_ABBREV)
4038 llvm_unreachable("Unexpected abbrev ordering!");
4039 }
4040 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
4041 auto Abbv = std::make_shared<BitCodeAbbrev>();
4042 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
4043 Abbv->Add(ValAbbrevOp); // LHS
4044 Abbv->Add(ValAbbrevOp); // RHS
4045 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
4046 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
4047 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4048 FUNCTION_INST_BINOP_FLAGS_ABBREV)
4049 llvm_unreachable("Unexpected abbrev ordering!");
4050 }
4051 { // INST_CAST abbrev for FUNCTION_BLOCK.
4052 auto Abbv = std::make_shared<BitCodeAbbrev>();
4053 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
4054 Abbv->Add(ValAbbrevOp); // OpVal
4055 Abbv->Add(TypeAbbrevOp); // dest ty
4056 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
4057 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4058 FUNCTION_INST_CAST_ABBREV)
4059 llvm_unreachable("Unexpected abbrev ordering!");
4060 }
4061 { // INST_CAST_FLAGS abbrev for FUNCTION_BLOCK.
4062 auto Abbv = std::make_shared<BitCodeAbbrev>();
4063 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
4064 Abbv->Add(ValAbbrevOp); // OpVal
4065 Abbv->Add(TypeAbbrevOp); // dest ty
4066 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
4067 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
4068 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4069 FUNCTION_INST_CAST_FLAGS_ABBREV)
4070 llvm_unreachable("Unexpected abbrev ordering!");
4071 }
4072
4073 { // INST_RET abbrev for FUNCTION_BLOCK.
4074 auto Abbv = std::make_shared<BitCodeAbbrev>();
4075 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
4076 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4077 FUNCTION_INST_RET_VOID_ABBREV)
4078 llvm_unreachable("Unexpected abbrev ordering!");
4079 }
4080 { // INST_RET abbrev for FUNCTION_BLOCK.
4081 auto Abbv = std::make_shared<BitCodeAbbrev>();
4082 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
4083 Abbv->Add(ValAbbrevOp);
4084 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4085 FUNCTION_INST_RET_VAL_ABBREV)
4086 llvm_unreachable("Unexpected abbrev ordering!");
4087 }
4088 {
4089 auto Abbv = std::make_shared<BitCodeAbbrev>();
4090 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BR));
4091 // TODO: Use different abbrev for absolute value reference (succ0)?
4092 Abbv->Add(ValAbbrevOp); // succ0
4093 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4094 FUNCTION_INST_BR_UNCOND_ABBREV)
4095 llvm_unreachable("Unexpected abbrev ordering!");
4096 }
4097 {
4098 auto Abbv = std::make_shared<BitCodeAbbrev>();
4099 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BR));
4100 // TODO: Use different abbrev for absolute value references (succ0, succ1)?
4101 Abbv->Add(ValAbbrevOp); // succ0
4102 Abbv->Add(ValAbbrevOp); // succ1
4103 Abbv->Add(ValAbbrevOp); // cond
4104 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4105 FUNCTION_INST_BR_COND_ABBREV)
4106 llvm_unreachable("Unexpected abbrev ordering!");
4107 }
4108 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
4109 auto Abbv = std::make_shared<BitCodeAbbrev>();
4110 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
4111 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4112 FUNCTION_INST_UNREACHABLE_ABBREV)
4113 llvm_unreachable("Unexpected abbrev ordering!");
4114 }
4115 {
4116 auto Abbv = std::make_shared<BitCodeAbbrev>();
4117 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
4118 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // flags
4119 Abbv->Add(TypeAbbrevOp); // dest ty
4120 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4121 Abbv->Add(ValAbbrevOp);
4122 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4123 FUNCTION_INST_GEP_ABBREV)
4124 llvm_unreachable("Unexpected abbrev ordering!");
4125 }
4126 {
4127 auto Abbv = std::make_shared<BitCodeAbbrev>();
4128 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CMP2));
4129 Abbv->Add(ValAbbrevOp); // op0
4130 Abbv->Add(ValAbbrevOp); // op1
4131 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 6)); // pred
4132 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4133 FUNCTION_INST_CMP_ABBREV)
4134 llvm_unreachable("Unexpected abbrev ordering!");
4135 }
4136 {
4137 auto Abbv = std::make_shared<BitCodeAbbrev>();
4138 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CMP2));
4139 Abbv->Add(ValAbbrevOp); // op0
4140 Abbv->Add(ValAbbrevOp); // op1
4141 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 6)); // pred
4142 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
4143 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4144 FUNCTION_INST_CMP_FLAGS_ABBREV)
4145 llvm_unreachable("Unexpected abbrev ordering!");
4146 }
4147 {
4148 auto Abbv = std::make_shared<BitCodeAbbrev>();
4149 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE));
4150 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // dbgloc
4151 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // var
4152 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // expr
4153 Abbv->Add(ValAbbrevOp); // val
4154 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4155 FUNCTION_DEBUG_RECORD_VALUE_ABBREV)
4156 llvm_unreachable("Unexpected abbrev ordering! 1");
4157 }
4158 {
4159 auto Abbv = std::make_shared<BitCodeAbbrev>();
4160 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_DEBUG_LOC));
4161 // NOTE: No IsDistinct field for FUNC_CODE_DEBUG_LOC.
4162 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4163 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4164 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4165 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4166 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
4167 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Atom group.
4168 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3)); // Atom rank.
4169 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4170 FUNCTION_DEBUG_LOC_ABBREV)
4171 llvm_unreachable("Unexpected abbrev ordering!");
4172 }
4173 Stream.ExitBlock();
4174}
4175
4176/// Write the module path strings, currently only used when generating
4177/// a combined index file.
4178void IndexBitcodeWriter::writeModStrings() {
4180
4181 // TODO: See which abbrev sizes we actually need to emit
4182
4183 // 8-bit fixed-width MST_ENTRY strings.
4184 auto Abbv = std::make_shared<BitCodeAbbrev>();
4185 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
4186 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4187 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4188 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
4189 unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
4190
4191 // 7-bit fixed width MST_ENTRY strings.
4192 Abbv = std::make_shared<BitCodeAbbrev>();
4193 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
4194 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4195 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4196 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
4197 unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
4198
4199 // 6-bit char6 MST_ENTRY strings.
4200 Abbv = std::make_shared<BitCodeAbbrev>();
4201 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
4202 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4203 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4204 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
4205 unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
4206
4207 // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
4208 Abbv = std::make_shared<BitCodeAbbrev>();
4209 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH));
4210 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4211 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4212 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4213 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4214 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4215 unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
4216
4218 forEachModule([&](const StringMapEntry<ModuleHash> &MPSE) {
4219 StringRef Key = MPSE.getKey();
4220 const auto &Hash = MPSE.getValue();
4222 unsigned AbbrevToUse = Abbrev8Bit;
4223 if (Bits == SE_Char6)
4224 AbbrevToUse = Abbrev6Bit;
4225 else if (Bits == SE_Fixed7)
4226 AbbrevToUse = Abbrev7Bit;
4227
4228 auto ModuleId = ModuleIdMap.size();
4229 ModuleIdMap[Key] = ModuleId;
4230 Vals.push_back(ModuleId);
4231 Vals.append(Key.begin(), Key.end());
4232
4233 // Emit the finished record.
4234 Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
4235
4236 // Emit an optional hash for the module now
4237 if (llvm::any_of(Hash, [](uint32_t H) { return H; })) {
4238 Vals.assign(Hash.begin(), Hash.end());
4239 // Emit the hash record.
4240 Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
4241 }
4242
4243 Vals.clear();
4244 });
4245 Stream.ExitBlock();
4246}
4247
4248/// Write the function type metadata related records that need to appear before
4249/// a function summary entry (whether per-module or combined).
4250template <typename Fn>
4252 FunctionSummary *FS,
4253 Fn GetValueID) {
4254 if (!FS->type_tests().empty())
4255 Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
4256
4258
4259 auto WriteVFuncIdVec = [&](uint64_t Ty,
4261 if (VFs.empty())
4262 return;
4263 Record.clear();
4264 for (auto &VF : VFs) {
4265 Record.push_back(VF.GUID);
4266 Record.push_back(VF.Offset);
4267 }
4268 Stream.EmitRecord(Ty, Record);
4269 };
4270
4271 WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
4272 FS->type_test_assume_vcalls());
4273 WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
4274 FS->type_checked_load_vcalls());
4275
4276 auto WriteConstVCallVec = [&](uint64_t Ty,
4278 for (auto &VC : VCs) {
4279 Record.clear();
4280 Record.push_back(VC.VFunc.GUID);
4281 Record.push_back(VC.VFunc.Offset);
4282 llvm::append_range(Record, VC.Args);
4283 Stream.EmitRecord(Ty, Record);
4284 }
4285 };
4286
4287 WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
4288 FS->type_test_assume_const_vcalls());
4289 WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
4290 FS->type_checked_load_const_vcalls());
4291
4292 auto WriteRange = [&](ConstantRange Range) {
4294 assert(Range.getLower().getNumWords() == 1);
4295 assert(Range.getUpper().getNumWords() == 1);
4296 emitSignedInt64(Record, *Range.getLower().getRawData());
4297 emitSignedInt64(Record, *Range.getUpper().getRawData());
4298 };
4299
4300 if (!FS->paramAccesses().empty()) {
4301 Record.clear();
4302 for (auto &Arg : FS->paramAccesses()) {
4303 size_t UndoSize = Record.size();
4304 Record.push_back(Arg.ParamNo);
4305 WriteRange(Arg.Use);
4306 Record.push_back(Arg.Calls.size());
4307 for (auto &Call : Arg.Calls) {
4308 Record.push_back(Call.ParamNo);
4309 std::optional<unsigned> ValueID = GetValueID(Call.Callee);
4310 if (!ValueID) {
4311 // If ValueID is unknown we can't drop just this call, we must drop
4312 // entire parameter.
4313 Record.resize(UndoSize);
4314 break;
4315 }
4316 Record.push_back(*ValueID);
4317 WriteRange(Call.Offsets);
4318 }
4319 }
4320 if (!Record.empty())
4322 }
4323}
4324
4325/// Collect type IDs from type tests used by function.
4326static void
4328 std::set<GlobalValue::GUID> &ReferencedTypeIds) {
4329 if (!FS->type_tests().empty())
4330 for (auto &TT : FS->type_tests())
4331 ReferencedTypeIds.insert(TT);
4332
4333 auto GetReferencedTypesFromVFuncIdVec =
4335 for (auto &VF : VFs)
4336 ReferencedTypeIds.insert(VF.GUID);
4337 };
4338
4339 GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls());
4340 GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls());
4341
4342 auto GetReferencedTypesFromConstVCallVec =
4344 for (auto &VC : VCs)
4345 ReferencedTypeIds.insert(VC.VFunc.GUID);
4346 };
4347
4348 GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls());
4349 GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls());
4350}
4351
4353 SmallVector<uint64_t, 64> &NameVals, const std::vector<uint64_t> &args,
4355 NameVals.push_back(args.size());
4356 llvm::append_range(NameVals, args);
4357
4358 NameVals.push_back(ByArg.TheKind);
4359 NameVals.push_back(ByArg.Info);
4360 NameVals.push_back(ByArg.Byte);
4361 NameVals.push_back(ByArg.Bit);
4362}
4363
4365 SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
4366 uint64_t Id, const WholeProgramDevirtResolution &Wpd) {
4367 NameVals.push_back(Id);
4368
4369 NameVals.push_back(Wpd.TheKind);
4370 NameVals.push_back(StrtabBuilder.add(Wpd.SingleImplName));
4371 NameVals.push_back(Wpd.SingleImplName.size());
4372
4373 NameVals.push_back(Wpd.ResByArg.size());
4374 for (auto &A : Wpd.ResByArg)
4375 writeWholeProgramDevirtResolutionByArg(NameVals, A.first, A.second);
4376}
4377
4379 StringTableBuilder &StrtabBuilder,
4380 StringRef Id,
4381 const TypeIdSummary &Summary) {
4382 NameVals.push_back(StrtabBuilder.add(Id));
4383 NameVals.push_back(Id.size());
4384
4385 NameVals.push_back(Summary.TTRes.TheKind);
4386 NameVals.push_back(Summary.TTRes.SizeM1BitWidth);
4387 NameVals.push_back(Summary.TTRes.AlignLog2);
4388 NameVals.push_back(Summary.TTRes.SizeM1);
4389 NameVals.push_back(Summary.TTRes.BitMask);
4390 NameVals.push_back(Summary.TTRes.InlineBits);
4391
4392 for (auto &W : Summary.WPDRes)
4393 writeWholeProgramDevirtResolution(NameVals, StrtabBuilder, W.first,
4394 W.second);
4395}
4396
4398 SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
4399 StringRef Id, const TypeIdCompatibleVtableInfo &Summary,
4401 NameVals.push_back(StrtabBuilder.add(Id));
4402 NameVals.push_back(Id.size());
4403
4404 for (auto &P : Summary) {
4405 NameVals.push_back(P.AddressPointOffset);
4406 NameVals.push_back(VE.getValueID(P.VTableVI.getValue()));
4407 }
4408}
4409
4410// Adds the allocation contexts to the CallStacks map. We simply use the
4411// size at the time the context was added as the CallStackId. This works because
4412// when we look up the call stacks later on we process the function summaries
4413// and their allocation records in the same exact order.
4415 FunctionSummary *FS, std::function<LinearFrameId(unsigned)> GetStackIndex,
4417 // The interfaces in ProfileData/MemProf.h use a type alias for a stack frame
4418 // id offset into the index of the full stack frames. The ModuleSummaryIndex
4419 // currently uses unsigned. Make sure these stay in sync.
4420 static_assert(std::is_same_v<LinearFrameId, unsigned>);
4421 for (auto &AI : FS->allocs()) {
4422 for (auto &MIB : AI.MIBs) {
4423 SmallVector<unsigned> StackIdIndices;
4424 StackIdIndices.reserve(MIB.StackIdIndices.size());
4425 for (auto Id : MIB.StackIdIndices)
4426 StackIdIndices.push_back(GetStackIndex(Id));
4427 // The CallStackId is the size at the time this context was inserted.
4428 CallStacks.insert({CallStacks.size(), StackIdIndices});
4429 }
4430 }
4431}
4432
4433// Build the radix tree from the accumulated CallStacks, write out the resulting
4434// linearized radix tree array, and return the map of call stack positions into
4435// this array for use when writing the allocation records. The returned map is
4436// indexed by a CallStackId which in this case is implicitly determined by the
4437// order of function summaries and their allocation infos being written.
4440 BitstreamWriter &Stream, unsigned RadixAbbrev) {
4441 assert(!CallStacks.empty());
4442 DenseMap<unsigned, FrameStat> FrameHistogram =
4445 // We don't need a MemProfFrameIndexes map as we have already converted the
4446 // full stack id hash to a linear offset into the StackIds array.
4447 Builder.build(std::move(CallStacks), /*MemProfFrameIndexes=*/nullptr,
4448 FrameHistogram);
4449 Stream.EmitRecord(bitc::FS_CONTEXT_RADIX_TREE_ARRAY, Builder.getRadixArray(),
4450 RadixAbbrev);
4451 return Builder.takeCallStackPos();
4452}
4453
4455 BitstreamWriter &Stream, FunctionSummary *FS, unsigned CallsiteAbbrev,
4456 unsigned AllocAbbrev, unsigned ContextIdAbbvId, bool PerModule,
4457 std::function<unsigned(const ValueInfo &VI)> GetValueID,
4458 std::function<unsigned(unsigned)> GetStackIndex,
4459 bool WriteContextSizeInfoIndex,
4461 CallStackId &CallStackCount) {
4463
4464 for (auto &CI : FS->callsites()) {
4465 Record.clear();
4466 // Per module callsite clones should always have a single entry of
4467 // value 0.
4468 assert(!PerModule || (CI.Clones.size() == 1 && CI.Clones[0] == 0));
4469 Record.push_back(GetValueID(CI.Callee));
4470 if (!PerModule) {
4471 Record.push_back(CI.StackIdIndices.size());
4472 Record.push_back(CI.Clones.size());
4473 }
4474 for (auto Id : CI.StackIdIndices)
4475 Record.push_back(GetStackIndex(Id));
4476 if (!PerModule)
4477 llvm::append_range(Record, CI.Clones);
4480 Record, CallsiteAbbrev);
4481 }
4482
4483 for (auto &AI : FS->allocs()) {
4484 Record.clear();
4485 // Per module alloc versions should always have a single entry of
4486 // value 0.
4487 assert(!PerModule || (AI.Versions.size() == 1 && AI.Versions[0] == 0));
4488 Record.push_back(AI.MIBs.size());
4489 if (!PerModule)
4490 Record.push_back(AI.Versions.size());
4491 for (auto &MIB : AI.MIBs) {
4492 Record.push_back((uint8_t)MIB.AllocType);
4493 // The per-module summary always needs to include the alloc context, as we
4494 // use it during the thin link. For the combined index it is optional (see
4495 // comments where CombinedIndexMemProfContext is defined).
4496 if (PerModule || CombinedIndexMemProfContext) {
4497 // Record the index into the radix tree array for this context.
4498 assert(CallStackCount <= CallStackPos.size());
4499 Record.push_back(CallStackPos[CallStackCount++]);
4500 }
4501 }
4502 if (!PerModule)
4503 llvm::append_range(Record, AI.Versions);
4504 assert(AI.ContextSizeInfos.empty() ||
4505 AI.ContextSizeInfos.size() == AI.MIBs.size());
4506 // Optionally emit the context size information if it exists.
4507 if (WriteContextSizeInfoIndex && !AI.ContextSizeInfos.empty()) {
4508 // The abbreviation id for the context ids record should have been created
4509 // if we are emitting the per-module index, which is where we write this
4510 // info.
4511 assert(ContextIdAbbvId);
4512 SmallVector<uint32_t> ContextIds;
4513 // At least one context id per ContextSizeInfos entry (MIB), broken into 2
4514 // halves.
4515 ContextIds.reserve(AI.ContextSizeInfos.size() * 2);
4516 for (auto &Infos : AI.ContextSizeInfos) {
4517 Record.push_back(Infos.size());
4518 for (auto [FullStackId, TotalSize] : Infos) {
4519 // The context ids are emitted separately as a fixed width array,
4520 // which is more efficient than a VBR given that these hashes are
4521 // typically close to 64-bits. The max fixed width entry is 32 bits so
4522 // it is split into 2.
4523 ContextIds.push_back(static_cast<uint32_t>(FullStackId >> 32));
4524 ContextIds.push_back(static_cast<uint32_t>(FullStackId));
4525 Record.push_back(TotalSize);
4526 }
4527 }
4528 // The context ids are expected by the reader to immediately precede the
4529 // associated alloc info record.
4530 Stream.EmitRecord(bitc::FS_ALLOC_CONTEXT_IDS, ContextIds,
4531 ContextIdAbbvId);
4532 }
4533 Stream.EmitRecord(PerModule
4538 Record, AllocAbbrev);
4539 }
4540}
4541
4542// Helper to emit a single function summary record.
4543void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
4544 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
4545 unsigned ValueID, unsigned FSCallsRelBFAbbrev,
4546 unsigned FSCallsProfileAbbrev, unsigned CallsiteAbbrev,
4547 unsigned AllocAbbrev, unsigned ContextIdAbbvId, const Function &F,
4548 DenseMap<CallStackId, LinearCallStackId> &CallStackPos,
4549 CallStackId &CallStackCount) {
4550 NameVals.push_back(ValueID);
4551
4552 FunctionSummary *FS = cast<FunctionSummary>(Summary);
4553
4555 Stream, FS, [&](const ValueInfo &VI) -> std::optional<unsigned> {
4556 return {VE.getValueID(VI.getValue())};
4557 });
4558
4560 Stream, FS, CallsiteAbbrev, AllocAbbrev, ContextIdAbbvId,
4561 /*PerModule*/ true,
4562 /*GetValueId*/ [&](const ValueInfo &VI) { return getValueId(VI); },
4563 /*GetStackIndex*/ [&](unsigned I) { return I; },
4564 /*WriteContextSizeInfoIndex*/ true, CallStackPos, CallStackCount);
4565
4566 auto SpecialRefCnts = FS->specialRefCounts();
4567 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
4568 NameVals.push_back(FS->instCount());
4569 NameVals.push_back(getEncodedFFlags(FS->fflags()));
4570 NameVals.push_back(FS->refs().size());
4571 NameVals.push_back(SpecialRefCnts.first); // rorefcnt
4572 NameVals.push_back(SpecialRefCnts.second); // worefcnt
4573
4574 for (auto &RI : FS->refs())
4575 NameVals.push_back(getValueId(RI));
4576
4577 const bool UseRelBFRecord =
4578 WriteRelBFToSummary && !F.hasProfileData() &&
4580 for (auto &ECI : FS->calls()) {
4581 NameVals.push_back(getValueId(ECI.first));
4582 if (UseRelBFRecord)
4583 NameVals.push_back(getEncodedRelBFCallEdgeInfo(ECI.second));
4584 else
4585 NameVals.push_back(getEncodedHotnessCallEdgeInfo(ECI.second));
4586 }
4587
4588 unsigned FSAbbrev =
4589 (UseRelBFRecord ? FSCallsRelBFAbbrev : FSCallsProfileAbbrev);
4590 unsigned Code =
4592
4593 // Emit the finished record.
4594 Stream.EmitRecord(Code, NameVals, FSAbbrev);
4595 NameVals.clear();
4596}
4597
4598// Collect the global value references in the given variable's initializer,
4599// and emit them in a summary record.
4600void ModuleBitcodeWriterBase::writeModuleLevelReferences(
4601 const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
4602 unsigned FSModRefsAbbrev, unsigned FSModVTableRefsAbbrev) {
4603 auto VI = Index->getValueInfo(V.getGUID());
4604 if (!VI || VI.getSummaryList().empty()) {
4605 // Only declarations should not have a summary (a declaration might however
4606 // have a summary if the def was in module level asm).
4607 assert(V.isDeclaration());
4608 return;
4609 }
4610 auto *Summary = VI.getSummaryList()[0].get();
4611 NameVals.push_back(VE.getValueID(&V));
4612 GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
4613 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
4614 NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
4615
4616 auto VTableFuncs = VS->vTableFuncs();
4617 if (!VTableFuncs.empty())
4618 NameVals.push_back(VS->refs().size());
4619
4620 unsigned SizeBeforeRefs = NameVals.size();
4621 for (auto &RI : VS->refs())
4622 NameVals.push_back(VE.getValueID(RI.getValue()));
4623 // Sort the refs for determinism output, the vector returned by FS->refs() has
4624 // been initialized from a DenseSet.
4625 llvm::sort(drop_begin(NameVals, SizeBeforeRefs));
4626
4627 if (VTableFuncs.empty())
4629 FSModRefsAbbrev);
4630 else {
4631 // VTableFuncs pairs should already be sorted by offset.
4632 for (auto &P : VTableFuncs) {
4633 NameVals.push_back(VE.getValueID(P.FuncVI.getValue()));
4634 NameVals.push_back(P.VTableOffset);
4635 }
4636
4638 FSModVTableRefsAbbrev);
4639 }
4640 NameVals.clear();
4641}
4642
4643/// Emit the per-module summary section alongside the rest of
4644/// the module's bitcode.
4645void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
4646 // By default we compile with ThinLTO if the module has a summary, but the
4647 // client can request full LTO with a module flag.
4648 bool IsThinLTO = true;
4649 if (auto *MD =
4650 mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
4651 IsThinLTO = MD->getZExtValue();
4654 4);
4655
4656 Stream.EmitRecord(
4658 ArrayRef<uint64_t>{ModuleSummaryIndex::BitcodeSummaryVersion});
4659
4660 // Write the index flags.
4661 uint64_t Flags = 0;
4662 // Bits 1-3 are set only in the combined index, skip them.
4663 if (Index->enableSplitLTOUnit())
4664 Flags |= 0x8;
4665 if (Index->hasUnifiedLTO())
4666 Flags |= 0x200;
4667
4668 Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Flags});
4669
4670 if (Index->begin() == Index->end()) {
4671 Stream.ExitBlock();
4672 return;
4673 }
4674
4675 auto Abbv = std::make_shared<BitCodeAbbrev>();
4676 Abbv->Add(BitCodeAbbrevOp(bitc::FS_VALUE_GUID));
4677 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4678 // GUIDS often use up most of 64-bits, so encode as two Fixed 32.
4679 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4680 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4681 unsigned ValueGuidAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4682
4683 for (const auto &GVI : valueIds()) {
4685 ArrayRef<uint32_t>{GVI.second,
4686 static_cast<uint32_t>(GVI.first >> 32),
4687 static_cast<uint32_t>(GVI.first)},
4688 ValueGuidAbbrev);
4689 }
4690
4691 if (!Index->stackIds().empty()) {
4692 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
4693 StackIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_STACK_IDS));
4694 // numids x stackid
4695 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4696 // The stack ids are hashes that are close to 64 bits in size, so emitting
4697 // as a pair of 32-bit fixed-width values is more efficient than a VBR.
4698 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4699 unsigned StackIdAbbvId = Stream.EmitAbbrev(std::move(StackIdAbbv));
4700 SmallVector<uint32_t> Vals;
4701 Vals.reserve(Index->stackIds().size() * 2);
4702 for (auto Id : Index->stackIds()) {
4703 Vals.push_back(static_cast<uint32_t>(Id >> 32));
4704 Vals.push_back(static_cast<uint32_t>(Id));
4705 }
4706 Stream.EmitRecord(bitc::FS_STACK_IDS, Vals, StackIdAbbvId);
4707 }
4708
4709 unsigned ContextIdAbbvId = 0;
4711 // n x context id
4712 auto ContextIdAbbv = std::make_shared<BitCodeAbbrev>();
4713 ContextIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_ALLOC_CONTEXT_IDS));
4714 ContextIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4715 // The context ids are hashes that are close to 64 bits in size, so emitting
4716 // as a pair of 32-bit fixed-width values is more efficient than a VBR if we
4717 // are emitting them for all MIBs. Otherwise we use VBR to better compress 0
4718 // values that are expected to more frequently occur in an alloc's memprof
4719 // summary.
4721 ContextIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4722 else
4723 ContextIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4724 ContextIdAbbvId = Stream.EmitAbbrev(std::move(ContextIdAbbv));
4725 }
4726
4727 // Abbrev for FS_PERMODULE_PROFILE.
4728 Abbv = std::make_shared<BitCodeAbbrev>();
4729 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));
4730 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4731 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // flags
4732 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
4733 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
4734 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4735 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
4736 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
4737 // numrefs x valueid, n x (valueid, hotness+tailcall flags)
4738 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4739 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4740 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4741
4742 // Abbrev for FS_PERMODULE_RELBF.
4743 Abbv = std::make_shared<BitCodeAbbrev>();
4744 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_RELBF));
4745 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4746 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4747 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
4748 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
4749 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4750 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
4751 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
4752 // numrefs x valueid, n x (valueid, rel_block_freq+tailcall])
4753 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4754 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4755 unsigned FSCallsRelBFAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4756
4757 // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
4758 Abbv = std::make_shared<BitCodeAbbrev>();
4759 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));
4760 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4761 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4762 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
4763 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4764 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4765
4766 // Abbrev for FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS.
4767 Abbv = std::make_shared<BitCodeAbbrev>();
4768 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS));
4769 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4770 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4771 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4772 // numrefs x valueid, n x (valueid , offset)
4773 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4774 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4775 unsigned FSModVTableRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4776
4777 // Abbrev for FS_ALIAS.
4778 Abbv = std::make_shared<BitCodeAbbrev>();
4779 Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
4780 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4781 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4782 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4783 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4784
4785 // Abbrev for FS_TYPE_ID_METADATA
4786 Abbv = std::make_shared<BitCodeAbbrev>();
4787 Abbv->Add(BitCodeAbbrevOp(bitc::FS_TYPE_ID_METADATA));
4788 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid strtab index
4789 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid length
4790 // n x (valueid , offset)
4791 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4792 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4793 unsigned TypeIdCompatibleVtableAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4794
4795 Abbv = std::make_shared<BitCodeAbbrev>();
4796 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_CALLSITE_INFO));
4797 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4798 // n x stackidindex
4799 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4800 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4801 unsigned CallsiteAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4802
4803 Abbv = std::make_shared<BitCodeAbbrev>();
4804 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_ALLOC_INFO));
4805 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // nummib
4806 // n x (alloc type, context radix tree index)
4807 // optional: nummib x (numcontext x total size)
4808 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4809 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4810 unsigned AllocAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4811
4812 Abbv = std::make_shared<BitCodeAbbrev>();
4813 Abbv->Add(BitCodeAbbrevOp(bitc::FS_CONTEXT_RADIX_TREE_ARRAY));
4814 // n x entry
4815 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4816 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4817 unsigned RadixAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4818
4819 // First walk through all the functions and collect the allocation contexts in
4820 // their associated summaries, for use in constructing a radix tree of
4821 // contexts. Note that we need to do this in the same order as the functions
4822 // are processed further below since the call stack positions in the resulting
4823 // radix tree array are identified based on this order.
4824 MapVector<CallStackId, llvm::SmallVector<LinearFrameId>> CallStacks;
4825 for (const Function &F : M) {
4826 // Summary emission does not support anonymous functions, they have to be
4827 // renamed using the anonymous function renaming pass.
4828 if (!F.hasName())
4829 report_fatal_error("Unexpected anonymous function when writing summary");
4830
4831 ValueInfo VI = Index->getValueInfo(F.getGUID());
4832 if (!VI || VI.getSummaryList().empty()) {
4833 // Only declarations should not have a summary (a declaration might
4834 // however have a summary if the def was in module level asm).
4835 assert(F.isDeclaration());
4836 continue;
4837 }
4838 auto *Summary = VI.getSummaryList()[0].get();
4839 FunctionSummary *FS = cast<FunctionSummary>(Summary);
4841 FS, /*GetStackIndex*/ [](unsigned I) { return I; }, CallStacks);
4842 }
4843 // Finalize the radix tree, write it out, and get the map of positions in the
4844 // linearized tree array.
4845 DenseMap<CallStackId, LinearCallStackId> CallStackPos;
4846 if (!CallStacks.empty()) {
4847 CallStackPos =
4848 writeMemoryProfileRadixTree(std::move(CallStacks), Stream, RadixAbbrev);
4849 }
4850
4851 // Keep track of the current index into the CallStackPos map.
4852 CallStackId CallStackCount = 0;
4853
4854 SmallVector<uint64_t, 64> NameVals;
4855 // Iterate over the list of functions instead of the Index to
4856 // ensure the ordering is stable.
4857 for (const Function &F : M) {
4858 // Summary emission does not support anonymous functions, they have to
4859 // renamed using the anonymous function renaming pass.
4860 if (!F.hasName())
4861 report_fatal_error("Unexpected anonymous function when writing summary");
4862
4863 ValueInfo VI = Index->getValueInfo(F.getGUID());
4864 if (!VI || VI.getSummaryList().empty()) {
4865 // Only declarations should not have a summary (a declaration might
4866 // however have a summary if the def was in module level asm).
4867 assert(F.isDeclaration());
4868 continue;
4869 }
4870 auto *Summary = VI.getSummaryList()[0].get();
4871 writePerModuleFunctionSummaryRecord(
4872 NameVals, Summary, VE.getValueID(&F), FSCallsRelBFAbbrev,
4873 FSCallsProfileAbbrev, CallsiteAbbrev, AllocAbbrev, ContextIdAbbvId, F,
4874 CallStackPos, CallStackCount);
4875 }
4876
4877 // Capture references from GlobalVariable initializers, which are outside
4878 // of a function scope.
4879 for (const GlobalVariable &G : M.globals())
4880 writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev,
4881 FSModVTableRefsAbbrev);
4882
4883 for (const GlobalAlias &A : M.aliases()) {
4884 auto *Aliasee = A.getAliaseeObject();
4885 // Skip ifunc and nameless functions which don't have an entry in the
4886 // summary.
4887 if (!Aliasee->hasName() || isa<GlobalIFunc>(Aliasee))
4888 continue;
4889 auto AliasId = VE.getValueID(&A);
4890 auto AliaseeId = VE.getValueID(Aliasee);
4891 NameVals.push_back(AliasId);
4892 auto *Summary = Index->getGlobalValueSummary(A);
4893 AliasSummary *AS = cast<AliasSummary>(Summary);
4894 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
4895 NameVals.push_back(AliaseeId);
4896 Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
4897 NameVals.clear();
4898 }
4899
4900 for (auto &S : Index->typeIdCompatibleVtableMap()) {
4901 writeTypeIdCompatibleVtableSummaryRecord(NameVals, StrtabBuilder, S.first,
4902 S.second, VE);
4903 Stream.EmitRecord(bitc::FS_TYPE_ID_METADATA, NameVals,
4904 TypeIdCompatibleVtableAbbrev);
4905 NameVals.clear();
4906 }
4907
4908 if (Index->getBlockCount())
4910 ArrayRef<uint64_t>{Index->getBlockCount()});
4911
4912 Stream.ExitBlock();
4913}
4914
4915/// Emit the combined summary section into the combined index file.
4916void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
4918 Stream.EmitRecord(
4920 ArrayRef<uint64_t>{ModuleSummaryIndex::BitcodeSummaryVersion});
4921
4922 // Write the index flags.
4923 Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Index.getFlags()});
4924
4925 auto Abbv = std::make_shared<BitCodeAbbrev>();
4926 Abbv->Add(BitCodeAbbrevOp(bitc::FS_VALUE_GUID));
4927 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4928 // GUIDS often use up most of 64-bits, so encode as two Fixed 32.
4929 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4930 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4931 unsigned ValueGuidAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4932
4933 for (const auto &GVI : valueIds()) {
4935 ArrayRef<uint32_t>{GVI.second,
4936 static_cast<uint32_t>(GVI.first >> 32),
4937 static_cast<uint32_t>(GVI.first)},
4938 ValueGuidAbbrev);
4939 }
4940
4941 // Write the stack ids used by this index, which will be a subset of those in
4942 // the full index in the case of distributed indexes.
4943 if (!StackIds.empty()) {
4944 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
4945 StackIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_STACK_IDS));
4946 // numids x stackid
4947 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4948 // The stack ids are hashes that are close to 64 bits in size, so emitting
4949 // as a pair of 32-bit fixed-width values is more efficient than a VBR.
4950 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4951 unsigned StackIdAbbvId = Stream.EmitAbbrev(std::move(StackIdAbbv));
4952 SmallVector<uint32_t> Vals;
4953 Vals.reserve(StackIds.size() * 2);
4954 for (auto Id : StackIds) {
4955 Vals.push_back(static_cast<uint32_t>(Id >> 32));
4956 Vals.push_back(static_cast<uint32_t>(Id));
4957 }
4958 Stream.EmitRecord(bitc::FS_STACK_IDS, Vals, StackIdAbbvId);
4959 }
4960
4961 // Abbrev for FS_COMBINED_PROFILE.
4962 Abbv = std::make_shared<BitCodeAbbrev>();
4963 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));
4964 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4965 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
4966 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4967 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
4968 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
4969 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // entrycount
4970 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4971 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
4972 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
4973 // numrefs x valueid, n x (valueid, hotness+tailcall flags)
4974 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4975 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4976 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4977
4978 // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
4979 Abbv = std::make_shared<BitCodeAbbrev>();
4980 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));
4981 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4982 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
4983 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4984 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
4985 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4986 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4987
4988 // Abbrev for FS_COMBINED_ALIAS.
4989 Abbv = std::make_shared<BitCodeAbbrev>();
4990 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS));
4991 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4992 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
4993 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4994 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4995 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4996
4997 Abbv = std::make_shared<BitCodeAbbrev>();
4998 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_CALLSITE_INFO));
4999 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
5000 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numstackindices
5001 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numver
5002 // numstackindices x stackidindex, numver x version
5003 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5004 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
5005 unsigned CallsiteAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5006
5007 Abbv = std::make_shared<BitCodeAbbrev>();
5008 Abbv->Add(BitCodeAbbrevOp(CombinedIndexMemProfContext
5011 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // nummib
5012 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numver
5013 // nummib x (alloc type, context radix tree index),
5014 // numver x version
5015 // optional: nummib x total size
5016 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5017 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
5018 unsigned AllocAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5019
5020 auto shouldImportValueAsDecl = [&](GlobalValueSummary *GVS) -> bool {
5021 if (DecSummaries == nullptr)
5022 return false;
5023 return DecSummaries->count(GVS);
5024 };
5025
5026 // The aliases are emitted as a post-pass, and will point to the value
5027 // id of the aliasee. Save them in a vector for post-processing.
5029
5030 // Save the value id for each summary for alias emission.
5031 DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
5032
5033 SmallVector<uint64_t, 64> NameVals;
5034
5035 // Set that will be populated during call to writeFunctionTypeMetadataRecords
5036 // with the type ids referenced by this index file.
5037 std::set<GlobalValue::GUID> ReferencedTypeIds;
5038
5039 // For local linkage, we also emit the original name separately
5040 // immediately after the record.
5041 auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
5042 // We don't need to emit the original name if we are writing the index for
5043 // distributed backends (in which case ModuleToSummariesForIndex is
5044 // non-null). The original name is only needed during the thin link, since
5045 // for SamplePGO the indirect call targets for local functions have
5046 // have the original name annotated in profile.
5047 // Continue to emit it when writing out the entire combined index, which is
5048 // used in testing the thin link via llvm-lto.
5049 if (ModuleToSummariesForIndex || !GlobalValue::isLocalLinkage(S.linkage()))
5050 return;
5051 NameVals.push_back(S.getOriginalName());
5053 NameVals.clear();
5054 };
5055
5056 DenseMap<CallStackId, LinearCallStackId> CallStackPos;
5058 Abbv = std::make_shared<BitCodeAbbrev>();
5059 Abbv->Add(BitCodeAbbrevOp(bitc::FS_CONTEXT_RADIX_TREE_ARRAY));
5060 // n x entry
5061 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5062 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
5063 unsigned RadixAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5064
5065 // First walk through all the functions and collect the allocation contexts
5066 // in their associated summaries, for use in constructing a radix tree of
5067 // contexts. Note that we need to do this in the same order as the functions
5068 // are processed further below since the call stack positions in the
5069 // resulting radix tree array are identified based on this order.
5070 MapVector<CallStackId, llvm::SmallVector<LinearFrameId>> CallStacks;
5071 forEachSummary([&](GVInfo I, bool IsAliasee) {
5072 // Don't collect this when invoked for an aliasee, as it is not needed for
5073 // the alias summary. If the aliasee is to be imported, we will invoke
5074 // this separately with IsAliasee=false.
5075 if (IsAliasee)
5076 return;
5077 GlobalValueSummary *S = I.second;
5078 assert(S);
5079 auto *FS = dyn_cast<FunctionSummary>(S);
5080 if (!FS)
5081 return;
5083 FS,
5084 /*GetStackIndex*/
5085 [&](unsigned I) {
5086 // Get the corresponding index into the list of StackIds actually
5087 // being written for this combined index (which may be a subset in
5088 // the case of distributed indexes).
5089 assert(StackIdIndicesToIndex.contains(I));
5090 return StackIdIndicesToIndex[I];
5091 },
5092 CallStacks);
5093 });
5094 // Finalize the radix tree, write it out, and get the map of positions in
5095 // the linearized tree array.
5096 if (!CallStacks.empty()) {
5097 CallStackPos = writeMemoryProfileRadixTree(std::move(CallStacks), Stream,
5098 RadixAbbrev);
5099 }
5100 }
5101
5102 // Keep track of the current index into the CallStackPos map. Not used if
5103 // CombinedIndexMemProfContext is false.
5104 CallStackId CallStackCount = 0;
5105
5106 DenseSet<GlobalValue::GUID> DefOrUseGUIDs;
5107 forEachSummary([&](GVInfo I, bool IsAliasee) {
5108 GlobalValueSummary *S = I.second;
5109 assert(S);
5110 DefOrUseGUIDs.insert(I.first);
5111 for (const ValueInfo &VI : S->refs())
5112 DefOrUseGUIDs.insert(VI.getGUID());
5113
5114 auto ValueId = getValueId(I.first);
5115 assert(ValueId);
5116 SummaryToValueIdMap[S] = *ValueId;
5117
5118 // If this is invoked for an aliasee, we want to record the above
5119 // mapping, but then not emit a summary entry (if the aliasee is
5120 // to be imported, we will invoke this separately with IsAliasee=false).
5121 if (IsAliasee)
5122 return;
5123
5124 if (auto *AS = dyn_cast<AliasSummary>(S)) {
5125 // Will process aliases as a post-pass because the reader wants all
5126 // global to be loaded first.
5127 Aliases.push_back(AS);
5128 return;
5129 }
5130
5131 if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
5132 NameVals.push_back(*ValueId);
5133 assert(ModuleIdMap.count(VS->modulePath()));
5134 NameVals.push_back(ModuleIdMap[VS->modulePath()]);
5135 NameVals.push_back(
5136 getEncodedGVSummaryFlags(VS->flags(), shouldImportValueAsDecl(VS)));
5137 NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
5138 for (auto &RI : VS->refs()) {
5139 auto RefValueId = getValueId(RI.getGUID());
5140 if (!RefValueId)
5141 continue;
5142 NameVals.push_back(*RefValueId);
5143 }
5144
5145 // Emit the finished record.
5147 FSModRefsAbbrev);
5148 NameVals.clear();
5149 MaybeEmitOriginalName(*S);
5150 return;
5151 }
5152
5153 auto GetValueId = [&](const ValueInfo &VI) -> std::optional<unsigned> {
5154 if (!VI)
5155 return std::nullopt;
5156 return getValueId(VI.getGUID());
5157 };
5158
5159 auto *FS = cast<FunctionSummary>(S);
5160 writeFunctionTypeMetadataRecords(Stream, FS, GetValueId);
5161 getReferencedTypeIds(FS, ReferencedTypeIds);
5162
5164 Stream, FS, CallsiteAbbrev, AllocAbbrev, /*ContextIdAbbvId*/ 0,
5165 /*PerModule*/ false,
5166 /*GetValueId*/
5167 [&](const ValueInfo &VI) -> unsigned {
5168 std::optional<unsigned> ValueID = GetValueId(VI);
5169 // This can happen in shared index files for distributed ThinLTO if
5170 // the callee function summary is not included. Record 0 which we
5171 // will have to deal with conservatively when doing any kind of
5172 // validation in the ThinLTO backends.
5173 if (!ValueID)
5174 return 0;
5175 return *ValueID;
5176 },
5177 /*GetStackIndex*/
5178 [&](unsigned I) {
5179 // Get the corresponding index into the list of StackIds actually
5180 // being written for this combined index (which may be a subset in
5181 // the case of distributed indexes).
5182 assert(StackIdIndicesToIndex.contains(I));
5183 return StackIdIndicesToIndex[I];
5184 },
5185 /*WriteContextSizeInfoIndex*/ false, CallStackPos, CallStackCount);
5186
5187 NameVals.push_back(*ValueId);
5188 assert(ModuleIdMap.count(FS->modulePath()));
5189 NameVals.push_back(ModuleIdMap[FS->modulePath()]);
5190 NameVals.push_back(
5191 getEncodedGVSummaryFlags(FS->flags(), shouldImportValueAsDecl(FS)));
5192 NameVals.push_back(FS->instCount());
5193 NameVals.push_back(getEncodedFFlags(FS->fflags()));
5194 // TODO: Stop writing entry count and bump bitcode version.
5195 NameVals.push_back(0 /* EntryCount */);
5196
5197 // Fill in below
5198 NameVals.push_back(0); // numrefs
5199 NameVals.push_back(0); // rorefcnt
5200 NameVals.push_back(0); // worefcnt
5201
5202 unsigned Count = 0, RORefCnt = 0, WORefCnt = 0;
5203 for (auto &RI : FS->refs()) {
5204 auto RefValueId = getValueId(RI.getGUID());
5205 if (!RefValueId)
5206 continue;
5207 NameVals.push_back(*RefValueId);
5208 if (RI.isReadOnly())
5209 RORefCnt++;
5210 else if (RI.isWriteOnly())
5211 WORefCnt++;
5212 Count++;
5213 }
5214 NameVals[6] = Count;
5215 NameVals[7] = RORefCnt;
5216 NameVals[8] = WORefCnt;
5217
5218 for (auto &EI : FS->calls()) {
5219 // If this GUID doesn't have a value id, it doesn't have a function
5220 // summary and we don't need to record any calls to it.
5221 std::optional<unsigned> CallValueId = GetValueId(EI.first);
5222 if (!CallValueId)
5223 continue;
5224 NameVals.push_back(*CallValueId);
5225 NameVals.push_back(getEncodedHotnessCallEdgeInfo(EI.second));
5226 }
5227
5228 // Emit the finished record.
5229 Stream.EmitRecord(bitc::FS_COMBINED_PROFILE, NameVals,
5230 FSCallsProfileAbbrev);
5231 NameVals.clear();
5232 MaybeEmitOriginalName(*S);
5233 });
5234
5235 for (auto *AS : Aliases) {
5236 auto AliasValueId = SummaryToValueIdMap[AS];
5237 assert(AliasValueId);
5238 NameVals.push_back(AliasValueId);
5239 assert(ModuleIdMap.count(AS->modulePath()));
5240 NameVals.push_back(ModuleIdMap[AS->modulePath()]);
5241 NameVals.push_back(
5242 getEncodedGVSummaryFlags(AS->flags(), shouldImportValueAsDecl(AS)));
5243 auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()];
5244 assert(AliaseeValueId);
5245 NameVals.push_back(AliaseeValueId);
5246
5247 // Emit the finished record.
5248 Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
5249 NameVals.clear();
5250 MaybeEmitOriginalName(*AS);
5251
5252 if (auto *FS = dyn_cast<FunctionSummary>(&AS->getAliasee()))
5253 getReferencedTypeIds(FS, ReferencedTypeIds);
5254 }
5255
5256 SmallVector<StringRef, 4> Functions;
5257 auto EmitCfiFunctions = [&](const CfiFunctionIndex &CfiIndex,
5259 if (CfiIndex.empty())
5260 return;
5261 for (GlobalValue::GUID GUID : DefOrUseGUIDs) {
5262 auto Defs = CfiIndex.forGuid(GUID);
5263 llvm::append_range(Functions, Defs);
5264 }
5265 if (Functions.empty())
5266 return;
5267 llvm::sort(Functions);
5268 for (const auto &S : Functions) {
5269 NameVals.push_back(StrtabBuilder.add(S));
5270 NameVals.push_back(S.size());
5271 }
5272 Stream.EmitRecord(Code, NameVals);
5273 NameVals.clear();
5274 Functions.clear();
5275 };
5276
5277 EmitCfiFunctions(Index.cfiFunctionDefs(), bitc::FS_CFI_FUNCTION_DEFS);
5278 EmitCfiFunctions(Index.cfiFunctionDecls(), bitc::FS_CFI_FUNCTION_DECLS);
5279
5280 // Walk the GUIDs that were referenced, and write the
5281 // corresponding type id records.
5282 for (auto &T : ReferencedTypeIds) {
5283 auto TidIter = Index.typeIds().equal_range(T);
5284 for (const auto &[GUID, TypeIdPair] : make_range(TidIter)) {
5285 writeTypeIdSummaryRecord(NameVals, StrtabBuilder, TypeIdPair.first,
5286 TypeIdPair.second);
5287 Stream.EmitRecord(bitc::FS_TYPE_ID, NameVals);
5288 NameVals.clear();
5289 }
5290 }
5291
5292 if (Index.getBlockCount())
5294 ArrayRef<uint64_t>{Index.getBlockCount()});
5295
5296 Stream.ExitBlock();
5297}
5298
5299/// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
5300/// current llvm version, and a record for the epoch number.
5303
5304 // Write the "user readable" string identifying the bitcode producer
5305 auto Abbv = std::make_shared<BitCodeAbbrev>();
5309 auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5311 "LLVM" LLVM_VERSION_STRING, StringAbbrev);
5312
5313 // Write the epoch version
5314 Abbv = std::make_shared<BitCodeAbbrev>();
5317 auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5318 constexpr std::array<unsigned, 1> Vals = {{bitc::BITCODE_CURRENT_EPOCH}};
5319 Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
5320 Stream.ExitBlock();
5321}
5322
5323void ModuleBitcodeWriter::writeModuleHash(StringRef View) {
5324 // Emit the module's hash.
5325 // MODULE_CODE_HASH: [5*i32]
5326 if (GenerateHash) {
5327 uint32_t Vals[5];
5328 Hasher.update(ArrayRef<uint8_t>(
5329 reinterpret_cast<const uint8_t *>(View.data()), View.size()));
5330 std::array<uint8_t, 20> Hash = Hasher.result();
5331 for (int Pos = 0; Pos < 20; Pos += 4) {
5332 Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);
5333 }
5334
5335 // Emit the finished record.
5336 Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
5337
5338 if (ModHash)
5339 // Save the written hash value.
5340 llvm::copy(Vals, std::begin(*ModHash));
5341 }
5342}
5343
5344void ModuleBitcodeWriter::write() {
5346
5348 // We will want to write the module hash at this point. Block any flushing so
5349 // we can have access to the whole underlying data later.
5350 Stream.markAndBlockFlushing();
5351
5352 writeModuleVersion();
5353
5354 // Emit blockinfo, which defines the standard abbreviations etc.
5355 writeBlockInfo();
5356
5357 // Emit information describing all of the types in the module.
5358 writeTypeTable();
5359
5360 // Emit information about attribute groups.
5361 writeAttributeGroupTable();
5362
5363 // Emit information about parameter attributes.
5364 writeAttributeTable();
5365
5366 writeComdats();
5367
5368 // Emit top-level description of module, including target triple, inline asm,
5369 // descriptors for global variables, and function prototype info.
5370 writeModuleInfo();
5371
5372 // Emit constants.
5373 writeModuleConstants();
5374
5375 // Emit metadata kind names.
5376 writeModuleMetadataKinds();
5377
5378 // Emit metadata.
5379 writeModuleMetadata();
5380
5381 // Emit module-level use-lists.
5383 writeUseListBlock(nullptr);
5384
5385 writeOperandBundleTags();
5386 writeSyncScopeNames();
5387
5388 // Emit function bodies.
5389 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
5390 for (const Function &F : M)
5391 if (!F.isDeclaration())
5392 writeFunction(F, FunctionToBitcodeIndex);
5393
5394 // Need to write after the above call to WriteFunction which populates
5395 // the summary information in the index.
5396 if (Index)
5397 writePerModuleGlobalValueSummary();
5398
5399 writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
5400
5401 writeModuleHash(Stream.getMarkedBufferAndResumeFlushing());
5402
5403 Stream.ExitBlock();
5404}
5405
5407 uint32_t &Position) {
5408 support::endian::write32le(&Buffer[Position], Value);
5409 Position += 4;
5410}
5411
5412/// If generating a bc file on darwin, we have to emit a
5413/// header and trailer to make it compatible with the system archiver. To do
5414/// this we emit the following header, and then emit a trailer that pads the
5415/// file out to be a multiple of 16 bytes.
5416///
5417/// struct bc_header {
5418/// uint32_t Magic; // 0x0B17C0DE
5419/// uint32_t Version; // Version, currently always 0.
5420/// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
5421/// uint32_t BitcodeSize; // Size of traditional bitcode file.
5422/// uint32_t CPUType; // CPU specifier.
5423/// ... potentially more later ...
5424/// };
5426 const Triple &TT) {
5427 unsigned CPUType = ~0U;
5428
5429 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
5430 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
5431 // number from /usr/include/mach/machine.h. It is ok to reproduce the
5432 // specific constants here because they are implicitly part of the Darwin ABI.
5433 enum {
5434 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
5435 DARWIN_CPU_TYPE_X86 = 7,
5436 DARWIN_CPU_TYPE_ARM = 12,
5437 DARWIN_CPU_TYPE_POWERPC = 18
5438 };
5439
5440 Triple::ArchType Arch = TT.getArch();
5441 if (Arch == Triple::x86_64)
5442 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
5443 else if (Arch == Triple::x86)
5444 CPUType = DARWIN_CPU_TYPE_X86;
5445 else if (Arch == Triple::ppc)
5446 CPUType = DARWIN_CPU_TYPE_POWERPC;
5447 else if (Arch == Triple::ppc64)
5448 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
5449 else if (Arch == Triple::arm || Arch == Triple::thumb)
5450 CPUType = DARWIN_CPU_TYPE_ARM;
5451
5452 // Traditional Bitcode starts after header.
5453 assert(Buffer.size() >= BWH_HeaderSize &&
5454 "Expected header size to be reserved");
5455 unsigned BCOffset = BWH_HeaderSize;
5456 unsigned BCSize = Buffer.size() - BWH_HeaderSize;
5457
5458 // Write the magic and version.
5459 unsigned Position = 0;
5460 writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
5461 writeInt32ToBuffer(0, Buffer, Position); // Version.
5462 writeInt32ToBuffer(BCOffset, Buffer, Position);
5463 writeInt32ToBuffer(BCSize, Buffer, Position);
5464 writeInt32ToBuffer(CPUType, Buffer, Position);
5465
5466 // If the file is not a multiple of 16 bytes, insert dummy padding.
5467 while (Buffer.size() & 15)
5468 Buffer.push_back(0);
5469}
5470
5471/// Helper to write the header common to all bitcode files.
5473 // Emit the file header.
5474 Stream.Emit((unsigned)'B', 8);
5475 Stream.Emit((unsigned)'C', 8);
5476 Stream.Emit(0x0, 4);
5477 Stream.Emit(0xC, 4);
5478 Stream.Emit(0xE, 4);
5479 Stream.Emit(0xD, 4);
5480}
5481
5483 : Stream(new BitstreamWriter(Buffer)) {
5484 writeBitcodeHeader(*Stream);
5485}
5486
5491
5493
5494void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) {
5495 Stream->EnterSubblock(Block, 3);
5496
5497 auto Abbv = std::make_shared<BitCodeAbbrev>();
5498 Abbv->Add(BitCodeAbbrevOp(Record));
5500 auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv));
5501
5502 Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob);
5503
5504 Stream->ExitBlock();
5505}
5506
5508 assert(!WroteStrtab && !WroteSymtab);
5509
5510 // If any module has module-level inline asm, we will require a registered asm
5511 // parser for the target so that we can create an accurate symbol table for
5512 // the module.
5513 for (Module *M : Mods) {
5514 if (M->getModuleInlineAsm().empty())
5515 continue;
5516
5517 std::string Err;
5518 const Triple TT(M->getTargetTriple());
5519 const Target *T = TargetRegistry::lookupTarget(TT, Err);
5520 if (!T || !T->hasMCAsmParser())
5521 return;
5522 }
5523
5524 WroteSymtab = true;
5525 SmallVector<char, 0> Symtab;
5526 // The irsymtab::build function may be unable to create a symbol table if the
5527 // module is malformed (e.g. it contains an invalid alias). Writing a symbol
5528 // table is not required for correctness, but we still want to be able to
5529 // write malformed modules to bitcode files, so swallow the error.
5530 if (Error E = irsymtab::build(Mods, Symtab, StrtabBuilder, Alloc)) {
5531 consumeError(std::move(E));
5532 return;
5533 }
5534
5536 {Symtab.data(), Symtab.size()});
5537}
5538
5540 assert(!WroteStrtab);
5541
5542 std::vector<char> Strtab;
5543 StrtabBuilder.finalizeInOrder();
5544 Strtab.resize(StrtabBuilder.getSize());
5545 StrtabBuilder.write((uint8_t *)Strtab.data());
5546
5548 {Strtab.data(), Strtab.size()});
5549
5550 WroteStrtab = true;
5551}
5552
5554 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab);
5555 WroteStrtab = true;
5556}
5557
5559 bool ShouldPreserveUseListOrder,
5560 const ModuleSummaryIndex *Index,
5561 bool GenerateHash, ModuleHash *ModHash) {
5562 assert(!WroteStrtab);
5563
5564 // The Mods vector is used by irsymtab::build, which requires non-const
5565 // Modules in case it needs to materialize metadata. But the bitcode writer
5566 // requires that the module is materialized, so we can cast to non-const here,
5567 // after checking that it is in fact materialized.
5568 assert(M.isMaterialized());
5569 Mods.push_back(const_cast<Module *>(&M));
5570
5571 ModuleBitcodeWriter ModuleWriter(M, StrtabBuilder, *Stream,
5572 ShouldPreserveUseListOrder, Index,
5573 GenerateHash, ModHash);
5574 ModuleWriter.write();
5575}
5576
5578 const ModuleSummaryIndex *Index,
5579 const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex,
5580 const GVSummaryPtrSet *DecSummaries) {
5581 IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index, DecSummaries,
5582 ModuleToSummariesForIndex);
5583 IndexWriter.write();
5584}
5585
5586/// Write the specified module to the specified output stream.
5588 bool ShouldPreserveUseListOrder,
5589 const ModuleSummaryIndex *Index,
5590 bool GenerateHash, ModuleHash *ModHash) {
5591 auto Write = [&](BitcodeWriter &Writer) {
5592 Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
5593 ModHash);
5594 Writer.writeSymtab();
5595 Writer.writeStrtab();
5596 };
5597 Triple TT(M.getTargetTriple());
5598 if (TT.isOSDarwin() || TT.isOSBinFormatMachO()) {
5599 // If this is darwin or another generic macho target, reserve space for the
5600 // header. Note that the header is computed *after* the output is known, so
5601 // we currently explicitly use a buffer, write to it, and then subsequently
5602 // flush to Out.
5603 SmallVector<char, 0> Buffer;
5604 Buffer.reserve(256 * 1024);
5605 Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
5606 BitcodeWriter Writer(Buffer);
5607 Write(Writer);
5608 emitDarwinBCHeaderAndTrailer(Buffer, TT);
5609 Out.write(Buffer.data(), Buffer.size());
5610 } else {
5611 BitcodeWriter Writer(Out);
5612 Write(Writer);
5613 }
5614}
5615
5616void IndexBitcodeWriter::write() {
5618
5619 writeModuleVersion();
5620
5621 // Write the module paths in the combined index.
5622 writeModStrings();
5623
5624 // Write the summary combined index records.
5625 writeCombinedGlobalValueSummary();
5626
5627 Stream.ExitBlock();
5628}
5629
5630// Write the specified module summary index to the given raw output stream,
5631// where it will be written in a new bitcode block. This is used when
5632// writing the combined index file for ThinLTO. When writing a subset of the
5633// index for a distributed backend, provide a \p ModuleToSummariesForIndex map.
5635 const ModuleSummaryIndex &Index, raw_ostream &Out,
5636 const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex,
5637 const GVSummaryPtrSet *DecSummaries) {
5638 SmallVector<char, 0> Buffer;
5639 Buffer.reserve(256 * 1024);
5640
5641 BitcodeWriter Writer(Buffer);
5642 Writer.writeIndex(&Index, ModuleToSummariesForIndex, DecSummaries);
5643 Writer.writeStrtab();
5644
5645 Out.write((char *)&Buffer.front(), Buffer.size());
5646}
5647
5648namespace {
5649
5650/// Class to manage the bitcode writing for a thin link bitcode file.
5651class ThinLinkBitcodeWriter : public ModuleBitcodeWriterBase {
5652 /// ModHash is for use in ThinLTO incremental build, generated while writing
5653 /// the module bitcode file.
5654 const ModuleHash *ModHash;
5655
5656public:
5657 ThinLinkBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder,
5658 BitstreamWriter &Stream,
5659 const ModuleSummaryIndex &Index,
5660 const ModuleHash &ModHash)
5661 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
5662 /*ShouldPreserveUseListOrder=*/false, &Index),
5663 ModHash(&ModHash) {}
5664
5665 void write();
5666
5667private:
5668 void writeSimplifiedModuleInfo();
5669};
5670
5671} // end anonymous namespace
5672
5673// This function writes a simpilified module info for thin link bitcode file.
5674// It only contains the source file name along with the name(the offset and
5675// size in strtab) and linkage for global values. For the global value info
5676// entry, in order to keep linkage at offset 5, there are three zeros used
5677// as padding.
5678void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {
5680 // Emit the module's source file name.
5681 {
5682 StringEncoding Bits = getStringEncoding(M.getSourceFileName());
5684 if (Bits == SE_Char6)
5685 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
5686 else if (Bits == SE_Fixed7)
5687 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
5688
5689 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
5690 auto Abbv = std::make_shared<BitCodeAbbrev>();
5693 Abbv->Add(AbbrevOpToUse);
5694 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5695
5696 for (const auto P : M.getSourceFileName())
5697 Vals.push_back((unsigned char)P);
5698
5699 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
5700 Vals.clear();
5701 }
5702
5703 // Emit the global variable information.
5704 for (const GlobalVariable &GV : M.globals()) {
5705 // GLOBALVAR: [strtab offset, strtab size, 0, 0, 0, linkage]
5706 Vals.push_back(StrtabBuilder.add(GV.getName()));
5707 Vals.push_back(GV.getName().size());
5708 Vals.push_back(0);
5709 Vals.push_back(0);
5710 Vals.push_back(0);
5711 Vals.push_back(getEncodedLinkage(GV));
5712
5714 Vals.clear();
5715 }
5716
5717 // Emit the function proto information.
5718 for (const Function &F : M) {
5719 // FUNCTION: [strtab offset, strtab size, 0, 0, 0, linkage]
5720 Vals.push_back(StrtabBuilder.add(F.getName()));
5721 Vals.push_back(F.getName().size());
5722 Vals.push_back(0);
5723 Vals.push_back(0);
5724 Vals.push_back(0);
5726
5728 Vals.clear();
5729 }
5730
5731 // Emit the alias information.
5732 for (const GlobalAlias &A : M.aliases()) {
5733 // ALIAS: [strtab offset, strtab size, 0, 0, 0, linkage]
5734 Vals.push_back(StrtabBuilder.add(A.getName()));
5735 Vals.push_back(A.getName().size());
5736 Vals.push_back(0);
5737 Vals.push_back(0);
5738 Vals.push_back(0);
5740
5741 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals);
5742 Vals.clear();
5743 }
5744
5745 // Emit the ifunc information.
5746 for (const GlobalIFunc &I : M.ifuncs()) {
5747 // IFUNC: [strtab offset, strtab size, 0, 0, 0, linkage]
5748 Vals.push_back(StrtabBuilder.add(I.getName()));
5749 Vals.push_back(I.getName().size());
5750 Vals.push_back(0);
5751 Vals.push_back(0);
5752 Vals.push_back(0);
5754
5755 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
5756 Vals.clear();
5757 }
5758}
5759
5760void ThinLinkBitcodeWriter::write() {
5762
5763 writeModuleVersion();
5764
5765 writeSimplifiedModuleInfo();
5766
5767 writePerModuleGlobalValueSummary();
5768
5769 // Write module hash.
5771
5772 Stream.ExitBlock();
5773}
5774
5776 const ModuleSummaryIndex &Index,
5777 const ModuleHash &ModHash) {
5778 assert(!WroteStrtab);
5779
5780 // The Mods vector is used by irsymtab::build, which requires non-const
5781 // Modules in case it needs to materialize metadata. But the bitcode writer
5782 // requires that the module is materialized, so we can cast to non-const here,
5783 // after checking that it is in fact materialized.
5784 assert(M.isMaterialized());
5785 Mods.push_back(const_cast<Module *>(&M));
5786
5787 ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index,
5788 ModHash);
5789 ThinLinkWriter.write();
5790}
5791
5792// Write the specified thin link bitcode file to the given raw output stream,
5793// where it will be written in a new bitcode block. This is used when
5794// writing the per-module index file for ThinLTO.
5796 const ModuleSummaryIndex &Index,
5797 const ModuleHash &ModHash) {
5798 SmallVector<char, 0> Buffer;
5799 Buffer.reserve(256 * 1024);
5800
5801 BitcodeWriter Writer(Buffer);
5802 Writer.writeThinLinkBitcode(M, Index, ModHash);
5803 Writer.writeSymtab();
5804 Writer.writeStrtab();
5805
5806 Out.write((char *)&Buffer.front(), Buffer.size());
5807}
5808
5809static const char *getSectionNameForBitcode(const Triple &T) {
5810 switch (T.getObjectFormat()) {
5811 case Triple::MachO:
5812 return "__LLVM,__bitcode";
5813 case Triple::COFF:
5814 case Triple::ELF:
5815 case Triple::Wasm:
5817 return ".llvmbc";
5818 case Triple::GOFF:
5819 llvm_unreachable("GOFF is not yet implemented");
5820 break;
5821 case Triple::SPIRV:
5822 if (T.getVendor() == Triple::AMD)
5823 return ".llvmbc";
5824 llvm_unreachable("SPIRV is not yet implemented");
5825 break;
5826 case Triple::XCOFF:
5827 llvm_unreachable("XCOFF is not yet implemented");
5828 break;
5830 llvm_unreachable("DXContainer is not yet implemented");
5831 break;
5832 }
5833 llvm_unreachable("Unimplemented ObjectFormatType");
5834}
5835
5836static const char *getSectionNameForCommandline(const Triple &T) {
5837 switch (T.getObjectFormat()) {
5838 case Triple::MachO:
5839 return "__LLVM,__cmdline";
5840 case Triple::COFF:
5841 case Triple::ELF:
5842 case Triple::Wasm:
5844 return ".llvmcmd";
5845 case Triple::GOFF:
5846 llvm_unreachable("GOFF is not yet implemented");
5847 break;
5848 case Triple::SPIRV:
5849 if (T.getVendor() == Triple::AMD)
5850 return ".llvmcmd";
5851 llvm_unreachable("SPIRV is not yet implemented");
5852 break;
5853 case Triple::XCOFF:
5854 llvm_unreachable("XCOFF is not yet implemented");
5855 break;
5857 llvm_unreachable("DXC is not yet implemented");
5858 break;
5859 }
5860 llvm_unreachable("Unimplemented ObjectFormatType");
5861}
5862
5864 bool EmbedBitcode, bool EmbedCmdline,
5865 const std::vector<uint8_t> &CmdArgs) {
5866 // Save llvm.compiler.used and remove it.
5869 GlobalVariable *Used = collectUsedGlobalVariables(M, UsedGlobals, true);
5870 Type *UsedElementType = Used ? Used->getValueType()->getArrayElementType()
5871 : PointerType::getUnqual(M.getContext());
5872 for (auto *GV : UsedGlobals) {
5873 if (GV->getName() != "llvm.embedded.module" &&
5874 GV->getName() != "llvm.cmdline")
5875 UsedArray.push_back(
5877 }
5878 if (Used)
5879 Used->eraseFromParent();
5880
5881 // Embed the bitcode for the llvm module.
5882 std::string Data;
5883 ArrayRef<uint8_t> ModuleData;
5884 Triple T(M.getTargetTriple());
5885
5886 if (EmbedBitcode) {
5887 if (Buf.getBufferSize() == 0 ||
5888 !isBitcode((const unsigned char *)Buf.getBufferStart(),
5889 (const unsigned char *)Buf.getBufferEnd())) {
5890 // If the input is LLVM Assembly, bitcode is produced by serializing
5891 // the module. Use-lists order need to be preserved in this case.
5893 llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true);
5894 ModuleData =
5895 ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
5896 } else
5897 // If the input is LLVM bitcode, write the input byte stream directly.
5898 ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
5899 Buf.getBufferSize());
5900 }
5901 llvm::Constant *ModuleConstant =
5902 llvm::ConstantDataArray::get(M.getContext(), ModuleData);
5904 M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
5905 ModuleConstant);
5907 // Set alignment to 1 to prevent padding between two contributions from input
5908 // sections after linking.
5909 GV->setAlignment(Align(1));
5910 UsedArray.push_back(
5912 if (llvm::GlobalVariable *Old =
5913 M.getGlobalVariable("llvm.embedded.module", true)) {
5914 assert(Old->hasZeroLiveUses() &&
5915 "llvm.embedded.module can only be used once in llvm.compiler.used");
5916 GV->takeName(Old);
5917 Old->eraseFromParent();
5918 } else {
5919 GV->setName("llvm.embedded.module");
5920 }
5921
5922 // Skip if only bitcode needs to be embedded.
5923 if (EmbedCmdline) {
5924 // Embed command-line options.
5925 ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CmdArgs.data()),
5926 CmdArgs.size());
5927 llvm::Constant *CmdConstant =
5928 llvm::ConstantDataArray::get(M.getContext(), CmdData);
5929 GV = new llvm::GlobalVariable(M, CmdConstant->getType(), true,
5931 CmdConstant);
5933 GV->setAlignment(Align(1));
5934 UsedArray.push_back(
5936 if (llvm::GlobalVariable *Old = M.getGlobalVariable("llvm.cmdline", true)) {
5937 assert(Old->hasZeroLiveUses() &&
5938 "llvm.cmdline can only be used once in llvm.compiler.used");
5939 GV->takeName(Old);
5940 Old->eraseFromParent();
5941 } else {
5942 GV->setName("llvm.cmdline");
5943 }
5944 }
5945
5946 if (UsedArray.empty())
5947 return;
5948
5949 // Recreate llvm.compiler.used.
5950 ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
5951 auto *NewUsed = new GlobalVariable(
5953 llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
5954 NewUsed->setSection("llvm.metadata");
5955}
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:147
bool empty() const
empty - Check if the array is empty.
Definition ArrayRef.h:142
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:163
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:158
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:222
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:319
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:355
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:644
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:548
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:560
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:865
#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:270
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,...