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.
196
197 /// Optional per-module index to write for ThinLTO.
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(
257 unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
258 unsigned CallsiteAbbrev, unsigned AllocAbbrev, unsigned ContextIdAbbvId,
260 CallStackId &CallStackCount);
261 void writeModuleLevelReferences(const GlobalVariable &V,
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,
332 unsigned Abbrev);
333 unsigned createDILocationAbbrev();
335 unsigned &Abbrev);
336 unsigned createGenericDINodeAbbrev();
338 SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev);
340 unsigned Abbrev);
343 unsigned Abbrev);
344 void writeDIEnumerator(const DIEnumerator *N,
345 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
347 unsigned Abbrev);
350 unsigned Abbrev);
351 void writeDIStringType(const DIStringType *N,
352 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
354 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
356 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
358 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
361 unsigned Abbrev);
363 unsigned Abbrev);
365 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
366 void writeDISubprogram(const DISubprogram *N,
367 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
369 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
372 unsigned Abbrev);
374 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
376 unsigned Abbrev);
378 unsigned Abbrev);
380 unsigned Abbrev);
383 unsigned Abbrev);
385 unsigned Abbrev);
388 unsigned Abbrev);
391 unsigned Abbrev);
394 unsigned Abbrev);
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);
403 unsigned Abbrev);
405 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
408 unsigned Abbrev);
409 unsigned createNamedMetadataAbbrev();
410 void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
411 unsigned createMetadataStringsAbbrev();
412 void writeMetadataStrings(ArrayRef<const Metadata *> Strings,
414 void writeMetadataRecords(ArrayRef<const Metadata *> MDs,
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,
430 bool pushValueOrMetadata(const Value *V, unsigned InstID,
432 void writeOperandBundles(const CallBase &CB, unsigned InstID);
433 void pushValue(const Value *V, unsigned InstID,
435 void pushValueSigned(const Value *V, unsigned InstID,
437 void writeInstruction(const Instruction &I, unsigned InstID,
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.
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.
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
722static unsigned getEncodedOrdering(AtomicOrdering Ordering) {
723 switch (Ordering) {
724 case AtomicOrdering::NotAtomic: return bitc::ORDERING_NOTATOMIC;
725 case AtomicOrdering::Unordered: return bitc::ORDERING_UNORDERED;
726 case AtomicOrdering::Monotonic: return bitc::ORDERING_MONOTONIC;
727 case AtomicOrdering::Acquire: return bitc::ORDERING_ACQUIRE;
728 case AtomicOrdering::Release: return bitc::ORDERING_RELEASE;
729 case AtomicOrdering::AcquireRelease: return bitc::ORDERING_ACQREL;
730 case AtomicOrdering::SequentiallyConsistent: return bitc::ORDERING_SEQCST;
731 }
732 llvm_unreachable("Invalid ordering");
733}
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::SanitizeHWAddress:
888 case Attribute::SanitizeThread:
890 case Attribute::SanitizeType:
892 case Attribute::SanitizeMemory:
894 case Attribute::SanitizeNumericalStability:
896 case Attribute::SanitizeRealtime:
898 case Attribute::SanitizeRealtimeBlocking:
900 case Attribute::SpeculativeLoadHardening:
902 case Attribute::SwiftError:
904 case Attribute::SwiftSelf:
906 case Attribute::SwiftAsync:
908 case Attribute::UWTable:
910 case Attribute::VScaleRange:
912 case Attribute::WillReturn:
914 case Attribute::WriteOnly:
916 case Attribute::ZExt:
918 case Attribute::ImmArg:
920 case Attribute::SanitizeMemTag:
922 case Attribute::Preallocated:
924 case Attribute::NoUndef:
926 case Attribute::ByRef:
928 case Attribute::MustProgress:
930 case Attribute::PresplitCoroutine:
932 case Attribute::Writable:
934 case Attribute::CoroDestroyOnlyWhenComplete:
936 case Attribute::CoroElideSafe:
938 case Attribute::DeadOnUnwind:
940 case Attribute::Range:
942 case Attribute::Initializes:
944 case Attribute::NoExt:
946 case Attribute::Captures:
948 case Attribute::DeadOnReturn:
951 llvm_unreachable("Can not encode end-attribute kinds marker.");
952 case Attribute::None:
953 llvm_unreachable("Can not encode none-attribute.");
956 llvm_unreachable("Trying to encode EmptyKey/TombstoneKey");
957 }
958
959 llvm_unreachable("Trying to encode unknown attribute");
960}
961
963 if ((int64_t)V >= 0)
964 Vals.push_back(V << 1);
965 else
966 Vals.push_back((-V << 1) | 1);
967}
968
969static void emitWideAPInt(SmallVectorImpl<uint64_t> &Vals, const APInt &A) {
970 // We have an arbitrary precision integer value to write whose
971 // bit width is > 64. However, in canonical unsigned integer
972 // format it is likely that the high bits are going to be zero.
973 // So, we only write the number of active words.
974 unsigned NumWords = A.getActiveWords();
975 const uint64_t *RawData = A.getRawData();
976 for (unsigned i = 0; i < NumWords; i++)
977 emitSignedInt64(Vals, RawData[i]);
978}
979
981 const ConstantRange &CR, bool EmitBitWidth) {
982 unsigned BitWidth = CR.getBitWidth();
983 if (EmitBitWidth)
984 Record.push_back(BitWidth);
985 if (BitWidth > 64) {
986 Record.push_back(CR.getLower().getActiveWords() |
987 (uint64_t(CR.getUpper().getActiveWords()) << 32));
990 } else {
993 }
994}
995
996void ModuleBitcodeWriter::writeAttributeGroupTable() {
997 const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
999 if (AttrGrps.empty()) return;
1000
1002
1004 for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) {
1005 unsigned AttrListIndex = Pair.first;
1006 AttributeSet AS = Pair.second;
1007 Record.push_back(VE.getAttributeGroupID(Pair));
1008 Record.push_back(AttrListIndex);
1009
1010 for (Attribute Attr : AS) {
1011 if (Attr.isEnumAttribute()) {
1012 Record.push_back(0);
1013 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
1014 } else if (Attr.isIntAttribute()) {
1015 Record.push_back(1);
1016 Attribute::AttrKind Kind = Attr.getKindAsEnum();
1017 Record.push_back(getAttrKindEncoding(Kind));
1018 if (Kind == Attribute::Memory) {
1019 // Version field for upgrading old memory effects.
1020 const uint64_t Version = 1;
1021 Record.push_back((Version << 56) | Attr.getValueAsInt());
1022 } else {
1023 Record.push_back(Attr.getValueAsInt());
1024 }
1025 } else if (Attr.isStringAttribute()) {
1026 StringRef Kind = Attr.getKindAsString();
1027 StringRef Val = Attr.getValueAsString();
1028
1029 Record.push_back(Val.empty() ? 3 : 4);
1030 Record.append(Kind.begin(), Kind.end());
1031 Record.push_back(0);
1032 if (!Val.empty()) {
1033 Record.append(Val.begin(), Val.end());
1034 Record.push_back(0);
1035 }
1036 } else if (Attr.isTypeAttribute()) {
1037 Type *Ty = Attr.getValueAsType();
1038 Record.push_back(Ty ? 6 : 5);
1039 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
1040 if (Ty)
1041 Record.push_back(VE.getTypeID(Attr.getValueAsType()));
1042 } else if (Attr.isConstantRangeAttribute()) {
1043 Record.push_back(7);
1044 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
1045 emitConstantRange(Record, Attr.getValueAsConstantRange(),
1046 /*EmitBitWidth=*/true);
1047 } else {
1048 assert(Attr.isConstantRangeListAttribute());
1049 Record.push_back(8);
1050 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
1051 ArrayRef<ConstantRange> Val = Attr.getValueAsConstantRangeList();
1052 Record.push_back(Val.size());
1053 Record.push_back(Val[0].getBitWidth());
1054 for (auto &CR : Val)
1055 emitConstantRange(Record, CR, /*EmitBitWidth=*/false);
1056 }
1057 }
1058
1060 Record.clear();
1061 }
1062
1063 Stream.ExitBlock();
1064}
1065
1066void ModuleBitcodeWriter::writeAttributeTable() {
1067 const std::vector<AttributeList> &Attrs = VE.getAttributeLists();
1068 if (Attrs.empty()) return;
1069
1071
1073 for (const AttributeList &AL : Attrs) {
1074 for (unsigned i : AL.indexes()) {
1075 AttributeSet AS = AL.getAttributes(i);
1076 if (AS.hasAttributes())
1077 Record.push_back(VE.getAttributeGroupID({i, AS}));
1078 }
1079
1081 Record.clear();
1082 }
1083
1084 Stream.ExitBlock();
1085}
1086
1087/// WriteTypeTable - Write out the type table for a module.
1088void ModuleBitcodeWriter::writeTypeTable() {
1089 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
1090
1091 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
1093
1095
1096 // Abbrev for TYPE_CODE_OPAQUE_POINTER.
1097 auto Abbv = std::make_shared<BitCodeAbbrev>();
1099 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
1100 unsigned OpaquePtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1101
1102 // Abbrev for TYPE_CODE_FUNCTION.
1103 Abbv = std::make_shared<BitCodeAbbrev>();
1105 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
1107 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
1108 unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1109
1110 // Abbrev for TYPE_CODE_STRUCT_ANON.
1111 Abbv = std::make_shared<BitCodeAbbrev>();
1113 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
1115 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
1116 unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1117
1118 // Abbrev for TYPE_CODE_STRUCT_NAME.
1119 Abbv = std::make_shared<BitCodeAbbrev>();
1123 unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1124
1125 // Abbrev for TYPE_CODE_STRUCT_NAMED.
1126 Abbv = std::make_shared<BitCodeAbbrev>();
1128 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
1130 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
1131 unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1132
1133 // Abbrev for TYPE_CODE_ARRAY.
1134 Abbv = std::make_shared<BitCodeAbbrev>();
1136 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
1137 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
1138 unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1139
1140 // Emit an entry count so the reader can reserve space.
1141 TypeVals.push_back(TypeList.size());
1142 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
1143 TypeVals.clear();
1144
1145 // Loop over all of the types, emitting each in turn.
1146 for (Type *T : TypeList) {
1147 int AbbrevToUse = 0;
1148 unsigned Code = 0;
1149
1150 switch (T->getTypeID()) {
1160 case Type::MetadataTyID:
1162 break;
1165 case Type::IntegerTyID:
1166 // INTEGER: [width]
1168 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
1169 break;
1170 case Type::PointerTyID: {
1171 PointerType *PTy = cast<PointerType>(T);
1172 unsigned AddressSpace = PTy->getAddressSpace();
1173 // OPAQUE_POINTER: [address space]
1175 TypeVals.push_back(AddressSpace);
1176 if (AddressSpace == 0)
1177 AbbrevToUse = OpaquePtrAbbrev;
1178 break;
1179 }
1180 case Type::FunctionTyID: {
1181 FunctionType *FT = cast<FunctionType>(T);
1182 // FUNCTION: [isvararg, retty, paramty x N]
1184 TypeVals.push_back(FT->isVarArg());
1185 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
1186 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
1187 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
1188 AbbrevToUse = FunctionAbbrev;
1189 break;
1190 }
1191 case Type::StructTyID: {
1192 StructType *ST = cast<StructType>(T);
1193 // STRUCT: [ispacked, eltty x N]
1194 TypeVals.push_back(ST->isPacked());
1195 // Output all of the element types.
1196 for (Type *ET : ST->elements())
1197 TypeVals.push_back(VE.getTypeID(ET));
1198
1199 if (ST->isLiteral()) {
1201 AbbrevToUse = StructAnonAbbrev;
1202 } else {
1203 if (ST->isOpaque()) {
1205 } else {
1207 AbbrevToUse = StructNamedAbbrev;
1208 }
1209
1210 // Emit the name if it is present.
1211 if (!ST->getName().empty())
1213 StructNameAbbrev);
1214 }
1215 break;
1216 }
1217 case Type::ArrayTyID: {
1218 ArrayType *AT = cast<ArrayType>(T);
1219 // ARRAY: [numelts, eltty]
1221 TypeVals.push_back(AT->getNumElements());
1222 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
1223 AbbrevToUse = ArrayAbbrev;
1224 break;
1225 }
1228 VectorType *VT = cast<VectorType>(T);
1229 // VECTOR [numelts, eltty] or
1230 // [numelts, eltty, scalable]
1232 TypeVals.push_back(VT->getElementCount().getKnownMinValue());
1233 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
1234 if (isa<ScalableVectorType>(VT))
1235 TypeVals.push_back(true);
1236 break;
1237 }
1238 case Type::TargetExtTyID: {
1239 TargetExtType *TET = cast<TargetExtType>(T);
1242 StructNameAbbrev);
1243 TypeVals.push_back(TET->getNumTypeParameters());
1244 for (Type *InnerTy : TET->type_params())
1245 TypeVals.push_back(VE.getTypeID(InnerTy));
1246 llvm::append_range(TypeVals, TET->int_params());
1247 break;
1248 }
1250 llvm_unreachable("Typed pointers cannot be added to IR modules");
1251 }
1252
1253 // Emit the finished record.
1254 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
1255 TypeVals.clear();
1256 }
1257
1258 Stream.ExitBlock();
1259}
1260
1261static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {
1262 switch (Linkage) {
1264 return 0;
1266 return 16;
1268 return 2;
1270 return 3;
1272 return 18;
1274 return 7;
1276 return 8;
1278 return 9;
1280 return 17;
1282 return 19;
1284 return 12;
1285 }
1286 llvm_unreachable("Invalid linkage");
1287}
1288
1289static unsigned getEncodedLinkage(const GlobalValue &GV) {
1290 return getEncodedLinkage(GV.getLinkage());
1291}
1292
1294 uint64_t RawFlags = 0;
1295 RawFlags |= Flags.ReadNone;
1296 RawFlags |= (Flags.ReadOnly << 1);
1297 RawFlags |= (Flags.NoRecurse << 2);
1298 RawFlags |= (Flags.ReturnDoesNotAlias << 3);
1299 RawFlags |= (Flags.NoInline << 4);
1300 RawFlags |= (Flags.AlwaysInline << 5);
1301 RawFlags |= (Flags.NoUnwind << 6);
1302 RawFlags |= (Flags.MayThrow << 7);
1303 RawFlags |= (Flags.HasUnknownCall << 8);
1304 RawFlags |= (Flags.MustBeUnreachable << 9);
1305 return RawFlags;
1306}
1307
1308// Decode the flags for GlobalValue in the summary. See getDecodedGVSummaryFlags
1309// in BitcodeReader.cpp.
1311 bool ImportAsDecl = false) {
1312 uint64_t RawFlags = 0;
1313
1314 RawFlags |= Flags.NotEligibleToImport; // bool
1315 RawFlags |= (Flags.Live << 1);
1316 RawFlags |= (Flags.DSOLocal << 2);
1317 RawFlags |= (Flags.CanAutoHide << 3);
1318
1319 // Linkage don't need to be remapped at that time for the summary. Any future
1320 // change to the getEncodedLinkage() function will need to be taken into
1321 // account here as well.
1322 RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits
1323
1324 RawFlags |= (Flags.Visibility << 8); // 2 bits
1325
1326 unsigned ImportType = Flags.ImportType | ImportAsDecl;
1327 RawFlags |= (ImportType << 10); // 1 bit
1328
1329 return RawFlags;
1330}
1331
1333 uint64_t RawFlags = Flags.MaybeReadOnly | (Flags.MaybeWriteOnly << 1) |
1334 (Flags.Constant << 2) | Flags.VCallVisibility << 3;
1335 return RawFlags;
1336}
1337
1339 uint64_t RawFlags = 0;
1340
1341 RawFlags |= CI.Hotness; // 3 bits
1342 RawFlags |= (CI.HasTailCall << 3); // 1 bit
1343
1344 return RawFlags;
1345}
1346
1348 uint64_t RawFlags = 0;
1349
1350 RawFlags |= CI.RelBlockFreq; // CalleeInfo::RelBlockFreqBits bits
1351 RawFlags |= (CI.HasTailCall << CalleeInfo::RelBlockFreqBits); // 1 bit
1352
1353 return RawFlags;
1354}
1355
1356static unsigned getEncodedVisibility(const GlobalValue &GV) {
1357 switch (GV.getVisibility()) {
1358 case GlobalValue::DefaultVisibility: return 0;
1359 case GlobalValue::HiddenVisibility: return 1;
1360 case GlobalValue::ProtectedVisibility: return 2;
1361 }
1362 llvm_unreachable("Invalid visibility");
1363}
1364
1365static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
1366 switch (GV.getDLLStorageClass()) {
1367 case GlobalValue::DefaultStorageClass: return 0;
1370 }
1371 llvm_unreachable("Invalid DLL storage class");
1372}
1373
1374static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
1375 switch (GV.getThreadLocalMode()) {
1376 case GlobalVariable::NotThreadLocal: return 0;
1377 case GlobalVariable::GeneralDynamicTLSModel: return 1;
1378 case GlobalVariable::LocalDynamicTLSModel: return 2;
1379 case GlobalVariable::InitialExecTLSModel: return 3;
1380 case GlobalVariable::LocalExecTLSModel: return 4;
1381 }
1382 llvm_unreachable("Invalid TLS model");
1383}
1384
1385static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
1386 switch (C.getSelectionKind()) {
1387 case Comdat::Any:
1389 case Comdat::ExactMatch:
1391 case Comdat::Largest:
1395 case Comdat::SameSize:
1397 }
1398 llvm_unreachable("Invalid selection kind");
1399}
1400
1401static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) {
1402 switch (GV.getUnnamedAddr()) {
1403 case GlobalValue::UnnamedAddr::None: return 0;
1404 case GlobalValue::UnnamedAddr::Local: return 2;
1405 case GlobalValue::UnnamedAddr::Global: return 1;
1406 }
1407 llvm_unreachable("Invalid unnamed_addr");
1408}
1409
1410size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) {
1411 if (GenerateHash)
1412 Hasher.update(Str);
1413 return StrtabBuilder.add(Str);
1414}
1415
1416void ModuleBitcodeWriter::writeComdats() {
1418 for (const Comdat *C : VE.getComdats()) {
1419 // COMDAT: [strtab offset, strtab size, selection_kind]
1420 Vals.push_back(addToStrtab(C->getName()));
1421 Vals.push_back(C->getName().size());
1423 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
1424 Vals.clear();
1425 }
1426}
1427
1428/// Write a record that will eventually hold the word offset of the
1429/// module-level VST. For now the offset is 0, which will be backpatched
1430/// after the real VST is written. Saves the bit offset to backpatch.
1431void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
1432 // Write a placeholder value in for the offset of the real VST,
1433 // which is written after the function blocks so that it can include
1434 // the offset of each function. The placeholder offset will be
1435 // updated when the real VST is written.
1436 auto Abbv = std::make_shared<BitCodeAbbrev>();
1438 // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
1439 // hold the real VST offset. Must use fixed instead of VBR as we don't
1440 // know how many VBR chunks to reserve ahead of time.
1442 unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1443
1444 // Emit the placeholder
1446 Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
1447
1448 // Compute and save the bit offset to the placeholder, which will be
1449 // patched when the real VST is written. We can simply subtract the 32-bit
1450 // fixed size from the current bit number to get the location to backpatch.
1451 VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32;
1452}
1453
1455
1456/// Determine the encoding to use for the given string name and length.
1458 bool isChar6 = true;
1459 for (char C : Str) {
1460 if (isChar6)
1461 isChar6 = BitCodeAbbrevOp::isChar6(C);
1462 if ((unsigned char)C & 128)
1463 // don't bother scanning the rest.
1464 return SE_Fixed8;
1465 }
1466 if (isChar6)
1467 return SE_Char6;
1468 return SE_Fixed7;
1469}
1470
1471static_assert(sizeof(GlobalValue::SanitizerMetadata) <= sizeof(unsigned),
1472 "Sanitizer Metadata is too large for naive serialization.");
1473static unsigned
1475 return Meta.NoAddress | (Meta.NoHWAddress << 1) |
1476 (Meta.Memtag << 2) | (Meta.IsDynInit << 3);
1477}
1478
1479/// Emit top-level description of module, including target triple, inline asm,
1480/// descriptors for global variables, and function prototype info.
1481/// Returns the bit offset to backpatch with the location of the real VST.
1482void ModuleBitcodeWriter::writeModuleInfo() {
1483 // Emit various pieces of data attached to a module.
1484 if (!M.getTargetTriple().empty())
1486 M.getTargetTriple().str(), 0 /*TODO*/);
1487 const std::string &DL = M.getDataLayoutStr();
1488 if (!DL.empty())
1490 if (!M.getModuleInlineAsm().empty())
1491 writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(),
1492 0 /*TODO*/);
1493
1494 // Emit information about sections and GC, computing how many there are. Also
1495 // compute the maximum alignment value.
1496 std::map<std::string, unsigned> SectionMap;
1497 std::map<std::string, unsigned> GCMap;
1498 MaybeAlign MaxGVarAlignment;
1499 unsigned MaxGlobalType = 0;
1500 for (const GlobalVariable &GV : M.globals()) {
1501 if (MaybeAlign A = GV.getAlign())
1502 MaxGVarAlignment = !MaxGVarAlignment ? *A : std::max(*MaxGVarAlignment, *A);
1503 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
1504 if (GV.hasSection()) {
1505 // Give section names unique ID's.
1506 unsigned &Entry = SectionMap[std::string(GV.getSection())];
1507 if (!Entry) {
1508 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
1509 0 /*TODO*/);
1510 Entry = SectionMap.size();
1511 }
1512 }
1513 }
1514 for (const Function &F : M) {
1515 if (F.hasSection()) {
1516 // Give section names unique ID's.
1517 unsigned &Entry = SectionMap[std::string(F.getSection())];
1518 if (!Entry) {
1520 0 /*TODO*/);
1521 Entry = SectionMap.size();
1522 }
1523 }
1524 if (F.hasGC()) {
1525 // Same for GC names.
1526 unsigned &Entry = GCMap[F.getGC()];
1527 if (!Entry) {
1529 0 /*TODO*/);
1530 Entry = GCMap.size();
1531 }
1532 }
1533 }
1534
1535 // Emit abbrev for globals, now that we know # sections and max alignment.
1536 unsigned SimpleGVarAbbrev = 0;
1537 if (!M.global_empty()) {
1538 // Add an abbrev for common globals with no visibility or thread localness.
1539 auto Abbv = std::make_shared<BitCodeAbbrev>();
1544 Log2_32_Ceil(MaxGlobalType+1)));
1545 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2
1546 //| explicitType << 1
1547 //| constant
1548 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
1549 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
1550 if (!MaxGVarAlignment) // Alignment.
1551 Abbv->Add(BitCodeAbbrevOp(0));
1552 else {
1553 unsigned MaxEncAlignment = getEncodedAlign(MaxGVarAlignment);
1555 Log2_32_Ceil(MaxEncAlignment+1)));
1556 }
1557 if (SectionMap.empty()) // Section.
1558 Abbv->Add(BitCodeAbbrevOp(0));
1559 else
1561 Log2_32_Ceil(SectionMap.size()+1)));
1562 // Don't bother emitting vis + thread local.
1563 SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1564 }
1565
1567 // Emit the module's source file name.
1568 {
1569 StringEncoding Bits = getStringEncoding(M.getSourceFileName());
1571 if (Bits == SE_Char6)
1572 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
1573 else if (Bits == SE_Fixed7)
1574 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
1575
1576 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
1577 auto Abbv = std::make_shared<BitCodeAbbrev>();
1580 Abbv->Add(AbbrevOpToUse);
1581 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1582
1583 for (const auto P : M.getSourceFileName())
1584 Vals.push_back((unsigned char)P);
1585
1586 // Emit the finished record.
1587 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
1588 Vals.clear();
1589 }
1590
1591 // Emit the global variable information.
1592 for (const GlobalVariable &GV : M.globals()) {
1593 unsigned AbbrevToUse = 0;
1594
1595 // GLOBALVAR: [strtab offset, strtab size, type, isconst, initid,
1596 // linkage, alignment, section, visibility, threadlocal,
1597 // unnamed_addr, externally_initialized, dllstorageclass,
1598 // comdat, attributes, DSO_Local, GlobalSanitizer, code_model]
1599 Vals.push_back(addToStrtab(GV.getName()));
1600 Vals.push_back(GV.getName().size());
1601 Vals.push_back(VE.getTypeID(GV.getValueType()));
1602 Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
1603 Vals.push_back(GV.isDeclaration() ? 0 :
1604 (VE.getValueID(GV.getInitializer()) + 1));
1605 Vals.push_back(getEncodedLinkage(GV));
1606 Vals.push_back(getEncodedAlign(GV.getAlign()));
1607 Vals.push_back(GV.hasSection() ? SectionMap[std::string(GV.getSection())]
1608 : 0);
1609 if (GV.isThreadLocal() ||
1610 GV.getVisibility() != GlobalValue::DefaultVisibility ||
1611 GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1612 GV.isExternallyInitialized() ||
1613 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
1614 GV.hasComdat() || GV.hasAttributes() || GV.isDSOLocal() ||
1615 GV.hasPartition() || GV.hasSanitizerMetadata() || GV.getCodeModel()) {
1619 Vals.push_back(GV.isExternallyInitialized());
1621 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
1622
1623 auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
1624 Vals.push_back(VE.getAttributeListID(AL));
1625
1626 Vals.push_back(GV.isDSOLocal());
1627 Vals.push_back(addToStrtab(GV.getPartition()));
1628 Vals.push_back(GV.getPartition().size());
1629
1630 Vals.push_back((GV.hasSanitizerMetadata() ? serializeSanitizerMetadata(
1631 GV.getSanitizerMetadata())
1632 : 0));
1633 Vals.push_back(GV.getCodeModelRaw());
1634 } else {
1635 AbbrevToUse = SimpleGVarAbbrev;
1636 }
1637
1638 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
1639 Vals.clear();
1640 }
1641
1642 // Emit the function proto information.
1643 for (const Function &F : M) {
1644 // FUNCTION: [strtab offset, strtab size, type, callingconv, isproto,
1645 // linkage, paramattrs, alignment, section, visibility, gc,
1646 // unnamed_addr, prologuedata, dllstorageclass, comdat,
1647 // prefixdata, personalityfn, DSO_Local, addrspace]
1648 Vals.push_back(addToStrtab(F.getName()));
1649 Vals.push_back(F.getName().size());
1650 Vals.push_back(VE.getTypeID(F.getFunctionType()));
1651 Vals.push_back(F.getCallingConv());
1652 Vals.push_back(F.isDeclaration());
1654 Vals.push_back(VE.getAttributeListID(F.getAttributes()));
1655 Vals.push_back(getEncodedAlign(F.getAlign()));
1656 Vals.push_back(F.hasSection() ? SectionMap[std::string(F.getSection())]
1657 : 0);
1659 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
1661 Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
1662 : 0);
1664 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
1665 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
1666 : 0);
1667 Vals.push_back(
1668 F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
1669
1670 Vals.push_back(F.isDSOLocal());
1671 Vals.push_back(F.getAddressSpace());
1672 Vals.push_back(addToStrtab(F.getPartition()));
1673 Vals.push_back(F.getPartition().size());
1674
1675 unsigned AbbrevToUse = 0;
1676 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
1677 Vals.clear();
1678 }
1679
1680 // Emit the alias information.
1681 for (const GlobalAlias &A : M.aliases()) {
1682 // ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage,
1683 // visibility, dllstorageclass, threadlocal, unnamed_addr,
1684 // DSO_Local]
1685 Vals.push_back(addToStrtab(A.getName()));
1686 Vals.push_back(A.getName().size());
1687 Vals.push_back(VE.getTypeID(A.getValueType()));
1688 Vals.push_back(A.getType()->getAddressSpace());
1689 Vals.push_back(VE.getValueID(A.getAliasee()));
1695 Vals.push_back(A.isDSOLocal());
1696 Vals.push_back(addToStrtab(A.getPartition()));
1697 Vals.push_back(A.getPartition().size());
1698
1699 unsigned AbbrevToUse = 0;
1700 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
1701 Vals.clear();
1702 }
1703
1704 // Emit the ifunc information.
1705 for (const GlobalIFunc &I : M.ifuncs()) {
1706 // IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver
1707 // val#, linkage, visibility, DSO_Local]
1708 Vals.push_back(addToStrtab(I.getName()));
1709 Vals.push_back(I.getName().size());
1710 Vals.push_back(VE.getTypeID(I.getValueType()));
1711 Vals.push_back(I.getType()->getAddressSpace());
1712 Vals.push_back(VE.getValueID(I.getResolver()));
1715 Vals.push_back(I.isDSOLocal());
1716 Vals.push_back(addToStrtab(I.getPartition()));
1717 Vals.push_back(I.getPartition().size());
1718 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
1719 Vals.clear();
1720 }
1721
1722 writeValueSymbolTableForwardDecl();
1723}
1724
1726 uint64_t Flags = 0;
1727
1728 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
1729 if (OBO->hasNoSignedWrap())
1730 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
1731 if (OBO->hasNoUnsignedWrap())
1732 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
1733 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
1734 if (PEO->isExact())
1735 Flags |= 1 << bitc::PEO_EXACT;
1736 } else if (const auto *PDI = dyn_cast<PossiblyDisjointInst>(V)) {
1737 if (PDI->isDisjoint())
1738 Flags |= 1 << bitc::PDI_DISJOINT;
1739 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
1740 if (FPMO->hasAllowReassoc())
1741 Flags |= bitc::AllowReassoc;
1742 if (FPMO->hasNoNaNs())
1743 Flags |= bitc::NoNaNs;
1744 if (FPMO->hasNoInfs())
1745 Flags |= bitc::NoInfs;
1746 if (FPMO->hasNoSignedZeros())
1747 Flags |= bitc::NoSignedZeros;
1748 if (FPMO->hasAllowReciprocal())
1749 Flags |= bitc::AllowReciprocal;
1750 if (FPMO->hasAllowContract())
1751 Flags |= bitc::AllowContract;
1752 if (FPMO->hasApproxFunc())
1753 Flags |= bitc::ApproxFunc;
1754 } else if (const auto *NNI = dyn_cast<PossiblyNonNegInst>(V)) {
1755 if (NNI->hasNonNeg())
1756 Flags |= 1 << bitc::PNNI_NON_NEG;
1757 } else if (const auto *TI = dyn_cast<TruncInst>(V)) {
1758 if (TI->hasNoSignedWrap())
1759 Flags |= 1 << bitc::TIO_NO_SIGNED_WRAP;
1760 if (TI->hasNoUnsignedWrap())
1761 Flags |= 1 << bitc::TIO_NO_UNSIGNED_WRAP;
1762 } else if (const auto *GEP = dyn_cast<GEPOperator>(V)) {
1763 if (GEP->isInBounds())
1764 Flags |= 1 << bitc::GEP_INBOUNDS;
1765 if (GEP->hasNoUnsignedSignedWrap())
1766 Flags |= 1 << bitc::GEP_NUSW;
1767 if (GEP->hasNoUnsignedWrap())
1768 Flags |= 1 << bitc::GEP_NUW;
1769 } else if (const auto *ICmp = dyn_cast<ICmpInst>(V)) {
1770 if (ICmp->hasSameSign())
1771 Flags |= 1 << bitc::ICMP_SAME_SIGN;
1772 }
1773
1774 return Flags;
1775}
1776
1777void ModuleBitcodeWriter::writeValueAsMetadata(
1779 // Mimic an MDNode with a value as one operand.
1780 Value *V = MD->getValue();
1781 Record.push_back(VE.getTypeID(V->getType()));
1782 Record.push_back(VE.getValueID(V));
1784 Record.clear();
1785}
1786
1787void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N,
1789 unsigned Abbrev) {
1790 for (const MDOperand &MDO : N->operands()) {
1791 Metadata *MD = MDO;
1792 assert(!(MD && isa<LocalAsMetadata>(MD)) &&
1793 "Unexpected function-local metadata");
1794 Record.push_back(VE.getMetadataOrNullID(MD));
1795 }
1796 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
1798 Record, Abbrev);
1799 Record.clear();
1800}
1801
1802unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
1803 // Assume the column is usually under 128, and always output the inlined-at
1804 // location (it's never more expensive than building an array size 1).
1805 auto Abbv = std::make_shared<BitCodeAbbrev>();
1807 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isDistinct
1808 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // line
1809 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // column
1810 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // scope
1811 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // inlinedAt
1812 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isImplicitCode
1813 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // atomGroup
1814 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // atomRank
1815 return Stream.EmitAbbrev(std::move(Abbv));
1816}
1817
1818void ModuleBitcodeWriter::writeDILocation(const DILocation *N,
1820 unsigned &Abbrev) {
1821 if (!Abbrev)
1822 Abbrev = createDILocationAbbrev();
1823
1824 Record.push_back(N->isDistinct());
1825 Record.push_back(N->getLine());
1826 Record.push_back(N->getColumn());
1827 Record.push_back(VE.getMetadataID(N->getScope()));
1828 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
1829 Record.push_back(N->isImplicitCode());
1830 Record.push_back(N->getAtomGroup());
1831 Record.push_back(N->getAtomRank());
1832 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
1833 Record.clear();
1834}
1835
1836unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
1837 // Assume the column is usually under 128, and always output the inlined-at
1838 // location (it's never more expensive than building an array size 1).
1839 auto Abbv = std::make_shared<BitCodeAbbrev>();
1847 return Stream.EmitAbbrev(std::move(Abbv));
1848}
1849
1850void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N,
1852 unsigned &Abbrev) {
1853 if (!Abbrev)
1854 Abbrev = createGenericDINodeAbbrev();
1855
1856 Record.push_back(N->isDistinct());
1857 Record.push_back(N->getTag());
1858 Record.push_back(0); // Per-tag version field; unused for now.
1859
1860 for (auto &I : N->operands())
1861 Record.push_back(VE.getMetadataOrNullID(I));
1862
1864 Record.clear();
1865}
1866
1867void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N,
1869 unsigned Abbrev) {
1870 const uint64_t Version = 2 << 1;
1871 Record.push_back((uint64_t)N->isDistinct() | Version);
1872 Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
1873 Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
1874 Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
1875 Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
1876
1877 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
1878 Record.clear();
1879}
1880
1881void ModuleBitcodeWriter::writeDIGenericSubrange(
1883 unsigned Abbrev) {
1884 Record.push_back((uint64_t)N->isDistinct());
1885 Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
1886 Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
1887 Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
1888 Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
1889
1891 Record.clear();
1892}
1893
1894void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,
1896 unsigned Abbrev) {
1897 const uint64_t IsBigInt = 1 << 2;
1898 Record.push_back(IsBigInt | (N->isUnsigned() << 1) | N->isDistinct());
1899 Record.push_back(N->getValue().getBitWidth());
1900 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1901 emitWideAPInt(Record, N->getValue());
1902
1904 Record.clear();
1905}
1906
1907void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N,
1909 unsigned Abbrev) {
1910 const unsigned SizeIsMetadata = 0x2;
1911 Record.push_back(SizeIsMetadata | (unsigned)N->isDistinct());
1912 Record.push_back(N->getTag());
1913 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1914 Record.push_back(VE.getMetadataOrNullID(N->getRawSizeInBits()));
1915 Record.push_back(N->getAlignInBits());
1916 Record.push_back(N->getEncoding());
1917 Record.push_back(N->getFlags());
1918 Record.push_back(N->getNumExtraInhabitants());
1919
1921 Record.clear();
1922}
1923
1924void ModuleBitcodeWriter::writeDIFixedPointType(
1926 unsigned Abbrev) {
1927 const unsigned SizeIsMetadata = 0x2;
1928 Record.push_back(SizeIsMetadata | (unsigned)N->isDistinct());
1929 Record.push_back(N->getTag());
1930 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1931 Record.push_back(VE.getMetadataOrNullID(N->getRawSizeInBits()));
1932 Record.push_back(N->getAlignInBits());
1933 Record.push_back(N->getEncoding());
1934 Record.push_back(N->getFlags());
1935 Record.push_back(N->getKind());
1936 Record.push_back(N->getFactorRaw());
1937
1938 auto WriteWideInt = [&](const APInt &Value) {
1939 // Write an encoded word that holds the number of active words and
1940 // the number of bits.
1941 uint64_t NumWords = Value.getActiveWords();
1942 uint64_t Encoded = (NumWords << 32) | Value.getBitWidth();
1943 Record.push_back(Encoded);
1945 };
1946
1947 WriteWideInt(N->getNumeratorRaw());
1948 WriteWideInt(N->getDenominatorRaw());
1949
1951 Record.clear();
1952}
1953
1954void ModuleBitcodeWriter::writeDIStringType(const DIStringType *N,
1956 unsigned Abbrev) {
1957 const unsigned SizeIsMetadata = 0x2;
1958 Record.push_back(SizeIsMetadata | (unsigned)N->isDistinct());
1959 Record.push_back(N->getTag());
1960 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1961 Record.push_back(VE.getMetadataOrNullID(N->getStringLength()));
1962 Record.push_back(VE.getMetadataOrNullID(N->getStringLengthExp()));
1963 Record.push_back(VE.getMetadataOrNullID(N->getStringLocationExp()));
1964 Record.push_back(VE.getMetadataOrNullID(N->getRawSizeInBits()));
1965 Record.push_back(N->getAlignInBits());
1966 Record.push_back(N->getEncoding());
1967
1969 Record.clear();
1970}
1971
1972void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,
1974 unsigned Abbrev) {
1975 const unsigned SizeIsMetadata = 0x2;
1976 Record.push_back(SizeIsMetadata | (unsigned)N->isDistinct());
1977 Record.push_back(N->getTag());
1978 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1979 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1980 Record.push_back(N->getLine());
1981 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1982 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1983 Record.push_back(VE.getMetadataOrNullID(N->getRawSizeInBits()));
1984 Record.push_back(N->getAlignInBits());
1985 Record.push_back(VE.getMetadataOrNullID(N->getRawOffsetInBits()));
1986 Record.push_back(N->getFlags());
1987 Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
1988
1989 // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
1990 // that there is no DWARF address space associated with DIDerivedType.
1991 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
1992 Record.push_back(*DWARFAddressSpace + 1);
1993 else
1994 Record.push_back(0);
1995
1996 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
1997
1998 if (auto PtrAuthData = N->getPtrAuthData())
1999 Record.push_back(PtrAuthData->RawData);
2000 else
2001 Record.push_back(0);
2002
2004 Record.clear();
2005}
2006
2007void ModuleBitcodeWriter::writeDISubrangeType(const DISubrangeType *N,
2009 unsigned Abbrev) {
2010 const unsigned SizeIsMetadata = 0x2;
2011 Record.push_back(SizeIsMetadata | (unsigned)N->isDistinct());
2012 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2013 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2014 Record.push_back(N->getLine());
2015 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2016 Record.push_back(VE.getMetadataOrNullID(N->getRawSizeInBits()));
2017 Record.push_back(N->getAlignInBits());
2018 Record.push_back(N->getFlags());
2019 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
2020 Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
2021 Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
2022 Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
2023 Record.push_back(VE.getMetadataOrNullID(N->getRawBias()));
2024
2026 Record.clear();
2027}
2028
2029void ModuleBitcodeWriter::writeDICompositeType(
2031 unsigned Abbrev) {
2032 const unsigned IsNotUsedInOldTypeRef = 0x2;
2033 const unsigned SizeIsMetadata = 0x4;
2034 Record.push_back(SizeIsMetadata | IsNotUsedInOldTypeRef |
2035 (unsigned)N->isDistinct());
2036 Record.push_back(N->getTag());
2037 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2038 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2039 Record.push_back(N->getLine());
2040 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2041 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
2042 Record.push_back(VE.getMetadataOrNullID(N->getRawSizeInBits()));
2043 Record.push_back(N->getAlignInBits());
2044 Record.push_back(VE.getMetadataOrNullID(N->getRawOffsetInBits()));
2045 Record.push_back(N->getFlags());
2046 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
2047 Record.push_back(N->getRuntimeLang());
2048 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
2049 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
2050 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
2051 Record.push_back(VE.getMetadataOrNullID(N->getDiscriminator()));
2052 Record.push_back(VE.getMetadataOrNullID(N->getRawDataLocation()));
2053 Record.push_back(VE.getMetadataOrNullID(N->getRawAssociated()));
2054 Record.push_back(VE.getMetadataOrNullID(N->getRawAllocated()));
2055 Record.push_back(VE.getMetadataOrNullID(N->getRawRank()));
2056 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2057 Record.push_back(N->getNumExtraInhabitants());
2058 Record.push_back(VE.getMetadataOrNullID(N->getRawSpecification()));
2059 Record.push_back(
2060 N->getEnumKind().value_or(dwarf::DW_APPLE_ENUM_KIND_invalid));
2061 Record.push_back(VE.getMetadataOrNullID(N->getRawBitStride()));
2062
2064 Record.clear();
2065}
2066
2067void ModuleBitcodeWriter::writeDISubroutineType(
2069 unsigned Abbrev) {
2070 const unsigned HasNoOldTypeRefs = 0x2;
2071 Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
2072 Record.push_back(N->getFlags());
2073 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
2074 Record.push_back(N->getCC());
2075
2077 Record.clear();
2078}
2079
2080void ModuleBitcodeWriter::writeDIFile(const DIFile *N,
2082 unsigned Abbrev) {
2083 Record.push_back(N->isDistinct());
2084 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
2085 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
2086 if (N->getRawChecksum()) {
2087 Record.push_back(N->getRawChecksum()->Kind);
2088 Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()->Value));
2089 } else {
2090 // Maintain backwards compatibility with the old internal representation of
2091 // CSK_None in ChecksumKind by writing nulls here when Checksum is None.
2092 Record.push_back(0);
2093 Record.push_back(VE.getMetadataOrNullID(nullptr));
2094 }
2095 auto Source = N->getRawSource();
2096 if (Source)
2097 Record.push_back(VE.getMetadataOrNullID(Source));
2098
2099 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
2100 Record.clear();
2101}
2102
2103void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
2105 unsigned Abbrev) {
2106 assert(N->isDistinct() && "Expected distinct compile units");
2107 Record.push_back(/* IsDistinct */ true);
2108 Record.push_back(N->getSourceLanguage());
2109 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2110 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
2111 Record.push_back(N->isOptimized());
2112 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
2113 Record.push_back(N->getRuntimeVersion());
2114 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
2115 Record.push_back(N->getEmissionKind());
2116 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
2117 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
2118 Record.push_back(/* subprograms */ 0);
2119 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
2120 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
2121 Record.push_back(N->getDWOId());
2122 Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
2123 Record.push_back(N->getSplitDebugInlining());
2124 Record.push_back(N->getDebugInfoForProfiling());
2125 Record.push_back((unsigned)N->getNameTableKind());
2126 Record.push_back(N->getRangesBaseAddress());
2127 Record.push_back(VE.getMetadataOrNullID(N->getRawSysRoot()));
2128 Record.push_back(VE.getMetadataOrNullID(N->getRawSDK()));
2129
2131 Record.clear();
2132}
2133
2134void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,
2136 unsigned Abbrev) {
2137 const uint64_t HasUnitFlag = 1 << 1;
2138 const uint64_t HasSPFlagsFlag = 1 << 2;
2139 Record.push_back(uint64_t(N->isDistinct()) | HasUnitFlag | HasSPFlagsFlag);
2140 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2141 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2142 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
2143 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2144 Record.push_back(N->getLine());
2145 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2146 Record.push_back(N->getScopeLine());
2147 Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
2148 Record.push_back(N->getSPFlags());
2149 Record.push_back(N->getVirtualIndex());
2150 Record.push_back(N->getFlags());
2151 Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
2152 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
2153 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
2154 Record.push_back(VE.getMetadataOrNullID(N->getRetainedNodes().get()));
2155 Record.push_back(N->getThisAdjustment());
2156 Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get()));
2157 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2158 Record.push_back(VE.getMetadataOrNullID(N->getRawTargetFuncName()));
2159 Record.push_back(N->getKeyInstructionsEnabled());
2160
2162 Record.clear();
2163}
2164
2165void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
2167 unsigned Abbrev) {
2168 Record.push_back(N->isDistinct());
2169 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2170 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2171 Record.push_back(N->getLine());
2172 Record.push_back(N->getColumn());
2173
2175 Record.clear();
2176}
2177
2178void ModuleBitcodeWriter::writeDILexicalBlockFile(
2180 unsigned Abbrev) {
2181 Record.push_back(N->isDistinct());
2182 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2183 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2184 Record.push_back(N->getDiscriminator());
2185
2187 Record.clear();
2188}
2189
2190void ModuleBitcodeWriter::writeDICommonBlock(const DICommonBlock *N,
2192 unsigned Abbrev) {
2193 Record.push_back(N->isDistinct());
2194 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2195 Record.push_back(VE.getMetadataOrNullID(N->getDecl()));
2196 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2197 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2198 Record.push_back(N->getLineNo());
2199
2201 Record.clear();
2202}
2203
2204void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,
2206 unsigned Abbrev) {
2207 Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
2208 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2209 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2210
2212 Record.clear();
2213}
2214
2215void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,
2217 unsigned Abbrev) {
2218 Record.push_back(N->isDistinct());
2219 Record.push_back(N->getMacinfoType());
2220 Record.push_back(N->getLine());
2221 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2222 Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
2223
2224 Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
2225 Record.clear();
2226}
2227
2228void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,
2230 unsigned Abbrev) {
2231 Record.push_back(N->isDistinct());
2232 Record.push_back(N->getMacinfoType());
2233 Record.push_back(N->getLine());
2234 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2235 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
2236
2238 Record.clear();
2239}
2240
2241void ModuleBitcodeWriter::writeDIArgList(const DIArgList *N,
2243 Record.reserve(N->getArgs().size());
2244 for (ValueAsMetadata *MD : N->getArgs())
2245 Record.push_back(VE.getMetadataID(MD));
2246
2248 Record.clear();
2249}
2250
2251void ModuleBitcodeWriter::writeDIModule(const DIModule *N,
2253 unsigned Abbrev) {
2254 Record.push_back(N->isDistinct());
2255 for (auto &I : N->operands())
2256 Record.push_back(VE.getMetadataOrNullID(I));
2257 Record.push_back(N->getLineNo());
2258 Record.push_back(N->getIsDecl());
2259
2260 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
2261 Record.clear();
2262}
2263
2264void ModuleBitcodeWriter::writeDIAssignID(const DIAssignID *N,
2266 unsigned Abbrev) {
2267 // There are no arguments for this metadata type.
2268 Record.push_back(N->isDistinct());
2270 Record.clear();
2271}
2272
2273void ModuleBitcodeWriter::writeDITemplateTypeParameter(
2275 unsigned Abbrev) {
2276 Record.push_back(N->isDistinct());
2277 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2278 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2279 Record.push_back(N->isDefault());
2280
2282 Record.clear();
2283}
2284
2285void ModuleBitcodeWriter::writeDITemplateValueParameter(
2287 unsigned Abbrev) {
2288 Record.push_back(N->isDistinct());
2289 Record.push_back(N->getTag());
2290 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2291 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2292 Record.push_back(N->isDefault());
2293 Record.push_back(VE.getMetadataOrNullID(N->getValue()));
2294
2296 Record.clear();
2297}
2298
2299void ModuleBitcodeWriter::writeDIGlobalVariable(
2301 unsigned Abbrev) {
2302 const uint64_t Version = 2 << 1;
2303 Record.push_back((uint64_t)N->isDistinct() | Version);
2304 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2305 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2306 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
2307 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2308 Record.push_back(N->getLine());
2309 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2310 Record.push_back(N->isLocalToUnit());
2311 Record.push_back(N->isDefinition());
2312 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
2313 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams()));
2314 Record.push_back(N->getAlignInBits());
2315 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2316
2318 Record.clear();
2319}
2320
2321void ModuleBitcodeWriter::writeDILocalVariable(
2323 unsigned Abbrev) {
2324 // In order to support all possible bitcode formats in BitcodeReader we need
2325 // to distinguish the following cases:
2326 // 1) Record has no artificial tag (Record[1]),
2327 // has no obsolete inlinedAt field (Record[9]).
2328 // In this case Record size will be 8, HasAlignment flag is false.
2329 // 2) Record has artificial tag (Record[1]),
2330 // has no obsolete inlignedAt field (Record[9]).
2331 // In this case Record size will be 9, HasAlignment flag is false.
2332 // 3) Record has both artificial tag (Record[1]) and
2333 // obsolete inlignedAt field (Record[9]).
2334 // In this case Record size will be 10, HasAlignment flag is false.
2335 // 4) Record has neither artificial tag, nor inlignedAt field, but
2336 // HasAlignment flag is true and Record[8] contains alignment value.
2337 const uint64_t HasAlignmentFlag = 1 << 1;
2338 Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
2339 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2340 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2341 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2342 Record.push_back(N->getLine());
2343 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2344 Record.push_back(N->getArg());
2345 Record.push_back(N->getFlags());
2346 Record.push_back(N->getAlignInBits());
2347 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2348
2350 Record.clear();
2351}
2352
2353void ModuleBitcodeWriter::writeDILabel(
2355 unsigned Abbrev) {
2356 uint64_t IsArtificialFlag = uint64_t(N->isArtificial()) << 1;
2357 Record.push_back((uint64_t)N->isDistinct() | IsArtificialFlag);
2358 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2359 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2360 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2361 Record.push_back(N->getLine());
2362 Record.push_back(N->getColumn());
2363 Record.push_back(N->getCoroSuspendIdx().has_value()
2364 ? (uint64_t)N->getCoroSuspendIdx().value()
2365 : std::numeric_limits<uint64_t>::max());
2366
2367 Stream.EmitRecord(bitc::METADATA_LABEL, Record, Abbrev);
2368 Record.clear();
2369}
2370
2371void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,
2373 unsigned Abbrev) {
2374 Record.reserve(N->getElements().size() + 1);
2375 const uint64_t Version = 3 << 1;
2376 Record.push_back((uint64_t)N->isDistinct() | Version);
2377 Record.append(N->elements_begin(), N->elements_end());
2378
2380 Record.clear();
2381}
2382
2383void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
2385 unsigned Abbrev) {
2386 Record.push_back(N->isDistinct());
2387 Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
2388 Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
2389
2391 Record.clear();
2392}
2393
2394void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
2396 unsigned Abbrev) {
2397 Record.push_back(N->isDistinct());
2398 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2399 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2400 Record.push_back(N->getLine());
2401 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
2402 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
2403 Record.push_back(N->getAttributes());
2404 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2405
2407 Record.clear();
2408}
2409
2410void ModuleBitcodeWriter::writeDIImportedEntity(
2412 unsigned Abbrev) {
2413 Record.push_back(N->isDistinct());
2414 Record.push_back(N->getTag());
2415 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2416 Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
2417 Record.push_back(N->getLine());
2418 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2419 Record.push_back(VE.getMetadataOrNullID(N->getRawFile()));
2420 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
2421
2423 Record.clear();
2424}
2425
2426unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
2427 auto Abbv = std::make_shared<BitCodeAbbrev>();
2431 return Stream.EmitAbbrev(std::move(Abbv));
2432}
2433
2434void ModuleBitcodeWriter::writeNamedMetadata(
2436 if (M.named_metadata_empty())
2437 return;
2438
2439 unsigned Abbrev = createNamedMetadataAbbrev();
2440 for (const NamedMDNode &NMD : M.named_metadata()) {
2441 // Write name.
2442 StringRef Str = NMD.getName();
2443 Record.append(Str.bytes_begin(), Str.bytes_end());
2444 Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
2445 Record.clear();
2446
2447 // Write named metadata operands.
2448 for (const MDNode *N : NMD.operands())
2449 Record.push_back(VE.getMetadataID(N));
2451 Record.clear();
2452 }
2453}
2454
2455unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
2456 auto Abbv = std::make_shared<BitCodeAbbrev>();
2458 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
2459 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
2461 return Stream.EmitAbbrev(std::move(Abbv));
2462}
2463
2464/// Write out a record for MDString.
2465///
2466/// All the metadata strings in a metadata block are emitted in a single
2467/// record. The sizes and strings themselves are shoved into a blob.
2468void ModuleBitcodeWriter::writeMetadataStrings(
2470 if (Strings.empty())
2471 return;
2472
2473 // Start the record with the number of strings.
2474 Record.push_back(bitc::METADATA_STRINGS);
2475 Record.push_back(Strings.size());
2476
2477 // Emit the sizes of the strings in the blob.
2478 SmallString<256> Blob;
2479 {
2480 BitstreamWriter W(Blob);
2481 for (const Metadata *MD : Strings)
2482 W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
2483 W.FlushToWord();
2484 }
2485
2486 // Add the offset to the strings to the record.
2487 Record.push_back(Blob.size());
2488
2489 // Add the strings to the blob.
2490 for (const Metadata *MD : Strings)
2491 Blob.append(cast<MDString>(MD)->getString());
2492
2493 // Emit the final record.
2494 Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
2495 Record.clear();
2496}
2497
2498// Generates an enum to use as an index in the Abbrev array of Metadata record.
2499enum MetadataAbbrev : unsigned {
2500#define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
2501#include "llvm/IR/Metadata.def"
2504
2505void ModuleBitcodeWriter::writeMetadataRecords(
2507 std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
2508 if (MDs.empty())
2509 return;
2510
2511 // Initialize MDNode abbreviations.
2512#define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
2513#include "llvm/IR/Metadata.def"
2514
2515 for (const Metadata *MD : MDs) {
2516 if (IndexPos)
2517 IndexPos->push_back(Stream.GetCurrentBitNo());
2518 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
2519 assert(N->isResolved() && "Expected forward references to be resolved");
2520
2521 switch (N->getMetadataID()) {
2522 default:
2523 llvm_unreachable("Invalid MDNode subclass");
2524#define HANDLE_MDNODE_LEAF(CLASS) \
2525 case Metadata::CLASS##Kind: \
2526 if (MDAbbrevs) \
2527 write##CLASS(cast<CLASS>(N), Record, \
2528 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
2529 else \
2530 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
2531 continue;
2532#include "llvm/IR/Metadata.def"
2533 }
2534 }
2535 if (auto *AL = dyn_cast<DIArgList>(MD)) {
2537 continue;
2538 }
2539 writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
2540 }
2541}
2542
2543void ModuleBitcodeWriter::writeModuleMetadata() {
2544 if (!VE.hasMDs() && M.named_metadata_empty())
2545 return;
2546
2549
2550 // Emit all abbrevs upfront, so that the reader can jump in the middle of the
2551 // block and load any metadata.
2552 std::vector<unsigned> MDAbbrevs;
2553
2554 MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
2555 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
2556 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
2557 createGenericDINodeAbbrev();
2558
2559 auto Abbv = std::make_shared<BitCodeAbbrev>();
2563 unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2564
2565 Abbv = std::make_shared<BitCodeAbbrev>();
2569 unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2570
2571 // Emit MDStrings together upfront.
2572 writeMetadataStrings(VE.getMDStrings(), Record);
2573
2574 // We only emit an index for the metadata record if we have more than a given
2575 // (naive) threshold of metadatas, otherwise it is not worth it.
2576 if (VE.getNonMDStrings().size() > IndexThreshold) {
2577 // Write a placeholder value in for the offset of the metadata index,
2578 // which is written after the records, so that it can include
2579 // the offset of each entry. The placeholder offset will be
2580 // updated after all records are emitted.
2581 uint64_t Vals[] = {0, 0};
2582 Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
2583 }
2584
2585 // Compute and save the bit offset to the current position, which will be
2586 // patched when we emit the index later. We can simply subtract the 64-bit
2587 // fixed size from the current bit number to get the location to backpatch.
2588 uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
2589
2590 // This index will contain the bitpos for each individual record.
2591 std::vector<uint64_t> IndexPos;
2592 IndexPos.reserve(VE.getNonMDStrings().size());
2593
2594 // Write all the records
2595 writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
2596
2597 if (VE.getNonMDStrings().size() > IndexThreshold) {
2598 // Now that we have emitted all the records we will emit the index. But
2599 // first
2600 // backpatch the forward reference so that the reader can skip the records
2601 // efficiently.
2602 Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
2603 Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
2604
2605 // Delta encode the index.
2606 uint64_t PreviousValue = IndexOffsetRecordBitPos;
2607 for (auto &Elt : IndexPos) {
2608 auto EltDelta = Elt - PreviousValue;
2609 PreviousValue = Elt;
2610 Elt = EltDelta;
2611 }
2612 // Emit the index record.
2613 Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
2614 IndexPos.clear();
2615 }
2616
2617 // Write the named metadata now.
2618 writeNamedMetadata(Record);
2619
2620 auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
2622 Record.push_back(VE.getValueID(&GO));
2623 pushGlobalMetadataAttachment(Record, GO);
2625 };
2626 for (const Function &F : M)
2627 if (F.isDeclaration() && F.hasMetadata())
2628 AddDeclAttachedMetadata(F);
2629 // FIXME: Only store metadata for declarations here, and move data for global
2630 // variable definitions to a separate block (PR28134).
2631 for (const GlobalVariable &GV : M.globals())
2632 if (GV.hasMetadata())
2633 AddDeclAttachedMetadata(GV);
2634
2635 Stream.ExitBlock();
2636}
2637
2638void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
2639 if (!VE.hasMDs())
2640 return;
2641
2644 writeMetadataStrings(VE.getMDStrings(), Record);
2645 writeMetadataRecords(VE.getNonMDStrings(), Record);
2646 Stream.ExitBlock();
2647}
2648
2649void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
2651 // [n x [id, mdnode]]
2653 GO.getAllMetadata(MDs);
2654 for (const auto &I : MDs) {
2655 Record.push_back(I.first);
2656 Record.push_back(VE.getMetadataID(I.second));
2657 }
2658}
2659
2660void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
2662
2664
2665 if (F.hasMetadata()) {
2666 pushGlobalMetadataAttachment(Record, F);
2668 Record.clear();
2669 }
2670
2671 // Write metadata attachments
2672 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
2674 for (const BasicBlock &BB : F)
2675 for (const Instruction &I : BB) {
2676 MDs.clear();
2677 I.getAllMetadataOtherThanDebugLoc(MDs);
2678
2679 // If no metadata, ignore instruction.
2680 if (MDs.empty()) continue;
2681
2682 Record.push_back(VE.getInstructionID(&I));
2683
2684 for (const auto &[ID, MD] : MDs) {
2685 Record.push_back(ID);
2686 Record.push_back(VE.getMetadataID(MD));
2687 }
2689 Record.clear();
2690 }
2691
2692 Stream.ExitBlock();
2693}
2694
2695void ModuleBitcodeWriter::writeModuleMetadataKinds() {
2697
2698 // Write metadata kinds
2699 // METADATA_KIND - [n x [id, name]]
2701 M.getMDKindNames(Names);
2702
2703 if (Names.empty()) return;
2704
2706
2707 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
2708 Record.push_back(MDKindID);
2709 StringRef KName = Names[MDKindID];
2710 Record.append(KName.begin(), KName.end());
2711
2713 Record.clear();
2714 }
2715
2716 Stream.ExitBlock();
2717}
2718
2719void ModuleBitcodeWriter::writeOperandBundleTags() {
2720 // Write metadata kinds
2721 //
2722 // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
2723 //
2724 // OPERAND_BUNDLE_TAG - [strchr x N]
2725
2727 M.getOperandBundleTags(Tags);
2728
2729 if (Tags.empty())
2730 return;
2731
2733
2735
2736 for (auto Tag : Tags) {
2737 Record.append(Tag.begin(), Tag.end());
2738
2740 Record.clear();
2741 }
2742
2743 Stream.ExitBlock();
2744}
2745
2746void ModuleBitcodeWriter::writeSyncScopeNames() {
2748 M.getContext().getSyncScopeNames(SSNs);
2749 if (SSNs.empty())
2750 return;
2751
2753
2755 for (auto SSN : SSNs) {
2756 Record.append(SSN.begin(), SSN.end());
2758 Record.clear();
2759 }
2760
2761 Stream.ExitBlock();
2762}
2763
2764void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
2765 bool isGlobal) {
2766 if (FirstVal == LastVal) return;
2767
2769
2770 unsigned AggregateAbbrev = 0;
2771 unsigned String8Abbrev = 0;
2772 unsigned CString7Abbrev = 0;
2773 unsigned CString6Abbrev = 0;
2774 // If this is a constant pool for the module, emit module-specific abbrevs.
2775 if (isGlobal) {
2776 // Abbrev for CST_CODE_AGGREGATE.
2777 auto Abbv = std::make_shared<BitCodeAbbrev>();
2780 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
2781 AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2782
2783 // Abbrev for CST_CODE_STRING.
2784 Abbv = std::make_shared<BitCodeAbbrev>();
2788 String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2789 // Abbrev for CST_CODE_CSTRING.
2790 Abbv = std::make_shared<BitCodeAbbrev>();
2794 CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2795 // Abbrev for CST_CODE_CSTRING.
2796 Abbv = std::make_shared<BitCodeAbbrev>();
2800 CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2801 }
2802
2804
2805 const ValueEnumerator::ValueList &Vals = VE.getValues();
2806 Type *LastTy = nullptr;
2807 for (unsigned i = FirstVal; i != LastVal; ++i) {
2808 const Value *V = Vals[i].first;
2809 // If we need to switch types, do so now.
2810 if (V->getType() != LastTy) {
2811 LastTy = V->getType();
2812 Record.push_back(VE.getTypeID(LastTy));
2814 CONSTANTS_SETTYPE_ABBREV);
2815 Record.clear();
2816 }
2817
2818 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
2819 Record.push_back(VE.getTypeID(IA->getFunctionType()));
2820 Record.push_back(
2821 unsigned(IA->hasSideEffects()) | unsigned(IA->isAlignStack()) << 1 |
2822 unsigned(IA->getDialect() & 1) << 2 | unsigned(IA->canThrow()) << 3);
2823
2824 // Add the asm string.
2825 StringRef AsmStr = IA->getAsmString();
2826 Record.push_back(AsmStr.size());
2827 Record.append(AsmStr.begin(), AsmStr.end());
2828
2829 // Add the constraint string.
2830 StringRef ConstraintStr = IA->getConstraintString();
2831 Record.push_back(ConstraintStr.size());
2832 Record.append(ConstraintStr.begin(), ConstraintStr.end());
2834 Record.clear();
2835 continue;
2836 }
2837 const Constant *C = cast<Constant>(V);
2838 unsigned Code = -1U;
2839 unsigned AbbrevToUse = 0;
2840 if (C->isNullValue()) {
2842 } else if (isa<PoisonValue>(C)) {
2844 } else if (isa<UndefValue>(C)) {
2846 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
2847 if (IV->getBitWidth() <= 64) {
2848 uint64_t V = IV->getSExtValue();
2851 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
2852 } else { // Wide integers, > 64 bits in size.
2853 emitWideAPInt(Record, IV->getValue());
2855 }
2856 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
2858 Type *Ty = CFP->getType()->getScalarType();
2859 if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() ||
2860 Ty->isDoubleTy()) {
2861 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
2862 } else if (Ty->isX86_FP80Ty()) {
2863 // api needed to prevent premature destruction
2864 // bits are not in the same order as a normal i80 APInt, compensate.
2865 APInt api = CFP->getValueAPF().bitcastToAPInt();
2866 const uint64_t *p = api.getRawData();
2867 Record.push_back((p[1] << 48) | (p[0] >> 16));
2868 Record.push_back(p[0] & 0xffffLL);
2869 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
2870 APInt api = CFP->getValueAPF().bitcastToAPInt();
2871 const uint64_t *p = api.getRawData();
2872 Record.push_back(p[0]);
2873 Record.push_back(p[1]);
2874 } else {
2875 assert(0 && "Unknown FP type!");
2876 }
2877 } else if (isa<ConstantDataSequential>(C) &&
2878 cast<ConstantDataSequential>(C)->isString()) {
2879 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
2880 // Emit constant strings specially.
2881 uint64_t NumElts = Str->getNumElements();
2882 // If this is a null-terminated string, use the denser CSTRING encoding.
2883 if (Str->isCString()) {
2885 --NumElts; // Don't encode the null, which isn't allowed by char6.
2886 } else {
2888 AbbrevToUse = String8Abbrev;
2889 }
2890 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
2891 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
2892 for (uint64_t i = 0; i != NumElts; ++i) {
2893 unsigned char V = Str->getElementAsInteger(i);
2894 Record.push_back(V);
2895 isCStr7 &= (V & 128) == 0;
2896 if (isCStrChar6)
2897 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
2898 }
2899
2900 if (isCStrChar6)
2901 AbbrevToUse = CString6Abbrev;
2902 else if (isCStr7)
2903 AbbrevToUse = CString7Abbrev;
2904 } else if (const ConstantDataSequential *CDS =
2905 dyn_cast<ConstantDataSequential>(C)) {
2907 Type *EltTy = CDS->getElementType();
2908 if (isa<IntegerType>(EltTy)) {
2909 for (uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i)
2910 Record.push_back(CDS->getElementAsInteger(i));
2911 } else {
2912 for (uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i)
2913 Record.push_back(
2914 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
2915 }
2916 } else if (isa<ConstantAggregate>(C)) {
2918 for (const Value *Op : C->operands())
2919 Record.push_back(VE.getValueID(Op));
2920 AbbrevToUse = AggregateAbbrev;
2921 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2922 switch (CE->getOpcode()) {
2923 default:
2924 if (Instruction::isCast(CE->getOpcode())) {
2926 Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
2927 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2928 Record.push_back(VE.getValueID(C->getOperand(0)));
2929 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
2930 } else {
2931 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
2933 Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
2934 Record.push_back(VE.getValueID(C->getOperand(0)));
2935 Record.push_back(VE.getValueID(C->getOperand(1)));
2937 if (Flags != 0)
2938 Record.push_back(Flags);
2939 }
2940 break;
2941 case Instruction::FNeg: {
2942 assert(CE->getNumOperands() == 1 && "Unknown constant expr!");
2944 Record.push_back(getEncodedUnaryOpcode(CE->getOpcode()));
2945 Record.push_back(VE.getValueID(C->getOperand(0)));
2947 if (Flags != 0)
2948 Record.push_back(Flags);
2949 break;
2950 }
2951 case Instruction::GetElementPtr: {
2953 const auto *GO = cast<GEPOperator>(C);
2954 Record.push_back(VE.getTypeID(GO->getSourceElementType()));
2955 Record.push_back(getOptimizationFlags(GO));
2956 if (std::optional<ConstantRange> Range = GO->getInRange()) {
2958 emitConstantRange(Record, *Range, /*EmitBitWidth=*/true);
2959 }
2960 for (const Value *Op : CE->operands()) {
2961 Record.push_back(VE.getTypeID(Op->getType()));
2962 Record.push_back(VE.getValueID(Op));
2963 }
2964 break;
2965 }
2966 case Instruction::ExtractElement:
2968 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2969 Record.push_back(VE.getValueID(C->getOperand(0)));
2970 Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
2971 Record.push_back(VE.getValueID(C->getOperand(1)));
2972 break;
2973 case Instruction::InsertElement:
2975 Record.push_back(VE.getValueID(C->getOperand(0)));
2976 Record.push_back(VE.getValueID(C->getOperand(1)));
2977 Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
2978 Record.push_back(VE.getValueID(C->getOperand(2)));
2979 break;
2980 case Instruction::ShuffleVector:
2981 // If the return type and argument types are the same, this is a
2982 // standard shufflevector instruction. If the types are different,
2983 // then the shuffle is widening or truncating the input vectors, and
2984 // the argument type must also be encoded.
2985 if (C->getType() == C->getOperand(0)->getType()) {
2987 } else {
2989 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2990 }
2991 Record.push_back(VE.getValueID(C->getOperand(0)));
2992 Record.push_back(VE.getValueID(C->getOperand(1)));
2993 Record.push_back(VE.getValueID(CE->getShuffleMaskForBitcode()));
2994 break;
2995 }
2996 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
2998 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
2999 Record.push_back(VE.getValueID(BA->getFunction()));
3000 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
3001 } else if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) {
3003 Record.push_back(VE.getTypeID(Equiv->getGlobalValue()->getType()));
3004 Record.push_back(VE.getValueID(Equiv->getGlobalValue()));
3005 } else if (const auto *NC = dyn_cast<NoCFIValue>(C)) {
3007 Record.push_back(VE.getTypeID(NC->getGlobalValue()->getType()));
3008 Record.push_back(VE.getValueID(NC->getGlobalValue()));
3009 } else if (const auto *CPA = dyn_cast<ConstantPtrAuth>(C)) {
3011 Record.push_back(VE.getValueID(CPA->getPointer()));
3012 Record.push_back(VE.getValueID(CPA->getKey()));
3013 Record.push_back(VE.getValueID(CPA->getDiscriminator()));
3014 Record.push_back(VE.getValueID(CPA->getAddrDiscriminator()));
3015 } else {
3016#ifndef NDEBUG
3017 C->dump();
3018#endif
3019 llvm_unreachable("Unknown constant!");
3020 }
3021 Stream.EmitRecord(Code, Record, AbbrevToUse);
3022 Record.clear();
3023 }
3024
3025 Stream.ExitBlock();
3026}
3027
3028void ModuleBitcodeWriter::writeModuleConstants() {
3029 const ValueEnumerator::ValueList &Vals = VE.getValues();
3030
3031 // Find the first constant to emit, which is the first non-globalvalue value.
3032 // We know globalvalues have been emitted by WriteModuleInfo.
3033 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
3034 if (!isa<GlobalValue>(Vals[i].first)) {
3035 writeConstants(i, Vals.size(), true);
3036 return;
3037 }
3038 }
3039}
3040
3041/// pushValueAndType - The file has to encode both the value and type id for
3042/// many values, because we need to know what type to create for forward
3043/// references. However, most operands are not forward references, so this type
3044/// field is not needed.
3045///
3046/// This function adds V's value ID to Vals. If the value ID is higher than the
3047/// instruction ID, then it is a forward reference, and it also includes the
3048/// type ID. The value ID that is written is encoded relative to the InstID.
3049bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
3051 unsigned ValID = VE.getValueID(V);
3052 // Make encoding relative to the InstID.
3053 Vals.push_back(InstID - ValID);
3054 if (ValID >= InstID) {
3055 Vals.push_back(VE.getTypeID(V->getType()));
3056 return true;
3057 }
3058 return false;
3059}
3060
3061bool ModuleBitcodeWriter::pushValueOrMetadata(const Value *V, unsigned InstID,
3063 bool IsMetadata = V->getType()->isMetadataTy();
3064 if (IsMetadata) {
3066 Metadata *MD = cast<MetadataAsValue>(V)->getMetadata();
3067 unsigned ValID = VE.getMetadataID(MD);
3068 Vals.push_back(InstID - ValID);
3069 return false;
3070 }
3071 return pushValueAndType(V, InstID, Vals);
3072}
3073
3074void ModuleBitcodeWriter::writeOperandBundles(const CallBase &CS,
3075 unsigned InstID) {
3077 LLVMContext &C = CS.getContext();
3078
3079 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
3080 const auto &Bundle = CS.getOperandBundleAt(i);
3081 Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
3082
3083 for (auto &Input : Bundle.Inputs)
3084 pushValueOrMetadata(Input, InstID, Record);
3085
3087 Record.clear();
3088 }
3089}
3090
3091/// pushValue - Like pushValueAndType, but where the type of the value is
3092/// omitted (perhaps it was already encoded in an earlier operand).
3093void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
3095 unsigned ValID = VE.getValueID(V);
3096 Vals.push_back(InstID - ValID);
3097}
3098
3099void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
3101 unsigned ValID = VE.getValueID(V);
3102 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
3103 emitSignedInt64(Vals, diff);
3104}
3105
3106/// WriteInstruction - Emit an instruction to the specified stream.
3107void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
3108 unsigned InstID,
3110 unsigned Code = 0;
3111 unsigned AbbrevToUse = 0;
3112 VE.setInstructionID(&I);
3113 switch (I.getOpcode()) {
3114 default:
3115 if (Instruction::isCast(I.getOpcode())) {
3117 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
3118 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
3119 Vals.push_back(VE.getTypeID(I.getType()));
3120 Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
3122 if (Flags != 0) {
3123 if (AbbrevToUse == FUNCTION_INST_CAST_ABBREV)
3124 AbbrevToUse = FUNCTION_INST_CAST_FLAGS_ABBREV;
3125 Vals.push_back(Flags);
3126 }
3127 } else {
3128 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
3130 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
3131 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
3132 pushValue(I.getOperand(1), InstID, Vals);
3133 Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
3135 if (Flags != 0) {
3136 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
3137 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
3138 Vals.push_back(Flags);
3139 }
3140 }
3141 break;
3142 case Instruction::FNeg: {
3144 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
3145 AbbrevToUse = FUNCTION_INST_UNOP_ABBREV;
3146 Vals.push_back(getEncodedUnaryOpcode(I.getOpcode()));
3148 if (Flags != 0) {
3149 if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV)
3150 AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV;
3151 Vals.push_back(Flags);
3152 }
3153 break;
3154 }
3155 case Instruction::GetElementPtr: {
3157 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
3158 auto &GEPInst = cast<GetElementPtrInst>(I);
3160 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
3161 for (const Value *Op : I.operands())
3162 pushValueAndType(Op, InstID, Vals);
3163 break;
3164 }
3165 case Instruction::ExtractValue: {
3167 pushValueAndType(I.getOperand(0), InstID, Vals);
3168 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
3169 Vals.append(EVI->idx_begin(), EVI->idx_end());
3170 break;
3171 }
3172 case Instruction::InsertValue: {
3174 pushValueAndType(I.getOperand(0), InstID, Vals);
3175 pushValueAndType(I.getOperand(1), InstID, Vals);
3176 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
3177 Vals.append(IVI->idx_begin(), IVI->idx_end());
3178 break;
3179 }
3180 case Instruction::Select: {
3182 pushValueAndType(I.getOperand(1), InstID, Vals);
3183 pushValue(I.getOperand(2), InstID, Vals);
3184 pushValueAndType(I.getOperand(0), InstID, Vals);
3186 if (Flags != 0)
3187 Vals.push_back(Flags);
3188 break;
3189 }
3190 case Instruction::ExtractElement:
3192 pushValueAndType(I.getOperand(0), InstID, Vals);
3193 pushValueAndType(I.getOperand(1), InstID, Vals);
3194 break;
3195 case Instruction::InsertElement:
3197 pushValueAndType(I.getOperand(0), InstID, Vals);
3198 pushValue(I.getOperand(1), InstID, Vals);
3199 pushValueAndType(I.getOperand(2), InstID, Vals);
3200 break;
3201 case Instruction::ShuffleVector:
3203 pushValueAndType(I.getOperand(0), InstID, Vals);
3204 pushValue(I.getOperand(1), InstID, Vals);
3205 pushValue(cast<ShuffleVectorInst>(I).getShuffleMaskForBitcode(), InstID,
3206 Vals);
3207 break;
3208 case Instruction::ICmp:
3209 case Instruction::FCmp: {
3210 // compare returning Int1Ty or vector of Int1Ty
3212 AbbrevToUse = FUNCTION_INST_CMP_ABBREV;
3213 if (pushValueAndType(I.getOperand(0), InstID, Vals))
3214 AbbrevToUse = 0;
3215 pushValue(I.getOperand(1), InstID, Vals);
3216 Vals.push_back(cast<CmpInst>(I).getPredicate());
3218 if (Flags != 0) {
3219 Vals.push_back(Flags);
3220 if (AbbrevToUse)
3221 AbbrevToUse = FUNCTION_INST_CMP_FLAGS_ABBREV;
3222 }
3223 break;
3224 }
3225
3226 case Instruction::Ret:
3227 {
3229 unsigned NumOperands = I.getNumOperands();
3230 if (NumOperands == 0)
3231 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
3232 else if (NumOperands == 1) {
3233 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
3234 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
3235 } else {
3236 for (const Value *Op : I.operands())
3237 pushValueAndType(Op, InstID, Vals);
3238 }
3239 }
3240 break;
3241 case Instruction::Br:
3242 {
3244 AbbrevToUse = FUNCTION_INST_BR_UNCOND_ABBREV;
3245 const BranchInst &II = cast<BranchInst>(I);
3246 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
3247 if (II.isConditional()) {
3248 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
3249 pushValue(II.getCondition(), InstID, Vals);
3250 AbbrevToUse = FUNCTION_INST_BR_COND_ABBREV;
3251 }
3252 }
3253 break;
3254 case Instruction::Switch:
3255 {
3257 const SwitchInst &SI = cast<SwitchInst>(I);
3258 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
3259 pushValue(SI.getCondition(), InstID, Vals);
3260 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
3261 for (auto Case : SI.cases()) {
3262 Vals.push_back(VE.getValueID(Case.getCaseValue()));
3263 Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
3264 }
3265 }
3266 break;
3267 case Instruction::IndirectBr:
3269 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
3270 // Encode the address operand as relative, but not the basic blocks.
3271 pushValue(I.getOperand(0), InstID, Vals);
3272 for (const Value *Op : drop_begin(I.operands()))
3273 Vals.push_back(VE.getValueID(Op));
3274 break;
3275
3276 case Instruction::Invoke: {
3277 const InvokeInst *II = cast<InvokeInst>(&I);
3278 const Value *Callee = II->getCalledOperand();
3279 FunctionType *FTy = II->getFunctionType();
3280
3281 if (II->hasOperandBundles())
3282 writeOperandBundles(*II, InstID);
3283
3285
3286 Vals.push_back(VE.getAttributeListID(II->getAttributes()));
3287 Vals.push_back(II->getCallingConv() | 1 << 13);
3288 Vals.push_back(VE.getValueID(II->getNormalDest()));
3289 Vals.push_back(VE.getValueID(II->getUnwindDest()));
3290 Vals.push_back(VE.getTypeID(FTy));
3291 pushValueAndType(Callee, InstID, Vals);
3292
3293 // Emit value #'s for the fixed parameters.
3294 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3295 pushValue(I.getOperand(i), InstID, Vals); // fixed param.
3296
3297 // Emit type/value pairs for varargs params.
3298 if (FTy->isVarArg()) {
3299 for (unsigned i = FTy->getNumParams(), e = II->arg_size(); i != e; ++i)
3300 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
3301 }
3302 break;
3303 }
3304 case Instruction::Resume:
3306 pushValueAndType(I.getOperand(0), InstID, Vals);
3307 break;
3308 case Instruction::CleanupRet: {
3310 const auto &CRI = cast<CleanupReturnInst>(I);
3311 pushValue(CRI.getCleanupPad(), InstID, Vals);
3312 if (CRI.hasUnwindDest())
3313 Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
3314 break;
3315 }
3316 case Instruction::CatchRet: {
3318 const auto &CRI = cast<CatchReturnInst>(I);
3319 pushValue(CRI.getCatchPad(), InstID, Vals);
3320 Vals.push_back(VE.getValueID(CRI.getSuccessor()));
3321 break;
3322 }
3323 case Instruction::CleanupPad:
3324 case Instruction::CatchPad: {
3325 const auto &FuncletPad = cast<FuncletPadInst>(I);
3326 Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
3328 pushValue(FuncletPad.getParentPad(), InstID, Vals);
3329
3330 unsigned NumArgOperands = FuncletPad.arg_size();
3331 Vals.push_back(NumArgOperands);
3332 for (unsigned Op = 0; Op != NumArgOperands; ++Op)
3333 pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
3334 break;
3335 }
3336 case Instruction::CatchSwitch: {
3338 const auto &CatchSwitch = cast<CatchSwitchInst>(I);
3339
3340 pushValue(CatchSwitch.getParentPad(), InstID, Vals);
3341
3342 unsigned NumHandlers = CatchSwitch.getNumHandlers();
3343 Vals.push_back(NumHandlers);
3344 for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
3345 Vals.push_back(VE.getValueID(CatchPadBB));
3346
3347 if (CatchSwitch.hasUnwindDest())
3348 Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
3349 break;
3350 }
3351 case Instruction::CallBr: {
3352 const CallBrInst *CBI = cast<CallBrInst>(&I);
3353 const Value *Callee = CBI->getCalledOperand();
3354 FunctionType *FTy = CBI->getFunctionType();
3355
3356 if (CBI->hasOperandBundles())
3357 writeOperandBundles(*CBI, InstID);
3358
3360
3362
3365
3366 Vals.push_back(VE.getValueID(CBI->getDefaultDest()));
3367 Vals.push_back(CBI->getNumIndirectDests());
3368 for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i)
3369 Vals.push_back(VE.getValueID(CBI->getIndirectDest(i)));
3370
3371 Vals.push_back(VE.getTypeID(FTy));
3372 pushValueAndType(Callee, InstID, Vals);
3373
3374 // Emit value #'s for the fixed parameters.
3375 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3376 pushValue(I.getOperand(i), InstID, Vals); // fixed param.
3377
3378 // Emit type/value pairs for varargs params.
3379 if (FTy->isVarArg()) {
3380 for (unsigned i = FTy->getNumParams(), e = CBI->arg_size(); i != e; ++i)
3381 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
3382 }
3383 break;
3384 }
3385 case Instruction::Unreachable:
3387 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
3388 break;
3389
3390 case Instruction::PHI: {
3391 const PHINode &PN = cast<PHINode>(I);
3393 // With the newer instruction encoding, forward references could give
3394 // negative valued IDs. This is most common for PHIs, so we use
3395 // signed VBRs.
3397 Vals64.push_back(VE.getTypeID(PN.getType()));
3398 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
3399 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
3400 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
3401 }
3402
3404 if (Flags != 0)
3405 Vals64.push_back(Flags);
3406
3407 // Emit a Vals64 vector and exit.
3408 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
3409 Vals64.clear();
3410 return;
3411 }
3412
3413 case Instruction::LandingPad: {
3414 const LandingPadInst &LP = cast<LandingPadInst>(I);
3416 Vals.push_back(VE.getTypeID(LP.getType()));
3417 Vals.push_back(LP.isCleanup());
3418 Vals.push_back(LP.getNumClauses());
3419 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
3420 if (LP.isCatch(I))
3422 else
3424 pushValueAndType(LP.getClause(I), InstID, Vals);
3425 }
3426 break;
3427 }
3428
3429 case Instruction::Alloca: {
3431 const AllocaInst &AI = cast<AllocaInst>(I);
3432 Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
3433 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
3434 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
3435 using APV = AllocaPackedValues;
3436 unsigned Record = 0;
3437 unsigned EncodedAlign = getEncodedAlign(AI.getAlign());
3438 Bitfield::set<APV::AlignLower>(
3439 Record, EncodedAlign & ((1 << APV::AlignLower::Bits) - 1));
3440 Bitfield::set<APV::AlignUpper>(Record,
3441 EncodedAlign >> APV::AlignLower::Bits);
3442 Bitfield::set<APV::UsedWithInAlloca>(Record, AI.isUsedWithInAlloca());
3443 Bitfield::set<APV::ExplicitType>(Record, true);
3444 Bitfield::set<APV::SwiftError>(Record, AI.isSwiftError());
3445 Vals.push_back(Record);
3446
3447 unsigned AS = AI.getAddressSpace();
3448 if (AS != M.getDataLayout().getAllocaAddrSpace())
3449 Vals.push_back(AS);
3450 break;
3451 }
3452
3453 case Instruction::Load:
3454 if (cast<LoadInst>(I).isAtomic()) {
3456 pushValueAndType(I.getOperand(0), InstID, Vals);
3457 } else {
3459 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
3460 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
3461 }
3462 Vals.push_back(VE.getTypeID(I.getType()));
3463 Vals.push_back(getEncodedAlign(cast<LoadInst>(I).getAlign()));
3464 Vals.push_back(cast<LoadInst>(I).isVolatile());
3465 if (cast<LoadInst>(I).isAtomic()) {
3466 Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
3467 Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID()));
3468 }
3469 break;
3470 case Instruction::Store:
3471 if (cast<StoreInst>(I).isAtomic()) {
3473 } else {
3475 AbbrevToUse = FUNCTION_INST_STORE_ABBREV;
3476 }
3477 if (pushValueAndType(I.getOperand(1), InstID, Vals)) // ptrty + ptr
3478 AbbrevToUse = 0;
3479 if (pushValueAndType(I.getOperand(0), InstID, Vals)) // valty + val
3480 AbbrevToUse = 0;
3481 Vals.push_back(getEncodedAlign(cast<StoreInst>(I).getAlign()));
3482 Vals.push_back(cast<StoreInst>(I).isVolatile());
3483 if (cast<StoreInst>(I).isAtomic()) {
3484 Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
3485 Vals.push_back(
3486 getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID()));
3487 }
3488 break;
3489 case Instruction::AtomicCmpXchg:
3491 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
3492 pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
3493 pushValue(I.getOperand(2), InstID, Vals); // newval.
3494 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
3495 Vals.push_back(
3496 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
3497 Vals.push_back(
3498 getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID()));
3499 Vals.push_back(
3500 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
3501 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
3502 Vals.push_back(getEncodedAlign(cast<AtomicCmpXchgInst>(I).getAlign()));
3503 break;
3504 case Instruction::AtomicRMW:
3506 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
3507 pushValueAndType(I.getOperand(1), InstID, Vals); // valty + val
3508 Vals.push_back(
3509 getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
3510 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
3511 Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
3512 Vals.push_back(
3513 getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID()));
3514 Vals.push_back(getEncodedAlign(cast<AtomicRMWInst>(I).getAlign()));
3515 break;
3516 case Instruction::Fence:
3518 Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
3519 Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID()));
3520 break;
3521 case Instruction::Call: {
3522 const CallInst &CI = cast<CallInst>(I);
3523 FunctionType *FTy = CI.getFunctionType();
3524
3525 if (CI.hasOperandBundles())
3526 writeOperandBundles(CI, InstID);
3527
3529
3531
3532 unsigned Flags = getOptimizationFlags(&I);
3534 unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
3535 unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
3537 unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
3538 unsigned(Flags != 0) << bitc::CALL_FMF);
3539 if (Flags != 0)
3540 Vals.push_back(Flags);
3541
3542 Vals.push_back(VE.getTypeID(FTy));
3543 pushValueAndType(CI.getCalledOperand(), InstID, Vals); // Callee
3544
3545 // Emit value #'s for the fixed parameters.
3546 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3547 pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
3548
3549 // Emit type/value pairs for varargs params.
3550 if (FTy->isVarArg()) {
3551 for (unsigned i = FTy->getNumParams(), e = CI.arg_size(); i != e; ++i)
3552 pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
3553 }
3554 break;
3555 }
3556 case Instruction::VAArg:
3558 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
3559 pushValue(I.getOperand(0), InstID, Vals); // valist.
3560 Vals.push_back(VE.getTypeID(I.getType())); // restype.
3561 break;
3562 case Instruction::Freeze:
3564 pushValueAndType(I.getOperand(0), InstID, Vals);
3565 break;
3566 }
3567
3568 Stream.EmitRecord(Code, Vals, AbbrevToUse);
3569 Vals.clear();
3570}
3571
3572/// Write a GlobalValue VST to the module. The purpose of this data structure is
3573/// to allow clients to efficiently find the function body.
3574void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
3575 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3576 // Get the offset of the VST we are writing, and backpatch it into
3577 // the VST forward declaration record.
3578 uint64_t VSTOffset = Stream.GetCurrentBitNo();
3579 // The BitcodeStartBit was the stream offset of the identification block.
3580 VSTOffset -= bitcodeStartBit();
3581 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
3582 // Note that we add 1 here because the offset is relative to one word
3583 // before the start of the identification block, which was historically
3584 // always the start of the regular bitcode header.
3585 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
3586
3588
3589 auto Abbv = std::make_shared<BitCodeAbbrev>();
3591 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3592 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
3593 unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3594
3595 for (const Function &F : M) {
3596 uint64_t Record[2];
3597
3598 if (F.isDeclaration())
3599 continue;
3600
3601 Record[0] = VE.getValueID(&F);
3602
3603 // Save the word offset of the function (from the start of the
3604 // actual bitcode written to the stream).
3605 uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit();
3606 assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
3607 // Note that we add 1 here because the offset is relative to one word
3608 // before the start of the identification block, which was historically
3609 // always the start of the regular bitcode header.
3610 Record[1] = BitcodeIndex / 32 + 1;
3611
3612 Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev);
3613 }
3614
3615 Stream.ExitBlock();
3616}
3617
3618/// Emit names for arguments, instructions and basic blocks in a function.
3619void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
3620 const ValueSymbolTable &VST) {
3621 if (VST.empty())
3622 return;
3623
3625
3626 // FIXME: Set up the abbrev, we know how many values there are!
3627 // FIXME: We know if the type names can use 7-bit ascii.
3629
3630 for (const ValueName &Name : VST) {
3631 // Figure out the encoding to use for the name.
3633
3634 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
3635 NameVals.push_back(VE.getValueID(Name.getValue()));
3636
3637 // VST_CODE_ENTRY: [valueid, namechar x N]
3638 // VST_CODE_BBENTRY: [bbid, namechar x N]
3639 unsigned Code;
3640 if (isa<BasicBlock>(Name.getValue())) {
3642 if (Bits == SE_Char6)
3643 AbbrevToUse = VST_BBENTRY_6_ABBREV;
3644 } else {
3646 if (Bits == SE_Char6)
3647 AbbrevToUse = VST_ENTRY_6_ABBREV;
3648 else if (Bits == SE_Fixed7)
3649 AbbrevToUse = VST_ENTRY_7_ABBREV;
3650 }
3651
3652 for (const auto P : Name.getKey())
3653 NameVals.push_back((unsigned char)P);
3654
3655 // Emit the finished record.
3656 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
3657 NameVals.clear();
3658 }
3659
3660 Stream.ExitBlock();
3661}
3662
3663void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
3664 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
3665 unsigned Code;
3666 if (isa<BasicBlock>(Order.V))
3668 else
3670
3671 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
3672 Record.push_back(VE.getValueID(Order.V));
3673 Stream.EmitRecord(Code, Record);
3674}
3675
3676void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
3678 "Expected to be preserving use-list order");
3679
3680 auto hasMore = [&]() {
3681 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
3682 };
3683 if (!hasMore())
3684 // Nothing to do.
3685 return;
3686
3688 while (hasMore()) {
3689 writeUseList(std::move(VE.UseListOrders.back()));
3690 VE.UseListOrders.pop_back();
3691 }
3692 Stream.ExitBlock();
3693}
3694
3695/// Emit a function body to the module stream.
3696void ModuleBitcodeWriter::writeFunction(
3697 const Function &F,
3698 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3699 // Save the bitcode index of the start of this function block for recording
3700 // in the VST.
3701 FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
3702
3705
3707
3708 // Emit the number of basic blocks, so the reader can create them ahead of
3709 // time.
3710 Vals.push_back(VE.getBasicBlocks().size());
3712 Vals.clear();
3713
3714 // If there are function-local constants, emit them now.
3715 unsigned CstStart, CstEnd;
3716 VE.getFunctionConstantRange(CstStart, CstEnd);
3717 writeConstants(CstStart, CstEnd, false);
3718
3719 // If there is function-local metadata, emit it now.
3720 writeFunctionMetadata(F);
3721
3722 // Keep a running idea of what the instruction ID is.
3723 unsigned InstID = CstEnd;
3724
3725 bool NeedsMetadataAttachment = F.hasMetadata();
3726
3727 DILocation *LastDL = nullptr;
3728 SmallSetVector<Function *, 4> BlockAddressUsers;
3729
3730 // Finally, emit all the instructions, in order.
3731 for (const BasicBlock &BB : F) {
3732 for (const Instruction &I : BB) {
3733 writeInstruction(I, InstID, Vals);
3734
3735 if (!I.getType()->isVoidTy())
3736 ++InstID;
3737
3738 // If the instruction has metadata, write a metadata attachment later.
3739 NeedsMetadataAttachment |= I.hasMetadataOtherThanDebugLoc();
3740
3741 // If the instruction has a debug location, emit it.
3742 if (DILocation *DL = I.getDebugLoc()) {
3743 if (DL == LastDL) {
3744 // Just repeat the same debug loc as last time.
3746 } else {
3747 Vals.push_back(DL->getLine());
3748 Vals.push_back(DL->getColumn());
3749 Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
3750 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
3751 Vals.push_back(DL->isImplicitCode());
3752 Vals.push_back(DL->getAtomGroup());
3753 Vals.push_back(DL->getAtomRank());
3755 FUNCTION_DEBUG_LOC_ABBREV);
3756 Vals.clear();
3757 LastDL = DL;
3758 }
3759 }
3760
3761 // If the instruction has DbgRecords attached to it, emit them. Note that
3762 // they come after the instruction so that it's easy to attach them again
3763 // when reading the bitcode, even though conceptually the debug locations
3764 // start "before" the instruction.
3765 if (I.hasDbgRecords()) {
3766 /// Try to push the value only (unwrapped), otherwise push the
3767 /// metadata wrapped value. Returns true if the value was pushed
3768 /// without the ValueAsMetadata wrapper.
3769 auto PushValueOrMetadata = [&Vals, InstID,
3770 this](Metadata *RawLocation) {
3771 assert(RawLocation &&
3772 "RawLocation unexpectedly null in DbgVariableRecord");
3773 if (ValueAsMetadata *VAM = dyn_cast<ValueAsMetadata>(RawLocation)) {
3774 SmallVector<unsigned, 2> ValAndType;
3775 // If the value is a fwd-ref the type is also pushed. We don't
3776 // want the type, so fwd-refs are kept wrapped (pushValueAndType
3777 // returns false if the value is pushed without type).
3778 if (!pushValueAndType(VAM->getValue(), InstID, ValAndType)) {
3779 Vals.push_back(ValAndType[0]);
3780 return true;
3781 }
3782 }
3783 // The metadata is a DIArgList, or ValueAsMetadata wrapping a
3784 // fwd-ref. Push the metadata ID.
3785 Vals.push_back(VE.getMetadataID(RawLocation));
3786 return false;
3787 };
3788
3789 // Write out non-instruction debug information attached to this
3790 // instruction. Write it after the instruction so that it's easy to
3791 // re-attach to the instruction reading the records in.
3792 for (DbgRecord &DR : I.DebugMarker->getDbgRecordRange()) {
3793 if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) {
3794 Vals.push_back(VE.getMetadataID(&*DLR->getDebugLoc()));
3795 Vals.push_back(VE.getMetadataID(DLR->getLabel()));
3797 Vals.clear();
3798 continue;
3799 }
3800
3801 // First 3 fields are common to all kinds:
3802 // DILocation, DILocalVariable, DIExpression
3803 // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE)
3804 // ..., LocationMetadata
3805 // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE - abbrev'd)
3806 // ..., Value
3807 // dbg_declare (FUNC_CODE_DEBUG_RECORD_DECLARE)
3808 // ..., LocationMetadata
3809 // dbg_assign (FUNC_CODE_DEBUG_RECORD_ASSIGN)
3810 // ..., LocationMetadata, DIAssignID, DIExpression, LocationMetadata
3811 DbgVariableRecord &DVR = cast<DbgVariableRecord>(DR);
3812 Vals.push_back(VE.getMetadataID(&*DVR.getDebugLoc()));
3813 Vals.push_back(VE.getMetadataID(DVR.getVariable()));
3814 Vals.push_back(VE.getMetadataID(DVR.getExpression()));
3815 if (DVR.isDbgValue()) {
3816 if (PushValueOrMetadata(DVR.getRawLocation()))
3818 FUNCTION_DEBUG_RECORD_VALUE_ABBREV);
3819 else
3821 } else if (DVR.isDbgDeclare()) {
3822 Vals.push_back(VE.getMetadataID(DVR.getRawLocation()));
3824 } else {
3825 assert(DVR.isDbgAssign() && "Unexpected DbgRecord kind");
3826 Vals.push_back(VE.getMetadataID(DVR.getRawLocation()));
3827 Vals.push_back(VE.getMetadataID(DVR.getAssignID()));
3829 Vals.push_back(VE.getMetadataID(DVR.getRawAddress()));
3831 }
3832 Vals.clear();
3833 }
3834 }
3835 }
3836
3837 if (BlockAddress *BA = BlockAddress::lookup(&BB)) {
3838 SmallVector<Value *> Worklist{BA};
3839 SmallPtrSet<Value *, 8> Visited{BA};
3840 while (!Worklist.empty()) {
3841 Value *V = Worklist.pop_back_val();
3842 for (User *U : V->users()) {
3843 if (auto *I = dyn_cast<Instruction>(U)) {
3844 Function *P = I->getFunction();
3845 if (P != &F)
3846 BlockAddressUsers.insert(P);
3847 } else if (isa<Constant>(U) && !isa<GlobalValue>(U) &&
3848 Visited.insert(U).second)
3849 Worklist.push_back(U);
3850 }
3851 }
3852 }
3853 }
3854
3855 if (!BlockAddressUsers.empty()) {
3856 Vals.resize(BlockAddressUsers.size());
3857 for (auto I : llvm::enumerate(BlockAddressUsers))
3858 Vals[I.index()] = VE.getValueID(I.value());
3860 Vals.clear();
3861 }
3862
3863 // Emit names for all the instructions etc.
3864 if (auto *Symtab = F.getValueSymbolTable())
3865 writeFunctionLevelValueSymbolTable(*Symtab);
3866
3867 if (NeedsMetadataAttachment)
3868 writeFunctionMetadataAttachment(F);
3870 writeUseListBlock(&F);
3871 VE.purgeFunction();
3872 Stream.ExitBlock();
3873}
3874
3875// Emit blockinfo, which defines the standard abbreviations etc.
3876void ModuleBitcodeWriter::writeBlockInfo() {
3877 // We only want to emit block info records for blocks that have multiple
3878 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
3879 // Other blocks can define their abbrevs inline.
3880 Stream.EnterBlockInfoBlock();
3881
3882 // Encode type indices using fixed size based on number of types.
3885 // Encode value indices as 6-bit VBR.
3886 BitCodeAbbrevOp ValAbbrevOp(BitCodeAbbrevOp::VBR, 6);
3887
3888 { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
3889 auto Abbv = std::make_shared<BitCodeAbbrev>();
3895 VST_ENTRY_8_ABBREV)
3896 llvm_unreachable("Unexpected abbrev ordering!");
3897 }
3898
3899 { // 7-bit fixed width VST_CODE_ENTRY strings.
3900 auto Abbv = std::make_shared<BitCodeAbbrev>();
3906 VST_ENTRY_7_ABBREV)
3907 llvm_unreachable("Unexpected abbrev ordering!");
3908 }
3909 { // 6-bit char6 VST_CODE_ENTRY strings.
3910 auto Abbv = std::make_shared<BitCodeAbbrev>();
3916 VST_ENTRY_6_ABBREV)
3917 llvm_unreachable("Unexpected abbrev ordering!");
3918 }
3919 { // 6-bit char6 VST_CODE_BBENTRY strings.
3920 auto Abbv = std::make_shared<BitCodeAbbrev>();
3926 VST_BBENTRY_6_ABBREV)
3927 llvm_unreachable("Unexpected abbrev ordering!");
3928 }
3929
3930 { // SETTYPE abbrev for CONSTANTS_BLOCK.
3931 auto Abbv = std::make_shared<BitCodeAbbrev>();
3933 Abbv->Add(TypeAbbrevOp);
3935 CONSTANTS_SETTYPE_ABBREV)
3936 llvm_unreachable("Unexpected abbrev ordering!");
3937 }
3938
3939 { // INTEGER abbrev for CONSTANTS_BLOCK.
3940 auto Abbv = std::make_shared<BitCodeAbbrev>();
3944 CONSTANTS_INTEGER_ABBREV)
3945 llvm_unreachable("Unexpected abbrev ordering!");
3946 }
3947
3948 { // CE_CAST abbrev for CONSTANTS_BLOCK.
3949 auto Abbv = std::make_shared<BitCodeAbbrev>();
3951 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
3952 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
3954 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3955
3957 CONSTANTS_CE_CAST_Abbrev)
3958 llvm_unreachable("Unexpected abbrev ordering!");
3959 }
3960 { // NULL abbrev for CONSTANTS_BLOCK.
3961 auto Abbv = std::make_shared<BitCodeAbbrev>();
3964 CONSTANTS_NULL_Abbrev)
3965 llvm_unreachable("Unexpected abbrev ordering!");
3966 }
3967
3968 // FIXME: This should only use space for first class types!
3969
3970 { // INST_LOAD abbrev for FUNCTION_BLOCK.
3971 auto Abbv = std::make_shared<BitCodeAbbrev>();
3973 Abbv->Add(ValAbbrevOp); // Ptr
3974 Abbv->Add(TypeAbbrevOp); // dest ty
3975 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
3976 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
3977 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3978 FUNCTION_INST_LOAD_ABBREV)
3979 llvm_unreachable("Unexpected abbrev ordering!");
3980 }
3981 {
3982 auto Abbv = std::make_shared<BitCodeAbbrev>();
3984 Abbv->Add(ValAbbrevOp); // op1
3985 Abbv->Add(ValAbbrevOp); // op0
3986 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // align
3987 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
3988 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3989 FUNCTION_INST_STORE_ABBREV)
3990 llvm_unreachable("Unexpected abbrev ordering!");
3991 }
3992 { // INST_UNOP abbrev for FUNCTION_BLOCK.
3993 auto Abbv = std::make_shared<BitCodeAbbrev>();
3995 Abbv->Add(ValAbbrevOp); // LHS
3996 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3997 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3998 FUNCTION_INST_UNOP_ABBREV)
3999 llvm_unreachable("Unexpected abbrev ordering!");
4000 }
4001 { // INST_UNOP_FLAGS abbrev for FUNCTION_BLOCK.
4002 auto Abbv = std::make_shared<BitCodeAbbrev>();
4004 Abbv->Add(ValAbbrevOp); // LHS
4005 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
4006 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
4007 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4008 FUNCTION_INST_UNOP_FLAGS_ABBREV)
4009 llvm_unreachable("Unexpected abbrev ordering!");
4010 }
4011 { // INST_BINOP abbrev for FUNCTION_BLOCK.
4012 auto Abbv = std::make_shared<BitCodeAbbrev>();
4014 Abbv->Add(ValAbbrevOp); // LHS
4015 Abbv->Add(ValAbbrevOp); // RHS
4016 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
4017 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4018 FUNCTION_INST_BINOP_ABBREV)
4019 llvm_unreachable("Unexpected abbrev ordering!");
4020 }
4021 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
4022 auto Abbv = std::make_shared<BitCodeAbbrev>();
4024 Abbv->Add(ValAbbrevOp); // LHS
4025 Abbv->Add(ValAbbrevOp); // RHS
4026 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
4027 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
4028 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4029 FUNCTION_INST_BINOP_FLAGS_ABBREV)
4030 llvm_unreachable("Unexpected abbrev ordering!");
4031 }
4032 { // INST_CAST abbrev for FUNCTION_BLOCK.
4033 auto Abbv = std::make_shared<BitCodeAbbrev>();
4035 Abbv->Add(ValAbbrevOp); // OpVal
4036 Abbv->Add(TypeAbbrevOp); // dest ty
4037 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
4038 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4039 FUNCTION_INST_CAST_ABBREV)
4040 llvm_unreachable("Unexpected abbrev ordering!");
4041 }
4042 { // INST_CAST_FLAGS abbrev for FUNCTION_BLOCK.
4043 auto Abbv = std::make_shared<BitCodeAbbrev>();
4045 Abbv->Add(ValAbbrevOp); // OpVal
4046 Abbv->Add(TypeAbbrevOp); // dest ty
4047 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
4048 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
4049 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4050 FUNCTION_INST_CAST_FLAGS_ABBREV)
4051 llvm_unreachable("Unexpected abbrev ordering!");
4052 }
4053
4054 { // INST_RET abbrev for FUNCTION_BLOCK.
4055 auto Abbv = std::make_shared<BitCodeAbbrev>();
4057 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4058 FUNCTION_INST_RET_VOID_ABBREV)
4059 llvm_unreachable("Unexpected abbrev ordering!");
4060 }
4061 { // INST_RET abbrev for FUNCTION_BLOCK.
4062 auto Abbv = std::make_shared<BitCodeAbbrev>();
4064 Abbv->Add(ValAbbrevOp);
4065 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4066 FUNCTION_INST_RET_VAL_ABBREV)
4067 llvm_unreachable("Unexpected abbrev ordering!");
4068 }
4069 {
4070 auto Abbv = std::make_shared<BitCodeAbbrev>();
4072 // TODO: Use different abbrev for absolute value reference (succ0)?
4073 Abbv->Add(ValAbbrevOp); // succ0
4074 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4075 FUNCTION_INST_BR_UNCOND_ABBREV)
4076 llvm_unreachable("Unexpected abbrev ordering!");
4077 }
4078 {
4079 auto Abbv = std::make_shared<BitCodeAbbrev>();
4081 // TODO: Use different abbrev for absolute value references (succ0, succ1)?
4082 Abbv->Add(ValAbbrevOp); // succ0
4083 Abbv->Add(ValAbbrevOp); // succ1
4084 Abbv->Add(ValAbbrevOp); // cond
4085 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4086 FUNCTION_INST_BR_COND_ABBREV)
4087 llvm_unreachable("Unexpected abbrev ordering!");
4088 }
4089 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
4090 auto Abbv = std::make_shared<BitCodeAbbrev>();
4092 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4093 FUNCTION_INST_UNREACHABLE_ABBREV)
4094 llvm_unreachable("Unexpected abbrev ordering!");
4095 }
4096 {
4097 auto Abbv = std::make_shared<BitCodeAbbrev>();
4099 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // flags
4100 Abbv->Add(TypeAbbrevOp); // dest ty
4102 Abbv->Add(ValAbbrevOp);
4103 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4104 FUNCTION_INST_GEP_ABBREV)
4105 llvm_unreachable("Unexpected abbrev ordering!");
4106 }
4107 {
4108 auto Abbv = std::make_shared<BitCodeAbbrev>();
4110 Abbv->Add(ValAbbrevOp); // op0
4111 Abbv->Add(ValAbbrevOp); // op1
4112 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 6)); // pred
4113 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4114 FUNCTION_INST_CMP_ABBREV)
4115 llvm_unreachable("Unexpected abbrev ordering!");
4116 }
4117 {
4118 auto Abbv = std::make_shared<BitCodeAbbrev>();
4120 Abbv->Add(ValAbbrevOp); // op0
4121 Abbv->Add(ValAbbrevOp); // op1
4122 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 6)); // pred
4123 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
4124 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4125 FUNCTION_INST_CMP_FLAGS_ABBREV)
4126 llvm_unreachable("Unexpected abbrev ordering!");
4127 }
4128 {
4129 auto Abbv = std::make_shared<BitCodeAbbrev>();
4131 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // dbgloc
4132 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // var
4133 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // expr
4134 Abbv->Add(ValAbbrevOp); // val
4135 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4136 FUNCTION_DEBUG_RECORD_VALUE_ABBREV)
4137 llvm_unreachable("Unexpected abbrev ordering! 1");
4138 }
4139 {
4140 auto Abbv = std::make_shared<BitCodeAbbrev>();
4142 // NOTE: No IsDistinct field for FUNC_CODE_DEBUG_LOC.
4148 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Atom group.
4149 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3)); // Atom rank.
4150 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4151 FUNCTION_DEBUG_LOC_ABBREV)
4152 llvm_unreachable("Unexpected abbrev ordering!");
4153 }
4154 Stream.ExitBlock();
4155}
4156
4157/// Write the module path strings, currently only used when generating
4158/// a combined index file.
4159void IndexBitcodeWriter::writeModStrings() {
4161
4162 // TODO: See which abbrev sizes we actually need to emit
4163
4164 // 8-bit fixed-width MST_ENTRY strings.
4165 auto Abbv = std::make_shared<BitCodeAbbrev>();
4170 unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
4171
4172 // 7-bit fixed width MST_ENTRY strings.
4173 Abbv = std::make_shared<BitCodeAbbrev>();
4178 unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
4179
4180 // 6-bit char6 MST_ENTRY strings.
4181 Abbv = std::make_shared<BitCodeAbbrev>();
4186 unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
4187
4188 // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
4189 Abbv = std::make_shared<BitCodeAbbrev>();
4196 unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
4197
4199 forEachModule([&](const StringMapEntry<ModuleHash> &MPSE) {
4200 StringRef Key = MPSE.getKey();
4201 const auto &Hash = MPSE.getValue();
4203 unsigned AbbrevToUse = Abbrev8Bit;
4204 if (Bits == SE_Char6)
4205 AbbrevToUse = Abbrev6Bit;
4206 else if (Bits == SE_Fixed7)
4207 AbbrevToUse = Abbrev7Bit;
4208
4209 auto ModuleId = ModuleIdMap.size();
4210 ModuleIdMap[Key] = ModuleId;
4211 Vals.push_back(ModuleId);
4212 Vals.append(Key.begin(), Key.end());
4213
4214 // Emit the finished record.
4215 Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
4216
4217 // Emit an optional hash for the module now
4218 if (llvm::any_of(Hash, [](uint32_t H) { return H; })) {
4219 Vals.assign(Hash.begin(), Hash.end());
4220 // Emit the hash record.
4221 Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
4222 }
4223
4224 Vals.clear();
4225 });
4226 Stream.ExitBlock();
4227}
4228
4229/// Write the function type metadata related records that need to appear before
4230/// a function summary entry (whether per-module or combined).
4231template <typename Fn>
4233 FunctionSummary *FS,
4234 Fn GetValueID) {
4235 if (!FS->type_tests().empty())
4236 Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
4237
4239
4240 auto WriteVFuncIdVec = [&](uint64_t Ty,
4242 if (VFs.empty())
4243 return;
4244 Record.clear();
4245 for (auto &VF : VFs) {
4246 Record.push_back(VF.GUID);
4247 Record.push_back(VF.Offset);
4248 }
4249 Stream.EmitRecord(Ty, Record);
4250 };
4251
4252 WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
4253 FS->type_test_assume_vcalls());
4254 WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
4255 FS->type_checked_load_vcalls());
4256
4257 auto WriteConstVCallVec = [&](uint64_t Ty,
4259 for (auto &VC : VCs) {
4260 Record.clear();
4261 Record.push_back(VC.VFunc.GUID);
4262 Record.push_back(VC.VFunc.Offset);
4263 llvm::append_range(Record, VC.Args);
4264 Stream.EmitRecord(Ty, Record);
4265 }
4266 };
4267
4268 WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
4269 FS->type_test_assume_const_vcalls());
4270 WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
4271 FS->type_checked_load_const_vcalls());
4272
4273 auto WriteRange = [&](ConstantRange Range) {
4275 assert(Range.getLower().getNumWords() == 1);
4276 assert(Range.getUpper().getNumWords() == 1);
4279 };
4280
4281 if (!FS->paramAccesses().empty()) {
4282 Record.clear();
4283 for (auto &Arg : FS->paramAccesses()) {
4284 size_t UndoSize = Record.size();
4285 Record.push_back(Arg.ParamNo);
4286 WriteRange(Arg.Use);
4287 Record.push_back(Arg.Calls.size());
4288 for (auto &Call : Arg.Calls) {
4289 Record.push_back(Call.ParamNo);
4290 std::optional<unsigned> ValueID = GetValueID(Call.Callee);
4291 if (!ValueID) {
4292 // If ValueID is unknown we can't drop just this call, we must drop
4293 // entire parameter.
4294 Record.resize(UndoSize);
4295 break;
4296 }
4297 Record.push_back(*ValueID);
4298 WriteRange(Call.Offsets);
4299 }
4300 }
4301 if (!Record.empty())
4303 }
4304}
4305
4306/// Collect type IDs from type tests used by function.
4307static void
4309 std::set<GlobalValue::GUID> &ReferencedTypeIds) {
4310 if (!FS->type_tests().empty())
4311 for (auto &TT : FS->type_tests())
4312 ReferencedTypeIds.insert(TT);
4313
4314 auto GetReferencedTypesFromVFuncIdVec =
4316 for (auto &VF : VFs)
4317 ReferencedTypeIds.insert(VF.GUID);
4318 };
4319
4320 GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls());
4321 GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls());
4322
4323 auto GetReferencedTypesFromConstVCallVec =
4325 for (auto &VC : VCs)
4326 ReferencedTypeIds.insert(VC.VFunc.GUID);
4327 };
4328
4329 GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls());
4330 GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls());
4331}
4332
4334 SmallVector<uint64_t, 64> &NameVals, const std::vector<uint64_t> &args,
4336 NameVals.push_back(args.size());
4337 llvm::append_range(NameVals, args);
4338
4339 NameVals.push_back(ByArg.TheKind);
4340 NameVals.push_back(ByArg.Info);
4341 NameVals.push_back(ByArg.Byte);
4342 NameVals.push_back(ByArg.Bit);
4343}
4344
4346 SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
4347 uint64_t Id, const WholeProgramDevirtResolution &Wpd) {
4348 NameVals.push_back(Id);
4349
4350 NameVals.push_back(Wpd.TheKind);
4351 NameVals.push_back(StrtabBuilder.add(Wpd.SingleImplName));
4352 NameVals.push_back(Wpd.SingleImplName.size());
4353
4354 NameVals.push_back(Wpd.ResByArg.size());
4355 for (auto &A : Wpd.ResByArg)
4356 writeWholeProgramDevirtResolutionByArg(NameVals, A.first, A.second);
4357}
4358
4360 StringTableBuilder &StrtabBuilder,
4361 StringRef Id,
4362 const TypeIdSummary &Summary) {
4363 NameVals.push_back(StrtabBuilder.add(Id));
4364 NameVals.push_back(Id.size());
4365
4366 NameVals.push_back(Summary.TTRes.TheKind);
4367 NameVals.push_back(Summary.TTRes.SizeM1BitWidth);
4368 NameVals.push_back(Summary.TTRes.AlignLog2);
4369 NameVals.push_back(Summary.TTRes.SizeM1);
4370 NameVals.push_back(Summary.TTRes.BitMask);
4371 NameVals.push_back(Summary.TTRes.InlineBits);
4372
4373 for (auto &W : Summary.WPDRes)
4374 writeWholeProgramDevirtResolution(NameVals, StrtabBuilder, W.first,
4375 W.second);
4376}
4377
4379 SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
4380 StringRef Id, const TypeIdCompatibleVtableInfo &Summary,
4381 ValueEnumerator &VE) {
4382 NameVals.push_back(StrtabBuilder.add(Id));
4383 NameVals.push_back(Id.size());
4384
4385 for (auto &P : Summary) {
4386 NameVals.push_back(P.AddressPointOffset);
4387 NameVals.push_back(VE.getValueID(P.VTableVI.getValue()));
4388 }
4389}
4390
4391// Adds the allocation contexts to the CallStacks map. We simply use the
4392// size at the time the context was added as the CallStackId. This works because
4393// when we look up the call stacks later on we process the function summaries
4394// and their allocation records in the same exact order.
4396 FunctionSummary *FS, std::function<LinearFrameId(unsigned)> GetStackIndex,
4398 // The interfaces in ProfileData/MemProf.h use a type alias for a stack frame
4399 // id offset into the index of the full stack frames. The ModuleSummaryIndex
4400 // currently uses unsigned. Make sure these stay in sync.
4401 static_assert(std::is_same_v<LinearFrameId, unsigned>);
4402 for (auto &AI : FS->allocs()) {
4403 for (auto &MIB : AI.MIBs) {
4404 SmallVector<unsigned> StackIdIndices;
4405 StackIdIndices.reserve(MIB.StackIdIndices.size());
4406 for (auto Id : MIB.StackIdIndices)
4407 StackIdIndices.push_back(GetStackIndex(Id));
4408 // The CallStackId is the size at the time this context was inserted.
4409 CallStacks.insert({CallStacks.size(), StackIdIndices});
4410 }
4411 }
4412}
4413
4414// Build the radix tree from the accumulated CallStacks, write out the resulting
4415// linearized radix tree array, and return the map of call stack positions into
4416// this array for use when writing the allocation records. The returned map is
4417// indexed by a CallStackId which in this case is implicitly determined by the
4418// order of function summaries and their allocation infos being written.
4421 BitstreamWriter &Stream, unsigned RadixAbbrev) {
4422 assert(!CallStacks.empty());
4423 DenseMap<unsigned, FrameStat> FrameHistogram =
4426 // We don't need a MemProfFrameIndexes map as we have already converted the
4427 // full stack id hash to a linear offset into the StackIds array.
4428 Builder.build(std::move(CallStacks), /*MemProfFrameIndexes=*/nullptr,
4429 FrameHistogram);
4431 RadixAbbrev);
4432 return Builder.takeCallStackPos();
4433}
4434
4436 BitstreamWriter &Stream, FunctionSummary *FS, unsigned CallsiteAbbrev,
4437 unsigned AllocAbbrev, unsigned ContextIdAbbvId, bool PerModule,
4438 std::function<unsigned(const ValueInfo &VI)> GetValueID,
4439 std::function<unsigned(unsigned)> GetStackIndex,
4440 bool WriteContextSizeInfoIndex,
4442 CallStackId &CallStackCount) {
4444
4445 for (auto &CI : FS->callsites()) {
4446 Record.clear();
4447 // Per module callsite clones should always have a single entry of
4448 // value 0.
4449 assert(!PerModule || (CI.Clones.size() == 1 && CI.Clones[0] == 0));
4450 Record.push_back(GetValueID(CI.Callee));
4451 if (!PerModule) {
4452 Record.push_back(CI.StackIdIndices.size());
4453 Record.push_back(CI.Clones.size());
4454 }
4455 for (auto Id : CI.StackIdIndices)
4456 Record.push_back(GetStackIndex(Id));
4457 if (!PerModule)
4458 llvm::append_range(Record, CI.Clones);
4461 Record, CallsiteAbbrev);
4462 }
4463
4464 for (auto &AI : FS->allocs()) {
4465 Record.clear();
4466 // Per module alloc versions should always have a single entry of
4467 // value 0.
4468 assert(!PerModule || (AI.Versions.size() == 1 && AI.Versions[0] == 0));
4469 Record.push_back(AI.MIBs.size());
4470 if (!PerModule)
4471 Record.push_back(AI.Versions.size());
4472 for (auto &MIB : AI.MIBs) {
4473 Record.push_back((uint8_t)MIB.AllocType);
4474 // The per-module summary always needs to include the alloc context, as we
4475 // use it during the thin link. For the combined index it is optional (see
4476 // comments where CombinedIndexMemProfContext is defined).
4477 if (PerModule || CombinedIndexMemProfContext) {
4478 // Record the index into the radix tree array for this context.
4479 assert(CallStackCount <= CallStackPos.size());
4480 Record.push_back(CallStackPos[CallStackCount++]);
4481 }
4482 }
4483 if (!PerModule)
4484 llvm::append_range(Record, AI.Versions);
4485 assert(AI.ContextSizeInfos.empty() ||
4486 AI.ContextSizeInfos.size() == AI.MIBs.size());
4487 // Optionally emit the context size information if it exists.
4488 if (WriteContextSizeInfoIndex && !AI.ContextSizeInfos.empty()) {
4489 // The abbreviation id for the context ids record should have been created
4490 // if we are emitting the per-module index, which is where we write this
4491 // info.
4492 assert(ContextIdAbbvId);
4493 SmallVector<uint32_t> ContextIds;
4494 // At least one context id per ContextSizeInfos entry (MIB), broken into 2
4495 // halves.
4496 ContextIds.reserve(AI.ContextSizeInfos.size() * 2);
4497 for (auto &Infos : AI.ContextSizeInfos) {
4498 Record.push_back(Infos.size());
4499 for (auto [FullStackId, TotalSize] : Infos) {
4500 // The context ids are emitted separately as a fixed width array,
4501 // which is more efficient than a VBR given that these hashes are
4502 // typically close to 64-bits. The max fixed width entry is 32 bits so
4503 // it is split into 2.
4504 ContextIds.push_back(static_cast<uint32_t>(FullStackId >> 32));
4505 ContextIds.push_back(static_cast<uint32_t>(FullStackId));
4506 Record.push_back(TotalSize);
4507 }
4508 }
4509 // The context ids are expected by the reader to immediately precede the
4510 // associated alloc info record.
4511 Stream.EmitRecord(bitc::FS_ALLOC_CONTEXT_IDS, ContextIds,
4512 ContextIdAbbvId);
4513 }
4514 Stream.EmitRecord(PerModule
4519 Record, AllocAbbrev);
4520 }
4521}
4522
4523// Helper to emit a single function summary record.
4524void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
4526 unsigned ValueID, unsigned FSCallsRelBFAbbrev,
4527 unsigned FSCallsProfileAbbrev, unsigned CallsiteAbbrev,
4528 unsigned AllocAbbrev, unsigned ContextIdAbbvId, const Function &F,
4530 CallStackId &CallStackCount) {
4531 NameVals.push_back(ValueID);
4532
4533 FunctionSummary *FS = cast<FunctionSummary>(Summary);
4534
4536 Stream, FS, [&](const ValueInfo &VI) -> std::optional<unsigned> {
4537 return {VE.getValueID(VI.getValue())};
4538 });
4539
4541 Stream, FS, CallsiteAbbrev, AllocAbbrev, ContextIdAbbvId,
4542 /*PerModule*/ true,
4543 /*GetValueId*/ [&](const ValueInfo &VI) { return getValueId(VI); },
4544 /*GetStackIndex*/ [&](unsigned I) { return I; },
4545 /*WriteContextSizeInfoIndex*/ true, CallStackPos, CallStackCount);
4546
4547 auto SpecialRefCnts = FS->specialRefCounts();
4548 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
4549 NameVals.push_back(FS->instCount());
4550 NameVals.push_back(getEncodedFFlags(FS->fflags()));
4551 NameVals.push_back(FS->refs().size());
4552 NameVals.push_back(SpecialRefCnts.first); // rorefcnt
4553 NameVals.push_back(SpecialRefCnts.second); // worefcnt
4554
4555 for (auto &RI : FS->refs())
4556 NameVals.push_back(getValueId(RI));
4557
4558 const bool UseRelBFRecord =
4559 WriteRelBFToSummary && !F.hasProfileData() &&
4561 for (auto &ECI : FS->calls()) {
4562 NameVals.push_back(getValueId(ECI.first));
4563 if (UseRelBFRecord)
4564 NameVals.push_back(getEncodedRelBFCallEdgeInfo(ECI.second));
4565 else
4566 NameVals.push_back(getEncodedHotnessCallEdgeInfo(ECI.second));
4567 }
4568
4569 unsigned FSAbbrev =
4570 (UseRelBFRecord ? FSCallsRelBFAbbrev : FSCallsProfileAbbrev);
4571 unsigned Code =
4573
4574 // Emit the finished record.
4575 Stream.EmitRecord(Code, NameVals, FSAbbrev);
4576 NameVals.clear();
4577}
4578
4579// Collect the global value references in the given variable's initializer,
4580// and emit them in a summary record.
4581void ModuleBitcodeWriterBase::writeModuleLevelReferences(
4582 const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
4583 unsigned FSModRefsAbbrev, unsigned FSModVTableRefsAbbrev) {
4584 auto VI = Index->getValueInfo(V.getGUID());
4585 if (!VI || VI.getSummaryList().empty()) {
4586 // Only declarations should not have a summary (a declaration might however
4587 // have a summary if the def was in module level asm).
4588 assert(V.isDeclaration());
4589 return;
4590 }
4591 auto *Summary = VI.getSummaryList()[0].get();
4592 NameVals.push_back(VE.getValueID(&V));
4593 GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
4594 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
4595 NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
4596
4597 auto VTableFuncs = VS->vTableFuncs();
4598 if (!VTableFuncs.empty())
4599 NameVals.push_back(VS->refs().size());
4600
4601 unsigned SizeBeforeRefs = NameVals.size();
4602 for (auto &RI : VS->refs())
4603 NameVals.push_back(VE.getValueID(RI.getValue()));
4604 // Sort the refs for determinism output, the vector returned by FS->refs() has
4605 // been initialized from a DenseSet.
4606 llvm::sort(drop_begin(NameVals, SizeBeforeRefs));
4607
4608 if (VTableFuncs.empty())
4610 FSModRefsAbbrev);
4611 else {
4612 // VTableFuncs pairs should already be sorted by offset.
4613 for (auto &P : VTableFuncs) {
4614 NameVals.push_back(VE.getValueID(P.FuncVI.getValue()));
4615 NameVals.push_back(P.VTableOffset);
4616 }
4617
4619 FSModVTableRefsAbbrev);
4620 }
4621 NameVals.clear();
4622}
4623
4624/// Emit the per-module summary section alongside the rest of
4625/// the module's bitcode.
4626void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
4627 // By default we compile with ThinLTO if the module has a summary, but the
4628 // client can request full LTO with a module flag.
4629 bool IsThinLTO = true;
4630 if (auto *MD =
4631 mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
4632 IsThinLTO = MD->getZExtValue();
4635 4);
4636
4637 Stream.EmitRecord(
4640
4641 // Write the index flags.
4642 uint64_t Flags = 0;
4643 // Bits 1-3 are set only in the combined index, skip them.
4644 if (Index->enableSplitLTOUnit())
4645 Flags |= 0x8;
4646 if (Index->hasUnifiedLTO())
4647 Flags |= 0x200;
4648
4650
4651 if (Index->begin() == Index->end()) {
4652 Stream.ExitBlock();
4653 return;
4654 }
4655
4656 auto Abbv = std::make_shared<BitCodeAbbrev>();
4659 // GUIDS often use up most of 64-bits, so encode as two Fixed 32.
4662 unsigned ValueGuidAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4663
4664 for (const auto &GVI : valueIds()) {
4666 ArrayRef<uint32_t>{GVI.second,
4667 static_cast<uint32_t>(GVI.first >> 32),
4668 static_cast<uint32_t>(GVI.first)},
4669 ValueGuidAbbrev);
4670 }
4671
4672 if (!Index->stackIds().empty()) {
4673 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
4674 StackIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_STACK_IDS));
4675 // numids x stackid
4676 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4677 // The stack ids are hashes that are close to 64 bits in size, so emitting
4678 // as a pair of 32-bit fixed-width values is more efficient than a VBR.
4679 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4680 unsigned StackIdAbbvId = Stream.EmitAbbrev(std::move(StackIdAbbv));
4682 Vals.reserve(Index->stackIds().size() * 2);
4683 for (auto Id : Index->stackIds()) {
4684 Vals.push_back(static_cast<uint32_t>(Id >> 32));
4685 Vals.push_back(static_cast<uint32_t>(Id));
4686 }
4687 Stream.EmitRecord(bitc::FS_STACK_IDS, Vals, StackIdAbbvId);
4688 }
4689
4690 unsigned ContextIdAbbvId = 0;
4692 // n x context id
4693 auto ContextIdAbbv = std::make_shared<BitCodeAbbrev>();
4694 ContextIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_ALLOC_CONTEXT_IDS));
4695 ContextIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4696 // The context ids are hashes that are close to 64 bits in size, so emitting
4697 // as a pair of 32-bit fixed-width values is more efficient than a VBR if we
4698 // are emitting them for all MIBs. Otherwise we use VBR to better compress 0
4699 // values that are expected to more frequently occur in an alloc's memprof
4700 // summary.
4702 ContextIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4703 else
4704 ContextIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4705 ContextIdAbbvId = Stream.EmitAbbrev(std::move(ContextIdAbbv));
4706 }
4707
4708 // Abbrev for FS_PERMODULE_PROFILE.
4709 Abbv = std::make_shared<BitCodeAbbrev>();
4711 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4712 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // flags
4713 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
4714 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
4715 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4716 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
4717 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
4718 // numrefs x valueid, n x (valueid, hotness+tailcall flags)
4721 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4722
4723 // Abbrev for FS_PERMODULE_RELBF.
4724 Abbv = std::make_shared<BitCodeAbbrev>();
4726 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4727 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4728 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
4729 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
4730 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4731 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
4732 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
4733 // numrefs x valueid, n x (valueid, rel_block_freq+tailcall])
4736 unsigned FSCallsRelBFAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4737
4738 // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
4739 Abbv = std::make_shared<BitCodeAbbrev>();
4741 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4742 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4743 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
4745 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4746
4747 // Abbrev for FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS.
4748 Abbv = std::make_shared<BitCodeAbbrev>();
4750 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4751 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4752 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4753 // numrefs x valueid, n x (valueid , offset)
4756 unsigned FSModVTableRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4757
4758 // Abbrev for FS_ALIAS.
4759 Abbv = std::make_shared<BitCodeAbbrev>();
4760 Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
4761 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4762 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4763 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4764 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4765
4766 // Abbrev for FS_TYPE_ID_METADATA
4767 Abbv = std::make_shared<BitCodeAbbrev>();
4769 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid strtab index
4770 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid length
4771 // n x (valueid , offset)
4774 unsigned TypeIdCompatibleVtableAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4775
4776 Abbv = std::make_shared<BitCodeAbbrev>();
4778 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4779 // n x stackidindex
4782 unsigned CallsiteAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4783
4784 Abbv = std::make_shared<BitCodeAbbrev>();
4786 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // nummib
4787 // n x (alloc type, context radix tree index)
4788 // optional: nummib x (numcontext x total size)
4791 unsigned AllocAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4792
4793 Abbv = std::make_shared<BitCodeAbbrev>();
4795 // n x entry
4798 unsigned RadixAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4799
4800 // First walk through all the functions and collect the allocation contexts in
4801 // their associated summaries, for use in constructing a radix tree of
4802 // contexts. Note that we need to do this in the same order as the functions
4803 // are processed further below since the call stack positions in the resulting
4804 // radix tree array are identified based on this order.
4806 for (const Function &F : M) {
4807 // Summary emission does not support anonymous functions, they have to be
4808 // renamed using the anonymous function renaming pass.
4809 if (!F.hasName())
4810 report_fatal_error("Unexpected anonymous function when writing summary");
4811
4812 ValueInfo VI = Index->getValueInfo(F.getGUID());
4813 if (!VI || VI.getSummaryList().empty()) {
4814 // Only declarations should not have a summary (a declaration might
4815 // however have a summary if the def was in module level asm).
4816 assert(F.isDeclaration());
4817 continue;
4818 }
4819 auto *Summary = VI.getSummaryList()[0].get();
4820 FunctionSummary *FS = cast<FunctionSummary>(Summary);
4822 FS, /*GetStackIndex*/ [](unsigned I) { return I; }, CallStacks);
4823 }
4824 // Finalize the radix tree, write it out, and get the map of positions in the
4825 // linearized tree array.
4827 if (!CallStacks.empty()) {
4828 CallStackPos =
4829 writeMemoryProfileRadixTree(std::move(CallStacks), Stream, RadixAbbrev);
4830 }
4831
4832 // Keep track of the current index into the CallStackPos map.
4833 CallStackId CallStackCount = 0;
4834
4836 // Iterate over the list of functions instead of the Index to
4837 // ensure the ordering is stable.
4838 for (const Function &F : M) {
4839 // Summary emission does not support anonymous functions, they have to
4840 // renamed using the anonymous function renaming pass.
4841 if (!F.hasName())
4842 report_fatal_error("Unexpected anonymous function when writing summary");
4843
4844 ValueInfo VI = Index->getValueInfo(F.getGUID());
4845 if (!VI || VI.getSummaryList().empty()) {
4846 // Only declarations should not have a summary (a declaration might
4847 // however have a summary if the def was in module level asm).
4848 assert(F.isDeclaration());
4849 continue;
4850 }
4851 auto *Summary = VI.getSummaryList()[0].get();
4852 writePerModuleFunctionSummaryRecord(
4853 NameVals, Summary, VE.getValueID(&F), FSCallsRelBFAbbrev,
4854 FSCallsProfileAbbrev, CallsiteAbbrev, AllocAbbrev, ContextIdAbbvId, F,
4855 CallStackPos, CallStackCount);
4856 }
4857
4858 // Capture references from GlobalVariable initializers, which are outside
4859 // of a function scope.
4860 for (const GlobalVariable &G : M.globals())
4861 writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev,
4862 FSModVTableRefsAbbrev);
4863
4864 for (const GlobalAlias &A : M.aliases()) {
4865 auto *Aliasee = A.getAliaseeObject();
4866 // Skip ifunc and nameless functions which don't have an entry in the
4867 // summary.
4868 if (!Aliasee->hasName() || isa<GlobalIFunc>(Aliasee))
4869 continue;
4870 auto AliasId = VE.getValueID(&A);
4871 auto AliaseeId = VE.getValueID(Aliasee);
4872 NameVals.push_back(AliasId);
4873 auto *Summary = Index->getGlobalValueSummary(A);
4874 AliasSummary *AS = cast<AliasSummary>(Summary);
4875 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
4876 NameVals.push_back(AliaseeId);
4877 Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
4878 NameVals.clear();
4879 }
4880
4881 for (auto &S : Index->typeIdCompatibleVtableMap()) {
4882 writeTypeIdCompatibleVtableSummaryRecord(NameVals, StrtabBuilder, S.first,
4883 S.second, VE);
4884 Stream.EmitRecord(bitc::FS_TYPE_ID_METADATA, NameVals,
4885 TypeIdCompatibleVtableAbbrev);
4886 NameVals.clear();
4887 }
4888
4889 if (Index->getBlockCount())
4891 ArrayRef<uint64_t>{Index->getBlockCount()});
4892
4893 Stream.ExitBlock();
4894}
4895
4896/// Emit the combined summary section into the combined index file.
4897void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
4899 Stream.EmitRecord(
4902
4903 // Write the index flags.
4905
4906 auto Abbv = std::make_shared<BitCodeAbbrev>();
4909 // GUIDS often use up most of 64-bits, so encode as two Fixed 32.
4912 unsigned ValueGuidAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4913
4914 for (const auto &GVI : valueIds()) {
4916 ArrayRef<uint32_t>{GVI.second,
4917 static_cast<uint32_t>(GVI.first >> 32),
4918 static_cast<uint32_t>(GVI.first)},
4919 ValueGuidAbbrev);
4920 }
4921
4922 // Write the stack ids used by this index, which will be a subset of those in
4923 // the full index in the case of distributed indexes.
4924 if (!StackIds.empty()) {
4925 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
4926 StackIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_STACK_IDS));
4927 // numids x stackid
4928 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4929 // The stack ids are hashes that are close to 64 bits in size, so emitting
4930 // as a pair of 32-bit fixed-width values is more efficient than a VBR.
4931 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4932 unsigned StackIdAbbvId = Stream.EmitAbbrev(std::move(StackIdAbbv));
4934 Vals.reserve(StackIds.size() * 2);
4935 for (auto Id : StackIds) {
4936 Vals.push_back(static_cast<uint32_t>(Id >> 32));
4937 Vals.push_back(static_cast<uint32_t>(Id));
4938 }
4939 Stream.EmitRecord(bitc::FS_STACK_IDS, Vals, StackIdAbbvId);
4940 }
4941
4942 // Abbrev for FS_COMBINED_PROFILE.
4943 Abbv = std::make_shared<BitCodeAbbrev>();
4945 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4946 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
4947 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4948 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
4949 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
4950 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // entrycount
4951 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4952 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
4953 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
4954 // numrefs x valueid, n x (valueid, hotness+tailcall flags)
4957 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4958
4959 // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
4960 Abbv = std::make_shared<BitCodeAbbrev>();
4962 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4963 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
4964 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4965 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
4967 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4968
4969 // Abbrev for FS_COMBINED_ALIAS.
4970 Abbv = std::make_shared<BitCodeAbbrev>();
4972 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4973 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
4974 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4975 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4976 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4977
4978 Abbv = std::make_shared<BitCodeAbbrev>();
4980 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4981 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numstackindices
4982 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numver
4983 // numstackindices x stackidindex, numver x version
4986 unsigned CallsiteAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4987
4988 Abbv = std::make_shared<BitCodeAbbrev>();
4992 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // nummib
4993 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numver
4994 // nummib x (alloc type, context radix tree index),
4995 // numver x version
4996 // optional: nummib x total size
4999 unsigned AllocAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5000
5001 auto shouldImportValueAsDecl = [&](GlobalValueSummary *GVS) -> bool {
5002 if (DecSummaries == nullptr)
5003 return false;
5004 return DecSummaries->count(GVS);
5005 };
5006
5007 // The aliases are emitted as a post-pass, and will point to the value
5008 // id of the aliasee. Save them in a vector for post-processing.
5010
5011 // Save the value id for each summary for alias emission.
5013
5015
5016 // Set that will be populated during call to writeFunctionTypeMetadataRecords
5017 // with the type ids referenced by this index file.
5018 std::set<GlobalValue::GUID> ReferencedTypeIds;
5019
5020 // For local linkage, we also emit the original name separately
5021 // immediately after the record.
5022 auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
5023 // We don't need to emit the original name if we are writing the index for
5024 // distributed backends (in which case ModuleToSummariesForIndex is
5025 // non-null). The original name is only needed during the thin link, since
5026 // for SamplePGO the indirect call targets for local functions have
5027 // have the original name annotated in profile.
5028 // Continue to emit it when writing out the entire combined index, which is
5029 // used in testing the thin link via llvm-lto.
5030 if (ModuleToSummariesForIndex || !GlobalValue::isLocalLinkage(S.linkage()))
5031 return;
5032 NameVals.push_back(S.getOriginalName());
5034 NameVals.clear();
5035 };
5036
5039 Abbv = std::make_shared<BitCodeAbbrev>();
5041 // n x entry
5044 unsigned RadixAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5045
5046 // First walk through all the functions and collect the allocation contexts
5047 // in their associated summaries, for use in constructing a radix tree of
5048 // contexts. Note that we need to do this in the same order as the functions
5049 // are processed further below since the call stack positions in the
5050 // resulting radix tree array are identified based on this order.
5052 forEachSummary([&](GVInfo I, bool IsAliasee) {
5053 // Don't collect this when invoked for an aliasee, as it is not needed for
5054 // the alias summary. If the aliasee is to be imported, we will invoke
5055 // this separately with IsAliasee=false.
5056 if (IsAliasee)
5057 return;
5058 GlobalValueSummary *S = I.second;
5059 assert(S);
5060 auto *FS = dyn_cast<FunctionSummary>(S);
5061 if (!FS)
5062 return;
5064 FS,
5065 /*GetStackIndex*/
5066 [&](unsigned I) {
5067 // Get the corresponding index into the list of StackIds actually
5068 // being written for this combined index (which may be a subset in
5069 // the case of distributed indexes).
5070 assert(StackIdIndicesToIndex.contains(I));
5071 return StackIdIndicesToIndex[I];
5072 },
5073 CallStacks);
5074 });
5075 // Finalize the radix tree, write it out, and get the map of positions in
5076 // the linearized tree array.
5077 if (!CallStacks.empty()) {
5078 CallStackPos = writeMemoryProfileRadixTree(std::move(CallStacks), Stream,
5079 RadixAbbrev);
5080 }
5081 }
5082
5083 // Keep track of the current index into the CallStackPos map. Not used if
5084 // CombinedIndexMemProfContext is false.
5085 CallStackId CallStackCount = 0;
5086
5087 DenseSet<GlobalValue::GUID> DefOrUseGUIDs;
5088 forEachSummary([&](GVInfo I, bool IsAliasee) {
5089 GlobalValueSummary *S = I.second;
5090 assert(S);
5091 DefOrUseGUIDs.insert(I.first);
5092 for (const ValueInfo &VI : S->refs())
5093 DefOrUseGUIDs.insert(VI.getGUID());
5094
5095 auto ValueId = getValueId(I.first);
5096 assert(ValueId);
5097 SummaryToValueIdMap[S] = *ValueId;
5098
5099 // If this is invoked for an aliasee, we want to record the above
5100 // mapping, but then not emit a summary entry (if the aliasee is
5101 // to be imported, we will invoke this separately with IsAliasee=false).
5102 if (IsAliasee)
5103 return;
5104
5105 if (auto *AS = dyn_cast<AliasSummary>(S)) {
5106 // Will process aliases as a post-pass because the reader wants all
5107 // global to be loaded first.
5108 Aliases.push_back(AS);
5109 return;
5110 }
5111
5112 if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
5113 NameVals.push_back(*ValueId);
5114 assert(ModuleIdMap.count(VS->modulePath()));
5115 NameVals.push_back(ModuleIdMap[VS->modulePath()]);
5116 NameVals.push_back(
5117 getEncodedGVSummaryFlags(VS->flags(), shouldImportValueAsDecl(VS)));
5118 NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
5119 for (auto &RI : VS->refs()) {
5120 auto RefValueId = getValueId(RI.getGUID());
5121 if (!RefValueId)
5122 continue;
5123 NameVals.push_back(*RefValueId);
5124 }
5125
5126 // Emit the finished record.
5128 FSModRefsAbbrev);
5129 NameVals.clear();
5130 MaybeEmitOriginalName(*S);
5131 return;
5132 }
5133
5134 auto GetValueId = [&](const ValueInfo &VI) -> std::optional<unsigned> {
5135 if (!VI)
5136 return std::nullopt;
5137 return getValueId(VI.getGUID());
5138 };
5139
5140 auto *FS = cast<FunctionSummary>(S);
5141 writeFunctionTypeMetadataRecords(Stream, FS, GetValueId);
5142 getReferencedTypeIds(FS, ReferencedTypeIds);
5143
5145 Stream, FS, CallsiteAbbrev, AllocAbbrev, /*ContextIdAbbvId*/ 0,
5146 /*PerModule*/ false,
5147 /*GetValueId*/
5148 [&](const ValueInfo &VI) -> unsigned {
5149 std::optional<unsigned> ValueID = GetValueId(VI);
5150 // This can happen in shared index files for distributed ThinLTO if
5151 // the callee function summary is not included. Record 0 which we
5152 // will have to deal with conservatively when doing any kind of
5153 // validation in the ThinLTO backends.
5154 if (!ValueID)
5155 return 0;
5156 return *ValueID;
5157 },
5158 /*GetStackIndex*/
5159 [&](unsigned I) {
5160 // Get the corresponding index into the list of StackIds actually
5161 // being written for this combined index (which may be a subset in
5162 // the case of distributed indexes).
5163 assert(StackIdIndicesToIndex.contains(I));
5164 return StackIdIndicesToIndex[I];
5165 },
5166 /*WriteContextSizeInfoIndex*/ false, CallStackPos, CallStackCount);
5167
5168 NameVals.push_back(*ValueId);
5169 assert(ModuleIdMap.count(FS->modulePath()));
5170 NameVals.push_back(ModuleIdMap[FS->modulePath()]);
5171 NameVals.push_back(
5172 getEncodedGVSummaryFlags(FS->flags(), shouldImportValueAsDecl(FS)));
5173 NameVals.push_back(FS->instCount());
5174 NameVals.push_back(getEncodedFFlags(FS->fflags()));
5175 // TODO: Stop writing entry count and bump bitcode version.
5176 NameVals.push_back(0 /* EntryCount */);
5177
5178 // Fill in below
5179 NameVals.push_back(0); // numrefs
5180 NameVals.push_back(0); // rorefcnt
5181 NameVals.push_back(0); // worefcnt
5182
5183 unsigned Count = 0, RORefCnt = 0, WORefCnt = 0;
5184 for (auto &RI : FS->refs()) {
5185 auto RefValueId = getValueId(RI.getGUID());
5186 if (!RefValueId)
5187 continue;
5188 NameVals.push_back(*RefValueId);
5189 if (RI.isReadOnly())
5190 RORefCnt++;
5191 else if (RI.isWriteOnly())
5192 WORefCnt++;
5193 Count++;
5194 }
5195 NameVals[6] = Count;
5196 NameVals[7] = RORefCnt;
5197 NameVals[8] = WORefCnt;
5198
5199 for (auto &EI : FS->calls()) {
5200 // If this GUID doesn't have a value id, it doesn't have a function
5201 // summary and we don't need to record any calls to it.
5202 std::optional<unsigned> CallValueId = GetValueId(EI.first);
5203 if (!CallValueId)
5204 continue;
5205 NameVals.push_back(*CallValueId);
5206 NameVals.push_back(getEncodedHotnessCallEdgeInfo(EI.second));
5207 }
5208
5209 // Emit the finished record.
5210 Stream.EmitRecord(bitc::FS_COMBINED_PROFILE, NameVals,
5211 FSCallsProfileAbbrev);
5212 NameVals.clear();
5213 MaybeEmitOriginalName(*S);
5214 });
5215
5216 for (auto *AS : Aliases) {
5217 auto AliasValueId = SummaryToValueIdMap[AS];
5218 assert(AliasValueId);
5219 NameVals.push_back(AliasValueId);
5220 assert(ModuleIdMap.count(AS->modulePath()));
5221 NameVals.push_back(ModuleIdMap[AS->modulePath()]);
5222 NameVals.push_back(
5223 getEncodedGVSummaryFlags(AS->flags(), shouldImportValueAsDecl(AS)));
5224 auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()];
5225 assert(AliaseeValueId);
5226 NameVals.push_back(AliaseeValueId);
5227
5228 // Emit the finished record.
5229 Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
5230 NameVals.clear();
5231 MaybeEmitOriginalName(*AS);
5232
5233 if (auto *FS = dyn_cast<FunctionSummary>(&AS->getAliasee()))
5234 getReferencedTypeIds(FS, ReferencedTypeIds);
5235 }
5236
5237 SmallVector<StringRef, 4> Functions;
5238 auto EmitCfiFunctions = [&](const CfiFunctionIndex &CfiIndex,
5240 if (CfiIndex.empty())
5241 return;
5242 for (GlobalValue::GUID GUID : DefOrUseGUIDs) {
5243 auto Defs = CfiIndex.forGuid(GUID);
5244 llvm::append_range(Functions, Defs);
5245 }
5246 if (Functions.empty())
5247 return;
5248 llvm::sort(Functions);
5249 for (const auto &S : Functions) {
5250 NameVals.push_back(StrtabBuilder.add(S));
5251 NameVals.push_back(S.size());
5252 }
5253 Stream.EmitRecord(Code, NameVals);
5254 NameVals.clear();
5255 Functions.clear();
5256 };
5257
5258 EmitCfiFunctions(Index.cfiFunctionDefs(), bitc::FS_CFI_FUNCTION_DEFS);
5259 EmitCfiFunctions(Index.cfiFunctionDecls(), bitc::FS_CFI_FUNCTION_DECLS);
5260
5261 // Walk the GUIDs that were referenced, and write the
5262 // corresponding type id records.
5263 for (auto &T : ReferencedTypeIds) {
5264 auto TidIter = Index.typeIds().equal_range(T);
5265 for (const auto &[GUID, TypeIdPair] : make_range(TidIter)) {
5266 writeTypeIdSummaryRecord(NameVals, StrtabBuilder, TypeIdPair.first,
5267 TypeIdPair.second);
5268 Stream.EmitRecord(bitc::FS_TYPE_ID, NameVals);
5269 NameVals.clear();
5270 }
5271 }
5272
5273 if (Index.getBlockCount())
5275 ArrayRef<uint64_t>{Index.getBlockCount()});
5276
5277 Stream.ExitBlock();
5278}
5279
5280/// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
5281/// current llvm version, and a record for the epoch number.
5284
5285 // Write the "user readable" string identifying the bitcode producer
5286 auto Abbv = std::make_shared<BitCodeAbbrev>();
5290 auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5292 "LLVM" LLVM_VERSION_STRING, StringAbbrev);
5293
5294 // Write the epoch version
5295 Abbv = std::make_shared<BitCodeAbbrev>();
5298 auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5299 constexpr std::array<unsigned, 1> Vals = {{bitc::BITCODE_CURRENT_EPOCH}};
5300 Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
5301 Stream.ExitBlock();
5302}
5303
5304void ModuleBitcodeWriter::writeModuleHash(StringRef View) {
5305 // Emit the module's hash.
5306 // MODULE_CODE_HASH: [5*i32]
5307 if (GenerateHash) {
5308 uint32_t Vals[5];
5309 Hasher.update(ArrayRef<uint8_t>(
5310 reinterpret_cast<const uint8_t *>(View.data()), View.size()));
5311 std::array<uint8_t, 20> Hash = Hasher.result();
5312 for (int Pos = 0; Pos < 20; Pos += 4) {
5313 Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);
5314 }
5315
5316 // Emit the finished record.
5317 Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
5318
5319 if (ModHash)
5320 // Save the written hash value.
5321 llvm::copy(Vals, std::begin(*ModHash));
5322 }
5323}
5324
5325void ModuleBitcodeWriter::write() {
5327
5329 // We will want to write the module hash at this point. Block any flushing so
5330 // we can have access to the whole underlying data later.
5331 Stream.markAndBlockFlushing();
5332
5333 writeModuleVersion();
5334
5335 // Emit blockinfo, which defines the standard abbreviations etc.
5336 writeBlockInfo();
5337
5338 // Emit information describing all of the types in the module.
5339 writeTypeTable();
5340
5341 // Emit information about attribute groups.
5342 writeAttributeGroupTable();
5343
5344 // Emit information about parameter attributes.
5345 writeAttributeTable();
5346
5347 writeComdats();
5348
5349 // Emit top-level description of module, including target triple, inline asm,
5350 // descriptors for global variables, and function prototype info.
5351 writeModuleInfo();
5352
5353 // Emit constants.
5354 writeModuleConstants();
5355
5356 // Emit metadata kind names.
5357 writeModuleMetadataKinds();
5358
5359 // Emit metadata.
5360 writeModuleMetadata();
5361
5362 // Emit module-level use-lists.
5364 writeUseListBlock(nullptr);
5365
5366 writeOperandBundleTags();
5367 writeSyncScopeNames();
5368
5369 // Emit function bodies.
5370 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
5371 for (const Function &F : M)
5372 if (!F.isDeclaration())
5373 writeFunction(F, FunctionToBitcodeIndex);
5374
5375 // Need to write after the above call to WriteFunction which populates
5376 // the summary information in the index.
5377 if (Index)
5378 writePerModuleGlobalValueSummary();
5379
5380 writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
5381
5382 writeModuleHash(Stream.getMarkedBufferAndResumeFlushing());
5383
5384 Stream.ExitBlock();
5385}
5386
5388 uint32_t &Position) {
5389 support::endian::write32le(&Buffer[Position], Value);
5390 Position += 4;
5391}
5392
5393/// If generating a bc file on darwin, we have to emit a
5394/// header and trailer to make it compatible with the system archiver. To do
5395/// this we emit the following header, and then emit a trailer that pads the
5396/// file out to be a multiple of 16 bytes.
5397///
5398/// struct bc_header {
5399/// uint32_t Magic; // 0x0B17C0DE
5400/// uint32_t Version; // Version, currently always 0.
5401/// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
5402/// uint32_t BitcodeSize; // Size of traditional bitcode file.
5403/// uint32_t CPUType; // CPU specifier.
5404/// ... potentially more later ...
5405/// };
5407 const Triple &TT) {
5408 unsigned CPUType = ~0U;
5409
5410 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
5411 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
5412 // number from /usr/include/mach/machine.h. It is ok to reproduce the
5413 // specific constants here because they are implicitly part of the Darwin ABI.
5414 enum {
5415 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
5416 DARWIN_CPU_TYPE_X86 = 7,
5417 DARWIN_CPU_TYPE_ARM = 12,
5418 DARWIN_CPU_TYPE_POWERPC = 18
5419 };
5420
5421 Triple::ArchType Arch = TT.getArch();
5422 if (Arch == Triple::x86_64)
5423 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
5424 else if (Arch == Triple::x86)
5425 CPUType = DARWIN_CPU_TYPE_X86;
5426 else if (Arch == Triple::ppc)
5427 CPUType = DARWIN_CPU_TYPE_POWERPC;
5428 else if (Arch == Triple::ppc64)
5429 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
5430 else if (Arch == Triple::arm || Arch == Triple::thumb)
5431 CPUType = DARWIN_CPU_TYPE_ARM;
5432
5433 // Traditional Bitcode starts after header.
5434 assert(Buffer.size() >= BWH_HeaderSize &&
5435 "Expected header size to be reserved");
5436 unsigned BCOffset = BWH_HeaderSize;
5437 unsigned BCSize = Buffer.size() - BWH_HeaderSize;
5438
5439 // Write the magic and version.
5440 unsigned Position = 0;
5441 writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
5442 writeInt32ToBuffer(0, Buffer, Position); // Version.
5443 writeInt32ToBuffer(BCOffset, Buffer, Position);
5444 writeInt32ToBuffer(BCSize, Buffer, Position);
5445 writeInt32ToBuffer(CPUType, Buffer, Position);
5446
5447 // If the file is not a multiple of 16 bytes, insert dummy padding.
5448 while (Buffer.size() & 15)
5449 Buffer.push_back(0);
5450}
5451
5452/// Helper to write the header common to all bitcode files.
5454 // Emit the file header.
5455 Stream.Emit((unsigned)'B', 8);
5456 Stream.Emit((unsigned)'C', 8);
5457 Stream.Emit(0x0, 4);
5458 Stream.Emit(0xC, 4);
5459 Stream.Emit(0xE, 4);
5460 Stream.Emit(0xD, 4);
5461}
5462
5464 : Stream(new BitstreamWriter(Buffer)) {
5465 writeBitcodeHeader(*Stream);
5466}
5467
5469 : Stream(new BitstreamWriter(FS, FlushThreshold)) {
5470 writeBitcodeHeader(*Stream);
5471}
5472
5474
5475void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) {
5476 Stream->EnterSubblock(Block, 3);
5477
5478 auto Abbv = std::make_shared<BitCodeAbbrev>();
5479 Abbv->Add(BitCodeAbbrevOp(Record));
5481 auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv));
5482
5483 Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob);
5484
5485 Stream->ExitBlock();
5486}
5487
5489 assert(!WroteStrtab && !WroteSymtab);
5490
5491 // If any module has module-level inline asm, we will require a registered asm
5492 // parser for the target so that we can create an accurate symbol table for
5493 // the module.
5494 for (Module *M : Mods) {
5495 if (M->getModuleInlineAsm().empty())
5496 continue;
5497
5498 std::string Err;
5499 const Triple TT(M->getTargetTriple());
5500 const Target *T = TargetRegistry::lookupTarget(TT, Err);
5501 if (!T || !T->hasMCAsmParser())
5502 return;
5503 }
5504
5505 WroteSymtab = true;
5506 SmallVector<char, 0> Symtab;
5507 // The irsymtab::build function may be unable to create a symbol table if the
5508 // module is malformed (e.g. it contains an invalid alias). Writing a symbol
5509 // table is not required for correctness, but we still want to be able to
5510 // write malformed modules to bitcode files, so swallow the error.
5511 if (Error E = irsymtab::build(Mods, Symtab, StrtabBuilder, Alloc)) {
5512 consumeError(std::move(E));
5513 return;
5514 }
5515
5517 {Symtab.data(), Symtab.size()});
5518}
5519
5521 assert(!WroteStrtab);
5522
5523 std::vector<char> Strtab;
5524 StrtabBuilder.finalizeInOrder();
5525 Strtab.resize(StrtabBuilder.getSize());
5526 StrtabBuilder.write((uint8_t *)Strtab.data());
5527
5529 {Strtab.data(), Strtab.size()});
5530
5531 WroteStrtab = true;
5532}
5533
5535 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab);
5536 WroteStrtab = true;
5537}
5538
5540 bool ShouldPreserveUseListOrder,
5541 const ModuleSummaryIndex *Index,
5542 bool GenerateHash, ModuleHash *ModHash) {
5543 assert(!WroteStrtab);
5544
5545 // The Mods vector is used by irsymtab::build, which requires non-const
5546 // Modules in case it needs to materialize metadata. But the bitcode writer
5547 // requires that the module is materialized, so we can cast to non-const here,
5548 // after checking that it is in fact materialized.
5549 assert(M.isMaterialized());
5550 Mods.push_back(const_cast<Module *>(&M));
5551
5552 ModuleBitcodeWriter ModuleWriter(M, StrtabBuilder, *Stream,
5553 ShouldPreserveUseListOrder, Index,
5554 GenerateHash, ModHash);
5555 ModuleWriter.write();
5556}
5557
5559 const ModuleSummaryIndex *Index,
5560 const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex,
5561 const GVSummaryPtrSet *DecSummaries) {
5562 IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index, DecSummaries,
5563 ModuleToSummariesForIndex);
5564 IndexWriter.write();
5565}
5566
5567/// Write the specified module to the specified output stream.
5569 bool ShouldPreserveUseListOrder,
5570 const ModuleSummaryIndex *Index,
5571 bool GenerateHash, ModuleHash *ModHash) {
5572 auto Write = [&](BitcodeWriter &Writer) {
5573 Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
5574 ModHash);
5575 Writer.writeSymtab();
5576 Writer.writeStrtab();
5577 };
5578 Triple TT(M.getTargetTriple());
5579 if (TT.isOSDarwin() || TT.isOSBinFormatMachO()) {
5580 // If this is darwin or another generic macho target, reserve space for the
5581 // header. Note that the header is computed *after* the output is known, so
5582 // we currently explicitly use a buffer, write to it, and then subsequently
5583 // flush to Out.
5584 SmallVector<char, 0> Buffer;
5585 Buffer.reserve(256 * 1024);
5586 Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
5587 BitcodeWriter Writer(Buffer);
5588 Write(Writer);
5589 emitDarwinBCHeaderAndTrailer(Buffer, TT);
5590 Out.write(Buffer.data(), Buffer.size());
5591 } else {
5592 BitcodeWriter Writer(Out);
5593 Write(Writer);
5594 }
5595}
5596
5597void IndexBitcodeWriter::write() {
5599
5600 writeModuleVersion();
5601
5602 // Write the module paths in the combined index.
5603 writeModStrings();
5604
5605 // Write the summary combined index records.
5606 writeCombinedGlobalValueSummary();
5607
5608 Stream.ExitBlock();
5609}
5610
5611// Write the specified module summary index to the given raw output stream,
5612// where it will be written in a new bitcode block. This is used when
5613// writing the combined index file for ThinLTO. When writing a subset of the
5614// index for a distributed backend, provide a \p ModuleToSummariesForIndex map.
5616 const ModuleSummaryIndex &Index, raw_ostream &Out,
5617 const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex,
5618 const GVSummaryPtrSet *DecSummaries) {
5619 SmallVector<char, 0> Buffer;
5620 Buffer.reserve(256 * 1024);
5621
5622 BitcodeWriter Writer(Buffer);
5623 Writer.writeIndex(&Index, ModuleToSummariesForIndex, DecSummaries);
5624 Writer.writeStrtab();
5625
5626 Out.write((char *)&Buffer.front(), Buffer.size());
5627}
5628
5629namespace {
5630
5631/// Class to manage the bitcode writing for a thin link bitcode file.
5632class ThinLinkBitcodeWriter : public ModuleBitcodeWriterBase {
5633 /// ModHash is for use in ThinLTO incremental build, generated while writing
5634 /// the module bitcode file.
5635 const ModuleHash *ModHash;
5636
5637public:
5638 ThinLinkBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder,
5639 BitstreamWriter &Stream,
5641 const ModuleHash &ModHash)
5642 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
5643 /*ShouldPreserveUseListOrder=*/false, &Index),
5644 ModHash(&ModHash) {}
5645
5646 void write();
5647
5648private:
5649 void writeSimplifiedModuleInfo();
5650};
5651
5652} // end anonymous namespace
5653
5654// This function writes a simpilified module info for thin link bitcode file.
5655// It only contains the source file name along with the name(the offset and
5656// size in strtab) and linkage for global values. For the global value info
5657// entry, in order to keep linkage at offset 5, there are three zeros used
5658// as padding.
5659void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {
5661 // Emit the module's source file name.
5662 {
5663 StringEncoding Bits = getStringEncoding(M.getSourceFileName());
5665 if (Bits == SE_Char6)
5666 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
5667 else if (Bits == SE_Fixed7)
5668 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
5669
5670 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
5671 auto Abbv = std::make_shared<BitCodeAbbrev>();
5674 Abbv->Add(AbbrevOpToUse);
5675 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5676
5677 for (const auto P : M.getSourceFileName())
5678 Vals.push_back((unsigned char)P);
5679
5680 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
5681 Vals.clear();
5682 }
5683
5684 // Emit the global variable information.
5685 for (const GlobalVariable &GV : M.globals()) {
5686 // GLOBALVAR: [strtab offset, strtab size, 0, 0, 0, linkage]
5687 Vals.push_back(StrtabBuilder.add(GV.getName()));
5688 Vals.push_back(GV.getName().size());
5689 Vals.push_back(0);
5690 Vals.push_back(0);
5691 Vals.push_back(0);
5692 Vals.push_back(getEncodedLinkage(GV));
5693
5695 Vals.clear();
5696 }
5697
5698 // Emit the function proto information.
5699 for (const Function &F : M) {
5700 // FUNCTION: [strtab offset, strtab size, 0, 0, 0, linkage]
5701 Vals.push_back(StrtabBuilder.add(F.getName()));
5702 Vals.push_back(F.getName().size());
5703 Vals.push_back(0);
5704 Vals.push_back(0);
5705 Vals.push_back(0);
5707
5709 Vals.clear();
5710 }
5711
5712 // Emit the alias information.
5713 for (const GlobalAlias &A : M.aliases()) {
5714 // ALIAS: [strtab offset, strtab size, 0, 0, 0, linkage]
5715 Vals.push_back(StrtabBuilder.add(A.getName()));
5716 Vals.push_back(A.getName().size());
5717 Vals.push_back(0);
5718 Vals.push_back(0);
5719 Vals.push_back(0);
5721
5722 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals);
5723 Vals.clear();
5724 }
5725
5726 // Emit the ifunc information.
5727 for (const GlobalIFunc &I : M.ifuncs()) {
5728 // IFUNC: [strtab offset, strtab size, 0, 0, 0, linkage]
5729 Vals.push_back(StrtabBuilder.add(I.getName()));
5730 Vals.push_back(I.getName().size());
5731 Vals.push_back(0);
5732 Vals.push_back(0);
5733 Vals.push_back(0);
5735
5736 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
5737 Vals.clear();
5738 }
5739}
5740
5741void ThinLinkBitcodeWriter::write() {
5743
5744 writeModuleVersion();
5745
5746 writeSimplifiedModuleInfo();
5747
5748 writePerModuleGlobalValueSummary();
5749
5750 // Write module hash.
5752
5753 Stream.ExitBlock();
5754}
5755
5757 const ModuleSummaryIndex &Index,
5758 const ModuleHash &ModHash) {
5759 assert(!WroteStrtab);
5760
5761 // The Mods vector is used by irsymtab::build, which requires non-const
5762 // Modules in case it needs to materialize metadata. But the bitcode writer
5763 // requires that the module is materialized, so we can cast to non-const here,
5764 // after checking that it is in fact materialized.
5765 assert(M.isMaterialized());
5766 Mods.push_back(const_cast<Module *>(&M));
5767
5768 ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index,
5769 ModHash);
5770 ThinLinkWriter.write();
5771}
5772
5773// Write the specified thin link bitcode file to the given raw output stream,
5774// where it will be written in a new bitcode block. This is used when
5775// writing the per-module index file for ThinLTO.
5777 const ModuleSummaryIndex &Index,
5778 const ModuleHash &ModHash) {
5779 SmallVector<char, 0> Buffer;
5780 Buffer.reserve(256 * 1024);
5781
5782 BitcodeWriter Writer(Buffer);
5783 Writer.writeThinLinkBitcode(M, Index, ModHash);
5784 Writer.writeSymtab();
5785 Writer.writeStrtab();
5786
5787 Out.write((char *)&Buffer.front(), Buffer.size());
5788}
5789
5790static const char *getSectionNameForBitcode(const Triple &T) {
5791 switch (T.getObjectFormat()) {
5792 case Triple::MachO:
5793 return "__LLVM,__bitcode";
5794 case Triple::COFF:
5795 case Triple::ELF:
5796 case Triple::Wasm:
5798 return ".llvmbc";
5799 case Triple::GOFF:
5800 llvm_unreachable("GOFF is not yet implemented");
5801 break;
5802 case Triple::SPIRV:
5803 if (T.getVendor() == Triple::AMD)
5804 return ".llvmbc";
5805 llvm_unreachable("SPIRV is not yet implemented");
5806 break;
5807 case Triple::XCOFF:
5808 llvm_unreachable("XCOFF is not yet implemented");
5809 break;
5811 llvm_unreachable("DXContainer is not yet implemented");
5812 break;
5813 }
5814 llvm_unreachable("Unimplemented ObjectFormatType");
5815}
5816
5817static const char *getSectionNameForCommandline(const Triple &T) {
5818 switch (T.getObjectFormat()) {
5819 case Triple::MachO:
5820 return "__LLVM,__cmdline";
5821 case Triple::COFF:
5822 case Triple::ELF:
5823 case Triple::Wasm:
5825 return ".llvmcmd";
5826 case Triple::GOFF:
5827 llvm_unreachable("GOFF is not yet implemented");
5828 break;
5829 case Triple::SPIRV:
5830 if (T.getVendor() == Triple::AMD)
5831 return ".llvmcmd";
5832 llvm_unreachable("SPIRV is not yet implemented");
5833 break;
5834 case Triple::XCOFF:
5835 llvm_unreachable("XCOFF is not yet implemented");
5836 break;
5838 llvm_unreachable("DXC is not yet implemented");
5839 break;
5840 }
5841 llvm_unreachable("Unimplemented ObjectFormatType");
5842}
5843
5845 bool EmbedBitcode, bool EmbedCmdline,
5846 const std::vector<uint8_t> &CmdArgs) {
5847 // Save llvm.compiler.used and remove it.
5850 GlobalVariable *Used = collectUsedGlobalVariables(M, UsedGlobals, true);
5851 Type *UsedElementType = Used ? Used->getValueType()->getArrayElementType()
5852 : PointerType::getUnqual(M.getContext());
5853 for (auto *GV : UsedGlobals) {
5854 if (GV->getName() != "llvm.embedded.module" &&
5855 GV->getName() != "llvm.cmdline")
5856 UsedArray.push_back(
5858 }
5859 if (Used)
5860 Used->eraseFromParent();
5861
5862 // Embed the bitcode for the llvm module.
5863 std::string Data;
5864 ArrayRef<uint8_t> ModuleData;
5865 Triple T(M.getTargetTriple());
5866
5867 if (EmbedBitcode) {
5868 if (Buf.getBufferSize() == 0 ||
5869 !isBitcode((const unsigned char *)Buf.getBufferStart(),
5870 (const unsigned char *)Buf.getBufferEnd())) {
5871 // If the input is LLVM Assembly, bitcode is produced by serializing
5872 // the module. Use-lists order need to be preserved in this case.
5874 llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true);
5875 ModuleData =
5876 ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
5877 } else
5878 // If the input is LLVM bitcode, write the input byte stream directly.
5879 ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
5880 Buf.getBufferSize());
5881 }
5882 llvm::Constant *ModuleConstant =
5883 llvm::ConstantDataArray::get(M.getContext(), ModuleData);
5885 M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
5886 ModuleConstant);
5888 // Set alignment to 1 to prevent padding between two contributions from input
5889 // sections after linking.
5890 GV->setAlignment(Align(1));
5891 UsedArray.push_back(
5893 if (llvm::GlobalVariable *Old =
5894 M.getGlobalVariable("llvm.embedded.module", true)) {
5895 assert(Old->hasZeroLiveUses() &&
5896 "llvm.embedded.module can only be used once in llvm.compiler.used");
5897 GV->takeName(Old);
5898 Old->eraseFromParent();
5899 } else {
5900 GV->setName("llvm.embedded.module");
5901 }
5902
5903 // Skip if only bitcode needs to be embedded.
5904 if (EmbedCmdline) {
5905 // Embed command-line options.
5906 ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CmdArgs.data()),
5907 CmdArgs.size());
5908 llvm::Constant *CmdConstant =
5909 llvm::ConstantDataArray::get(M.getContext(), CmdData);
5910 GV = new llvm::GlobalVariable(M, CmdConstant->getType(), true,
5912 CmdConstant);
5914 GV->setAlignment(Align(1));
5915 UsedArray.push_back(
5917 if (llvm::GlobalVariable *Old = M.getGlobalVariable("llvm.cmdline", true)) {
5918 assert(Old->hasZeroLiveUses() &&
5919 "llvm.cmdline can only be used once in llvm.compiler.used");
5920 GV->takeName(Old);
5921 Old->eraseFromParent();
5922 } else {
5923 GV->setName("llvm.cmdline");
5924 }
5925 }
5926
5927 if (UsedArray.empty())
5928 return;
5929
5930 // Recreate llvm.compiler.used.
5931 ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
5932 auto *NewUsed = new GlobalVariable(
5934 llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
5935 NewUsed->setSection("llvm.metadata");
5936}
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)
Definition: AsmWriter.cpp:2514
static void writeDIGlobalVariableExpression(raw_ostream &Out, const DIGlobalVariableExpression *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2666
static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2341
static void writeDIFixedPointType(raw_ostream &Out, const DIFixedPointType *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2247
static void writeDISubrangeType(raw_ostream &Out, const DISubrangeType *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2321
static void writeDIStringType(raw_ostream &Out, const DIStringType *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2270
static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2575
static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2231
static void writeDIModule(raw_ostream &Out, const DIModule *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2535
static void writeDIFile(raw_ostream &Out, const DIFile *N, AsmWriterContext &)
Definition: AsmWriter.cpp:2394
static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2383
static void writeDILabel(raw_ostream &Out, const DILabel *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2610
static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2288
static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2690
static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2676
static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2440
static void writeDILocation(raw_ostream &Out, const DILocation *DL, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2125
static void writeDINamespace(raw_ostream &Out, const DINamespace *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2492
static void writeDICommonBlock(raw_ostream &Out, const DICommonBlock *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2502
static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2107
static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2594
static void writeDITemplateTypeParameter(raw_ostream &Out, const DITemplateTypeParameter *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2550
static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2410
static void writeDIGenericSubrange(raw_ostream &Out, const DIGenericSubrange *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2171
static void writeDISubrange(raw_ostream &Out, const DISubrange *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2147
static void writeDILexicalBlockFile(raw_ostream &Out, const DILexicalBlockFile *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2480
static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N, AsmWriterContext &)
Definition: AsmWriter.cpp:2219
static void writeMDTuple(raw_ostream &Out, const MDTuple *Node, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:1863
static void writeDIExpression(raw_ostream &Out, const DIExpression *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2626
static void writeDIAssignID(raw_ostream &Out, const DIAssignID *DL, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2141
static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2469
static void writeDIArgList(raw_ostream &Out, const DIArgList *N, AsmWriterContext &WriterCtx, bool FromValue=false)
Definition: AsmWriter.cpp:2651
static void writeDITemplateValueParameter(raw_ostream &Out, const DITemplateValueParameter *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2561
static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2525
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")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
This file defines the DenseMap class.
This file contains constants used for implementing Dwarf debug support.
std::string Name
uint32_t Index
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
Hexagon Common GEP
#define _
static MaybeAlign getAlign(Value *Ptr)
Definition: IRBuilder.cpp:442
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
This file contains the declarations for metadata subclasses.
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)
This file contains some templates that are useful if you are working with the STL at all.
raw_pwrite_stream & OS
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 getNumWords() const
Get the number of words.
Definition: APInt.h:1495
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
Alias summary information.
const GlobalValueSummary & getAliasee() const
an instruction to allocate memory on the stack
Definition: Instructions.h:64
bool isSwiftError() const
Return true if this alloca is used as a swifterror argument to a call.
Definition: Instructions.h:153
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
Definition: Instructions.h:128
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
Definition: Instructions.h:121
bool isUsedWithInAlloca() const
Return true if this alloca is used as an inalloca argument to a call.
Definition: Instructions.h:143
unsigned getAddressSpace() const
Return the address space for the allocation.
Definition: Instructions.h:106
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.
Definition: DerivedTypes.h:398
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.
Definition: Instructions.h:721
@ Add
*p = old + v
Definition: Instructions.h:725
@ FAdd
*p = old + v
Definition: Instructions.h:746
@ USubCond
Subtract only if no unsigned overflow.
Definition: Instructions.h:777
@ FMinimum
*p = minimum(old, v) minimum matches the behavior of llvm.minimum.
Definition: Instructions.h:765
@ Min
*p = old <signed v ? old : v
Definition: Instructions.h:739
@ Or
*p = old | v
Definition: Instructions.h:733
@ Sub
*p = old - v
Definition: Instructions.h:727
@ And
*p = old & v
Definition: Instructions.h:729
@ Xor
*p = old ^ v
Definition: Instructions.h:735
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
Definition: Instructions.h:781
@ FMaximum
*p = maximum(old, v) maximum matches the behavior of llvm.maximum.
Definition: Instructions.h:761
@ FSub
*p = old - v
Definition: Instructions.h:749
@ UIncWrap
Increment one up to a maximum value.
Definition: Instructions.h:769
@ Max
*p = old >signed v ? old : v
Definition: Instructions.h:737
@ UMin
*p = old <unsigned v ? old : v
Definition: Instructions.h:743
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
Definition: Instructions.h:757
@ UMax
*p = old >unsigned v ? old : v
Definition: Instructions.h:741
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
Definition: Instructions.h:753
@ UDecWrap
Decrement one until a minimum value or zero.
Definition: Instructions.h:773
@ Nand
*p = ~(old & v)
Definition: Instructions.h:731
bool hasAttributes() const
Return true if attributes exists in this set.
Definition: Attributes.h:427
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
LLVM Basic Block Representation.
Definition: BasicBlock.h:62
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.
The address of a basic block.
Definition: Constants.h:899
static LLVM_ABI BlockAddress * lookup(const BasicBlock *BB)
Lookup an existing BlockAddress constant for the given BasicBlock.
Definition: Constants.cpp:1922
Conditional or Unconditional Branch instruction.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Definition: InstrTypes.h:1116
OperandBundleUse getOperandBundleAt(unsigned Index) const
Return the operand bundle at a specific index.
Definition: InstrTypes.h:2052
unsigned getNumOperandBundles() const
Return the number of operand bundles associated with this User.
Definition: InstrTypes.h:1996
CallingConv::ID getCallingConv() const
Definition: InstrTypes.h:1406
Value * getCalledOperand() const
Definition: InstrTypes.h:1340
Value * getArgOperand(unsigned i) const
Definition: InstrTypes.h:1292
FunctionType * getFunctionType() const
Definition: InstrTypes.h:1205
unsigned arg_size() const
Definition: InstrTypes.h:1290
AttributeList getAttributes() const
Return the attributes for this call.
Definition: InstrTypes.h:1424
bool hasOperandBundles() const
Return true if this User has any operand bundles.
Definition: InstrTypes.h:2001
CallBr instruction, tracking function calls that may not return control but instead transfer it to a ...
BasicBlock * getIndirectDest(unsigned i) const
BasicBlock * getDefaultDest() const
unsigned getNumIndirectDests() const
Return the number of callbr indirect dest labels.
This class represents a function call, abstracting a target machine's calling convention.
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)
Definition: Constants.cpp:1314
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
ConstantDataSequential - A vector or array constant whose element type is a simple 1/2/4/8-byte integ...
Definition: Constants.h:593
A constant value that is initialized with an expression using other constant values.
Definition: Constants.h:1120
static LLVM_ABI Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
Definition: Constants.cpp:2261
ConstantFP - Floating Point Values [float, double].
Definition: Constants.h:277
This is the shared class of boolean and integer constants.
Definition: Constants.h:87
This class represents a range of values.
Definition: ConstantRange.h:47
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.
LLVM_ABI ConstantRange sextOrTrunc(uint32_t BitWidth) const
Make this range have the bit width given by BitWidth.
This is an important base class in LLVM.
Definition: Constant.h:43
List of ValueAsMetadata, to be used as an argument to a dbg.value intrinsic.
Assignment ID.
Basic type, like 'int' or 'float'.
Debug common block.
Enumeration value.
DWARF expression.
A pair of DIGlobalVariable and DIExpression.
An imported module (C++ using directive or similar).
Debug lexical block.
Debug location.
Represents a module in the programming language, for example, a Clang module, or a Fortran module.
Debug lexical block.
String type, Fortran CHARACTER(n)
Subprogram description. Uses SubclassData1.
Array subrange.
Type array for a subprogram.
This class represents an Operation in the Expression.
Records a position in IR for a source label (DILabel).
Base class for non-instruction debug metadata records that have positions within IR.
DebugLoc getDebugLoc() const
Record of a variable value-assignment, aka a non instruction representation of the dbg....
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:120
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:173
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition: DenseMap.h:168
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:230
Implements a dense probed hash-table based set.
Definition: DenseSet.h:263
Lightweight error class with error context and mandatory checking.
Definition: Error.h:159
This instruction extracts a struct member or array element value from an aggregate value.
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.
Generic tagged DWARF-like metadata node.
LLVM_ABI void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode * > > &MDs) const
Appends all metadata attached to this value to MDs, sorting by KindID.
Definition: Metadata.cpp:1561
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
Definition: Globals.cpp:275
Function and variable summary information to aid decisions and implementation of importing.
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
Definition: GlobalValue.h:250
static bool isLocalLinkage(LinkageTypes Linkage)
Definition: GlobalValue.h:411
LinkageTypes getLinkage() const
Definition: GlobalValue.h:548
ThreadLocalMode getThreadLocalMode() const
Definition: GlobalValue.h:273
@ 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
Definition: GlobalValue.h:230
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
Definition: GlobalValue.h:277
Global variable summary information to aid decisions and implementation of importing.
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
This instruction inserts a struct field of array element value into an aggregate value.
idx_iterator idx_end() const
idx_iterator idx_begin() const
bool isCast() const
Definition: Instruction.h:321
Invoke instruction.
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:68
The landingpad instruction holds all of the information necessary to generate correct exception handl...
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.
Metadata node.
Definition: Metadata.h:1077
Tracking metadata reference owned by Metadata.
Definition: Metadata.h:899
Tuple of metadata.
Definition: Metadata.h:1493
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:75
size_t getBufferSize() const
const char * getBufferStart() const
const char * getBufferEnd() const
Root of the metadata hierarchy.
Definition: Metadata.h:63
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
A tuple of MDNodes.
Definition: Metadata.h:1753
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...
Definition: DerivedTypes.h:720
A class that wrap the SHA1 algorithm.
Definition: SHA1.h:27
size_type size() const
Determine the number of elements in the SetVector.
Definition: SetVector.h:104
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:168
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:541
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:356
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
void append(StringRef RHS)
Append from a StringRef.
Definition: SmallString.h:68
bool empty() const
Definition: SmallVector.h:82
size_t size() const
Definition: SmallVector.h:79
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:574
void assign(size_type NumElts, ValueParamT Elt)
Definition: SmallVector.h:705
void reserve(size_type N)
Definition: SmallVector.h:664
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:684
iterator insert(iterator I, T &&Elt)
Definition: SmallVector.h:806
void resize(size_type N)
Definition: SmallVector.h:639
void push_back(const T &Elt)
Definition: SmallVector.h:414
pointer data()
Return a pointer to the vector's buffer, even if empty().
Definition: SmallVector.h:287
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1197
const ValueTy & getValue() const
StringMapEntry - This is used to represent one value that is inserted into a StringMap.
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:151
iterator begin() const
Definition: StringRef.h:120
constexpr size_t size() const
size - Get the string size.
Definition: StringRef.h:154
iterator end() const
Definition: StringRef.h:122
Utility for building string tables with deduplicated suffixes.
LLVM_ABI void finalizeInOrder()
Finalize the string table without reording it.
LLVM_ABI size_t add(CachedHashStringRef S, uint8_t Priority=0)
Add a string to the builder.
LLVM_ABI void write(raw_ostream &OS) const
Class to represent struct types.
Definition: DerivedTypes.h:218
Multiway switch.
Class to represent target extensions types, which are generally unintrospectable from target-independ...
Definition: DerivedTypes.h:781
Target - Wrapper for Target specific information.
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:47
@ DXContainer
Definition: Triple.h:318
@ UnknownObjectFormat
Definition: Triple.h:315
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
@ X86_AMXTyID
AMX vectors (8192 bits, X86 specific)
Definition: Type.h:66
@ FunctionTyID
Functions.
Definition: Type.h:71
@ ArrayTyID
Arrays.
Definition: Type.h:74
@ TypedPointerTyID
Typed pointer used by some GPU targets.
Definition: Type.h:77
@ HalfTyID
16-bit floating point type
Definition: Type.h:56
@ TargetExtTyID
Target extension type.
Definition: Type.h:78
@ VoidTyID
type with no size
Definition: Type.h:63
@ ScalableVectorTyID
Scalable SIMD vector type.
Definition: Type.h:76
@ LabelTyID
Labels.
Definition: Type.h:64
@ FloatTyID
32-bit floating point type
Definition: Type.h:58
@ StructTyID
Structures.
Definition: Type.h:73
@ IntegerTyID
Arbitrary bit width integers.
Definition: Type.h:70
@ FixedVectorTyID
Fixed width SIMD vector type.
Definition: Type.h:75
@ BFloatTyID
16-bit floating point type (7-bit significand)
Definition: Type.h:57
@ DoubleTyID
64-bit floating point type
Definition: Type.h:59
@ X86_FP80TyID
80-bit floating point type (X87)
Definition: Type.h:60
@ PPC_FP128TyID
128-bit floating point type (two 64-bits, PowerPC)
Definition: Type.h:62
@ MetadataTyID
Metadata.
Definition: Type.h:65
@ TokenTyID
Tokens.
Definition: Type.h:67
@ PointerTyID
Pointers.
Definition: Type.h:72
@ FP128TyID
128-bit floating point type (112-bit significand)
Definition: Type.h:61
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
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
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition: Type.h:352
Value wrapper in the Metadata hierarchy.
Definition: Metadata.h:457
Value * getValue() const
Definition: Metadata.h:497
unsigned getTypeID(Type *T) const
unsigned getMetadataID(const Metadata *MD) const
UseListOrderStack UseListOrders
std::vector< std::pair< const Value *, unsigned > > ValueList
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
This class provides a symbol table of name/value pairs.
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:1098
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:194
void build(llvm::MapVector< CallStackId, llvm::SmallVector< FrameIdTy > > &&MemProfCallStackData, const llvm::DenseMap< FrameIdTy, LinearFrameId > *MemProfFrameIndexes, llvm::DenseMap< FrameIdTy, FrameStat > &FrameHistogram)
ArrayRef< LinearFrameId > getRadixArray() const
llvm::DenseMap< CallStackId, LinearCallStackId > takeCallStackPos()
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.
Definition: raw_ostream.h:662
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.
Key
PAL metadata keys.
@ Entry
Definition: COFF.h:862
@ 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.
Definition: PPCPredicates.h:87
@ CE
Windows NT (Windows on ARM)
@ FS
Definition: X86.h:214
@ TYPE_CODE_METADATA
Definition: LLVMBitCodes.h:162
@ TYPE_CODE_PPC_FP128
Definition: LLVMBitCodes.h:160
@ TYPE_CODE_TARGET_TYPE
Definition: LLVMBitCodes.h:179
@ TYPE_CODE_STRUCT_ANON
Definition: LLVMBitCodes.h:166
@ TYPE_CODE_STRUCT_NAME
Definition: LLVMBitCodes.h:167
@ TYPE_CODE_X86_FP80
Definition: LLVMBitCodes.h:158
@ TYPE_CODE_OPAQUE_POINTER
Definition: LLVMBitCodes.h:177
@ TYPE_CODE_FUNCTION
Definition: LLVMBitCodes.h:170
@ TYPE_CODE_NUMENTRY
Definition: LLVMBitCodes.h:136
@ TYPE_CODE_STRUCT_NAMED
Definition: LLVMBitCodes.h:168
@ METADATA_NAMESPACE
Definition: LLVMBitCodes.h:369
@ METADATA_COMMON_BLOCK
Definition: LLVMBitCodes.h:389
@ METADATA_STRING_TYPE
Definition: LLVMBitCodes.h:386
@ METADATA_MACRO_FILE
Definition: LLVMBitCodes.h:379
@ METADATA_TEMPLATE_VALUE
Definition: LLVMBitCodes.h:371
@ METADATA_LEXICAL_BLOCK_FILE
Definition: LLVMBitCodes.h:368
@ METADATA_INDEX_OFFSET
Definition: LLVMBitCodes.h:383
@ METADATA_LEXICAL_BLOCK
Definition: LLVMBitCodes.h:367
@ METADATA_SUBPROGRAM
Definition: LLVMBitCodes.h:366
@ METADATA_SUBROUTINE_TYPE
Definition: LLVMBitCodes.h:364
@ METADATA_GLOBAL_DECL_ATTACHMENT
Definition: LLVMBitCodes.h:381
@ METADATA_LOCAL_VAR
Definition: LLVMBitCodes.h:373
@ METADATA_GLOBAL_VAR
Definition: LLVMBitCodes.h:372
@ METADATA_EXPRESSION
Definition: LLVMBitCodes.h:374
@ METADATA_ATTACHMENT
Definition: LLVMBitCodes.h:356
@ METADATA_OBJC_PROPERTY
Definition: LLVMBitCodes.h:375
@ METADATA_NAMED_NODE
Definition: LLVMBitCodes.h:355
@ METADATA_IMPORTED_ENTITY
Definition: LLVMBitCodes.h:376
@ METADATA_GENERIC_SUBRANGE
Definition: LLVMBitCodes.h:390
@ METADATA_ASSIGN_ID
Definition: LLVMBitCodes.h:392
@ METADATA_COMPILE_UNIT
Definition: LLVMBitCodes.h:365
@ METADATA_COMPOSITE_TYPE
Definition: LLVMBitCodes.h:363
@ METADATA_FIXED_POINT_TYPE
Definition: LLVMBitCodes.h:394
@ METADATA_ENUMERATOR
Definition: LLVMBitCodes.h:359
@ METADATA_DERIVED_TYPE
Definition: LLVMBitCodes.h:362
@ METADATA_SUBRANGE_TYPE
Definition: LLVMBitCodes.h:393
@ METADATA_TEMPLATE_TYPE
Definition: LLVMBitCodes.h:370
@ METADATA_GLOBAL_VAR_EXPR
Definition: LLVMBitCodes.h:382
@ METADATA_BASIC_TYPE
Definition: LLVMBitCodes.h:360
@ METADATA_DISTINCT_NODE
Definition: LLVMBitCodes.h:350
@ METADATA_GENERIC_DEBUG
Definition: LLVMBitCodes.h:357
GlobalValueSummarySymtabCodes
Definition: LLVMBitCodes.h:207
@ FS_CONTEXT_RADIX_TREE_ARRAY
Definition: LLVMBitCodes.h:337
@ FS_CFI_FUNCTION_DEFS
Definition: LLVMBitCodes.h:263
@ FS_PERMODULE_RELBF
Definition: LLVMBitCodes.h:272
@ FS_COMBINED_GLOBALVAR_INIT_REFS
Definition: LLVMBitCodes.h:225
@ FS_TYPE_CHECKED_LOAD_VCALLS
Definition: LLVMBitCodes.h:247
@ FS_COMBINED_PROFILE
Definition: LLVMBitCodes.h:223
@ FS_ALLOC_CONTEXT_IDS
Definition: LLVMBitCodes.h:333
@ FS_COMBINED_ORIGINAL_NAME
Definition: LLVMBitCodes.h:231
@ FS_TYPE_ID_METADATA
Definition: LLVMBitCodes.h:294
@ FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS
Definition: LLVMBitCodes.h:300
@ FS_TYPE_TEST_ASSUME_CONST_VCALL
Definition: LLVMBitCodes.h:251
@ FS_PERMODULE_GLOBALVAR_INIT_REFS
Definition: LLVMBitCodes.h:216
@ FS_TYPE_TEST_ASSUME_VCALLS
Definition: LLVMBitCodes.h:242
@ FS_COMBINED_ALLOC_INFO_NO_CONTEXT
Definition: LLVMBitCodes.h:342
@ FS_CFI_FUNCTION_DECLS
Definition: LLVMBitCodes.h:267
@ FS_COMBINED_CALLSITE_INFO
Definition: LLVMBitCodes.h:316
@ FS_COMBINED_ALLOC_INFO
Definition: LLVMBitCodes.h:321
@ FS_PERMODULE_PROFILE
Definition: LLVMBitCodes.h:214
@ FS_PERMODULE_CALLSITE_INFO
Definition: LLVMBitCodes.h:308
@ FS_PERMODULE_ALLOC_INFO
Definition: LLVMBitCodes.h:312
@ FS_TYPE_CHECKED_LOAD_CONST_VCALL
Definition: LLVMBitCodes.h:255
@ IDENTIFICATION_CODE_EPOCH
Definition: LLVMBitCodes.h:72
@ IDENTIFICATION_CODE_STRING
Definition: LLVMBitCodes.h:71
@ CST_CODE_BLOCKADDRESS
Definition: LLVMBitCodes.h:421
@ CST_CODE_NO_CFI_VALUE
Definition: LLVMBitCodes.h:432
@ CST_CODE_CE_SHUFVEC_EX
Definition: LLVMBitCodes.h:419
@ CST_CODE_CE_EXTRACTELT
Definition: LLVMBitCodes.h:413
@ CST_CODE_CE_SHUFFLEVEC
Definition: LLVMBitCodes.h:415
@ CST_CODE_WIDE_INTEGER
Definition: LLVMBitCodes.h:404
@ CST_CODE_DSO_LOCAL_EQUIVALENT
Definition: LLVMBitCodes.h:428
@ CST_CODE_AGGREGATE
Definition: LLVMBitCodes.h:406
@ CST_CODE_CE_INSERTELT
Definition: LLVMBitCodes.h:414
@ CST_CODE_CE_GEP_WITH_INRANGE
Definition: LLVMBitCodes.h:437
@ CST_CODE_INLINEASM
Definition: LLVMBitCodes.h:433
@ CALL_EXPLICIT_TYPE
Definition: LLVMBitCodes.h:588
@ COMDAT_SELECTION_KIND_LARGEST
Definition: LLVMBitCodes.h:808
@ COMDAT_SELECTION_KIND_ANY
Definition: LLVMBitCodes.h:806
@ COMDAT_SELECTION_KIND_SAME_SIZE
Definition: LLVMBitCodes.h:810
@ COMDAT_SELECTION_KIND_EXACT_MATCH
Definition: LLVMBitCodes.h:807
@ COMDAT_SELECTION_KIND_NO_DUPLICATES
Definition: LLVMBitCodes.h:809
@ ATTR_KIND_STACK_PROTECT
Definition: LLVMBitCodes.h:725
@ ATTR_KIND_NO_UNWIND
Definition: LLVMBitCodes.h:717
@ ATTR_KIND_STACK_PROTECT_STRONG
Definition: LLVMBitCodes.h:727
@ ATTR_KIND_SANITIZE_MEMORY
Definition: LLVMBitCodes.h:731
@ ATTR_KIND_SAFESTACK
Definition: LLVMBitCodes.h:743
@ ATTR_KIND_OPTIMIZE_FOR_SIZE
Definition: LLVMBitCodes.h:718
@ ATTR_KIND_SWIFT_ERROR
Definition: LLVMBitCodes.h:746
@ ATTR_KIND_STRUCT_RET
Definition: LLVMBitCodes.h:728
@ ATTR_KIND_MIN_SIZE
Definition: LLVMBitCodes.h:705
@ ATTR_KIND_NO_CALLBACK
Definition: LLVMBitCodes.h:770
@ ATTR_KIND_FNRETTHUNK_EXTERN
Definition: LLVMBitCodes.h:783
@ ATTR_KIND_NO_DIVERGENCE_SOURCE
Definition: LLVMBitCodes.h:799
@ ATTR_KIND_SANITIZE_ADDRESS
Definition: LLVMBitCodes.h:729
@ ATTR_KIND_NO_IMPLICIT_FLOAT
Definition: LLVMBitCodes.h:712
@ ATTR_KIND_NO_BUILTIN
Definition: LLVMBitCodes.h:709
@ ATTR_KIND_NO_RECURSE
Definition: LLVMBitCodes.h:747
@ ATTR_KIND_DEAD_ON_UNWIND
Definition: LLVMBitCodes.h:790
@ ATTR_KIND_CONVERGENT
Definition: LLVMBitCodes.h:742
@ ATTR_KIND_RETURNED
Definition: LLVMBitCodes.h:721
@ ATTR_KIND_STACK_ALIGNMENT
Definition: LLVMBitCodes.h:724
@ ATTR_KIND_SWIFT_SELF
Definition: LLVMBitCodes.h:745
@ ATTR_KIND_ALLOC_SIZE
Definition: LLVMBitCodes.h:750
@ ATTR_KIND_STACK_PROTECT_REQ
Definition: LLVMBitCodes.h:726
@ ATTR_KIND_INLINE_HINT
Definition: LLVMBitCodes.h:703
@ ATTR_KIND_NON_NULL
Definition: LLVMBitCodes.h:738
@ ATTR_KIND_NULL_POINTER_IS_VALID
Definition: LLVMBitCodes.h:766
@ ATTR_KIND_SANITIZE_HWADDRESS
Definition: LLVMBitCodes.h:754
@ ATTR_KIND_NO_RETURN
Definition: LLVMBitCodes.h:716
@ ATTR_KIND_MUSTPROGRESS
Definition: LLVMBitCodes.h:769
@ ATTR_KIND_RETURNS_TWICE
Definition: LLVMBitCodes.h:722
@ ATTR_KIND_SHADOWCALLSTACK
Definition: LLVMBitCodes.h:757
@ ATTR_KIND_OPT_FOR_FUZZING
Definition: LLVMBitCodes.h:756
@ ATTR_KIND_WRITABLE
Definition: LLVMBitCodes.h:788
@ ATTR_KIND_SANITIZE_NUMERICAL_STABILITY
Definition: LLVMBitCodes.h:792
@ ATTR_KIND_INITIALIZES
Definition: LLVMBitCodes.h:793
@ ATTR_KIND_ALLOCATED_POINTER
Definition: LLVMBitCodes.h:780
@ ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION
Definition: LLVMBitCodes.h:777
@ ATTR_KIND_SKIP_PROFILE
Definition: LLVMBitCodes.h:784
@ ATTR_KIND_ELEMENTTYPE
Definition: LLVMBitCodes.h:776
@ ATTR_KIND_CORO_ELIDE_SAFE
Definition: LLVMBitCodes.h:797
@ ATTR_KIND_ALLOC_KIND
Definition: LLVMBitCodes.h:781
@ ATTR_KIND_NO_MERGE
Definition: LLVMBitCodes.h:765
@ ATTR_KIND_STRICT_FP
Definition: LLVMBitCodes.h:753
@ ATTR_KIND_NO_DUPLICATE
Definition: LLVMBitCodes.h:711
@ ATTR_KIND_ALLOC_ALIGN
Definition: LLVMBitCodes.h:779
@ ATTR_KIND_NON_LAZY_BIND
Definition: LLVMBitCodes.h:714
@ ATTR_KIND_DEREFERENCEABLE
Definition: LLVMBitCodes.h:740
@ ATTR_KIND_READ_NONE
Definition: LLVMBitCodes.h:719
@ ATTR_KIND_UW_TABLE
Definition: LLVMBitCodes.h:732
@ ATTR_KIND_OPTIMIZE_NONE
Definition: LLVMBitCodes.h:736
@ ATTR_KIND_WRITEONLY
Definition: LLVMBitCodes.h:751
@ ATTR_KIND_HYBRID_PATCHABLE
Definition: LLVMBitCodes.h:794
@ ATTR_KIND_NO_RED_ZONE
Definition: LLVMBitCodes.h:715
@ ATTR_KIND_NOCF_CHECK
Definition: LLVMBitCodes.h:755
@ ATTR_KIND_NO_PROFILE
Definition: LLVMBitCodes.h:772
@ ATTR_KIND_DEREFERENCEABLE_OR_NULL
Definition: LLVMBitCodes.h:741
@ ATTR_KIND_SANITIZE_REALTIME
Definition: LLVMBitCodes.h:795
@ ATTR_KIND_IN_ALLOCA
Definition: LLVMBitCodes.h:737
@ ATTR_KIND_READ_ONLY
Definition: LLVMBitCodes.h:720
@ ATTR_KIND_ALIGNMENT
Definition: LLVMBitCodes.h:700
@ ATTR_KIND_SPECULATIVE_LOAD_HARDENING
Definition: LLVMBitCodes.h:758
@ ATTR_KIND_ALWAYS_INLINE
Definition: LLVMBitCodes.h:701
@ ATTR_KIND_NOFPCLASS
Definition: LLVMBitCodes.h:786
@ ATTR_KIND_WILLRETURN
Definition: LLVMBitCodes.h:760
@ ATTR_KIND_SANITIZE_TYPE
Definition: LLVMBitCodes.h:800
@ ATTR_KIND_PRESPLIT_COROUTINE
Definition: LLVMBitCodes.h:782
@ ATTR_KIND_NO_ALIAS
Definition: LLVMBitCodes.h:708
@ ATTR_KIND_VSCALE_RANGE
Definition: LLVMBitCodes.h:773
@ ATTR_KIND_NO_SANITIZE_COVERAGE
Definition: LLVMBitCodes.h:775
@ ATTR_KIND_JUMP_TABLE
Definition: LLVMBitCodes.h:739
@ ATTR_KIND_SPECULATABLE
Definition: LLVMBitCodes.h:752
@ ATTR_KIND_NO_INLINE
Definition: LLVMBitCodes.h:713
@ ATTR_KIND_DEAD_ON_RETURN
Definition: LLVMBitCodes.h:802
@ ATTR_KIND_SANITIZE_REALTIME_BLOCKING
Definition: LLVMBitCodes.h:796
@ ATTR_KIND_NO_SANITIZE_BOUNDS
Definition: LLVMBitCodes.h:778
@ ATTR_KIND_SANITIZE_MEMTAG
Definition: LLVMBitCodes.h:763
@ ATTR_KIND_CORO_ONLY_DESTROY_WHEN_COMPLETE
Definition: LLVMBitCodes.h:789
@ ATTR_KIND_CAPTURES
Definition: LLVMBitCodes.h:801
@ ATTR_KIND_SANITIZE_THREAD
Definition: LLVMBitCodes.h:730
@ ATTR_KIND_OPTIMIZE_FOR_DEBUGGING
Definition: LLVMBitCodes.h:787
@ ATTR_KIND_PREALLOCATED
Definition: LLVMBitCodes.h:764
@ ATTR_KIND_SWIFT_ASYNC
Definition: LLVMBitCodes.h:774
@ OBO_NO_SIGNED_WRAP
Definition: LLVMBitCodes.h:522
@ OBO_NO_UNSIGNED_WRAP
Definition: LLVMBitCodes.h:521
@ TIO_NO_UNSIGNED_WRAP
Definition: LLVMBitCodes.h:528
@ TIO_NO_SIGNED_WRAP
Definition: LLVMBitCodes.h:529
@ USELIST_CODE_DEFAULT
Definition: LLVMBitCodes.h:694
@ SYNC_SCOPE_NAMES_BLOCK_ID
Definition: LLVMBitCodes.h:65
@ PARAMATTR_BLOCK_ID
Definition: LLVMBitCodes.h:33
@ TYPE_BLOCK_ID_NEW
Definition: LLVMBitCodes.h:48
@ CONSTANTS_BLOCK_ID
Definition: LLVMBitCodes.h:36
@ PARAMATTR_GROUP_BLOCK_ID
Definition: LLVMBitCodes.h:34
@ METADATA_KIND_BLOCK_ID
Definition: LLVMBitCodes.h:57
@ IDENTIFICATION_BLOCK_ID
Definition: LLVMBitCodes.h:42
@ GLOBALVAL_SUMMARY_BLOCK_ID
Definition: LLVMBitCodes.h:53
@ METADATA_ATTACHMENT_ID
Definition: LLVMBitCodes.h:46
@ METADATA_BLOCK_ID
Definition: LLVMBitCodes.h:45
@ FUNCTION_BLOCK_ID
Definition: LLVMBitCodes.h:37
@ FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID
Definition: LLVMBitCodes.h:61
@ MODULE_STRTAB_BLOCK_ID
Definition: LLVMBitCodes.h:52
@ VALUE_SYMTAB_BLOCK_ID
Definition: LLVMBitCodes.h:44
@ OPERAND_BUNDLE_TAGS_BLOCK_ID
Definition: LLVMBitCodes.h:55
@ USELIST_BLOCK_ID
Definition: LLVMBitCodes.h:50
@ CAST_ADDRSPACECAST
Definition: LLVMBitCodes.h:459
@ MODULE_CODE_FUNCTION
Definition: LLVMBitCodes.h:100
@ MODULE_CODE_VERSION
Definition: LLVMBitCodes.h:85
@ MODULE_CODE_SOURCE_FILENAME
Definition: LLVMBitCodes.h:116
@ MODULE_CODE_SECTIONNAME
Definition: LLVMBitCodes.h:89
@ MODULE_CODE_TRIPLE
Definition: LLVMBitCodes.h:86
@ MODULE_CODE_DATALAYOUT
Definition: LLVMBitCodes.h:87
@ MODULE_CODE_GLOBALVAR
Definition: LLVMBitCodes.h:96
@ MODULE_CODE_VSTOFFSET
Definition: LLVMBitCodes.h:108
@ MODULE_CODE_GCNAME
Definition: LLVMBitCodes.h:105
@ MODULE_CODE_COMDAT
Definition: LLVMBitCodes.h:106
@ FUNC_CODE_INST_CATCHRET
Definition: LLVMBitCodes.h:664
@ FUNC_CODE_INST_LANDINGPAD
Definition: LLVMBitCodes.h:662
@ FUNC_CODE_INST_EXTRACTVAL
Definition: LLVMBitCodes.h:627
@ FUNC_CODE_INST_CATCHPAD
Definition: LLVMBitCodes.h:665
@ FUNC_CODE_INST_RESUME
Definition: LLVMBitCodes.h:649
@ FUNC_CODE_INST_CMP2
Definition: LLVMBitCodes.h:631
@ FUNC_CODE_INST_FENCE
Definition: LLVMBitCodes.h:642
@ FUNC_CODE_INST_CALLBR
Definition: LLVMBitCodes.h:673
@ FUNC_CODE_INST_CATCHSWITCH
Definition: LLVMBitCodes.h:667
@ FUNC_CODE_INST_VSELECT
Definition: LLVMBitCodes.h:633
@ FUNC_CODE_INST_GEP
Definition: LLVMBitCodes.h:656
@ FUNC_CODE_INST_CLEANUPRET
Definition: LLVMBitCodes.h:663
@ FUNC_CODE_DEBUG_RECORD_VALUE
Definition: LLVMBitCodes.h:681
@ FUNC_CODE_INST_LOADATOMIC
Definition: LLVMBitCodes.h:652
@ FUNC_CODE_DEBUG_RECORD_ASSIGN
Definition: LLVMBitCodes.h:685
@ FUNC_CODE_INST_LOAD
Definition: LLVMBitCodes.h:618
@ FUNC_CODE_INST_STOREATOMIC
Definition: LLVMBitCodes.h:658
@ FUNC_CODE_INST_ATOMICRMW
Definition: LLVMBitCodes.h:676
@ FUNC_CODE_INST_BINOP
Definition: LLVMBitCodes.h:598
@ FUNC_CODE_INST_STORE
Definition: LLVMBitCodes.h:657
@ FUNC_CODE_DEBUG_LOC_AGAIN
Definition: LLVMBitCodes.h:637
@ FUNC_CODE_INST_EXTRACTELT
Definition: LLVMBitCodes.h:602
@ FUNC_CODE_INST_INDIRECTBR
Definition: LLVMBitCodes.h:635
@ FUNC_CODE_INST_INVOKE
Definition: LLVMBitCodes.h:610
@ FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE
Definition: LLVMBitCodes.h:688
@ FUNC_CODE_INST_INSERTVAL
Definition: LLVMBitCodes.h:628
@ FUNC_CODE_DECLAREBLOCKS
Definition: LLVMBitCodes.h:596
@ FUNC_CODE_DEBUG_RECORD_LABEL
Definition: LLVMBitCodes.h:690
@ FUNC_CODE_INST_SWITCH
Definition: LLVMBitCodes.h:609
@ FUNC_CODE_INST_PHI
Definition: LLVMBitCodes.h:614
@ FUNC_CODE_INST_RET
Definition: LLVMBitCodes.h:607
@ FUNC_CODE_INST_CALL
Definition: LLVMBitCodes.h:639
@ FUNC_CODE_INST_ALLOCA
Definition: LLVMBitCodes.h:617
@ FUNC_CODE_INST_INSERTELT
Definition: LLVMBitCodes.h:603
@ FUNC_CODE_BLOCKADDR_USERS
Definition: LLVMBitCodes.h:679
@ FUNC_CODE_INST_CLEANUPPAD
Definition: LLVMBitCodes.h:666
@ FUNC_CODE_INST_SHUFFLEVEC
Definition: LLVMBitCodes.h:604
@ FUNC_CODE_INST_UNOP
Definition: LLVMBitCodes.h:672
@ FUNC_CODE_INST_VAARG
Definition: LLVMBitCodes.h:621
@ FUNC_CODE_INST_FREEZE
Definition: LLVMBitCodes.h:675
@ FUNC_CODE_INST_CMPXCHG
Definition: LLVMBitCodes.h:659
@ FUNC_CODE_INST_UNREACHABLE
Definition: LLVMBitCodes.h:612
@ FUNC_CODE_INST_CAST
Definition: LLVMBitCodes.h:599
@ FUNC_CODE_DEBUG_LOC
Definition: LLVMBitCodes.h:641
@ FUNC_CODE_DEBUG_RECORD_DECLARE
Definition: LLVMBitCodes.h:683
@ FUNC_CODE_OPERAND_BUNDLE
Definition: LLVMBitCodes.h:671
@ BITCODE_CURRENT_EPOCH
Definition: LLVMBitCodes.h:81
@ FIRST_APPLICATION_ABBREV
Definition: BitCodeEnums.h:60
@ OPERAND_BUNDLE_TAG
Definition: LLVMBitCodes.h:183
@ PARAMATTR_GRP_CODE_ENTRY
Definition: LLVMBitCodes.h:131
@ PARAMATTR_CODE_ENTRY
Definition: LLVMBitCodes.h:130
@ ORDERING_NOTATOMIC
Definition: LLVMBitCodes.h:574
@ ORDERING_UNORDERED
Definition: LLVMBitCodes.h:575
@ ORDERING_MONOTONIC
Definition: LLVMBitCodes.h:576
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:444
@ DW_APPLE_ENUM_KIND_invalid
Enum kind for invalid results.
Definition: Dwarf.h:50
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_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
NodeAddr< CodeNode * > Code
Definition: RDFGraph.h:388
void write32le(void *P, uint32_t V)
Definition: Endian.h:472
uint32_t read32be(const void *P)
Definition: Endian.h:438
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition: STLExtras.h:338
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:349
unsigned encode(MaybeAlign A)
Returns a representation of the alignment that encodes undefined as 0.
Definition: Alignment.h:217
@ Write
Definition: CodeGenData.h:109
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:2491
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
Definition: BitCodeEnums.h:32
FunctionSummary::ForceSummaryHotnessType ForceSummaryEdgesCold
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition: STLExtras.h:2155
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:1751
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:1669
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition: Error.cpp:167
AtomicOrdering
Atomic ordering for LLVM's memory model.
std::unordered_set< GlobalValueSummary * > GVSummaryPtrSet
A set of global value summary pointers.
DWARFExpression::Operation Op
std::map< std::string, GVSummaryMapTy, std::less<> > ModuleToSummariesForIndexTy
Map of a module name to the GUIDs and summaries we will import from that module.
OutputIt copy(R &&Range, OutputIt Out)
Definition: STLExtras.h:1854
constexpr unsigned BitWidth
Definition: BitmaskEnum.h:223
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
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,...
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
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:863
#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
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.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition: Alignment.h:117
static const Target * lookupTarget(StringRef TripleStr, std::string &Error)
lookupTarget - Lookup a target based on a target triple.
Structure to hold a use-list order.
Definition: UseListOrder.h:26
ValID - Represents a reference of a definition of some sort with no type.
Definition: LLParser.h:53
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,...