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