1 //===--- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Bitcode writer implementation.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Bitcode/BitcodeWriter.h"
15 #include "ValueEnumerator.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/ADT/Triple.h"
18 #include "llvm/Bitcode/BitstreamWriter.h"
19 #include "llvm/Bitcode/LLVMBitCodes.h"
20 #include "llvm/IR/CallSite.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DebugInfoMetadata.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/InlineAsm.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/Operator.h"
29 #include "llvm/IR/UseListOrder.h"
30 #include "llvm/IR/ValueSymbolTable.h"
31 #include "llvm/MC/StringTableBuilder.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/Program.h"
35 #include "llvm/Support/SHA1.h"
36 #include "llvm/Support/raw_ostream.h"
44 IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25),
45 cl::desc("Number of metadatas above which we emit an index "
46 "to enable lazy-loading"));
47 /// These are manifest constants used by the bitcode writer. They do not need to
48 /// be kept in sync with the reader, but need to be consistent within this file.
50 // VALUE_SYMTAB_BLOCK abbrev id's.
51 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
56 // CONSTANTS_BLOCK abbrev id's.
57 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
58 CONSTANTS_INTEGER_ABBREV,
59 CONSTANTS_CE_CAST_Abbrev,
60 CONSTANTS_NULL_Abbrev,
62 // FUNCTION_BLOCK abbrev id's.
63 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
64 FUNCTION_INST_BINOP_ABBREV,
65 FUNCTION_INST_BINOP_FLAGS_ABBREV,
66 FUNCTION_INST_CAST_ABBREV,
67 FUNCTION_INST_RET_VOID_ABBREV,
68 FUNCTION_INST_RET_VAL_ABBREV,
69 FUNCTION_INST_UNREACHABLE_ABBREV,
70 FUNCTION_INST_GEP_ABBREV,
73 /// Abstract class to manage the bitcode writing, subclassed for each bitcode
75 class BitcodeWriterBase {
77 /// The stream created and owned by the client.
78 BitstreamWriter &Stream;
81 /// Constructs a BitcodeWriterBase object that writes to the provided
83 BitcodeWriterBase(BitstreamWriter &Stream) : Stream(Stream) {}
86 void writeBitcodeHeader();
87 void writeModuleVersion();
90 void BitcodeWriterBase::writeModuleVersion() {
91 // VERSION: [version#]
92 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, ArrayRef<uint64_t>{2});
95 /// Class to manage the bitcode writing for a module.
96 class ModuleBitcodeWriter : public BitcodeWriterBase {
97 /// Pointer to the buffer allocated by caller for bitcode writing.
98 const SmallVectorImpl<char> &Buffer;
100 StringTableBuilder &StrtabBuilder;
102 /// The Module to write to bitcode.
105 /// Enumerates ids for all values in the module.
108 /// Optional per-module index to write for ThinLTO.
109 const ModuleSummaryIndex *Index;
111 /// True if a module hash record should be written.
114 /// If non-null, when GenerateHash is true, the resulting hash is written
115 /// into ModHash. When GenerateHash is false, that specified value
116 /// is used as the hash instead of computing from the generated bitcode.
117 /// Can be used to produce the same module hash for a minimized bitcode
118 /// used just for the thin link as in the regular full bitcode that will
119 /// be used in the backend.
122 /// The start bit of the identification block.
123 uint64_t BitcodeStartBit;
125 /// Map that holds the correspondence between GUIDs in the summary index,
126 /// that came from indirect call profiles, and a value id generated by this
127 /// class to use in the VST and summary block records.
128 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
130 /// Tracks the last value id recorded in the GUIDToValueMap.
131 unsigned GlobalValueId;
133 /// Saves the offset of the VSTOffset record that must eventually be
134 /// backpatched with the offset of the actual VST.
135 uint64_t VSTOffsetPlaceholder = 0;
138 /// Constructs a ModuleBitcodeWriter object for the given Module,
139 /// writing to the provided \p Buffer.
140 ModuleBitcodeWriter(const Module *M, SmallVectorImpl<char> &Buffer,
141 StringTableBuilder &StrtabBuilder,
142 BitstreamWriter &Stream, bool ShouldPreserveUseListOrder,
143 const ModuleSummaryIndex *Index, bool GenerateHash,
144 ModuleHash *ModHash = nullptr)
145 : BitcodeWriterBase(Stream), Buffer(Buffer), StrtabBuilder(StrtabBuilder),
146 M(*M), VE(*M, ShouldPreserveUseListOrder), Index(Index),
147 GenerateHash(GenerateHash), ModHash(ModHash),
148 BitcodeStartBit(Stream.GetCurrentBitNo()) {
149 // Assign ValueIds to any callee values in the index that came from
150 // indirect call profiles and were recorded as a GUID not a Value*
151 // (which would have been assigned an ID by the ValueEnumerator).
152 // The starting ValueId is just after the number of values in the
153 // ValueEnumerator, so that they can be emitted in the VST.
154 GlobalValueId = VE.getValues().size();
157 for (const auto &GUIDSummaryLists : *Index)
158 // Examine all summaries for this GUID.
159 for (auto &Summary : GUIDSummaryLists.second.SummaryList)
160 if (auto FS = dyn_cast<FunctionSummary>(Summary.get()))
161 // For each call in the function summary, see if the call
162 // is to a GUID (which means it is for an indirect call,
163 // otherwise we would have a Value for it). If so, synthesize
165 for (auto &CallEdge : FS->calls())
166 if (!CallEdge.first.getValue())
167 assignValueId(CallEdge.first.getGUID());
170 /// Emit the current module to the bitstream.
174 uint64_t bitcodeStartBit() { return BitcodeStartBit; }
176 void writeAttributeGroupTable();
177 void writeAttributeTable();
178 void writeTypeTable();
180 void writeValueSymbolTableForwardDecl();
181 void writeModuleInfo();
182 void writeValueAsMetadata(const ValueAsMetadata *MD,
183 SmallVectorImpl<uint64_t> &Record);
184 void writeMDTuple(const MDTuple *N, SmallVectorImpl<uint64_t> &Record,
186 unsigned createDILocationAbbrev();
187 void writeDILocation(const DILocation *N, SmallVectorImpl<uint64_t> &Record,
189 unsigned createGenericDINodeAbbrev();
190 void writeGenericDINode(const GenericDINode *N,
191 SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev);
192 void writeDISubrange(const DISubrange *N, SmallVectorImpl<uint64_t> &Record,
194 void writeDIEnumerator(const DIEnumerator *N,
195 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
196 void writeDIBasicType(const DIBasicType *N, SmallVectorImpl<uint64_t> &Record,
198 void writeDIDerivedType(const DIDerivedType *N,
199 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
200 void writeDICompositeType(const DICompositeType *N,
201 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
202 void writeDISubroutineType(const DISubroutineType *N,
203 SmallVectorImpl<uint64_t> &Record,
205 void writeDIFile(const DIFile *N, SmallVectorImpl<uint64_t> &Record,
207 void writeDICompileUnit(const DICompileUnit *N,
208 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
209 void writeDISubprogram(const DISubprogram *N,
210 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
211 void writeDILexicalBlock(const DILexicalBlock *N,
212 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
213 void writeDILexicalBlockFile(const DILexicalBlockFile *N,
214 SmallVectorImpl<uint64_t> &Record,
216 void writeDINamespace(const DINamespace *N, SmallVectorImpl<uint64_t> &Record,
218 void writeDIMacro(const DIMacro *N, SmallVectorImpl<uint64_t> &Record,
220 void writeDIMacroFile(const DIMacroFile *N, SmallVectorImpl<uint64_t> &Record,
222 void writeDIModule(const DIModule *N, SmallVectorImpl<uint64_t> &Record,
224 void writeDITemplateTypeParameter(const DITemplateTypeParameter *N,
225 SmallVectorImpl<uint64_t> &Record,
227 void writeDITemplateValueParameter(const DITemplateValueParameter *N,
228 SmallVectorImpl<uint64_t> &Record,
230 void writeDIGlobalVariable(const DIGlobalVariable *N,
231 SmallVectorImpl<uint64_t> &Record,
233 void writeDILocalVariable(const DILocalVariable *N,
234 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
235 void writeDIExpression(const DIExpression *N,
236 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
237 void writeDIGlobalVariableExpression(const DIGlobalVariableExpression *N,
238 SmallVectorImpl<uint64_t> &Record,
240 void writeDIObjCProperty(const DIObjCProperty *N,
241 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
242 void writeDIImportedEntity(const DIImportedEntity *N,
243 SmallVectorImpl<uint64_t> &Record,
245 unsigned createNamedMetadataAbbrev();
246 void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
247 unsigned createMetadataStringsAbbrev();
248 void writeMetadataStrings(ArrayRef<const Metadata *> Strings,
249 SmallVectorImpl<uint64_t> &Record);
250 void writeMetadataRecords(ArrayRef<const Metadata *> MDs,
251 SmallVectorImpl<uint64_t> &Record,
252 std::vector<unsigned> *MDAbbrevs = nullptr,
253 std::vector<uint64_t> *IndexPos = nullptr);
254 void writeModuleMetadata();
255 void writeFunctionMetadata(const Function &F);
256 void writeFunctionMetadataAttachment(const Function &F);
257 void writeGlobalVariableMetadataAttachment(const GlobalVariable &GV);
258 void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
259 const GlobalObject &GO);
260 void writeModuleMetadataKinds();
261 void writeOperandBundleTags();
262 void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal);
263 void writeModuleConstants();
264 bool pushValueAndType(const Value *V, unsigned InstID,
265 SmallVectorImpl<unsigned> &Vals);
266 void writeOperandBundles(ImmutableCallSite CS, unsigned InstID);
267 void pushValue(const Value *V, unsigned InstID,
268 SmallVectorImpl<unsigned> &Vals);
269 void pushValueSigned(const Value *V, unsigned InstID,
270 SmallVectorImpl<uint64_t> &Vals);
271 void writeInstruction(const Instruction &I, unsigned InstID,
272 SmallVectorImpl<unsigned> &Vals);
273 void writeFunctionLevelValueSymbolTable(const ValueSymbolTable &VST);
274 void writeGlobalValueSymbolTable(
275 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
276 void writeUseList(UseListOrder &&Order);
277 void writeUseListBlock(const Function *F);
279 writeFunction(const Function &F,
280 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
281 void writeBlockInfo();
282 void writePerModuleFunctionSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
283 GlobalValueSummary *Summary,
285 unsigned FSCallsAbbrev,
286 unsigned FSCallsProfileAbbrev,
288 void writeModuleLevelReferences(const GlobalVariable &V,
289 SmallVector<uint64_t, 64> &NameVals,
290 unsigned FSModRefsAbbrev);
291 void writePerModuleGlobalValueSummary();
292 void writeModuleHash(size_t BlockStartPos);
294 void assignValueId(GlobalValue::GUID ValGUID) {
295 GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
297 unsigned getValueId(GlobalValue::GUID ValGUID) {
298 const auto &VMI = GUIDToValueIdMap.find(ValGUID);
299 // Expect that any GUID value had a value Id assigned by an
300 // earlier call to assignValueId.
301 assert(VMI != GUIDToValueIdMap.end() &&
302 "GUID does not have assigned value Id");
305 // Helper to get the valueId for the type of value recorded in VI.
306 unsigned getValueId(ValueInfo VI) {
308 return getValueId(VI.getGUID());
309 return VE.getValueID(VI.getValue());
311 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
314 /// Class to manage the bitcode writing for a combined index.
315 class IndexBitcodeWriter : public BitcodeWriterBase {
316 /// The combined index to write to bitcode.
317 const ModuleSummaryIndex &Index;
319 /// When writing a subset of the index for distributed backends, client
320 /// provides a map of modules to the corresponding GUIDs/summaries to write.
321 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex;
323 /// Map that holds the correspondence between the GUID used in the combined
324 /// index and a value id generated by this class to use in references.
325 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
327 /// Tracks the last value id recorded in the GUIDToValueMap.
328 unsigned GlobalValueId = 0;
331 /// Constructs a IndexBitcodeWriter object for the given combined index,
332 /// writing to the provided \p Buffer. When writing a subset of the index
333 /// for a distributed backend, provide a \p ModuleToSummariesForIndex map.
334 IndexBitcodeWriter(BitstreamWriter &Stream, const ModuleSummaryIndex &Index,
335 const std::map<std::string, GVSummaryMapTy>
336 *ModuleToSummariesForIndex = nullptr)
337 : BitcodeWriterBase(Stream), Index(Index),
338 ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
339 // Assign unique value ids to all summaries to be written, for use
340 // in writing out the call graph edges. Save the mapping from GUID
341 // to the new global value id to use when writing those edges, which
342 // are currently saved in the index in terms of GUID.
343 forEachSummary([&](GVInfo I) {
344 GUIDToValueIdMap[I.first] = ++GlobalValueId;
348 /// The below iterator returns the GUID and associated summary.
349 typedef std::pair<GlobalValue::GUID, GlobalValueSummary *> GVInfo;
351 /// Calls the callback for each value GUID and summary to be written to
352 /// bitcode. This hides the details of whether they are being pulled from the
353 /// entire index or just those in a provided ModuleToSummariesForIndex map.
354 template<typename Functor>
355 void forEachSummary(Functor Callback) {
356 if (ModuleToSummariesForIndex) {
357 for (auto &M : *ModuleToSummariesForIndex)
358 for (auto &Summary : M.second)
361 for (auto &Summaries : Index)
362 for (auto &Summary : Summaries.second.SummaryList)
363 Callback({Summaries.first, Summary.get()});
367 /// Calls the callback for each entry in the modulePaths StringMap that
368 /// should be written to the module path string table. This hides the details
369 /// of whether they are being pulled from the entire index or just those in a
370 /// provided ModuleToSummariesForIndex map.
371 template <typename Functor> void forEachModule(Functor Callback) {
372 if (ModuleToSummariesForIndex) {
373 for (const auto &M : *ModuleToSummariesForIndex) {
374 const auto &MPI = Index.modulePaths().find(M.first);
375 if (MPI == Index.modulePaths().end()) {
376 // This should only happen if the bitcode file was empty, in which
377 // case we shouldn't be importing (the ModuleToSummariesForIndex
378 // would only include the module we are writing and index for).
379 assert(ModuleToSummariesForIndex->size() == 1);
385 for (const auto &MPSE : Index.modulePaths())
390 /// Main entry point for writing a combined index to bitcode.
394 void writeModStrings();
395 void writeCombinedGlobalValueSummary();
397 Optional<unsigned> getValueId(GlobalValue::GUID ValGUID) {
398 auto VMI = GUIDToValueIdMap.find(ValGUID);
399 if (VMI == GUIDToValueIdMap.end())
403 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
405 } // end anonymous namespace
407 static unsigned getEncodedCastOpcode(unsigned Opcode) {
409 default: llvm_unreachable("Unknown cast instruction!");
410 case Instruction::Trunc : return bitc::CAST_TRUNC;
411 case Instruction::ZExt : return bitc::CAST_ZEXT;
412 case Instruction::SExt : return bitc::CAST_SEXT;
413 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
414 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
415 case Instruction::UIToFP : return bitc::CAST_UITOFP;
416 case Instruction::SIToFP : return bitc::CAST_SITOFP;
417 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
418 case Instruction::FPExt : return bitc::CAST_FPEXT;
419 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
420 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
421 case Instruction::BitCast : return bitc::CAST_BITCAST;
422 case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
426 static unsigned getEncodedBinaryOpcode(unsigned Opcode) {
428 default: llvm_unreachable("Unknown binary instruction!");
429 case Instruction::Add:
430 case Instruction::FAdd: return bitc::BINOP_ADD;
431 case Instruction::Sub:
432 case Instruction::FSub: return bitc::BINOP_SUB;
433 case Instruction::Mul:
434 case Instruction::FMul: return bitc::BINOP_MUL;
435 case Instruction::UDiv: return bitc::BINOP_UDIV;
436 case Instruction::FDiv:
437 case Instruction::SDiv: return bitc::BINOP_SDIV;
438 case Instruction::URem: return bitc::BINOP_UREM;
439 case Instruction::FRem:
440 case Instruction::SRem: return bitc::BINOP_SREM;
441 case Instruction::Shl: return bitc::BINOP_SHL;
442 case Instruction::LShr: return bitc::BINOP_LSHR;
443 case Instruction::AShr: return bitc::BINOP_ASHR;
444 case Instruction::And: return bitc::BINOP_AND;
445 case Instruction::Or: return bitc::BINOP_OR;
446 case Instruction::Xor: return bitc::BINOP_XOR;
450 static unsigned getEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
452 default: llvm_unreachable("Unknown RMW operation!");
453 case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
454 case AtomicRMWInst::Add: return bitc::RMW_ADD;
455 case AtomicRMWInst::Sub: return bitc::RMW_SUB;
456 case AtomicRMWInst::And: return bitc::RMW_AND;
457 case AtomicRMWInst::Nand: return bitc::RMW_NAND;
458 case AtomicRMWInst::Or: return bitc::RMW_OR;
459 case AtomicRMWInst::Xor: return bitc::RMW_XOR;
460 case AtomicRMWInst::Max: return bitc::RMW_MAX;
461 case AtomicRMWInst::Min: return bitc::RMW_MIN;
462 case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
463 case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
467 static unsigned getEncodedOrdering(AtomicOrdering Ordering) {
469 case AtomicOrdering::NotAtomic: return bitc::ORDERING_NOTATOMIC;
470 case AtomicOrdering::Unordered: return bitc::ORDERING_UNORDERED;
471 case AtomicOrdering::Monotonic: return bitc::ORDERING_MONOTONIC;
472 case AtomicOrdering::Acquire: return bitc::ORDERING_ACQUIRE;
473 case AtomicOrdering::Release: return bitc::ORDERING_RELEASE;
474 case AtomicOrdering::AcquireRelease: return bitc::ORDERING_ACQREL;
475 case AtomicOrdering::SequentiallyConsistent: return bitc::ORDERING_SEQCST;
477 llvm_unreachable("Invalid ordering");
480 static unsigned getEncodedSynchScope(SynchronizationScope SynchScope) {
481 switch (SynchScope) {
482 case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD;
483 case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD;
485 llvm_unreachable("Invalid synch scope");
488 static void writeStringRecord(BitstreamWriter &Stream, unsigned Code,
489 StringRef Str, unsigned AbbrevToUse) {
490 SmallVector<unsigned, 64> Vals;
492 // Code: [strchar x N]
493 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
494 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
496 Vals.push_back(Str[i]);
499 // Emit the finished record.
500 Stream.EmitRecord(Code, Vals, AbbrevToUse);
503 static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
505 case Attribute::Alignment:
506 return bitc::ATTR_KIND_ALIGNMENT;
507 case Attribute::AllocSize:
508 return bitc::ATTR_KIND_ALLOC_SIZE;
509 case Attribute::AlwaysInline:
510 return bitc::ATTR_KIND_ALWAYS_INLINE;
511 case Attribute::ArgMemOnly:
512 return bitc::ATTR_KIND_ARGMEMONLY;
513 case Attribute::Builtin:
514 return bitc::ATTR_KIND_BUILTIN;
515 case Attribute::ByVal:
516 return bitc::ATTR_KIND_BY_VAL;
517 case Attribute::Convergent:
518 return bitc::ATTR_KIND_CONVERGENT;
519 case Attribute::InAlloca:
520 return bitc::ATTR_KIND_IN_ALLOCA;
521 case Attribute::Cold:
522 return bitc::ATTR_KIND_COLD;
523 case Attribute::InaccessibleMemOnly:
524 return bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY;
525 case Attribute::InaccessibleMemOrArgMemOnly:
526 return bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY;
527 case Attribute::InlineHint:
528 return bitc::ATTR_KIND_INLINE_HINT;
529 case Attribute::InReg:
530 return bitc::ATTR_KIND_IN_REG;
531 case Attribute::JumpTable:
532 return bitc::ATTR_KIND_JUMP_TABLE;
533 case Attribute::MinSize:
534 return bitc::ATTR_KIND_MIN_SIZE;
535 case Attribute::Naked:
536 return bitc::ATTR_KIND_NAKED;
537 case Attribute::Nest:
538 return bitc::ATTR_KIND_NEST;
539 case Attribute::NoAlias:
540 return bitc::ATTR_KIND_NO_ALIAS;
541 case Attribute::NoBuiltin:
542 return bitc::ATTR_KIND_NO_BUILTIN;
543 case Attribute::NoCapture:
544 return bitc::ATTR_KIND_NO_CAPTURE;
545 case Attribute::NoDuplicate:
546 return bitc::ATTR_KIND_NO_DUPLICATE;
547 case Attribute::NoImplicitFloat:
548 return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
549 case Attribute::NoInline:
550 return bitc::ATTR_KIND_NO_INLINE;
551 case Attribute::NoRecurse:
552 return bitc::ATTR_KIND_NO_RECURSE;
553 case Attribute::NonLazyBind:
554 return bitc::ATTR_KIND_NON_LAZY_BIND;
555 case Attribute::NonNull:
556 return bitc::ATTR_KIND_NON_NULL;
557 case Attribute::Dereferenceable:
558 return bitc::ATTR_KIND_DEREFERENCEABLE;
559 case Attribute::DereferenceableOrNull:
560 return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL;
561 case Attribute::NoRedZone:
562 return bitc::ATTR_KIND_NO_RED_ZONE;
563 case Attribute::NoReturn:
564 return bitc::ATTR_KIND_NO_RETURN;
565 case Attribute::NoUnwind:
566 return bitc::ATTR_KIND_NO_UNWIND;
567 case Attribute::OptimizeForSize:
568 return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
569 case Attribute::OptimizeNone:
570 return bitc::ATTR_KIND_OPTIMIZE_NONE;
571 case Attribute::ReadNone:
572 return bitc::ATTR_KIND_READ_NONE;
573 case Attribute::ReadOnly:
574 return bitc::ATTR_KIND_READ_ONLY;
575 case Attribute::Returned:
576 return bitc::ATTR_KIND_RETURNED;
577 case Attribute::ReturnsTwice:
578 return bitc::ATTR_KIND_RETURNS_TWICE;
579 case Attribute::SExt:
580 return bitc::ATTR_KIND_S_EXT;
581 case Attribute::Speculatable:
582 return bitc::ATTR_KIND_SPECULATABLE;
583 case Attribute::StackAlignment:
584 return bitc::ATTR_KIND_STACK_ALIGNMENT;
585 case Attribute::StackProtect:
586 return bitc::ATTR_KIND_STACK_PROTECT;
587 case Attribute::StackProtectReq:
588 return bitc::ATTR_KIND_STACK_PROTECT_REQ;
589 case Attribute::StackProtectStrong:
590 return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
591 case Attribute::SafeStack:
592 return bitc::ATTR_KIND_SAFESTACK;
593 case Attribute::StructRet:
594 return bitc::ATTR_KIND_STRUCT_RET;
595 case Attribute::SanitizeAddress:
596 return bitc::ATTR_KIND_SANITIZE_ADDRESS;
597 case Attribute::SanitizeThread:
598 return bitc::ATTR_KIND_SANITIZE_THREAD;
599 case Attribute::SanitizeMemory:
600 return bitc::ATTR_KIND_SANITIZE_MEMORY;
601 case Attribute::SwiftError:
602 return bitc::ATTR_KIND_SWIFT_ERROR;
603 case Attribute::SwiftSelf:
604 return bitc::ATTR_KIND_SWIFT_SELF;
605 case Attribute::UWTable:
606 return bitc::ATTR_KIND_UW_TABLE;
607 case Attribute::WriteOnly:
608 return bitc::ATTR_KIND_WRITEONLY;
609 case Attribute::ZExt:
610 return bitc::ATTR_KIND_Z_EXT;
611 case Attribute::EndAttrKinds:
612 llvm_unreachable("Can not encode end-attribute kinds marker.");
613 case Attribute::None:
614 llvm_unreachable("Can not encode none-attribute.");
617 llvm_unreachable("Trying to encode unknown attribute");
620 void ModuleBitcodeWriter::writeAttributeGroupTable() {
621 const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
622 VE.getAttributeGroups();
623 if (AttrGrps.empty()) return;
625 Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
627 SmallVector<uint64_t, 64> Record;
628 for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) {
629 unsigned AttrListIndex = Pair.first;
630 AttributeSet AS = Pair.second;
631 Record.push_back(VE.getAttributeGroupID(Pair));
632 Record.push_back(AttrListIndex);
634 for (Attribute Attr : AS) {
635 if (Attr.isEnumAttribute()) {
637 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
638 } else if (Attr.isIntAttribute()) {
640 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
641 Record.push_back(Attr.getValueAsInt());
643 StringRef Kind = Attr.getKindAsString();
644 StringRef Val = Attr.getValueAsString();
646 Record.push_back(Val.empty() ? 3 : 4);
647 Record.append(Kind.begin(), Kind.end());
650 Record.append(Val.begin(), Val.end());
656 Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
663 void ModuleBitcodeWriter::writeAttributeTable() {
664 const std::vector<AttributeList> &Attrs = VE.getAttributeLists();
665 if (Attrs.empty()) return;
667 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
669 SmallVector<uint64_t, 64> Record;
670 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
671 AttributeList AL = Attrs[i];
672 for (unsigned i = AL.index_begin(), e = AL.index_end(); i != e; ++i) {
673 AttributeSet AS = AL.getAttributes(i);
674 if (AS.hasAttributes())
675 Record.push_back(VE.getAttributeGroupID({i, AS}));
678 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
685 /// WriteTypeTable - Write out the type table for a module.
686 void ModuleBitcodeWriter::writeTypeTable() {
687 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
689 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
690 SmallVector<uint64_t, 64> TypeVals;
692 uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies();
694 // Abbrev for TYPE_CODE_POINTER.
695 auto Abbv = std::make_shared<BitCodeAbbrev>();
696 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
697 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
698 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
699 unsigned PtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
701 // Abbrev for TYPE_CODE_FUNCTION.
702 Abbv = std::make_shared<BitCodeAbbrev>();
703 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
704 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
705 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
706 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
708 unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));
710 // Abbrev for TYPE_CODE_STRUCT_ANON.
711 Abbv = std::make_shared<BitCodeAbbrev>();
712 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
713 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
714 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
715 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
717 unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));
719 // Abbrev for TYPE_CODE_STRUCT_NAME.
720 Abbv = std::make_shared<BitCodeAbbrev>();
721 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
722 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
723 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
724 unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
726 // Abbrev for TYPE_CODE_STRUCT_NAMED.
727 Abbv = std::make_shared<BitCodeAbbrev>();
728 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
729 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
730 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
731 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
733 unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));
735 // Abbrev for TYPE_CODE_ARRAY.
736 Abbv = std::make_shared<BitCodeAbbrev>();
737 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
738 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
739 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
741 unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));
743 // Emit an entry count so the reader can reserve space.
744 TypeVals.push_back(TypeList.size());
745 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
748 // Loop over all of the types, emitting each in turn.
749 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
750 Type *T = TypeList[i];
754 switch (T->getTypeID()) {
755 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
756 case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break;
757 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
758 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
759 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
760 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
761 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
762 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
763 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
764 case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break;
765 case Type::TokenTyID: Code = bitc::TYPE_CODE_TOKEN; break;
766 case Type::IntegerTyID:
768 Code = bitc::TYPE_CODE_INTEGER;
769 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
771 case Type::PointerTyID: {
772 PointerType *PTy = cast<PointerType>(T);
773 // POINTER: [pointee type, address space]
774 Code = bitc::TYPE_CODE_POINTER;
775 TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
776 unsigned AddressSpace = PTy->getAddressSpace();
777 TypeVals.push_back(AddressSpace);
778 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
781 case Type::FunctionTyID: {
782 FunctionType *FT = cast<FunctionType>(T);
783 // FUNCTION: [isvararg, retty, paramty x N]
784 Code = bitc::TYPE_CODE_FUNCTION;
785 TypeVals.push_back(FT->isVarArg());
786 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
787 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
788 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
789 AbbrevToUse = FunctionAbbrev;
792 case Type::StructTyID: {
793 StructType *ST = cast<StructType>(T);
794 // STRUCT: [ispacked, eltty x N]
795 TypeVals.push_back(ST->isPacked());
796 // Output all of the element types.
797 for (StructType::element_iterator I = ST->element_begin(),
798 E = ST->element_end(); I != E; ++I)
799 TypeVals.push_back(VE.getTypeID(*I));
801 if (ST->isLiteral()) {
802 Code = bitc::TYPE_CODE_STRUCT_ANON;
803 AbbrevToUse = StructAnonAbbrev;
805 if (ST->isOpaque()) {
806 Code = bitc::TYPE_CODE_OPAQUE;
808 Code = bitc::TYPE_CODE_STRUCT_NAMED;
809 AbbrevToUse = StructNamedAbbrev;
812 // Emit the name if it is present.
813 if (!ST->getName().empty())
814 writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
819 case Type::ArrayTyID: {
820 ArrayType *AT = cast<ArrayType>(T);
821 // ARRAY: [numelts, eltty]
822 Code = bitc::TYPE_CODE_ARRAY;
823 TypeVals.push_back(AT->getNumElements());
824 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
825 AbbrevToUse = ArrayAbbrev;
828 case Type::VectorTyID: {
829 VectorType *VT = cast<VectorType>(T);
830 // VECTOR [numelts, eltty]
831 Code = bitc::TYPE_CODE_VECTOR;
832 TypeVals.push_back(VT->getNumElements());
833 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
838 // Emit the finished record.
839 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
846 static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {
848 case GlobalValue::ExternalLinkage:
850 case GlobalValue::WeakAnyLinkage:
852 case GlobalValue::AppendingLinkage:
854 case GlobalValue::InternalLinkage:
856 case GlobalValue::LinkOnceAnyLinkage:
858 case GlobalValue::ExternalWeakLinkage:
860 case GlobalValue::CommonLinkage:
862 case GlobalValue::PrivateLinkage:
864 case GlobalValue::WeakODRLinkage:
866 case GlobalValue::LinkOnceODRLinkage:
868 case GlobalValue::AvailableExternallyLinkage:
871 llvm_unreachable("Invalid linkage");
874 static unsigned getEncodedLinkage(const GlobalValue &GV) {
875 return getEncodedLinkage(GV.getLinkage());
878 // Decode the flags for GlobalValue in the summary
879 static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags) {
880 uint64_t RawFlags = 0;
882 RawFlags |= Flags.NotEligibleToImport; // bool
883 RawFlags |= (Flags.Live << 1);
884 // Linkage don't need to be remapped at that time for the summary. Any future
885 // change to the getEncodedLinkage() function will need to be taken into
886 // account here as well.
887 RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits
892 static unsigned getEncodedVisibility(const GlobalValue &GV) {
893 switch (GV.getVisibility()) {
894 case GlobalValue::DefaultVisibility: return 0;
895 case GlobalValue::HiddenVisibility: return 1;
896 case GlobalValue::ProtectedVisibility: return 2;
898 llvm_unreachable("Invalid visibility");
901 static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
902 switch (GV.getDLLStorageClass()) {
903 case GlobalValue::DefaultStorageClass: return 0;
904 case GlobalValue::DLLImportStorageClass: return 1;
905 case GlobalValue::DLLExportStorageClass: return 2;
907 llvm_unreachable("Invalid DLL storage class");
910 static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
911 switch (GV.getThreadLocalMode()) {
912 case GlobalVariable::NotThreadLocal: return 0;
913 case GlobalVariable::GeneralDynamicTLSModel: return 1;
914 case GlobalVariable::LocalDynamicTLSModel: return 2;
915 case GlobalVariable::InitialExecTLSModel: return 3;
916 case GlobalVariable::LocalExecTLSModel: return 4;
918 llvm_unreachable("Invalid TLS model");
921 static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
922 switch (C.getSelectionKind()) {
924 return bitc::COMDAT_SELECTION_KIND_ANY;
925 case Comdat::ExactMatch:
926 return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
927 case Comdat::Largest:
928 return bitc::COMDAT_SELECTION_KIND_LARGEST;
929 case Comdat::NoDuplicates:
930 return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
931 case Comdat::SameSize:
932 return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
934 llvm_unreachable("Invalid selection kind");
937 static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) {
938 switch (GV.getUnnamedAddr()) {
939 case GlobalValue::UnnamedAddr::None: return 0;
940 case GlobalValue::UnnamedAddr::Local: return 2;
941 case GlobalValue::UnnamedAddr::Global: return 1;
943 llvm_unreachable("Invalid unnamed_addr");
946 void ModuleBitcodeWriter::writeComdats() {
947 SmallVector<unsigned, 64> Vals;
948 for (const Comdat *C : VE.getComdats()) {
949 // COMDAT: [strtab offset, strtab size, selection_kind]
950 Vals.push_back(StrtabBuilder.add(C->getName()));
951 Vals.push_back(C->getName().size());
952 Vals.push_back(getEncodedComdatSelectionKind(*C));
953 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
958 /// Write a record that will eventually hold the word offset of the
959 /// module-level VST. For now the offset is 0, which will be backpatched
960 /// after the real VST is written. Saves the bit offset to backpatch.
961 void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
962 // Write a placeholder value in for the offset of the real VST,
963 // which is written after the function blocks so that it can include
964 // the offset of each function. The placeholder offset will be
965 // updated when the real VST is written.
966 auto Abbv = std::make_shared<BitCodeAbbrev>();
967 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET));
968 // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
969 // hold the real VST offset. Must use fixed instead of VBR as we don't
970 // know how many VBR chunks to reserve ahead of time.
971 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
972 unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
974 // Emit the placeholder
975 uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0};
976 Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
978 // Compute and save the bit offset to the placeholder, which will be
979 // patched when the real VST is written. We can simply subtract the 32-bit
980 // fixed size from the current bit number to get the location to backpatch.
981 VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32;
984 enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 };
986 /// Determine the encoding to use for the given string name and length.
987 static StringEncoding getStringEncoding(StringRef Str) {
991 isChar6 = BitCodeAbbrevOp::isChar6(C);
992 if ((unsigned char)C & 128)
993 // don't bother scanning the rest.
1001 /// Emit top-level description of module, including target triple, inline asm,
1002 /// descriptors for global variables, and function prototype info.
1003 /// Returns the bit offset to backpatch with the location of the real VST.
1004 void ModuleBitcodeWriter::writeModuleInfo() {
1005 // Emit various pieces of data attached to a module.
1006 if (!M.getTargetTriple().empty())
1007 writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(),
1009 const std::string &DL = M.getDataLayoutStr();
1011 writeStringRecord(Stream, bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/);
1012 if (!M.getModuleInlineAsm().empty())
1013 writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(),
1016 // Emit information about sections and GC, computing how many there are. Also
1017 // compute the maximum alignment value.
1018 std::map<std::string, unsigned> SectionMap;
1019 std::map<std::string, unsigned> GCMap;
1020 unsigned MaxAlignment = 0;
1021 unsigned MaxGlobalType = 0;
1022 for (const GlobalValue &GV : M.globals()) {
1023 MaxAlignment = std::max(MaxAlignment, GV.getAlignment());
1024 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
1025 if (GV.hasSection()) {
1026 // Give section names unique ID's.
1027 unsigned &Entry = SectionMap[GV.getSection()];
1029 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
1031 Entry = SectionMap.size();
1035 for (const Function &F : M) {
1036 MaxAlignment = std::max(MaxAlignment, F.getAlignment());
1037 if (F.hasSection()) {
1038 // Give section names unique ID's.
1039 unsigned &Entry = SectionMap[F.getSection()];
1041 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
1043 Entry = SectionMap.size();
1047 // Same for GC names.
1048 unsigned &Entry = GCMap[F.getGC()];
1050 writeStringRecord(Stream, bitc::MODULE_CODE_GCNAME, F.getGC(),
1052 Entry = GCMap.size();
1057 // Emit abbrev for globals, now that we know # sections and max alignment.
1058 unsigned SimpleGVarAbbrev = 0;
1059 if (!M.global_empty()) {
1060 // Add an abbrev for common globals with no visibility or thread localness.
1061 auto Abbv = std::make_shared<BitCodeAbbrev>();
1062 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
1063 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1064 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1065 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1066 Log2_32_Ceil(MaxGlobalType+1)));
1067 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2
1068 //| explicitType << 1
1070 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
1071 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
1072 if (MaxAlignment == 0) // Alignment.
1073 Abbv->Add(BitCodeAbbrevOp(0));
1075 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
1076 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1077 Log2_32_Ceil(MaxEncAlignment+1)));
1079 if (SectionMap.empty()) // Section.
1080 Abbv->Add(BitCodeAbbrevOp(0));
1082 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1083 Log2_32_Ceil(SectionMap.size()+1)));
1084 // Don't bother emitting vis + thread local.
1085 SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1088 SmallVector<unsigned, 64> Vals;
1089 // Emit the module's source file name.
1091 StringEncoding Bits = getStringEncoding(M.getSourceFileName());
1092 BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
1093 if (Bits == SE_Char6)
1094 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
1095 else if (Bits == SE_Fixed7)
1096 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
1098 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
1099 auto Abbv = std::make_shared<BitCodeAbbrev>();
1100 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
1101 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1102 Abbv->Add(AbbrevOpToUse);
1103 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1105 for (const auto P : M.getSourceFileName())
1106 Vals.push_back((unsigned char)P);
1108 // Emit the finished record.
1109 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
1113 // Emit the global variable information.
1114 for (const GlobalVariable &GV : M.globals()) {
1115 unsigned AbbrevToUse = 0;
1117 // GLOBALVAR: [strtab offset, strtab size, type, isconst, initid,
1118 // linkage, alignment, section, visibility, threadlocal,
1119 // unnamed_addr, externally_initialized, dllstorageclass,
1120 // comdat, attributes]
1121 Vals.push_back(StrtabBuilder.add(GV.getName()));
1122 Vals.push_back(GV.getName().size());
1123 Vals.push_back(VE.getTypeID(GV.getValueType()));
1124 Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
1125 Vals.push_back(GV.isDeclaration() ? 0 :
1126 (VE.getValueID(GV.getInitializer()) + 1));
1127 Vals.push_back(getEncodedLinkage(GV));
1128 Vals.push_back(Log2_32(GV.getAlignment())+1);
1129 Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0);
1130 if (GV.isThreadLocal() ||
1131 GV.getVisibility() != GlobalValue::DefaultVisibility ||
1132 GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1133 GV.isExternallyInitialized() ||
1134 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
1136 GV.hasAttributes()) {
1137 Vals.push_back(getEncodedVisibility(GV));
1138 Vals.push_back(getEncodedThreadLocalMode(GV));
1139 Vals.push_back(getEncodedUnnamedAddr(GV));
1140 Vals.push_back(GV.isExternallyInitialized());
1141 Vals.push_back(getEncodedDLLStorageClass(GV));
1142 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
1144 auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
1145 Vals.push_back(VE.getAttributeListID(AL));
1147 AbbrevToUse = SimpleGVarAbbrev;
1150 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
1154 // Emit the function proto information.
1155 for (const Function &F : M) {
1156 // FUNCTION: [strtab offset, strtab size, type, callingconv, isproto,
1157 // linkage, paramattrs, alignment, section, visibility, gc,
1158 // unnamed_addr, prologuedata, dllstorageclass, comdat,
1159 // prefixdata, personalityfn]
1160 Vals.push_back(StrtabBuilder.add(F.getName()));
1161 Vals.push_back(F.getName().size());
1162 Vals.push_back(VE.getTypeID(F.getFunctionType()));
1163 Vals.push_back(F.getCallingConv());
1164 Vals.push_back(F.isDeclaration());
1165 Vals.push_back(getEncodedLinkage(F));
1166 Vals.push_back(VE.getAttributeListID(F.getAttributes()));
1167 Vals.push_back(Log2_32(F.getAlignment())+1);
1168 Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0);
1169 Vals.push_back(getEncodedVisibility(F));
1170 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
1171 Vals.push_back(getEncodedUnnamedAddr(F));
1172 Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
1174 Vals.push_back(getEncodedDLLStorageClass(F));
1175 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
1176 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
1179 F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
1181 unsigned AbbrevToUse = 0;
1182 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
1186 // Emit the alias information.
1187 for (const GlobalAlias &A : M.aliases()) {
1188 // ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage,
1189 // visibility, dllstorageclass, threadlocal, unnamed_addr]
1190 Vals.push_back(StrtabBuilder.add(A.getName()));
1191 Vals.push_back(A.getName().size());
1192 Vals.push_back(VE.getTypeID(A.getValueType()));
1193 Vals.push_back(A.getType()->getAddressSpace());
1194 Vals.push_back(VE.getValueID(A.getAliasee()));
1195 Vals.push_back(getEncodedLinkage(A));
1196 Vals.push_back(getEncodedVisibility(A));
1197 Vals.push_back(getEncodedDLLStorageClass(A));
1198 Vals.push_back(getEncodedThreadLocalMode(A));
1199 Vals.push_back(getEncodedUnnamedAddr(A));
1200 unsigned AbbrevToUse = 0;
1201 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
1205 // Emit the ifunc information.
1206 for (const GlobalIFunc &I : M.ifuncs()) {
1207 // IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver
1208 // val#, linkage, visibility]
1209 Vals.push_back(StrtabBuilder.add(I.getName()));
1210 Vals.push_back(I.getName().size());
1211 Vals.push_back(VE.getTypeID(I.getValueType()));
1212 Vals.push_back(I.getType()->getAddressSpace());
1213 Vals.push_back(VE.getValueID(I.getResolver()));
1214 Vals.push_back(getEncodedLinkage(I));
1215 Vals.push_back(getEncodedVisibility(I));
1216 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
1220 writeValueSymbolTableForwardDecl();
1223 static uint64_t getOptimizationFlags(const Value *V) {
1226 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
1227 if (OBO->hasNoSignedWrap())
1228 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
1229 if (OBO->hasNoUnsignedWrap())
1230 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
1231 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
1233 Flags |= 1 << bitc::PEO_EXACT;
1234 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
1235 if (FPMO->hasUnsafeAlgebra())
1236 Flags |= FastMathFlags::UnsafeAlgebra;
1237 if (FPMO->hasNoNaNs())
1238 Flags |= FastMathFlags::NoNaNs;
1239 if (FPMO->hasNoInfs())
1240 Flags |= FastMathFlags::NoInfs;
1241 if (FPMO->hasNoSignedZeros())
1242 Flags |= FastMathFlags::NoSignedZeros;
1243 if (FPMO->hasAllowReciprocal())
1244 Flags |= FastMathFlags::AllowReciprocal;
1245 if (FPMO->hasAllowContract())
1246 Flags |= FastMathFlags::AllowContract;
1252 void ModuleBitcodeWriter::writeValueAsMetadata(
1253 const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
1254 // Mimic an MDNode with a value as one operand.
1255 Value *V = MD->getValue();
1256 Record.push_back(VE.getTypeID(V->getType()));
1257 Record.push_back(VE.getValueID(V));
1258 Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
1262 void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N,
1263 SmallVectorImpl<uint64_t> &Record,
1265 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1266 Metadata *MD = N->getOperand(i);
1267 assert(!(MD && isa<LocalAsMetadata>(MD)) &&
1268 "Unexpected function-local metadata");
1269 Record.push_back(VE.getMetadataOrNullID(MD));
1271 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
1272 : bitc::METADATA_NODE,
1277 unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
1278 // Assume the column is usually under 128, and always output the inlined-at
1279 // location (it's never more expensive than building an array size 1).
1280 auto Abbv = std::make_shared<BitCodeAbbrev>();
1281 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
1282 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1283 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1284 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1285 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1286 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1287 return Stream.EmitAbbrev(std::move(Abbv));
1290 void ModuleBitcodeWriter::writeDILocation(const DILocation *N,
1291 SmallVectorImpl<uint64_t> &Record,
1294 Abbrev = createDILocationAbbrev();
1296 Record.push_back(N->isDistinct());
1297 Record.push_back(N->getLine());
1298 Record.push_back(N->getColumn());
1299 Record.push_back(VE.getMetadataID(N->getScope()));
1300 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
1302 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
1306 unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
1307 // Assume the column is usually under 128, and always output the inlined-at
1308 // location (it's never more expensive than building an array size 1).
1309 auto Abbv = std::make_shared<BitCodeAbbrev>();
1310 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
1311 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1312 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1313 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1314 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1315 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1316 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1317 return Stream.EmitAbbrev(std::move(Abbv));
1320 void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N,
1321 SmallVectorImpl<uint64_t> &Record,
1324 Abbrev = createGenericDINodeAbbrev();
1326 Record.push_back(N->isDistinct());
1327 Record.push_back(N->getTag());
1328 Record.push_back(0); // Per-tag version field; unused for now.
1330 for (auto &I : N->operands())
1331 Record.push_back(VE.getMetadataOrNullID(I));
1333 Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
1337 static uint64_t rotateSign(int64_t I) {
1339 return I < 0 ? ~(U << 1) : U << 1;
1342 void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N,
1343 SmallVectorImpl<uint64_t> &Record,
1345 Record.push_back(N->isDistinct());
1346 Record.push_back(N->getCount());
1347 Record.push_back(rotateSign(N->getLowerBound()));
1349 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
1353 void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,
1354 SmallVectorImpl<uint64_t> &Record,
1356 Record.push_back(N->isDistinct());
1357 Record.push_back(rotateSign(N->getValue()));
1358 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1360 Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
1364 void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N,
1365 SmallVectorImpl<uint64_t> &Record,
1367 Record.push_back(N->isDistinct());
1368 Record.push_back(N->getTag());
1369 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1370 Record.push_back(N->getSizeInBits());
1371 Record.push_back(N->getAlignInBits());
1372 Record.push_back(N->getEncoding());
1374 Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
1378 void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,
1379 SmallVectorImpl<uint64_t> &Record,
1381 Record.push_back(N->isDistinct());
1382 Record.push_back(N->getTag());
1383 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1384 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1385 Record.push_back(N->getLine());
1386 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1387 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1388 Record.push_back(N->getSizeInBits());
1389 Record.push_back(N->getAlignInBits());
1390 Record.push_back(N->getOffsetInBits());
1391 Record.push_back(N->getFlags());
1392 Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
1394 // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
1395 // that there is no DWARF address space associated with DIDerivedType.
1396 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
1397 Record.push_back(*DWARFAddressSpace + 1);
1399 Record.push_back(0);
1401 Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
1405 void ModuleBitcodeWriter::writeDICompositeType(
1406 const DICompositeType *N, SmallVectorImpl<uint64_t> &Record,
1408 const unsigned IsNotUsedInOldTypeRef = 0x2;
1409 Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct());
1410 Record.push_back(N->getTag());
1411 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1412 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1413 Record.push_back(N->getLine());
1414 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1415 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1416 Record.push_back(N->getSizeInBits());
1417 Record.push_back(N->getAlignInBits());
1418 Record.push_back(N->getOffsetInBits());
1419 Record.push_back(N->getFlags());
1420 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1421 Record.push_back(N->getRuntimeLang());
1422 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
1423 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1424 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
1426 Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
1430 void ModuleBitcodeWriter::writeDISubroutineType(
1431 const DISubroutineType *N, SmallVectorImpl<uint64_t> &Record,
1433 const unsigned HasNoOldTypeRefs = 0x2;
1434 Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
1435 Record.push_back(N->getFlags());
1436 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
1437 Record.push_back(N->getCC());
1439 Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
1443 void ModuleBitcodeWriter::writeDIFile(const DIFile *N,
1444 SmallVectorImpl<uint64_t> &Record,
1446 Record.push_back(N->isDistinct());
1447 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
1448 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
1449 Record.push_back(N->getChecksumKind());
1450 Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()));
1452 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
1456 void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
1457 SmallVectorImpl<uint64_t> &Record,
1459 assert(N->isDistinct() && "Expected distinct compile units");
1460 Record.push_back(/* IsDistinct */ true);
1461 Record.push_back(N->getSourceLanguage());
1462 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1463 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
1464 Record.push_back(N->isOptimized());
1465 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
1466 Record.push_back(N->getRuntimeVersion());
1467 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
1468 Record.push_back(N->getEmissionKind());
1469 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
1470 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
1471 Record.push_back(/* subprograms */ 0);
1472 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
1473 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
1474 Record.push_back(N->getDWOId());
1475 Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
1476 Record.push_back(N->getSplitDebugInlining());
1477 Record.push_back(N->getDebugInfoForProfiling());
1479 Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
1483 void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,
1484 SmallVectorImpl<uint64_t> &Record,
1486 uint64_t HasUnitFlag = 1 << 1;
1487 Record.push_back(N->isDistinct() | HasUnitFlag);
1488 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1489 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1490 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1491 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1492 Record.push_back(N->getLine());
1493 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1494 Record.push_back(N->isLocalToUnit());
1495 Record.push_back(N->isDefinition());
1496 Record.push_back(N->getScopeLine());
1497 Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
1498 Record.push_back(N->getVirtuality());
1499 Record.push_back(N->getVirtualIndex());
1500 Record.push_back(N->getFlags());
1501 Record.push_back(N->isOptimized());
1502 Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
1503 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1504 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
1505 Record.push_back(VE.getMetadataOrNullID(N->getVariables().get()));
1506 Record.push_back(N->getThisAdjustment());
1507 Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get()));
1509 Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
1513 void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
1514 SmallVectorImpl<uint64_t> &Record,
1516 Record.push_back(N->isDistinct());
1517 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1518 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1519 Record.push_back(N->getLine());
1520 Record.push_back(N->getColumn());
1522 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
1526 void ModuleBitcodeWriter::writeDILexicalBlockFile(
1527 const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record,
1529 Record.push_back(N->isDistinct());
1530 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1531 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1532 Record.push_back(N->getDiscriminator());
1534 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
1538 void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,
1539 SmallVectorImpl<uint64_t> &Record,
1541 Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
1542 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1543 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1545 Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
1549 void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,
1550 SmallVectorImpl<uint64_t> &Record,
1552 Record.push_back(N->isDistinct());
1553 Record.push_back(N->getMacinfoType());
1554 Record.push_back(N->getLine());
1555 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1556 Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
1558 Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
1562 void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,
1563 SmallVectorImpl<uint64_t> &Record,
1565 Record.push_back(N->isDistinct());
1566 Record.push_back(N->getMacinfoType());
1567 Record.push_back(N->getLine());
1568 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1569 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1571 Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
1575 void ModuleBitcodeWriter::writeDIModule(const DIModule *N,
1576 SmallVectorImpl<uint64_t> &Record,
1578 Record.push_back(N->isDistinct());
1579 for (auto &I : N->operands())
1580 Record.push_back(VE.getMetadataOrNullID(I));
1582 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
1586 void ModuleBitcodeWriter::writeDITemplateTypeParameter(
1587 const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record,
1589 Record.push_back(N->isDistinct());
1590 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1591 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1593 Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
1597 void ModuleBitcodeWriter::writeDITemplateValueParameter(
1598 const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record,
1600 Record.push_back(N->isDistinct());
1601 Record.push_back(N->getTag());
1602 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1603 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1604 Record.push_back(VE.getMetadataOrNullID(N->getValue()));
1606 Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
1610 void ModuleBitcodeWriter::writeDIGlobalVariable(
1611 const DIGlobalVariable *N, SmallVectorImpl<uint64_t> &Record,
1613 const uint64_t Version = 1 << 1;
1614 Record.push_back((uint64_t)N->isDistinct() | Version);
1615 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1616 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1617 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1618 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1619 Record.push_back(N->getLine());
1620 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1621 Record.push_back(N->isLocalToUnit());
1622 Record.push_back(N->isDefinition());
1623 Record.push_back(/* expr */ 0);
1624 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
1625 Record.push_back(N->getAlignInBits());
1627 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
1631 void ModuleBitcodeWriter::writeDILocalVariable(
1632 const DILocalVariable *N, SmallVectorImpl<uint64_t> &Record,
1634 // In order to support all possible bitcode formats in BitcodeReader we need
1635 // to distinguish the following cases:
1636 // 1) Record has no artificial tag (Record[1]),
1637 // has no obsolete inlinedAt field (Record[9]).
1638 // In this case Record size will be 8, HasAlignment flag is false.
1639 // 2) Record has artificial tag (Record[1]),
1640 // has no obsolete inlignedAt field (Record[9]).
1641 // In this case Record size will be 9, HasAlignment flag is false.
1642 // 3) Record has both artificial tag (Record[1]) and
1643 // obsolete inlignedAt field (Record[9]).
1644 // In this case Record size will be 10, HasAlignment flag is false.
1645 // 4) Record has neither artificial tag, nor inlignedAt field, but
1646 // HasAlignment flag is true and Record[8] contains alignment value.
1647 const uint64_t HasAlignmentFlag = 1 << 1;
1648 Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
1649 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1650 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1651 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1652 Record.push_back(N->getLine());
1653 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1654 Record.push_back(N->getArg());
1655 Record.push_back(N->getFlags());
1656 Record.push_back(N->getAlignInBits());
1658 Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
1662 void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,
1663 SmallVectorImpl<uint64_t> &Record,
1665 Record.reserve(N->getElements().size() + 1);
1666 const uint64_t Version = 2 << 1;
1667 Record.push_back((uint64_t)N->isDistinct() | Version);
1668 Record.append(N->elements_begin(), N->elements_end());
1670 Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
1674 void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
1675 const DIGlobalVariableExpression *N, SmallVectorImpl<uint64_t> &Record,
1677 Record.push_back(N->isDistinct());
1678 Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
1679 Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
1681 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR, Record, Abbrev);
1685 void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
1686 SmallVectorImpl<uint64_t> &Record,
1688 Record.push_back(N->isDistinct());
1689 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1690 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1691 Record.push_back(N->getLine());
1692 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
1693 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
1694 Record.push_back(N->getAttributes());
1695 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1697 Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
1701 void ModuleBitcodeWriter::writeDIImportedEntity(
1702 const DIImportedEntity *N, SmallVectorImpl<uint64_t> &Record,
1704 Record.push_back(N->isDistinct());
1705 Record.push_back(N->getTag());
1706 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1707 Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
1708 Record.push_back(N->getLine());
1709 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1711 Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
1715 unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
1716 auto Abbv = std::make_shared<BitCodeAbbrev>();
1717 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
1718 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1719 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1720 return Stream.EmitAbbrev(std::move(Abbv));
1723 void ModuleBitcodeWriter::writeNamedMetadata(
1724 SmallVectorImpl<uint64_t> &Record) {
1725 if (M.named_metadata_empty())
1728 unsigned Abbrev = createNamedMetadataAbbrev();
1729 for (const NamedMDNode &NMD : M.named_metadata()) {
1731 StringRef Str = NMD.getName();
1732 Record.append(Str.bytes_begin(), Str.bytes_end());
1733 Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
1736 // Write named metadata operands.
1737 for (const MDNode *N : NMD.operands())
1738 Record.push_back(VE.getMetadataID(N));
1739 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
1744 unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
1745 auto Abbv = std::make_shared<BitCodeAbbrev>();
1746 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS));
1747 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
1748 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
1749 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1750 return Stream.EmitAbbrev(std::move(Abbv));
1753 /// Write out a record for MDString.
1755 /// All the metadata strings in a metadata block are emitted in a single
1756 /// record. The sizes and strings themselves are shoved into a blob.
1757 void ModuleBitcodeWriter::writeMetadataStrings(
1758 ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) {
1759 if (Strings.empty())
1762 // Start the record with the number of strings.
1763 Record.push_back(bitc::METADATA_STRINGS);
1764 Record.push_back(Strings.size());
1766 // Emit the sizes of the strings in the blob.
1767 SmallString<256> Blob;
1769 BitstreamWriter W(Blob);
1770 for (const Metadata *MD : Strings)
1771 W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
1775 // Add the offset to the strings to the record.
1776 Record.push_back(Blob.size());
1778 // Add the strings to the blob.
1779 for (const Metadata *MD : Strings)
1780 Blob.append(cast<MDString>(MD)->getString());
1782 // Emit the final record.
1783 Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
1787 // Generates an enum to use as an index in the Abbrev array of Metadata record.
1788 enum MetadataAbbrev : unsigned {
1789 #define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
1790 #include "llvm/IR/Metadata.def"
1794 void ModuleBitcodeWriter::writeMetadataRecords(
1795 ArrayRef<const Metadata *> MDs, SmallVectorImpl<uint64_t> &Record,
1796 std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
1800 // Initialize MDNode abbreviations.
1801 #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
1802 #include "llvm/IR/Metadata.def"
1804 for (const Metadata *MD : MDs) {
1806 IndexPos->push_back(Stream.GetCurrentBitNo());
1807 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
1808 assert(N->isResolved() && "Expected forward references to be resolved");
1810 switch (N->getMetadataID()) {
1812 llvm_unreachable("Invalid MDNode subclass");
1813 #define HANDLE_MDNODE_LEAF(CLASS) \
1814 case Metadata::CLASS##Kind: \
1816 write##CLASS(cast<CLASS>(N), Record, \
1817 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
1819 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
1821 #include "llvm/IR/Metadata.def"
1824 writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
1828 void ModuleBitcodeWriter::writeModuleMetadata() {
1829 if (!VE.hasMDs() && M.named_metadata_empty())
1832 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 4);
1833 SmallVector<uint64_t, 64> Record;
1835 // Emit all abbrevs upfront, so that the reader can jump in the middle of the
1836 // block and load any metadata.
1837 std::vector<unsigned> MDAbbrevs;
1839 MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
1840 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
1841 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
1842 createGenericDINodeAbbrev();
1844 auto Abbv = std::make_shared<BitCodeAbbrev>();
1845 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX_OFFSET));
1846 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1847 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1848 unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1850 Abbv = std::make_shared<BitCodeAbbrev>();
1851 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX));
1852 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1853 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1854 unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1856 // Emit MDStrings together upfront.
1857 writeMetadataStrings(VE.getMDStrings(), Record);
1859 // We only emit an index for the metadata record if we have more than a given
1860 // (naive) threshold of metadatas, otherwise it is not worth it.
1861 if (VE.getNonMDStrings().size() > IndexThreshold) {
1862 // Write a placeholder value in for the offset of the metadata index,
1863 // which is written after the records, so that it can include
1864 // the offset of each entry. The placeholder offset will be
1865 // updated after all records are emitted.
1866 uint64_t Vals[] = {0, 0};
1867 Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
1870 // Compute and save the bit offset to the current position, which will be
1871 // patched when we emit the index later. We can simply subtract the 64-bit
1872 // fixed size from the current bit number to get the location to backpatch.
1873 uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
1875 // This index will contain the bitpos for each individual record.
1876 std::vector<uint64_t> IndexPos;
1877 IndexPos.reserve(VE.getNonMDStrings().size());
1879 // Write all the records
1880 writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
1882 if (VE.getNonMDStrings().size() > IndexThreshold) {
1883 // Now that we have emitted all the records we will emit the index. But
1885 // backpatch the forward reference so that the reader can skip the records
1887 Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
1888 Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
1890 // Delta encode the index.
1891 uint64_t PreviousValue = IndexOffsetRecordBitPos;
1892 for (auto &Elt : IndexPos) {
1893 auto EltDelta = Elt - PreviousValue;
1894 PreviousValue = Elt;
1897 // Emit the index record.
1898 Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
1902 // Write the named metadata now.
1903 writeNamedMetadata(Record);
1905 auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
1906 SmallVector<uint64_t, 4> Record;
1907 Record.push_back(VE.getValueID(&GO));
1908 pushGlobalMetadataAttachment(Record, GO);
1909 Stream.EmitRecord(bitc::METADATA_GLOBAL_DECL_ATTACHMENT, Record);
1911 for (const Function &F : M)
1912 if (F.isDeclaration() && F.hasMetadata())
1913 AddDeclAttachedMetadata(F);
1914 // FIXME: Only store metadata for declarations here, and move data for global
1915 // variable definitions to a separate block (PR28134).
1916 for (const GlobalVariable &GV : M.globals())
1917 if (GV.hasMetadata())
1918 AddDeclAttachedMetadata(GV);
1923 void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
1927 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
1928 SmallVector<uint64_t, 64> Record;
1929 writeMetadataStrings(VE.getMDStrings(), Record);
1930 writeMetadataRecords(VE.getNonMDStrings(), Record);
1934 void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
1935 SmallVectorImpl<uint64_t> &Record, const GlobalObject &GO) {
1936 // [n x [id, mdnode]]
1937 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1938 GO.getAllMetadata(MDs);
1939 for (const auto &I : MDs) {
1940 Record.push_back(I.first);
1941 Record.push_back(VE.getMetadataID(I.second));
1945 void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
1946 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
1948 SmallVector<uint64_t, 64> Record;
1950 if (F.hasMetadata()) {
1951 pushGlobalMetadataAttachment(Record, F);
1952 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
1956 // Write metadata attachments
1957 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
1958 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1959 for (const BasicBlock &BB : F)
1960 for (const Instruction &I : BB) {
1962 I.getAllMetadataOtherThanDebugLoc(MDs);
1964 // If no metadata, ignore instruction.
1965 if (MDs.empty()) continue;
1967 Record.push_back(VE.getInstructionID(&I));
1969 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
1970 Record.push_back(MDs[i].first);
1971 Record.push_back(VE.getMetadataID(MDs[i].second));
1973 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
1980 void ModuleBitcodeWriter::writeModuleMetadataKinds() {
1981 SmallVector<uint64_t, 64> Record;
1983 // Write metadata kinds
1984 // METADATA_KIND - [n x [id, name]]
1985 SmallVector<StringRef, 8> Names;
1986 M.getMDKindNames(Names);
1988 if (Names.empty()) return;
1990 Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3);
1992 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
1993 Record.push_back(MDKindID);
1994 StringRef KName = Names[MDKindID];
1995 Record.append(KName.begin(), KName.end());
1997 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
2004 void ModuleBitcodeWriter::writeOperandBundleTags() {
2005 // Write metadata kinds
2007 // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
2009 // OPERAND_BUNDLE_TAG - [strchr x N]
2011 SmallVector<StringRef, 8> Tags;
2012 M.getOperandBundleTags(Tags);
2017 Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3);
2019 SmallVector<uint64_t, 64> Record;
2021 for (auto Tag : Tags) {
2022 Record.append(Tag.begin(), Tag.end());
2024 Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
2031 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
2032 if ((int64_t)V >= 0)
2033 Vals.push_back(V << 1);
2035 Vals.push_back((-V << 1) | 1);
2038 void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
2040 if (FirstVal == LastVal) return;
2042 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
2044 unsigned AggregateAbbrev = 0;
2045 unsigned String8Abbrev = 0;
2046 unsigned CString7Abbrev = 0;
2047 unsigned CString6Abbrev = 0;
2048 // If this is a constant pool for the module, emit module-specific abbrevs.
2050 // Abbrev for CST_CODE_AGGREGATE.
2051 auto Abbv = std::make_shared<BitCodeAbbrev>();
2052 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
2053 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2054 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
2055 AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2057 // Abbrev for CST_CODE_STRING.
2058 Abbv = std::make_shared<BitCodeAbbrev>();
2059 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
2060 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2061 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2062 String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2063 // Abbrev for CST_CODE_CSTRING.
2064 Abbv = std::make_shared<BitCodeAbbrev>();
2065 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2066 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2067 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2068 CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2069 // Abbrev for CST_CODE_CSTRING.
2070 Abbv = std::make_shared<BitCodeAbbrev>();
2071 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2072 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2073 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2074 CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2077 SmallVector<uint64_t, 64> Record;
2079 const ValueEnumerator::ValueList &Vals = VE.getValues();
2080 Type *LastTy = nullptr;
2081 for (unsigned i = FirstVal; i != LastVal; ++i) {
2082 const Value *V = Vals[i].first;
2083 // If we need to switch types, do so now.
2084 if (V->getType() != LastTy) {
2085 LastTy = V->getType();
2086 Record.push_back(VE.getTypeID(LastTy));
2087 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
2088 CONSTANTS_SETTYPE_ABBREV);
2092 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
2093 Record.push_back(unsigned(IA->hasSideEffects()) |
2094 unsigned(IA->isAlignStack()) << 1 |
2095 unsigned(IA->getDialect()&1) << 2);
2097 // Add the asm string.
2098 const std::string &AsmStr = IA->getAsmString();
2099 Record.push_back(AsmStr.size());
2100 Record.append(AsmStr.begin(), AsmStr.end());
2102 // Add the constraint string.
2103 const std::string &ConstraintStr = IA->getConstraintString();
2104 Record.push_back(ConstraintStr.size());
2105 Record.append(ConstraintStr.begin(), ConstraintStr.end());
2106 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
2110 const Constant *C = cast<Constant>(V);
2111 unsigned Code = -1U;
2112 unsigned AbbrevToUse = 0;
2113 if (C->isNullValue()) {
2114 Code = bitc::CST_CODE_NULL;
2115 } else if (isa<UndefValue>(C)) {
2116 Code = bitc::CST_CODE_UNDEF;
2117 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
2118 if (IV->getBitWidth() <= 64) {
2119 uint64_t V = IV->getSExtValue();
2120 emitSignedInt64(Record, V);
2121 Code = bitc::CST_CODE_INTEGER;
2122 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
2123 } else { // Wide integers, > 64 bits in size.
2124 // We have an arbitrary precision integer value to write whose
2125 // bit width is > 64. However, in canonical unsigned integer
2126 // format it is likely that the high bits are going to be zero.
2127 // So, we only write the number of active words.
2128 unsigned NWords = IV->getValue().getActiveWords();
2129 const uint64_t *RawWords = IV->getValue().getRawData();
2130 for (unsigned i = 0; i != NWords; ++i) {
2131 emitSignedInt64(Record, RawWords[i]);
2133 Code = bitc::CST_CODE_WIDE_INTEGER;
2135 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
2136 Code = bitc::CST_CODE_FLOAT;
2137 Type *Ty = CFP->getType();
2138 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
2139 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
2140 } else if (Ty->isX86_FP80Ty()) {
2141 // api needed to prevent premature destruction
2142 // bits are not in the same order as a normal i80 APInt, compensate.
2143 APInt api = CFP->getValueAPF().bitcastToAPInt();
2144 const uint64_t *p = api.getRawData();
2145 Record.push_back((p[1] << 48) | (p[0] >> 16));
2146 Record.push_back(p[0] & 0xffffLL);
2147 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
2148 APInt api = CFP->getValueAPF().bitcastToAPInt();
2149 const uint64_t *p = api.getRawData();
2150 Record.push_back(p[0]);
2151 Record.push_back(p[1]);
2153 assert (0 && "Unknown FP type!");
2155 } else if (isa<ConstantDataSequential>(C) &&
2156 cast<ConstantDataSequential>(C)->isString()) {
2157 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
2158 // Emit constant strings specially.
2159 unsigned NumElts = Str->getNumElements();
2160 // If this is a null-terminated string, use the denser CSTRING encoding.
2161 if (Str->isCString()) {
2162 Code = bitc::CST_CODE_CSTRING;
2163 --NumElts; // Don't encode the null, which isn't allowed by char6.
2165 Code = bitc::CST_CODE_STRING;
2166 AbbrevToUse = String8Abbrev;
2168 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
2169 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
2170 for (unsigned i = 0; i != NumElts; ++i) {
2171 unsigned char V = Str->getElementAsInteger(i);
2172 Record.push_back(V);
2173 isCStr7 &= (V & 128) == 0;
2175 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
2179 AbbrevToUse = CString6Abbrev;
2181 AbbrevToUse = CString7Abbrev;
2182 } else if (const ConstantDataSequential *CDS =
2183 dyn_cast<ConstantDataSequential>(C)) {
2184 Code = bitc::CST_CODE_DATA;
2185 Type *EltTy = CDS->getType()->getElementType();
2186 if (isa<IntegerType>(EltTy)) {
2187 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2188 Record.push_back(CDS->getElementAsInteger(i));
2190 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2192 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
2194 } else if (isa<ConstantAggregate>(C)) {
2195 Code = bitc::CST_CODE_AGGREGATE;
2196 for (const Value *Op : C->operands())
2197 Record.push_back(VE.getValueID(Op));
2198 AbbrevToUse = AggregateAbbrev;
2199 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2200 switch (CE->getOpcode()) {
2202 if (Instruction::isCast(CE->getOpcode())) {
2203 Code = bitc::CST_CODE_CE_CAST;
2204 Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
2205 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2206 Record.push_back(VE.getValueID(C->getOperand(0)));
2207 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
2209 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
2210 Code = bitc::CST_CODE_CE_BINOP;
2211 Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
2212 Record.push_back(VE.getValueID(C->getOperand(0)));
2213 Record.push_back(VE.getValueID(C->getOperand(1)));
2214 uint64_t Flags = getOptimizationFlags(CE);
2216 Record.push_back(Flags);
2219 case Instruction::GetElementPtr: {
2220 Code = bitc::CST_CODE_CE_GEP;
2221 const auto *GO = cast<GEPOperator>(C);
2222 Record.push_back(VE.getTypeID(GO->getSourceElementType()));
2223 if (Optional<unsigned> Idx = GO->getInRangeIndex()) {
2224 Code = bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX;
2225 Record.push_back((*Idx << 1) | GO->isInBounds());
2226 } else if (GO->isInBounds())
2227 Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
2228 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
2229 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
2230 Record.push_back(VE.getValueID(C->getOperand(i)));
2234 case Instruction::Select:
2235 Code = bitc::CST_CODE_CE_SELECT;
2236 Record.push_back(VE.getValueID(C->getOperand(0)));
2237 Record.push_back(VE.getValueID(C->getOperand(1)));
2238 Record.push_back(VE.getValueID(C->getOperand(2)));
2240 case Instruction::ExtractElement:
2241 Code = bitc::CST_CODE_CE_EXTRACTELT;
2242 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2243 Record.push_back(VE.getValueID(C->getOperand(0)));
2244 Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
2245 Record.push_back(VE.getValueID(C->getOperand(1)));
2247 case Instruction::InsertElement:
2248 Code = bitc::CST_CODE_CE_INSERTELT;
2249 Record.push_back(VE.getValueID(C->getOperand(0)));
2250 Record.push_back(VE.getValueID(C->getOperand(1)));
2251 Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
2252 Record.push_back(VE.getValueID(C->getOperand(2)));
2254 case Instruction::ShuffleVector:
2255 // If the return type and argument types are the same, this is a
2256 // standard shufflevector instruction. If the types are different,
2257 // then the shuffle is widening or truncating the input vectors, and
2258 // the argument type must also be encoded.
2259 if (C->getType() == C->getOperand(0)->getType()) {
2260 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
2262 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
2263 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2265 Record.push_back(VE.getValueID(C->getOperand(0)));
2266 Record.push_back(VE.getValueID(C->getOperand(1)));
2267 Record.push_back(VE.getValueID(C->getOperand(2)));
2269 case Instruction::ICmp:
2270 case Instruction::FCmp:
2271 Code = bitc::CST_CODE_CE_CMP;
2272 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2273 Record.push_back(VE.getValueID(C->getOperand(0)));
2274 Record.push_back(VE.getValueID(C->getOperand(1)));
2275 Record.push_back(CE->getPredicate());
2278 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
2279 Code = bitc::CST_CODE_BLOCKADDRESS;
2280 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
2281 Record.push_back(VE.getValueID(BA->getFunction()));
2282 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
2287 llvm_unreachable("Unknown constant!");
2289 Stream.EmitRecord(Code, Record, AbbrevToUse);
2296 void ModuleBitcodeWriter::writeModuleConstants() {
2297 const ValueEnumerator::ValueList &Vals = VE.getValues();
2299 // Find the first constant to emit, which is the first non-globalvalue value.
2300 // We know globalvalues have been emitted by WriteModuleInfo.
2301 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
2302 if (!isa<GlobalValue>(Vals[i].first)) {
2303 writeConstants(i, Vals.size(), true);
2309 /// pushValueAndType - The file has to encode both the value and type id for
2310 /// many values, because we need to know what type to create for forward
2311 /// references. However, most operands are not forward references, so this type
2312 /// field is not needed.
2314 /// This function adds V's value ID to Vals. If the value ID is higher than the
2315 /// instruction ID, then it is a forward reference, and it also includes the
2316 /// type ID. The value ID that is written is encoded relative to the InstID.
2317 bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
2318 SmallVectorImpl<unsigned> &Vals) {
2319 unsigned ValID = VE.getValueID(V);
2320 // Make encoding relative to the InstID.
2321 Vals.push_back(InstID - ValID);
2322 if (ValID >= InstID) {
2323 Vals.push_back(VE.getTypeID(V->getType()));
2329 void ModuleBitcodeWriter::writeOperandBundles(ImmutableCallSite CS,
2331 SmallVector<unsigned, 64> Record;
2332 LLVMContext &C = CS.getInstruction()->getContext();
2334 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
2335 const auto &Bundle = CS.getOperandBundleAt(i);
2336 Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
2338 for (auto &Input : Bundle.Inputs)
2339 pushValueAndType(Input, InstID, Record);
2341 Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record);
2346 /// pushValue - Like pushValueAndType, but where the type of the value is
2347 /// omitted (perhaps it was already encoded in an earlier operand).
2348 void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
2349 SmallVectorImpl<unsigned> &Vals) {
2350 unsigned ValID = VE.getValueID(V);
2351 Vals.push_back(InstID - ValID);
2354 void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
2355 SmallVectorImpl<uint64_t> &Vals) {
2356 unsigned ValID = VE.getValueID(V);
2357 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
2358 emitSignedInt64(Vals, diff);
2361 /// WriteInstruction - Emit an instruction to the specified stream.
2362 void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
2364 SmallVectorImpl<unsigned> &Vals) {
2366 unsigned AbbrevToUse = 0;
2367 VE.setInstructionID(&I);
2368 switch (I.getOpcode()) {
2370 if (Instruction::isCast(I.getOpcode())) {
2371 Code = bitc::FUNC_CODE_INST_CAST;
2372 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2373 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
2374 Vals.push_back(VE.getTypeID(I.getType()));
2375 Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
2377 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
2378 Code = bitc::FUNC_CODE_INST_BINOP;
2379 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2380 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
2381 pushValue(I.getOperand(1), InstID, Vals);
2382 Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
2383 uint64_t Flags = getOptimizationFlags(&I);
2385 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
2386 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
2387 Vals.push_back(Flags);
2392 case Instruction::GetElementPtr: {
2393 Code = bitc::FUNC_CODE_INST_GEP;
2394 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
2395 auto &GEPInst = cast<GetElementPtrInst>(I);
2396 Vals.push_back(GEPInst.isInBounds());
2397 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
2398 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
2399 pushValueAndType(I.getOperand(i), InstID, Vals);
2402 case Instruction::ExtractValue: {
2403 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
2404 pushValueAndType(I.getOperand(0), InstID, Vals);
2405 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
2406 Vals.append(EVI->idx_begin(), EVI->idx_end());
2409 case Instruction::InsertValue: {
2410 Code = bitc::FUNC_CODE_INST_INSERTVAL;
2411 pushValueAndType(I.getOperand(0), InstID, Vals);
2412 pushValueAndType(I.getOperand(1), InstID, Vals);
2413 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
2414 Vals.append(IVI->idx_begin(), IVI->idx_end());
2417 case Instruction::Select:
2418 Code = bitc::FUNC_CODE_INST_VSELECT;
2419 pushValueAndType(I.getOperand(1), InstID, Vals);
2420 pushValue(I.getOperand(2), InstID, Vals);
2421 pushValueAndType(I.getOperand(0), InstID, Vals);
2423 case Instruction::ExtractElement:
2424 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
2425 pushValueAndType(I.getOperand(0), InstID, Vals);
2426 pushValueAndType(I.getOperand(1), InstID, Vals);
2428 case Instruction::InsertElement:
2429 Code = bitc::FUNC_CODE_INST_INSERTELT;
2430 pushValueAndType(I.getOperand(0), InstID, Vals);
2431 pushValue(I.getOperand(1), InstID, Vals);
2432 pushValueAndType(I.getOperand(2), InstID, Vals);
2434 case Instruction::ShuffleVector:
2435 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
2436 pushValueAndType(I.getOperand(0), InstID, Vals);
2437 pushValue(I.getOperand(1), InstID, Vals);
2438 pushValue(I.getOperand(2), InstID, Vals);
2440 case Instruction::ICmp:
2441 case Instruction::FCmp: {
2442 // compare returning Int1Ty or vector of Int1Ty
2443 Code = bitc::FUNC_CODE_INST_CMP2;
2444 pushValueAndType(I.getOperand(0), InstID, Vals);
2445 pushValue(I.getOperand(1), InstID, Vals);
2446 Vals.push_back(cast<CmpInst>(I).getPredicate());
2447 uint64_t Flags = getOptimizationFlags(&I);
2449 Vals.push_back(Flags);
2453 case Instruction::Ret:
2455 Code = bitc::FUNC_CODE_INST_RET;
2456 unsigned NumOperands = I.getNumOperands();
2457 if (NumOperands == 0)
2458 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
2459 else if (NumOperands == 1) {
2460 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2461 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
2463 for (unsigned i = 0, e = NumOperands; i != e; ++i)
2464 pushValueAndType(I.getOperand(i), InstID, Vals);
2468 case Instruction::Br:
2470 Code = bitc::FUNC_CODE_INST_BR;
2471 const BranchInst &II = cast<BranchInst>(I);
2472 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
2473 if (II.isConditional()) {
2474 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
2475 pushValue(II.getCondition(), InstID, Vals);
2479 case Instruction::Switch:
2481 Code = bitc::FUNC_CODE_INST_SWITCH;
2482 const SwitchInst &SI = cast<SwitchInst>(I);
2483 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
2484 pushValue(SI.getCondition(), InstID, Vals);
2485 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
2486 for (auto Case : SI.cases()) {
2487 Vals.push_back(VE.getValueID(Case.getCaseValue()));
2488 Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
2492 case Instruction::IndirectBr:
2493 Code = bitc::FUNC_CODE_INST_INDIRECTBR;
2494 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
2495 // Encode the address operand as relative, but not the basic blocks.
2496 pushValue(I.getOperand(0), InstID, Vals);
2497 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
2498 Vals.push_back(VE.getValueID(I.getOperand(i)));
2501 case Instruction::Invoke: {
2502 const InvokeInst *II = cast<InvokeInst>(&I);
2503 const Value *Callee = II->getCalledValue();
2504 FunctionType *FTy = II->getFunctionType();
2506 if (II->hasOperandBundles())
2507 writeOperandBundles(II, InstID);
2509 Code = bitc::FUNC_CODE_INST_INVOKE;
2511 Vals.push_back(VE.getAttributeListID(II->getAttributes()));
2512 Vals.push_back(II->getCallingConv() | 1 << 13);
2513 Vals.push_back(VE.getValueID(II->getNormalDest()));
2514 Vals.push_back(VE.getValueID(II->getUnwindDest()));
2515 Vals.push_back(VE.getTypeID(FTy));
2516 pushValueAndType(Callee, InstID, Vals);
2518 // Emit value #'s for the fixed parameters.
2519 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2520 pushValue(I.getOperand(i), InstID, Vals); // fixed param.
2522 // Emit type/value pairs for varargs params.
2523 if (FTy->isVarArg()) {
2524 for (unsigned i = FTy->getNumParams(), e = II->getNumArgOperands();
2526 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
2530 case Instruction::Resume:
2531 Code = bitc::FUNC_CODE_INST_RESUME;
2532 pushValueAndType(I.getOperand(0), InstID, Vals);
2534 case Instruction::CleanupRet: {
2535 Code = bitc::FUNC_CODE_INST_CLEANUPRET;
2536 const auto &CRI = cast<CleanupReturnInst>(I);
2537 pushValue(CRI.getCleanupPad(), InstID, Vals);
2538 if (CRI.hasUnwindDest())
2539 Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
2542 case Instruction::CatchRet: {
2543 Code = bitc::FUNC_CODE_INST_CATCHRET;
2544 const auto &CRI = cast<CatchReturnInst>(I);
2545 pushValue(CRI.getCatchPad(), InstID, Vals);
2546 Vals.push_back(VE.getValueID(CRI.getSuccessor()));
2549 case Instruction::CleanupPad:
2550 case Instruction::CatchPad: {
2551 const auto &FuncletPad = cast<FuncletPadInst>(I);
2552 Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
2553 : bitc::FUNC_CODE_INST_CLEANUPPAD;
2554 pushValue(FuncletPad.getParentPad(), InstID, Vals);
2556 unsigned NumArgOperands = FuncletPad.getNumArgOperands();
2557 Vals.push_back(NumArgOperands);
2558 for (unsigned Op = 0; Op != NumArgOperands; ++Op)
2559 pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
2562 case Instruction::CatchSwitch: {
2563 Code = bitc::FUNC_CODE_INST_CATCHSWITCH;
2564 const auto &CatchSwitch = cast<CatchSwitchInst>(I);
2566 pushValue(CatchSwitch.getParentPad(), InstID, Vals);
2568 unsigned NumHandlers = CatchSwitch.getNumHandlers();
2569 Vals.push_back(NumHandlers);
2570 for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
2571 Vals.push_back(VE.getValueID(CatchPadBB));
2573 if (CatchSwitch.hasUnwindDest())
2574 Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
2577 case Instruction::Unreachable:
2578 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
2579 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
2582 case Instruction::PHI: {
2583 const PHINode &PN = cast<PHINode>(I);
2584 Code = bitc::FUNC_CODE_INST_PHI;
2585 // With the newer instruction encoding, forward references could give
2586 // negative valued IDs. This is most common for PHIs, so we use
2588 SmallVector<uint64_t, 128> Vals64;
2589 Vals64.push_back(VE.getTypeID(PN.getType()));
2590 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
2591 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
2592 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
2594 // Emit a Vals64 vector and exit.
2595 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
2600 case Instruction::LandingPad: {
2601 const LandingPadInst &LP = cast<LandingPadInst>(I);
2602 Code = bitc::FUNC_CODE_INST_LANDINGPAD;
2603 Vals.push_back(VE.getTypeID(LP.getType()));
2604 Vals.push_back(LP.isCleanup());
2605 Vals.push_back(LP.getNumClauses());
2606 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
2608 Vals.push_back(LandingPadInst::Catch);
2610 Vals.push_back(LandingPadInst::Filter);
2611 pushValueAndType(LP.getClause(I), InstID, Vals);
2616 case Instruction::Alloca: {
2617 Code = bitc::FUNC_CODE_INST_ALLOCA;
2618 const AllocaInst &AI = cast<AllocaInst>(I);
2619 Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
2620 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
2621 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
2622 unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
2623 assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
2624 "not enough bits for maximum alignment");
2625 assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
2626 AlignRecord |= AI.isUsedWithInAlloca() << 5;
2627 AlignRecord |= 1 << 6;
2628 AlignRecord |= AI.isSwiftError() << 7;
2629 Vals.push_back(AlignRecord);
2633 case Instruction::Load:
2634 if (cast<LoadInst>(I).isAtomic()) {
2635 Code = bitc::FUNC_CODE_INST_LOADATOMIC;
2636 pushValueAndType(I.getOperand(0), InstID, Vals);
2638 Code = bitc::FUNC_CODE_INST_LOAD;
2639 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
2640 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
2642 Vals.push_back(VE.getTypeID(I.getType()));
2643 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
2644 Vals.push_back(cast<LoadInst>(I).isVolatile());
2645 if (cast<LoadInst>(I).isAtomic()) {
2646 Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
2647 Vals.push_back(getEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
2650 case Instruction::Store:
2651 if (cast<StoreInst>(I).isAtomic())
2652 Code = bitc::FUNC_CODE_INST_STOREATOMIC;
2654 Code = bitc::FUNC_CODE_INST_STORE;
2655 pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr
2656 pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val
2657 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
2658 Vals.push_back(cast<StoreInst>(I).isVolatile());
2659 if (cast<StoreInst>(I).isAtomic()) {
2660 Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
2661 Vals.push_back(getEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
2664 case Instruction::AtomicCmpXchg:
2665 Code = bitc::FUNC_CODE_INST_CMPXCHG;
2666 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2667 pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
2668 pushValue(I.getOperand(2), InstID, Vals); // newval.
2669 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
2671 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
2673 getEncodedSynchScope(cast<AtomicCmpXchgInst>(I).getSynchScope()));
2675 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
2676 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
2678 case Instruction::AtomicRMW:
2679 Code = bitc::FUNC_CODE_INST_ATOMICRMW;
2680 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2681 pushValue(I.getOperand(1), InstID, Vals); // val.
2683 getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
2684 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
2685 Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
2687 getEncodedSynchScope(cast<AtomicRMWInst>(I).getSynchScope()));
2689 case Instruction::Fence:
2690 Code = bitc::FUNC_CODE_INST_FENCE;
2691 Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
2692 Vals.push_back(getEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
2694 case Instruction::Call: {
2695 const CallInst &CI = cast<CallInst>(I);
2696 FunctionType *FTy = CI.getFunctionType();
2698 if (CI.hasOperandBundles())
2699 writeOperandBundles(&CI, InstID);
2701 Code = bitc::FUNC_CODE_INST_CALL;
2703 Vals.push_back(VE.getAttributeListID(CI.getAttributes()));
2705 unsigned Flags = getOptimizationFlags(&I);
2706 Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |
2707 unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
2708 unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
2709 1 << bitc::CALL_EXPLICIT_TYPE |
2710 unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
2711 unsigned(Flags != 0) << bitc::CALL_FMF);
2713 Vals.push_back(Flags);
2715 Vals.push_back(VE.getTypeID(FTy));
2716 pushValueAndType(CI.getCalledValue(), InstID, Vals); // Callee
2718 // Emit value #'s for the fixed parameters.
2719 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
2720 // Check for labels (can happen with asm labels).
2721 if (FTy->getParamType(i)->isLabelTy())
2722 Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
2724 pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
2727 // Emit type/value pairs for varargs params.
2728 if (FTy->isVarArg()) {
2729 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
2731 pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
2735 case Instruction::VAArg:
2736 Code = bitc::FUNC_CODE_INST_VAARG;
2737 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
2738 pushValue(I.getOperand(0), InstID, Vals); // valist.
2739 Vals.push_back(VE.getTypeID(I.getType())); // restype.
2743 Stream.EmitRecord(Code, Vals, AbbrevToUse);
2747 /// Write a GlobalValue VST to the module. The purpose of this data structure is
2748 /// to allow clients to efficiently find the function body.
2749 void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
2750 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
2751 // Get the offset of the VST we are writing, and backpatch it into
2752 // the VST forward declaration record.
2753 uint64_t VSTOffset = Stream.GetCurrentBitNo();
2754 // The BitcodeStartBit was the stream offset of the identification block.
2755 VSTOffset -= bitcodeStartBit();
2756 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
2757 // Note that we add 1 here because the offset is relative to one word
2758 // before the start of the identification block, which was historically
2759 // always the start of the regular bitcode header.
2760 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
2762 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
2764 auto Abbv = std::make_shared<BitCodeAbbrev>();
2765 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2766 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2767 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2768 unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2770 for (const Function &F : M) {
2773 if (F.isDeclaration())
2776 Record[0] = VE.getValueID(&F);
2778 // Save the word offset of the function (from the start of the
2779 // actual bitcode written to the stream).
2780 uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit();
2781 assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
2782 // Note that we add 1 here because the offset is relative to one word
2783 // before the start of the identification block, which was historically
2784 // always the start of the regular bitcode header.
2785 Record[1] = BitcodeIndex / 32 + 1;
2787 Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev);
2793 /// Emit names for arguments, instructions and basic blocks in a function.
2794 void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
2795 const ValueSymbolTable &VST) {
2799 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
2801 // FIXME: Set up the abbrev, we know how many values there are!
2802 // FIXME: We know if the type names can use 7-bit ascii.
2803 SmallVector<uint64_t, 64> NameVals;
2805 for (const ValueName &Name : VST) {
2806 // Figure out the encoding to use for the name.
2807 StringEncoding Bits = getStringEncoding(Name.getKey());
2809 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
2810 NameVals.push_back(VE.getValueID(Name.getValue()));
2812 // VST_CODE_ENTRY: [valueid, namechar x N]
2813 // VST_CODE_BBENTRY: [bbid, namechar x N]
2815 if (isa<BasicBlock>(Name.getValue())) {
2816 Code = bitc::VST_CODE_BBENTRY;
2817 if (Bits == SE_Char6)
2818 AbbrevToUse = VST_BBENTRY_6_ABBREV;
2820 Code = bitc::VST_CODE_ENTRY;
2821 if (Bits == SE_Char6)
2822 AbbrevToUse = VST_ENTRY_6_ABBREV;
2823 else if (Bits == SE_Fixed7)
2824 AbbrevToUse = VST_ENTRY_7_ABBREV;
2827 for (const auto P : Name.getKey())
2828 NameVals.push_back((unsigned char)P);
2830 // Emit the finished record.
2831 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
2838 void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
2839 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
2841 if (isa<BasicBlock>(Order.V))
2842 Code = bitc::USELIST_CODE_BB;
2844 Code = bitc::USELIST_CODE_DEFAULT;
2846 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
2847 Record.push_back(VE.getValueID(Order.V));
2848 Stream.EmitRecord(Code, Record);
2851 void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
2852 assert(VE.shouldPreserveUseListOrder() &&
2853 "Expected to be preserving use-list order");
2855 auto hasMore = [&]() {
2856 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
2862 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
2864 writeUseList(std::move(VE.UseListOrders.back()));
2865 VE.UseListOrders.pop_back();
2870 /// Emit a function body to the module stream.
2871 void ModuleBitcodeWriter::writeFunction(
2873 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
2874 // Save the bitcode index of the start of this function block for recording
2876 FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
2878 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
2879 VE.incorporateFunction(F);
2881 SmallVector<unsigned, 64> Vals;
2883 // Emit the number of basic blocks, so the reader can create them ahead of
2885 Vals.push_back(VE.getBasicBlocks().size());
2886 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
2889 // If there are function-local constants, emit them now.
2890 unsigned CstStart, CstEnd;
2891 VE.getFunctionConstantRange(CstStart, CstEnd);
2892 writeConstants(CstStart, CstEnd, false);
2894 // If there is function-local metadata, emit it now.
2895 writeFunctionMetadata(F);
2897 // Keep a running idea of what the instruction ID is.
2898 unsigned InstID = CstEnd;
2900 bool NeedsMetadataAttachment = F.hasMetadata();
2902 DILocation *LastDL = nullptr;
2903 // Finally, emit all the instructions, in order.
2904 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
2905 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
2907 writeInstruction(*I, InstID, Vals);
2909 if (!I->getType()->isVoidTy())
2912 // If the instruction has metadata, write a metadata attachment later.
2913 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
2915 // If the instruction has a debug location, emit it.
2916 DILocation *DL = I->getDebugLoc();
2921 // Just repeat the same debug loc as last time.
2922 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
2926 Vals.push_back(DL->getLine());
2927 Vals.push_back(DL->getColumn());
2928 Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
2929 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
2930 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
2936 // Emit names for all the instructions etc.
2937 if (auto *Symtab = F.getValueSymbolTable())
2938 writeFunctionLevelValueSymbolTable(*Symtab);
2940 if (NeedsMetadataAttachment)
2941 writeFunctionMetadataAttachment(F);
2942 if (VE.shouldPreserveUseListOrder())
2943 writeUseListBlock(&F);
2948 // Emit blockinfo, which defines the standard abbreviations etc.
2949 void ModuleBitcodeWriter::writeBlockInfo() {
2950 // We only want to emit block info records for blocks that have multiple
2951 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
2952 // Other blocks can define their abbrevs inline.
2953 Stream.EnterBlockInfoBlock();
2955 { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
2956 auto Abbv = std::make_shared<BitCodeAbbrev>();
2957 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
2958 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2959 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2960 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2961 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
2963 llvm_unreachable("Unexpected abbrev ordering!");
2966 { // 7-bit fixed width VST_CODE_ENTRY strings.
2967 auto Abbv = std::make_shared<BitCodeAbbrev>();
2968 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2969 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2970 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2971 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2972 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
2974 llvm_unreachable("Unexpected abbrev ordering!");
2976 { // 6-bit char6 VST_CODE_ENTRY strings.
2977 auto Abbv = std::make_shared<BitCodeAbbrev>();
2978 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2979 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2980 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2981 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2982 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
2984 llvm_unreachable("Unexpected abbrev ordering!");
2986 { // 6-bit char6 VST_CODE_BBENTRY strings.
2987 auto Abbv = std::make_shared<BitCodeAbbrev>();
2988 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
2989 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2990 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2991 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2992 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
2993 VST_BBENTRY_6_ABBREV)
2994 llvm_unreachable("Unexpected abbrev ordering!");
2999 { // SETTYPE abbrev for CONSTANTS_BLOCK.
3000 auto Abbv = std::make_shared<BitCodeAbbrev>();
3001 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
3002 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
3003 VE.computeBitsRequiredForTypeIndicies()));
3004 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3005 CONSTANTS_SETTYPE_ABBREV)
3006 llvm_unreachable("Unexpected abbrev ordering!");
3009 { // INTEGER abbrev for CONSTANTS_BLOCK.
3010 auto Abbv = std::make_shared<BitCodeAbbrev>();
3011 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
3012 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3013 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3014 CONSTANTS_INTEGER_ABBREV)
3015 llvm_unreachable("Unexpected abbrev ordering!");
3018 { // CE_CAST abbrev for CONSTANTS_BLOCK.
3019 auto Abbv = std::make_shared<BitCodeAbbrev>();
3020 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
3021 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
3022 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
3023 VE.computeBitsRequiredForTypeIndicies()));
3024 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3026 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3027 CONSTANTS_CE_CAST_Abbrev)
3028 llvm_unreachable("Unexpected abbrev ordering!");
3030 { // NULL abbrev for CONSTANTS_BLOCK.
3031 auto Abbv = std::make_shared<BitCodeAbbrev>();
3032 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
3033 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3034 CONSTANTS_NULL_Abbrev)
3035 llvm_unreachable("Unexpected abbrev ordering!");
3038 // FIXME: This should only use space for first class types!
3040 { // INST_LOAD abbrev for FUNCTION_BLOCK.
3041 auto Abbv = std::make_shared<BitCodeAbbrev>();
3042 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
3043 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
3044 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3045 VE.computeBitsRequiredForTypeIndicies()));
3046 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
3047 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
3048 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3049 FUNCTION_INST_LOAD_ABBREV)
3050 llvm_unreachable("Unexpected abbrev ordering!");
3052 { // INST_BINOP abbrev for FUNCTION_BLOCK.
3053 auto Abbv = std::make_shared<BitCodeAbbrev>();
3054 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3055 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3056 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3057 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3058 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3059 FUNCTION_INST_BINOP_ABBREV)
3060 llvm_unreachable("Unexpected abbrev ordering!");
3062 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
3063 auto Abbv = std::make_shared<BitCodeAbbrev>();
3064 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3065 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3066 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3067 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3068 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
3069 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3070 FUNCTION_INST_BINOP_FLAGS_ABBREV)
3071 llvm_unreachable("Unexpected abbrev ordering!");
3073 { // INST_CAST abbrev for FUNCTION_BLOCK.
3074 auto Abbv = std::make_shared<BitCodeAbbrev>();
3075 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
3076 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
3077 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3078 VE.computeBitsRequiredForTypeIndicies()));
3079 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3080 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3081 FUNCTION_INST_CAST_ABBREV)
3082 llvm_unreachable("Unexpected abbrev ordering!");
3085 { // INST_RET abbrev for FUNCTION_BLOCK.
3086 auto Abbv = std::make_shared<BitCodeAbbrev>();
3087 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
3088 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3089 FUNCTION_INST_RET_VOID_ABBREV)
3090 llvm_unreachable("Unexpected abbrev ordering!");
3092 { // INST_RET abbrev for FUNCTION_BLOCK.
3093 auto Abbv = std::make_shared<BitCodeAbbrev>();
3094 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
3095 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
3096 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3097 FUNCTION_INST_RET_VAL_ABBREV)
3098 llvm_unreachable("Unexpected abbrev ordering!");
3100 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
3101 auto Abbv = std::make_shared<BitCodeAbbrev>();
3102 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
3103 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3104 FUNCTION_INST_UNREACHABLE_ABBREV)
3105 llvm_unreachable("Unexpected abbrev ordering!");
3108 auto Abbv = std::make_shared<BitCodeAbbrev>();
3109 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
3110 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
3111 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3112 Log2_32_Ceil(VE.getTypes().size() + 1)));
3113 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3114 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
3115 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3116 FUNCTION_INST_GEP_ABBREV)
3117 llvm_unreachable("Unexpected abbrev ordering!");
3123 /// Write the module path strings, currently only used when generating
3124 /// a combined index file.
3125 void IndexBitcodeWriter::writeModStrings() {
3126 Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);
3128 // TODO: See which abbrev sizes we actually need to emit
3130 // 8-bit fixed-width MST_ENTRY strings.
3131 auto Abbv = std::make_shared<BitCodeAbbrev>();
3132 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3133 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3134 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3135 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
3136 unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
3138 // 7-bit fixed width MST_ENTRY strings.
3139 Abbv = std::make_shared<BitCodeAbbrev>();
3140 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3141 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3142 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3143 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
3144 unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
3146 // 6-bit char6 MST_ENTRY strings.
3147 Abbv = std::make_shared<BitCodeAbbrev>();
3148 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3149 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3150 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3151 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3152 unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
3154 // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
3155 Abbv = std::make_shared<BitCodeAbbrev>();
3156 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH));
3157 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3158 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3159 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3160 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3161 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3162 unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
3164 SmallVector<unsigned, 64> Vals;
3166 [&](const StringMapEntry<std::pair<uint64_t, ModuleHash>> &MPSE) {
3167 StringRef Key = MPSE.getKey();
3168 const auto &Value = MPSE.getValue();
3169 StringEncoding Bits = getStringEncoding(Key);
3170 unsigned AbbrevToUse = Abbrev8Bit;
3171 if (Bits == SE_Char6)
3172 AbbrevToUse = Abbrev6Bit;
3173 else if (Bits == SE_Fixed7)
3174 AbbrevToUse = Abbrev7Bit;
3176 Vals.push_back(Value.first);
3177 Vals.append(Key.begin(), Key.end());
3179 // Emit the finished record.
3180 Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
3182 // Emit an optional hash for the module now
3183 const auto &Hash = Value.second;
3184 if (llvm::any_of(Hash, [](uint32_t H) { return H; })) {
3185 Vals.assign(Hash.begin(), Hash.end());
3186 // Emit the hash record.
3187 Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
3195 /// Write the function type metadata related records that need to appear before
3196 /// a function summary entry (whether per-module or combined).
3197 static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream,
3198 FunctionSummary *FS) {
3199 if (!FS->type_tests().empty())
3200 Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
3202 SmallVector<uint64_t, 64> Record;
3204 auto WriteVFuncIdVec = [&](uint64_t Ty,
3205 ArrayRef<FunctionSummary::VFuncId> VFs) {
3209 for (auto &VF : VFs) {
3210 Record.push_back(VF.GUID);
3211 Record.push_back(VF.Offset);
3213 Stream.EmitRecord(Ty, Record);
3216 WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
3217 FS->type_test_assume_vcalls());
3218 WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
3219 FS->type_checked_load_vcalls());
3221 auto WriteConstVCallVec = [&](uint64_t Ty,
3222 ArrayRef<FunctionSummary::ConstVCall> VCs) {
3223 for (auto &VC : VCs) {
3225 Record.push_back(VC.VFunc.GUID);
3226 Record.push_back(VC.VFunc.Offset);
3227 Record.insert(Record.end(), VC.Args.begin(), VC.Args.end());
3228 Stream.EmitRecord(Ty, Record);
3232 WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
3233 FS->type_test_assume_const_vcalls());
3234 WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
3235 FS->type_checked_load_const_vcalls());
3238 // Helper to emit a single function summary record.
3239 void ModuleBitcodeWriter::writePerModuleFunctionSummaryRecord(
3240 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
3241 unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
3242 const Function &F) {
3243 NameVals.push_back(ValueID);
3245 FunctionSummary *FS = cast<FunctionSummary>(Summary);
3246 writeFunctionTypeMetadataRecords(Stream, FS);
3248 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
3249 NameVals.push_back(FS->instCount());
3250 NameVals.push_back(FS->refs().size());
3252 for (auto &RI : FS->refs())
3253 NameVals.push_back(VE.getValueID(RI.getValue()));
3255 bool HasProfileData = F.getEntryCount().hasValue();
3256 for (auto &ECI : FS->calls()) {
3257 NameVals.push_back(getValueId(ECI.first));
3259 NameVals.push_back(static_cast<uint8_t>(ECI.second.Hotness));
3262 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3264 (HasProfileData ? bitc::FS_PERMODULE_PROFILE : bitc::FS_PERMODULE);
3266 // Emit the finished record.
3267 Stream.EmitRecord(Code, NameVals, FSAbbrev);
3271 // Collect the global value references in the given variable's initializer,
3272 // and emit them in a summary record.
3273 void ModuleBitcodeWriter::writeModuleLevelReferences(
3274 const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
3275 unsigned FSModRefsAbbrev) {
3276 auto VI = Index->getValueInfo(GlobalValue::getGUID(V.getName()));
3277 if (!VI || VI.getSummaryList().empty()) {
3278 // Only declarations should not have a summary (a declaration might however
3279 // have a summary if the def was in module level asm).
3280 assert(V.isDeclaration());
3283 auto *Summary = VI.getSummaryList()[0].get();
3284 NameVals.push_back(VE.getValueID(&V));
3285 GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
3286 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
3288 unsigned SizeBeforeRefs = NameVals.size();
3289 for (auto &RI : VS->refs())
3290 NameVals.push_back(VE.getValueID(RI.getValue()));
3291 // Sort the refs for determinism output, the vector returned by FS->refs() has
3292 // been initialized from a DenseSet.
3293 std::sort(NameVals.begin() + SizeBeforeRefs, NameVals.end());
3295 Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals,
3300 // Current version for the summary.
3301 // This is bumped whenever we introduce changes in the way some record are
3302 // interpreted, like flags for instance.
3303 static const uint64_t INDEX_VERSION = 3;
3305 /// Emit the per-module summary section alongside the rest of
3306 /// the module's bitcode.
3307 void ModuleBitcodeWriter::writePerModuleGlobalValueSummary() {
3308 // By default we compile with ThinLTO if the module has a summary, but the
3309 // client can request full LTO with a module flag.
3310 bool IsThinLTO = true;
3312 mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
3313 IsThinLTO = MD->getZExtValue();
3314 Stream.EnterSubblock(IsThinLTO ? bitc::GLOBALVAL_SUMMARY_BLOCK_ID
3315 : bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID,
3318 Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
3320 if (Index->begin() == Index->end()) {
3325 for (const auto &GVI : valueIds()) {
3326 Stream.EmitRecord(bitc::FS_VALUE_GUID,
3327 ArrayRef<uint64_t>{GVI.second, GVI.first});
3330 // Abbrev for FS_PERMODULE.
3331 auto Abbv = std::make_shared<BitCodeAbbrev>();
3332 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE));
3333 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3334 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3335 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3336 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3337 // numrefs x valueid, n x (valueid)
3338 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3339 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3340 unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3342 // Abbrev for FS_PERMODULE_PROFILE.
3343 Abbv = std::make_shared<BitCodeAbbrev>();
3344 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));
3345 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3346 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3347 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3348 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3349 // numrefs x valueid, n x (valueid, hotness)
3350 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3351 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3352 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3354 // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
3355 Abbv = std::make_shared<BitCodeAbbrev>();
3356 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));
3357 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3358 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3359 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
3360 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3361 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3363 // Abbrev for FS_ALIAS.
3364 Abbv = std::make_shared<BitCodeAbbrev>();
3365 Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
3366 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3367 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3368 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3369 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3371 SmallVector<uint64_t, 64> NameVals;
3372 // Iterate over the list of functions instead of the Index to
3373 // ensure the ordering is stable.
3374 for (const Function &F : M) {
3375 // Summary emission does not support anonymous functions, they have to
3376 // renamed using the anonymous function renaming pass.
3378 report_fatal_error("Unexpected anonymous function when writing summary");
3380 ValueInfo VI = Index->getValueInfo(GlobalValue::getGUID(F.getName()));
3381 if (!VI || VI.getSummaryList().empty()) {
3382 // Only declarations should not have a summary (a declaration might
3383 // however have a summary if the def was in module level asm).
3384 assert(F.isDeclaration());
3387 auto *Summary = VI.getSummaryList()[0].get();
3388 writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.getValueID(&F),
3389 FSCallsAbbrev, FSCallsProfileAbbrev, F);
3392 // Capture references from GlobalVariable initializers, which are outside
3393 // of a function scope.
3394 for (const GlobalVariable &G : M.globals())
3395 writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev);
3397 for (const GlobalAlias &A : M.aliases()) {
3398 auto *Aliasee = A.getBaseObject();
3399 if (!Aliasee->hasName())
3400 // Nameless function don't have an entry in the summary, skip it.
3402 auto AliasId = VE.getValueID(&A);
3403 auto AliaseeId = VE.getValueID(Aliasee);
3404 NameVals.push_back(AliasId);
3405 auto *Summary = Index->getGlobalValueSummary(A);
3406 AliasSummary *AS = cast<AliasSummary>(Summary);
3407 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
3408 NameVals.push_back(AliaseeId);
3409 Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
3416 /// Emit the combined summary section into the combined index file.
3417 void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
3418 Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3);
3419 Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
3421 for (const auto &GVI : valueIds()) {
3422 Stream.EmitRecord(bitc::FS_VALUE_GUID,
3423 ArrayRef<uint64_t>{GVI.second, GVI.first});
3426 // Abbrev for FS_COMBINED.
3427 auto Abbv = std::make_shared<BitCodeAbbrev>();
3428 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED));
3429 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3430 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
3431 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3432 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3433 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3434 // numrefs x valueid, n x (valueid)
3435 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3436 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3437 unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3439 // Abbrev for FS_COMBINED_PROFILE.
3440 Abbv = std::make_shared<BitCodeAbbrev>();
3441 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));
3442 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3443 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
3444 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3445 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3446 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3447 // numrefs x valueid, n x (valueid, hotness)
3448 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3449 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3450 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3452 // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
3453 Abbv = std::make_shared<BitCodeAbbrev>();
3454 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));
3455 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3456 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
3457 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3458 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
3459 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3460 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3462 // Abbrev for FS_COMBINED_ALIAS.
3463 Abbv = std::make_shared<BitCodeAbbrev>();
3464 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS));
3465 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3466 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
3467 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3468 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3469 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3471 // The aliases are emitted as a post-pass, and will point to the value
3472 // id of the aliasee. Save them in a vector for post-processing.
3473 SmallVector<AliasSummary *, 64> Aliases;
3475 // Save the value id for each summary for alias emission.
3476 DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
3478 SmallVector<uint64_t, 64> NameVals;
3480 // For local linkage, we also emit the original name separately
3481 // immediately after the record.
3482 auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
3483 if (!GlobalValue::isLocalLinkage(S.linkage()))
3485 NameVals.push_back(S.getOriginalName());
3486 Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals);
3490 forEachSummary([&](GVInfo I) {
3491 GlobalValueSummary *S = I.second;
3494 auto ValueId = getValueId(I.first);
3496 SummaryToValueIdMap[S] = *ValueId;
3498 if (auto *AS = dyn_cast<AliasSummary>(S)) {
3499 // Will process aliases as a post-pass because the reader wants all
3500 // global to be loaded first.
3501 Aliases.push_back(AS);
3505 if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
3506 NameVals.push_back(*ValueId);
3507 NameVals.push_back(Index.getModuleId(VS->modulePath()));
3508 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
3509 for (auto &RI : VS->refs()) {
3510 auto RefValueId = getValueId(RI.getGUID());
3513 NameVals.push_back(*RefValueId);
3516 // Emit the finished record.
3517 Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals,
3520 MaybeEmitOriginalName(*S);
3524 auto *FS = cast<FunctionSummary>(S);
3525 writeFunctionTypeMetadataRecords(Stream, FS);
3527 NameVals.push_back(*ValueId);
3528 NameVals.push_back(Index.getModuleId(FS->modulePath()));
3529 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
3530 NameVals.push_back(FS->instCount());
3532 NameVals.push_back(0);
3535 for (auto &RI : FS->refs()) {
3536 auto RefValueId = getValueId(RI.getGUID());
3539 NameVals.push_back(*RefValueId);
3542 NameVals[4] = Count;
3544 bool HasProfileData = false;
3545 for (auto &EI : FS->calls()) {
3546 HasProfileData |= EI.second.Hotness != CalleeInfo::HotnessType::Unknown;
3551 for (auto &EI : FS->calls()) {
3552 // If this GUID doesn't have a value id, it doesn't have a function
3553 // summary and we don't need to record any calls to it.
3554 GlobalValue::GUID GUID = EI.first.getGUID();
3555 auto CallValueId = getValueId(GUID);
3557 // For SamplePGO, the indirect call targets for local functions will
3558 // have its original name annotated in profile. We try to find the
3559 // corresponding PGOFuncName as the GUID.
3560 GUID = Index.getGUIDFromOriginalID(GUID);
3563 CallValueId = getValueId(GUID);
3567 NameVals.push_back(*CallValueId);
3569 NameVals.push_back(static_cast<uint8_t>(EI.second.Hotness));
3572 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3574 (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED);
3576 // Emit the finished record.
3577 Stream.EmitRecord(Code, NameVals, FSAbbrev);
3579 MaybeEmitOriginalName(*S);
3582 for (auto *AS : Aliases) {
3583 auto AliasValueId = SummaryToValueIdMap[AS];
3584 assert(AliasValueId);
3585 NameVals.push_back(AliasValueId);
3586 NameVals.push_back(Index.getModuleId(AS->modulePath()));
3587 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
3588 auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()];
3589 assert(AliaseeValueId);
3590 NameVals.push_back(AliaseeValueId);
3592 // Emit the finished record.
3593 Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
3595 MaybeEmitOriginalName(*AS);
3601 /// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
3602 /// current llvm version, and a record for the epoch number.
3603 static void writeIdentificationBlock(BitstreamWriter &Stream) {
3604 Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);
3606 // Write the "user readable" string identifying the bitcode producer
3607 auto Abbv = std::make_shared<BitCodeAbbrev>();
3608 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING));
3609 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3610 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3611 auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3612 writeStringRecord(Stream, bitc::IDENTIFICATION_CODE_STRING,
3613 "LLVM" LLVM_VERSION_STRING, StringAbbrev);
3615 // Write the epoch version
3616 Abbv = std::make_shared<BitCodeAbbrev>();
3617 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH));
3618 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
3619 auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3620 SmallVector<unsigned, 1> Vals = {bitc::BITCODE_CURRENT_EPOCH};
3621 Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
3625 void ModuleBitcodeWriter::writeModuleHash(size_t BlockStartPos) {
3626 // Emit the module's hash.
3627 // MODULE_CODE_HASH: [5*i32]
3631 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&(Buffer)[BlockStartPos],
3632 Buffer.size() - BlockStartPos));
3633 StringRef Hash = Hasher.result();
3634 for (int Pos = 0; Pos < 20; Pos += 4) {
3635 Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);
3638 // Emit the finished record.
3639 Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
3642 // Save the written hash value.
3643 std::copy(std::begin(Vals), std::end(Vals), std::begin(*ModHash));
3645 Stream.EmitRecord(bitc::MODULE_CODE_HASH, ArrayRef<uint32_t>(*ModHash));
3648 void ModuleBitcodeWriter::write() {
3649 writeIdentificationBlock(Stream);
3651 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
3652 size_t BlockStartPos = Buffer.size();
3654 writeModuleVersion();
3656 // Emit blockinfo, which defines the standard abbreviations etc.
3659 // Emit information about attribute groups.
3660 writeAttributeGroupTable();
3662 // Emit information about parameter attributes.
3663 writeAttributeTable();
3665 // Emit information describing all of the types in the module.
3670 // Emit top-level description of module, including target triple, inline asm,
3671 // descriptors for global variables, and function prototype info.
3675 writeModuleConstants();
3677 // Emit metadata kind names.
3678 writeModuleMetadataKinds();
3681 writeModuleMetadata();
3683 // Emit module-level use-lists.
3684 if (VE.shouldPreserveUseListOrder())
3685 writeUseListBlock(nullptr);
3687 writeOperandBundleTags();
3689 // Emit function bodies.
3690 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
3691 for (Module::const_iterator F = M.begin(), E = M.end(); F != E; ++F)
3692 if (!F->isDeclaration())
3693 writeFunction(*F, FunctionToBitcodeIndex);
3695 // Need to write after the above call to WriteFunction which populates
3696 // the summary information in the index.
3698 writePerModuleGlobalValueSummary();
3700 writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
3702 writeModuleHash(BlockStartPos);
3707 static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
3708 uint32_t &Position) {
3709 support::endian::write32le(&Buffer[Position], Value);
3713 /// If generating a bc file on darwin, we have to emit a
3714 /// header and trailer to make it compatible with the system archiver. To do
3715 /// this we emit the following header, and then emit a trailer that pads the
3716 /// file out to be a multiple of 16 bytes.
3718 /// struct bc_header {
3719 /// uint32_t Magic; // 0x0B17C0DE
3720 /// uint32_t Version; // Version, currently always 0.
3721 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
3722 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
3723 /// uint32_t CPUType; // CPU specifier.
3724 /// ... potentially more later ...
3726 static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
3728 unsigned CPUType = ~0U;
3730 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
3731 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
3732 // number from /usr/include/mach/machine.h. It is ok to reproduce the
3733 // specific constants here because they are implicitly part of the Darwin ABI.
3735 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
3736 DARWIN_CPU_TYPE_X86 = 7,
3737 DARWIN_CPU_TYPE_ARM = 12,
3738 DARWIN_CPU_TYPE_POWERPC = 18
3741 Triple::ArchType Arch = TT.getArch();
3742 if (Arch == Triple::x86_64)
3743 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
3744 else if (Arch == Triple::x86)
3745 CPUType = DARWIN_CPU_TYPE_X86;
3746 else if (Arch == Triple::ppc)
3747 CPUType = DARWIN_CPU_TYPE_POWERPC;
3748 else if (Arch == Triple::ppc64)
3749 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
3750 else if (Arch == Triple::arm || Arch == Triple::thumb)
3751 CPUType = DARWIN_CPU_TYPE_ARM;
3753 // Traditional Bitcode starts after header.
3754 assert(Buffer.size() >= BWH_HeaderSize &&
3755 "Expected header size to be reserved");
3756 unsigned BCOffset = BWH_HeaderSize;
3757 unsigned BCSize = Buffer.size() - BWH_HeaderSize;
3759 // Write the magic and version.
3760 unsigned Position = 0;
3761 writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
3762 writeInt32ToBuffer(0, Buffer, Position); // Version.
3763 writeInt32ToBuffer(BCOffset, Buffer, Position);
3764 writeInt32ToBuffer(BCSize, Buffer, Position);
3765 writeInt32ToBuffer(CPUType, Buffer, Position);
3767 // If the file is not a multiple of 16 bytes, insert dummy padding.
3768 while (Buffer.size() & 15)
3769 Buffer.push_back(0);
3772 /// Helper to write the header common to all bitcode files.
3773 static void writeBitcodeHeader(BitstreamWriter &Stream) {
3774 // Emit the file header.
3775 Stream.Emit((unsigned)'B', 8);
3776 Stream.Emit((unsigned)'C', 8);
3777 Stream.Emit(0x0, 4);
3778 Stream.Emit(0xC, 4);
3779 Stream.Emit(0xE, 4);
3780 Stream.Emit(0xD, 4);
3783 BitcodeWriter::BitcodeWriter(SmallVectorImpl<char> &Buffer)
3784 : Buffer(Buffer), Stream(new BitstreamWriter(Buffer)) {
3785 writeBitcodeHeader(*Stream);
3788 BitcodeWriter::~BitcodeWriter() { assert(WroteStrtab); }
3790 void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) {
3791 Stream->EnterSubblock(Block, 3);
3793 auto Abbv = std::make_shared<BitCodeAbbrev>();
3794 Abbv->Add(BitCodeAbbrevOp(Record));
3795 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3796 auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv));
3798 Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob);
3800 Stream->ExitBlock();
3803 void BitcodeWriter::writeStrtab() {
3804 assert(!WroteStrtab);
3806 std::vector<char> Strtab;
3807 StrtabBuilder.finalizeInOrder();
3808 Strtab.resize(StrtabBuilder.getSize());
3809 StrtabBuilder.write((uint8_t *)Strtab.data());
3811 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB,
3812 {Strtab.data(), Strtab.size()});
3817 void BitcodeWriter::copyStrtab(StringRef Strtab) {
3818 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab);
3822 void BitcodeWriter::writeModule(const Module *M,
3823 bool ShouldPreserveUseListOrder,
3824 const ModuleSummaryIndex *Index,
3825 bool GenerateHash, ModuleHash *ModHash) {
3826 ModuleBitcodeWriter ModuleWriter(M, Buffer, StrtabBuilder, *Stream,
3827 ShouldPreserveUseListOrder, Index,
3828 GenerateHash, ModHash);
3829 ModuleWriter.write();
3832 /// WriteBitcodeToFile - Write the specified module to the specified output
3834 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out,
3835 bool ShouldPreserveUseListOrder,
3836 const ModuleSummaryIndex *Index,
3837 bool GenerateHash, ModuleHash *ModHash) {
3838 SmallVector<char, 0> Buffer;
3839 Buffer.reserve(256*1024);
3841 // If this is darwin or another generic macho target, reserve space for the
3843 Triple TT(M->getTargetTriple());
3844 if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
3845 Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
3847 BitcodeWriter Writer(Buffer);
3848 Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
3850 Writer.writeStrtab();
3852 if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
3853 emitDarwinBCHeaderAndTrailer(Buffer, TT);
3855 // Write the generated bitstream to "Out".
3856 Out.write((char*)&Buffer.front(), Buffer.size());
3859 void IndexBitcodeWriter::write() {
3860 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
3862 writeModuleVersion();
3864 // Write the module paths in the combined index.
3867 // Write the summary combined index records.
3868 writeCombinedGlobalValueSummary();
3873 // Write the specified module summary index to the given raw output stream,
3874 // where it will be written in a new bitcode block. This is used when
3875 // writing the combined index file for ThinLTO. When writing a subset of the
3876 // index for a distributed backend, provide a \p ModuleToSummariesForIndex map.
3877 void llvm::WriteIndexToFile(
3878 const ModuleSummaryIndex &Index, raw_ostream &Out,
3879 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
3880 SmallVector<char, 0> Buffer;
3881 Buffer.reserve(256 * 1024);
3883 BitstreamWriter Stream(Buffer);
3884 writeBitcodeHeader(Stream);
3886 IndexBitcodeWriter IndexWriter(Stream, Index, ModuleToSummariesForIndex);
3887 IndexWriter.write();
3889 Out.write((char *)&Buffer.front(), Buffer.size());