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