LLVM 19.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"
36#include "llvm/IR/Constants.h"
38#include "llvm/IR/DebugLoc.h"
40#include "llvm/IR/Function.h"
41#include "llvm/IR/GlobalAlias.h"
42#include "llvm/IR/GlobalIFunc.h"
44#include "llvm/IR/GlobalValue.h"
46#include "llvm/IR/InlineAsm.h"
47#include "llvm/IR/InstrTypes.h"
48#include "llvm/IR/Instruction.h"
50#include "llvm/IR/LLVMContext.h"
51#include "llvm/IR/Metadata.h"
52#include "llvm/IR/Module.h"
54#include "llvm/IR/Operator.h"
55#include "llvm/IR/Type.h"
57#include "llvm/IR/Value.h"
65#include "llvm/Support/Endian.h"
66#include "llvm/Support/Error.h"
69#include "llvm/Support/SHA1.h"
72#include <algorithm>
73#include <cassert>
74#include <cstddef>
75#include <cstdint>
76#include <iterator>
77#include <map>
78#include <memory>
79#include <optional>
80#include <string>
81#include <utility>
82#include <vector>
83
84using namespace llvm;
85
87 IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25),
88 cl::desc("Number of metadatas above which we emit an index "
89 "to enable lazy-loading"));
91 "bitcode-flush-threshold", cl::Hidden, cl::init(512),
92 cl::desc("The threshold (unit M) for flushing LLVM bitcode."));
93
95 "write-relbf-to-summary", cl::Hidden, cl::init(false),
96 cl::desc("Write relative block frequency to function summary "));
97
98namespace llvm {
100}
101
104
105namespace {
106
107/// These are manifest constants used by the bitcode writer. They do not need to
108/// be kept in sync with the reader, but need to be consistent within this file.
109enum {
110 // VALUE_SYMTAB_BLOCK abbrev id's.
111 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
112 VST_ENTRY_7_ABBREV,
113 VST_ENTRY_6_ABBREV,
114 VST_BBENTRY_6_ABBREV,
115
116 // CONSTANTS_BLOCK abbrev id's.
117 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
118 CONSTANTS_INTEGER_ABBREV,
119 CONSTANTS_CE_CAST_Abbrev,
120 CONSTANTS_NULL_Abbrev,
121
122 // FUNCTION_BLOCK abbrev id's.
123 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
124 FUNCTION_INST_UNOP_ABBREV,
125 FUNCTION_INST_UNOP_FLAGS_ABBREV,
126 FUNCTION_INST_BINOP_ABBREV,
127 FUNCTION_INST_BINOP_FLAGS_ABBREV,
128 FUNCTION_INST_CAST_ABBREV,
129 FUNCTION_INST_CAST_FLAGS_ABBREV,
130 FUNCTION_INST_RET_VOID_ABBREV,
131 FUNCTION_INST_RET_VAL_ABBREV,
132 FUNCTION_INST_UNREACHABLE_ABBREV,
133 FUNCTION_INST_GEP_ABBREV,
134 FUNCTION_DEBUG_RECORD_VALUE_ABBREV,
135};
136
137/// Abstract class to manage the bitcode writing, subclassed for each bitcode
138/// file type.
139class BitcodeWriterBase {
140protected:
141 /// The stream created and owned by the client.
142 BitstreamWriter &Stream;
143
144 StringTableBuilder &StrtabBuilder;
145
146public:
147 /// Constructs a BitcodeWriterBase object that writes to the provided
148 /// \p Stream.
149 BitcodeWriterBase(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder)
150 : Stream(Stream), StrtabBuilder(StrtabBuilder) {}
151
152protected:
153 void writeModuleVersion();
154};
155
156void BitcodeWriterBase::writeModuleVersion() {
157 // VERSION: [version#]
158 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, ArrayRef<uint64_t>{2});
159}
160
161/// Base class to manage the module bitcode writing, currently subclassed for
162/// ModuleBitcodeWriter and ThinLinkBitcodeWriter.
163class ModuleBitcodeWriterBase : public BitcodeWriterBase {
164protected:
165 /// The Module to write to bitcode.
166 const Module &M;
167
168 /// Enumerates ids for all values in the module.
170
171 /// Optional per-module index to write for ThinLTO.
173
174 /// Map that holds the correspondence between GUIDs in the summary index,
175 /// that came from indirect call profiles, and a value id generated by this
176 /// class to use in the VST and summary block records.
177 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
178
179 /// Tracks the last value id recorded in the GUIDToValueMap.
180 unsigned GlobalValueId;
181
182 /// Saves the offset of the VSTOffset record that must eventually be
183 /// backpatched with the offset of the actual VST.
184 uint64_t VSTOffsetPlaceholder = 0;
185
186public:
187 /// Constructs a ModuleBitcodeWriterBase object for the given Module,
188 /// writing to the provided \p Buffer.
189 ModuleBitcodeWriterBase(const Module &M, StringTableBuilder &StrtabBuilder,
190 BitstreamWriter &Stream,
191 bool ShouldPreserveUseListOrder,
193 : BitcodeWriterBase(Stream, StrtabBuilder), M(M),
194 VE(M, ShouldPreserveUseListOrder), Index(Index) {
195 // Assign ValueIds to any callee values in the index that came from
196 // indirect call profiles and were recorded as a GUID not a Value*
197 // (which would have been assigned an ID by the ValueEnumerator).
198 // The starting ValueId is just after the number of values in the
199 // ValueEnumerator, so that they can be emitted in the VST.
200 GlobalValueId = VE.getValues().size();
201 if (!Index)
202 return;
203 for (const auto &GUIDSummaryLists : *Index)
204 // Examine all summaries for this GUID.
205 for (auto &Summary : GUIDSummaryLists.second.SummaryList)
206 if (auto FS = dyn_cast<FunctionSummary>(Summary.get())) {
207 // For each call in the function summary, see if the call
208 // is to a GUID (which means it is for an indirect call,
209 // otherwise we would have a Value for it). If so, synthesize
210 // a value id.
211 for (auto &CallEdge : FS->calls())
212 if (!CallEdge.first.haveGVs() || !CallEdge.first.getValue())
213 assignValueId(CallEdge.first.getGUID());
214
215 // For each referenced variables in the function summary, see if the
216 // variable is represented by a GUID (as opposed to a symbol to
217 // declarations or definitions in the module). If so, synthesize a
218 // value id.
219 for (auto &RefEdge : FS->refs())
220 if (!RefEdge.haveGVs() || !RefEdge.getValue())
221 assignValueId(RefEdge.getGUID());
222 }
223 }
224
225protected:
226 void writePerModuleGlobalValueSummary();
227
228private:
229 void writePerModuleFunctionSummaryRecord(
231 unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
232 unsigned CallsiteAbbrev, unsigned AllocAbbrev, const Function &F);
233 void writeModuleLevelReferences(const GlobalVariable &V,
235 unsigned FSModRefsAbbrev,
236 unsigned FSModVTableRefsAbbrev);
237
238 void assignValueId(GlobalValue::GUID ValGUID) {
239 GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
240 }
241
242 unsigned getValueId(GlobalValue::GUID ValGUID) {
243 const auto &VMI = GUIDToValueIdMap.find(ValGUID);
244 // Expect that any GUID value had a value Id assigned by an
245 // earlier call to assignValueId.
246 assert(VMI != GUIDToValueIdMap.end() &&
247 "GUID does not have assigned value Id");
248 return VMI->second;
249 }
250
251 // Helper to get the valueId for the type of value recorded in VI.
252 unsigned getValueId(ValueInfo VI) {
253 if (!VI.haveGVs() || !VI.getValue())
254 return getValueId(VI.getGUID());
255 return VE.getValueID(VI.getValue());
256 }
257
258 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
259};
260
261/// Class to manage the bitcode writing for a module.
262class ModuleBitcodeWriter : public ModuleBitcodeWriterBase {
263 /// True if a module hash record should be written.
264 bool GenerateHash;
265
266 /// If non-null, when GenerateHash is true, the resulting hash is written
267 /// into ModHash.
268 ModuleHash *ModHash;
269
270 SHA1 Hasher;
271
272 /// The start bit of the identification block.
273 uint64_t BitcodeStartBit;
274
275public:
276 /// Constructs a ModuleBitcodeWriter object for the given Module,
277 /// writing to the provided \p Buffer.
278 ModuleBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder,
279 BitstreamWriter &Stream, bool ShouldPreserveUseListOrder,
280 const ModuleSummaryIndex *Index, bool GenerateHash,
281 ModuleHash *ModHash = nullptr)
282 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
283 ShouldPreserveUseListOrder, Index),
284 GenerateHash(GenerateHash), ModHash(ModHash),
285 BitcodeStartBit(Stream.GetCurrentBitNo()) {}
286
287 /// Emit the current module to the bitstream.
288 void write();
289
290private:
291 uint64_t bitcodeStartBit() { return BitcodeStartBit; }
292
293 size_t addToStrtab(StringRef Str);
294
295 void writeAttributeGroupTable();
296 void writeAttributeTable();
297 void writeTypeTable();
298 void writeComdats();
299 void writeValueSymbolTableForwardDecl();
300 void writeModuleInfo();
301 void writeValueAsMetadata(const ValueAsMetadata *MD,
304 unsigned Abbrev);
305 unsigned createDILocationAbbrev();
307 unsigned &Abbrev);
308 unsigned createGenericDINodeAbbrev();
310 SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev);
312 unsigned Abbrev);
315 unsigned Abbrev);
316 void writeDIEnumerator(const DIEnumerator *N,
317 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
319 unsigned Abbrev);
320 void writeDIStringType(const DIStringType *N,
321 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
323 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
325 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
328 unsigned Abbrev);
330 unsigned Abbrev);
332 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
333 void writeDISubprogram(const DISubprogram *N,
334 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
336 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
339 unsigned Abbrev);
341 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
343 unsigned Abbrev);
345 unsigned Abbrev);
347 unsigned Abbrev);
350 unsigned Abbrev);
352 unsigned Abbrev);
355 unsigned Abbrev);
358 unsigned Abbrev);
361 unsigned Abbrev);
363 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
364 void writeDILabel(const DILabel *N,
365 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
366 void writeDIExpression(const DIExpression *N,
367 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
370 unsigned Abbrev);
372 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
375 unsigned Abbrev);
376 unsigned createNamedMetadataAbbrev();
377 void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
378 unsigned createMetadataStringsAbbrev();
379 void writeMetadataStrings(ArrayRef<const Metadata *> Strings,
381 void writeMetadataRecords(ArrayRef<const Metadata *> MDs,
383 std::vector<unsigned> *MDAbbrevs = nullptr,
384 std::vector<uint64_t> *IndexPos = nullptr);
385 void writeModuleMetadata();
386 void writeFunctionMetadata(const Function &F);
387 void writeFunctionMetadataAttachment(const Function &F);
388 void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
389 const GlobalObject &GO);
390 void writeModuleMetadataKinds();
391 void writeOperandBundleTags();
392 void writeSyncScopeNames();
393 void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal);
394 void writeModuleConstants();
395 bool pushValueAndType(const Value *V, unsigned InstID,
397 void writeOperandBundles(const CallBase &CB, unsigned InstID);
398 void pushValue(const Value *V, unsigned InstID,
400 void pushValueSigned(const Value *V, unsigned InstID,
402 void writeInstruction(const Instruction &I, unsigned InstID,
404 void writeFunctionLevelValueSymbolTable(const ValueSymbolTable &VST);
405 void writeGlobalValueSymbolTable(
406 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
407 void writeUseList(UseListOrder &&Order);
408 void writeUseListBlock(const Function *F);
409 void
410 writeFunction(const Function &F,
411 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
412 void writeBlockInfo();
413 void writeModuleHash(StringRef View);
414
415 unsigned getEncodedSyncScopeID(SyncScope::ID SSID) {
416 return unsigned(SSID);
417 }
418
419 unsigned getEncodedAlign(MaybeAlign Alignment) { return encode(Alignment); }
420};
421
422/// Class to manage the bitcode writing for a combined index.
423class IndexBitcodeWriter : public BitcodeWriterBase {
424 /// The combined index to write to bitcode.
426
427 /// When writing a subset of the index for distributed backends, client
428 /// provides a map of modules to the corresponding GUIDs/summaries to write.
429 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex;
430
431 /// Map that holds the correspondence between the GUID used in the combined
432 /// index and a value id generated by this class to use in references.
433 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
434
435 // The stack ids used by this index, which will be a subset of those in
436 // the full index in the case of distributed indexes.
437 std::vector<uint64_t> StackIds;
438
439 // Keep a map of the stack id indices used by records being written for this
440 // index to the index of the corresponding stack id in the above StackIds
441 // vector. Ensures we write each referenced stack id once.
442 DenseMap<unsigned, unsigned> StackIdIndicesToIndex;
443
444 /// Tracks the last value id recorded in the GUIDToValueMap.
445 unsigned GlobalValueId = 0;
446
447 /// Tracks the assignment of module paths in the module path string table to
448 /// an id assigned for use in summary references to the module path.
450
451public:
452 /// Constructs a IndexBitcodeWriter object for the given combined index,
453 /// writing to the provided \p Buffer. When writing a subset of the index
454 /// for a distributed backend, provide a \p ModuleToSummariesForIndex map.
455 IndexBitcodeWriter(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder,
457 const std::map<std::string, GVSummaryMapTy>
458 *ModuleToSummariesForIndex = nullptr)
459 : BitcodeWriterBase(Stream, StrtabBuilder), Index(Index),
460 ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
461
462 // See if the StackIdIndex was already added to the StackId map and
463 // vector. If not, record it.
464 auto RecordStackIdReference = [&](unsigned StackIdIndex) {
465 // If the StackIdIndex is not yet in the map, the below insert ensures
466 // that it will point to the new StackIds vector entry we push to just
467 // below.
468 auto Inserted =
469 StackIdIndicesToIndex.insert({StackIdIndex, StackIds.size()});
470 if (Inserted.second)
471 StackIds.push_back(Index.getStackIdAtIndex(StackIdIndex));
472 };
473
474 // Assign unique value ids to all summaries to be written, for use
475 // in writing out the call graph edges. Save the mapping from GUID
476 // to the new global value id to use when writing those edges, which
477 // are currently saved in the index in terms of GUID.
478 forEachSummary([&](GVInfo I, bool IsAliasee) {
479 GUIDToValueIdMap[I.first] = ++GlobalValueId;
480 if (IsAliasee)
481 return;
482 auto *FS = dyn_cast<FunctionSummary>(I.second);
483 if (!FS)
484 return;
485 // Record all stack id indices actually used in the summary entries being
486 // written, so that we can compact them in the case of distributed ThinLTO
487 // indexes.
488 for (auto &CI : FS->callsites()) {
489 // If the stack id list is empty, this callsite info was synthesized for
490 // a missing tail call frame. Ensure that the callee's GUID gets a value
491 // id. Normally we only generate these for defined summaries, which in
492 // the case of distributed ThinLTO is only the functions already defined
493 // in the module or that we want to import. We don't bother to include
494 // all the callee symbols as they aren't normally needed in the backend.
495 // However, for the synthesized callsite infos we do need the callee
496 // GUID in the backend so that we can correlate the identified callee
497 // with this callsite info (which for non-tail calls is done by the
498 // ordering of the callsite infos and verified via stack ids).
499 if (CI.StackIdIndices.empty()) {
500 GUIDToValueIdMap[CI.Callee.getGUID()] = ++GlobalValueId;
501 continue;
502 }
503 for (auto Idx : CI.StackIdIndices)
504 RecordStackIdReference(Idx);
505 }
506 for (auto &AI : FS->allocs())
507 for (auto &MIB : AI.MIBs)
508 for (auto Idx : MIB.StackIdIndices)
509 RecordStackIdReference(Idx);
510 });
511 }
512
513 /// The below iterator returns the GUID and associated summary.
514 using GVInfo = std::pair<GlobalValue::GUID, GlobalValueSummary *>;
515
516 /// Calls the callback for each value GUID and summary to be written to
517 /// bitcode. This hides the details of whether they are being pulled from the
518 /// entire index or just those in a provided ModuleToSummariesForIndex map.
519 template<typename Functor>
520 void forEachSummary(Functor Callback) {
521 if (ModuleToSummariesForIndex) {
522 for (auto &M : *ModuleToSummariesForIndex)
523 for (auto &Summary : M.second) {
524 Callback(Summary, false);
525 // Ensure aliasee is handled, e.g. for assigning a valueId,
526 // even if we are not importing the aliasee directly (the
527 // imported alias will contain a copy of aliasee).
528 if (auto *AS = dyn_cast<AliasSummary>(Summary.getSecond()))
529 Callback({AS->getAliaseeGUID(), &AS->getAliasee()}, true);
530 }
531 } else {
532 for (auto &Summaries : Index)
533 for (auto &Summary : Summaries.second.SummaryList)
534 Callback({Summaries.first, Summary.get()}, false);
535 }
536 }
537
538 /// Calls the callback for each entry in the modulePaths StringMap that
539 /// should be written to the module path string table. This hides the details
540 /// of whether they are being pulled from the entire index or just those in a
541 /// provided ModuleToSummariesForIndex map.
542 template <typename Functor> void forEachModule(Functor Callback) {
543 if (ModuleToSummariesForIndex) {
544 for (const auto &M : *ModuleToSummariesForIndex) {
545 const auto &MPI = Index.modulePaths().find(M.first);
546 if (MPI == Index.modulePaths().end()) {
547 // This should only happen if the bitcode file was empty, in which
548 // case we shouldn't be importing (the ModuleToSummariesForIndex
549 // would only include the module we are writing and index for).
550 assert(ModuleToSummariesForIndex->size() == 1);
551 continue;
552 }
553 Callback(*MPI);
554 }
555 } else {
556 // Since StringMap iteration order isn't guaranteed, order by path string
557 // first.
558 // FIXME: Make this a vector of StringMapEntry instead to avoid the later
559 // map lookup.
560 std::vector<StringRef> ModulePaths;
561 for (auto &[ModPath, _] : Index.modulePaths())
562 ModulePaths.push_back(ModPath);
563 llvm::sort(ModulePaths.begin(), ModulePaths.end());
564 for (auto &ModPath : ModulePaths)
565 Callback(*Index.modulePaths().find(ModPath));
566 }
567 }
568
569 /// Main entry point for writing a combined index to bitcode.
570 void write();
571
572private:
573 void writeModStrings();
574 void writeCombinedGlobalValueSummary();
575
576 std::optional<unsigned> getValueId(GlobalValue::GUID ValGUID) {
577 auto VMI = GUIDToValueIdMap.find(ValGUID);
578 if (VMI == GUIDToValueIdMap.end())
579 return std::nullopt;
580 return VMI->second;
581 }
582
583 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
584};
585
586} // end anonymous namespace
587
588static unsigned getEncodedCastOpcode(unsigned Opcode) {
589 switch (Opcode) {
590 default: llvm_unreachable("Unknown cast instruction!");
591 case Instruction::Trunc : return bitc::CAST_TRUNC;
592 case Instruction::ZExt : return bitc::CAST_ZEXT;
593 case Instruction::SExt : return bitc::CAST_SEXT;
594 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
595 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
596 case Instruction::UIToFP : return bitc::CAST_UITOFP;
597 case Instruction::SIToFP : return bitc::CAST_SITOFP;
598 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
599 case Instruction::FPExt : return bitc::CAST_FPEXT;
600 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
601 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
602 case Instruction::BitCast : return bitc::CAST_BITCAST;
603 case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
604 }
605}
606
607static unsigned getEncodedUnaryOpcode(unsigned Opcode) {
608 switch (Opcode) {
609 default: llvm_unreachable("Unknown binary instruction!");
610 case Instruction::FNeg: return bitc::UNOP_FNEG;
611 }
612}
613
614static unsigned getEncodedBinaryOpcode(unsigned Opcode) {
615 switch (Opcode) {
616 default: llvm_unreachable("Unknown binary instruction!");
617 case Instruction::Add:
618 case Instruction::FAdd: return bitc::BINOP_ADD;
619 case Instruction::Sub:
620 case Instruction::FSub: return bitc::BINOP_SUB;
621 case Instruction::Mul:
622 case Instruction::FMul: return bitc::BINOP_MUL;
623 case Instruction::UDiv: return bitc::BINOP_UDIV;
624 case Instruction::FDiv:
625 case Instruction::SDiv: return bitc::BINOP_SDIV;
626 case Instruction::URem: return bitc::BINOP_UREM;
627 case Instruction::FRem:
628 case Instruction::SRem: return bitc::BINOP_SREM;
629 case Instruction::Shl: return bitc::BINOP_SHL;
630 case Instruction::LShr: return bitc::BINOP_LSHR;
631 case Instruction::AShr: return bitc::BINOP_ASHR;
632 case Instruction::And: return bitc::BINOP_AND;
633 case Instruction::Or: return bitc::BINOP_OR;
634 case Instruction::Xor: return bitc::BINOP_XOR;
635 }
636}
637
639 switch (Op) {
640 default: llvm_unreachable("Unknown RMW operation!");
646 case AtomicRMWInst::Or: return bitc::RMW_OR;
657 return bitc::RMW_UINC_WRAP;
659 return bitc::RMW_UDEC_WRAP;
660 }
661}
662
663static unsigned getEncodedOrdering(AtomicOrdering Ordering) {
664 switch (Ordering) {
665 case AtomicOrdering::NotAtomic: return bitc::ORDERING_NOTATOMIC;
666 case AtomicOrdering::Unordered: return bitc::ORDERING_UNORDERED;
667 case AtomicOrdering::Monotonic: return bitc::ORDERING_MONOTONIC;
668 case AtomicOrdering::Acquire: return bitc::ORDERING_ACQUIRE;
669 case AtomicOrdering::Release: return bitc::ORDERING_RELEASE;
670 case AtomicOrdering::AcquireRelease: return bitc::ORDERING_ACQREL;
671 case AtomicOrdering::SequentiallyConsistent: return bitc::ORDERING_SEQCST;
672 }
673 llvm_unreachable("Invalid ordering");
674}
675
676static void writeStringRecord(BitstreamWriter &Stream, unsigned Code,
677 StringRef Str, unsigned AbbrevToUse) {
679
680 // Code: [strchar x N]
681 for (char C : Str) {
682 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(C))
683 AbbrevToUse = 0;
684 Vals.push_back(C);
685 }
686
687 // Emit the finished record.
688 Stream.EmitRecord(Code, Vals, AbbrevToUse);
689}
690
692 switch (Kind) {
693 case Attribute::Alignment:
695 case Attribute::AllocAlign:
697 case Attribute::AllocSize:
699 case Attribute::AlwaysInline:
701 case Attribute::Builtin:
703 case Attribute::ByVal:
705 case Attribute::Convergent:
707 case Attribute::InAlloca:
709 case Attribute::Cold:
711 case Attribute::DisableSanitizerInstrumentation:
713 case Attribute::FnRetThunkExtern:
715 case Attribute::Hot:
716 return bitc::ATTR_KIND_HOT;
717 case Attribute::ElementType:
719 case Attribute::InlineHint:
721 case Attribute::InReg:
723 case Attribute::JumpTable:
725 case Attribute::MinSize:
727 case Attribute::AllocatedPointer:
729 case Attribute::AllocKind:
731 case Attribute::Memory:
733 case Attribute::NoFPClass:
735 case Attribute::Naked:
737 case Attribute::Nest:
739 case Attribute::NoAlias:
741 case Attribute::NoBuiltin:
743 case Attribute::NoCallback:
745 case Attribute::NoCapture:
747 case Attribute::NoDuplicate:
749 case Attribute::NoFree:
751 case Attribute::NoImplicitFloat:
753 case Attribute::NoInline:
755 case Attribute::NoRecurse:
757 case Attribute::NoMerge:
759 case Attribute::NonLazyBind:
761 case Attribute::NonNull:
763 case Attribute::Dereferenceable:
765 case Attribute::DereferenceableOrNull:
767 case Attribute::NoRedZone:
769 case Attribute::NoReturn:
771 case Attribute::NoSync:
773 case Attribute::NoCfCheck:
775 case Attribute::NoProfile:
777 case Attribute::SkipProfile:
779 case Attribute::NoUnwind:
781 case Attribute::NoSanitizeBounds:
783 case Attribute::NoSanitizeCoverage:
785 case Attribute::NullPointerIsValid:
787 case Attribute::OptimizeForDebugging:
789 case Attribute::OptForFuzzing:
791 case Attribute::OptimizeForSize:
793 case Attribute::OptimizeNone:
795 case Attribute::ReadNone:
797 case Attribute::ReadOnly:
799 case Attribute::Returned:
801 case Attribute::ReturnsTwice:
803 case Attribute::SExt:
805 case Attribute::Speculatable:
807 case Attribute::StackAlignment:
809 case Attribute::StackProtect:
811 case Attribute::StackProtectReq:
813 case Attribute::StackProtectStrong:
815 case Attribute::SafeStack:
817 case Attribute::ShadowCallStack:
819 case Attribute::StrictFP:
821 case Attribute::StructRet:
823 case Attribute::SanitizeAddress:
825 case Attribute::SanitizeHWAddress:
827 case Attribute::SanitizeThread:
829 case Attribute::SanitizeMemory:
831 case Attribute::SanitizeNumericalStability:
833 case Attribute::SpeculativeLoadHardening:
835 case Attribute::SwiftError:
837 case Attribute::SwiftSelf:
839 case Attribute::SwiftAsync:
841 case Attribute::UWTable:
843 case Attribute::VScaleRange:
845 case Attribute::WillReturn:
847 case Attribute::WriteOnly:
849 case Attribute::ZExt:
851 case Attribute::ImmArg:
853 case Attribute::SanitizeMemTag:
855 case Attribute::Preallocated:
857 case Attribute::NoUndef:
859 case Attribute::ByRef:
861 case Attribute::MustProgress:
863 case Attribute::PresplitCoroutine:
865 case Attribute::Writable:
867 case Attribute::CoroDestroyOnlyWhenComplete:
869 case Attribute::DeadOnUnwind:
871 case Attribute::Range:
874 llvm_unreachable("Can not encode end-attribute kinds marker.");
875 case Attribute::None:
876 llvm_unreachable("Can not encode none-attribute.");
879 llvm_unreachable("Trying to encode EmptyKey/TombstoneKey");
880 }
881
882 llvm_unreachable("Trying to encode unknown attribute");
883}
884
886 if ((int64_t)V >= 0)
887 Vals.push_back(V << 1);
888 else
889 Vals.push_back((-V << 1) | 1);
890}
891
892static void emitWideAPInt(SmallVectorImpl<uint64_t> &Vals, const APInt &A) {
893 // We have an arbitrary precision integer value to write whose
894 // bit width is > 64. However, in canonical unsigned integer
895 // format it is likely that the high bits are going to be zero.
896 // So, we only write the number of active words.
897 unsigned NumWords = A.getActiveWords();
898 const uint64_t *RawData = A.getRawData();
899 for (unsigned i = 0; i < NumWords; i++)
900 emitSignedInt64(Vals, RawData[i]);
901}
902
904 const ConstantRange &CR) {
905 unsigned BitWidth = CR.getBitWidth();
906 Record.push_back(BitWidth);
907 if (BitWidth > 64) {
908 Record.push_back(CR.getLower().getActiveWords() |
909 (uint64_t(CR.getUpper().getActiveWords()) << 32));
912 } else {
915 }
916}
917
918void ModuleBitcodeWriter::writeAttributeGroupTable() {
919 const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
921 if (AttrGrps.empty()) return;
922
924
926 for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) {
927 unsigned AttrListIndex = Pair.first;
928 AttributeSet AS = Pair.second;
929 Record.push_back(VE.getAttributeGroupID(Pair));
930 Record.push_back(AttrListIndex);
931
932 for (Attribute Attr : AS) {
933 if (Attr.isEnumAttribute()) {
934 Record.push_back(0);
935 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
936 } else if (Attr.isIntAttribute()) {
937 Record.push_back(1);
938 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
939 Record.push_back(Attr.getValueAsInt());
940 } else if (Attr.isStringAttribute()) {
941 StringRef Kind = Attr.getKindAsString();
942 StringRef Val = Attr.getValueAsString();
943
944 Record.push_back(Val.empty() ? 3 : 4);
945 Record.append(Kind.begin(), Kind.end());
946 Record.push_back(0);
947 if (!Val.empty()) {
948 Record.append(Val.begin(), Val.end());
949 Record.push_back(0);
950 }
951 } else if (Attr.isTypeAttribute()) {
952 Type *Ty = Attr.getValueAsType();
953 Record.push_back(Ty ? 6 : 5);
954 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
955 if (Ty)
956 Record.push_back(VE.getTypeID(Attr.getValueAsType()));
957 } else {
958 assert(Attr.isConstantRangeAttribute());
959 Record.push_back(7);
960 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
961 emitConstantRange(Record, Attr.getValueAsConstantRange());
962 }
963 }
964
966 Record.clear();
967 }
968
969 Stream.ExitBlock();
970}
971
972void ModuleBitcodeWriter::writeAttributeTable() {
973 const std::vector<AttributeList> &Attrs = VE.getAttributeLists();
974 if (Attrs.empty()) return;
975
977
979 for (const AttributeList &AL : Attrs) {
980 for (unsigned i : AL.indexes()) {
981 AttributeSet AS = AL.getAttributes(i);
982 if (AS.hasAttributes())
983 Record.push_back(VE.getAttributeGroupID({i, AS}));
984 }
985
987 Record.clear();
988 }
989
990 Stream.ExitBlock();
991}
992
993/// WriteTypeTable - Write out the type table for a module.
994void ModuleBitcodeWriter::writeTypeTable() {
995 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
996
997 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
999
1001
1002 // Abbrev for TYPE_CODE_OPAQUE_POINTER.
1003 auto Abbv = std::make_shared<BitCodeAbbrev>();
1005 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
1006 unsigned OpaquePtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1007
1008 // Abbrev for TYPE_CODE_FUNCTION.
1009 Abbv = std::make_shared<BitCodeAbbrev>();
1011 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
1013 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
1014 unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1015
1016 // Abbrev for TYPE_CODE_STRUCT_ANON.
1017 Abbv = std::make_shared<BitCodeAbbrev>();
1019 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
1021 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
1022 unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1023
1024 // Abbrev for TYPE_CODE_STRUCT_NAME.
1025 Abbv = std::make_shared<BitCodeAbbrev>();
1029 unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1030
1031 // Abbrev for TYPE_CODE_STRUCT_NAMED.
1032 Abbv = std::make_shared<BitCodeAbbrev>();
1034 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
1036 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
1037 unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1038
1039 // Abbrev for TYPE_CODE_ARRAY.
1040 Abbv = std::make_shared<BitCodeAbbrev>();
1042 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
1043 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
1044 unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1045
1046 // Emit an entry count so the reader can reserve space.
1047 TypeVals.push_back(TypeList.size());
1048 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
1049 TypeVals.clear();
1050
1051 // Loop over all of the types, emitting each in turn.
1052 for (Type *T : TypeList) {
1053 int AbbrevToUse = 0;
1054 unsigned Code = 0;
1055
1056 switch (T->getTypeID()) {
1070 case Type::IntegerTyID:
1071 // INTEGER: [width]
1073 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
1074 break;
1075 case Type::PointerTyID: {
1076 PointerType *PTy = cast<PointerType>(T);
1077 unsigned AddressSpace = PTy->getAddressSpace();
1078 // OPAQUE_POINTER: [address space]
1080 TypeVals.push_back(AddressSpace);
1081 if (AddressSpace == 0)
1082 AbbrevToUse = OpaquePtrAbbrev;
1083 break;
1084 }
1085 case Type::FunctionTyID: {
1086 FunctionType *FT = cast<FunctionType>(T);
1087 // FUNCTION: [isvararg, retty, paramty x N]
1089 TypeVals.push_back(FT->isVarArg());
1090 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
1091 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
1092 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
1093 AbbrevToUse = FunctionAbbrev;
1094 break;
1095 }
1096 case Type::StructTyID: {
1097 StructType *ST = cast<StructType>(T);
1098 // STRUCT: [ispacked, eltty x N]
1099 TypeVals.push_back(ST->isPacked());
1100 // Output all of the element types.
1101 for (Type *ET : ST->elements())
1102 TypeVals.push_back(VE.getTypeID(ET));
1103
1104 if (ST->isLiteral()) {
1106 AbbrevToUse = StructAnonAbbrev;
1107 } else {
1108 if (ST->isOpaque()) {
1110 } else {
1112 AbbrevToUse = StructNamedAbbrev;
1113 }
1114
1115 // Emit the name if it is present.
1116 if (!ST->getName().empty())
1118 StructNameAbbrev);
1119 }
1120 break;
1121 }
1122 case Type::ArrayTyID: {
1123 ArrayType *AT = cast<ArrayType>(T);
1124 // ARRAY: [numelts, eltty]
1126 TypeVals.push_back(AT->getNumElements());
1127 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
1128 AbbrevToUse = ArrayAbbrev;
1129 break;
1130 }
1133 VectorType *VT = cast<VectorType>(T);
1134 // VECTOR [numelts, eltty] or
1135 // [numelts, eltty, scalable]
1137 TypeVals.push_back(VT->getElementCount().getKnownMinValue());
1138 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
1139 if (isa<ScalableVectorType>(VT))
1140 TypeVals.push_back(true);
1141 break;
1142 }
1143 case Type::TargetExtTyID: {
1144 TargetExtType *TET = cast<TargetExtType>(T);
1147 StructNameAbbrev);
1148 TypeVals.push_back(TET->getNumTypeParameters());
1149 for (Type *InnerTy : TET->type_params())
1150 TypeVals.push_back(VE.getTypeID(InnerTy));
1151 for (unsigned IntParam : TET->int_params())
1152 TypeVals.push_back(IntParam);
1153 break;
1154 }
1156 llvm_unreachable("Typed pointers cannot be added to IR modules");
1157 }
1158
1159 // Emit the finished record.
1160 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
1161 TypeVals.clear();
1162 }
1163
1164 Stream.ExitBlock();
1165}
1166
1167static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {
1168 switch (Linkage) {
1170 return 0;
1172 return 16;
1174 return 2;
1176 return 3;
1178 return 18;
1180 return 7;
1182 return 8;
1184 return 9;
1186 return 17;
1188 return 19;
1190 return 12;
1191 }
1192 llvm_unreachable("Invalid linkage");
1193}
1194
1195static unsigned getEncodedLinkage(const GlobalValue &GV) {
1196 return getEncodedLinkage(GV.getLinkage());
1197}
1198
1200 uint64_t RawFlags = 0;
1201 RawFlags |= Flags.ReadNone;
1202 RawFlags |= (Flags.ReadOnly << 1);
1203 RawFlags |= (Flags.NoRecurse << 2);
1204 RawFlags |= (Flags.ReturnDoesNotAlias << 3);
1205 RawFlags |= (Flags.NoInline << 4);
1206 RawFlags |= (Flags.AlwaysInline << 5);
1207 RawFlags |= (Flags.NoUnwind << 6);
1208 RawFlags |= (Flags.MayThrow << 7);
1209 RawFlags |= (Flags.HasUnknownCall << 8);
1210 RawFlags |= (Flags.MustBeUnreachable << 9);
1211 return RawFlags;
1212}
1213
1214// Decode the flags for GlobalValue in the summary. See getDecodedGVSummaryFlags
1215// in BitcodeReader.cpp.
1217 uint64_t RawFlags = 0;
1218
1219 RawFlags |= Flags.NotEligibleToImport; // bool
1220 RawFlags |= (Flags.Live << 1);
1221 RawFlags |= (Flags.DSOLocal << 2);
1222 RawFlags |= (Flags.CanAutoHide << 3);
1223
1224 // Linkage don't need to be remapped at that time for the summary. Any future
1225 // change to the getEncodedLinkage() function will need to be taken into
1226 // account here as well.
1227 RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits
1228
1229 RawFlags |= (Flags.Visibility << 8); // 2 bits
1230
1231 RawFlags |= (Flags.ImportType << 10); // 1 bit
1232
1233 return RawFlags;
1234}
1235
1237 uint64_t RawFlags = Flags.MaybeReadOnly | (Flags.MaybeWriteOnly << 1) |
1238 (Flags.Constant << 2) | Flags.VCallVisibility << 3;
1239 return RawFlags;
1240}
1241
1243 uint64_t RawFlags = 0;
1244
1245 RawFlags |= CI.Hotness; // 3 bits
1246 RawFlags |= (CI.HasTailCall << 3); // 1 bit
1247
1248 return RawFlags;
1249}
1250
1252 uint64_t RawFlags = 0;
1253
1254 RawFlags |= CI.RelBlockFreq; // CalleeInfo::RelBlockFreqBits bits
1255 RawFlags |= (CI.HasTailCall << CalleeInfo::RelBlockFreqBits); // 1 bit
1256
1257 return RawFlags;
1258}
1259
1260static unsigned getEncodedVisibility(const GlobalValue &GV) {
1261 switch (GV.getVisibility()) {
1262 case GlobalValue::DefaultVisibility: return 0;
1263 case GlobalValue::HiddenVisibility: return 1;
1264 case GlobalValue::ProtectedVisibility: return 2;
1265 }
1266 llvm_unreachable("Invalid visibility");
1267}
1268
1269static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
1270 switch (GV.getDLLStorageClass()) {
1271 case GlobalValue::DefaultStorageClass: return 0;
1274 }
1275 llvm_unreachable("Invalid DLL storage class");
1276}
1277
1278static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
1279 switch (GV.getThreadLocalMode()) {
1280 case GlobalVariable::NotThreadLocal: return 0;
1281 case GlobalVariable::GeneralDynamicTLSModel: return 1;
1282 case GlobalVariable::LocalDynamicTLSModel: return 2;
1283 case GlobalVariable::InitialExecTLSModel: return 3;
1284 case GlobalVariable::LocalExecTLSModel: return 4;
1285 }
1286 llvm_unreachable("Invalid TLS model");
1287}
1288
1289static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
1290 switch (C.getSelectionKind()) {
1291 case Comdat::Any:
1293 case Comdat::ExactMatch:
1295 case Comdat::Largest:
1299 case Comdat::SameSize:
1301 }
1302 llvm_unreachable("Invalid selection kind");
1303}
1304
1305static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) {
1306 switch (GV.getUnnamedAddr()) {
1307 case GlobalValue::UnnamedAddr::None: return 0;
1308 case GlobalValue::UnnamedAddr::Local: return 2;
1309 case GlobalValue::UnnamedAddr::Global: return 1;
1310 }
1311 llvm_unreachable("Invalid unnamed_addr");
1312}
1313
1314size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) {
1315 if (GenerateHash)
1316 Hasher.update(Str);
1317 return StrtabBuilder.add(Str);
1318}
1319
1320void ModuleBitcodeWriter::writeComdats() {
1322 for (const Comdat *C : VE.getComdats()) {
1323 // COMDAT: [strtab offset, strtab size, selection_kind]
1324 Vals.push_back(addToStrtab(C->getName()));
1325 Vals.push_back(C->getName().size());
1327 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
1328 Vals.clear();
1329 }
1330}
1331
1332/// Write a record that will eventually hold the word offset of the
1333/// module-level VST. For now the offset is 0, which will be backpatched
1334/// after the real VST is written. Saves the bit offset to backpatch.
1335void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
1336 // Write a placeholder value in for the offset of the real VST,
1337 // which is written after the function blocks so that it can include
1338 // the offset of each function. The placeholder offset will be
1339 // updated when the real VST is written.
1340 auto Abbv = std::make_shared<BitCodeAbbrev>();
1342 // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
1343 // hold the real VST offset. Must use fixed instead of VBR as we don't
1344 // know how many VBR chunks to reserve ahead of time.
1346 unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1347
1348 // Emit the placeholder
1350 Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
1351
1352 // Compute and save the bit offset to the placeholder, which will be
1353 // patched when the real VST is written. We can simply subtract the 32-bit
1354 // fixed size from the current bit number to get the location to backpatch.
1355 VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32;
1356}
1357
1359
1360/// Determine the encoding to use for the given string name and length.
1362 bool isChar6 = true;
1363 for (char C : Str) {
1364 if (isChar6)
1365 isChar6 = BitCodeAbbrevOp::isChar6(C);
1366 if ((unsigned char)C & 128)
1367 // don't bother scanning the rest.
1368 return SE_Fixed8;
1369 }
1370 if (isChar6)
1371 return SE_Char6;
1372 return SE_Fixed7;
1373}
1374
1375static_assert(sizeof(GlobalValue::SanitizerMetadata) <= sizeof(unsigned),
1376 "Sanitizer Metadata is too large for naive serialization.");
1377static unsigned
1379 return Meta.NoAddress | (Meta.NoHWAddress << 1) |
1380 (Meta.Memtag << 2) | (Meta.IsDynInit << 3);
1381}
1382
1383/// Emit top-level description of module, including target triple, inline asm,
1384/// descriptors for global variables, and function prototype info.
1385/// Returns the bit offset to backpatch with the location of the real VST.
1386void ModuleBitcodeWriter::writeModuleInfo() {
1387 // Emit various pieces of data attached to a module.
1388 if (!M.getTargetTriple().empty())
1389 writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(),
1390 0 /*TODO*/);
1391 const std::string &DL = M.getDataLayoutStr();
1392 if (!DL.empty())
1394 if (!M.getModuleInlineAsm().empty())
1395 writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(),
1396 0 /*TODO*/);
1397
1398 // Emit information about sections and GC, computing how many there are. Also
1399 // compute the maximum alignment value.
1400 std::map<std::string, unsigned> SectionMap;
1401 std::map<std::string, unsigned> GCMap;
1402 MaybeAlign MaxAlignment;
1403 unsigned MaxGlobalType = 0;
1404 const auto UpdateMaxAlignment = [&MaxAlignment](const MaybeAlign A) {
1405 if (A)
1406 MaxAlignment = !MaxAlignment ? *A : std::max(*MaxAlignment, *A);
1407 };
1408 for (const GlobalVariable &GV : M.globals()) {
1409 UpdateMaxAlignment(GV.getAlign());
1410 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
1411 if (GV.hasSection()) {
1412 // Give section names unique ID's.
1413 unsigned &Entry = SectionMap[std::string(GV.getSection())];
1414 if (!Entry) {
1415 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
1416 0 /*TODO*/);
1417 Entry = SectionMap.size();
1418 }
1419 }
1420 }
1421 for (const Function &F : M) {
1422 UpdateMaxAlignment(F.getAlign());
1423 if (F.hasSection()) {
1424 // Give section names unique ID's.
1425 unsigned &Entry = SectionMap[std::string(F.getSection())];
1426 if (!Entry) {
1428 0 /*TODO*/);
1429 Entry = SectionMap.size();
1430 }
1431 }
1432 if (F.hasGC()) {
1433 // Same for GC names.
1434 unsigned &Entry = GCMap[F.getGC()];
1435 if (!Entry) {
1437 0 /*TODO*/);
1438 Entry = GCMap.size();
1439 }
1440 }
1441 }
1442
1443 // Emit abbrev for globals, now that we know # sections and max alignment.
1444 unsigned SimpleGVarAbbrev = 0;
1445 if (!M.global_empty()) {
1446 // Add an abbrev for common globals with no visibility or thread localness.
1447 auto Abbv = std::make_shared<BitCodeAbbrev>();
1452 Log2_32_Ceil(MaxGlobalType+1)));
1453 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2
1454 //| explicitType << 1
1455 //| constant
1456 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
1457 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
1458 if (!MaxAlignment) // Alignment.
1459 Abbv->Add(BitCodeAbbrevOp(0));
1460 else {
1461 unsigned MaxEncAlignment = getEncodedAlign(MaxAlignment);
1463 Log2_32_Ceil(MaxEncAlignment+1)));
1464 }
1465 if (SectionMap.empty()) // Section.
1466 Abbv->Add(BitCodeAbbrevOp(0));
1467 else
1469 Log2_32_Ceil(SectionMap.size()+1)));
1470 // Don't bother emitting vis + thread local.
1471 SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1472 }
1473
1475 // Emit the module's source file name.
1476 {
1477 StringEncoding Bits = getStringEncoding(M.getSourceFileName());
1479 if (Bits == SE_Char6)
1480 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
1481 else if (Bits == SE_Fixed7)
1482 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
1483
1484 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
1485 auto Abbv = std::make_shared<BitCodeAbbrev>();
1488 Abbv->Add(AbbrevOpToUse);
1489 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1490
1491 for (const auto P : M.getSourceFileName())
1492 Vals.push_back((unsigned char)P);
1493
1494 // Emit the finished record.
1495 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
1496 Vals.clear();
1497 }
1498
1499 // Emit the global variable information.
1500 for (const GlobalVariable &GV : M.globals()) {
1501 unsigned AbbrevToUse = 0;
1502
1503 // GLOBALVAR: [strtab offset, strtab size, type, isconst, initid,
1504 // linkage, alignment, section, visibility, threadlocal,
1505 // unnamed_addr, externally_initialized, dllstorageclass,
1506 // comdat, attributes, DSO_Local, GlobalSanitizer, code_model]
1507 Vals.push_back(addToStrtab(GV.getName()));
1508 Vals.push_back(GV.getName().size());
1509 Vals.push_back(VE.getTypeID(GV.getValueType()));
1510 Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
1511 Vals.push_back(GV.isDeclaration() ? 0 :
1512 (VE.getValueID(GV.getInitializer()) + 1));
1513 Vals.push_back(getEncodedLinkage(GV));
1514 Vals.push_back(getEncodedAlign(GV.getAlign()));
1515 Vals.push_back(GV.hasSection() ? SectionMap[std::string(GV.getSection())]
1516 : 0);
1517 if (GV.isThreadLocal() ||
1518 GV.getVisibility() != GlobalValue::DefaultVisibility ||
1519 GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1520 GV.isExternallyInitialized() ||
1521 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
1522 GV.hasComdat() || GV.hasAttributes() || GV.isDSOLocal() ||
1523 GV.hasPartition() || GV.hasSanitizerMetadata() || GV.getCodeModel()) {
1527 Vals.push_back(GV.isExternallyInitialized());
1529 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
1530
1531 auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
1532 Vals.push_back(VE.getAttributeListID(AL));
1533
1534 Vals.push_back(GV.isDSOLocal());
1535 Vals.push_back(addToStrtab(GV.getPartition()));
1536 Vals.push_back(GV.getPartition().size());
1537
1538 Vals.push_back((GV.hasSanitizerMetadata() ? serializeSanitizerMetadata(
1539 GV.getSanitizerMetadata())
1540 : 0));
1541 Vals.push_back(GV.getCodeModelRaw());
1542 } else {
1543 AbbrevToUse = SimpleGVarAbbrev;
1544 }
1545
1546 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
1547 Vals.clear();
1548 }
1549
1550 // Emit the function proto information.
1551 for (const Function &F : M) {
1552 // FUNCTION: [strtab offset, strtab size, type, callingconv, isproto,
1553 // linkage, paramattrs, alignment, section, visibility, gc,
1554 // unnamed_addr, prologuedata, dllstorageclass, comdat,
1555 // prefixdata, personalityfn, DSO_Local, addrspace]
1556 Vals.push_back(addToStrtab(F.getName()));
1557 Vals.push_back(F.getName().size());
1558 Vals.push_back(VE.getTypeID(F.getFunctionType()));
1559 Vals.push_back(F.getCallingConv());
1560 Vals.push_back(F.isDeclaration());
1562 Vals.push_back(VE.getAttributeListID(F.getAttributes()));
1563 Vals.push_back(getEncodedAlign(F.getAlign()));
1564 Vals.push_back(F.hasSection() ? SectionMap[std::string(F.getSection())]
1565 : 0);
1567 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
1569 Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
1570 : 0);
1572 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
1573 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
1574 : 0);
1575 Vals.push_back(
1576 F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
1577
1578 Vals.push_back(F.isDSOLocal());
1579 Vals.push_back(F.getAddressSpace());
1580 Vals.push_back(addToStrtab(F.getPartition()));
1581 Vals.push_back(F.getPartition().size());
1582
1583 unsigned AbbrevToUse = 0;
1584 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
1585 Vals.clear();
1586 }
1587
1588 // Emit the alias information.
1589 for (const GlobalAlias &A : M.aliases()) {
1590 // ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage,
1591 // visibility, dllstorageclass, threadlocal, unnamed_addr,
1592 // DSO_Local]
1593 Vals.push_back(addToStrtab(A.getName()));
1594 Vals.push_back(A.getName().size());
1595 Vals.push_back(VE.getTypeID(A.getValueType()));
1596 Vals.push_back(A.getType()->getAddressSpace());
1597 Vals.push_back(VE.getValueID(A.getAliasee()));
1603 Vals.push_back(A.isDSOLocal());
1604 Vals.push_back(addToStrtab(A.getPartition()));
1605 Vals.push_back(A.getPartition().size());
1606
1607 unsigned AbbrevToUse = 0;
1608 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
1609 Vals.clear();
1610 }
1611
1612 // Emit the ifunc information.
1613 for (const GlobalIFunc &I : M.ifuncs()) {
1614 // IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver
1615 // val#, linkage, visibility, DSO_Local]
1616 Vals.push_back(addToStrtab(I.getName()));
1617 Vals.push_back(I.getName().size());
1618 Vals.push_back(VE.getTypeID(I.getValueType()));
1619 Vals.push_back(I.getType()->getAddressSpace());
1620 Vals.push_back(VE.getValueID(I.getResolver()));
1623 Vals.push_back(I.isDSOLocal());
1624 Vals.push_back(addToStrtab(I.getPartition()));
1625 Vals.push_back(I.getPartition().size());
1626 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
1627 Vals.clear();
1628 }
1629
1630 writeValueSymbolTableForwardDecl();
1631}
1632
1634 uint64_t Flags = 0;
1635
1636 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
1637 if (OBO->hasNoSignedWrap())
1638 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
1639 if (OBO->hasNoUnsignedWrap())
1640 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
1641 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
1642 if (PEO->isExact())
1643 Flags |= 1 << bitc::PEO_EXACT;
1644 } else if (const auto *PDI = dyn_cast<PossiblyDisjointInst>(V)) {
1645 if (PDI->isDisjoint())
1646 Flags |= 1 << bitc::PDI_DISJOINT;
1647 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
1648 if (FPMO->hasAllowReassoc())
1649 Flags |= bitc::AllowReassoc;
1650 if (FPMO->hasNoNaNs())
1651 Flags |= bitc::NoNaNs;
1652 if (FPMO->hasNoInfs())
1653 Flags |= bitc::NoInfs;
1654 if (FPMO->hasNoSignedZeros())
1655 Flags |= bitc::NoSignedZeros;
1656 if (FPMO->hasAllowReciprocal())
1657 Flags |= bitc::AllowReciprocal;
1658 if (FPMO->hasAllowContract())
1659 Flags |= bitc::AllowContract;
1660 if (FPMO->hasApproxFunc())
1661 Flags |= bitc::ApproxFunc;
1662 } else if (const auto *NNI = dyn_cast<PossiblyNonNegInst>(V)) {
1663 if (NNI->hasNonNeg())
1664 Flags |= 1 << bitc::PNNI_NON_NEG;
1665 } else if (const auto *TI = dyn_cast<TruncInst>(V)) {
1666 if (TI->hasNoSignedWrap())
1667 Flags |= 1 << bitc::TIO_NO_SIGNED_WRAP;
1668 if (TI->hasNoUnsignedWrap())
1669 Flags |= 1 << bitc::TIO_NO_UNSIGNED_WRAP;
1670 } else if (const auto *GEP = dyn_cast<GEPOperator>(V)) {
1671 if (GEP->isInBounds())
1672 Flags |= 1 << bitc::GEP_INBOUNDS;
1673 if (GEP->hasNoUnsignedSignedWrap())
1674 Flags |= 1 << bitc::GEP_NUSW;
1675 if (GEP->hasNoUnsignedWrap())
1676 Flags |= 1 << bitc::GEP_NUW;
1677 }
1678
1679 return Flags;
1680}
1681
1682void ModuleBitcodeWriter::writeValueAsMetadata(
1684 // Mimic an MDNode with a value as one operand.
1685 Value *V = MD->getValue();
1686 Record.push_back(VE.getTypeID(V->getType()));
1687 Record.push_back(VE.getValueID(V));
1689 Record.clear();
1690}
1691
1692void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N,
1694 unsigned Abbrev) {
1695 for (const MDOperand &MDO : N->operands()) {
1696 Metadata *MD = MDO;
1697 assert(!(MD && isa<LocalAsMetadata>(MD)) &&
1698 "Unexpected function-local metadata");
1699 Record.push_back(VE.getMetadataOrNullID(MD));
1700 }
1701 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
1703 Record, Abbrev);
1704 Record.clear();
1705}
1706
1707unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
1708 // Assume the column is usually under 128, and always output the inlined-at
1709 // location (it's never more expensive than building an array size 1).
1710 auto Abbv = std::make_shared<BitCodeAbbrev>();
1718 return Stream.EmitAbbrev(std::move(Abbv));
1719}
1720
1721void ModuleBitcodeWriter::writeDILocation(const DILocation *N,
1723 unsigned &Abbrev) {
1724 if (!Abbrev)
1725 Abbrev = createDILocationAbbrev();
1726
1727 Record.push_back(N->isDistinct());
1728 Record.push_back(N->getLine());
1729 Record.push_back(N->getColumn());
1730 Record.push_back(VE.getMetadataID(N->getScope()));
1731 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
1732 Record.push_back(N->isImplicitCode());
1733
1734 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
1735 Record.clear();
1736}
1737
1738unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
1739 // Assume the column is usually under 128, and always output the inlined-at
1740 // location (it's never more expensive than building an array size 1).
1741 auto Abbv = std::make_shared<BitCodeAbbrev>();
1749 return Stream.EmitAbbrev(std::move(Abbv));
1750}
1751
1752void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N,
1754 unsigned &Abbrev) {
1755 if (!Abbrev)
1756 Abbrev = createGenericDINodeAbbrev();
1757
1758 Record.push_back(N->isDistinct());
1759 Record.push_back(N->getTag());
1760 Record.push_back(0); // Per-tag version field; unused for now.
1761
1762 for (auto &I : N->operands())
1763 Record.push_back(VE.getMetadataOrNullID(I));
1764
1766 Record.clear();
1767}
1768
1769void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N,
1771 unsigned Abbrev) {
1772 const uint64_t Version = 2 << 1;
1773 Record.push_back((uint64_t)N->isDistinct() | Version);
1774 Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
1775 Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
1776 Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
1777 Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
1778
1779 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
1780 Record.clear();
1781}
1782
1783void ModuleBitcodeWriter::writeDIGenericSubrange(
1785 unsigned Abbrev) {
1786 Record.push_back((uint64_t)N->isDistinct());
1787 Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
1788 Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
1789 Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
1790 Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
1791
1793 Record.clear();
1794}
1795
1796void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,
1798 unsigned Abbrev) {
1799 const uint64_t IsBigInt = 1 << 2;
1800 Record.push_back(IsBigInt | (N->isUnsigned() << 1) | N->isDistinct());
1801 Record.push_back(N->getValue().getBitWidth());
1802 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1803 emitWideAPInt(Record, N->getValue());
1804
1806 Record.clear();
1807}
1808
1809void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N,
1811 unsigned Abbrev) {
1812 Record.push_back(N->isDistinct());
1813 Record.push_back(N->getTag());
1814 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1815 Record.push_back(N->getSizeInBits());
1816 Record.push_back(N->getAlignInBits());
1817 Record.push_back(N->getEncoding());
1818 Record.push_back(N->getFlags());
1819
1821 Record.clear();
1822}
1823
1824void ModuleBitcodeWriter::writeDIStringType(const DIStringType *N,
1826 unsigned Abbrev) {
1827 Record.push_back(N->isDistinct());
1828 Record.push_back(N->getTag());
1829 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1830 Record.push_back(VE.getMetadataOrNullID(N->getStringLength()));
1831 Record.push_back(VE.getMetadataOrNullID(N->getStringLengthExp()));
1832 Record.push_back(VE.getMetadataOrNullID(N->getStringLocationExp()));
1833 Record.push_back(N->getSizeInBits());
1834 Record.push_back(N->getAlignInBits());
1835 Record.push_back(N->getEncoding());
1836
1838 Record.clear();
1839}
1840
1841void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,
1843 unsigned Abbrev) {
1844 Record.push_back(N->isDistinct());
1845 Record.push_back(N->getTag());
1846 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1847 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1848 Record.push_back(N->getLine());
1849 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1850 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1851 Record.push_back(N->getSizeInBits());
1852 Record.push_back(N->getAlignInBits());
1853 Record.push_back(N->getOffsetInBits());
1854 Record.push_back(N->getFlags());
1855 Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
1856
1857 // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
1858 // that there is no DWARF address space associated with DIDerivedType.
1859 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
1860 Record.push_back(*DWARFAddressSpace + 1);
1861 else
1862 Record.push_back(0);
1863
1864 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
1865
1866 if (auto PtrAuthData = N->getPtrAuthData())
1867 Record.push_back(PtrAuthData->RawData);
1868 else
1869 Record.push_back(0);
1870
1872 Record.clear();
1873}
1874
1875void ModuleBitcodeWriter::writeDICompositeType(
1877 unsigned Abbrev) {
1878 const unsigned IsNotUsedInOldTypeRef = 0x2;
1879 Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct());
1880 Record.push_back(N->getTag());
1881 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1882 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1883 Record.push_back(N->getLine());
1884 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1885 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1886 Record.push_back(N->getSizeInBits());
1887 Record.push_back(N->getAlignInBits());
1888 Record.push_back(N->getOffsetInBits());
1889 Record.push_back(N->getFlags());
1890 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1891 Record.push_back(N->getRuntimeLang());
1892 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
1893 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1894 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
1895 Record.push_back(VE.getMetadataOrNullID(N->getDiscriminator()));
1896 Record.push_back(VE.getMetadataOrNullID(N->getRawDataLocation()));
1897 Record.push_back(VE.getMetadataOrNullID(N->getRawAssociated()));
1898 Record.push_back(VE.getMetadataOrNullID(N->getRawAllocated()));
1899 Record.push_back(VE.getMetadataOrNullID(N->getRawRank()));
1900 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
1901
1903 Record.clear();
1904}
1905
1906void ModuleBitcodeWriter::writeDISubroutineType(
1908 unsigned Abbrev) {
1909 const unsigned HasNoOldTypeRefs = 0x2;
1910 Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
1911 Record.push_back(N->getFlags());
1912 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
1913 Record.push_back(N->getCC());
1914
1916 Record.clear();
1917}
1918
1919void ModuleBitcodeWriter::writeDIFile(const DIFile *N,
1921 unsigned Abbrev) {
1922 Record.push_back(N->isDistinct());
1923 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
1924 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
1925 if (N->getRawChecksum()) {
1926 Record.push_back(N->getRawChecksum()->Kind);
1927 Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()->Value));
1928 } else {
1929 // Maintain backwards compatibility with the old internal representation of
1930 // CSK_None in ChecksumKind by writing nulls here when Checksum is None.
1931 Record.push_back(0);
1932 Record.push_back(VE.getMetadataOrNullID(nullptr));
1933 }
1934 auto Source = N->getRawSource();
1935 if (Source)
1936 Record.push_back(VE.getMetadataOrNullID(Source));
1937
1938 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
1939 Record.clear();
1940}
1941
1942void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
1944 unsigned Abbrev) {
1945 assert(N->isDistinct() && "Expected distinct compile units");
1946 Record.push_back(/* IsDistinct */ true);
1947 Record.push_back(N->getSourceLanguage());
1948 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1949 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
1950 Record.push_back(N->isOptimized());
1951 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
1952 Record.push_back(N->getRuntimeVersion());
1953 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
1954 Record.push_back(N->getEmissionKind());
1955 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
1956 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
1957 Record.push_back(/* subprograms */ 0);
1958 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
1959 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
1960 Record.push_back(N->getDWOId());
1961 Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
1962 Record.push_back(N->getSplitDebugInlining());
1963 Record.push_back(N->getDebugInfoForProfiling());
1964 Record.push_back((unsigned)N->getNameTableKind());
1965 Record.push_back(N->getRangesBaseAddress());
1966 Record.push_back(VE.getMetadataOrNullID(N->getRawSysRoot()));
1967 Record.push_back(VE.getMetadataOrNullID(N->getRawSDK()));
1968
1970 Record.clear();
1971}
1972
1973void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,
1975 unsigned Abbrev) {
1976 const uint64_t HasUnitFlag = 1 << 1;
1977 const uint64_t HasSPFlagsFlag = 1 << 2;
1978 Record.push_back(uint64_t(N->isDistinct()) | HasUnitFlag | HasSPFlagsFlag);
1979 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1980 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1981 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1982 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1983 Record.push_back(N->getLine());
1984 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1985 Record.push_back(N->getScopeLine());
1986 Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
1987 Record.push_back(N->getSPFlags());
1988 Record.push_back(N->getVirtualIndex());
1989 Record.push_back(N->getFlags());
1990 Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
1991 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1992 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
1993 Record.push_back(VE.getMetadataOrNullID(N->getRetainedNodes().get()));
1994 Record.push_back(N->getThisAdjustment());
1995 Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get()));
1996 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
1997 Record.push_back(VE.getMetadataOrNullID(N->getRawTargetFuncName()));
1998
2000 Record.clear();
2001}
2002
2003void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
2005 unsigned Abbrev) {
2006 Record.push_back(N->isDistinct());
2007 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2008 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2009 Record.push_back(N->getLine());
2010 Record.push_back(N->getColumn());
2011
2013 Record.clear();
2014}
2015
2016void ModuleBitcodeWriter::writeDILexicalBlockFile(
2018 unsigned Abbrev) {
2019 Record.push_back(N->isDistinct());
2020 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2021 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2022 Record.push_back(N->getDiscriminator());
2023
2025 Record.clear();
2026}
2027
2028void ModuleBitcodeWriter::writeDICommonBlock(const DICommonBlock *N,
2030 unsigned Abbrev) {
2031 Record.push_back(N->isDistinct());
2032 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2033 Record.push_back(VE.getMetadataOrNullID(N->getDecl()));
2034 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2035 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2036 Record.push_back(N->getLineNo());
2037
2039 Record.clear();
2040}
2041
2042void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,
2044 unsigned Abbrev) {
2045 Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
2046 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2047 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2048
2050 Record.clear();
2051}
2052
2053void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,
2055 unsigned Abbrev) {
2056 Record.push_back(N->isDistinct());
2057 Record.push_back(N->getMacinfoType());
2058 Record.push_back(N->getLine());
2059 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2060 Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
2061
2062 Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
2063 Record.clear();
2064}
2065
2066void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,
2068 unsigned Abbrev) {
2069 Record.push_back(N->isDistinct());
2070 Record.push_back(N->getMacinfoType());
2071 Record.push_back(N->getLine());
2072 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2073 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
2074
2076 Record.clear();
2077}
2078
2079void ModuleBitcodeWriter::writeDIArgList(const DIArgList *N,
2081 Record.reserve(N->getArgs().size());
2082 for (ValueAsMetadata *MD : N->getArgs())
2083 Record.push_back(VE.getMetadataID(MD));
2084
2086 Record.clear();
2087}
2088
2089void ModuleBitcodeWriter::writeDIModule(const DIModule *N,
2091 unsigned Abbrev) {
2092 Record.push_back(N->isDistinct());
2093 for (auto &I : N->operands())
2094 Record.push_back(VE.getMetadataOrNullID(I));
2095 Record.push_back(N->getLineNo());
2096 Record.push_back(N->getIsDecl());
2097
2098 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
2099 Record.clear();
2100}
2101
2102void ModuleBitcodeWriter::writeDIAssignID(const DIAssignID *N,
2104 unsigned Abbrev) {
2105 // There are no arguments for this metadata type.
2106 Record.push_back(N->isDistinct());
2108 Record.clear();
2109}
2110
2111void ModuleBitcodeWriter::writeDITemplateTypeParameter(
2113 unsigned Abbrev) {
2114 Record.push_back(N->isDistinct());
2115 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2116 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2117 Record.push_back(N->isDefault());
2118
2120 Record.clear();
2121}
2122
2123void ModuleBitcodeWriter::writeDITemplateValueParameter(
2125 unsigned Abbrev) {
2126 Record.push_back(N->isDistinct());
2127 Record.push_back(N->getTag());
2128 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2129 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2130 Record.push_back(N->isDefault());
2131 Record.push_back(VE.getMetadataOrNullID(N->getValue()));
2132
2134 Record.clear();
2135}
2136
2137void ModuleBitcodeWriter::writeDIGlobalVariable(
2139 unsigned Abbrev) {
2140 const uint64_t Version = 2 << 1;
2141 Record.push_back((uint64_t)N->isDistinct() | Version);
2142 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2143 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2144 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
2145 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2146 Record.push_back(N->getLine());
2147 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2148 Record.push_back(N->isLocalToUnit());
2149 Record.push_back(N->isDefinition());
2150 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
2151 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams()));
2152 Record.push_back(N->getAlignInBits());
2153 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2154
2156 Record.clear();
2157}
2158
2159void ModuleBitcodeWriter::writeDILocalVariable(
2161 unsigned Abbrev) {
2162 // In order to support all possible bitcode formats in BitcodeReader we need
2163 // to distinguish the following cases:
2164 // 1) Record has no artificial tag (Record[1]),
2165 // has no obsolete inlinedAt field (Record[9]).
2166 // In this case Record size will be 8, HasAlignment flag is false.
2167 // 2) Record has artificial tag (Record[1]),
2168 // has no obsolete inlignedAt field (Record[9]).
2169 // In this case Record size will be 9, HasAlignment flag is false.
2170 // 3) Record has both artificial tag (Record[1]) and
2171 // obsolete inlignedAt field (Record[9]).
2172 // In this case Record size will be 10, HasAlignment flag is false.
2173 // 4) Record has neither artificial tag, nor inlignedAt field, but
2174 // HasAlignment flag is true and Record[8] contains alignment value.
2175 const uint64_t HasAlignmentFlag = 1 << 1;
2176 Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
2177 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2178 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2179 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2180 Record.push_back(N->getLine());
2181 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2182 Record.push_back(N->getArg());
2183 Record.push_back(N->getFlags());
2184 Record.push_back(N->getAlignInBits());
2185 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2186
2188 Record.clear();
2189}
2190
2191void ModuleBitcodeWriter::writeDILabel(
2193 unsigned Abbrev) {
2194 Record.push_back((uint64_t)N->isDistinct());
2195 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2196 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2197 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2198 Record.push_back(N->getLine());
2199
2200 Stream.EmitRecord(bitc::METADATA_LABEL, Record, Abbrev);
2201 Record.clear();
2202}
2203
2204void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,
2206 unsigned Abbrev) {
2207 Record.reserve(N->getElements().size() + 1);
2208 const uint64_t Version = 3 << 1;
2209 Record.push_back((uint64_t)N->isDistinct() | Version);
2210 Record.append(N->elements_begin(), N->elements_end());
2211
2213 Record.clear();
2214}
2215
2216void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
2218 unsigned Abbrev) {
2219 Record.push_back(N->isDistinct());
2220 Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
2221 Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
2222
2224 Record.clear();
2225}
2226
2227void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
2229 unsigned Abbrev) {
2230 Record.push_back(N->isDistinct());
2231 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2232 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2233 Record.push_back(N->getLine());
2234 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
2235 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
2236 Record.push_back(N->getAttributes());
2237 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2238
2240 Record.clear();
2241}
2242
2243void ModuleBitcodeWriter::writeDIImportedEntity(
2245 unsigned Abbrev) {
2246 Record.push_back(N->isDistinct());
2247 Record.push_back(N->getTag());
2248 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2249 Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
2250 Record.push_back(N->getLine());
2251 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2252 Record.push_back(VE.getMetadataOrNullID(N->getRawFile()));
2253 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
2254
2256 Record.clear();
2257}
2258
2259unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
2260 auto Abbv = std::make_shared<BitCodeAbbrev>();
2264 return Stream.EmitAbbrev(std::move(Abbv));
2265}
2266
2267void ModuleBitcodeWriter::writeNamedMetadata(
2269 if (M.named_metadata_empty())
2270 return;
2271
2272 unsigned Abbrev = createNamedMetadataAbbrev();
2273 for (const NamedMDNode &NMD : M.named_metadata()) {
2274 // Write name.
2275 StringRef Str = NMD.getName();
2276 Record.append(Str.bytes_begin(), Str.bytes_end());
2277 Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
2278 Record.clear();
2279
2280 // Write named metadata operands.
2281 for (const MDNode *N : NMD.operands())
2282 Record.push_back(VE.getMetadataID(N));
2284 Record.clear();
2285 }
2286}
2287
2288unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
2289 auto Abbv = std::make_shared<BitCodeAbbrev>();
2291 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
2292 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
2294 return Stream.EmitAbbrev(std::move(Abbv));
2295}
2296
2297/// Write out a record for MDString.
2298///
2299/// All the metadata strings in a metadata block are emitted in a single
2300/// record. The sizes and strings themselves are shoved into a blob.
2301void ModuleBitcodeWriter::writeMetadataStrings(
2303 if (Strings.empty())
2304 return;
2305
2306 // Start the record with the number of strings.
2307 Record.push_back(bitc::METADATA_STRINGS);
2308 Record.push_back(Strings.size());
2309
2310 // Emit the sizes of the strings in the blob.
2311 SmallString<256> Blob;
2312 {
2313 BitstreamWriter W(Blob);
2314 for (const Metadata *MD : Strings)
2315 W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
2316 W.FlushToWord();
2317 }
2318
2319 // Add the offset to the strings to the record.
2320 Record.push_back(Blob.size());
2321
2322 // Add the strings to the blob.
2323 for (const Metadata *MD : Strings)
2324 Blob.append(cast<MDString>(MD)->getString());
2325
2326 // Emit the final record.
2327 Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
2328 Record.clear();
2329}
2330
2331// Generates an enum to use as an index in the Abbrev array of Metadata record.
2332enum MetadataAbbrev : unsigned {
2333#define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
2334#include "llvm/IR/Metadata.def"
2337
2338void ModuleBitcodeWriter::writeMetadataRecords(
2340 std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
2341 if (MDs.empty())
2342 return;
2343
2344 // Initialize MDNode abbreviations.
2345#define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
2346#include "llvm/IR/Metadata.def"
2347
2348 for (const Metadata *MD : MDs) {
2349 if (IndexPos)
2350 IndexPos->push_back(Stream.GetCurrentBitNo());
2351 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
2352 assert(N->isResolved() && "Expected forward references to be resolved");
2353
2354 switch (N->getMetadataID()) {
2355 default:
2356 llvm_unreachable("Invalid MDNode subclass");
2357#define HANDLE_MDNODE_LEAF(CLASS) \
2358 case Metadata::CLASS##Kind: \
2359 if (MDAbbrevs) \
2360 write##CLASS(cast<CLASS>(N), Record, \
2361 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
2362 else \
2363 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
2364 continue;
2365#include "llvm/IR/Metadata.def"
2366 }
2367 }
2368 if (auto *AL = dyn_cast<DIArgList>(MD)) {
2370 continue;
2371 }
2372 writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
2373 }
2374}
2375
2376void ModuleBitcodeWriter::writeModuleMetadata() {
2377 if (!VE.hasMDs() && M.named_metadata_empty())
2378 return;
2379
2382
2383 // Emit all abbrevs upfront, so that the reader can jump in the middle of the
2384 // block and load any metadata.
2385 std::vector<unsigned> MDAbbrevs;
2386
2387 MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
2388 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
2389 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
2390 createGenericDINodeAbbrev();
2391
2392 auto Abbv = std::make_shared<BitCodeAbbrev>();
2396 unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2397
2398 Abbv = std::make_shared<BitCodeAbbrev>();
2402 unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2403
2404 // Emit MDStrings together upfront.
2405 writeMetadataStrings(VE.getMDStrings(), Record);
2406
2407 // We only emit an index for the metadata record if we have more than a given
2408 // (naive) threshold of metadatas, otherwise it is not worth it.
2409 if (VE.getNonMDStrings().size() > IndexThreshold) {
2410 // Write a placeholder value in for the offset of the metadata index,
2411 // which is written after the records, so that it can include
2412 // the offset of each entry. The placeholder offset will be
2413 // updated after all records are emitted.
2414 uint64_t Vals[] = {0, 0};
2415 Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
2416 }
2417
2418 // Compute and save the bit offset to the current position, which will be
2419 // patched when we emit the index later. We can simply subtract the 64-bit
2420 // fixed size from the current bit number to get the location to backpatch.
2421 uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
2422
2423 // This index will contain the bitpos for each individual record.
2424 std::vector<uint64_t> IndexPos;
2425 IndexPos.reserve(VE.getNonMDStrings().size());
2426
2427 // Write all the records
2428 writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
2429
2430 if (VE.getNonMDStrings().size() > IndexThreshold) {
2431 // Now that we have emitted all the records we will emit the index. But
2432 // first
2433 // backpatch the forward reference so that the reader can skip the records
2434 // efficiently.
2435 Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
2436 Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
2437
2438 // Delta encode the index.
2439 uint64_t PreviousValue = IndexOffsetRecordBitPos;
2440 for (auto &Elt : IndexPos) {
2441 auto EltDelta = Elt - PreviousValue;
2442 PreviousValue = Elt;
2443 Elt = EltDelta;
2444 }
2445 // Emit the index record.
2446 Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
2447 IndexPos.clear();
2448 }
2449
2450 // Write the named metadata now.
2451 writeNamedMetadata(Record);
2452
2453 auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
2455 Record.push_back(VE.getValueID(&GO));
2456 pushGlobalMetadataAttachment(Record, GO);
2458 };
2459 for (const Function &F : M)
2460 if (F.isDeclaration() && F.hasMetadata())
2461 AddDeclAttachedMetadata(F);
2462 // FIXME: Only store metadata for declarations here, and move data for global
2463 // variable definitions to a separate block (PR28134).
2464 for (const GlobalVariable &GV : M.globals())
2465 if (GV.hasMetadata())
2466 AddDeclAttachedMetadata(GV);
2467
2468 Stream.ExitBlock();
2469}
2470
2471void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
2472 if (!VE.hasMDs())
2473 return;
2474
2477 writeMetadataStrings(VE.getMDStrings(), Record);
2478 writeMetadataRecords(VE.getNonMDStrings(), Record);
2479 Stream.ExitBlock();
2480}
2481
2482void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
2484 // [n x [id, mdnode]]
2486 GO.getAllMetadata(MDs);
2487 for (const auto &I : MDs) {
2488 Record.push_back(I.first);
2489 Record.push_back(VE.getMetadataID(I.second));
2490 }
2491}
2492
2493void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
2495
2497
2498 if (F.hasMetadata()) {
2499 pushGlobalMetadataAttachment(Record, F);
2501 Record.clear();
2502 }
2503
2504 // Write metadata attachments
2505 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
2507 for (const BasicBlock &BB : F)
2508 for (const Instruction &I : BB) {
2509 MDs.clear();
2510 I.getAllMetadataOtherThanDebugLoc(MDs);
2511
2512 // If no metadata, ignore instruction.
2513 if (MDs.empty()) continue;
2514
2515 Record.push_back(VE.getInstructionID(&I));
2516
2517 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
2518 Record.push_back(MDs[i].first);
2519 Record.push_back(VE.getMetadataID(MDs[i].second));
2520 }
2522 Record.clear();
2523 }
2524
2525 Stream.ExitBlock();
2526}
2527
2528void ModuleBitcodeWriter::writeModuleMetadataKinds() {
2530
2531 // Write metadata kinds
2532 // METADATA_KIND - [n x [id, name]]
2534 M.getMDKindNames(Names);
2535
2536 if (Names.empty()) return;
2537
2539
2540 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
2541 Record.push_back(MDKindID);
2542 StringRef KName = Names[MDKindID];
2543 Record.append(KName.begin(), KName.end());
2544
2546 Record.clear();
2547 }
2548
2549 Stream.ExitBlock();
2550}
2551
2552void ModuleBitcodeWriter::writeOperandBundleTags() {
2553 // Write metadata kinds
2554 //
2555 // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
2556 //
2557 // OPERAND_BUNDLE_TAG - [strchr x N]
2558
2560 M.getOperandBundleTags(Tags);
2561
2562 if (Tags.empty())
2563 return;
2564
2566
2568
2569 for (auto Tag : Tags) {
2570 Record.append(Tag.begin(), Tag.end());
2571
2573 Record.clear();
2574 }
2575
2576 Stream.ExitBlock();
2577}
2578
2579void ModuleBitcodeWriter::writeSyncScopeNames() {
2581 M.getContext().getSyncScopeNames(SSNs);
2582 if (SSNs.empty())
2583 return;
2584
2586
2588 for (auto SSN : SSNs) {
2589 Record.append(SSN.begin(), SSN.end());
2591 Record.clear();
2592 }
2593
2594 Stream.ExitBlock();
2595}
2596
2597void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
2598 bool isGlobal) {
2599 if (FirstVal == LastVal) return;
2600
2602
2603 unsigned AggregateAbbrev = 0;
2604 unsigned String8Abbrev = 0;
2605 unsigned CString7Abbrev = 0;
2606 unsigned CString6Abbrev = 0;
2607 // If this is a constant pool for the module, emit module-specific abbrevs.
2608 if (isGlobal) {
2609 // Abbrev for CST_CODE_AGGREGATE.
2610 auto Abbv = std::make_shared<BitCodeAbbrev>();
2613 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
2614 AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2615
2616 // Abbrev for CST_CODE_STRING.
2617 Abbv = std::make_shared<BitCodeAbbrev>();
2621 String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2622 // Abbrev for CST_CODE_CSTRING.
2623 Abbv = std::make_shared<BitCodeAbbrev>();
2627 CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2628 // Abbrev for CST_CODE_CSTRING.
2629 Abbv = std::make_shared<BitCodeAbbrev>();
2633 CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2634 }
2635
2637
2638 const ValueEnumerator::ValueList &Vals = VE.getValues();
2639 Type *LastTy = nullptr;
2640 for (unsigned i = FirstVal; i != LastVal; ++i) {
2641 const Value *V = Vals[i].first;
2642 // If we need to switch types, do so now.
2643 if (V->getType() != LastTy) {
2644 LastTy = V->getType();
2645 Record.push_back(VE.getTypeID(LastTy));
2647 CONSTANTS_SETTYPE_ABBREV);
2648 Record.clear();
2649 }
2650
2651 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
2652 Record.push_back(VE.getTypeID(IA->getFunctionType()));
2653 Record.push_back(
2654 unsigned(IA->hasSideEffects()) | unsigned(IA->isAlignStack()) << 1 |
2655 unsigned(IA->getDialect() & 1) << 2 | unsigned(IA->canThrow()) << 3);
2656
2657 // Add the asm string.
2658 const std::string &AsmStr = IA->getAsmString();
2659 Record.push_back(AsmStr.size());
2660 Record.append(AsmStr.begin(), AsmStr.end());
2661
2662 // Add the constraint string.
2663 const std::string &ConstraintStr = IA->getConstraintString();
2664 Record.push_back(ConstraintStr.size());
2665 Record.append(ConstraintStr.begin(), ConstraintStr.end());
2667 Record.clear();
2668 continue;
2669 }
2670 const Constant *C = cast<Constant>(V);
2671 unsigned Code = -1U;
2672 unsigned AbbrevToUse = 0;
2673 if (C->isNullValue()) {
2675 } else if (isa<PoisonValue>(C)) {
2677 } else if (isa<UndefValue>(C)) {
2679 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
2680 if (IV->getBitWidth() <= 64) {
2681 uint64_t V = IV->getSExtValue();
2684 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
2685 } else { // Wide integers, > 64 bits in size.
2686 emitWideAPInt(Record, IV->getValue());
2688 }
2689 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
2691 Type *Ty = CFP->getType()->getScalarType();
2692 if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() ||
2693 Ty->isDoubleTy()) {
2694 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
2695 } else if (Ty->isX86_FP80Ty()) {
2696 // api needed to prevent premature destruction
2697 // bits are not in the same order as a normal i80 APInt, compensate.
2698 APInt api = CFP->getValueAPF().bitcastToAPInt();
2699 const uint64_t *p = api.getRawData();
2700 Record.push_back((p[1] << 48) | (p[0] >> 16));
2701 Record.push_back(p[0] & 0xffffLL);
2702 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
2703 APInt api = CFP->getValueAPF().bitcastToAPInt();
2704 const uint64_t *p = api.getRawData();
2705 Record.push_back(p[0]);
2706 Record.push_back(p[1]);
2707 } else {
2708 assert(0 && "Unknown FP type!");
2709 }
2710 } else if (isa<ConstantDataSequential>(C) &&
2711 cast<ConstantDataSequential>(C)->isString()) {
2712 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
2713 // Emit constant strings specially.
2714 unsigned NumElts = Str->getNumElements();
2715 // If this is a null-terminated string, use the denser CSTRING encoding.
2716 if (Str->isCString()) {
2718 --NumElts; // Don't encode the null, which isn't allowed by char6.
2719 } else {
2721 AbbrevToUse = String8Abbrev;
2722 }
2723 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
2724 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
2725 for (unsigned i = 0; i != NumElts; ++i) {
2726 unsigned char V = Str->getElementAsInteger(i);
2727 Record.push_back(V);
2728 isCStr7 &= (V & 128) == 0;
2729 if (isCStrChar6)
2730 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
2731 }
2732
2733 if (isCStrChar6)
2734 AbbrevToUse = CString6Abbrev;
2735 else if (isCStr7)
2736 AbbrevToUse = CString7Abbrev;
2737 } else if (const ConstantDataSequential *CDS =
2738 dyn_cast<ConstantDataSequential>(C)) {
2740 Type *EltTy = CDS->getElementType();
2741 if (isa<IntegerType>(EltTy)) {
2742 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2743 Record.push_back(CDS->getElementAsInteger(i));
2744 } else {
2745 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2746 Record.push_back(
2747 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
2748 }
2749 } else if (isa<ConstantAggregate>(C)) {
2751 for (const Value *Op : C->operands())
2752 Record.push_back(VE.getValueID(Op));
2753 AbbrevToUse = AggregateAbbrev;
2754 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2755 switch (CE->getOpcode()) {
2756 default:
2757 if (Instruction::isCast(CE->getOpcode())) {
2759 Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
2760 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2761 Record.push_back(VE.getValueID(C->getOperand(0)));
2762 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
2763 } else {
2764 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
2766 Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
2767 Record.push_back(VE.getValueID(C->getOperand(0)));
2768 Record.push_back(VE.getValueID(C->getOperand(1)));
2770 if (Flags != 0)
2771 Record.push_back(Flags);
2772 }
2773 break;
2774 case Instruction::FNeg: {
2775 assert(CE->getNumOperands() == 1 && "Unknown constant expr!");
2777 Record.push_back(getEncodedUnaryOpcode(CE->getOpcode()));
2778 Record.push_back(VE.getValueID(C->getOperand(0)));
2780 if (Flags != 0)
2781 Record.push_back(Flags);
2782 break;
2783 }
2784 case Instruction::GetElementPtr: {
2786 const auto *GO = cast<GEPOperator>(C);
2787 Record.push_back(VE.getTypeID(GO->getSourceElementType()));
2788 Record.push_back(getOptimizationFlags(GO));
2789 if (std::optional<ConstantRange> Range = GO->getInRange()) {
2792 }
2793 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
2794 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
2795 Record.push_back(VE.getValueID(C->getOperand(i)));
2796 }
2797 break;
2798 }
2799 case Instruction::ExtractElement:
2801 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2802 Record.push_back(VE.getValueID(C->getOperand(0)));
2803 Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
2804 Record.push_back(VE.getValueID(C->getOperand(1)));
2805 break;
2806 case Instruction::InsertElement:
2808 Record.push_back(VE.getValueID(C->getOperand(0)));
2809 Record.push_back(VE.getValueID(C->getOperand(1)));
2810 Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
2811 Record.push_back(VE.getValueID(C->getOperand(2)));
2812 break;
2813 case Instruction::ShuffleVector:
2814 // If the return type and argument types are the same, this is a
2815 // standard shufflevector instruction. If the types are different,
2816 // then the shuffle is widening or truncating the input vectors, and
2817 // the argument type must also be encoded.
2818 if (C->getType() == C->getOperand(0)->getType()) {
2820 } else {
2822 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2823 }
2824 Record.push_back(VE.getValueID(C->getOperand(0)));
2825 Record.push_back(VE.getValueID(C->getOperand(1)));
2826 Record.push_back(VE.getValueID(CE->getShuffleMaskForBitcode()));
2827 break;
2828 }
2829 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
2831 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
2832 Record.push_back(VE.getValueID(BA->getFunction()));
2833 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
2834 } else if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) {
2836 Record.push_back(VE.getTypeID(Equiv->getGlobalValue()->getType()));
2837 Record.push_back(VE.getValueID(Equiv->getGlobalValue()));
2838 } else if (const auto *NC = dyn_cast<NoCFIValue>(C)) {
2840 Record.push_back(VE.getTypeID(NC->getGlobalValue()->getType()));
2841 Record.push_back(VE.getValueID(NC->getGlobalValue()));
2842 } else if (const auto *CPA = dyn_cast<ConstantPtrAuth>(C)) {
2844 Record.push_back(VE.getValueID(CPA->getPointer()));
2845 Record.push_back(VE.getValueID(CPA->getKey()));
2846 Record.push_back(VE.getValueID(CPA->getDiscriminator()));
2847 Record.push_back(VE.getValueID(CPA->getAddrDiscriminator()));
2848 } else {
2849#ifndef NDEBUG
2850 C->dump();
2851#endif
2852 llvm_unreachable("Unknown constant!");
2853 }
2854 Stream.EmitRecord(Code, Record, AbbrevToUse);
2855 Record.clear();
2856 }
2857
2858 Stream.ExitBlock();
2859}
2860
2861void ModuleBitcodeWriter::writeModuleConstants() {
2862 const ValueEnumerator::ValueList &Vals = VE.getValues();
2863
2864 // Find the first constant to emit, which is the first non-globalvalue value.
2865 // We know globalvalues have been emitted by WriteModuleInfo.
2866 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
2867 if (!isa<GlobalValue>(Vals[i].first)) {
2868 writeConstants(i, Vals.size(), true);
2869 return;
2870 }
2871 }
2872}
2873
2874/// pushValueAndType - The file has to encode both the value and type id for
2875/// many values, because we need to know what type to create for forward
2876/// references. However, most operands are not forward references, so this type
2877/// field is not needed.
2878///
2879/// This function adds V's value ID to Vals. If the value ID is higher than the
2880/// instruction ID, then it is a forward reference, and it also includes the
2881/// type ID. The value ID that is written is encoded relative to the InstID.
2882bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
2884 unsigned ValID = VE.getValueID(V);
2885 // Make encoding relative to the InstID.
2886 Vals.push_back(InstID - ValID);
2887 if (ValID >= InstID) {
2888 Vals.push_back(VE.getTypeID(V->getType()));
2889 return true;
2890 }
2891 return false;
2892}
2893
2894void ModuleBitcodeWriter::writeOperandBundles(const CallBase &CS,
2895 unsigned InstID) {
2897 LLVMContext &C = CS.getContext();
2898
2899 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
2900 const auto &Bundle = CS.getOperandBundleAt(i);
2901 Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
2902
2903 for (auto &Input : Bundle.Inputs)
2904 pushValueAndType(Input, InstID, Record);
2905
2907 Record.clear();
2908 }
2909}
2910
2911/// pushValue - Like pushValueAndType, but where the type of the value is
2912/// omitted (perhaps it was already encoded in an earlier operand).
2913void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
2915 unsigned ValID = VE.getValueID(V);
2916 Vals.push_back(InstID - ValID);
2917}
2918
2919void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
2921 unsigned ValID = VE.getValueID(V);
2922 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
2923 emitSignedInt64(Vals, diff);
2924}
2925
2926/// WriteInstruction - Emit an instruction to the specified stream.
2927void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
2928 unsigned InstID,
2930 unsigned Code = 0;
2931 unsigned AbbrevToUse = 0;
2932 VE.setInstructionID(&I);
2933 switch (I.getOpcode()) {
2934 default:
2935 if (Instruction::isCast(I.getOpcode())) {
2937 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2938 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
2939 Vals.push_back(VE.getTypeID(I.getType()));
2940 Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
2942 if (Flags != 0) {
2943 if (AbbrevToUse == FUNCTION_INST_CAST_ABBREV)
2944 AbbrevToUse = FUNCTION_INST_CAST_FLAGS_ABBREV;
2945 Vals.push_back(Flags);
2946 }
2947 } else {
2948 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
2950 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2951 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
2952 pushValue(I.getOperand(1), InstID, Vals);
2953 Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
2955 if (Flags != 0) {
2956 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
2957 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
2958 Vals.push_back(Flags);
2959 }
2960 }
2961 break;
2962 case Instruction::FNeg: {
2964 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2965 AbbrevToUse = FUNCTION_INST_UNOP_ABBREV;
2966 Vals.push_back(getEncodedUnaryOpcode(I.getOpcode()));
2968 if (Flags != 0) {
2969 if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV)
2970 AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV;
2971 Vals.push_back(Flags);
2972 }
2973 break;
2974 }
2975 case Instruction::GetElementPtr: {
2977 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
2978 auto &GEPInst = cast<GetElementPtrInst>(I);
2980 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
2981 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
2982 pushValueAndType(I.getOperand(i), InstID, Vals);
2983 break;
2984 }
2985 case Instruction::ExtractValue: {
2987 pushValueAndType(I.getOperand(0), InstID, Vals);
2988 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
2989 Vals.append(EVI->idx_begin(), EVI->idx_end());
2990 break;
2991 }
2992 case Instruction::InsertValue: {
2994 pushValueAndType(I.getOperand(0), InstID, Vals);
2995 pushValueAndType(I.getOperand(1), InstID, Vals);
2996 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
2997 Vals.append(IVI->idx_begin(), IVI->idx_end());
2998 break;
2999 }
3000 case Instruction::Select: {
3002 pushValueAndType(I.getOperand(1), InstID, Vals);
3003 pushValue(I.getOperand(2), InstID, Vals);
3004 pushValueAndType(I.getOperand(0), InstID, Vals);
3006 if (Flags != 0)
3007 Vals.push_back(Flags);
3008 break;
3009 }
3010 case Instruction::ExtractElement:
3012 pushValueAndType(I.getOperand(0), InstID, Vals);
3013 pushValueAndType(I.getOperand(1), InstID, Vals);
3014 break;
3015 case Instruction::InsertElement:
3017 pushValueAndType(I.getOperand(0), InstID, Vals);
3018 pushValue(I.getOperand(1), InstID, Vals);
3019 pushValueAndType(I.getOperand(2), InstID, Vals);
3020 break;
3021 case Instruction::ShuffleVector:
3023 pushValueAndType(I.getOperand(0), InstID, Vals);
3024 pushValue(I.getOperand(1), InstID, Vals);
3025 pushValue(cast<ShuffleVectorInst>(I).getShuffleMaskForBitcode(), InstID,
3026 Vals);
3027 break;
3028 case Instruction::ICmp:
3029 case Instruction::FCmp: {
3030 // compare returning Int1Ty or vector of Int1Ty
3032 pushValueAndType(I.getOperand(0), InstID, Vals);
3033 pushValue(I.getOperand(1), InstID, Vals);
3034 Vals.push_back(cast<CmpInst>(I).getPredicate());
3036 if (Flags != 0)
3037 Vals.push_back(Flags);
3038 break;
3039 }
3040
3041 case Instruction::Ret:
3042 {
3044 unsigned NumOperands = I.getNumOperands();
3045 if (NumOperands == 0)
3046 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
3047 else if (NumOperands == 1) {
3048 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
3049 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
3050 } else {
3051 for (unsigned i = 0, e = NumOperands; i != e; ++i)
3052 pushValueAndType(I.getOperand(i), InstID, Vals);
3053 }
3054 }
3055 break;
3056 case Instruction::Br:
3057 {
3059 const BranchInst &II = cast<BranchInst>(I);
3060 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
3061 if (II.isConditional()) {
3062 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
3063 pushValue(II.getCondition(), InstID, Vals);
3064 }
3065 }
3066 break;
3067 case Instruction::Switch:
3068 {
3070 const SwitchInst &SI = cast<SwitchInst>(I);
3071 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
3072 pushValue(SI.getCondition(), InstID, Vals);
3073 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
3074 for (auto Case : SI.cases()) {
3075 Vals.push_back(VE.getValueID(Case.getCaseValue()));
3076 Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
3077 }
3078 }
3079 break;
3080 case Instruction::IndirectBr:
3082 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
3083 // Encode the address operand as relative, but not the basic blocks.
3084 pushValue(I.getOperand(0), InstID, Vals);
3085 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
3086 Vals.push_back(VE.getValueID(I.getOperand(i)));
3087 break;
3088
3089 case Instruction::Invoke: {
3090 const InvokeInst *II = cast<InvokeInst>(&I);
3091 const Value *Callee = II->getCalledOperand();
3092 FunctionType *FTy = II->getFunctionType();
3093
3094 if (II->hasOperandBundles())
3095 writeOperandBundles(*II, InstID);
3096
3098
3099 Vals.push_back(VE.getAttributeListID(II->getAttributes()));
3100 Vals.push_back(II->getCallingConv() | 1 << 13);
3101 Vals.push_back(VE.getValueID(II->getNormalDest()));
3102 Vals.push_back(VE.getValueID(II->getUnwindDest()));
3103 Vals.push_back(VE.getTypeID(FTy));
3104 pushValueAndType(Callee, InstID, Vals);
3105
3106 // Emit value #'s for the fixed parameters.
3107 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3108 pushValue(I.getOperand(i), InstID, Vals); // fixed param.
3109
3110 // Emit type/value pairs for varargs params.
3111 if (FTy->isVarArg()) {
3112 for (unsigned i = FTy->getNumParams(), e = II->arg_size(); i != e; ++i)
3113 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
3114 }
3115 break;
3116 }
3117 case Instruction::Resume:
3119 pushValueAndType(I.getOperand(0), InstID, Vals);
3120 break;
3121 case Instruction::CleanupRet: {
3123 const auto &CRI = cast<CleanupReturnInst>(I);
3124 pushValue(CRI.getCleanupPad(), InstID, Vals);
3125 if (CRI.hasUnwindDest())
3126 Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
3127 break;
3128 }
3129 case Instruction::CatchRet: {
3131 const auto &CRI = cast<CatchReturnInst>(I);
3132 pushValue(CRI.getCatchPad(), InstID, Vals);
3133 Vals.push_back(VE.getValueID(CRI.getSuccessor()));
3134 break;
3135 }
3136 case Instruction::CleanupPad:
3137 case Instruction::CatchPad: {
3138 const auto &FuncletPad = cast<FuncletPadInst>(I);
3139 Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
3141 pushValue(FuncletPad.getParentPad(), InstID, Vals);
3142
3143 unsigned NumArgOperands = FuncletPad.arg_size();
3144 Vals.push_back(NumArgOperands);
3145 for (unsigned Op = 0; Op != NumArgOperands; ++Op)
3146 pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
3147 break;
3148 }
3149 case Instruction::CatchSwitch: {
3151 const auto &CatchSwitch = cast<CatchSwitchInst>(I);
3152
3153 pushValue(CatchSwitch.getParentPad(), InstID, Vals);
3154
3155 unsigned NumHandlers = CatchSwitch.getNumHandlers();
3156 Vals.push_back(NumHandlers);
3157 for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
3158 Vals.push_back(VE.getValueID(CatchPadBB));
3159
3160 if (CatchSwitch.hasUnwindDest())
3161 Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
3162 break;
3163 }
3164 case Instruction::CallBr: {
3165 const CallBrInst *CBI = cast<CallBrInst>(&I);
3166 const Value *Callee = CBI->getCalledOperand();
3167 FunctionType *FTy = CBI->getFunctionType();
3168
3169 if (CBI->hasOperandBundles())
3170 writeOperandBundles(*CBI, InstID);
3171
3173
3175
3178
3179 Vals.push_back(VE.getValueID(CBI->getDefaultDest()));
3180 Vals.push_back(CBI->getNumIndirectDests());
3181 for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i)
3182 Vals.push_back(VE.getValueID(CBI->getIndirectDest(i)));
3183
3184 Vals.push_back(VE.getTypeID(FTy));
3185 pushValueAndType(Callee, InstID, Vals);
3186
3187 // Emit value #'s for the fixed parameters.
3188 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3189 pushValue(I.getOperand(i), InstID, Vals); // fixed param.
3190
3191 // Emit type/value pairs for varargs params.
3192 if (FTy->isVarArg()) {
3193 for (unsigned i = FTy->getNumParams(), e = CBI->arg_size(); i != e; ++i)
3194 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
3195 }
3196 break;
3197 }
3198 case Instruction::Unreachable:
3200 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
3201 break;
3202
3203 case Instruction::PHI: {
3204 const PHINode &PN = cast<PHINode>(I);
3206 // With the newer instruction encoding, forward references could give
3207 // negative valued IDs. This is most common for PHIs, so we use
3208 // signed VBRs.
3210 Vals64.push_back(VE.getTypeID(PN.getType()));
3211 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
3212 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
3213 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
3214 }
3215
3217 if (Flags != 0)
3218 Vals64.push_back(Flags);
3219
3220 // Emit a Vals64 vector and exit.
3221 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
3222 Vals64.clear();
3223 return;
3224 }
3225
3226 case Instruction::LandingPad: {
3227 const LandingPadInst &LP = cast<LandingPadInst>(I);
3229 Vals.push_back(VE.getTypeID(LP.getType()));
3230 Vals.push_back(LP.isCleanup());
3231 Vals.push_back(LP.getNumClauses());
3232 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
3233 if (LP.isCatch(I))
3235 else
3237 pushValueAndType(LP.getClause(I), InstID, Vals);
3238 }
3239 break;
3240 }
3241
3242 case Instruction::Alloca: {
3244 const AllocaInst &AI = cast<AllocaInst>(I);
3245 Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
3246 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
3247 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
3248 using APV = AllocaPackedValues;
3249 unsigned Record = 0;
3250 unsigned EncodedAlign = getEncodedAlign(AI.getAlign());
3251 Bitfield::set<APV::AlignLower>(
3252 Record, EncodedAlign & ((1 << APV::AlignLower::Bits) - 1));
3253 Bitfield::set<APV::AlignUpper>(Record,
3254 EncodedAlign >> APV::AlignLower::Bits);
3255 Bitfield::set<APV::UsedWithInAlloca>(Record, AI.isUsedWithInAlloca());
3256 Bitfield::set<APV::ExplicitType>(Record, true);
3257 Bitfield::set<APV::SwiftError>(Record, AI.isSwiftError());
3258 Vals.push_back(Record);
3259
3260 unsigned AS = AI.getAddressSpace();
3261 if (AS != M.getDataLayout().getAllocaAddrSpace())
3262 Vals.push_back(AS);
3263 break;
3264 }
3265
3266 case Instruction::Load:
3267 if (cast<LoadInst>(I).isAtomic()) {
3269 pushValueAndType(I.getOperand(0), InstID, Vals);
3270 } else {
3272 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
3273 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
3274 }
3275 Vals.push_back(VE.getTypeID(I.getType()));
3276 Vals.push_back(getEncodedAlign(cast<LoadInst>(I).getAlign()));
3277 Vals.push_back(cast<LoadInst>(I).isVolatile());
3278 if (cast<LoadInst>(I).isAtomic()) {
3279 Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
3280 Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID()));
3281 }
3282 break;
3283 case Instruction::Store:
3284 if (cast<StoreInst>(I).isAtomic())
3286 else
3288 pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr
3289 pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val
3290 Vals.push_back(getEncodedAlign(cast<StoreInst>(I).getAlign()));
3291 Vals.push_back(cast<StoreInst>(I).isVolatile());
3292 if (cast<StoreInst>(I).isAtomic()) {
3293 Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
3294 Vals.push_back(
3295 getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID()));
3296 }
3297 break;
3298 case Instruction::AtomicCmpXchg:
3300 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
3301 pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
3302 pushValue(I.getOperand(2), InstID, Vals); // newval.
3303 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
3304 Vals.push_back(
3305 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
3306 Vals.push_back(
3307 getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID()));
3308 Vals.push_back(
3309 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
3310 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
3311 Vals.push_back(getEncodedAlign(cast<AtomicCmpXchgInst>(I).getAlign()));
3312 break;
3313 case Instruction::AtomicRMW:
3315 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
3316 pushValueAndType(I.getOperand(1), InstID, Vals); // valty + val
3317 Vals.push_back(
3318 getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
3319 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
3320 Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
3321 Vals.push_back(
3322 getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID()));
3323 Vals.push_back(getEncodedAlign(cast<AtomicRMWInst>(I).getAlign()));
3324 break;
3325 case Instruction::Fence:
3327 Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
3328 Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID()));
3329 break;
3330 case Instruction::Call: {
3331 const CallInst &CI = cast<CallInst>(I);
3332 FunctionType *FTy = CI.getFunctionType();
3333
3334 if (CI.hasOperandBundles())
3335 writeOperandBundles(CI, InstID);
3336
3338
3340
3341 unsigned Flags = getOptimizationFlags(&I);
3343 unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
3344 unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
3346 unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
3347 unsigned(Flags != 0) << bitc::CALL_FMF);
3348 if (Flags != 0)
3349 Vals.push_back(Flags);
3350
3351 Vals.push_back(VE.getTypeID(FTy));
3352 pushValueAndType(CI.getCalledOperand(), InstID, Vals); // Callee
3353
3354 // Emit value #'s for the fixed parameters.
3355 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3356 // Check for labels (can happen with asm labels).
3357 if (FTy->getParamType(i)->isLabelTy())
3358 Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
3359 else
3360 pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
3361 }
3362
3363 // Emit type/value pairs for varargs params.
3364 if (FTy->isVarArg()) {
3365 for (unsigned i = FTy->getNumParams(), e = CI.arg_size(); i != e; ++i)
3366 pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
3367 }
3368 break;
3369 }
3370 case Instruction::VAArg:
3372 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
3373 pushValue(I.getOperand(0), InstID, Vals); // valist.
3374 Vals.push_back(VE.getTypeID(I.getType())); // restype.
3375 break;
3376 case Instruction::Freeze:
3378 pushValueAndType(I.getOperand(0), InstID, Vals);
3379 break;
3380 }
3381
3382 Stream.EmitRecord(Code, Vals, AbbrevToUse);
3383 Vals.clear();
3384}
3385
3386/// Write a GlobalValue VST to the module. The purpose of this data structure is
3387/// to allow clients to efficiently find the function body.
3388void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
3389 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3390 // Get the offset of the VST we are writing, and backpatch it into
3391 // the VST forward declaration record.
3392 uint64_t VSTOffset = Stream.GetCurrentBitNo();
3393 // The BitcodeStartBit was the stream offset of the identification block.
3394 VSTOffset -= bitcodeStartBit();
3395 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
3396 // Note that we add 1 here because the offset is relative to one word
3397 // before the start of the identification block, which was historically
3398 // always the start of the regular bitcode header.
3399 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
3400
3402
3403 auto Abbv = std::make_shared<BitCodeAbbrev>();
3405 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3406 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
3407 unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3408
3409 for (const Function &F : M) {
3410 uint64_t Record[2];
3411
3412 if (F.isDeclaration())
3413 continue;
3414
3415 Record[0] = VE.getValueID(&F);
3416
3417 // Save the word offset of the function (from the start of the
3418 // actual bitcode written to the stream).
3419 uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit();
3420 assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
3421 // Note that we add 1 here because the offset is relative to one word
3422 // before the start of the identification block, which was historically
3423 // always the start of the regular bitcode header.
3424 Record[1] = BitcodeIndex / 32 + 1;
3425
3426 Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev);
3427 }
3428
3429 Stream.ExitBlock();
3430}
3431
3432/// Emit names for arguments, instructions and basic blocks in a function.
3433void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
3434 const ValueSymbolTable &VST) {
3435 if (VST.empty())
3436 return;
3437
3439
3440 // FIXME: Set up the abbrev, we know how many values there are!
3441 // FIXME: We know if the type names can use 7-bit ascii.
3443
3444 for (const ValueName &Name : VST) {
3445 // Figure out the encoding to use for the name.
3447
3448 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
3449 NameVals.push_back(VE.getValueID(Name.getValue()));
3450
3451 // VST_CODE_ENTRY: [valueid, namechar x N]
3452 // VST_CODE_BBENTRY: [bbid, namechar x N]
3453 unsigned Code;
3454 if (isa<BasicBlock>(Name.getValue())) {
3456 if (Bits == SE_Char6)
3457 AbbrevToUse = VST_BBENTRY_6_ABBREV;
3458 } else {
3460 if (Bits == SE_Char6)
3461 AbbrevToUse = VST_ENTRY_6_ABBREV;
3462 else if (Bits == SE_Fixed7)
3463 AbbrevToUse = VST_ENTRY_7_ABBREV;
3464 }
3465
3466 for (const auto P : Name.getKey())
3467 NameVals.push_back((unsigned char)P);
3468
3469 // Emit the finished record.
3470 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
3471 NameVals.clear();
3472 }
3473
3474 Stream.ExitBlock();
3475}
3476
3477void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
3478 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
3479 unsigned Code;
3480 if (isa<BasicBlock>(Order.V))
3482 else
3484
3485 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
3486 Record.push_back(VE.getValueID(Order.V));
3487 Stream.EmitRecord(Code, Record);
3488}
3489
3490void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
3492 "Expected to be preserving use-list order");
3493
3494 auto hasMore = [&]() {
3495 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
3496 };
3497 if (!hasMore())
3498 // Nothing to do.
3499 return;
3500
3502 while (hasMore()) {
3503 writeUseList(std::move(VE.UseListOrders.back()));
3504 VE.UseListOrders.pop_back();
3505 }
3506 Stream.ExitBlock();
3507}
3508
3509/// Emit a function body to the module stream.
3510void ModuleBitcodeWriter::writeFunction(
3511 const Function &F,
3512 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3513 // Save the bitcode index of the start of this function block for recording
3514 // in the VST.
3515 FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
3516
3519
3521
3522 // Emit the number of basic blocks, so the reader can create them ahead of
3523 // time.
3524 Vals.push_back(VE.getBasicBlocks().size());
3526 Vals.clear();
3527
3528 // If there are function-local constants, emit them now.
3529 unsigned CstStart, CstEnd;
3530 VE.getFunctionConstantRange(CstStart, CstEnd);
3531 writeConstants(CstStart, CstEnd, false);
3532
3533 // If there is function-local metadata, emit it now.
3534 writeFunctionMetadata(F);
3535
3536 // Keep a running idea of what the instruction ID is.
3537 unsigned InstID = CstEnd;
3538
3539 bool NeedsMetadataAttachment = F.hasMetadata();
3540
3541 DILocation *LastDL = nullptr;
3542 SmallSetVector<Function *, 4> BlockAddressUsers;
3543
3544 // Finally, emit all the instructions, in order.
3545 for (const BasicBlock &BB : F) {
3546 for (const Instruction &I : BB) {
3547 writeInstruction(I, InstID, Vals);
3548
3549 if (!I.getType()->isVoidTy())
3550 ++InstID;
3551
3552 // If the instruction has metadata, write a metadata attachment later.
3553 NeedsMetadataAttachment |= I.hasMetadataOtherThanDebugLoc();
3554
3555 // If the instruction has a debug location, emit it.
3556 if (DILocation *DL = I.getDebugLoc()) {
3557 if (DL == LastDL) {
3558 // Just repeat the same debug loc as last time.
3560 } else {
3561 Vals.push_back(DL->getLine());
3562 Vals.push_back(DL->getColumn());
3563 Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
3564 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
3565 Vals.push_back(DL->isImplicitCode());
3567 Vals.clear();
3568 LastDL = DL;
3569 }
3570 }
3571
3572 // If the instruction has DbgRecords attached to it, emit them. Note that
3573 // they come after the instruction so that it's easy to attach them again
3574 // when reading the bitcode, even though conceptually the debug locations
3575 // start "before" the instruction.
3576 if (I.hasDbgRecords() && WriteNewDbgInfoFormatToBitcode) {
3577 /// Try to push the value only (unwrapped), otherwise push the
3578 /// metadata wrapped value. Returns true if the value was pushed
3579 /// without the ValueAsMetadata wrapper.
3580 auto PushValueOrMetadata = [&Vals, InstID,
3581 this](Metadata *RawLocation) {
3582 assert(RawLocation &&
3583 "RawLocation unexpectedly null in DbgVariableRecord");
3584 if (ValueAsMetadata *VAM = dyn_cast<ValueAsMetadata>(RawLocation)) {
3585 SmallVector<unsigned, 2> ValAndType;
3586 // If the value is a fwd-ref the type is also pushed. We don't
3587 // want the type, so fwd-refs are kept wrapped (pushValueAndType
3588 // returns false if the value is pushed without type).
3589 if (!pushValueAndType(VAM->getValue(), InstID, ValAndType)) {
3590 Vals.push_back(ValAndType[0]);
3591 return true;
3592 }
3593 }
3594 // The metadata is a DIArgList, or ValueAsMetadata wrapping a
3595 // fwd-ref. Push the metadata ID.
3596 Vals.push_back(VE.getMetadataID(RawLocation));
3597 return false;
3598 };
3599
3600 // Write out non-instruction debug information attached to this
3601 // instruction. Write it after the instruction so that it's easy to
3602 // re-attach to the instruction reading the records in.
3603 for (DbgRecord &DR : I.DebugMarker->getDbgRecordRange()) {
3604 if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) {
3605 Vals.push_back(VE.getMetadataID(&*DLR->getDebugLoc()));
3606 Vals.push_back(VE.getMetadataID(DLR->getLabel()));
3608 Vals.clear();
3609 continue;
3610 }
3611
3612 // First 3 fields are common to all kinds:
3613 // DILocation, DILocalVariable, DIExpression
3614 // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE)
3615 // ..., LocationMetadata
3616 // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE - abbrev'd)
3617 // ..., Value
3618 // dbg_declare (FUNC_CODE_DEBUG_RECORD_DECLARE)
3619 // ..., LocationMetadata
3620 // dbg_assign (FUNC_CODE_DEBUG_RECORD_ASSIGN)
3621 // ..., LocationMetadata, DIAssignID, DIExpression, LocationMetadata
3622 DbgVariableRecord &DVR = cast<DbgVariableRecord>(DR);
3623 Vals.push_back(VE.getMetadataID(&*DVR.getDebugLoc()));
3624 Vals.push_back(VE.getMetadataID(DVR.getVariable()));
3625 Vals.push_back(VE.getMetadataID(DVR.getExpression()));
3626 if (DVR.isDbgValue()) {
3627 if (PushValueOrMetadata(DVR.getRawLocation()))
3629 FUNCTION_DEBUG_RECORD_VALUE_ABBREV);
3630 else
3632 } else if (DVR.isDbgDeclare()) {
3633 Vals.push_back(VE.getMetadataID(DVR.getRawLocation()));
3635 } else {
3636 assert(DVR.isDbgAssign() && "Unexpected DbgRecord kind");
3637 Vals.push_back(VE.getMetadataID(DVR.getRawLocation()));
3638 Vals.push_back(VE.getMetadataID(DVR.getAssignID()));
3640 Vals.push_back(VE.getMetadataID(DVR.getRawAddress()));
3642 }
3643 Vals.clear();
3644 }
3645 }
3646 }
3647
3648 if (BlockAddress *BA = BlockAddress::lookup(&BB)) {
3649 SmallVector<Value *> Worklist{BA};
3650 SmallPtrSet<Value *, 8> Visited{BA};
3651 while (!Worklist.empty()) {
3652 Value *V = Worklist.pop_back_val();
3653 for (User *U : V->users()) {
3654 if (auto *I = dyn_cast<Instruction>(U)) {
3655 Function *P = I->getFunction();
3656 if (P != &F)
3657 BlockAddressUsers.insert(P);
3658 } else if (isa<Constant>(U) && !isa<GlobalValue>(U) &&
3659 Visited.insert(U).second)
3660 Worklist.push_back(U);
3661 }
3662 }
3663 }
3664 }
3665
3666 if (!BlockAddressUsers.empty()) {
3667 Vals.resize(BlockAddressUsers.size());
3668 for (auto I : llvm::enumerate(BlockAddressUsers))
3669 Vals[I.index()] = VE.getValueID(I.value());
3671 Vals.clear();
3672 }
3673
3674 // Emit names for all the instructions etc.
3675 if (auto *Symtab = F.getValueSymbolTable())
3676 writeFunctionLevelValueSymbolTable(*Symtab);
3677
3678 if (NeedsMetadataAttachment)
3679 writeFunctionMetadataAttachment(F);
3681 writeUseListBlock(&F);
3682 VE.purgeFunction();
3683 Stream.ExitBlock();
3684}
3685
3686// Emit blockinfo, which defines the standard abbreviations etc.
3687void ModuleBitcodeWriter::writeBlockInfo() {
3688 // We only want to emit block info records for blocks that have multiple
3689 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
3690 // Other blocks can define their abbrevs inline.
3691 Stream.EnterBlockInfoBlock();
3692
3693 { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
3694 auto Abbv = std::make_shared<BitCodeAbbrev>();
3700 VST_ENTRY_8_ABBREV)
3701 llvm_unreachable("Unexpected abbrev ordering!");
3702 }
3703
3704 { // 7-bit fixed width VST_CODE_ENTRY strings.
3705 auto Abbv = std::make_shared<BitCodeAbbrev>();
3711 VST_ENTRY_7_ABBREV)
3712 llvm_unreachable("Unexpected abbrev ordering!");
3713 }
3714 { // 6-bit char6 VST_CODE_ENTRY strings.
3715 auto Abbv = std::make_shared<BitCodeAbbrev>();
3721 VST_ENTRY_6_ABBREV)
3722 llvm_unreachable("Unexpected abbrev ordering!");
3723 }
3724 { // 6-bit char6 VST_CODE_BBENTRY strings.
3725 auto Abbv = std::make_shared<BitCodeAbbrev>();
3731 VST_BBENTRY_6_ABBREV)
3732 llvm_unreachable("Unexpected abbrev ordering!");
3733 }
3734
3735 { // SETTYPE abbrev for CONSTANTS_BLOCK.
3736 auto Abbv = std::make_shared<BitCodeAbbrev>();
3741 CONSTANTS_SETTYPE_ABBREV)
3742 llvm_unreachable("Unexpected abbrev ordering!");
3743 }
3744
3745 { // INTEGER abbrev for CONSTANTS_BLOCK.
3746 auto Abbv = std::make_shared<BitCodeAbbrev>();
3750 CONSTANTS_INTEGER_ABBREV)
3751 llvm_unreachable("Unexpected abbrev ordering!");
3752 }
3753
3754 { // CE_CAST abbrev for CONSTANTS_BLOCK.
3755 auto Abbv = std::make_shared<BitCodeAbbrev>();
3757 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
3758 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
3760 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3761
3763 CONSTANTS_CE_CAST_Abbrev)
3764 llvm_unreachable("Unexpected abbrev ordering!");
3765 }
3766 { // NULL abbrev for CONSTANTS_BLOCK.
3767 auto Abbv = std::make_shared<BitCodeAbbrev>();
3770 CONSTANTS_NULL_Abbrev)
3771 llvm_unreachable("Unexpected abbrev ordering!");
3772 }
3773
3774 // FIXME: This should only use space for first class types!
3775
3776 { // INST_LOAD abbrev for FUNCTION_BLOCK.
3777 auto Abbv = std::make_shared<BitCodeAbbrev>();
3779 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
3780 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3782 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
3783 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
3784 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3785 FUNCTION_INST_LOAD_ABBREV)
3786 llvm_unreachable("Unexpected abbrev ordering!");
3787 }
3788 { // INST_UNOP abbrev for FUNCTION_BLOCK.
3789 auto Abbv = std::make_shared<BitCodeAbbrev>();
3791 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3792 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3793 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3794 FUNCTION_INST_UNOP_ABBREV)
3795 llvm_unreachable("Unexpected abbrev ordering!");
3796 }
3797 { // INST_UNOP_FLAGS abbrev for FUNCTION_BLOCK.
3798 auto Abbv = std::make_shared<BitCodeAbbrev>();
3800 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3801 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3802 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
3803 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3804 FUNCTION_INST_UNOP_FLAGS_ABBREV)
3805 llvm_unreachable("Unexpected abbrev ordering!");
3806 }
3807 { // INST_BINOP abbrev for FUNCTION_BLOCK.
3808 auto Abbv = std::make_shared<BitCodeAbbrev>();
3810 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3811 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3812 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3813 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3814 FUNCTION_INST_BINOP_ABBREV)
3815 llvm_unreachable("Unexpected abbrev ordering!");
3816 }
3817 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
3818 auto Abbv = std::make_shared<BitCodeAbbrev>();
3820 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3821 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3822 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3823 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
3824 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3825 FUNCTION_INST_BINOP_FLAGS_ABBREV)
3826 llvm_unreachable("Unexpected abbrev ordering!");
3827 }
3828 { // INST_CAST abbrev for FUNCTION_BLOCK.
3829 auto Abbv = std::make_shared<BitCodeAbbrev>();
3831 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
3832 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3834 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3835 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3836 FUNCTION_INST_CAST_ABBREV)
3837 llvm_unreachable("Unexpected abbrev ordering!");
3838 }
3839 { // INST_CAST_FLAGS abbrev for FUNCTION_BLOCK.
3840 auto Abbv = std::make_shared<BitCodeAbbrev>();
3842 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
3843 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3845 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3846 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
3847 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3848 FUNCTION_INST_CAST_FLAGS_ABBREV)
3849 llvm_unreachable("Unexpected abbrev ordering!");
3850 }
3851
3852 { // INST_RET abbrev for FUNCTION_BLOCK.
3853 auto Abbv = std::make_shared<BitCodeAbbrev>();
3855 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3856 FUNCTION_INST_RET_VOID_ABBREV)
3857 llvm_unreachable("Unexpected abbrev ordering!");
3858 }
3859 { // INST_RET abbrev for FUNCTION_BLOCK.
3860 auto Abbv = std::make_shared<BitCodeAbbrev>();
3862 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
3863 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3864 FUNCTION_INST_RET_VAL_ABBREV)
3865 llvm_unreachable("Unexpected abbrev ordering!");
3866 }
3867 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
3868 auto Abbv = std::make_shared<BitCodeAbbrev>();
3870 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3871 FUNCTION_INST_UNREACHABLE_ABBREV)
3872 llvm_unreachable("Unexpected abbrev ordering!");
3873 }
3874 {
3875 auto Abbv = std::make_shared<BitCodeAbbrev>();
3878 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3879 Log2_32_Ceil(VE.getTypes().size() + 1)));
3882 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3883 FUNCTION_INST_GEP_ABBREV)
3884 llvm_unreachable("Unexpected abbrev ordering!");
3885 }
3886 {
3887 auto Abbv = std::make_shared<BitCodeAbbrev>();
3889 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // dbgloc
3890 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // var
3891 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // expr
3892 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // val
3893 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3894 FUNCTION_DEBUG_RECORD_VALUE_ABBREV)
3895 llvm_unreachable("Unexpected abbrev ordering! 1");
3896 }
3897 Stream.ExitBlock();
3898}
3899
3900/// Write the module path strings, currently only used when generating
3901/// a combined index file.
3902void IndexBitcodeWriter::writeModStrings() {
3904
3905 // TODO: See which abbrev sizes we actually need to emit
3906
3907 // 8-bit fixed-width MST_ENTRY strings.
3908 auto Abbv = std::make_shared<BitCodeAbbrev>();
3913 unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
3914
3915 // 7-bit fixed width MST_ENTRY strings.
3916 Abbv = std::make_shared<BitCodeAbbrev>();
3921 unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
3922
3923 // 6-bit char6 MST_ENTRY strings.
3924 Abbv = std::make_shared<BitCodeAbbrev>();
3929 unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
3930
3931 // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
3932 Abbv = std::make_shared<BitCodeAbbrev>();
3939 unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
3940
3942 forEachModule([&](const StringMapEntry<ModuleHash> &MPSE) {
3943 StringRef Key = MPSE.getKey();
3944 const auto &Hash = MPSE.getValue();
3946 unsigned AbbrevToUse = Abbrev8Bit;
3947 if (Bits == SE_Char6)
3948 AbbrevToUse = Abbrev6Bit;
3949 else if (Bits == SE_Fixed7)
3950 AbbrevToUse = Abbrev7Bit;
3951
3952 auto ModuleId = ModuleIdMap.size();
3953 ModuleIdMap[Key] = ModuleId;
3954 Vals.push_back(ModuleId);
3955 Vals.append(Key.begin(), Key.end());
3956
3957 // Emit the finished record.
3958 Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
3959
3960 // Emit an optional hash for the module now
3961 if (llvm::any_of(Hash, [](uint32_t H) { return H; })) {
3962 Vals.assign(Hash.begin(), Hash.end());
3963 // Emit the hash record.
3964 Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
3965 }
3966
3967 Vals.clear();
3968 });
3969 Stream.ExitBlock();
3970}
3971
3972/// Write the function type metadata related records that need to appear before
3973/// a function summary entry (whether per-module or combined).
3974template <typename Fn>
3976 FunctionSummary *FS,
3977 Fn GetValueID) {
3978 if (!FS->type_tests().empty())
3979 Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
3980
3982
3983 auto WriteVFuncIdVec = [&](uint64_t Ty,
3985 if (VFs.empty())
3986 return;
3987 Record.clear();
3988 for (auto &VF : VFs) {
3989 Record.push_back(VF.GUID);
3990 Record.push_back(VF.Offset);
3991 }
3992 Stream.EmitRecord(Ty, Record);
3993 };
3994
3995 WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
3996 FS->type_test_assume_vcalls());
3997 WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
3998 FS->type_checked_load_vcalls());
3999
4000 auto WriteConstVCallVec = [&](uint64_t Ty,
4002 for (auto &VC : VCs) {
4003 Record.clear();
4004 Record.push_back(VC.VFunc.GUID);
4005 Record.push_back(VC.VFunc.Offset);
4006 llvm::append_range(Record, VC.Args);
4007 Stream.EmitRecord(Ty, Record);
4008 }
4009 };
4010
4011 WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
4012 FS->type_test_assume_const_vcalls());
4013 WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
4014 FS->type_checked_load_const_vcalls());
4015
4016 auto WriteRange = [&](ConstantRange Range) {
4018 assert(Range.getLower().getNumWords() == 1);
4019 assert(Range.getUpper().getNumWords() == 1);
4022 };
4023
4024 if (!FS->paramAccesses().empty()) {
4025 Record.clear();
4026 for (auto &Arg : FS->paramAccesses()) {
4027 size_t UndoSize = Record.size();
4028 Record.push_back(Arg.ParamNo);
4029 WriteRange(Arg.Use);
4030 Record.push_back(Arg.Calls.size());
4031 for (auto &Call : Arg.Calls) {
4032 Record.push_back(Call.ParamNo);
4033 std::optional<unsigned> ValueID = GetValueID(Call.Callee);
4034 if (!ValueID) {
4035 // If ValueID is unknown we can't drop just this call, we must drop
4036 // entire parameter.
4037 Record.resize(UndoSize);
4038 break;
4039 }
4040 Record.push_back(*ValueID);
4041 WriteRange(Call.Offsets);
4042 }
4043 }
4044 if (!Record.empty())
4046 }
4047}
4048
4049/// Collect type IDs from type tests used by function.
4050static void
4052 std::set<GlobalValue::GUID> &ReferencedTypeIds) {
4053 if (!FS->type_tests().empty())
4054 for (auto &TT : FS->type_tests())
4055 ReferencedTypeIds.insert(TT);
4056
4057 auto GetReferencedTypesFromVFuncIdVec =
4059 for (auto &VF : VFs)
4060 ReferencedTypeIds.insert(VF.GUID);
4061 };
4062
4063 GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls());
4064 GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls());
4065
4066 auto GetReferencedTypesFromConstVCallVec =
4068 for (auto &VC : VCs)
4069 ReferencedTypeIds.insert(VC.VFunc.GUID);
4070 };
4071
4072 GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls());
4073 GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls());
4074}
4075
4077 SmallVector<uint64_t, 64> &NameVals, const std::vector<uint64_t> &args,
4079 NameVals.push_back(args.size());
4080 llvm::append_range(NameVals, args);
4081
4082 NameVals.push_back(ByArg.TheKind);
4083 NameVals.push_back(ByArg.Info);
4084 NameVals.push_back(ByArg.Byte);
4085 NameVals.push_back(ByArg.Bit);
4086}
4087
4089 SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
4090 uint64_t Id, const WholeProgramDevirtResolution &Wpd) {
4091 NameVals.push_back(Id);
4092
4093 NameVals.push_back(Wpd.TheKind);
4094 NameVals.push_back(StrtabBuilder.add(Wpd.SingleImplName));
4095 NameVals.push_back(Wpd.SingleImplName.size());
4096
4097 NameVals.push_back(Wpd.ResByArg.size());
4098 for (auto &A : Wpd.ResByArg)
4099 writeWholeProgramDevirtResolutionByArg(NameVals, A.first, A.second);
4100}
4101
4103 StringTableBuilder &StrtabBuilder,
4104 const std::string &Id,
4105 const TypeIdSummary &Summary) {
4106 NameVals.push_back(StrtabBuilder.add(Id));
4107 NameVals.push_back(Id.size());
4108
4109 NameVals.push_back(Summary.TTRes.TheKind);
4110 NameVals.push_back(Summary.TTRes.SizeM1BitWidth);
4111 NameVals.push_back(Summary.TTRes.AlignLog2);
4112 NameVals.push_back(Summary.TTRes.SizeM1);
4113 NameVals.push_back(Summary.TTRes.BitMask);
4114 NameVals.push_back(Summary.TTRes.InlineBits);
4115
4116 for (auto &W : Summary.WPDRes)
4117 writeWholeProgramDevirtResolution(NameVals, StrtabBuilder, W.first,
4118 W.second);
4119}
4120
4122 SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
4123 const std::string &Id, const TypeIdCompatibleVtableInfo &Summary,
4124 ValueEnumerator &VE) {
4125 NameVals.push_back(StrtabBuilder.add(Id));
4126 NameVals.push_back(Id.size());
4127
4128 for (auto &P : Summary) {
4129 NameVals.push_back(P.AddressPointOffset);
4130 NameVals.push_back(VE.getValueID(P.VTableVI.getValue()));
4131 }
4132}
4133
4135 BitstreamWriter &Stream, FunctionSummary *FS, unsigned CallsiteAbbrev,
4136 unsigned AllocAbbrev, bool PerModule,
4137 std::function<unsigned(const ValueInfo &VI)> GetValueID,
4138 std::function<unsigned(unsigned)> GetStackIndex) {
4140
4141 for (auto &CI : FS->callsites()) {
4142 Record.clear();
4143 // Per module callsite clones should always have a single entry of
4144 // value 0.
4145 assert(!PerModule || (CI.Clones.size() == 1 && CI.Clones[0] == 0));
4146 Record.push_back(GetValueID(CI.Callee));
4147 if (!PerModule) {
4148 Record.push_back(CI.StackIdIndices.size());
4149 Record.push_back(CI.Clones.size());
4150 }
4151 for (auto Id : CI.StackIdIndices)
4152 Record.push_back(GetStackIndex(Id));
4153 if (!PerModule) {
4154 for (auto V : CI.Clones)
4155 Record.push_back(V);
4156 }
4159 Record, CallsiteAbbrev);
4160 }
4161
4162 for (auto &AI : FS->allocs()) {
4163 Record.clear();
4164 // Per module alloc versions should always have a single entry of
4165 // value 0.
4166 assert(!PerModule || (AI.Versions.size() == 1 && AI.Versions[0] == 0));
4167 if (!PerModule) {
4168 Record.push_back(AI.MIBs.size());
4169 Record.push_back(AI.Versions.size());
4170 }
4171 for (auto &MIB : AI.MIBs) {
4172 Record.push_back((uint8_t)MIB.AllocType);
4173 Record.push_back(MIB.StackIdIndices.size());
4174 for (auto Id : MIB.StackIdIndices)
4175 Record.push_back(GetStackIndex(Id));
4176 }
4177 if (!PerModule) {
4178 for (auto V : AI.Versions)
4179 Record.push_back(V);
4180 }
4181 Stream.EmitRecord(PerModule ? bitc::FS_PERMODULE_ALLOC_INFO
4183 Record, AllocAbbrev);
4184 }
4185}
4186
4187// Helper to emit a single function summary record.
4188void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
4190 unsigned ValueID, unsigned FSCallsRelBFAbbrev,
4191 unsigned FSCallsProfileAbbrev, unsigned CallsiteAbbrev,
4192 unsigned AllocAbbrev, const Function &F) {
4193 NameVals.push_back(ValueID);
4194
4195 FunctionSummary *FS = cast<FunctionSummary>(Summary);
4196
4198 Stream, FS, [&](const ValueInfo &VI) -> std::optional<unsigned> {
4199 return {VE.getValueID(VI.getValue())};
4200 });
4201
4203 Stream, FS, CallsiteAbbrev, AllocAbbrev,
4204 /*PerModule*/ true,
4205 /*GetValueId*/ [&](const ValueInfo &VI) { return getValueId(VI); },
4206 /*GetStackIndex*/ [&](unsigned I) { return I; });
4207
4208 auto SpecialRefCnts = FS->specialRefCounts();
4209 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
4210 NameVals.push_back(FS->instCount());
4211 NameVals.push_back(getEncodedFFlags(FS->fflags()));
4212 NameVals.push_back(FS->refs().size());
4213 NameVals.push_back(SpecialRefCnts.first); // rorefcnt
4214 NameVals.push_back(SpecialRefCnts.second); // worefcnt
4215
4216 for (auto &RI : FS->refs())
4217 NameVals.push_back(getValueId(RI));
4218
4219 const bool UseRelBFRecord =
4220 WriteRelBFToSummary && !F.hasProfileData() &&
4222 for (auto &ECI : FS->calls()) {
4223 NameVals.push_back(getValueId(ECI.first));
4224 if (UseRelBFRecord)
4225 NameVals.push_back(getEncodedRelBFCallEdgeInfo(ECI.second));
4226 else
4227 NameVals.push_back(getEncodedHotnessCallEdgeInfo(ECI.second));
4228 }
4229
4230 unsigned FSAbbrev =
4231 (UseRelBFRecord ? FSCallsRelBFAbbrev : FSCallsProfileAbbrev);
4232 unsigned Code =
4234
4235 // Emit the finished record.
4236 Stream.EmitRecord(Code, NameVals, FSAbbrev);
4237 NameVals.clear();
4238}
4239
4240// Collect the global value references in the given variable's initializer,
4241// and emit them in a summary record.
4242void ModuleBitcodeWriterBase::writeModuleLevelReferences(
4243 const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
4244 unsigned FSModRefsAbbrev, unsigned FSModVTableRefsAbbrev) {
4245 auto VI = Index->getValueInfo(V.getGUID());
4246 if (!VI || VI.getSummaryList().empty()) {
4247 // Only declarations should not have a summary (a declaration might however
4248 // have a summary if the def was in module level asm).
4249 assert(V.isDeclaration());
4250 return;
4251 }
4252 auto *Summary = VI.getSummaryList()[0].get();
4253 NameVals.push_back(VE.getValueID(&V));
4254 GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
4255 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
4256 NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
4257
4258 auto VTableFuncs = VS->vTableFuncs();
4259 if (!VTableFuncs.empty())
4260 NameVals.push_back(VS->refs().size());
4261
4262 unsigned SizeBeforeRefs = NameVals.size();
4263 for (auto &RI : VS->refs())
4264 NameVals.push_back(VE.getValueID(RI.getValue()));
4265 // Sort the refs for determinism output, the vector returned by FS->refs() has
4266 // been initialized from a DenseSet.
4267 llvm::sort(drop_begin(NameVals, SizeBeforeRefs));
4268
4269 if (VTableFuncs.empty())
4271 FSModRefsAbbrev);
4272 else {
4273 // VTableFuncs pairs should already be sorted by offset.
4274 for (auto &P : VTableFuncs) {
4275 NameVals.push_back(VE.getValueID(P.FuncVI.getValue()));
4276 NameVals.push_back(P.VTableOffset);
4277 }
4278
4280 FSModVTableRefsAbbrev);
4281 }
4282 NameVals.clear();
4283}
4284
4285/// Emit the per-module summary section alongside the rest of
4286/// the module's bitcode.
4287void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
4288 // By default we compile with ThinLTO if the module has a summary, but the
4289 // client can request full LTO with a module flag.
4290 bool IsThinLTO = true;
4291 if (auto *MD =
4292 mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
4293 IsThinLTO = MD->getZExtValue();
4296 4);
4297
4298 Stream.EmitRecord(
4301
4302 // Write the index flags.
4303 uint64_t Flags = 0;
4304 // Bits 1-3 are set only in the combined index, skip them.
4305 if (Index->enableSplitLTOUnit())
4306 Flags |= 0x8;
4307 if (Index->hasUnifiedLTO())
4308 Flags |= 0x200;
4309
4311
4312 if (Index->begin() == Index->end()) {
4313 Stream.ExitBlock();
4314 return;
4315 }
4316
4317 for (const auto &GVI : valueIds()) {
4319 ArrayRef<uint64_t>{GVI.second, GVI.first});
4320 }
4321
4322 if (!Index->stackIds().empty()) {
4323 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
4324 StackIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_STACK_IDS));
4325 // numids x stackid
4326 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4327 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4328 unsigned StackIdAbbvId = Stream.EmitAbbrev(std::move(StackIdAbbv));
4329 Stream.EmitRecord(bitc::FS_STACK_IDS, Index->stackIds(), StackIdAbbvId);
4330 }
4331
4332 // Abbrev for FS_PERMODULE_PROFILE.
4333 auto Abbv = std::make_shared<BitCodeAbbrev>();
4335 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4336 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // flags
4337 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
4338 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
4339 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4340 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
4341 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
4342 // numrefs x valueid, n x (valueid, hotness+tailcall flags)
4345 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4346
4347 // Abbrev for FS_PERMODULE_RELBF.
4348 Abbv = std::make_shared<BitCodeAbbrev>();
4350 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4351 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4352 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
4353 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
4354 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4355 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
4356 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
4357 // numrefs x valueid, n x (valueid, rel_block_freq+tailcall])
4360 unsigned FSCallsRelBFAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4361
4362 // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
4363 Abbv = std::make_shared<BitCodeAbbrev>();
4365 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid