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