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