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