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