Revert "[Sanitizers] UBSan unreachable incompatible with ASan in the presence of...
[llvm-core.git] / lib / Bitcode / Writer / BitcodeWriter.cpp
blobf4a539e51f705960ad955da529004bd1bc98cf3e
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.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/Bitcode/BitcodeWriter.h"
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/None.h"
20 #include "llvm/ADT/Optional.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/StringMap.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/ADT/Triple.h"
27 #include "llvm/Bitcode/BitCodes.h"
28 #include "llvm/Bitcode/BitstreamWriter.h"
29 #include "llvm/Bitcode/LLVMBitCodes.h"
30 #include "llvm/Config/llvm-config.h"
31 #include "llvm/IR/Attributes.h"
32 #include "llvm/IR/BasicBlock.h"
33 #include "llvm/IR/CallSite.h"
34 #include "llvm/IR/Comdat.h"
35 #include "llvm/IR/Constant.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DebugInfoMetadata.h"
38 #include "llvm/IR/DebugLoc.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GlobalAlias.h"
42 #include "llvm/IR/GlobalIFunc.h"
43 #include "llvm/IR/GlobalObject.h"
44 #include "llvm/IR/GlobalValue.h"
45 #include "llvm/IR/GlobalVariable.h"
46 #include "llvm/IR/InlineAsm.h"
47 #include "llvm/IR/InstrTypes.h"
48 #include "llvm/IR/Instruction.h"
49 #include "llvm/IR/Instructions.h"
50 #include "llvm/IR/LLVMContext.h"
51 #include "llvm/IR/Metadata.h"
52 #include "llvm/IR/Module.h"
53 #include "llvm/IR/ModuleSummaryIndex.h"
54 #include "llvm/IR/Operator.h"
55 #include "llvm/IR/Type.h"
56 #include "llvm/IR/UseListOrder.h"
57 #include "llvm/IR/Value.h"
58 #include "llvm/IR/ValueSymbolTable.h"
59 #include "llvm/MC/StringTableBuilder.h"
60 #include "llvm/Object/IRSymtab.h"
61 #include "llvm/Support/AtomicOrdering.h"
62 #include "llvm/Support/Casting.h"
63 #include "llvm/Support/CommandLine.h"
64 #include "llvm/Support/Endian.h"
65 #include "llvm/Support/Error.h"
66 #include "llvm/Support/ErrorHandling.h"
67 #include "llvm/Support/MathExtras.h"
68 #include "llvm/Support/SHA1.h"
69 #include "llvm/Support/TargetRegistry.h"
70 #include "llvm/Support/raw_ostream.h"
71 #include <algorithm>
72 #include <cassert>
73 #include <cstddef>
74 #include <cstdint>
75 #include <iterator>
76 #include <map>
77 #include <memory>
78 #include <string>
79 #include <utility>
80 #include <vector>
82 using namespace llvm;
84 static cl::opt<unsigned>
85 IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25),
86 cl::desc("Number of metadatas above which we emit an index "
87 "to enable lazy-loading"));
89 cl::opt<bool> WriteRelBFToSummary(
90 "write-relbf-to-summary", cl::Hidden, cl::init(false),
91 cl::desc("Write relative block frequency to function summary "));
93 extern FunctionSummary::ForceSummaryHotnessType ForceSummaryEdgesCold;
95 namespace {
97 /// These are manifest constants used by the bitcode writer. They do not need to
98 /// be kept in sync with the reader, but need to be consistent within this file.
99 enum {
100 // VALUE_SYMTAB_BLOCK abbrev id's.
101 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
102 VST_ENTRY_7_ABBREV,
103 VST_ENTRY_6_ABBREV,
104 VST_BBENTRY_6_ABBREV,
106 // CONSTANTS_BLOCK abbrev id's.
107 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
108 CONSTANTS_INTEGER_ABBREV,
109 CONSTANTS_CE_CAST_Abbrev,
110 CONSTANTS_NULL_Abbrev,
112 // FUNCTION_BLOCK abbrev id's.
113 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
114 FUNCTION_INST_UNOP_ABBREV,
115 FUNCTION_INST_UNOP_FLAGS_ABBREV,
116 FUNCTION_INST_BINOP_ABBREV,
117 FUNCTION_INST_BINOP_FLAGS_ABBREV,
118 FUNCTION_INST_CAST_ABBREV,
119 FUNCTION_INST_RET_VOID_ABBREV,
120 FUNCTION_INST_RET_VAL_ABBREV,
121 FUNCTION_INST_UNREACHABLE_ABBREV,
122 FUNCTION_INST_GEP_ABBREV,
125 /// Abstract class to manage the bitcode writing, subclassed for each bitcode
126 /// file type.
127 class BitcodeWriterBase {
128 protected:
129 /// The stream created and owned by the client.
130 BitstreamWriter &Stream;
132 StringTableBuilder &StrtabBuilder;
134 public:
135 /// Constructs a BitcodeWriterBase object that writes to the provided
136 /// \p Stream.
137 BitcodeWriterBase(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder)
138 : Stream(Stream), StrtabBuilder(StrtabBuilder) {}
140 protected:
141 void writeBitcodeHeader();
142 void writeModuleVersion();
145 void BitcodeWriterBase::writeModuleVersion() {
146 // VERSION: [version#]
147 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, ArrayRef<uint64_t>{2});
150 /// Base class to manage the module bitcode writing, currently subclassed for
151 /// ModuleBitcodeWriter and ThinLinkBitcodeWriter.
152 class ModuleBitcodeWriterBase : public BitcodeWriterBase {
153 protected:
154 /// The Module to write to bitcode.
155 const Module &M;
157 /// Enumerates ids for all values in the module.
158 ValueEnumerator VE;
160 /// Optional per-module index to write for ThinLTO.
161 const ModuleSummaryIndex *Index;
163 /// Map that holds the correspondence between GUIDs in the summary index,
164 /// that came from indirect call profiles, and a value id generated by this
165 /// class to use in the VST and summary block records.
166 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
168 /// Tracks the last value id recorded in the GUIDToValueMap.
169 unsigned GlobalValueId;
171 /// Saves the offset of the VSTOffset record that must eventually be
172 /// backpatched with the offset of the actual VST.
173 uint64_t VSTOffsetPlaceholder = 0;
175 public:
176 /// Constructs a ModuleBitcodeWriterBase object for the given Module,
177 /// writing to the provided \p Buffer.
178 ModuleBitcodeWriterBase(const Module &M, StringTableBuilder &StrtabBuilder,
179 BitstreamWriter &Stream,
180 bool ShouldPreserveUseListOrder,
181 const ModuleSummaryIndex *Index)
182 : BitcodeWriterBase(Stream, StrtabBuilder), M(M),
183 VE(M, ShouldPreserveUseListOrder), Index(Index) {
184 // Assign ValueIds to any callee values in the index that came from
185 // indirect call profiles and were recorded as a GUID not a Value*
186 // (which would have been assigned an ID by the ValueEnumerator).
187 // The starting ValueId is just after the number of values in the
188 // ValueEnumerator, so that they can be emitted in the VST.
189 GlobalValueId = VE.getValues().size();
190 if (!Index)
191 return;
192 for (const auto &GUIDSummaryLists : *Index)
193 // Examine all summaries for this GUID.
194 for (auto &Summary : GUIDSummaryLists.second.SummaryList)
195 if (auto FS = dyn_cast<FunctionSummary>(Summary.get()))
196 // For each call in the function summary, see if the call
197 // is to a GUID (which means it is for an indirect call,
198 // otherwise we would have a Value for it). If so, synthesize
199 // a value id.
200 for (auto &CallEdge : FS->calls())
201 if (!CallEdge.first.haveGVs() || !CallEdge.first.getValue())
202 assignValueId(CallEdge.first.getGUID());
205 protected:
206 void writePerModuleGlobalValueSummary();
208 private:
209 void writePerModuleFunctionSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
210 GlobalValueSummary *Summary,
211 unsigned ValueID,
212 unsigned FSCallsAbbrev,
213 unsigned FSCallsProfileAbbrev,
214 const Function &F);
215 void writeModuleLevelReferences(const GlobalVariable &V,
216 SmallVector<uint64_t, 64> &NameVals,
217 unsigned FSModRefsAbbrev);
219 void assignValueId(GlobalValue::GUID ValGUID) {
220 GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
223 unsigned getValueId(GlobalValue::GUID ValGUID) {
224 const auto &VMI = GUIDToValueIdMap.find(ValGUID);
225 // Expect that any GUID value had a value Id assigned by an
226 // earlier call to assignValueId.
227 assert(VMI != GUIDToValueIdMap.end() &&
228 "GUID does not have assigned value Id");
229 return VMI->second;
232 // Helper to get the valueId for the type of value recorded in VI.
233 unsigned getValueId(ValueInfo VI) {
234 if (!VI.haveGVs() || !VI.getValue())
235 return getValueId(VI.getGUID());
236 return VE.getValueID(VI.getValue());
239 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
242 /// Class to manage the bitcode writing for a module.
243 class ModuleBitcodeWriter : public ModuleBitcodeWriterBase {
244 /// Pointer to the buffer allocated by caller for bitcode writing.
245 const SmallVectorImpl<char> &Buffer;
247 /// True if a module hash record should be written.
248 bool GenerateHash;
250 /// If non-null, when GenerateHash is true, the resulting hash is written
251 /// into ModHash.
252 ModuleHash *ModHash;
254 SHA1 Hasher;
256 /// The start bit of the identification block.
257 uint64_t BitcodeStartBit;
259 public:
260 /// Constructs a ModuleBitcodeWriter object for the given Module,
261 /// writing to the provided \p Buffer.
262 ModuleBitcodeWriter(const Module &M, SmallVectorImpl<char> &Buffer,
263 StringTableBuilder &StrtabBuilder,
264 BitstreamWriter &Stream, bool ShouldPreserveUseListOrder,
265 const ModuleSummaryIndex *Index, bool GenerateHash,
266 ModuleHash *ModHash = nullptr)
267 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
268 ShouldPreserveUseListOrder, Index),
269 Buffer(Buffer), GenerateHash(GenerateHash), ModHash(ModHash),
270 BitcodeStartBit(Stream.GetCurrentBitNo()) {}
272 /// Emit the current module to the bitstream.
273 void write();
275 private:
276 uint64_t bitcodeStartBit() { return BitcodeStartBit; }
278 size_t addToStrtab(StringRef Str);
280 void writeAttributeGroupTable();
281 void writeAttributeTable();
282 void writeTypeTable();
283 void writeComdats();
284 void writeValueSymbolTableForwardDecl();
285 void writeModuleInfo();
286 void writeValueAsMetadata(const ValueAsMetadata *MD,
287 SmallVectorImpl<uint64_t> &Record);
288 void writeMDTuple(const MDTuple *N, SmallVectorImpl<uint64_t> &Record,
289 unsigned Abbrev);
290 unsigned createDILocationAbbrev();
291 void writeDILocation(const DILocation *N, SmallVectorImpl<uint64_t> &Record,
292 unsigned &Abbrev);
293 unsigned createGenericDINodeAbbrev();
294 void writeGenericDINode(const GenericDINode *N,
295 SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev);
296 void writeDISubrange(const DISubrange *N, SmallVectorImpl<uint64_t> &Record,
297 unsigned Abbrev);
298 void writeDIEnumerator(const DIEnumerator *N,
299 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
300 void writeDIBasicType(const DIBasicType *N, SmallVectorImpl<uint64_t> &Record,
301 unsigned Abbrev);
302 void writeDIDerivedType(const DIDerivedType *N,
303 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
304 void writeDICompositeType(const DICompositeType *N,
305 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
306 void writeDISubroutineType(const DISubroutineType *N,
307 SmallVectorImpl<uint64_t> &Record,
308 unsigned Abbrev);
309 void writeDIFile(const DIFile *N, SmallVectorImpl<uint64_t> &Record,
310 unsigned Abbrev);
311 void writeDICompileUnit(const DICompileUnit *N,
312 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
313 void writeDISubprogram(const DISubprogram *N,
314 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
315 void writeDILexicalBlock(const DILexicalBlock *N,
316 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
317 void writeDILexicalBlockFile(const DILexicalBlockFile *N,
318 SmallVectorImpl<uint64_t> &Record,
319 unsigned Abbrev);
320 void writeDINamespace(const DINamespace *N, SmallVectorImpl<uint64_t> &Record,
321 unsigned Abbrev);
322 void writeDIMacro(const DIMacro *N, SmallVectorImpl<uint64_t> &Record,
323 unsigned Abbrev);
324 void writeDIMacroFile(const DIMacroFile *N, SmallVectorImpl<uint64_t> &Record,
325 unsigned Abbrev);
326 void writeDIModule(const DIModule *N, SmallVectorImpl<uint64_t> &Record,
327 unsigned Abbrev);
328 void writeDITemplateTypeParameter(const DITemplateTypeParameter *N,
329 SmallVectorImpl<uint64_t> &Record,
330 unsigned Abbrev);
331 void writeDITemplateValueParameter(const DITemplateValueParameter *N,
332 SmallVectorImpl<uint64_t> &Record,
333 unsigned Abbrev);
334 void writeDIGlobalVariable(const DIGlobalVariable *N,
335 SmallVectorImpl<uint64_t> &Record,
336 unsigned Abbrev);
337 void writeDILocalVariable(const DILocalVariable *N,
338 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
339 void writeDILabel(const DILabel *N,
340 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
341 void writeDIExpression(const DIExpression *N,
342 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
343 void writeDIGlobalVariableExpression(const DIGlobalVariableExpression *N,
344 SmallVectorImpl<uint64_t> &Record,
345 unsigned Abbrev);
346 void writeDIObjCProperty(const DIObjCProperty *N,
347 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
348 void writeDIImportedEntity(const DIImportedEntity *N,
349 SmallVectorImpl<uint64_t> &Record,
350 unsigned Abbrev);
351 unsigned createNamedMetadataAbbrev();
352 void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
353 unsigned createMetadataStringsAbbrev();
354 void writeMetadataStrings(ArrayRef<const Metadata *> Strings,
355 SmallVectorImpl<uint64_t> &Record);
356 void writeMetadataRecords(ArrayRef<const Metadata *> MDs,
357 SmallVectorImpl<uint64_t> &Record,
358 std::vector<unsigned> *MDAbbrevs = nullptr,
359 std::vector<uint64_t> *IndexPos = nullptr);
360 void writeModuleMetadata();
361 void writeFunctionMetadata(const Function &F);
362 void writeFunctionMetadataAttachment(const Function &F);
363 void writeGlobalVariableMetadataAttachment(const GlobalVariable &GV);
364 void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
365 const GlobalObject &GO);
366 void writeModuleMetadataKinds();
367 void writeOperandBundleTags();
368 void writeSyncScopeNames();
369 void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal);
370 void writeModuleConstants();
371 bool pushValueAndType(const Value *V, unsigned InstID,
372 SmallVectorImpl<unsigned> &Vals);
373 void writeOperandBundles(ImmutableCallSite CS, unsigned InstID);
374 void pushValue(const Value *V, unsigned InstID,
375 SmallVectorImpl<unsigned> &Vals);
376 void pushValueSigned(const Value *V, unsigned InstID,
377 SmallVectorImpl<uint64_t> &Vals);
378 void writeInstruction(const Instruction &I, unsigned InstID,
379 SmallVectorImpl<unsigned> &Vals);
380 void writeFunctionLevelValueSymbolTable(const ValueSymbolTable &VST);
381 void writeGlobalValueSymbolTable(
382 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
383 void writeUseList(UseListOrder &&Order);
384 void writeUseListBlock(const Function *F);
385 void
386 writeFunction(const Function &F,
387 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
388 void writeBlockInfo();
389 void writeModuleHash(size_t BlockStartPos);
391 unsigned getEncodedSyncScopeID(SyncScope::ID SSID) {
392 return unsigned(SSID);
396 /// Class to manage the bitcode writing for a combined index.
397 class IndexBitcodeWriter : public BitcodeWriterBase {
398 /// The combined index to write to bitcode.
399 const ModuleSummaryIndex &Index;
401 /// When writing a subset of the index for distributed backends, client
402 /// provides a map of modules to the corresponding GUIDs/summaries to write.
403 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex;
405 /// Map that holds the correspondence between the GUID used in the combined
406 /// index and a value id generated by this class to use in references.
407 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
409 /// Tracks the last value id recorded in the GUIDToValueMap.
410 unsigned GlobalValueId = 0;
412 public:
413 /// Constructs a IndexBitcodeWriter object for the given combined index,
414 /// writing to the provided \p Buffer. When writing a subset of the index
415 /// for a distributed backend, provide a \p ModuleToSummariesForIndex map.
416 IndexBitcodeWriter(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder,
417 const ModuleSummaryIndex &Index,
418 const std::map<std::string, GVSummaryMapTy>
419 *ModuleToSummariesForIndex = nullptr)
420 : BitcodeWriterBase(Stream, StrtabBuilder), Index(Index),
421 ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
422 // Assign unique value ids to all summaries to be written, for use
423 // in writing out the call graph edges. Save the mapping from GUID
424 // to the new global value id to use when writing those edges, which
425 // are currently saved in the index in terms of GUID.
426 forEachSummary([&](GVInfo I, bool) {
427 GUIDToValueIdMap[I.first] = ++GlobalValueId;
431 /// The below iterator returns the GUID and associated summary.
432 using GVInfo = std::pair<GlobalValue::GUID, GlobalValueSummary *>;
434 /// Calls the callback for each value GUID and summary to be written to
435 /// bitcode. This hides the details of whether they are being pulled from the
436 /// entire index or just those in a provided ModuleToSummariesForIndex map.
437 template<typename Functor>
438 void forEachSummary(Functor Callback) {
439 if (ModuleToSummariesForIndex) {
440 for (auto &M : *ModuleToSummariesForIndex)
441 for (auto &Summary : M.second) {
442 Callback(Summary, false);
443 // Ensure aliasee is handled, e.g. for assigning a valueId,
444 // even if we are not importing the aliasee directly (the
445 // imported alias will contain a copy of aliasee).
446 if (auto *AS = dyn_cast<AliasSummary>(Summary.getSecond()))
447 Callback({AS->getAliaseeGUID(), &AS->getAliasee()}, true);
449 } else {
450 for (auto &Summaries : Index)
451 for (auto &Summary : Summaries.second.SummaryList)
452 Callback({Summaries.first, Summary.get()}, false);
456 /// Calls the callback for each entry in the modulePaths StringMap that
457 /// should be written to the module path string table. This hides the details
458 /// of whether they are being pulled from the entire index or just those in a
459 /// provided ModuleToSummariesForIndex map.
460 template <typename Functor> void forEachModule(Functor Callback) {
461 if (ModuleToSummariesForIndex) {
462 for (const auto &M : *ModuleToSummariesForIndex) {
463 const auto &MPI = Index.modulePaths().find(M.first);
464 if (MPI == Index.modulePaths().end()) {
465 // This should only happen if the bitcode file was empty, in which
466 // case we shouldn't be importing (the ModuleToSummariesForIndex
467 // would only include the module we are writing and index for).
468 assert(ModuleToSummariesForIndex->size() == 1);
469 continue;
471 Callback(*MPI);
473 } else {
474 for (const auto &MPSE : Index.modulePaths())
475 Callback(MPSE);
479 /// Main entry point for writing a combined index to bitcode.
480 void write();
482 private:
483 void writeModStrings();
484 void writeCombinedGlobalValueSummary();
486 Optional<unsigned> getValueId(GlobalValue::GUID ValGUID) {
487 auto VMI = GUIDToValueIdMap.find(ValGUID);
488 if (VMI == GUIDToValueIdMap.end())
489 return None;
490 return VMI->second;
493 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
496 } // end anonymous namespace
498 static unsigned getEncodedCastOpcode(unsigned Opcode) {
499 switch (Opcode) {
500 default: llvm_unreachable("Unknown cast instruction!");
501 case Instruction::Trunc : return bitc::CAST_TRUNC;
502 case Instruction::ZExt : return bitc::CAST_ZEXT;
503 case Instruction::SExt : return bitc::CAST_SEXT;
504 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
505 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
506 case Instruction::UIToFP : return bitc::CAST_UITOFP;
507 case Instruction::SIToFP : return bitc::CAST_SITOFP;
508 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
509 case Instruction::FPExt : return bitc::CAST_FPEXT;
510 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
511 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
512 case Instruction::BitCast : return bitc::CAST_BITCAST;
513 case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
517 static unsigned getEncodedUnaryOpcode(unsigned Opcode) {
518 switch (Opcode) {
519 default: llvm_unreachable("Unknown binary instruction!");
520 case Instruction::FNeg: return bitc::UNOP_NEG;
524 static unsigned getEncodedBinaryOpcode(unsigned Opcode) {
525 switch (Opcode) {
526 default: llvm_unreachable("Unknown binary instruction!");
527 case Instruction::Add:
528 case Instruction::FAdd: return bitc::BINOP_ADD;
529 case Instruction::Sub:
530 case Instruction::FSub: return bitc::BINOP_SUB;
531 case Instruction::Mul:
532 case Instruction::FMul: return bitc::BINOP_MUL;
533 case Instruction::UDiv: return bitc::BINOP_UDIV;
534 case Instruction::FDiv:
535 case Instruction::SDiv: return bitc::BINOP_SDIV;
536 case Instruction::URem: return bitc::BINOP_UREM;
537 case Instruction::FRem:
538 case Instruction::SRem: return bitc::BINOP_SREM;
539 case Instruction::Shl: return bitc::BINOP_SHL;
540 case Instruction::LShr: return bitc::BINOP_LSHR;
541 case Instruction::AShr: return bitc::BINOP_ASHR;
542 case Instruction::And: return bitc::BINOP_AND;
543 case Instruction::Or: return bitc::BINOP_OR;
544 case Instruction::Xor: return bitc::BINOP_XOR;
548 static unsigned getEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
549 switch (Op) {
550 default: llvm_unreachable("Unknown RMW operation!");
551 case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
552 case AtomicRMWInst::Add: return bitc::RMW_ADD;
553 case AtomicRMWInst::Sub: return bitc::RMW_SUB;
554 case AtomicRMWInst::And: return bitc::RMW_AND;
555 case AtomicRMWInst::Nand: return bitc::RMW_NAND;
556 case AtomicRMWInst::Or: return bitc::RMW_OR;
557 case AtomicRMWInst::Xor: return bitc::RMW_XOR;
558 case AtomicRMWInst::Max: return bitc::RMW_MAX;
559 case AtomicRMWInst::Min: return bitc::RMW_MIN;
560 case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
561 case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
562 case AtomicRMWInst::FAdd: return bitc::RMW_FADD;
563 case AtomicRMWInst::FSub: return bitc::RMW_FSUB;
567 static unsigned getEncodedOrdering(AtomicOrdering Ordering) {
568 switch (Ordering) {
569 case AtomicOrdering::NotAtomic: return bitc::ORDERING_NOTATOMIC;
570 case AtomicOrdering::Unordered: return bitc::ORDERING_UNORDERED;
571 case AtomicOrdering::Monotonic: return bitc::ORDERING_MONOTONIC;
572 case AtomicOrdering::Acquire: return bitc::ORDERING_ACQUIRE;
573 case AtomicOrdering::Release: return bitc::ORDERING_RELEASE;
574 case AtomicOrdering::AcquireRelease: return bitc::ORDERING_ACQREL;
575 case AtomicOrdering::SequentiallyConsistent: return bitc::ORDERING_SEQCST;
577 llvm_unreachable("Invalid ordering");
580 static void writeStringRecord(BitstreamWriter &Stream, unsigned Code,
581 StringRef Str, unsigned AbbrevToUse) {
582 SmallVector<unsigned, 64> Vals;
584 // Code: [strchar x N]
585 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
586 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
587 AbbrevToUse = 0;
588 Vals.push_back(Str[i]);
591 // Emit the finished record.
592 Stream.EmitRecord(Code, Vals, AbbrevToUse);
595 static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
596 switch (Kind) {
597 case Attribute::Alignment:
598 return bitc::ATTR_KIND_ALIGNMENT;
599 case Attribute::AllocSize:
600 return bitc::ATTR_KIND_ALLOC_SIZE;
601 case Attribute::AlwaysInline:
602 return bitc::ATTR_KIND_ALWAYS_INLINE;
603 case Attribute::ArgMemOnly:
604 return bitc::ATTR_KIND_ARGMEMONLY;
605 case Attribute::Builtin:
606 return bitc::ATTR_KIND_BUILTIN;
607 case Attribute::ByVal:
608 return bitc::ATTR_KIND_BY_VAL;
609 case Attribute::Convergent:
610 return bitc::ATTR_KIND_CONVERGENT;
611 case Attribute::InAlloca:
612 return bitc::ATTR_KIND_IN_ALLOCA;
613 case Attribute::Cold:
614 return bitc::ATTR_KIND_COLD;
615 case Attribute::InaccessibleMemOnly:
616 return bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY;
617 case Attribute::InaccessibleMemOrArgMemOnly:
618 return bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY;
619 case Attribute::InlineHint:
620 return bitc::ATTR_KIND_INLINE_HINT;
621 case Attribute::InReg:
622 return bitc::ATTR_KIND_IN_REG;
623 case Attribute::JumpTable:
624 return bitc::ATTR_KIND_JUMP_TABLE;
625 case Attribute::MinSize:
626 return bitc::ATTR_KIND_MIN_SIZE;
627 case Attribute::Naked:
628 return bitc::ATTR_KIND_NAKED;
629 case Attribute::Nest:
630 return bitc::ATTR_KIND_NEST;
631 case Attribute::NoAlias:
632 return bitc::ATTR_KIND_NO_ALIAS;
633 case Attribute::NoBuiltin:
634 return bitc::ATTR_KIND_NO_BUILTIN;
635 case Attribute::NoCapture:
636 return bitc::ATTR_KIND_NO_CAPTURE;
637 case Attribute::NoDuplicate:
638 return bitc::ATTR_KIND_NO_DUPLICATE;
639 case Attribute::NoImplicitFloat:
640 return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
641 case Attribute::NoInline:
642 return bitc::ATTR_KIND_NO_INLINE;
643 case Attribute::NoRecurse:
644 return bitc::ATTR_KIND_NO_RECURSE;
645 case Attribute::NonLazyBind:
646 return bitc::ATTR_KIND_NON_LAZY_BIND;
647 case Attribute::NonNull:
648 return bitc::ATTR_KIND_NON_NULL;
649 case Attribute::Dereferenceable:
650 return bitc::ATTR_KIND_DEREFERENCEABLE;
651 case Attribute::DereferenceableOrNull:
652 return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL;
653 case Attribute::NoRedZone:
654 return bitc::ATTR_KIND_NO_RED_ZONE;
655 case Attribute::NoReturn:
656 return bitc::ATTR_KIND_NO_RETURN;
657 case Attribute::NoCfCheck:
658 return bitc::ATTR_KIND_NOCF_CHECK;
659 case Attribute::NoUnwind:
660 return bitc::ATTR_KIND_NO_UNWIND;
661 case Attribute::OptForFuzzing:
662 return bitc::ATTR_KIND_OPT_FOR_FUZZING;
663 case Attribute::OptimizeForSize:
664 return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
665 case Attribute::OptimizeNone:
666 return bitc::ATTR_KIND_OPTIMIZE_NONE;
667 case Attribute::ReadNone:
668 return bitc::ATTR_KIND_READ_NONE;
669 case Attribute::ReadOnly:
670 return bitc::ATTR_KIND_READ_ONLY;
671 case Attribute::Returned:
672 return bitc::ATTR_KIND_RETURNED;
673 case Attribute::ReturnsTwice:
674 return bitc::ATTR_KIND_RETURNS_TWICE;
675 case Attribute::SExt:
676 return bitc::ATTR_KIND_S_EXT;
677 case Attribute::Speculatable:
678 return bitc::ATTR_KIND_SPECULATABLE;
679 case Attribute::StackAlignment:
680 return bitc::ATTR_KIND_STACK_ALIGNMENT;
681 case Attribute::StackProtect:
682 return bitc::ATTR_KIND_STACK_PROTECT;
683 case Attribute::StackProtectReq:
684 return bitc::ATTR_KIND_STACK_PROTECT_REQ;
685 case Attribute::StackProtectStrong:
686 return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
687 case Attribute::SafeStack:
688 return bitc::ATTR_KIND_SAFESTACK;
689 case Attribute::ShadowCallStack:
690 return bitc::ATTR_KIND_SHADOWCALLSTACK;
691 case Attribute::StrictFP:
692 return bitc::ATTR_KIND_STRICT_FP;
693 case Attribute::StructRet:
694 return bitc::ATTR_KIND_STRUCT_RET;
695 case Attribute::SanitizeAddress:
696 return bitc::ATTR_KIND_SANITIZE_ADDRESS;
697 case Attribute::SanitizeHWAddress:
698 return bitc::ATTR_KIND_SANITIZE_HWADDRESS;
699 case Attribute::SanitizeThread:
700 return bitc::ATTR_KIND_SANITIZE_THREAD;
701 case Attribute::SanitizeMemory:
702 return bitc::ATTR_KIND_SANITIZE_MEMORY;
703 case Attribute::SpeculativeLoadHardening:
704 return bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING;
705 case Attribute::SwiftError:
706 return bitc::ATTR_KIND_SWIFT_ERROR;
707 case Attribute::SwiftSelf:
708 return bitc::ATTR_KIND_SWIFT_SELF;
709 case Attribute::UWTable:
710 return bitc::ATTR_KIND_UW_TABLE;
711 case Attribute::WriteOnly:
712 return bitc::ATTR_KIND_WRITEONLY;
713 case Attribute::ZExt:
714 return bitc::ATTR_KIND_Z_EXT;
715 case Attribute::EndAttrKinds:
716 llvm_unreachable("Can not encode end-attribute kinds marker.");
717 case Attribute::None:
718 llvm_unreachable("Can not encode none-attribute.");
721 llvm_unreachable("Trying to encode unknown attribute");
724 void ModuleBitcodeWriter::writeAttributeGroupTable() {
725 const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
726 VE.getAttributeGroups();
727 if (AttrGrps.empty()) return;
729 Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
731 SmallVector<uint64_t, 64> Record;
732 for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) {
733 unsigned AttrListIndex = Pair.first;
734 AttributeSet AS = Pair.second;
735 Record.push_back(VE.getAttributeGroupID(Pair));
736 Record.push_back(AttrListIndex);
738 for (Attribute Attr : AS) {
739 if (Attr.isEnumAttribute()) {
740 Record.push_back(0);
741 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
742 } else if (Attr.isIntAttribute()) {
743 Record.push_back(1);
744 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
745 Record.push_back(Attr.getValueAsInt());
746 } else {
747 StringRef Kind = Attr.getKindAsString();
748 StringRef Val = Attr.getValueAsString();
750 Record.push_back(Val.empty() ? 3 : 4);
751 Record.append(Kind.begin(), Kind.end());
752 Record.push_back(0);
753 if (!Val.empty()) {
754 Record.append(Val.begin(), Val.end());
755 Record.push_back(0);
760 Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
761 Record.clear();
764 Stream.ExitBlock();
767 void ModuleBitcodeWriter::writeAttributeTable() {
768 const std::vector<AttributeList> &Attrs = VE.getAttributeLists();
769 if (Attrs.empty()) return;
771 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
773 SmallVector<uint64_t, 64> Record;
774 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
775 AttributeList AL = Attrs[i];
776 for (unsigned i = AL.index_begin(), e = AL.index_end(); i != e; ++i) {
777 AttributeSet AS = AL.getAttributes(i);
778 if (AS.hasAttributes())
779 Record.push_back(VE.getAttributeGroupID({i, AS}));
782 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
783 Record.clear();
786 Stream.ExitBlock();
789 /// WriteTypeTable - Write out the type table for a module.
790 void ModuleBitcodeWriter::writeTypeTable() {
791 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
793 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
794 SmallVector<uint64_t, 64> TypeVals;
796 uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies();
798 // Abbrev for TYPE_CODE_POINTER.
799 auto Abbv = std::make_shared<BitCodeAbbrev>();
800 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
801 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
802 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
803 unsigned PtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
805 // Abbrev for TYPE_CODE_FUNCTION.
806 Abbv = std::make_shared<BitCodeAbbrev>();
807 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
808 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
809 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
810 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
811 unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));
813 // Abbrev for TYPE_CODE_STRUCT_ANON.
814 Abbv = std::make_shared<BitCodeAbbrev>();
815 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
816 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
817 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
818 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
819 unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));
821 // Abbrev for TYPE_CODE_STRUCT_NAME.
822 Abbv = std::make_shared<BitCodeAbbrev>();
823 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
824 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
825 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
826 unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
828 // Abbrev for TYPE_CODE_STRUCT_NAMED.
829 Abbv = std::make_shared<BitCodeAbbrev>();
830 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
831 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
832 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
833 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
834 unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));
836 // Abbrev for TYPE_CODE_ARRAY.
837 Abbv = std::make_shared<BitCodeAbbrev>();
838 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
839 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
840 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
841 unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));
843 // Emit an entry count so the reader can reserve space.
844 TypeVals.push_back(TypeList.size());
845 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
846 TypeVals.clear();
848 // Loop over all of the types, emitting each in turn.
849 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
850 Type *T = TypeList[i];
851 int AbbrevToUse = 0;
852 unsigned Code = 0;
854 switch (T->getTypeID()) {
855 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
856 case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break;
857 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
858 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
859 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
860 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
861 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
862 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
863 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
864 case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break;
865 case Type::TokenTyID: Code = bitc::TYPE_CODE_TOKEN; break;
866 case Type::IntegerTyID:
867 // INTEGER: [width]
868 Code = bitc::TYPE_CODE_INTEGER;
869 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
870 break;
871 case Type::PointerTyID: {
872 PointerType *PTy = cast<PointerType>(T);
873 // POINTER: [pointee type, address space]
874 Code = bitc::TYPE_CODE_POINTER;
875 TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
876 unsigned AddressSpace = PTy->getAddressSpace();
877 TypeVals.push_back(AddressSpace);
878 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
879 break;
881 case Type::FunctionTyID: {
882 FunctionType *FT = cast<FunctionType>(T);
883 // FUNCTION: [isvararg, retty, paramty x N]
884 Code = bitc::TYPE_CODE_FUNCTION;
885 TypeVals.push_back(FT->isVarArg());
886 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
887 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
888 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
889 AbbrevToUse = FunctionAbbrev;
890 break;
892 case Type::StructTyID: {
893 StructType *ST = cast<StructType>(T);
894 // STRUCT: [ispacked, eltty x N]
895 TypeVals.push_back(ST->isPacked());
896 // Output all of the element types.
897 for (StructType::element_iterator I = ST->element_begin(),
898 E = ST->element_end(); I != E; ++I)
899 TypeVals.push_back(VE.getTypeID(*I));
901 if (ST->isLiteral()) {
902 Code = bitc::TYPE_CODE_STRUCT_ANON;
903 AbbrevToUse = StructAnonAbbrev;
904 } else {
905 if (ST->isOpaque()) {
906 Code = bitc::TYPE_CODE_OPAQUE;
907 } else {
908 Code = bitc::TYPE_CODE_STRUCT_NAMED;
909 AbbrevToUse = StructNamedAbbrev;
912 // Emit the name if it is present.
913 if (!ST->getName().empty())
914 writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
915 StructNameAbbrev);
917 break;
919 case Type::ArrayTyID: {
920 ArrayType *AT = cast<ArrayType>(T);
921 // ARRAY: [numelts, eltty]
922 Code = bitc::TYPE_CODE_ARRAY;
923 TypeVals.push_back(AT->getNumElements());
924 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
925 AbbrevToUse = ArrayAbbrev;
926 break;
928 case Type::VectorTyID: {
929 VectorType *VT = cast<VectorType>(T);
930 // VECTOR [numelts, eltty]
931 Code = bitc::TYPE_CODE_VECTOR;
932 TypeVals.push_back(VT->getNumElements());
933 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
934 break;
938 // Emit the finished record.
939 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
940 TypeVals.clear();
943 Stream.ExitBlock();
946 static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {
947 switch (Linkage) {
948 case GlobalValue::ExternalLinkage:
949 return 0;
950 case GlobalValue::WeakAnyLinkage:
951 return 16;
952 case GlobalValue::AppendingLinkage:
953 return 2;
954 case GlobalValue::InternalLinkage:
955 return 3;
956 case GlobalValue::LinkOnceAnyLinkage:
957 return 18;
958 case GlobalValue::ExternalWeakLinkage:
959 return 7;
960 case GlobalValue::CommonLinkage:
961 return 8;
962 case GlobalValue::PrivateLinkage:
963 return 9;
964 case GlobalValue::WeakODRLinkage:
965 return 17;
966 case GlobalValue::LinkOnceODRLinkage:
967 return 19;
968 case GlobalValue::AvailableExternallyLinkage:
969 return 12;
971 llvm_unreachable("Invalid linkage");
974 static unsigned getEncodedLinkage(const GlobalValue &GV) {
975 return getEncodedLinkage(GV.getLinkage());
978 static uint64_t getEncodedFFlags(FunctionSummary::FFlags Flags) {
979 uint64_t RawFlags = 0;
980 RawFlags |= Flags.ReadNone;
981 RawFlags |= (Flags.ReadOnly << 1);
982 RawFlags |= (Flags.NoRecurse << 2);
983 RawFlags |= (Flags.ReturnDoesNotAlias << 3);
984 RawFlags |= (Flags.NoInline << 4);
985 return RawFlags;
988 // Decode the flags for GlobalValue in the summary
989 static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags) {
990 uint64_t RawFlags = 0;
992 RawFlags |= Flags.NotEligibleToImport; // bool
993 RawFlags |= (Flags.Live << 1);
994 RawFlags |= (Flags.DSOLocal << 2);
996 // Linkage don't need to be remapped at that time for the summary. Any future
997 // change to the getEncodedLinkage() function will need to be taken into
998 // account here as well.
999 RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits
1001 return RawFlags;
1004 static uint64_t getEncodedGVarFlags(GlobalVarSummary::GVarFlags Flags) {
1005 uint64_t RawFlags = Flags.ReadOnly;
1006 return RawFlags;
1009 static unsigned getEncodedVisibility(const GlobalValue &GV) {
1010 switch (GV.getVisibility()) {
1011 case GlobalValue::DefaultVisibility: return 0;
1012 case GlobalValue::HiddenVisibility: return 1;
1013 case GlobalValue::ProtectedVisibility: return 2;
1015 llvm_unreachable("Invalid visibility");
1018 static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
1019 switch (GV.getDLLStorageClass()) {
1020 case GlobalValue::DefaultStorageClass: return 0;
1021 case GlobalValue::DLLImportStorageClass: return 1;
1022 case GlobalValue::DLLExportStorageClass: return 2;
1024 llvm_unreachable("Invalid DLL storage class");
1027 static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
1028 switch (GV.getThreadLocalMode()) {
1029 case GlobalVariable::NotThreadLocal: return 0;
1030 case GlobalVariable::GeneralDynamicTLSModel: return 1;
1031 case GlobalVariable::LocalDynamicTLSModel: return 2;
1032 case GlobalVariable::InitialExecTLSModel: return 3;
1033 case GlobalVariable::LocalExecTLSModel: return 4;
1035 llvm_unreachable("Invalid TLS model");
1038 static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
1039 switch (C.getSelectionKind()) {
1040 case Comdat::Any:
1041 return bitc::COMDAT_SELECTION_KIND_ANY;
1042 case Comdat::ExactMatch:
1043 return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
1044 case Comdat::Largest:
1045 return bitc::COMDAT_SELECTION_KIND_LARGEST;
1046 case Comdat::NoDuplicates:
1047 return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
1048 case Comdat::SameSize:
1049 return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
1051 llvm_unreachable("Invalid selection kind");
1054 static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) {
1055 switch (GV.getUnnamedAddr()) {
1056 case GlobalValue::UnnamedAddr::None: return 0;
1057 case GlobalValue::UnnamedAddr::Local: return 2;
1058 case GlobalValue::UnnamedAddr::Global: return 1;
1060 llvm_unreachable("Invalid unnamed_addr");
1063 size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) {
1064 if (GenerateHash)
1065 Hasher.update(Str);
1066 return StrtabBuilder.add(Str);
1069 void ModuleBitcodeWriter::writeComdats() {
1070 SmallVector<unsigned, 64> Vals;
1071 for (const Comdat *C : VE.getComdats()) {
1072 // COMDAT: [strtab offset, strtab size, selection_kind]
1073 Vals.push_back(addToStrtab(C->getName()));
1074 Vals.push_back(C->getName().size());
1075 Vals.push_back(getEncodedComdatSelectionKind(*C));
1076 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
1077 Vals.clear();
1081 /// Write a record that will eventually hold the word offset of the
1082 /// module-level VST. For now the offset is 0, which will be backpatched
1083 /// after the real VST is written. Saves the bit offset to backpatch.
1084 void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
1085 // Write a placeholder value in for the offset of the real VST,
1086 // which is written after the function blocks so that it can include
1087 // the offset of each function. The placeholder offset will be
1088 // updated when the real VST is written.
1089 auto Abbv = std::make_shared<BitCodeAbbrev>();
1090 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET));
1091 // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
1092 // hold the real VST offset. Must use fixed instead of VBR as we don't
1093 // know how many VBR chunks to reserve ahead of time.
1094 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1095 unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1097 // Emit the placeholder
1098 uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0};
1099 Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
1101 // Compute and save the bit offset to the placeholder, which will be
1102 // patched when the real VST is written. We can simply subtract the 32-bit
1103 // fixed size from the current bit number to get the location to backpatch.
1104 VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32;
1107 enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 };
1109 /// Determine the encoding to use for the given string name and length.
1110 static StringEncoding getStringEncoding(StringRef Str) {
1111 bool isChar6 = true;
1112 for (char C : Str) {
1113 if (isChar6)
1114 isChar6 = BitCodeAbbrevOp::isChar6(C);
1115 if ((unsigned char)C & 128)
1116 // don't bother scanning the rest.
1117 return SE_Fixed8;
1119 if (isChar6)
1120 return SE_Char6;
1121 return SE_Fixed7;
1124 /// Emit top-level description of module, including target triple, inline asm,
1125 /// descriptors for global variables, and function prototype info.
1126 /// Returns the bit offset to backpatch with the location of the real VST.
1127 void ModuleBitcodeWriter::writeModuleInfo() {
1128 // Emit various pieces of data attached to a module.
1129 if (!M.getTargetTriple().empty())
1130 writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(),
1131 0 /*TODO*/);
1132 const std::string &DL = M.getDataLayoutStr();
1133 if (!DL.empty())
1134 writeStringRecord(Stream, bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/);
1135 if (!M.getModuleInlineAsm().empty())
1136 writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(),
1137 0 /*TODO*/);
1139 // Emit information about sections and GC, computing how many there are. Also
1140 // compute the maximum alignment value.
1141 std::map<std::string, unsigned> SectionMap;
1142 std::map<std::string, unsigned> GCMap;
1143 unsigned MaxAlignment = 0;
1144 unsigned MaxGlobalType = 0;
1145 for (const GlobalValue &GV : M.globals()) {
1146 MaxAlignment = std::max(MaxAlignment, GV.getAlignment());
1147 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
1148 if (GV.hasSection()) {
1149 // Give section names unique ID's.
1150 unsigned &Entry = SectionMap[GV.getSection()];
1151 if (!Entry) {
1152 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
1153 0 /*TODO*/);
1154 Entry = SectionMap.size();
1158 for (const Function &F : M) {
1159 MaxAlignment = std::max(MaxAlignment, F.getAlignment());
1160 if (F.hasSection()) {
1161 // Give section names unique ID's.
1162 unsigned &Entry = SectionMap[F.getSection()];
1163 if (!Entry) {
1164 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
1165 0 /*TODO*/);
1166 Entry = SectionMap.size();
1169 if (F.hasGC()) {
1170 // Same for GC names.
1171 unsigned &Entry = GCMap[F.getGC()];
1172 if (!Entry) {
1173 writeStringRecord(Stream, bitc::MODULE_CODE_GCNAME, F.getGC(),
1174 0 /*TODO*/);
1175 Entry = GCMap.size();
1180 // Emit abbrev for globals, now that we know # sections and max alignment.
1181 unsigned SimpleGVarAbbrev = 0;
1182 if (!M.global_empty()) {
1183 // Add an abbrev for common globals with no visibility or thread localness.
1184 auto Abbv = std::make_shared<BitCodeAbbrev>();
1185 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
1186 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1187 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1188 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1189 Log2_32_Ceil(MaxGlobalType+1)));
1190 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2
1191 //| explicitType << 1
1192 //| constant
1193 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
1194 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
1195 if (MaxAlignment == 0) // Alignment.
1196 Abbv->Add(BitCodeAbbrevOp(0));
1197 else {
1198 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
1199 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1200 Log2_32_Ceil(MaxEncAlignment+1)));
1202 if (SectionMap.empty()) // Section.
1203 Abbv->Add(BitCodeAbbrevOp(0));
1204 else
1205 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1206 Log2_32_Ceil(SectionMap.size()+1)));
1207 // Don't bother emitting vis + thread local.
1208 SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1211 SmallVector<unsigned, 64> Vals;
1212 // Emit the module's source file name.
1214 StringEncoding Bits = getStringEncoding(M.getSourceFileName());
1215 BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
1216 if (Bits == SE_Char6)
1217 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
1218 else if (Bits == SE_Fixed7)
1219 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
1221 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
1222 auto Abbv = std::make_shared<BitCodeAbbrev>();
1223 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
1224 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1225 Abbv->Add(AbbrevOpToUse);
1226 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1228 for (const auto P : M.getSourceFileName())
1229 Vals.push_back((unsigned char)P);
1231 // Emit the finished record.
1232 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
1233 Vals.clear();
1236 // Emit the global variable information.
1237 for (const GlobalVariable &GV : M.globals()) {
1238 unsigned AbbrevToUse = 0;
1240 // GLOBALVAR: [strtab offset, strtab size, type, isconst, initid,
1241 // linkage, alignment, section, visibility, threadlocal,
1242 // unnamed_addr, externally_initialized, dllstorageclass,
1243 // comdat, attributes, DSO_Local]
1244 Vals.push_back(addToStrtab(GV.getName()));
1245 Vals.push_back(GV.getName().size());
1246 Vals.push_back(VE.getTypeID(GV.getValueType()));
1247 Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
1248 Vals.push_back(GV.isDeclaration() ? 0 :
1249 (VE.getValueID(GV.getInitializer()) + 1));
1250 Vals.push_back(getEncodedLinkage(GV));
1251 Vals.push_back(Log2_32(GV.getAlignment())+1);
1252 Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0);
1253 if (GV.isThreadLocal() ||
1254 GV.getVisibility() != GlobalValue::DefaultVisibility ||
1255 GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1256 GV.isExternallyInitialized() ||
1257 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
1258 GV.hasComdat() ||
1259 GV.hasAttributes() ||
1260 GV.isDSOLocal()) {
1261 Vals.push_back(getEncodedVisibility(GV));
1262 Vals.push_back(getEncodedThreadLocalMode(GV));
1263 Vals.push_back(getEncodedUnnamedAddr(GV));
1264 Vals.push_back(GV.isExternallyInitialized());
1265 Vals.push_back(getEncodedDLLStorageClass(GV));
1266 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
1268 auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
1269 Vals.push_back(VE.getAttributeListID(AL));
1271 Vals.push_back(GV.isDSOLocal());
1272 } else {
1273 AbbrevToUse = SimpleGVarAbbrev;
1276 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
1277 Vals.clear();
1280 // Emit the function proto information.
1281 for (const Function &F : M) {
1282 // FUNCTION: [strtab offset, strtab size, type, callingconv, isproto,
1283 // linkage, paramattrs, alignment, section, visibility, gc,
1284 // unnamed_addr, prologuedata, dllstorageclass, comdat,
1285 // prefixdata, personalityfn, DSO_Local, addrspace]
1286 Vals.push_back(addToStrtab(F.getName()));
1287 Vals.push_back(F.getName().size());
1288 Vals.push_back(VE.getTypeID(F.getFunctionType()));
1289 Vals.push_back(F.getCallingConv());
1290 Vals.push_back(F.isDeclaration());
1291 Vals.push_back(getEncodedLinkage(F));
1292 Vals.push_back(VE.getAttributeListID(F.getAttributes()));
1293 Vals.push_back(Log2_32(F.getAlignment())+1);
1294 Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0);
1295 Vals.push_back(getEncodedVisibility(F));
1296 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
1297 Vals.push_back(getEncodedUnnamedAddr(F));
1298 Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
1299 : 0);
1300 Vals.push_back(getEncodedDLLStorageClass(F));
1301 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
1302 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
1303 : 0);
1304 Vals.push_back(
1305 F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
1307 Vals.push_back(F.isDSOLocal());
1308 Vals.push_back(F.getAddressSpace());
1310 unsigned AbbrevToUse = 0;
1311 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
1312 Vals.clear();
1315 // Emit the alias information.
1316 for (const GlobalAlias &A : M.aliases()) {
1317 // ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage,
1318 // visibility, dllstorageclass, threadlocal, unnamed_addr,
1319 // DSO_Local]
1320 Vals.push_back(addToStrtab(A.getName()));
1321 Vals.push_back(A.getName().size());
1322 Vals.push_back(VE.getTypeID(A.getValueType()));
1323 Vals.push_back(A.getType()->getAddressSpace());
1324 Vals.push_back(VE.getValueID(A.getAliasee()));
1325 Vals.push_back(getEncodedLinkage(A));
1326 Vals.push_back(getEncodedVisibility(A));
1327 Vals.push_back(getEncodedDLLStorageClass(A));
1328 Vals.push_back(getEncodedThreadLocalMode(A));
1329 Vals.push_back(getEncodedUnnamedAddr(A));
1330 Vals.push_back(A.isDSOLocal());
1332 unsigned AbbrevToUse = 0;
1333 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
1334 Vals.clear();
1337 // Emit the ifunc information.
1338 for (const GlobalIFunc &I : M.ifuncs()) {
1339 // IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver
1340 // val#, linkage, visibility, DSO_Local]
1341 Vals.push_back(addToStrtab(I.getName()));
1342 Vals.push_back(I.getName().size());
1343 Vals.push_back(VE.getTypeID(I.getValueType()));
1344 Vals.push_back(I.getType()->getAddressSpace());
1345 Vals.push_back(VE.getValueID(I.getResolver()));
1346 Vals.push_back(getEncodedLinkage(I));
1347 Vals.push_back(getEncodedVisibility(I));
1348 Vals.push_back(I.isDSOLocal());
1349 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
1350 Vals.clear();
1353 writeValueSymbolTableForwardDecl();
1356 static uint64_t getOptimizationFlags(const Value *V) {
1357 uint64_t Flags = 0;
1359 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
1360 if (OBO->hasNoSignedWrap())
1361 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
1362 if (OBO->hasNoUnsignedWrap())
1363 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
1364 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
1365 if (PEO->isExact())
1366 Flags |= 1 << bitc::PEO_EXACT;
1367 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
1368 if (FPMO->hasAllowReassoc())
1369 Flags |= bitc::AllowReassoc;
1370 if (FPMO->hasNoNaNs())
1371 Flags |= bitc::NoNaNs;
1372 if (FPMO->hasNoInfs())
1373 Flags |= bitc::NoInfs;
1374 if (FPMO->hasNoSignedZeros())
1375 Flags |= bitc::NoSignedZeros;
1376 if (FPMO->hasAllowReciprocal())
1377 Flags |= bitc::AllowReciprocal;
1378 if (FPMO->hasAllowContract())
1379 Flags |= bitc::AllowContract;
1380 if (FPMO->hasApproxFunc())
1381 Flags |= bitc::ApproxFunc;
1384 return Flags;
1387 void ModuleBitcodeWriter::writeValueAsMetadata(
1388 const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
1389 // Mimic an MDNode with a value as one operand.
1390 Value *V = MD->getValue();
1391 Record.push_back(VE.getTypeID(V->getType()));
1392 Record.push_back(VE.getValueID(V));
1393 Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
1394 Record.clear();
1397 void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N,
1398 SmallVectorImpl<uint64_t> &Record,
1399 unsigned Abbrev) {
1400 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1401 Metadata *MD = N->getOperand(i);
1402 assert(!(MD && isa<LocalAsMetadata>(MD)) &&
1403 "Unexpected function-local metadata");
1404 Record.push_back(VE.getMetadataOrNullID(MD));
1406 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
1407 : bitc::METADATA_NODE,
1408 Record, Abbrev);
1409 Record.clear();
1412 unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
1413 // Assume the column is usually under 128, and always output the inlined-at
1414 // location (it's never more expensive than building an array size 1).
1415 auto Abbv = std::make_shared<BitCodeAbbrev>();
1416 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
1417 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1418 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1419 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1420 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1421 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1422 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1423 return Stream.EmitAbbrev(std::move(Abbv));
1426 void ModuleBitcodeWriter::writeDILocation(const DILocation *N,
1427 SmallVectorImpl<uint64_t> &Record,
1428 unsigned &Abbrev) {
1429 if (!Abbrev)
1430 Abbrev = createDILocationAbbrev();
1432 Record.push_back(N->isDistinct());
1433 Record.push_back(N->getLine());
1434 Record.push_back(N->getColumn());
1435 Record.push_back(VE.getMetadataID(N->getScope()));
1436 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
1437 Record.push_back(N->isImplicitCode());
1439 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
1440 Record.clear();
1443 unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
1444 // Assume the column is usually under 128, and always output the inlined-at
1445 // location (it's never more expensive than building an array size 1).
1446 auto Abbv = std::make_shared<BitCodeAbbrev>();
1447 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
1448 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1449 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1450 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1451 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1452 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1453 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1454 return Stream.EmitAbbrev(std::move(Abbv));
1457 void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N,
1458 SmallVectorImpl<uint64_t> &Record,
1459 unsigned &Abbrev) {
1460 if (!Abbrev)
1461 Abbrev = createGenericDINodeAbbrev();
1463 Record.push_back(N->isDistinct());
1464 Record.push_back(N->getTag());
1465 Record.push_back(0); // Per-tag version field; unused for now.
1467 for (auto &I : N->operands())
1468 Record.push_back(VE.getMetadataOrNullID(I));
1470 Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
1471 Record.clear();
1474 static uint64_t rotateSign(int64_t I) {
1475 uint64_t U = I;
1476 return I < 0 ? ~(U << 1) : U << 1;
1479 void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N,
1480 SmallVectorImpl<uint64_t> &Record,
1481 unsigned Abbrev) {
1482 const uint64_t Version = 1 << 1;
1483 Record.push_back((uint64_t)N->isDistinct() | Version);
1484 Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
1485 Record.push_back(rotateSign(N->getLowerBound()));
1487 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
1488 Record.clear();
1491 void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,
1492 SmallVectorImpl<uint64_t> &Record,
1493 unsigned Abbrev) {
1494 Record.push_back((N->isUnsigned() << 1) | N->isDistinct());
1495 Record.push_back(rotateSign(N->getValue()));
1496 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1498 Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
1499 Record.clear();
1502 void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N,
1503 SmallVectorImpl<uint64_t> &Record,
1504 unsigned Abbrev) {
1505 Record.push_back(N->isDistinct());
1506 Record.push_back(N->getTag());
1507 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1508 Record.push_back(N->getSizeInBits());
1509 Record.push_back(N->getAlignInBits());
1510 Record.push_back(N->getEncoding());
1511 Record.push_back(N->getFlags());
1513 Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
1514 Record.clear();
1517 void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,
1518 SmallVectorImpl<uint64_t> &Record,
1519 unsigned Abbrev) {
1520 Record.push_back(N->isDistinct());
1521 Record.push_back(N->getTag());
1522 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1523 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1524 Record.push_back(N->getLine());
1525 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1526 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1527 Record.push_back(N->getSizeInBits());
1528 Record.push_back(N->getAlignInBits());
1529 Record.push_back(N->getOffsetInBits());
1530 Record.push_back(N->getFlags());
1531 Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
1533 // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
1534 // that there is no DWARF address space associated with DIDerivedType.
1535 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
1536 Record.push_back(*DWARFAddressSpace + 1);
1537 else
1538 Record.push_back(0);
1540 Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
1541 Record.clear();
1544 void ModuleBitcodeWriter::writeDICompositeType(
1545 const DICompositeType *N, SmallVectorImpl<uint64_t> &Record,
1546 unsigned Abbrev) {
1547 const unsigned IsNotUsedInOldTypeRef = 0x2;
1548 Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct());
1549 Record.push_back(N->getTag());
1550 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1551 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1552 Record.push_back(N->getLine());
1553 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1554 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1555 Record.push_back(N->getSizeInBits());
1556 Record.push_back(N->getAlignInBits());
1557 Record.push_back(N->getOffsetInBits());
1558 Record.push_back(N->getFlags());
1559 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1560 Record.push_back(N->getRuntimeLang());
1561 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
1562 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1563 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
1564 Record.push_back(VE.getMetadataOrNullID(N->getDiscriminator()));
1566 Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
1567 Record.clear();
1570 void ModuleBitcodeWriter::writeDISubroutineType(
1571 const DISubroutineType *N, SmallVectorImpl<uint64_t> &Record,
1572 unsigned Abbrev) {
1573 const unsigned HasNoOldTypeRefs = 0x2;
1574 Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
1575 Record.push_back(N->getFlags());
1576 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
1577 Record.push_back(N->getCC());
1579 Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
1580 Record.clear();
1583 void ModuleBitcodeWriter::writeDIFile(const DIFile *N,
1584 SmallVectorImpl<uint64_t> &Record,
1585 unsigned Abbrev) {
1586 Record.push_back(N->isDistinct());
1587 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
1588 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
1589 if (N->getRawChecksum()) {
1590 Record.push_back(N->getRawChecksum()->Kind);
1591 Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()->Value));
1592 } else {
1593 // Maintain backwards compatibility with the old internal representation of
1594 // CSK_None in ChecksumKind by writing nulls here when Checksum is None.
1595 Record.push_back(0);
1596 Record.push_back(VE.getMetadataOrNullID(nullptr));
1598 auto Source = N->getRawSource();
1599 if (Source)
1600 Record.push_back(VE.getMetadataOrNullID(*Source));
1602 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
1603 Record.clear();
1606 void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
1607 SmallVectorImpl<uint64_t> &Record,
1608 unsigned Abbrev) {
1609 assert(N->isDistinct() && "Expected distinct compile units");
1610 Record.push_back(/* IsDistinct */ true);
1611 Record.push_back(N->getSourceLanguage());
1612 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1613 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
1614 Record.push_back(N->isOptimized());
1615 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
1616 Record.push_back(N->getRuntimeVersion());
1617 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
1618 Record.push_back(N->getEmissionKind());
1619 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
1620 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
1621 Record.push_back(/* subprograms */ 0);
1622 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
1623 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
1624 Record.push_back(N->getDWOId());
1625 Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
1626 Record.push_back(N->getSplitDebugInlining());
1627 Record.push_back(N->getDebugInfoForProfiling());
1628 Record.push_back((unsigned)N->getNameTableKind());
1630 Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
1631 Record.clear();
1634 void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,
1635 SmallVectorImpl<uint64_t> &Record,
1636 unsigned Abbrev) {
1637 const uint64_t HasUnitFlag = 1 << 1;
1638 const uint64_t HasSPFlagsFlag = 1 << 2;
1639 Record.push_back(uint64_t(N->isDistinct()) | HasUnitFlag | HasSPFlagsFlag);
1640 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1641 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1642 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1643 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1644 Record.push_back(N->getLine());
1645 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1646 Record.push_back(N->getScopeLine());
1647 Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
1648 Record.push_back(N->getSPFlags());
1649 Record.push_back(N->getVirtualIndex());
1650 Record.push_back(N->getFlags());
1651 Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
1652 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1653 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
1654 Record.push_back(VE.getMetadataOrNullID(N->getRetainedNodes().get()));
1655 Record.push_back(N->getThisAdjustment());
1656 Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get()));
1658 Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
1659 Record.clear();
1662 void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
1663 SmallVectorImpl<uint64_t> &Record,
1664 unsigned Abbrev) {
1665 Record.push_back(N->isDistinct());
1666 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1667 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1668 Record.push_back(N->getLine());
1669 Record.push_back(N->getColumn());
1671 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
1672 Record.clear();
1675 void ModuleBitcodeWriter::writeDILexicalBlockFile(
1676 const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record,
1677 unsigned Abbrev) {
1678 Record.push_back(N->isDistinct());
1679 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1680 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1681 Record.push_back(N->getDiscriminator());
1683 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
1684 Record.clear();
1687 void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,
1688 SmallVectorImpl<uint64_t> &Record,
1689 unsigned Abbrev) {
1690 Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
1691 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1692 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1694 Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
1695 Record.clear();
1698 void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,
1699 SmallVectorImpl<uint64_t> &Record,
1700 unsigned Abbrev) {
1701 Record.push_back(N->isDistinct());
1702 Record.push_back(N->getMacinfoType());
1703 Record.push_back(N->getLine());
1704 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1705 Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
1707 Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
1708 Record.clear();
1711 void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,
1712 SmallVectorImpl<uint64_t> &Record,
1713 unsigned Abbrev) {
1714 Record.push_back(N->isDistinct());
1715 Record.push_back(N->getMacinfoType());
1716 Record.push_back(N->getLine());
1717 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1718 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1720 Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
1721 Record.clear();
1724 void ModuleBitcodeWriter::writeDIModule(const DIModule *N,
1725 SmallVectorImpl<uint64_t> &Record,
1726 unsigned Abbrev) {
1727 Record.push_back(N->isDistinct());
1728 for (auto &I : N->operands())
1729 Record.push_back(VE.getMetadataOrNullID(I));
1731 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
1732 Record.clear();
1735 void ModuleBitcodeWriter::writeDITemplateTypeParameter(
1736 const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record,
1737 unsigned Abbrev) {
1738 Record.push_back(N->isDistinct());
1739 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1740 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1742 Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
1743 Record.clear();
1746 void ModuleBitcodeWriter::writeDITemplateValueParameter(
1747 const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record,
1748 unsigned Abbrev) {
1749 Record.push_back(N->isDistinct());
1750 Record.push_back(N->getTag());
1751 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1752 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1753 Record.push_back(VE.getMetadataOrNullID(N->getValue()));
1755 Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
1756 Record.clear();
1759 void ModuleBitcodeWriter::writeDIGlobalVariable(
1760 const DIGlobalVariable *N, SmallVectorImpl<uint64_t> &Record,
1761 unsigned Abbrev) {
1762 const uint64_t Version = 2 << 1;
1763 Record.push_back((uint64_t)N->isDistinct() | Version);
1764 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1765 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1766 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1767 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1768 Record.push_back(N->getLine());
1769 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1770 Record.push_back(N->isLocalToUnit());
1771 Record.push_back(N->isDefinition());
1772 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
1773 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams()));
1774 Record.push_back(N->getAlignInBits());
1776 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
1777 Record.clear();
1780 void ModuleBitcodeWriter::writeDILocalVariable(
1781 const DILocalVariable *N, SmallVectorImpl<uint64_t> &Record,
1782 unsigned Abbrev) {
1783 // In order to support all possible bitcode formats in BitcodeReader we need
1784 // to distinguish the following cases:
1785 // 1) Record has no artificial tag (Record[1]),
1786 // has no obsolete inlinedAt field (Record[9]).
1787 // In this case Record size will be 8, HasAlignment flag is false.
1788 // 2) Record has artificial tag (Record[1]),
1789 // has no obsolete inlignedAt field (Record[9]).
1790 // In this case Record size will be 9, HasAlignment flag is false.
1791 // 3) Record has both artificial tag (Record[1]) and
1792 // obsolete inlignedAt field (Record[9]).
1793 // In this case Record size will be 10, HasAlignment flag is false.
1794 // 4) Record has neither artificial tag, nor inlignedAt field, but
1795 // HasAlignment flag is true and Record[8] contains alignment value.
1796 const uint64_t HasAlignmentFlag = 1 << 1;
1797 Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
1798 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1799 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1800 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1801 Record.push_back(N->getLine());
1802 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1803 Record.push_back(N->getArg());
1804 Record.push_back(N->getFlags());
1805 Record.push_back(N->getAlignInBits());
1807 Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
1808 Record.clear();
1811 void ModuleBitcodeWriter::writeDILabel(
1812 const DILabel *N, SmallVectorImpl<uint64_t> &Record,
1813 unsigned Abbrev) {
1814 Record.push_back((uint64_t)N->isDistinct());
1815 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1816 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1817 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1818 Record.push_back(N->getLine());
1820 Stream.EmitRecord(bitc::METADATA_LABEL, Record, Abbrev);
1821 Record.clear();
1824 void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,
1825 SmallVectorImpl<uint64_t> &Record,
1826 unsigned Abbrev) {
1827 Record.reserve(N->getElements().size() + 1);
1828 const uint64_t Version = 3 << 1;
1829 Record.push_back((uint64_t)N->isDistinct() | Version);
1830 Record.append(N->elements_begin(), N->elements_end());
1832 Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
1833 Record.clear();
1836 void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
1837 const DIGlobalVariableExpression *N, SmallVectorImpl<uint64_t> &Record,
1838 unsigned Abbrev) {
1839 Record.push_back(N->isDistinct());
1840 Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
1841 Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
1843 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR, Record, Abbrev);
1844 Record.clear();
1847 void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
1848 SmallVectorImpl<uint64_t> &Record,
1849 unsigned Abbrev) {
1850 Record.push_back(N->isDistinct());
1851 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1852 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1853 Record.push_back(N->getLine());
1854 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
1855 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
1856 Record.push_back(N->getAttributes());
1857 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1859 Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
1860 Record.clear();
1863 void ModuleBitcodeWriter::writeDIImportedEntity(
1864 const DIImportedEntity *N, SmallVectorImpl<uint64_t> &Record,
1865 unsigned Abbrev) {
1866 Record.push_back(N->isDistinct());
1867 Record.push_back(N->getTag());
1868 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1869 Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
1870 Record.push_back(N->getLine());
1871 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1872 Record.push_back(VE.getMetadataOrNullID(N->getRawFile()));
1874 Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
1875 Record.clear();
1878 unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
1879 auto Abbv = std::make_shared<BitCodeAbbrev>();
1880 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
1881 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1882 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1883 return Stream.EmitAbbrev(std::move(Abbv));
1886 void ModuleBitcodeWriter::writeNamedMetadata(
1887 SmallVectorImpl<uint64_t> &Record) {
1888 if (M.named_metadata_empty())
1889 return;
1891 unsigned Abbrev = createNamedMetadataAbbrev();
1892 for (const NamedMDNode &NMD : M.named_metadata()) {
1893 // Write name.
1894 StringRef Str = NMD.getName();
1895 Record.append(Str.bytes_begin(), Str.bytes_end());
1896 Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
1897 Record.clear();
1899 // Write named metadata operands.
1900 for (const MDNode *N : NMD.operands())
1901 Record.push_back(VE.getMetadataID(N));
1902 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
1903 Record.clear();
1907 unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
1908 auto Abbv = std::make_shared<BitCodeAbbrev>();
1909 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS));
1910 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
1911 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
1912 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1913 return Stream.EmitAbbrev(std::move(Abbv));
1916 /// Write out a record for MDString.
1918 /// All the metadata strings in a metadata block are emitted in a single
1919 /// record. The sizes and strings themselves are shoved into a blob.
1920 void ModuleBitcodeWriter::writeMetadataStrings(
1921 ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) {
1922 if (Strings.empty())
1923 return;
1925 // Start the record with the number of strings.
1926 Record.push_back(bitc::METADATA_STRINGS);
1927 Record.push_back(Strings.size());
1929 // Emit the sizes of the strings in the blob.
1930 SmallString<256> Blob;
1932 BitstreamWriter W(Blob);
1933 for (const Metadata *MD : Strings)
1934 W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
1935 W.FlushToWord();
1938 // Add the offset to the strings to the record.
1939 Record.push_back(Blob.size());
1941 // Add the strings to the blob.
1942 for (const Metadata *MD : Strings)
1943 Blob.append(cast<MDString>(MD)->getString());
1945 // Emit the final record.
1946 Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
1947 Record.clear();
1950 // Generates an enum to use as an index in the Abbrev array of Metadata record.
1951 enum MetadataAbbrev : unsigned {
1952 #define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
1953 #include "llvm/IR/Metadata.def"
1954 LastPlusOne
1957 void ModuleBitcodeWriter::writeMetadataRecords(
1958 ArrayRef<const Metadata *> MDs, SmallVectorImpl<uint64_t> &Record,
1959 std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
1960 if (MDs.empty())
1961 return;
1963 // Initialize MDNode abbreviations.
1964 #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
1965 #include "llvm/IR/Metadata.def"
1967 for (const Metadata *MD : MDs) {
1968 if (IndexPos)
1969 IndexPos->push_back(Stream.GetCurrentBitNo());
1970 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
1971 assert(N->isResolved() && "Expected forward references to be resolved");
1973 switch (N->getMetadataID()) {
1974 default:
1975 llvm_unreachable("Invalid MDNode subclass");
1976 #define HANDLE_MDNODE_LEAF(CLASS) \
1977 case Metadata::CLASS##Kind: \
1978 if (MDAbbrevs) \
1979 write##CLASS(cast<CLASS>(N), Record, \
1980 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
1981 else \
1982 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
1983 continue;
1984 #include "llvm/IR/Metadata.def"
1987 writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
1991 void ModuleBitcodeWriter::writeModuleMetadata() {
1992 if (!VE.hasMDs() && M.named_metadata_empty())
1993 return;
1995 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 4);
1996 SmallVector<uint64_t, 64> Record;
1998 // Emit all abbrevs upfront, so that the reader can jump in the middle of the
1999 // block and load any metadata.
2000 std::vector<unsigned> MDAbbrevs;
2002 MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
2003 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
2004 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
2005 createGenericDINodeAbbrev();
2007 auto Abbv = std::make_shared<BitCodeAbbrev>();
2008 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX_OFFSET));
2009 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2010 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2011 unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2013 Abbv = std::make_shared<BitCodeAbbrev>();
2014 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX));
2015 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2016 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2017 unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2019 // Emit MDStrings together upfront.
2020 writeMetadataStrings(VE.getMDStrings(), Record);
2022 // We only emit an index for the metadata record if we have more than a given
2023 // (naive) threshold of metadatas, otherwise it is not worth it.
2024 if (VE.getNonMDStrings().size() > IndexThreshold) {
2025 // Write a placeholder value in for the offset of the metadata index,
2026 // which is written after the records, so that it can include
2027 // the offset of each entry. The placeholder offset will be
2028 // updated after all records are emitted.
2029 uint64_t Vals[] = {0, 0};
2030 Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
2033 // Compute and save the bit offset to the current position, which will be
2034 // patched when we emit the index later. We can simply subtract the 64-bit
2035 // fixed size from the current bit number to get the location to backpatch.
2036 uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
2038 // This index will contain the bitpos for each individual record.
2039 std::vector<uint64_t> IndexPos;
2040 IndexPos.reserve(VE.getNonMDStrings().size());
2042 // Write all the records
2043 writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
2045 if (VE.getNonMDStrings().size() > IndexThreshold) {
2046 // Now that we have emitted all the records we will emit the index. But
2047 // first
2048 // backpatch the forward reference so that the reader can skip the records
2049 // efficiently.
2050 Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
2051 Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
2053 // Delta encode the index.
2054 uint64_t PreviousValue = IndexOffsetRecordBitPos;
2055 for (auto &Elt : IndexPos) {
2056 auto EltDelta = Elt - PreviousValue;
2057 PreviousValue = Elt;
2058 Elt = EltDelta;
2060 // Emit the index record.
2061 Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
2062 IndexPos.clear();
2065 // Write the named metadata now.
2066 writeNamedMetadata(Record);
2068 auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
2069 SmallVector<uint64_t, 4> Record;
2070 Record.push_back(VE.getValueID(&GO));
2071 pushGlobalMetadataAttachment(Record, GO);
2072 Stream.EmitRecord(bitc::METADATA_GLOBAL_DECL_ATTACHMENT, Record);
2074 for (const Function &F : M)
2075 if (F.isDeclaration() && F.hasMetadata())
2076 AddDeclAttachedMetadata(F);
2077 // FIXME: Only store metadata for declarations here, and move data for global
2078 // variable definitions to a separate block (PR28134).
2079 for (const GlobalVariable &GV : M.globals())
2080 if (GV.hasMetadata())
2081 AddDeclAttachedMetadata(GV);
2083 Stream.ExitBlock();
2086 void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
2087 if (!VE.hasMDs())
2088 return;
2090 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
2091 SmallVector<uint64_t, 64> Record;
2092 writeMetadataStrings(VE.getMDStrings(), Record);
2093 writeMetadataRecords(VE.getNonMDStrings(), Record);
2094 Stream.ExitBlock();
2097 void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
2098 SmallVectorImpl<uint64_t> &Record, const GlobalObject &GO) {
2099 // [n x [id, mdnode]]
2100 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2101 GO.getAllMetadata(MDs);
2102 for (const auto &I : MDs) {
2103 Record.push_back(I.first);
2104 Record.push_back(VE.getMetadataID(I.second));
2108 void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
2109 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
2111 SmallVector<uint64_t, 64> Record;
2113 if (F.hasMetadata()) {
2114 pushGlobalMetadataAttachment(Record, F);
2115 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
2116 Record.clear();
2119 // Write metadata attachments
2120 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
2121 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2122 for (const BasicBlock &BB : F)
2123 for (const Instruction &I : BB) {
2124 MDs.clear();
2125 I.getAllMetadataOtherThanDebugLoc(MDs);
2127 // If no metadata, ignore instruction.
2128 if (MDs.empty()) continue;
2130 Record.push_back(VE.getInstructionID(&I));
2132 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
2133 Record.push_back(MDs[i].first);
2134 Record.push_back(VE.getMetadataID(MDs[i].second));
2136 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
2137 Record.clear();
2140 Stream.ExitBlock();
2143 void ModuleBitcodeWriter::writeModuleMetadataKinds() {
2144 SmallVector<uint64_t, 64> Record;
2146 // Write metadata kinds
2147 // METADATA_KIND - [n x [id, name]]
2148 SmallVector<StringRef, 8> Names;
2149 M.getMDKindNames(Names);
2151 if (Names.empty()) return;
2153 Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3);
2155 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
2156 Record.push_back(MDKindID);
2157 StringRef KName = Names[MDKindID];
2158 Record.append(KName.begin(), KName.end());
2160 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
2161 Record.clear();
2164 Stream.ExitBlock();
2167 void ModuleBitcodeWriter::writeOperandBundleTags() {
2168 // Write metadata kinds
2170 // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
2172 // OPERAND_BUNDLE_TAG - [strchr x N]
2174 SmallVector<StringRef, 8> Tags;
2175 M.getOperandBundleTags(Tags);
2177 if (Tags.empty())
2178 return;
2180 Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3);
2182 SmallVector<uint64_t, 64> Record;
2184 for (auto Tag : Tags) {
2185 Record.append(Tag.begin(), Tag.end());
2187 Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
2188 Record.clear();
2191 Stream.ExitBlock();
2194 void ModuleBitcodeWriter::writeSyncScopeNames() {
2195 SmallVector<StringRef, 8> SSNs;
2196 M.getContext().getSyncScopeNames(SSNs);
2197 if (SSNs.empty())
2198 return;
2200 Stream.EnterSubblock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID, 2);
2202 SmallVector<uint64_t, 64> Record;
2203 for (auto SSN : SSNs) {
2204 Record.append(SSN.begin(), SSN.end());
2205 Stream.EmitRecord(bitc::SYNC_SCOPE_NAME, Record, 0);
2206 Record.clear();
2209 Stream.ExitBlock();
2212 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
2213 if ((int64_t)V >= 0)
2214 Vals.push_back(V << 1);
2215 else
2216 Vals.push_back((-V << 1) | 1);
2219 void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
2220 bool isGlobal) {
2221 if (FirstVal == LastVal) return;
2223 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
2225 unsigned AggregateAbbrev = 0;
2226 unsigned String8Abbrev = 0;
2227 unsigned CString7Abbrev = 0;
2228 unsigned CString6Abbrev = 0;
2229 // If this is a constant pool for the module, emit module-specific abbrevs.
2230 if (isGlobal) {
2231 // Abbrev for CST_CODE_AGGREGATE.
2232 auto Abbv = std::make_shared<BitCodeAbbrev>();
2233 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
2234 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2235 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
2236 AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2238 // Abbrev for CST_CODE_STRING.
2239 Abbv = std::make_shared<BitCodeAbbrev>();
2240 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
2241 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2242 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2243 String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2244 // Abbrev for CST_CODE_CSTRING.
2245 Abbv = std::make_shared<BitCodeAbbrev>();
2246 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2247 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2248 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2249 CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2250 // Abbrev for CST_CODE_CSTRING.
2251 Abbv = std::make_shared<BitCodeAbbrev>();
2252 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2253 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2254 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2255 CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2258 SmallVector<uint64_t, 64> Record;
2260 const ValueEnumerator::ValueList &Vals = VE.getValues();
2261 Type *LastTy = nullptr;
2262 for (unsigned i = FirstVal; i != LastVal; ++i) {
2263 const Value *V = Vals[i].first;
2264 // If we need to switch types, do so now.
2265 if (V->getType() != LastTy) {
2266 LastTy = V->getType();
2267 Record.push_back(VE.getTypeID(LastTy));
2268 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
2269 CONSTANTS_SETTYPE_ABBREV);
2270 Record.clear();
2273 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
2274 Record.push_back(unsigned(IA->hasSideEffects()) |
2275 unsigned(IA->isAlignStack()) << 1 |
2276 unsigned(IA->getDialect()&1) << 2);
2278 // Add the asm string.
2279 const std::string &AsmStr = IA->getAsmString();
2280 Record.push_back(AsmStr.size());
2281 Record.append(AsmStr.begin(), AsmStr.end());
2283 // Add the constraint string.
2284 const std::string &ConstraintStr = IA->getConstraintString();
2285 Record.push_back(ConstraintStr.size());
2286 Record.append(ConstraintStr.begin(), ConstraintStr.end());
2287 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
2288 Record.clear();
2289 continue;
2291 const Constant *C = cast<Constant>(V);
2292 unsigned Code = -1U;
2293 unsigned AbbrevToUse = 0;
2294 if (C->isNullValue()) {
2295 Code = bitc::CST_CODE_NULL;
2296 } else if (isa<UndefValue>(C)) {
2297 Code = bitc::CST_CODE_UNDEF;
2298 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
2299 if (IV->getBitWidth() <= 64) {
2300 uint64_t V = IV->getSExtValue();
2301 emitSignedInt64(Record, V);
2302 Code = bitc::CST_CODE_INTEGER;
2303 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
2304 } else { // Wide integers, > 64 bits in size.
2305 // We have an arbitrary precision integer value to write whose
2306 // bit width is > 64. However, in canonical unsigned integer
2307 // format it is likely that the high bits are going to be zero.
2308 // So, we only write the number of active words.
2309 unsigned NWords = IV->getValue().getActiveWords();
2310 const uint64_t *RawWords = IV->getValue().getRawData();
2311 for (unsigned i = 0; i != NWords; ++i) {
2312 emitSignedInt64(Record, RawWords[i]);
2314 Code = bitc::CST_CODE_WIDE_INTEGER;
2316 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
2317 Code = bitc::CST_CODE_FLOAT;
2318 Type *Ty = CFP->getType();
2319 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
2320 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
2321 } else if (Ty->isX86_FP80Ty()) {
2322 // api needed to prevent premature destruction
2323 // bits are not in the same order as a normal i80 APInt, compensate.
2324 APInt api = CFP->getValueAPF().bitcastToAPInt();
2325 const uint64_t *p = api.getRawData();
2326 Record.push_back((p[1] << 48) | (p[0] >> 16));
2327 Record.push_back(p[0] & 0xffffLL);
2328 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
2329 APInt api = CFP->getValueAPF().bitcastToAPInt();
2330 const uint64_t *p = api.getRawData();
2331 Record.push_back(p[0]);
2332 Record.push_back(p[1]);
2333 } else {
2334 assert(0 && "Unknown FP type!");
2336 } else if (isa<ConstantDataSequential>(C) &&
2337 cast<ConstantDataSequential>(C)->isString()) {
2338 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
2339 // Emit constant strings specially.
2340 unsigned NumElts = Str->getNumElements();
2341 // If this is a null-terminated string, use the denser CSTRING encoding.
2342 if (Str->isCString()) {
2343 Code = bitc::CST_CODE_CSTRING;
2344 --NumElts; // Don't encode the null, which isn't allowed by char6.
2345 } else {
2346 Code = bitc::CST_CODE_STRING;
2347 AbbrevToUse = String8Abbrev;
2349 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
2350 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
2351 for (unsigned i = 0; i != NumElts; ++i) {
2352 unsigned char V = Str->getElementAsInteger(i);
2353 Record.push_back(V);
2354 isCStr7 &= (V & 128) == 0;
2355 if (isCStrChar6)
2356 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
2359 if (isCStrChar6)
2360 AbbrevToUse = CString6Abbrev;
2361 else if (isCStr7)
2362 AbbrevToUse = CString7Abbrev;
2363 } else if (const ConstantDataSequential *CDS =
2364 dyn_cast<ConstantDataSequential>(C)) {
2365 Code = bitc::CST_CODE_DATA;
2366 Type *EltTy = CDS->getType()->getElementType();
2367 if (isa<IntegerType>(EltTy)) {
2368 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2369 Record.push_back(CDS->getElementAsInteger(i));
2370 } else {
2371 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2372 Record.push_back(
2373 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
2375 } else if (isa<ConstantAggregate>(C)) {
2376 Code = bitc::CST_CODE_AGGREGATE;
2377 for (const Value *Op : C->operands())
2378 Record.push_back(VE.getValueID(Op));
2379 AbbrevToUse = AggregateAbbrev;
2380 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2381 switch (CE->getOpcode()) {
2382 default:
2383 if (Instruction::isCast(CE->getOpcode())) {
2384 Code = bitc::CST_CODE_CE_CAST;
2385 Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
2386 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2387 Record.push_back(VE.getValueID(C->getOperand(0)));
2388 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
2389 } else {
2390 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
2391 Code = bitc::CST_CODE_CE_BINOP;
2392 Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
2393 Record.push_back(VE.getValueID(C->getOperand(0)));
2394 Record.push_back(VE.getValueID(C->getOperand(1)));
2395 uint64_t Flags = getOptimizationFlags(CE);
2396 if (Flags != 0)
2397 Record.push_back(Flags);
2399 break;
2400 case Instruction::FNeg: {
2401 assert(CE->getNumOperands() == 1 && "Unknown constant expr!");
2402 Code = bitc::CST_CODE_CE_UNOP;
2403 Record.push_back(getEncodedUnaryOpcode(CE->getOpcode()));
2404 Record.push_back(VE.getValueID(C->getOperand(0)));
2405 uint64_t Flags = getOptimizationFlags(CE);
2406 if (Flags != 0)
2407 Record.push_back(Flags);
2408 break;
2410 case Instruction::GetElementPtr: {
2411 Code = bitc::CST_CODE_CE_GEP;
2412 const auto *GO = cast<GEPOperator>(C);
2413 Record.push_back(VE.getTypeID(GO->getSourceElementType()));
2414 if (Optional<unsigned> Idx = GO->getInRangeIndex()) {
2415 Code = bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX;
2416 Record.push_back((*Idx << 1) | GO->isInBounds());
2417 } else if (GO->isInBounds())
2418 Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
2419 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
2420 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
2421 Record.push_back(VE.getValueID(C->getOperand(i)));
2423 break;
2425 case Instruction::Select:
2426 Code = bitc::CST_CODE_CE_SELECT;
2427 Record.push_back(VE.getValueID(C->getOperand(0)));
2428 Record.push_back(VE.getValueID(C->getOperand(1)));
2429 Record.push_back(VE.getValueID(C->getOperand(2)));
2430 break;
2431 case Instruction::ExtractElement:
2432 Code = bitc::CST_CODE_CE_EXTRACTELT;
2433 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2434 Record.push_back(VE.getValueID(C->getOperand(0)));
2435 Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
2436 Record.push_back(VE.getValueID(C->getOperand(1)));
2437 break;
2438 case Instruction::InsertElement:
2439 Code = bitc::CST_CODE_CE_INSERTELT;
2440 Record.push_back(VE.getValueID(C->getOperand(0)));
2441 Record.push_back(VE.getValueID(C->getOperand(1)));
2442 Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
2443 Record.push_back(VE.getValueID(C->getOperand(2)));
2444 break;
2445 case Instruction::ShuffleVector:
2446 // If the return type and argument types are the same, this is a
2447 // standard shufflevector instruction. If the types are different,
2448 // then the shuffle is widening or truncating the input vectors, and
2449 // the argument type must also be encoded.
2450 if (C->getType() == C->getOperand(0)->getType()) {
2451 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
2452 } else {
2453 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
2454 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2456 Record.push_back(VE.getValueID(C->getOperand(0)));
2457 Record.push_back(VE.getValueID(C->getOperand(1)));
2458 Record.push_back(VE.getValueID(C->getOperand(2)));
2459 break;
2460 case Instruction::ICmp:
2461 case Instruction::FCmp:
2462 Code = bitc::CST_CODE_CE_CMP;
2463 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2464 Record.push_back(VE.getValueID(C->getOperand(0)));
2465 Record.push_back(VE.getValueID(C->getOperand(1)));
2466 Record.push_back(CE->getPredicate());
2467 break;
2469 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
2470 Code = bitc::CST_CODE_BLOCKADDRESS;
2471 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
2472 Record.push_back(VE.getValueID(BA->getFunction()));
2473 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
2474 } else {
2475 #ifndef NDEBUG
2476 C->dump();
2477 #endif
2478 llvm_unreachable("Unknown constant!");
2480 Stream.EmitRecord(Code, Record, AbbrevToUse);
2481 Record.clear();
2484 Stream.ExitBlock();
2487 void ModuleBitcodeWriter::writeModuleConstants() {
2488 const ValueEnumerator::ValueList &Vals = VE.getValues();
2490 // Find the first constant to emit, which is the first non-globalvalue value.
2491 // We know globalvalues have been emitted by WriteModuleInfo.
2492 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
2493 if (!isa<GlobalValue>(Vals[i].first)) {
2494 writeConstants(i, Vals.size(), true);
2495 return;
2500 /// pushValueAndType - The file has to encode both the value and type id for
2501 /// many values, because we need to know what type to create for forward
2502 /// references. However, most operands are not forward references, so this type
2503 /// field is not needed.
2505 /// This function adds V's value ID to Vals. If the value ID is higher than the
2506 /// instruction ID, then it is a forward reference, and it also includes the
2507 /// type ID. The value ID that is written is encoded relative to the InstID.
2508 bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
2509 SmallVectorImpl<unsigned> &Vals) {
2510 unsigned ValID = VE.getValueID(V);
2511 // Make encoding relative to the InstID.
2512 Vals.push_back(InstID - ValID);
2513 if (ValID >= InstID) {
2514 Vals.push_back(VE.getTypeID(V->getType()));
2515 return true;
2517 return false;
2520 void ModuleBitcodeWriter::writeOperandBundles(ImmutableCallSite CS,
2521 unsigned InstID) {
2522 SmallVector<unsigned, 64> Record;
2523 LLVMContext &C = CS.getInstruction()->getContext();
2525 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
2526 const auto &Bundle = CS.getOperandBundleAt(i);
2527 Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
2529 for (auto &Input : Bundle.Inputs)
2530 pushValueAndType(Input, InstID, Record);
2532 Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record);
2533 Record.clear();
2537 /// pushValue - Like pushValueAndType, but where the type of the value is
2538 /// omitted (perhaps it was already encoded in an earlier operand).
2539 void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
2540 SmallVectorImpl<unsigned> &Vals) {
2541 unsigned ValID = VE.getValueID(V);
2542 Vals.push_back(InstID - ValID);
2545 void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
2546 SmallVectorImpl<uint64_t> &Vals) {
2547 unsigned ValID = VE.getValueID(V);
2548 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
2549 emitSignedInt64(Vals, diff);
2552 /// WriteInstruction - Emit an instruction to the specified stream.
2553 void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
2554 unsigned InstID,
2555 SmallVectorImpl<unsigned> &Vals) {
2556 unsigned Code = 0;
2557 unsigned AbbrevToUse = 0;
2558 VE.setInstructionID(&I);
2559 switch (I.getOpcode()) {
2560 default:
2561 if (Instruction::isCast(I.getOpcode())) {
2562 Code = bitc::FUNC_CODE_INST_CAST;
2563 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2564 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
2565 Vals.push_back(VE.getTypeID(I.getType()));
2566 Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
2567 } else {
2568 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
2569 Code = bitc::FUNC_CODE_INST_BINOP;
2570 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2571 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
2572 pushValue(I.getOperand(1), InstID, Vals);
2573 Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
2574 uint64_t Flags = getOptimizationFlags(&I);
2575 if (Flags != 0) {
2576 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
2577 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
2578 Vals.push_back(Flags);
2581 break;
2582 case Instruction::FNeg: {
2583 Code = bitc::FUNC_CODE_INST_UNOP;
2584 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2585 AbbrevToUse = FUNCTION_INST_UNOP_ABBREV;
2586 Vals.push_back(getEncodedUnaryOpcode(I.getOpcode()));
2587 uint64_t Flags = getOptimizationFlags(&I);
2588 if (Flags != 0) {
2589 if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV)
2590 AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV;
2591 Vals.push_back(Flags);
2593 break;
2595 case Instruction::GetElementPtr: {
2596 Code = bitc::FUNC_CODE_INST_GEP;
2597 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
2598 auto &GEPInst = cast<GetElementPtrInst>(I);
2599 Vals.push_back(GEPInst.isInBounds());
2600 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
2601 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
2602 pushValueAndType(I.getOperand(i), InstID, Vals);
2603 break;
2605 case Instruction::ExtractValue: {
2606 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
2607 pushValueAndType(I.getOperand(0), InstID, Vals);
2608 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
2609 Vals.append(EVI->idx_begin(), EVI->idx_end());
2610 break;
2612 case Instruction::InsertValue: {
2613 Code = bitc::FUNC_CODE_INST_INSERTVAL;
2614 pushValueAndType(I.getOperand(0), InstID, Vals);
2615 pushValueAndType(I.getOperand(1), InstID, Vals);
2616 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
2617 Vals.append(IVI->idx_begin(), IVI->idx_end());
2618 break;
2620 case Instruction::Select:
2621 Code = bitc::FUNC_CODE_INST_VSELECT;
2622 pushValueAndType(I.getOperand(1), InstID, Vals);
2623 pushValue(I.getOperand(2), InstID, Vals);
2624 pushValueAndType(I.getOperand(0), InstID, Vals);
2625 break;
2626 case Instruction::ExtractElement:
2627 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
2628 pushValueAndType(I.getOperand(0), InstID, Vals);
2629 pushValueAndType(I.getOperand(1), InstID, Vals);
2630 break;
2631 case Instruction::InsertElement:
2632 Code = bitc::FUNC_CODE_INST_INSERTELT;
2633 pushValueAndType(I.getOperand(0), InstID, Vals);
2634 pushValue(I.getOperand(1), InstID, Vals);
2635 pushValueAndType(I.getOperand(2), InstID, Vals);
2636 break;
2637 case Instruction::ShuffleVector:
2638 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
2639 pushValueAndType(I.getOperand(0), InstID, Vals);
2640 pushValue(I.getOperand(1), InstID, Vals);
2641 pushValue(I.getOperand(2), InstID, Vals);
2642 break;
2643 case Instruction::ICmp:
2644 case Instruction::FCmp: {
2645 // compare returning Int1Ty or vector of Int1Ty
2646 Code = bitc::FUNC_CODE_INST_CMP2;
2647 pushValueAndType(I.getOperand(0), InstID, Vals);
2648 pushValue(I.getOperand(1), InstID, Vals);
2649 Vals.push_back(cast<CmpInst>(I).getPredicate());
2650 uint64_t Flags = getOptimizationFlags(&I);
2651 if (Flags != 0)
2652 Vals.push_back(Flags);
2653 break;
2656 case Instruction::Ret:
2658 Code = bitc::FUNC_CODE_INST_RET;
2659 unsigned NumOperands = I.getNumOperands();
2660 if (NumOperands == 0)
2661 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
2662 else if (NumOperands == 1) {
2663 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2664 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
2665 } else {
2666 for (unsigned i = 0, e = NumOperands; i != e; ++i)
2667 pushValueAndType(I.getOperand(i), InstID, Vals);
2670 break;
2671 case Instruction::Br:
2673 Code = bitc::FUNC_CODE_INST_BR;
2674 const BranchInst &II = cast<BranchInst>(I);
2675 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
2676 if (II.isConditional()) {
2677 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
2678 pushValue(II.getCondition(), InstID, Vals);
2681 break;
2682 case Instruction::Switch:
2684 Code = bitc::FUNC_CODE_INST_SWITCH;
2685 const SwitchInst &SI = cast<SwitchInst>(I);
2686 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
2687 pushValue(SI.getCondition(), InstID, Vals);
2688 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
2689 for (auto Case : SI.cases()) {
2690 Vals.push_back(VE.getValueID(Case.getCaseValue()));
2691 Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
2694 break;
2695 case Instruction::IndirectBr:
2696 Code = bitc::FUNC_CODE_INST_INDIRECTBR;
2697 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
2698 // Encode the address operand as relative, but not the basic blocks.
2699 pushValue(I.getOperand(0), InstID, Vals);
2700 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
2701 Vals.push_back(VE.getValueID(I.getOperand(i)));
2702 break;
2704 case Instruction::Invoke: {
2705 const InvokeInst *II = cast<InvokeInst>(&I);
2706 const Value *Callee = II->getCalledValue();
2707 FunctionType *FTy = II->getFunctionType();
2709 if (II->hasOperandBundles())
2710 writeOperandBundles(II, InstID);
2712 Code = bitc::FUNC_CODE_INST_INVOKE;
2714 Vals.push_back(VE.getAttributeListID(II->getAttributes()));
2715 Vals.push_back(II->getCallingConv() | 1 << 13);
2716 Vals.push_back(VE.getValueID(II->getNormalDest()));
2717 Vals.push_back(VE.getValueID(II->getUnwindDest()));
2718 Vals.push_back(VE.getTypeID(FTy));
2719 pushValueAndType(Callee, InstID, Vals);
2721 // Emit value #'s for the fixed parameters.
2722 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2723 pushValue(I.getOperand(i), InstID, Vals); // fixed param.
2725 // Emit type/value pairs for varargs params.
2726 if (FTy->isVarArg()) {
2727 for (unsigned i = FTy->getNumParams(), e = II->getNumArgOperands();
2728 i != e; ++i)
2729 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
2731 break;
2733 case Instruction::Resume:
2734 Code = bitc::FUNC_CODE_INST_RESUME;
2735 pushValueAndType(I.getOperand(0), InstID, Vals);
2736 break;
2737 case Instruction::CleanupRet: {
2738 Code = bitc::FUNC_CODE_INST_CLEANUPRET;
2739 const auto &CRI = cast<CleanupReturnInst>(I);
2740 pushValue(CRI.getCleanupPad(), InstID, Vals);
2741 if (CRI.hasUnwindDest())
2742 Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
2743 break;
2745 case Instruction::CatchRet: {
2746 Code = bitc::FUNC_CODE_INST_CATCHRET;
2747 const auto &CRI = cast<CatchReturnInst>(I);
2748 pushValue(CRI.getCatchPad(), InstID, Vals);
2749 Vals.push_back(VE.getValueID(CRI.getSuccessor()));
2750 break;
2752 case Instruction::CleanupPad:
2753 case Instruction::CatchPad: {
2754 const auto &FuncletPad = cast<FuncletPadInst>(I);
2755 Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
2756 : bitc::FUNC_CODE_INST_CLEANUPPAD;
2757 pushValue(FuncletPad.getParentPad(), InstID, Vals);
2759 unsigned NumArgOperands = FuncletPad.getNumArgOperands();
2760 Vals.push_back(NumArgOperands);
2761 for (unsigned Op = 0; Op != NumArgOperands; ++Op)
2762 pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
2763 break;
2765 case Instruction::CatchSwitch: {
2766 Code = bitc::FUNC_CODE_INST_CATCHSWITCH;
2767 const auto &CatchSwitch = cast<CatchSwitchInst>(I);
2769 pushValue(CatchSwitch.getParentPad(), InstID, Vals);
2771 unsigned NumHandlers = CatchSwitch.getNumHandlers();
2772 Vals.push_back(NumHandlers);
2773 for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
2774 Vals.push_back(VE.getValueID(CatchPadBB));
2776 if (CatchSwitch.hasUnwindDest())
2777 Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
2778 break;
2780 case Instruction::Unreachable:
2781 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
2782 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
2783 break;
2785 case Instruction::PHI: {
2786 const PHINode &PN = cast<PHINode>(I);
2787 Code = bitc::FUNC_CODE_INST_PHI;
2788 // With the newer instruction encoding, forward references could give
2789 // negative valued IDs. This is most common for PHIs, so we use
2790 // signed VBRs.
2791 SmallVector<uint64_t, 128> Vals64;
2792 Vals64.push_back(VE.getTypeID(PN.getType()));
2793 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
2794 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
2795 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
2797 // Emit a Vals64 vector and exit.
2798 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
2799 Vals64.clear();
2800 return;
2803 case Instruction::LandingPad: {
2804 const LandingPadInst &LP = cast<LandingPadInst>(I);
2805 Code = bitc::FUNC_CODE_INST_LANDINGPAD;
2806 Vals.push_back(VE.getTypeID(LP.getType()));
2807 Vals.push_back(LP.isCleanup());
2808 Vals.push_back(LP.getNumClauses());
2809 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
2810 if (LP.isCatch(I))
2811 Vals.push_back(LandingPadInst::Catch);
2812 else
2813 Vals.push_back(LandingPadInst::Filter);
2814 pushValueAndType(LP.getClause(I), InstID, Vals);
2816 break;
2819 case Instruction::Alloca: {
2820 Code = bitc::FUNC_CODE_INST_ALLOCA;
2821 const AllocaInst &AI = cast<AllocaInst>(I);
2822 Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
2823 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
2824 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
2825 unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
2826 assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
2827 "not enough bits for maximum alignment");
2828 assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
2829 AlignRecord |= AI.isUsedWithInAlloca() << 5;
2830 AlignRecord |= 1 << 6;
2831 AlignRecord |= AI.isSwiftError() << 7;
2832 Vals.push_back(AlignRecord);
2833 break;
2836 case Instruction::Load:
2837 if (cast<LoadInst>(I).isAtomic()) {
2838 Code = bitc::FUNC_CODE_INST_LOADATOMIC;
2839 pushValueAndType(I.getOperand(0), InstID, Vals);
2840 } else {
2841 Code = bitc::FUNC_CODE_INST_LOAD;
2842 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
2843 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
2845 Vals.push_back(VE.getTypeID(I.getType()));
2846 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
2847 Vals.push_back(cast<LoadInst>(I).isVolatile());
2848 if (cast<LoadInst>(I).isAtomic()) {
2849 Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
2850 Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID()));
2852 break;
2853 case Instruction::Store:
2854 if (cast<StoreInst>(I).isAtomic())
2855 Code = bitc::FUNC_CODE_INST_STOREATOMIC;
2856 else
2857 Code = bitc::FUNC_CODE_INST_STORE;
2858 pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr
2859 pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val
2860 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
2861 Vals.push_back(cast<StoreInst>(I).isVolatile());
2862 if (cast<StoreInst>(I).isAtomic()) {
2863 Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
2864 Vals.push_back(
2865 getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID()));
2867 break;
2868 case Instruction::AtomicCmpXchg:
2869 Code = bitc::FUNC_CODE_INST_CMPXCHG;
2870 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2871 pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
2872 pushValue(I.getOperand(2), InstID, Vals); // newval.
2873 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
2874 Vals.push_back(
2875 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
2876 Vals.push_back(
2877 getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID()));
2878 Vals.push_back(
2879 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
2880 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
2881 break;
2882 case Instruction::AtomicRMW:
2883 Code = bitc::FUNC_CODE_INST_ATOMICRMW;
2884 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2885 pushValue(I.getOperand(1), InstID, Vals); // val.
2886 Vals.push_back(
2887 getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
2888 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
2889 Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
2890 Vals.push_back(
2891 getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID()));
2892 break;
2893 case Instruction::Fence:
2894 Code = bitc::FUNC_CODE_INST_FENCE;
2895 Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
2896 Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID()));
2897 break;
2898 case Instruction::Call: {
2899 const CallInst &CI = cast<CallInst>(I);
2900 FunctionType *FTy = CI.getFunctionType();
2902 if (CI.hasOperandBundles())
2903 writeOperandBundles(&CI, InstID);
2905 Code = bitc::FUNC_CODE_INST_CALL;
2907 Vals.push_back(VE.getAttributeListID(CI.getAttributes()));
2909 unsigned Flags = getOptimizationFlags(&I);
2910 Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |
2911 unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
2912 unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
2913 1 << bitc::CALL_EXPLICIT_TYPE |
2914 unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
2915 unsigned(Flags != 0) << bitc::CALL_FMF);
2916 if (Flags != 0)
2917 Vals.push_back(Flags);
2919 Vals.push_back(VE.getTypeID(FTy));
2920 pushValueAndType(CI.getCalledValue(), InstID, Vals); // Callee
2922 // Emit value #'s for the fixed parameters.
2923 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
2924 // Check for labels (can happen with asm labels).
2925 if (FTy->getParamType(i)->isLabelTy())
2926 Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
2927 else
2928 pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
2931 // Emit type/value pairs for varargs params.
2932 if (FTy->isVarArg()) {
2933 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
2934 i != e; ++i)
2935 pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
2937 break;
2939 case Instruction::VAArg:
2940 Code = bitc::FUNC_CODE_INST_VAARG;
2941 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
2942 pushValue(I.getOperand(0), InstID, Vals); // valist.
2943 Vals.push_back(VE.getTypeID(I.getType())); // restype.
2944 break;
2947 Stream.EmitRecord(Code, Vals, AbbrevToUse);
2948 Vals.clear();
2951 /// Write a GlobalValue VST to the module. The purpose of this data structure is
2952 /// to allow clients to efficiently find the function body.
2953 void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
2954 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
2955 // Get the offset of the VST we are writing, and backpatch it into
2956 // the VST forward declaration record.
2957 uint64_t VSTOffset = Stream.GetCurrentBitNo();
2958 // The BitcodeStartBit was the stream offset of the identification block.
2959 VSTOffset -= bitcodeStartBit();
2960 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
2961 // Note that we add 1 here because the offset is relative to one word
2962 // before the start of the identification block, which was historically
2963 // always the start of the regular bitcode header.
2964 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
2966 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
2968 auto Abbv = std::make_shared<BitCodeAbbrev>();
2969 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2970 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2971 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2972 unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2974 for (const Function &F : M) {
2975 uint64_t Record[2];
2977 if (F.isDeclaration())
2978 continue;
2980 Record[0] = VE.getValueID(&F);
2982 // Save the word offset of the function (from the start of the
2983 // actual bitcode written to the stream).
2984 uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit();
2985 assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
2986 // Note that we add 1 here because the offset is relative to one word
2987 // before the start of the identification block, which was historically
2988 // always the start of the regular bitcode header.
2989 Record[1] = BitcodeIndex / 32 + 1;
2991 Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev);
2994 Stream.ExitBlock();
2997 /// Emit names for arguments, instructions and basic blocks in a function.
2998 void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
2999 const ValueSymbolTable &VST) {
3000 if (VST.empty())
3001 return;
3003 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
3005 // FIXME: Set up the abbrev, we know how many values there are!
3006 // FIXME: We know if the type names can use 7-bit ascii.
3007 SmallVector<uint64_t, 64> NameVals;
3009 for (const ValueName &Name : VST) {
3010 // Figure out the encoding to use for the name.
3011 StringEncoding Bits = getStringEncoding(Name.getKey());
3013 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
3014 NameVals.push_back(VE.getValueID(Name.getValue()));
3016 // VST_CODE_ENTRY: [valueid, namechar x N]
3017 // VST_CODE_BBENTRY: [bbid, namechar x N]
3018 unsigned Code;
3019 if (isa<BasicBlock>(Name.getValue())) {
3020 Code = bitc::VST_CODE_BBENTRY;
3021 if (Bits == SE_Char6)
3022 AbbrevToUse = VST_BBENTRY_6_ABBREV;
3023 } else {
3024 Code = bitc::VST_CODE_ENTRY;
3025 if (Bits == SE_Char6)
3026 AbbrevToUse = VST_ENTRY_6_ABBREV;
3027 else if (Bits == SE_Fixed7)
3028 AbbrevToUse = VST_ENTRY_7_ABBREV;
3031 for (const auto P : Name.getKey())
3032 NameVals.push_back((unsigned char)P);
3034 // Emit the finished record.
3035 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
3036 NameVals.clear();
3039 Stream.ExitBlock();
3042 void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
3043 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
3044 unsigned Code;
3045 if (isa<BasicBlock>(Order.V))
3046 Code = bitc::USELIST_CODE_BB;
3047 else
3048 Code = bitc::USELIST_CODE_DEFAULT;
3050 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
3051 Record.push_back(VE.getValueID(Order.V));
3052 Stream.EmitRecord(Code, Record);
3055 void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
3056 assert(VE.shouldPreserveUseListOrder() &&
3057 "Expected to be preserving use-list order");
3059 auto hasMore = [&]() {
3060 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
3062 if (!hasMore())
3063 // Nothing to do.
3064 return;
3066 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
3067 while (hasMore()) {
3068 writeUseList(std::move(VE.UseListOrders.back()));
3069 VE.UseListOrders.pop_back();
3071 Stream.ExitBlock();
3074 /// Emit a function body to the module stream.
3075 void ModuleBitcodeWriter::writeFunction(
3076 const Function &F,
3077 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3078 // Save the bitcode index of the start of this function block for recording
3079 // in the VST.
3080 FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
3082 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
3083 VE.incorporateFunction(F);
3085 SmallVector<unsigned, 64> Vals;
3087 // Emit the number of basic blocks, so the reader can create them ahead of
3088 // time.
3089 Vals.push_back(VE.getBasicBlocks().size());
3090 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
3091 Vals.clear();
3093 // If there are function-local constants, emit them now.
3094 unsigned CstStart, CstEnd;
3095 VE.getFunctionConstantRange(CstStart, CstEnd);
3096 writeConstants(CstStart, CstEnd, false);
3098 // If there is function-local metadata, emit it now.
3099 writeFunctionMetadata(F);
3101 // Keep a running idea of what the instruction ID is.
3102 unsigned InstID = CstEnd;
3104 bool NeedsMetadataAttachment = F.hasMetadata();
3106 DILocation *LastDL = nullptr;
3107 // Finally, emit all the instructions, in order.
3108 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
3109 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
3110 I != E; ++I) {
3111 writeInstruction(*I, InstID, Vals);
3113 if (!I->getType()->isVoidTy())
3114 ++InstID;
3116 // If the instruction has metadata, write a metadata attachment later.
3117 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
3119 // If the instruction has a debug location, emit it.
3120 DILocation *DL = I->getDebugLoc();
3121 if (!DL)
3122 continue;
3124 if (DL == LastDL) {
3125 // Just repeat the same debug loc as last time.
3126 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
3127 continue;
3130 Vals.push_back(DL->getLine());
3131 Vals.push_back(DL->getColumn());
3132 Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
3133 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
3134 Vals.push_back(DL->isImplicitCode());
3135 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
3136 Vals.clear();
3138 LastDL = DL;
3141 // Emit names for all the instructions etc.
3142 if (auto *Symtab = F.getValueSymbolTable())
3143 writeFunctionLevelValueSymbolTable(*Symtab);
3145 if (NeedsMetadataAttachment)
3146 writeFunctionMetadataAttachment(F);
3147 if (VE.shouldPreserveUseListOrder())
3148 writeUseListBlock(&F);
3149 VE.purgeFunction();
3150 Stream.ExitBlock();
3153 // Emit blockinfo, which defines the standard abbreviations etc.
3154 void ModuleBitcodeWriter::writeBlockInfo() {
3155 // We only want to emit block info records for blocks that have multiple
3156 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
3157 // Other blocks can define their abbrevs inline.
3158 Stream.EnterBlockInfoBlock();
3160 { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
3161 auto Abbv = std::make_shared<BitCodeAbbrev>();
3162 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
3163 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3164 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3165 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
3166 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3167 VST_ENTRY_8_ABBREV)
3168 llvm_unreachable("Unexpected abbrev ordering!");
3171 { // 7-bit fixed width VST_CODE_ENTRY strings.
3172 auto Abbv = std::make_shared<BitCodeAbbrev>();
3173 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
3174 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3175 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3176 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
3177 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3178 VST_ENTRY_7_ABBREV)
3179 llvm_unreachable("Unexpected abbrev ordering!");
3181 { // 6-bit char6 VST_CODE_ENTRY strings.
3182 auto Abbv = std::make_shared<BitCodeAbbrev>();
3183 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
3184 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3185 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3186 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3187 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3188 VST_ENTRY_6_ABBREV)
3189 llvm_unreachable("Unexpected abbrev ordering!");
3191 { // 6-bit char6 VST_CODE_BBENTRY strings.
3192 auto Abbv = std::make_shared<BitCodeAbbrev>();
3193 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
3194 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3195 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3196 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3197 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3198 VST_BBENTRY_6_ABBREV)
3199 llvm_unreachable("Unexpected abbrev ordering!");
3202 { // SETTYPE abbrev for CONSTANTS_BLOCK.
3203 auto Abbv = std::make_shared<BitCodeAbbrev>();
3204 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
3205 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
3206 VE.computeBitsRequiredForTypeIndicies()));
3207 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3208 CONSTANTS_SETTYPE_ABBREV)
3209 llvm_unreachable("Unexpected abbrev ordering!");
3212 { // INTEGER abbrev for CONSTANTS_BLOCK.
3213 auto Abbv = std::make_shared<BitCodeAbbrev>();
3214 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
3215 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3216 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3217 CONSTANTS_INTEGER_ABBREV)
3218 llvm_unreachable("Unexpected abbrev ordering!");
3221 { // CE_CAST abbrev for CONSTANTS_BLOCK.
3222 auto Abbv = std::make_shared<BitCodeAbbrev>();
3223 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
3224 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
3225 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
3226 VE.computeBitsRequiredForTypeIndicies()));
3227 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3229 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3230 CONSTANTS_CE_CAST_Abbrev)
3231 llvm_unreachable("Unexpected abbrev ordering!");
3233 { // NULL abbrev for CONSTANTS_BLOCK.
3234 auto Abbv = std::make_shared<BitCodeAbbrev>();
3235 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
3236 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3237 CONSTANTS_NULL_Abbrev)
3238 llvm_unreachable("Unexpected abbrev ordering!");
3241 // FIXME: This should only use space for first class types!
3243 { // INST_LOAD abbrev for FUNCTION_BLOCK.
3244 auto Abbv = std::make_shared<BitCodeAbbrev>();
3245 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
3246 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
3247 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3248 VE.computeBitsRequiredForTypeIndicies()));
3249 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
3250 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
3251 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3252 FUNCTION_INST_LOAD_ABBREV)
3253 llvm_unreachable("Unexpected abbrev ordering!");
3255 { // INST_UNOP abbrev for FUNCTION_BLOCK.
3256 auto Abbv = std::make_shared<BitCodeAbbrev>();
3257 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP));
3258 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3259 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3260 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3261 FUNCTION_INST_UNOP_ABBREV)
3262 llvm_unreachable("Unexpected abbrev ordering!");
3264 { // INST_UNOP_FLAGS abbrev for FUNCTION_BLOCK.
3265 auto Abbv = std::make_shared<BitCodeAbbrev>();
3266 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP));
3267 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3268 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3269 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
3270 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3271 FUNCTION_INST_UNOP_FLAGS_ABBREV)
3272 llvm_unreachable("Unexpected abbrev ordering!");
3274 { // INST_BINOP abbrev for FUNCTION_BLOCK.
3275 auto Abbv = std::make_shared<BitCodeAbbrev>();
3276 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3277 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3278 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3279 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3280 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3281 FUNCTION_INST_BINOP_ABBREV)
3282 llvm_unreachable("Unexpected abbrev ordering!");
3284 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
3285 auto Abbv = std::make_shared<BitCodeAbbrev>();
3286 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3287 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3288 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3289 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3290 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
3291 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3292 FUNCTION_INST_BINOP_FLAGS_ABBREV)
3293 llvm_unreachable("Unexpected abbrev ordering!");
3295 { // INST_CAST abbrev for FUNCTION_BLOCK.
3296 auto Abbv = std::make_shared<BitCodeAbbrev>();
3297 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
3298 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
3299 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3300 VE.computeBitsRequiredForTypeIndicies()));
3301 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3302 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3303 FUNCTION_INST_CAST_ABBREV)
3304 llvm_unreachable("Unexpected abbrev ordering!");
3307 { // INST_RET abbrev for FUNCTION_BLOCK.
3308 auto Abbv = std::make_shared<BitCodeAbbrev>();
3309 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
3310 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3311 FUNCTION_INST_RET_VOID_ABBREV)
3312 llvm_unreachable("Unexpected abbrev ordering!");
3314 { // INST_RET abbrev for FUNCTION_BLOCK.
3315 auto Abbv = std::make_shared<BitCodeAbbrev>();
3316 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
3317 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
3318 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3319 FUNCTION_INST_RET_VAL_ABBREV)
3320 llvm_unreachable("Unexpected abbrev ordering!");
3322 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
3323 auto Abbv = std::make_shared<BitCodeAbbrev>();
3324 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
3325 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3326 FUNCTION_INST_UNREACHABLE_ABBREV)
3327 llvm_unreachable("Unexpected abbrev ordering!");
3330 auto Abbv = std::make_shared<BitCodeAbbrev>();
3331 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
3332 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
3333 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3334 Log2_32_Ceil(VE.getTypes().size() + 1)));
3335 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3336 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
3337 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3338 FUNCTION_INST_GEP_ABBREV)
3339 llvm_unreachable("Unexpected abbrev ordering!");
3342 Stream.ExitBlock();
3345 /// Write the module path strings, currently only used when generating
3346 /// a combined index file.
3347 void IndexBitcodeWriter::writeModStrings() {
3348 Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);
3350 // TODO: See which abbrev sizes we actually need to emit
3352 // 8-bit fixed-width MST_ENTRY strings.
3353 auto Abbv = std::make_shared<BitCodeAbbrev>();
3354 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3355 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3356 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3357 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
3358 unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
3360 // 7-bit fixed width MST_ENTRY strings.
3361 Abbv = std::make_shared<BitCodeAbbrev>();
3362 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3363 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3364 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3365 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
3366 unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
3368 // 6-bit char6 MST_ENTRY strings.
3369 Abbv = std::make_shared<BitCodeAbbrev>();
3370 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3371 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3372 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3373 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3374 unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
3376 // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
3377 Abbv = std::make_shared<BitCodeAbbrev>();
3378 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH));
3379 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3380 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3381 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3382 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3383 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3384 unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
3386 SmallVector<unsigned, 64> Vals;
3387 forEachModule(
3388 [&](const StringMapEntry<std::pair<uint64_t, ModuleHash>> &MPSE) {
3389 StringRef Key = MPSE.getKey();
3390 const auto &Value = MPSE.getValue();
3391 StringEncoding Bits = getStringEncoding(Key);
3392 unsigned AbbrevToUse = Abbrev8Bit;
3393 if (Bits == SE_Char6)
3394 AbbrevToUse = Abbrev6Bit;
3395 else if (Bits == SE_Fixed7)
3396 AbbrevToUse = Abbrev7Bit;
3398 Vals.push_back(Value.first);
3399 Vals.append(Key.begin(), Key.end());
3401 // Emit the finished record.
3402 Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
3404 // Emit an optional hash for the module now
3405 const auto &Hash = Value.second;
3406 if (llvm::any_of(Hash, [](uint32_t H) { return H; })) {
3407 Vals.assign(Hash.begin(), Hash.end());
3408 // Emit the hash record.
3409 Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
3412 Vals.clear();
3414 Stream.ExitBlock();
3417 /// Write the function type metadata related records that need to appear before
3418 /// a function summary entry (whether per-module or combined).
3419 static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream,
3420 FunctionSummary *FS) {
3421 if (!FS->type_tests().empty())
3422 Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
3424 SmallVector<uint64_t, 64> Record;
3426 auto WriteVFuncIdVec = [&](uint64_t Ty,
3427 ArrayRef<FunctionSummary::VFuncId> VFs) {
3428 if (VFs.empty())
3429 return;
3430 Record.clear();
3431 for (auto &VF : VFs) {
3432 Record.push_back(VF.GUID);
3433 Record.push_back(VF.Offset);
3435 Stream.EmitRecord(Ty, Record);
3438 WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
3439 FS->type_test_assume_vcalls());
3440 WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
3441 FS->type_checked_load_vcalls());
3443 auto WriteConstVCallVec = [&](uint64_t Ty,
3444 ArrayRef<FunctionSummary::ConstVCall> VCs) {
3445 for (auto &VC : VCs) {
3446 Record.clear();
3447 Record.push_back(VC.VFunc.GUID);
3448 Record.push_back(VC.VFunc.Offset);
3449 Record.insert(Record.end(), VC.Args.begin(), VC.Args.end());
3450 Stream.EmitRecord(Ty, Record);
3454 WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
3455 FS->type_test_assume_const_vcalls());
3456 WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
3457 FS->type_checked_load_const_vcalls());
3460 /// Collect type IDs from type tests used by function.
3461 static void
3462 getReferencedTypeIds(FunctionSummary *FS,
3463 std::set<GlobalValue::GUID> &ReferencedTypeIds) {
3464 if (!FS->type_tests().empty())
3465 for (auto &TT : FS->type_tests())
3466 ReferencedTypeIds.insert(TT);
3468 auto GetReferencedTypesFromVFuncIdVec =
3469 [&](ArrayRef<FunctionSummary::VFuncId> VFs) {
3470 for (auto &VF : VFs)
3471 ReferencedTypeIds.insert(VF.GUID);
3474 GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls());
3475 GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls());
3477 auto GetReferencedTypesFromConstVCallVec =
3478 [&](ArrayRef<FunctionSummary::ConstVCall> VCs) {
3479 for (auto &VC : VCs)
3480 ReferencedTypeIds.insert(VC.VFunc.GUID);
3483 GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls());
3484 GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls());
3487 static void writeWholeProgramDevirtResolutionByArg(
3488 SmallVector<uint64_t, 64> &NameVals, const std::vector<uint64_t> &args,
3489 const WholeProgramDevirtResolution::ByArg &ByArg) {
3490 NameVals.push_back(args.size());
3491 NameVals.insert(NameVals.end(), args.begin(), args.end());
3493 NameVals.push_back(ByArg.TheKind);
3494 NameVals.push_back(ByArg.Info);
3495 NameVals.push_back(ByArg.Byte);
3496 NameVals.push_back(ByArg.Bit);
3499 static void writeWholeProgramDevirtResolution(
3500 SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
3501 uint64_t Id, const WholeProgramDevirtResolution &Wpd) {
3502 NameVals.push_back(Id);
3504 NameVals.push_back(Wpd.TheKind);
3505 NameVals.push_back(StrtabBuilder.add(Wpd.SingleImplName));
3506 NameVals.push_back(Wpd.SingleImplName.size());
3508 NameVals.push_back(Wpd.ResByArg.size());
3509 for (auto &A : Wpd.ResByArg)
3510 writeWholeProgramDevirtResolutionByArg(NameVals, A.first, A.second);
3513 static void writeTypeIdSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
3514 StringTableBuilder &StrtabBuilder,
3515 const std::string &Id,
3516 const TypeIdSummary &Summary) {
3517 NameVals.push_back(StrtabBuilder.add(Id));
3518 NameVals.push_back(Id.size());
3520 NameVals.push_back(Summary.TTRes.TheKind);
3521 NameVals.push_back(Summary.TTRes.SizeM1BitWidth);
3522 NameVals.push_back(Summary.TTRes.AlignLog2);
3523 NameVals.push_back(Summary.TTRes.SizeM1);
3524 NameVals.push_back(Summary.TTRes.BitMask);
3525 NameVals.push_back(Summary.TTRes.InlineBits);
3527 for (auto &W : Summary.WPDRes)
3528 writeWholeProgramDevirtResolution(NameVals, StrtabBuilder, W.first,
3529 W.second);
3532 // Helper to emit a single function summary record.
3533 void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
3534 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
3535 unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
3536 const Function &F) {
3537 NameVals.push_back(ValueID);
3539 FunctionSummary *FS = cast<FunctionSummary>(Summary);
3540 writeFunctionTypeMetadataRecords(Stream, FS);
3542 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
3543 NameVals.push_back(FS->instCount());
3544 NameVals.push_back(getEncodedFFlags(FS->fflags()));
3545 NameVals.push_back(FS->refs().size());
3546 NameVals.push_back(FS->immutableRefCount());
3548 for (auto &RI : FS->refs())
3549 NameVals.push_back(VE.getValueID(RI.getValue()));
3551 bool HasProfileData =
3552 F.hasProfileData() || ForceSummaryEdgesCold != FunctionSummary::FSHT_None;
3553 for (auto &ECI : FS->calls()) {
3554 NameVals.push_back(getValueId(ECI.first));
3555 if (HasProfileData)
3556 NameVals.push_back(static_cast<uint8_t>(ECI.second.Hotness));
3557 else if (WriteRelBFToSummary)
3558 NameVals.push_back(ECI.second.RelBlockFreq);
3561 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3562 unsigned Code =
3563 (HasProfileData ? bitc::FS_PERMODULE_PROFILE
3564 : (WriteRelBFToSummary ? bitc::FS_PERMODULE_RELBF
3565 : bitc::FS_PERMODULE));
3567 // Emit the finished record.
3568 Stream.EmitRecord(Code, NameVals, FSAbbrev);
3569 NameVals.clear();
3572 // Collect the global value references in the given variable's initializer,
3573 // and emit them in a summary record.
3574 void ModuleBitcodeWriterBase::writeModuleLevelReferences(
3575 const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
3576 unsigned FSModRefsAbbrev) {
3577 auto VI = Index->getValueInfo(V.getGUID());
3578 if (!VI || VI.getSummaryList().empty()) {
3579 // Only declarations should not have a summary (a declaration might however
3580 // have a summary if the def was in module level asm).
3581 assert(V.isDeclaration());
3582 return;
3584 auto *Summary = VI.getSummaryList()[0].get();
3585 NameVals.push_back(VE.getValueID(&V));
3586 GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
3587 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
3588 NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
3590 unsigned SizeBeforeRefs = NameVals.size();
3591 for (auto &RI : VS->refs())
3592 NameVals.push_back(VE.getValueID(RI.getValue()));
3593 // Sort the refs for determinism output, the vector returned by FS->refs() has
3594 // been initialized from a DenseSet.
3595 llvm::sort(NameVals.begin() + SizeBeforeRefs, NameVals.end());
3597 Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals,
3598 FSModRefsAbbrev);
3599 NameVals.clear();
3602 // Current version for the summary.
3603 // This is bumped whenever we introduce changes in the way some record are
3604 // interpreted, like flags for instance.
3605 static const uint64_t INDEX_VERSION = 6;
3607 /// Emit the per-module summary section alongside the rest of
3608 /// the module's bitcode.
3609 void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
3610 // By default we compile with ThinLTO if the module has a summary, but the
3611 // client can request full LTO with a module flag.
3612 bool IsThinLTO = true;
3613 if (auto *MD =
3614 mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
3615 IsThinLTO = MD->getZExtValue();
3616 Stream.EnterSubblock(IsThinLTO ? bitc::GLOBALVAL_SUMMARY_BLOCK_ID
3617 : bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID,
3620 Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
3622 // Write the index flags.
3623 uint64_t Flags = 0;
3624 // Bits 1-3 are set only in the combined index, skip them.
3625 if (Index->enableSplitLTOUnit())
3626 Flags |= 0x8;
3627 Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Flags});
3629 if (Index->begin() == Index->end()) {
3630 Stream.ExitBlock();
3631 return;
3634 for (const auto &GVI : valueIds()) {
3635 Stream.EmitRecord(bitc::FS_VALUE_GUID,
3636 ArrayRef<uint64_t>{GVI.second, GVI.first});
3639 // Abbrev for FS_PERMODULE_PROFILE.
3640 auto Abbv = std::make_shared<BitCodeAbbrev>();
3641 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));
3642 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3643 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3644 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3645 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
3646 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3647 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // immutablerefcnt
3648 // numrefs x valueid, n x (valueid, hotness)
3649 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3650 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3651 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3653 // Abbrev for FS_PERMODULE or FS_PERMODULE_RELBF.
3654 Abbv = std::make_shared<BitCodeAbbrev>();
3655 if (WriteRelBFToSummary)
3656 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_RELBF));
3657 else
3658 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE));
3659 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3660 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3661 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3662 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
3663 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3664 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // immutablerefcnt
3665 // numrefs x valueid, n x (valueid [, rel_block_freq])
3666 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3667 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3668 unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3670 // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
3671 Abbv = std::make_shared<BitCodeAbbrev>();
3672 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));
3673 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3674 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3675 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
3676 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3677 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3679 // Abbrev for FS_ALIAS.
3680 Abbv = std::make_shared<BitCodeAbbrev>();
3681 Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
3682 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3683 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3684 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3685 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3687 SmallVector<uint64_t, 64> NameVals;
3688 // Iterate over the list of functions instead of the Index to
3689 // ensure the ordering is stable.
3690 for (const Function &F : M) {
3691 // Summary emission does not support anonymous functions, they have to
3692 // renamed using the anonymous function renaming pass.
3693 if (!F.hasName())
3694 report_fatal_error("Unexpected anonymous function when writing summary");
3696 ValueInfo VI = Index->getValueInfo(F.getGUID());
3697 if (!VI || VI.getSummaryList().empty()) {
3698 // Only declarations should not have a summary (a declaration might
3699 // however have a summary if the def was in module level asm).
3700 assert(F.isDeclaration());
3701 continue;
3703 auto *Summary = VI.getSummaryList()[0].get();
3704 writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.getValueID(&F),
3705 FSCallsAbbrev, FSCallsProfileAbbrev, F);
3708 // Capture references from GlobalVariable initializers, which are outside
3709 // of a function scope.
3710 for (const GlobalVariable &G : M.globals())
3711 writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev);
3713 for (const GlobalAlias &A : M.aliases()) {
3714 auto *Aliasee = A.getBaseObject();
3715 if (!Aliasee->hasName())
3716 // Nameless function don't have an entry in the summary, skip it.
3717 continue;
3718 auto AliasId = VE.getValueID(&A);
3719 auto AliaseeId = VE.getValueID(Aliasee);
3720 NameVals.push_back(AliasId);
3721 auto *Summary = Index->getGlobalValueSummary(A);
3722 AliasSummary *AS = cast<AliasSummary>(Summary);
3723 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
3724 NameVals.push_back(AliaseeId);
3725 Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
3726 NameVals.clear();
3729 Stream.ExitBlock();
3732 /// Emit the combined summary section into the combined index file.
3733 void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
3734 Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3);
3735 Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
3737 // Write the index flags.
3738 uint64_t Flags = 0;
3739 if (Index.withGlobalValueDeadStripping())
3740 Flags |= 0x1;
3741 if (Index.skipModuleByDistributedBackend())
3742 Flags |= 0x2;
3743 if (Index.hasSyntheticEntryCounts())
3744 Flags |= 0x4;
3745 if (Index.enableSplitLTOUnit())
3746 Flags |= 0x8;
3747 if (Index.partiallySplitLTOUnits())
3748 Flags |= 0x10;
3749 Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Flags});
3751 for (const auto &GVI : valueIds()) {
3752 Stream.EmitRecord(bitc::FS_VALUE_GUID,
3753 ArrayRef<uint64_t>{GVI.second, GVI.first});
3756 // Abbrev for FS_COMBINED.
3757 auto Abbv = std::make_shared<BitCodeAbbrev>();
3758 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED));
3759 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3760 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
3761 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3762 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3763 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
3764 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // entrycount
3765 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3766 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // immutablerefcnt
3767 // numrefs x valueid, n x (valueid)
3768 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3769 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3770 unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3772 // Abbrev for FS_COMBINED_PROFILE.
3773 Abbv = std::make_shared<BitCodeAbbrev>();
3774 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));
3775 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3776 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
3777 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3778 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3779 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
3780 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3781 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // immutablerefcnt
3782 // numrefs x valueid, n x (valueid, hotness)
3783 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3784 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3785 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3787 // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
3788 Abbv = std::make_shared<BitCodeAbbrev>();
3789 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));
3790 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3791 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
3792 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3793 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
3794 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3795 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3797 // Abbrev for FS_COMBINED_ALIAS.
3798 Abbv = std::make_shared<BitCodeAbbrev>();
3799 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS));
3800 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3801 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
3802 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3803 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3804 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3806 // The aliases are emitted as a post-pass, and will point to the value
3807 // id of the aliasee. Save them in a vector for post-processing.
3808 SmallVector<AliasSummary *, 64> Aliases;
3810 // Save the value id for each summary for alias emission.
3811 DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
3813 SmallVector<uint64_t, 64> NameVals;
3815 // Set that will be populated during call to writeFunctionTypeMetadataRecords
3816 // with the type ids referenced by this index file.
3817 std::set<GlobalValue::GUID> ReferencedTypeIds;
3819 // For local linkage, we also emit the original name separately
3820 // immediately after the record.
3821 auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
3822 if (!GlobalValue::isLocalLinkage(S.linkage()))
3823 return;
3824 NameVals.push_back(S.getOriginalName());
3825 Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals);
3826 NameVals.clear();
3829 forEachSummary([&](GVInfo I, bool IsAliasee) {
3830 GlobalValueSummary *S = I.second;
3831 assert(S);
3833 auto ValueId = getValueId(I.first);
3834 assert(ValueId);
3835 SummaryToValueIdMap[S] = *ValueId;
3837 // If this is invoked for an aliasee, we want to record the above
3838 // mapping, but then not emit a summary entry (if the aliasee is
3839 // to be imported, we will invoke this separately with IsAliasee=false).
3840 if (IsAliasee)
3841 return;
3843 if (auto *AS = dyn_cast<AliasSummary>(S)) {
3844 // Will process aliases as a post-pass because the reader wants all
3845 // global to be loaded first.
3846 Aliases.push_back(AS);
3847 return;
3850 if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
3851 NameVals.push_back(*ValueId);
3852 NameVals.push_back(Index.getModuleId(VS->modulePath()));
3853 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
3854 NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
3855 for (auto &RI : VS->refs()) {
3856 auto RefValueId = getValueId(RI.getGUID());
3857 if (!RefValueId)
3858 continue;
3859 NameVals.push_back(*RefValueId);
3862 // Emit the finished record.
3863 Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals,
3864 FSModRefsAbbrev);
3865 NameVals.clear();
3866 MaybeEmitOriginalName(*S);
3867 return;
3870 auto *FS = cast<FunctionSummary>(S);
3871 writeFunctionTypeMetadataRecords(Stream, FS);
3872 getReferencedTypeIds(FS, ReferencedTypeIds);
3874 NameVals.push_back(*ValueId);
3875 NameVals.push_back(Index.getModuleId(FS->modulePath()));
3876 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
3877 NameVals.push_back(FS->instCount());
3878 NameVals.push_back(getEncodedFFlags(FS->fflags()));
3879 NameVals.push_back(FS->entryCount());
3881 // Fill in below
3882 NameVals.push_back(0); // numrefs
3883 NameVals.push_back(0); // immutablerefcnt
3885 unsigned Count = 0, ImmutableRefCnt = 0;
3886 for (auto &RI : FS->refs()) {
3887 auto RefValueId = getValueId(RI.getGUID());
3888 if (!RefValueId)
3889 continue;
3890 NameVals.push_back(*RefValueId);
3891 if (RI.isReadOnly())
3892 ImmutableRefCnt++;
3893 Count++;
3895 NameVals[6] = Count;
3896 NameVals[7] = ImmutableRefCnt;
3898 bool HasProfileData = false;
3899 for (auto &EI : FS->calls()) {
3900 HasProfileData |=
3901 EI.second.getHotness() != CalleeInfo::HotnessType::Unknown;
3902 if (HasProfileData)
3903 break;
3906 for (auto &EI : FS->calls()) {
3907 // If this GUID doesn't have a value id, it doesn't have a function
3908 // summary and we don't need to record any calls to it.
3909 GlobalValue::GUID GUID = EI.first.getGUID();
3910 auto CallValueId = getValueId(GUID);
3911 if (!CallValueId) {
3912 // For SamplePGO, the indirect call targets for local functions will
3913 // have its original name annotated in profile. We try to find the
3914 // corresponding PGOFuncName as the GUID.
3915 GUID = Index.getGUIDFromOriginalID(GUID);
3916 if (GUID == 0)
3917 continue;
3918 CallValueId = getValueId(GUID);
3919 if (!CallValueId)
3920 continue;
3921 // The mapping from OriginalId to GUID may return a GUID
3922 // that corresponds to a static variable. Filter it out here.
3923 // This can happen when
3924 // 1) There is a call to a library function which does not have
3925 // a CallValidId;
3926 // 2) There is a static variable with the OriginalGUID identical
3927 // to the GUID of the library function in 1);
3928 // When this happens, the logic for SamplePGO kicks in and
3929 // the static variable in 2) will be found, which needs to be
3930 // filtered out.
3931 auto *GVSum = Index.getGlobalValueSummary(GUID, false);
3932 if (GVSum &&
3933 GVSum->getSummaryKind() == GlobalValueSummary::GlobalVarKind)
3934 continue;
3936 NameVals.push_back(*CallValueId);
3937 if (HasProfileData)
3938 NameVals.push_back(static_cast<uint8_t>(EI.second.Hotness));
3941 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3942 unsigned Code =
3943 (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED);
3945 // Emit the finished record.
3946 Stream.EmitRecord(Code, NameVals, FSAbbrev);
3947 NameVals.clear();
3948 MaybeEmitOriginalName(*S);
3951 for (auto *AS : Aliases) {
3952 auto AliasValueId = SummaryToValueIdMap[AS];
3953 assert(AliasValueId);
3954 NameVals.push_back(AliasValueId);
3955 NameVals.push_back(Index.getModuleId(AS->modulePath()));
3956 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
3957 auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()];
3958 assert(AliaseeValueId);
3959 NameVals.push_back(AliaseeValueId);
3961 // Emit the finished record.
3962 Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
3963 NameVals.clear();
3964 MaybeEmitOriginalName(*AS);
3966 if (auto *FS = dyn_cast<FunctionSummary>(&AS->getAliasee()))
3967 getReferencedTypeIds(FS, ReferencedTypeIds);
3970 if (!Index.cfiFunctionDefs().empty()) {
3971 for (auto &S : Index.cfiFunctionDefs()) {
3972 NameVals.push_back(StrtabBuilder.add(S));
3973 NameVals.push_back(S.size());
3975 Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DEFS, NameVals);
3976 NameVals.clear();
3979 if (!Index.cfiFunctionDecls().empty()) {
3980 for (auto &S : Index.cfiFunctionDecls()) {
3981 NameVals.push_back(StrtabBuilder.add(S));
3982 NameVals.push_back(S.size());
3984 Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DECLS, NameVals);
3985 NameVals.clear();
3988 // Walk the GUIDs that were referenced, and write the
3989 // corresponding type id records.
3990 for (auto &T : ReferencedTypeIds) {
3991 auto TidIter = Index.typeIds().equal_range(T);
3992 for (auto It = TidIter.first; It != TidIter.second; ++It) {
3993 writeTypeIdSummaryRecord(NameVals, StrtabBuilder, It->second.first,
3994 It->second.second);
3995 Stream.EmitRecord(bitc::FS_TYPE_ID, NameVals);
3996 NameVals.clear();
4000 Stream.ExitBlock();
4003 /// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
4004 /// current llvm version, and a record for the epoch number.
4005 static void writeIdentificationBlock(BitstreamWriter &Stream) {
4006 Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);
4008 // Write the "user readable" string identifying the bitcode producer
4009 auto Abbv = std::make_shared<BitCodeAbbrev>();
4010 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING));
4011 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4012 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
4013 auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4014 writeStringRecord(Stream, bitc::IDENTIFICATION_CODE_STRING,
4015 "LLVM" LLVM_VERSION_STRING, StringAbbrev);
4017 // Write the epoch version
4018 Abbv = std::make_shared<BitCodeAbbrev>();
4019 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH));
4020 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4021 auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4022 SmallVector<unsigned, 1> Vals = {bitc::BITCODE_CURRENT_EPOCH};
4023 Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
4024 Stream.ExitBlock();
4027 void ModuleBitcodeWriter::writeModuleHash(size_t BlockStartPos) {
4028 // Emit the module's hash.
4029 // MODULE_CODE_HASH: [5*i32]
4030 if (GenerateHash) {
4031 uint32_t Vals[5];
4032 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&(Buffer)[BlockStartPos],
4033 Buffer.size() - BlockStartPos));
4034 StringRef Hash = Hasher.result();
4035 for (int Pos = 0; Pos < 20; Pos += 4) {
4036 Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);
4039 // Emit the finished record.
4040 Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
4042 if (ModHash)
4043 // Save the written hash value.
4044 llvm::copy(Vals, std::begin(*ModHash));
4048 void ModuleBitcodeWriter::write() {
4049 writeIdentificationBlock(Stream);
4051 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
4052 size_t BlockStartPos = Buffer.size();
4054 writeModuleVersion();
4056 // Emit blockinfo, which defines the standard abbreviations etc.
4057 writeBlockInfo();
4059 // Emit information about attribute groups.
4060 writeAttributeGroupTable();
4062 // Emit information about parameter attributes.
4063 writeAttributeTable();
4065 // Emit information describing all of the types in the module.
4066 writeTypeTable();
4068 writeComdats();
4070 // Emit top-level description of module, including target triple, inline asm,
4071 // descriptors for global variables, and function prototype info.
4072 writeModuleInfo();
4074 // Emit constants.
4075 writeModuleConstants();
4077 // Emit metadata kind names.
4078 writeModuleMetadataKinds();
4080 // Emit metadata.
4081 writeModuleMetadata();
4083 // Emit module-level use-lists.
4084 if (VE.shouldPreserveUseListOrder())
4085 writeUseListBlock(nullptr);
4087 writeOperandBundleTags();
4088 writeSyncScopeNames();
4090 // Emit function bodies.
4091 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
4092 for (Module::const_iterator F = M.begin(), E = M.end(); F != E; ++F)
4093 if (!F->isDeclaration())
4094 writeFunction(*F, FunctionToBitcodeIndex);
4096 // Need to write after the above call to WriteFunction which populates
4097 // the summary information in the index.
4098 if (Index)
4099 writePerModuleGlobalValueSummary();
4101 writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
4103 writeModuleHash(BlockStartPos);
4105 Stream.ExitBlock();
4108 static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
4109 uint32_t &Position) {
4110 support::endian::write32le(&Buffer[Position], Value);
4111 Position += 4;
4114 /// If generating a bc file on darwin, we have to emit a
4115 /// header and trailer to make it compatible with the system archiver. To do
4116 /// this we emit the following header, and then emit a trailer that pads the
4117 /// file out to be a multiple of 16 bytes.
4119 /// struct bc_header {
4120 /// uint32_t Magic; // 0x0B17C0DE
4121 /// uint32_t Version; // Version, currently always 0.
4122 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
4123 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
4124 /// uint32_t CPUType; // CPU specifier.
4125 /// ... potentially more later ...
4126 /// };
4127 static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
4128 const Triple &TT) {
4129 unsigned CPUType = ~0U;
4131 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
4132 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
4133 // number from /usr/include/mach/machine.h. It is ok to reproduce the
4134 // specific constants here because they are implicitly part of the Darwin ABI.
4135 enum {
4136 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
4137 DARWIN_CPU_TYPE_X86 = 7,
4138 DARWIN_CPU_TYPE_ARM = 12,
4139 DARWIN_CPU_TYPE_POWERPC = 18
4142 Triple::ArchType Arch = TT.getArch();
4143 if (Arch == Triple::x86_64)
4144 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
4145 else if (Arch == Triple::x86)
4146 CPUType = DARWIN_CPU_TYPE_X86;
4147 else if (Arch == Triple::ppc)
4148 CPUType = DARWIN_CPU_TYPE_POWERPC;
4149 else if (Arch == Triple::ppc64)
4150 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
4151 else if (Arch == Triple::arm || Arch == Triple::thumb)
4152 CPUType = DARWIN_CPU_TYPE_ARM;
4154 // Traditional Bitcode starts after header.
4155 assert(Buffer.size() >= BWH_HeaderSize &&
4156 "Expected header size to be reserved");
4157 unsigned BCOffset = BWH_HeaderSize;
4158 unsigned BCSize = Buffer.size() - BWH_HeaderSize;
4160 // Write the magic and version.
4161 unsigned Position = 0;
4162 writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
4163 writeInt32ToBuffer(0, Buffer, Position); // Version.
4164 writeInt32ToBuffer(BCOffset, Buffer, Position);
4165 writeInt32ToBuffer(BCSize, Buffer, Position);
4166 writeInt32ToBuffer(CPUType, Buffer, Position);
4168 // If the file is not a multiple of 16 bytes, insert dummy padding.
4169 while (Buffer.size() & 15)
4170 Buffer.push_back(0);
4173 /// Helper to write the header common to all bitcode files.
4174 static void writeBitcodeHeader(BitstreamWriter &Stream) {
4175 // Emit the file header.
4176 Stream.Emit((unsigned)'B', 8);
4177 Stream.Emit((unsigned)'C', 8);
4178 Stream.Emit(0x0, 4);
4179 Stream.Emit(0xC, 4);
4180 Stream.Emit(0xE, 4);
4181 Stream.Emit(0xD, 4);
4184 BitcodeWriter::BitcodeWriter(SmallVectorImpl<char> &Buffer)
4185 : Buffer(Buffer), Stream(new BitstreamWriter(Buffer)) {
4186 writeBitcodeHeader(*Stream);
4189 BitcodeWriter::~BitcodeWriter() { assert(WroteStrtab); }
4191 void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) {
4192 Stream->EnterSubblock(Block, 3);
4194 auto Abbv = std::make_shared<BitCodeAbbrev>();
4195 Abbv->Add(BitCodeAbbrevOp(Record));
4196 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4197 auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv));
4199 Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob);
4201 Stream->ExitBlock();
4204 void BitcodeWriter::writeSymtab() {
4205 assert(!WroteStrtab && !WroteSymtab);
4207 // If any module has module-level inline asm, we will require a registered asm
4208 // parser for the target so that we can create an accurate symbol table for
4209 // the module.
4210 for (Module *M : Mods) {
4211 if (M->getModuleInlineAsm().empty())
4212 continue;
4214 std::string Err;
4215 const Triple TT(M->getTargetTriple());
4216 const Target *T = TargetRegistry::lookupTarget(TT.str(), Err);
4217 if (!T || !T->hasMCAsmParser())
4218 return;
4221 WroteSymtab = true;
4222 SmallVector<char, 0> Symtab;
4223 // The irsymtab::build function may be unable to create a symbol table if the
4224 // module is malformed (e.g. it contains an invalid alias). Writing a symbol
4225 // table is not required for correctness, but we still want to be able to
4226 // write malformed modules to bitcode files, so swallow the error.
4227 if (Error E = irsymtab::build(Mods, Symtab, StrtabBuilder, Alloc)) {
4228 consumeError(std::move(E));
4229 return;
4232 writeBlob(bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB,
4233 {Symtab.data(), Symtab.size()});
4236 void BitcodeWriter::writeStrtab() {
4237 assert(!WroteStrtab);
4239 std::vector<char> Strtab;
4240 StrtabBuilder.finalizeInOrder();
4241 Strtab.resize(StrtabBuilder.getSize());
4242 StrtabBuilder.write((uint8_t *)Strtab.data());
4244 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB,
4245 {Strtab.data(), Strtab.size()});
4247 WroteStrtab = true;
4250 void BitcodeWriter::copyStrtab(StringRef Strtab) {
4251 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab);
4252 WroteStrtab = true;
4255 void BitcodeWriter::writeModule(const Module &M,
4256 bool ShouldPreserveUseListOrder,
4257 const ModuleSummaryIndex *Index,
4258 bool GenerateHash, ModuleHash *ModHash) {
4259 assert(!WroteStrtab);
4261 // The Mods vector is used by irsymtab::build, which requires non-const
4262 // Modules in case it needs to materialize metadata. But the bitcode writer
4263 // requires that the module is materialized, so we can cast to non-const here,
4264 // after checking that it is in fact materialized.
4265 assert(M.isMaterialized());
4266 Mods.push_back(const_cast<Module *>(&M));
4268 ModuleBitcodeWriter ModuleWriter(M, Buffer, StrtabBuilder, *Stream,
4269 ShouldPreserveUseListOrder, Index,
4270 GenerateHash, ModHash);
4271 ModuleWriter.write();
4274 void BitcodeWriter::writeIndex(
4275 const ModuleSummaryIndex *Index,
4276 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
4277 IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index,
4278 ModuleToSummariesForIndex);
4279 IndexWriter.write();
4282 /// Write the specified module to the specified output stream.
4283 void llvm::WriteBitcodeToFile(const Module &M, raw_ostream &Out,
4284 bool ShouldPreserveUseListOrder,
4285 const ModuleSummaryIndex *Index,
4286 bool GenerateHash, ModuleHash *ModHash) {
4287 SmallVector<char, 0> Buffer;
4288 Buffer.reserve(256*1024);
4290 // If this is darwin or another generic macho target, reserve space for the
4291 // header.
4292 Triple TT(M.getTargetTriple());
4293 if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
4294 Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
4296 BitcodeWriter Writer(Buffer);
4297 Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
4298 ModHash);
4299 Writer.writeSymtab();
4300 Writer.writeStrtab();
4302 if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
4303 emitDarwinBCHeaderAndTrailer(Buffer, TT);
4305 // Write the generated bitstream to "Out".
4306 Out.write((char*)&Buffer.front(), Buffer.size());
4309 void IndexBitcodeWriter::write() {
4310 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
4312 writeModuleVersion();
4314 // Write the module paths in the combined index.
4315 writeModStrings();
4317 // Write the summary combined index records.
4318 writeCombinedGlobalValueSummary();
4320 Stream.ExitBlock();
4323 // Write the specified module summary index to the given raw output stream,
4324 // where it will be written in a new bitcode block. This is used when
4325 // writing the combined index file for ThinLTO. When writing a subset of the
4326 // index for a distributed backend, provide a \p ModuleToSummariesForIndex map.
4327 void llvm::WriteIndexToFile(
4328 const ModuleSummaryIndex &Index, raw_ostream &Out,
4329 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
4330 SmallVector<char, 0> Buffer;
4331 Buffer.reserve(256 * 1024);
4333 BitcodeWriter Writer(Buffer);
4334 Writer.writeIndex(&Index, ModuleToSummariesForIndex);
4335 Writer.writeStrtab();
4337 Out.write((char *)&Buffer.front(), Buffer.size());
4340 namespace {
4342 /// Class to manage the bitcode writing for a thin link bitcode file.
4343 class ThinLinkBitcodeWriter : public ModuleBitcodeWriterBase {
4344 /// ModHash is for use in ThinLTO incremental build, generated while writing
4345 /// the module bitcode file.
4346 const ModuleHash *ModHash;
4348 public:
4349 ThinLinkBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder,
4350 BitstreamWriter &Stream,
4351 const ModuleSummaryIndex &Index,
4352 const ModuleHash &ModHash)
4353 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
4354 /*ShouldPreserveUseListOrder=*/false, &Index),
4355 ModHash(&ModHash) {}
4357 void write();
4359 private:
4360 void writeSimplifiedModuleInfo();
4363 } // end anonymous namespace
4365 // This function writes a simpilified module info for thin link bitcode file.
4366 // It only contains the source file name along with the name(the offset and
4367 // size in strtab) and linkage for global values. For the global value info
4368 // entry, in order to keep linkage at offset 5, there are three zeros used
4369 // as padding.
4370 void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {
4371 SmallVector<unsigned, 64> Vals;
4372 // Emit the module's source file name.
4374 StringEncoding Bits = getStringEncoding(M.getSourceFileName());
4375 BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
4376 if (Bits == SE_Char6)
4377 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
4378 else if (Bits == SE_Fixed7)
4379 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
4381 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
4382 auto Abbv = std::make_shared<BitCodeAbbrev>();
4383 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
4384 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4385 Abbv->Add(AbbrevOpToUse);
4386 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4388 for (const auto P : M.getSourceFileName())
4389 Vals.push_back((unsigned char)P);
4391 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
4392 Vals.clear();
4395 // Emit the global variable information.
4396 for (const GlobalVariable &GV : M.globals()) {
4397 // GLOBALVAR: [strtab offset, strtab size, 0, 0, 0, linkage]
4398 Vals.push_back(StrtabBuilder.add(GV.getName()));
4399 Vals.push_back(GV.getName().size());
4400 Vals.push_back(0);
4401 Vals.push_back(0);
4402 Vals.push_back(0);
4403 Vals.push_back(getEncodedLinkage(GV));
4405 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals);
4406 Vals.clear();
4409 // Emit the function proto information.
4410 for (const Function &F : M) {
4411 // FUNCTION: [strtab offset, strtab size, 0, 0, 0, linkage]
4412 Vals.push_back(StrtabBuilder.add(F.getName()));
4413 Vals.push_back(F.getName().size());
4414 Vals.push_back(0);
4415 Vals.push_back(0);
4416 Vals.push_back(0);
4417 Vals.push_back(getEncodedLinkage(F));
4419 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals);
4420 Vals.clear();
4423 // Emit the alias information.
4424 for (const GlobalAlias &A : M.aliases()) {
4425 // ALIAS: [strtab offset, strtab size, 0, 0, 0, linkage]
4426 Vals.push_back(StrtabBuilder.add(A.getName()));
4427 Vals.push_back(A.getName().size());
4428 Vals.push_back(0);
4429 Vals.push_back(0);
4430 Vals.push_back(0);
4431 Vals.push_back(getEncodedLinkage(A));
4433 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals);
4434 Vals.clear();
4437 // Emit the ifunc information.
4438 for (const GlobalIFunc &I : M.ifuncs()) {
4439 // IFUNC: [strtab offset, strtab size, 0, 0, 0, linkage]
4440 Vals.push_back(StrtabBuilder.add(I.getName()));
4441 Vals.push_back(I.getName().size());
4442 Vals.push_back(0);
4443 Vals.push_back(0);
4444 Vals.push_back(0);
4445 Vals.push_back(getEncodedLinkage(I));
4447 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
4448 Vals.clear();
4452 void ThinLinkBitcodeWriter::write() {
4453 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
4455 writeModuleVersion();
4457 writeSimplifiedModuleInfo();
4459 writePerModuleGlobalValueSummary();
4461 // Write module hash.
4462 Stream.EmitRecord(bitc::MODULE_CODE_HASH, ArrayRef<uint32_t>(*ModHash));
4464 Stream.ExitBlock();
4467 void BitcodeWriter::writeThinLinkBitcode(const Module &M,
4468 const ModuleSummaryIndex &Index,
4469 const ModuleHash &ModHash) {
4470 assert(!WroteStrtab);
4472 // The Mods vector is used by irsymtab::build, which requires non-const
4473 // Modules in case it needs to materialize metadata. But the bitcode writer
4474 // requires that the module is materialized, so we can cast to non-const here,
4475 // after checking that it is in fact materialized.
4476 assert(M.isMaterialized());
4477 Mods.push_back(const_cast<Module *>(&M));
4479 ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index,
4480 ModHash);
4481 ThinLinkWriter.write();
4484 // Write the specified thin link bitcode file to the given raw output stream,
4485 // where it will be written in a new bitcode block. This is used when
4486 // writing the per-module index file for ThinLTO.
4487 void llvm::WriteThinLinkBitcodeToFile(const Module &M, raw_ostream &Out,
4488 const ModuleSummaryIndex &Index,
4489 const ModuleHash &ModHash) {
4490 SmallVector<char, 0> Buffer;
4491 Buffer.reserve(256 * 1024);
4493 BitcodeWriter Writer(Buffer);
4494 Writer.writeThinLinkBitcode(M, Index, ModHash);
4495 Writer.writeSymtab();
4496 Writer.writeStrtab();
4498 Out.write((char *)&Buffer.front(), Buffer.size());