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/Object/IRSymtab.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/Program.h"
36 #include "llvm/Support/SHA1.h"
37 #include "llvm/Support/TargetRegistry.h"
38 #include "llvm/Support/raw_ostream.h"
46 IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25),
47 cl::desc("Number of metadatas above which we emit an index "
48 "to enable lazy-loading"));
49 /// These are manifest constants used by the bitcode writer. They do not need to
50 /// be kept in sync with the reader, but need to be consistent within this file.
52 // VALUE_SYMTAB_BLOCK abbrev id's.
53 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
58 // CONSTANTS_BLOCK abbrev id's.
59 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
60 CONSTANTS_INTEGER_ABBREV,
61 CONSTANTS_CE_CAST_Abbrev,
62 CONSTANTS_NULL_Abbrev,
64 // FUNCTION_BLOCK abbrev id's.
65 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
66 FUNCTION_INST_BINOP_ABBREV,
67 FUNCTION_INST_BINOP_FLAGS_ABBREV,
68 FUNCTION_INST_CAST_ABBREV,
69 FUNCTION_INST_RET_VOID_ABBREV,
70 FUNCTION_INST_RET_VAL_ABBREV,
71 FUNCTION_INST_UNREACHABLE_ABBREV,
72 FUNCTION_INST_GEP_ABBREV,
75 /// Abstract class to manage the bitcode writing, subclassed for each bitcode
77 class BitcodeWriterBase {
79 /// The stream created and owned by the client.
80 BitstreamWriter &Stream;
82 StringTableBuilder &StrtabBuilder;
85 /// Constructs a BitcodeWriterBase object that writes to the provided
87 BitcodeWriterBase(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder)
88 : Stream(Stream), StrtabBuilder(StrtabBuilder) {}
91 void writeBitcodeHeader();
92 void writeModuleVersion();
95 void BitcodeWriterBase::writeModuleVersion() {
96 // VERSION: [version#]
97 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, ArrayRef<uint64_t>{2});
100 /// Class to manage the bitcode writing for a module.
101 class ModuleBitcodeWriter : public BitcodeWriterBase {
102 /// Pointer to the buffer allocated by caller for bitcode writing.
103 const SmallVectorImpl<char> &Buffer;
105 /// The Module to write to bitcode.
108 /// Enumerates ids for all values in the module.
111 /// Optional per-module index to write for ThinLTO.
112 const ModuleSummaryIndex *Index;
114 /// True if a module hash record should be written.
117 /// If non-null, when GenerateHash is true, the resulting hash is written
118 /// into ModHash. When GenerateHash is false, that specified value
119 /// is used as the hash instead of computing from the generated bitcode.
120 /// Can be used to produce the same module hash for a minimized bitcode
121 /// used just for the thin link as in the regular full bitcode that will
122 /// be used in the backend.
125 /// The start bit of the identification block.
126 uint64_t BitcodeStartBit;
128 /// Map that holds the correspondence between GUIDs in the summary index,
129 /// that came from indirect call profiles, and a value id generated by this
130 /// class to use in the VST and summary block records.
131 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
133 /// Tracks the last value id recorded in the GUIDToValueMap.
134 unsigned GlobalValueId;
136 /// Saves the offset of the VSTOffset record that must eventually be
137 /// backpatched with the offset of the actual VST.
138 uint64_t VSTOffsetPlaceholder = 0;
141 /// Constructs a ModuleBitcodeWriter object for the given Module,
142 /// writing to the provided \p Buffer.
143 ModuleBitcodeWriter(const Module *M, SmallVectorImpl<char> &Buffer,
144 StringTableBuilder &StrtabBuilder,
145 BitstreamWriter &Stream, bool ShouldPreserveUseListOrder,
146 const ModuleSummaryIndex *Index, bool GenerateHash,
147 ModuleHash *ModHash = nullptr)
148 : BitcodeWriterBase(Stream, StrtabBuilder), Buffer(Buffer), M(*M),
149 VE(*M, ShouldPreserveUseListOrder), Index(Index),
150 GenerateHash(GenerateHash), ModHash(ModHash),
151 BitcodeStartBit(Stream.GetCurrentBitNo()) {
152 // Assign ValueIds to any callee values in the index that came from
153 // indirect call profiles and were recorded as a GUID not a Value*
154 // (which would have been assigned an ID by the ValueEnumerator).
155 // The starting ValueId is just after the number of values in the
156 // ValueEnumerator, so that they can be emitted in the VST.
157 GlobalValueId = VE.getValues().size();
160 for (const auto &GUIDSummaryLists : *Index)
161 // Examine all summaries for this GUID.
162 for (auto &Summary : GUIDSummaryLists.second.SummaryList)
163 if (auto FS = dyn_cast<FunctionSummary>(Summary.get()))
164 // For each call in the function summary, see if the call
165 // is to a GUID (which means it is for an indirect call,
166 // otherwise we would have a Value for it). If so, synthesize
168 for (auto &CallEdge : FS->calls())
169 if (!CallEdge.first.getValue())
170 assignValueId(CallEdge.first.getGUID());
173 /// Emit the current module to the bitstream.
177 uint64_t bitcodeStartBit() { return BitcodeStartBit; }
179 void writeAttributeGroupTable();
180 void writeAttributeTable();
181 void writeTypeTable();
183 void writeValueSymbolTableForwardDecl();
184 void writeModuleInfo();
185 void writeValueAsMetadata(const ValueAsMetadata *MD,
186 SmallVectorImpl<uint64_t> &Record);
187 void writeMDTuple(const MDTuple *N, SmallVectorImpl<uint64_t> &Record,
189 unsigned createDILocationAbbrev();
190 void writeDILocation(const DILocation *N, SmallVectorImpl<uint64_t> &Record,
192 unsigned createGenericDINodeAbbrev();
193 void writeGenericDINode(const GenericDINode *N,
194 SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev);
195 void writeDISubrange(const DISubrange *N, SmallVectorImpl<uint64_t> &Record,
197 void writeDIEnumerator(const DIEnumerator *N,
198 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
199 void writeDIBasicType(const DIBasicType *N, SmallVectorImpl<uint64_t> &Record,
201 void writeDIDerivedType(const DIDerivedType *N,
202 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
203 void writeDICompositeType(const DICompositeType *N,
204 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
205 void writeDISubroutineType(const DISubroutineType *N,
206 SmallVectorImpl<uint64_t> &Record,
208 void writeDIFile(const DIFile *N, SmallVectorImpl<uint64_t> &Record,
210 void writeDICompileUnit(const DICompileUnit *N,
211 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
212 void writeDISubprogram(const DISubprogram *N,
213 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
214 void writeDILexicalBlock(const DILexicalBlock *N,
215 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
216 void writeDILexicalBlockFile(const DILexicalBlockFile *N,
217 SmallVectorImpl<uint64_t> &Record,
219 void writeDINamespace(const DINamespace *N, SmallVectorImpl<uint64_t> &Record,
221 void writeDIMacro(const DIMacro *N, SmallVectorImpl<uint64_t> &Record,
223 void writeDIMacroFile(const DIMacroFile *N, SmallVectorImpl<uint64_t> &Record,
225 void writeDIModule(const DIModule *N, SmallVectorImpl<uint64_t> &Record,
227 void writeDITemplateTypeParameter(const DITemplateTypeParameter *N,
228 SmallVectorImpl<uint64_t> &Record,
230 void writeDITemplateValueParameter(const DITemplateValueParameter *N,
231 SmallVectorImpl<uint64_t> &Record,
233 void writeDIGlobalVariable(const DIGlobalVariable *N,
234 SmallVectorImpl<uint64_t> &Record,
236 void writeDILocalVariable(const DILocalVariable *N,
237 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
238 void writeDIExpression(const DIExpression *N,
239 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
240 void writeDIGlobalVariableExpression(const DIGlobalVariableExpression *N,
241 SmallVectorImpl<uint64_t> &Record,
243 void writeDIObjCProperty(const DIObjCProperty *N,
244 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
245 void writeDIImportedEntity(const DIImportedEntity *N,
246 SmallVectorImpl<uint64_t> &Record,
248 unsigned createNamedMetadataAbbrev();
249 void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
250 unsigned createMetadataStringsAbbrev();
251 void writeMetadataStrings(ArrayRef<const Metadata *> Strings,
252 SmallVectorImpl<uint64_t> &Record);
253 void writeMetadataRecords(ArrayRef<const Metadata *> MDs,
254 SmallVectorImpl<uint64_t> &Record,
255 std::vector<unsigned> *MDAbbrevs = nullptr,
256 std::vector<uint64_t> *IndexPos = nullptr);
257 void writeModuleMetadata();
258 void writeFunctionMetadata(const Function &F);
259 void writeFunctionMetadataAttachment(const Function &F);
260 void writeGlobalVariableMetadataAttachment(const GlobalVariable &GV);
261 void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
262 const GlobalObject &GO);
263 void writeModuleMetadataKinds();
264 void writeOperandBundleTags();
265 void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal);
266 void writeModuleConstants();
267 bool pushValueAndType(const Value *V, unsigned InstID,
268 SmallVectorImpl<unsigned> &Vals);
269 void writeOperandBundles(ImmutableCallSite CS, unsigned InstID);
270 void pushValue(const Value *V, unsigned InstID,
271 SmallVectorImpl<unsigned> &Vals);
272 void pushValueSigned(const Value *V, unsigned InstID,
273 SmallVectorImpl<uint64_t> &Vals);
274 void writeInstruction(const Instruction &I, unsigned InstID,
275 SmallVectorImpl<unsigned> &Vals);
276 void writeFunctionLevelValueSymbolTable(const ValueSymbolTable &VST);
277 void writeGlobalValueSymbolTable(
278 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
279 void writeUseList(UseListOrder &&Order);
280 void writeUseListBlock(const Function *F);
282 writeFunction(const Function &F,
283 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
284 void writeBlockInfo();
285 void writePerModuleFunctionSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
286 GlobalValueSummary *Summary,
288 unsigned FSCallsAbbrev,
289 unsigned FSCallsProfileAbbrev,
291 void writeModuleLevelReferences(const GlobalVariable &V,
292 SmallVector<uint64_t, 64> &NameVals,
293 unsigned FSModRefsAbbrev);
294 void writePerModuleGlobalValueSummary();
295 void writeModuleHash(size_t BlockStartPos);
297 void assignValueId(GlobalValue::GUID ValGUID) {
298 GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
300 unsigned getValueId(GlobalValue::GUID ValGUID) {
301 const auto &VMI = GUIDToValueIdMap.find(ValGUID);
302 // Expect that any GUID value had a value Id assigned by an
303 // earlier call to assignValueId.
304 assert(VMI != GUIDToValueIdMap.end() &&
305 "GUID does not have assigned value Id");
308 // Helper to get the valueId for the type of value recorded in VI.
309 unsigned getValueId(ValueInfo VI) {
311 return getValueId(VI.getGUID());
312 return VE.getValueID(VI.getValue());
314 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
317 /// Class to manage the bitcode writing for a combined index.
318 class IndexBitcodeWriter : public BitcodeWriterBase {
319 /// The combined index to write to bitcode.
320 const ModuleSummaryIndex &Index;
322 /// When writing a subset of the index for distributed backends, client
323 /// provides a map of modules to the corresponding GUIDs/summaries to write.
324 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex;
326 /// Map that holds the correspondence between the GUID used in the combined
327 /// index and a value id generated by this class to use in references.
328 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
330 /// Tracks the last value id recorded in the GUIDToValueMap.
331 unsigned GlobalValueId = 0;
334 /// Constructs a IndexBitcodeWriter object for the given combined index,
335 /// writing to the provided \p Buffer. When writing a subset of the index
336 /// for a distributed backend, provide a \p ModuleToSummariesForIndex map.
337 IndexBitcodeWriter(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder,
338 const ModuleSummaryIndex &Index,
339 const std::map<std::string, GVSummaryMapTy>
340 *ModuleToSummariesForIndex = nullptr)
341 : BitcodeWriterBase(Stream, StrtabBuilder), Index(Index),
342 ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
343 // Assign unique value ids to all summaries to be written, for use
344 // in writing out the call graph edges. Save the mapping from GUID
345 // to the new global value id to use when writing those edges, which
346 // are currently saved in the index in terms of GUID.
347 forEachSummary([&](GVInfo I) {
348 GUIDToValueIdMap[I.first] = ++GlobalValueId;
352 /// The below iterator returns the GUID and associated summary.
353 typedef std::pair<GlobalValue::GUID, GlobalValueSummary *> GVInfo;
355 /// Calls the callback for each value GUID and summary to be written to
356 /// bitcode. This hides the details of whether they are being pulled from the
357 /// entire index or just those in a provided ModuleToSummariesForIndex map.
358 template<typename Functor>
359 void forEachSummary(Functor Callback) {
360 if (ModuleToSummariesForIndex) {
361 for (auto &M : *ModuleToSummariesForIndex)
362 for (auto &Summary : M.second)
365 for (auto &Summaries : Index)
366 for (auto &Summary : Summaries.second.SummaryList)
367 Callback({Summaries.first, Summary.get()});
371 /// Calls the callback for each entry in the modulePaths StringMap that
372 /// should be written to the module path string table. This hides the details
373 /// of whether they are being pulled from the entire index or just those in a
374 /// provided ModuleToSummariesForIndex map.
375 template <typename Functor> void forEachModule(Functor Callback) {
376 if (ModuleToSummariesForIndex) {
377 for (const auto &M : *ModuleToSummariesForIndex) {
378 const auto &MPI = Index.modulePaths().find(M.first);
379 if (MPI == Index.modulePaths().end()) {
380 // This should only happen if the bitcode file was empty, in which
381 // case we shouldn't be importing (the ModuleToSummariesForIndex
382 // would only include the module we are writing and index for).
383 assert(ModuleToSummariesForIndex->size() == 1);
389 for (const auto &MPSE : Index.modulePaths())
394 /// Main entry point for writing a combined index to bitcode.
398 void writeModStrings();
399 void writeCombinedGlobalValueSummary();
401 Optional<unsigned> getValueId(GlobalValue::GUID ValGUID) {
402 auto VMI = GUIDToValueIdMap.find(ValGUID);
403 if (VMI == GUIDToValueIdMap.end())
407 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
409 } // end anonymous namespace
411 static unsigned getEncodedCastOpcode(unsigned Opcode) {
413 default: llvm_unreachable("Unknown cast instruction!");
414 case Instruction::Trunc : return bitc::CAST_TRUNC;
415 case Instruction::ZExt : return bitc::CAST_ZEXT;
416 case Instruction::SExt : return bitc::CAST_SEXT;
417 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
418 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
419 case Instruction::UIToFP : return bitc::CAST_UITOFP;
420 case Instruction::SIToFP : return bitc::CAST_SITOFP;
421 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
422 case Instruction::FPExt : return bitc::CAST_FPEXT;
423 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
424 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
425 case Instruction::BitCast : return bitc::CAST_BITCAST;
426 case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
430 static unsigned getEncodedBinaryOpcode(unsigned Opcode) {
432 default: llvm_unreachable("Unknown binary instruction!");
433 case Instruction::Add:
434 case Instruction::FAdd: return bitc::BINOP_ADD;
435 case Instruction::Sub:
436 case Instruction::FSub: return bitc::BINOP_SUB;
437 case Instruction::Mul:
438 case Instruction::FMul: return bitc::BINOP_MUL;
439 case Instruction::UDiv: return bitc::BINOP_UDIV;
440 case Instruction::FDiv:
441 case Instruction::SDiv: return bitc::BINOP_SDIV;
442 case Instruction::URem: return bitc::BINOP_UREM;
443 case Instruction::FRem:
444 case Instruction::SRem: return bitc::BINOP_SREM;
445 case Instruction::Shl: return bitc::BINOP_SHL;
446 case Instruction::LShr: return bitc::BINOP_LSHR;
447 case Instruction::AShr: return bitc::BINOP_ASHR;
448 case Instruction::And: return bitc::BINOP_AND;
449 case Instruction::Or: return bitc::BINOP_OR;
450 case Instruction::Xor: return bitc::BINOP_XOR;
454 static unsigned getEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
456 default: llvm_unreachable("Unknown RMW operation!");
457 case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
458 case AtomicRMWInst::Add: return bitc::RMW_ADD;
459 case AtomicRMWInst::Sub: return bitc::RMW_SUB;
460 case AtomicRMWInst::And: return bitc::RMW_AND;
461 case AtomicRMWInst::Nand: return bitc::RMW_NAND;
462 case AtomicRMWInst::Or: return bitc::RMW_OR;
463 case AtomicRMWInst::Xor: return bitc::RMW_XOR;
464 case AtomicRMWInst::Max: return bitc::RMW_MAX;
465 case AtomicRMWInst::Min: return bitc::RMW_MIN;
466 case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
467 case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
471 static unsigned getEncodedOrdering(AtomicOrdering Ordering) {
473 case AtomicOrdering::NotAtomic: return bitc::ORDERING_NOTATOMIC;
474 case AtomicOrdering::Unordered: return bitc::ORDERING_UNORDERED;
475 case AtomicOrdering::Monotonic: return bitc::ORDERING_MONOTONIC;
476 case AtomicOrdering::Acquire: return bitc::ORDERING_ACQUIRE;
477 case AtomicOrdering::Release: return bitc::ORDERING_RELEASE;
478 case AtomicOrdering::AcquireRelease: return bitc::ORDERING_ACQREL;
479 case AtomicOrdering::SequentiallyConsistent: return bitc::ORDERING_SEQCST;
481 llvm_unreachable("Invalid ordering");
484 static unsigned getEncodedSynchScope(SynchronizationScope SynchScope) {
485 switch (SynchScope) {
486 case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD;
487 case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD;
489 llvm_unreachable("Invalid synch scope");
492 static void writeStringRecord(BitstreamWriter &Stream, unsigned Code,
493 StringRef Str, unsigned AbbrevToUse) {
494 SmallVector<unsigned, 64> Vals;
496 // Code: [strchar x N]
497 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
498 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
500 Vals.push_back(Str[i]);
503 // Emit the finished record.
504 Stream.EmitRecord(Code, Vals, AbbrevToUse);
507 static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
509 case Attribute::Alignment:
510 return bitc::ATTR_KIND_ALIGNMENT;
511 case Attribute::AllocSize:
512 return bitc::ATTR_KIND_ALLOC_SIZE;
513 case Attribute::AlwaysInline:
514 return bitc::ATTR_KIND_ALWAYS_INLINE;
515 case Attribute::ArgMemOnly:
516 return bitc::ATTR_KIND_ARGMEMONLY;
517 case Attribute::Builtin:
518 return bitc::ATTR_KIND_BUILTIN;
519 case Attribute::ByVal:
520 return bitc::ATTR_KIND_BY_VAL;
521 case Attribute::Convergent:
522 return bitc::ATTR_KIND_CONVERGENT;
523 case Attribute::InAlloca:
524 return bitc::ATTR_KIND_IN_ALLOCA;
525 case Attribute::Cold:
526 return bitc::ATTR_KIND_COLD;
527 case Attribute::InaccessibleMemOnly:
528 return bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY;
529 case Attribute::InaccessibleMemOrArgMemOnly:
530 return bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY;
531 case Attribute::InlineHint:
532 return bitc::ATTR_KIND_INLINE_HINT;
533 case Attribute::InReg:
534 return bitc::ATTR_KIND_IN_REG;
535 case Attribute::JumpTable:
536 return bitc::ATTR_KIND_JUMP_TABLE;
537 case Attribute::MinSize:
538 return bitc::ATTR_KIND_MIN_SIZE;
539 case Attribute::Naked:
540 return bitc::ATTR_KIND_NAKED;
541 case Attribute::Nest:
542 return bitc::ATTR_KIND_NEST;
543 case Attribute::NoAlias:
544 return bitc::ATTR_KIND_NO_ALIAS;
545 case Attribute::NoBuiltin:
546 return bitc::ATTR_KIND_NO_BUILTIN;
547 case Attribute::NoCapture:
548 return bitc::ATTR_KIND_NO_CAPTURE;
549 case Attribute::NoDuplicate:
550 return bitc::ATTR_KIND_NO_DUPLICATE;
551 case Attribute::NoImplicitFloat:
552 return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
553 case Attribute::NoInline:
554 return bitc::ATTR_KIND_NO_INLINE;
555 case Attribute::NoRecurse:
556 return bitc::ATTR_KIND_NO_RECURSE;
557 case Attribute::NonLazyBind:
558 return bitc::ATTR_KIND_NON_LAZY_BIND;
559 case Attribute::NonNull:
560 return bitc::ATTR_KIND_NON_NULL;
561 case Attribute::Dereferenceable:
562 return bitc::ATTR_KIND_DEREFERENCEABLE;
563 case Attribute::DereferenceableOrNull:
564 return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL;
565 case Attribute::NoRedZone:
566 return bitc::ATTR_KIND_NO_RED_ZONE;
567 case Attribute::NoReturn:
568 return bitc::ATTR_KIND_NO_RETURN;
569 case Attribute::NoUnwind:
570 return bitc::ATTR_KIND_NO_UNWIND;
571 case Attribute::OptimizeForSize:
572 return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
573 case Attribute::OptimizeNone:
574 return bitc::ATTR_KIND_OPTIMIZE_NONE;
575 case Attribute::ReadNone:
576 return bitc::ATTR_KIND_READ_NONE;
577 case Attribute::ReadOnly:
578 return bitc::ATTR_KIND_READ_ONLY;
579 case Attribute::Returned:
580 return bitc::ATTR_KIND_RETURNED;
581 case Attribute::ReturnsTwice:
582 return bitc::ATTR_KIND_RETURNS_TWICE;
583 case Attribute::SExt:
584 return bitc::ATTR_KIND_S_EXT;
585 case Attribute::Speculatable:
586 return bitc::ATTR_KIND_SPECULATABLE;
587 case Attribute::StackAlignment:
588 return bitc::ATTR_KIND_STACK_ALIGNMENT;
589 case Attribute::StackProtect:
590 return bitc::ATTR_KIND_STACK_PROTECT;
591 case Attribute::StackProtectReq:
592 return bitc::ATTR_KIND_STACK_PROTECT_REQ;
593 case Attribute::StackProtectStrong:
594 return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
595 case Attribute::SafeStack:
596 return bitc::ATTR_KIND_SAFESTACK;
597 case Attribute::StructRet:
598 return bitc::ATTR_KIND_STRUCT_RET;
599 case Attribute::SanitizeAddress:
600 return bitc::ATTR_KIND_SANITIZE_ADDRESS;
601 case Attribute::SanitizeThread:
602 return bitc::ATTR_KIND_SANITIZE_THREAD;
603 case Attribute::SanitizeMemory:
604 return bitc::ATTR_KIND_SANITIZE_MEMORY;
605 case Attribute::SwiftError:
606 return bitc::ATTR_KIND_SWIFT_ERROR;
607 case Attribute::SwiftSelf:
608 return bitc::ATTR_KIND_SWIFT_SELF;
609 case Attribute::UWTable:
610 return bitc::ATTR_KIND_UW_TABLE;
611 case Attribute::WriteOnly:
612 return bitc::ATTR_KIND_WRITEONLY;
613 case Attribute::ZExt:
614 return bitc::ATTR_KIND_Z_EXT;
615 case Attribute::EndAttrKinds:
616 llvm_unreachable("Can not encode end-attribute kinds marker.");
617 case Attribute::None:
618 llvm_unreachable("Can not encode none-attribute.");
621 llvm_unreachable("Trying to encode unknown attribute");
624 void ModuleBitcodeWriter::writeAttributeGroupTable() {
625 const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
626 VE.getAttributeGroups();
627 if (AttrGrps.empty()) return;
629 Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
631 SmallVector<uint64_t, 64> Record;
632 for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) {
633 unsigned AttrListIndex = Pair.first;
634 AttributeSet AS = Pair.second;
635 Record.push_back(VE.getAttributeGroupID(Pair));
636 Record.push_back(AttrListIndex);
638 for (Attribute Attr : AS) {
639 if (Attr.isEnumAttribute()) {
641 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
642 } else if (Attr.isIntAttribute()) {
644 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
645 Record.push_back(Attr.getValueAsInt());
647 StringRef Kind = Attr.getKindAsString();
648 StringRef Val = Attr.getValueAsString();
650 Record.push_back(Val.empty() ? 3 : 4);
651 Record.append(Kind.begin(), Kind.end());
654 Record.append(Val.begin(), Val.end());
660 Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
667 void ModuleBitcodeWriter::writeAttributeTable() {
668 const std::vector<AttributeList> &Attrs = VE.getAttributeLists();
669 if (Attrs.empty()) return;
671 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
673 SmallVector<uint64_t, 64> Record;
674 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
675 AttributeList AL = Attrs[i];
676 for (unsigned i = AL.index_begin(), e = AL.index_end(); i != e; ++i) {
677 AttributeSet AS = AL.getAttributes(i);
678 if (AS.hasAttributes())
679 Record.push_back(VE.getAttributeGroupID({i, AS}));
682 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
689 /// WriteTypeTable - Write out the type table for a module.
690 void ModuleBitcodeWriter::writeTypeTable() {
691 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
693 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
694 SmallVector<uint64_t, 64> TypeVals;
696 uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies();
698 // Abbrev for TYPE_CODE_POINTER.
699 auto Abbv = std::make_shared<BitCodeAbbrev>();
700 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
701 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
702 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
703 unsigned PtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
705 // Abbrev for TYPE_CODE_FUNCTION.
706 Abbv = std::make_shared<BitCodeAbbrev>();
707 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
708 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
709 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
710 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
712 unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));
714 // Abbrev for TYPE_CODE_STRUCT_ANON.
715 Abbv = std::make_shared<BitCodeAbbrev>();
716 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
717 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
718 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
719 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
721 unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));
723 // Abbrev for TYPE_CODE_STRUCT_NAME.
724 Abbv = std::make_shared<BitCodeAbbrev>();
725 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
726 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
727 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
728 unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
730 // Abbrev for TYPE_CODE_STRUCT_NAMED.
731 Abbv = std::make_shared<BitCodeAbbrev>();
732 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
733 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
734 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
735 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
737 unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));
739 // Abbrev for TYPE_CODE_ARRAY.
740 Abbv = std::make_shared<BitCodeAbbrev>();
741 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
742 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
743 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
745 unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));
747 // Emit an entry count so the reader can reserve space.
748 TypeVals.push_back(TypeList.size());
749 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
752 // Loop over all of the types, emitting each in turn.
753 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
754 Type *T = TypeList[i];
758 switch (T->getTypeID()) {
759 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
760 case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break;
761 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
762 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
763 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
764 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
765 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
766 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
767 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
768 case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break;
769 case Type::TokenTyID: Code = bitc::TYPE_CODE_TOKEN; break;
770 case Type::IntegerTyID:
772 Code = bitc::TYPE_CODE_INTEGER;
773 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
775 case Type::PointerTyID: {
776 PointerType *PTy = cast<PointerType>(T);
777 // POINTER: [pointee type, address space]
778 Code = bitc::TYPE_CODE_POINTER;
779 TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
780 unsigned AddressSpace = PTy->getAddressSpace();
781 TypeVals.push_back(AddressSpace);
782 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
785 case Type::FunctionTyID: {
786 FunctionType *FT = cast<FunctionType>(T);
787 // FUNCTION: [isvararg, retty, paramty x N]
788 Code = bitc::TYPE_CODE_FUNCTION;
789 TypeVals.push_back(FT->isVarArg());
790 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
791 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
792 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
793 AbbrevToUse = FunctionAbbrev;
796 case Type::StructTyID: {
797 StructType *ST = cast<StructType>(T);
798 // STRUCT: [ispacked, eltty x N]
799 TypeVals.push_back(ST->isPacked());
800 // Output all of the element types.
801 for (StructType::element_iterator I = ST->element_begin(),
802 E = ST->element_end(); I != E; ++I)
803 TypeVals.push_back(VE.getTypeID(*I));
805 if (ST->isLiteral()) {
806 Code = bitc::TYPE_CODE_STRUCT_ANON;
807 AbbrevToUse = StructAnonAbbrev;
809 if (ST->isOpaque()) {
810 Code = bitc::TYPE_CODE_OPAQUE;
812 Code = bitc::TYPE_CODE_STRUCT_NAMED;
813 AbbrevToUse = StructNamedAbbrev;
816 // Emit the name if it is present.
817 if (!ST->getName().empty())
818 writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
823 case Type::ArrayTyID: {
824 ArrayType *AT = cast<ArrayType>(T);
825 // ARRAY: [numelts, eltty]
826 Code = bitc::TYPE_CODE_ARRAY;
827 TypeVals.push_back(AT->getNumElements());
828 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
829 AbbrevToUse = ArrayAbbrev;
832 case Type::VectorTyID: {
833 VectorType *VT = cast<VectorType>(T);
834 // VECTOR [numelts, eltty]
835 Code = bitc::TYPE_CODE_VECTOR;
836 TypeVals.push_back(VT->getNumElements());
837 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
842 // Emit the finished record.
843 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
850 static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {
852 case GlobalValue::ExternalLinkage:
854 case GlobalValue::WeakAnyLinkage:
856 case GlobalValue::AppendingLinkage:
858 case GlobalValue::InternalLinkage:
860 case GlobalValue::LinkOnceAnyLinkage:
862 case GlobalValue::ExternalWeakLinkage:
864 case GlobalValue::CommonLinkage:
866 case GlobalValue::PrivateLinkage:
868 case GlobalValue::WeakODRLinkage:
870 case GlobalValue::LinkOnceODRLinkage:
872 case GlobalValue::AvailableExternallyLinkage:
875 llvm_unreachable("Invalid linkage");
878 static unsigned getEncodedLinkage(const GlobalValue &GV) {
879 return getEncodedLinkage(GV.getLinkage());
882 // Decode the flags for GlobalValue in the summary
883 static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags) {
884 uint64_t RawFlags = 0;
886 RawFlags |= Flags.NotEligibleToImport; // bool
887 RawFlags |= (Flags.Live << 1);
888 // Linkage don't need to be remapped at that time for the summary. Any future
889 // change to the getEncodedLinkage() function will need to be taken into
890 // account here as well.
891 RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits
896 static unsigned getEncodedVisibility(const GlobalValue &GV) {
897 switch (GV.getVisibility()) {
898 case GlobalValue::DefaultVisibility: return 0;
899 case GlobalValue::HiddenVisibility: return 1;
900 case GlobalValue::ProtectedVisibility: return 2;
902 llvm_unreachable("Invalid visibility");
905 static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
906 switch (GV.getDLLStorageClass()) {
907 case GlobalValue::DefaultStorageClass: return 0;
908 case GlobalValue::DLLImportStorageClass: return 1;
909 case GlobalValue::DLLExportStorageClass: return 2;
911 llvm_unreachable("Invalid DLL storage class");
914 static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
915 switch (GV.getThreadLocalMode()) {
916 case GlobalVariable::NotThreadLocal: return 0;
917 case GlobalVariable::GeneralDynamicTLSModel: return 1;
918 case GlobalVariable::LocalDynamicTLSModel: return 2;
919 case GlobalVariable::InitialExecTLSModel: return 3;
920 case GlobalVariable::LocalExecTLSModel: return 4;
922 llvm_unreachable("Invalid TLS model");
925 static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
926 switch (C.getSelectionKind()) {
928 return bitc::COMDAT_SELECTION_KIND_ANY;
929 case Comdat::ExactMatch:
930 return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
931 case Comdat::Largest:
932 return bitc::COMDAT_SELECTION_KIND_LARGEST;
933 case Comdat::NoDuplicates:
934 return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
935 case Comdat::SameSize:
936 return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
938 llvm_unreachable("Invalid selection kind");
941 static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) {
942 switch (GV.getUnnamedAddr()) {
943 case GlobalValue::UnnamedAddr::None: return 0;
944 case GlobalValue::UnnamedAddr::Local: return 2;
945 case GlobalValue::UnnamedAddr::Global: return 1;
947 llvm_unreachable("Invalid unnamed_addr");
950 void ModuleBitcodeWriter::writeComdats() {
951 SmallVector<unsigned, 64> Vals;
952 for (const Comdat *C : VE.getComdats()) {
953 // COMDAT: [strtab offset, strtab size, selection_kind]
954 Vals.push_back(StrtabBuilder.add(C->getName()));
955 Vals.push_back(C->getName().size());
956 Vals.push_back(getEncodedComdatSelectionKind(*C));
957 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
962 /// Write a record that will eventually hold the word offset of the
963 /// module-level VST. For now the offset is 0, which will be backpatched
964 /// after the real VST is written. Saves the bit offset to backpatch.
965 void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
966 // Write a placeholder value in for the offset of the real VST,
967 // which is written after the function blocks so that it can include
968 // the offset of each function. The placeholder offset will be
969 // updated when the real VST is written.
970 auto Abbv = std::make_shared<BitCodeAbbrev>();
971 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET));
972 // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
973 // hold the real VST offset. Must use fixed instead of VBR as we don't
974 // know how many VBR chunks to reserve ahead of time.
975 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
976 unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
978 // Emit the placeholder
979 uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0};
980 Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
982 // Compute and save the bit offset to the placeholder, which will be
983 // patched when the real VST is written. We can simply subtract the 32-bit
984 // fixed size from the current bit number to get the location to backpatch.
985 VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32;
988 enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 };
990 /// Determine the encoding to use for the given string name and length.
991 static StringEncoding getStringEncoding(StringRef Str) {
995 isChar6 = BitCodeAbbrevOp::isChar6(C);
996 if ((unsigned char)C & 128)
997 // don't bother scanning the rest.
1005 /// Emit top-level description of module, including target triple, inline asm,
1006 /// descriptors for global variables, and function prototype info.
1007 /// Returns the bit offset to backpatch with the location of the real VST.
1008 void ModuleBitcodeWriter::writeModuleInfo() {
1009 // Emit various pieces of data attached to a module.
1010 if (!M.getTargetTriple().empty())
1011 writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(),
1013 const std::string &DL = M.getDataLayoutStr();
1015 writeStringRecord(Stream, bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/);
1016 if (!M.getModuleInlineAsm().empty())
1017 writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(),
1020 // Emit information about sections and GC, computing how many there are. Also
1021 // compute the maximum alignment value.
1022 std::map<std::string, unsigned> SectionMap;
1023 std::map<std::string, unsigned> GCMap;
1024 unsigned MaxAlignment = 0;
1025 unsigned MaxGlobalType = 0;
1026 for (const GlobalValue &GV : M.globals()) {
1027 MaxAlignment = std::max(MaxAlignment, GV.getAlignment());
1028 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
1029 if (GV.hasSection()) {
1030 // Give section names unique ID's.
1031 unsigned &Entry = SectionMap[GV.getSection()];
1033 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
1035 Entry = SectionMap.size();
1039 for (const Function &F : M) {
1040 MaxAlignment = std::max(MaxAlignment, F.getAlignment());
1041 if (F.hasSection()) {
1042 // Give section names unique ID's.
1043 unsigned &Entry = SectionMap[F.getSection()];
1045 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
1047 Entry = SectionMap.size();
1051 // Same for GC names.
1052 unsigned &Entry = GCMap[F.getGC()];
1054 writeStringRecord(Stream, bitc::MODULE_CODE_GCNAME, F.getGC(),
1056 Entry = GCMap.size();
1061 // Emit abbrev for globals, now that we know # sections and max alignment.
1062 unsigned SimpleGVarAbbrev = 0;
1063 if (!M.global_empty()) {
1064 // Add an abbrev for common globals with no visibility or thread localness.
1065 auto Abbv = std::make_shared<BitCodeAbbrev>();
1066 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
1067 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1068 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1069 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1070 Log2_32_Ceil(MaxGlobalType+1)));
1071 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2
1072 //| explicitType << 1
1074 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
1075 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
1076 if (MaxAlignment == 0) // Alignment.
1077 Abbv->Add(BitCodeAbbrevOp(0));
1079 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
1080 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1081 Log2_32_Ceil(MaxEncAlignment+1)));
1083 if (SectionMap.empty()) // Section.
1084 Abbv->Add(BitCodeAbbrevOp(0));
1086 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1087 Log2_32_Ceil(SectionMap.size()+1)));
1088 // Don't bother emitting vis + thread local.
1089 SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1092 SmallVector<unsigned, 64> Vals;
1093 // Emit the module's source file name.
1095 StringEncoding Bits = getStringEncoding(M.getSourceFileName());
1096 BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
1097 if (Bits == SE_Char6)
1098 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
1099 else if (Bits == SE_Fixed7)
1100 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
1102 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
1103 auto Abbv = std::make_shared<BitCodeAbbrev>();
1104 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
1105 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1106 Abbv->Add(AbbrevOpToUse);
1107 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1109 for (const auto P : M.getSourceFileName())
1110 Vals.push_back((unsigned char)P);
1112 // Emit the finished record.
1113 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
1117 // Emit the global variable information.
1118 for (const GlobalVariable &GV : M.globals()) {
1119 unsigned AbbrevToUse = 0;
1121 // GLOBALVAR: [strtab offset, strtab size, type, isconst, initid,
1122 // linkage, alignment, section, visibility, threadlocal,
1123 // unnamed_addr, externally_initialized, dllstorageclass,
1124 // comdat, attributes]
1125 Vals.push_back(StrtabBuilder.add(GV.getName()));
1126 Vals.push_back(GV.getName().size());
1127 Vals.push_back(VE.getTypeID(GV.getValueType()));
1128 Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
1129 Vals.push_back(GV.isDeclaration() ? 0 :
1130 (VE.getValueID(GV.getInitializer()) + 1));
1131 Vals.push_back(getEncodedLinkage(GV));
1132 Vals.push_back(Log2_32(GV.getAlignment())+1);
1133 Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0);
1134 if (GV.isThreadLocal() ||
1135 GV.getVisibility() != GlobalValue::DefaultVisibility ||
1136 GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1137 GV.isExternallyInitialized() ||
1138 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
1140 GV.hasAttributes()) {
1141 Vals.push_back(getEncodedVisibility(GV));
1142 Vals.push_back(getEncodedThreadLocalMode(GV));
1143 Vals.push_back(getEncodedUnnamedAddr(GV));
1144 Vals.push_back(GV.isExternallyInitialized());
1145 Vals.push_back(getEncodedDLLStorageClass(GV));
1146 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
1148 auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
1149 Vals.push_back(VE.getAttributeListID(AL));
1151 AbbrevToUse = SimpleGVarAbbrev;
1154 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
1158 // Emit the function proto information.
1159 for (const Function &F : M) {
1160 // FUNCTION: [strtab offset, strtab size, type, callingconv, isproto,
1161 // linkage, paramattrs, alignment, section, visibility, gc,
1162 // unnamed_addr, prologuedata, dllstorageclass, comdat,
1163 // prefixdata, personalityfn]
1164 Vals.push_back(StrtabBuilder.add(F.getName()));
1165 Vals.push_back(F.getName().size());
1166 Vals.push_back(VE.getTypeID(F.getFunctionType()));
1167 Vals.push_back(F.getCallingConv());
1168 Vals.push_back(F.isDeclaration());
1169 Vals.push_back(getEncodedLinkage(F));
1170 Vals.push_back(VE.getAttributeListID(F.getAttributes()));
1171 Vals.push_back(Log2_32(F.getAlignment())+1);
1172 Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0);
1173 Vals.push_back(getEncodedVisibility(F));
1174 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
1175 Vals.push_back(getEncodedUnnamedAddr(F));
1176 Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
1178 Vals.push_back(getEncodedDLLStorageClass(F));
1179 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
1180 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
1183 F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
1185 unsigned AbbrevToUse = 0;
1186 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
1190 // Emit the alias information.
1191 for (const GlobalAlias &A : M.aliases()) {
1192 // ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage,
1193 // visibility, dllstorageclass, threadlocal, unnamed_addr]
1194 Vals.push_back(StrtabBuilder.add(A.getName()));
1195 Vals.push_back(A.getName().size());
1196 Vals.push_back(VE.getTypeID(A.getValueType()));
1197 Vals.push_back(A.getType()->getAddressSpace());
1198 Vals.push_back(VE.getValueID(A.getAliasee()));
1199 Vals.push_back(getEncodedLinkage(A));
1200 Vals.push_back(getEncodedVisibility(A));
1201 Vals.push_back(getEncodedDLLStorageClass(A));
1202 Vals.push_back(getEncodedThreadLocalMode(A));
1203 Vals.push_back(getEncodedUnnamedAddr(A));
1204 unsigned AbbrevToUse = 0;
1205 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
1209 // Emit the ifunc information.
1210 for (const GlobalIFunc &I : M.ifuncs()) {
1211 // IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver
1212 // val#, linkage, visibility]
1213 Vals.push_back(StrtabBuilder.add(I.getName()));
1214 Vals.push_back(I.getName().size());
1215 Vals.push_back(VE.getTypeID(I.getValueType()));
1216 Vals.push_back(I.getType()->getAddressSpace());
1217 Vals.push_back(VE.getValueID(I.getResolver()));
1218 Vals.push_back(getEncodedLinkage(I));
1219 Vals.push_back(getEncodedVisibility(I));
1220 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
1224 writeValueSymbolTableForwardDecl();
1227 static uint64_t getOptimizationFlags(const Value *V) {
1230 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
1231 if (OBO->hasNoSignedWrap())
1232 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
1233 if (OBO->hasNoUnsignedWrap())
1234 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
1235 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
1237 Flags |= 1 << bitc::PEO_EXACT;
1238 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
1239 if (FPMO->hasUnsafeAlgebra())
1240 Flags |= FastMathFlags::UnsafeAlgebra;
1241 if (FPMO->hasNoNaNs())
1242 Flags |= FastMathFlags::NoNaNs;
1243 if (FPMO->hasNoInfs())
1244 Flags |= FastMathFlags::NoInfs;
1245 if (FPMO->hasNoSignedZeros())
1246 Flags |= FastMathFlags::NoSignedZeros;
1247 if (FPMO->hasAllowReciprocal())
1248 Flags |= FastMathFlags::AllowReciprocal;
1249 if (FPMO->hasAllowContract())
1250 Flags |= FastMathFlags::AllowContract;
1256 void ModuleBitcodeWriter::writeValueAsMetadata(
1257 const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
1258 // Mimic an MDNode with a value as one operand.
1259 Value *V = MD->getValue();
1260 Record.push_back(VE.getTypeID(V->getType()));
1261 Record.push_back(VE.getValueID(V));
1262 Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
1266 void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N,
1267 SmallVectorImpl<uint64_t> &Record,
1269 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1270 Metadata *MD = N->getOperand(i);
1271 assert(!(MD && isa<LocalAsMetadata>(MD)) &&
1272 "Unexpected function-local metadata");
1273 Record.push_back(VE.getMetadataOrNullID(MD));
1275 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
1276 : bitc::METADATA_NODE,
1281 unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
1282 // Assume the column is usually under 128, and always output the inlined-at
1283 // location (it's never more expensive than building an array size 1).
1284 auto Abbv = std::make_shared<BitCodeAbbrev>();
1285 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
1286 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1287 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1288 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1289 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1290 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1291 return Stream.EmitAbbrev(std::move(Abbv));
1294 void ModuleBitcodeWriter::writeDILocation(const DILocation *N,
1295 SmallVectorImpl<uint64_t> &Record,
1298 Abbrev = createDILocationAbbrev();
1300 Record.push_back(N->isDistinct());
1301 Record.push_back(N->getLine());
1302 Record.push_back(N->getColumn());
1303 Record.push_back(VE.getMetadataID(N->getScope()));
1304 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
1306 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
1310 unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
1311 // Assume the column is usually under 128, and always output the inlined-at
1312 // location (it's never more expensive than building an array size 1).
1313 auto Abbv = std::make_shared<BitCodeAbbrev>();
1314 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
1315 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1316 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1317 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1318 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1319 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1320 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1321 return Stream.EmitAbbrev(std::move(Abbv));
1324 void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N,
1325 SmallVectorImpl<uint64_t> &Record,
1328 Abbrev = createGenericDINodeAbbrev();
1330 Record.push_back(N->isDistinct());
1331 Record.push_back(N->getTag());
1332 Record.push_back(0); // Per-tag version field; unused for now.
1334 for (auto &I : N->operands())
1335 Record.push_back(VE.getMetadataOrNullID(I));
1337 Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
1341 static uint64_t rotateSign(int64_t I) {
1343 return I < 0 ? ~(U << 1) : U << 1;
1346 void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N,
1347 SmallVectorImpl<uint64_t> &Record,
1349 Record.push_back(N->isDistinct());
1350 Record.push_back(N->getCount());
1351 Record.push_back(rotateSign(N->getLowerBound()));
1353 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
1357 void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,
1358 SmallVectorImpl<uint64_t> &Record,
1360 Record.push_back(N->isDistinct());
1361 Record.push_back(rotateSign(N->getValue()));
1362 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1364 Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
1368 void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N,
1369 SmallVectorImpl<uint64_t> &Record,
1371 Record.push_back(N->isDistinct());
1372 Record.push_back(N->getTag());
1373 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1374 Record.push_back(N->getSizeInBits());
1375 Record.push_back(N->getAlignInBits());
1376 Record.push_back(N->getEncoding());
1378 Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
1382 void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,
1383 SmallVectorImpl<uint64_t> &Record,
1385 Record.push_back(N->isDistinct());
1386 Record.push_back(N->getTag());
1387 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1388 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1389 Record.push_back(N->getLine());
1390 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1391 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1392 Record.push_back(N->getSizeInBits());
1393 Record.push_back(N->getAlignInBits());
1394 Record.push_back(N->getOffsetInBits());
1395 Record.push_back(N->getFlags());
1396 Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
1398 // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
1399 // that there is no DWARF address space associated with DIDerivedType.
1400 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
1401 Record.push_back(*DWARFAddressSpace + 1);
1403 Record.push_back(0);
1405 Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
1409 void ModuleBitcodeWriter::writeDICompositeType(
1410 const DICompositeType *N, SmallVectorImpl<uint64_t> &Record,
1412 const unsigned IsNotUsedInOldTypeRef = 0x2;
1413 Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct());
1414 Record.push_back(N->getTag());
1415 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1416 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1417 Record.push_back(N->getLine());
1418 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1419 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1420 Record.push_back(N->getSizeInBits());
1421 Record.push_back(N->getAlignInBits());
1422 Record.push_back(N->getOffsetInBits());
1423 Record.push_back(N->getFlags());
1424 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1425 Record.push_back(N->getRuntimeLang());
1426 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
1427 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1428 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
1430 Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
1434 void ModuleBitcodeWriter::writeDISubroutineType(
1435 const DISubroutineType *N, SmallVectorImpl<uint64_t> &Record,
1437 const unsigned HasNoOldTypeRefs = 0x2;
1438 Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
1439 Record.push_back(N->getFlags());
1440 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
1441 Record.push_back(N->getCC());
1443 Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
1447 void ModuleBitcodeWriter::writeDIFile(const DIFile *N,
1448 SmallVectorImpl<uint64_t> &Record,
1450 Record.push_back(N->isDistinct());
1451 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
1452 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
1453 Record.push_back(N->getChecksumKind());
1454 Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()));
1456 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
1460 void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
1461 SmallVectorImpl<uint64_t> &Record,
1463 assert(N->isDistinct() && "Expected distinct compile units");
1464 Record.push_back(/* IsDistinct */ true);
1465 Record.push_back(N->getSourceLanguage());
1466 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1467 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
1468 Record.push_back(N->isOptimized());
1469 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
1470 Record.push_back(N->getRuntimeVersion());
1471 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
1472 Record.push_back(N->getEmissionKind());
1473 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
1474 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
1475 Record.push_back(/* subprograms */ 0);
1476 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
1477 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
1478 Record.push_back(N->getDWOId());
1479 Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
1480 Record.push_back(N->getSplitDebugInlining());
1481 Record.push_back(N->getDebugInfoForProfiling());
1483 Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
1487 void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,
1488 SmallVectorImpl<uint64_t> &Record,
1490 uint64_t HasUnitFlag = 1 << 1;
1491 Record.push_back(N->isDistinct() | HasUnitFlag);
1492 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1493 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1494 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1495 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1496 Record.push_back(N->getLine());
1497 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1498 Record.push_back(N->isLocalToUnit());
1499 Record.push_back(N->isDefinition());
1500 Record.push_back(N->getScopeLine());
1501 Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
1502 Record.push_back(N->getVirtuality());
1503 Record.push_back(N->getVirtualIndex());
1504 Record.push_back(N->getFlags());
1505 Record.push_back(N->isOptimized());
1506 Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
1507 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1508 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
1509 Record.push_back(VE.getMetadataOrNullID(N->getVariables().get()));
1510 Record.push_back(N->getThisAdjustment());
1511 Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get()));
1513 Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
1517 void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
1518 SmallVectorImpl<uint64_t> &Record,
1520 Record.push_back(N->isDistinct());
1521 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1522 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1523 Record.push_back(N->getLine());
1524 Record.push_back(N->getColumn());
1526 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
1530 void ModuleBitcodeWriter::writeDILexicalBlockFile(
1531 const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record,
1533 Record.push_back(N->isDistinct());
1534 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1535 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1536 Record.push_back(N->getDiscriminator());
1538 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
1542 void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,
1543 SmallVectorImpl<uint64_t> &Record,
1545 Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
1546 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1547 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1549 Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
1553 void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,
1554 SmallVectorImpl<uint64_t> &Record,
1556 Record.push_back(N->isDistinct());
1557 Record.push_back(N->getMacinfoType());
1558 Record.push_back(N->getLine());
1559 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1560 Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
1562 Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
1566 void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,
1567 SmallVectorImpl<uint64_t> &Record,
1569 Record.push_back(N->isDistinct());
1570 Record.push_back(N->getMacinfoType());
1571 Record.push_back(N->getLine());
1572 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1573 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1575 Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
1579 void ModuleBitcodeWriter::writeDIModule(const DIModule *N,
1580 SmallVectorImpl<uint64_t> &Record,
1582 Record.push_back(N->isDistinct());
1583 for (auto &I : N->operands())
1584 Record.push_back(VE.getMetadataOrNullID(I));
1586 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
1590 void ModuleBitcodeWriter::writeDITemplateTypeParameter(
1591 const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record,
1593 Record.push_back(N->isDistinct());
1594 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1595 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1597 Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
1601 void ModuleBitcodeWriter::writeDITemplateValueParameter(
1602 const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record,
1604 Record.push_back(N->isDistinct());
1605 Record.push_back(N->getTag());
1606 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1607 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1608 Record.push_back(VE.getMetadataOrNullID(N->getValue()));
1610 Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
1614 void ModuleBitcodeWriter::writeDIGlobalVariable(
1615 const DIGlobalVariable *N, SmallVectorImpl<uint64_t> &Record,
1617 const uint64_t Version = 1 << 1;
1618 Record.push_back((uint64_t)N->isDistinct() | Version);
1619 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1620 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1621 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1622 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1623 Record.push_back(N->getLine());
1624 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1625 Record.push_back(N->isLocalToUnit());
1626 Record.push_back(N->isDefinition());
1627 Record.push_back(/* expr */ 0);
1628 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
1629 Record.push_back(N->getAlignInBits());
1631 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
1635 void ModuleBitcodeWriter::writeDILocalVariable(
1636 const DILocalVariable *N, SmallVectorImpl<uint64_t> &Record,
1638 // In order to support all possible bitcode formats in BitcodeReader we need
1639 // to distinguish the following cases:
1640 // 1) Record has no artificial tag (Record[1]),
1641 // has no obsolete inlinedAt field (Record[9]).
1642 // In this case Record size will be 8, HasAlignment flag is false.
1643 // 2) Record has artificial tag (Record[1]),
1644 // has no obsolete inlignedAt field (Record[9]).
1645 // In this case Record size will be 9, HasAlignment flag is false.
1646 // 3) Record has both artificial tag (Record[1]) and
1647 // obsolete inlignedAt field (Record[9]).
1648 // In this case Record size will be 10, HasAlignment flag is false.
1649 // 4) Record has neither artificial tag, nor inlignedAt field, but
1650 // HasAlignment flag is true and Record[8] contains alignment value.
1651 const uint64_t HasAlignmentFlag = 1 << 1;
1652 Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
1653 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1654 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1655 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1656 Record.push_back(N->getLine());
1657 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1658 Record.push_back(N->getArg());
1659 Record.push_back(N->getFlags());
1660 Record.push_back(N->getAlignInBits());
1662 Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
1666 void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,
1667 SmallVectorImpl<uint64_t> &Record,
1669 Record.reserve(N->getElements().size() + 1);
1670 const uint64_t Version = 3 << 1;
1671 Record.push_back((uint64_t)N->isDistinct() | Version);
1672 Record.append(N->elements_begin(), N->elements_end());
1674 Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
1678 void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
1679 const DIGlobalVariableExpression *N, SmallVectorImpl<uint64_t> &Record,
1681 Record.push_back(N->isDistinct());
1682 Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
1683 Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
1685 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR, Record, Abbrev);
1689 void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
1690 SmallVectorImpl<uint64_t> &Record,
1692 Record.push_back(N->isDistinct());
1693 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1694 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1695 Record.push_back(N->getLine());
1696 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
1697 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
1698 Record.push_back(N->getAttributes());
1699 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1701 Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
1705 void ModuleBitcodeWriter::writeDIImportedEntity(
1706 const DIImportedEntity *N, SmallVectorImpl<uint64_t> &Record,
1708 Record.push_back(N->isDistinct());
1709 Record.push_back(N->getTag());
1710 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1711 Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
1712 Record.push_back(N->getLine());
1713 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1715 Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
1719 unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
1720 auto Abbv = std::make_shared<BitCodeAbbrev>();
1721 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
1722 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1723 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1724 return Stream.EmitAbbrev(std::move(Abbv));
1727 void ModuleBitcodeWriter::writeNamedMetadata(
1728 SmallVectorImpl<uint64_t> &Record) {
1729 if (M.named_metadata_empty())
1732 unsigned Abbrev = createNamedMetadataAbbrev();
1733 for (const NamedMDNode &NMD : M.named_metadata()) {
1735 StringRef Str = NMD.getName();
1736 Record.append(Str.bytes_begin(), Str.bytes_end());
1737 Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
1740 // Write named metadata operands.
1741 for (const MDNode *N : NMD.operands())
1742 Record.push_back(VE.getMetadataID(N));
1743 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
1748 unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
1749 auto Abbv = std::make_shared<BitCodeAbbrev>();
1750 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS));
1751 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
1752 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
1753 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1754 return Stream.EmitAbbrev(std::move(Abbv));
1757 /// Write out a record for MDString.
1759 /// All the metadata strings in a metadata block are emitted in a single
1760 /// record. The sizes and strings themselves are shoved into a blob.
1761 void ModuleBitcodeWriter::writeMetadataStrings(
1762 ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) {
1763 if (Strings.empty())
1766 // Start the record with the number of strings.
1767 Record.push_back(bitc::METADATA_STRINGS);
1768 Record.push_back(Strings.size());
1770 // Emit the sizes of the strings in the blob.
1771 SmallString<256> Blob;
1773 BitstreamWriter W(Blob);
1774 for (const Metadata *MD : Strings)
1775 W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
1779 // Add the offset to the strings to the record.
1780 Record.push_back(Blob.size());
1782 // Add the strings to the blob.
1783 for (const Metadata *MD : Strings)
1784 Blob.append(cast<MDString>(MD)->getString());
1786 // Emit the final record.
1787 Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
1791 // Generates an enum to use as an index in the Abbrev array of Metadata record.
1792 enum MetadataAbbrev : unsigned {
1793 #define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
1794 #include "llvm/IR/Metadata.def"
1798 void ModuleBitcodeWriter::writeMetadataRecords(
1799 ArrayRef<const Metadata *> MDs, SmallVectorImpl<uint64_t> &Record,
1800 std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
1804 // Initialize MDNode abbreviations.
1805 #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
1806 #include "llvm/IR/Metadata.def"
1808 for (const Metadata *MD : MDs) {
1810 IndexPos->push_back(Stream.GetCurrentBitNo());
1811 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
1812 assert(N->isResolved() && "Expected forward references to be resolved");
1814 switch (N->getMetadataID()) {
1816 llvm_unreachable("Invalid MDNode subclass");
1817 #define HANDLE_MDNODE_LEAF(CLASS) \
1818 case Metadata::CLASS##Kind: \
1820 write##CLASS(cast<CLASS>(N), Record, \
1821 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
1823 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
1825 #include "llvm/IR/Metadata.def"
1828 writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
1832 void ModuleBitcodeWriter::writeModuleMetadata() {
1833 if (!VE.hasMDs() && M.named_metadata_empty())
1836 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 4);
1837 SmallVector<uint64_t, 64> Record;
1839 // Emit all abbrevs upfront, so that the reader can jump in the middle of the
1840 // block and load any metadata.
1841 std::vector<unsigned> MDAbbrevs;
1843 MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
1844 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
1845 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
1846 createGenericDINodeAbbrev();
1848 auto Abbv = std::make_shared<BitCodeAbbrev>();
1849 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX_OFFSET));
1850 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1851 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1852 unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1854 Abbv = std::make_shared<BitCodeAbbrev>();
1855 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX));
1856 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1857 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1858 unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1860 // Emit MDStrings together upfront.
1861 writeMetadataStrings(VE.getMDStrings(), Record);
1863 // We only emit an index for the metadata record if we have more than a given
1864 // (naive) threshold of metadatas, otherwise it is not worth it.
1865 if (VE.getNonMDStrings().size() > IndexThreshold) {
1866 // Write a placeholder value in for the offset of the metadata index,
1867 // which is written after the records, so that it can include
1868 // the offset of each entry. The placeholder offset will be
1869 // updated after all records are emitted.
1870 uint64_t Vals[] = {0, 0};
1871 Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
1874 // Compute and save the bit offset to the current position, which will be
1875 // patched when we emit the index later. We can simply subtract the 64-bit
1876 // fixed size from the current bit number to get the location to backpatch.
1877 uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
1879 // This index will contain the bitpos for each individual record.
1880 std::vector<uint64_t> IndexPos;
1881 IndexPos.reserve(VE.getNonMDStrings().size());
1883 // Write all the records
1884 writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
1886 if (VE.getNonMDStrings().size() > IndexThreshold) {
1887 // Now that we have emitted all the records we will emit the index. But
1889 // backpatch the forward reference so that the reader can skip the records
1891 Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
1892 Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
1894 // Delta encode the index.
1895 uint64_t PreviousValue = IndexOffsetRecordBitPos;
1896 for (auto &Elt : IndexPos) {
1897 auto EltDelta = Elt - PreviousValue;
1898 PreviousValue = Elt;
1901 // Emit the index record.
1902 Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
1906 // Write the named metadata now.
1907 writeNamedMetadata(Record);
1909 auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
1910 SmallVector<uint64_t, 4> Record;
1911 Record.push_back(VE.getValueID(&GO));
1912 pushGlobalMetadataAttachment(Record, GO);
1913 Stream.EmitRecord(bitc::METADATA_GLOBAL_DECL_ATTACHMENT, Record);
1915 for (const Function &F : M)
1916 if (F.isDeclaration() && F.hasMetadata())
1917 AddDeclAttachedMetadata(F);
1918 // FIXME: Only store metadata for declarations here, and move data for global
1919 // variable definitions to a separate block (PR28134).
1920 for (const GlobalVariable &GV : M.globals())
1921 if (GV.hasMetadata())
1922 AddDeclAttachedMetadata(GV);
1927 void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
1931 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
1932 SmallVector<uint64_t, 64> Record;
1933 writeMetadataStrings(VE.getMDStrings(), Record);
1934 writeMetadataRecords(VE.getNonMDStrings(), Record);
1938 void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
1939 SmallVectorImpl<uint64_t> &Record, const GlobalObject &GO) {
1940 // [n x [id, mdnode]]
1941 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1942 GO.getAllMetadata(MDs);
1943 for (const auto &I : MDs) {
1944 Record.push_back(I.first);
1945 Record.push_back(VE.getMetadataID(I.second));
1949 void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
1950 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
1952 SmallVector<uint64_t, 64> Record;
1954 if (F.hasMetadata()) {
1955 pushGlobalMetadataAttachment(Record, F);
1956 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
1960 // Write metadata attachments
1961 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
1962 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1963 for (const BasicBlock &BB : F)
1964 for (const Instruction &I : BB) {
1966 I.getAllMetadataOtherThanDebugLoc(MDs);
1968 // If no metadata, ignore instruction.
1969 if (MDs.empty()) continue;
1971 Record.push_back(VE.getInstructionID(&I));
1973 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
1974 Record.push_back(MDs[i].first);
1975 Record.push_back(VE.getMetadataID(MDs[i].second));
1977 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
1984 void ModuleBitcodeWriter::writeModuleMetadataKinds() {
1985 SmallVector<uint64_t, 64> Record;
1987 // Write metadata kinds
1988 // METADATA_KIND - [n x [id, name]]
1989 SmallVector<StringRef, 8> Names;
1990 M.getMDKindNames(Names);
1992 if (Names.empty()) return;
1994 Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3);
1996 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
1997 Record.push_back(MDKindID);
1998 StringRef KName = Names[MDKindID];
1999 Record.append(KName.begin(), KName.end());
2001 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
2008 void ModuleBitcodeWriter::writeOperandBundleTags() {
2009 // Write metadata kinds
2011 // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
2013 // OPERAND_BUNDLE_TAG - [strchr x N]
2015 SmallVector<StringRef, 8> Tags;
2016 M.getOperandBundleTags(Tags);
2021 Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3);
2023 SmallVector<uint64_t, 64> Record;
2025 for (auto Tag : Tags) {
2026 Record.append(Tag.begin(), Tag.end());
2028 Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
2035 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
2036 if ((int64_t)V >= 0)
2037 Vals.push_back(V << 1);
2039 Vals.push_back((-V << 1) | 1);
2042 void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
2044 if (FirstVal == LastVal) return;
2046 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
2048 unsigned AggregateAbbrev = 0;
2049 unsigned String8Abbrev = 0;
2050 unsigned CString7Abbrev = 0;
2051 unsigned CString6Abbrev = 0;
2052 // If this is a constant pool for the module, emit module-specific abbrevs.
2054 // Abbrev for CST_CODE_AGGREGATE.
2055 auto Abbv = std::make_shared<BitCodeAbbrev>();
2056 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
2057 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2058 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
2059 AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2061 // Abbrev for CST_CODE_STRING.
2062 Abbv = std::make_shared<BitCodeAbbrev>();
2063 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
2064 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2065 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2066 String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2067 // Abbrev for CST_CODE_CSTRING.
2068 Abbv = std::make_shared<BitCodeAbbrev>();
2069 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2070 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2071 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2072 CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2073 // Abbrev for CST_CODE_CSTRING.
2074 Abbv = std::make_shared<BitCodeAbbrev>();
2075 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2076 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2077 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2078 CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2081 SmallVector<uint64_t, 64> Record;
2083 const ValueEnumerator::ValueList &Vals = VE.getValues();
2084 Type *LastTy = nullptr;
2085 for (unsigned i = FirstVal; i != LastVal; ++i) {
2086 const Value *V = Vals[i].first;
2087 // If we need to switch types, do so now.
2088 if (V->getType() != LastTy) {
2089 LastTy = V->getType();
2090 Record.push_back(VE.getTypeID(LastTy));
2091 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
2092 CONSTANTS_SETTYPE_ABBREV);
2096 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
2097 Record.push_back(unsigned(IA->hasSideEffects()) |
2098 unsigned(IA->isAlignStack()) << 1 |
2099 unsigned(IA->getDialect()&1) << 2);
2101 // Add the asm string.
2102 const std::string &AsmStr = IA->getAsmString();
2103 Record.push_back(AsmStr.size());
2104 Record.append(AsmStr.begin(), AsmStr.end());
2106 // Add the constraint string.
2107 const std::string &ConstraintStr = IA->getConstraintString();
2108 Record.push_back(ConstraintStr.size());
2109 Record.append(ConstraintStr.begin(), ConstraintStr.end());
2110 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
2114 const Constant *C = cast<Constant>(V);
2115 unsigned Code = -1U;
2116 unsigned AbbrevToUse = 0;
2117 if (C->isNullValue()) {
2118 Code = bitc::CST_CODE_NULL;
2119 } else if (isa<UndefValue>(C)) {
2120 Code = bitc::CST_CODE_UNDEF;
2121 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
2122 if (IV->getBitWidth() <= 64) {
2123 uint64_t V = IV->getSExtValue();
2124 emitSignedInt64(Record, V);
2125 Code = bitc::CST_CODE_INTEGER;
2126 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
2127 } else { // Wide integers, > 64 bits in size.
2128 // We have an arbitrary precision integer value to write whose
2129 // bit width is > 64. However, in canonical unsigned integer
2130 // format it is likely that the high bits are going to be zero.
2131 // So, we only write the number of active words.
2132 unsigned NWords = IV->getValue().getActiveWords();
2133 const uint64_t *RawWords = IV->getValue().getRawData();
2134 for (unsigned i = 0; i != NWords; ++i) {
2135 emitSignedInt64(Record, RawWords[i]);
2137 Code = bitc::CST_CODE_WIDE_INTEGER;
2139 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
2140 Code = bitc::CST_CODE_FLOAT;
2141 Type *Ty = CFP->getType();
2142 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
2143 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
2144 } else if (Ty->isX86_FP80Ty()) {
2145 // api needed to prevent premature destruction
2146 // bits are not in the same order as a normal i80 APInt, compensate.
2147 APInt api = CFP->getValueAPF().bitcastToAPInt();
2148 const uint64_t *p = api.getRawData();
2149 Record.push_back((p[1] << 48) | (p[0] >> 16));
2150 Record.push_back(p[0] & 0xffffLL);
2151 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
2152 APInt api = CFP->getValueAPF().bitcastToAPInt();
2153 const uint64_t *p = api.getRawData();
2154 Record.push_back(p[0]);
2155 Record.push_back(p[1]);
2157 assert (0 && "Unknown FP type!");
2159 } else if (isa<ConstantDataSequential>(C) &&
2160 cast<ConstantDataSequential>(C)->isString()) {
2161 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
2162 // Emit constant strings specially.
2163 unsigned NumElts = Str->getNumElements();
2164 // If this is a null-terminated string, use the denser CSTRING encoding.
2165 if (Str->isCString()) {
2166 Code = bitc::CST_CODE_CSTRING;
2167 --NumElts; // Don't encode the null, which isn't allowed by char6.
2169 Code = bitc::CST_CODE_STRING;
2170 AbbrevToUse = String8Abbrev;
2172 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
2173 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
2174 for (unsigned i = 0; i != NumElts; ++i) {
2175 unsigned char V = Str->getElementAsInteger(i);
2176 Record.push_back(V);
2177 isCStr7 &= (V & 128) == 0;
2179 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
2183 AbbrevToUse = CString6Abbrev;
2185 AbbrevToUse = CString7Abbrev;
2186 } else if (const ConstantDataSequential *CDS =
2187 dyn_cast<ConstantDataSequential>(C)) {
2188 Code = bitc::CST_CODE_DATA;
2189 Type *EltTy = CDS->getType()->getElementType();
2190 if (isa<IntegerType>(EltTy)) {
2191 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2192 Record.push_back(CDS->getElementAsInteger(i));
2194 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2196 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
2198 } else if (isa<ConstantAggregate>(C)) {
2199 Code = bitc::CST_CODE_AGGREGATE;
2200 for (const Value *Op : C->operands())
2201 Record.push_back(VE.getValueID(Op));
2202 AbbrevToUse = AggregateAbbrev;
2203 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2204 switch (CE->getOpcode()) {
2206 if (Instruction::isCast(CE->getOpcode())) {
2207 Code = bitc::CST_CODE_CE_CAST;
2208 Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
2209 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2210 Record.push_back(VE.getValueID(C->getOperand(0)));
2211 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
2213 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
2214 Code = bitc::CST_CODE_CE_BINOP;
2215 Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
2216 Record.push_back(VE.getValueID(C->getOperand(0)));
2217 Record.push_back(VE.getValueID(C->getOperand(1)));
2218 uint64_t Flags = getOptimizationFlags(CE);
2220 Record.push_back(Flags);
2223 case Instruction::GetElementPtr: {
2224 Code = bitc::CST_CODE_CE_GEP;
2225 const auto *GO = cast<GEPOperator>(C);
2226 Record.push_back(VE.getTypeID(GO->getSourceElementType()));
2227 if (Optional<unsigned> Idx = GO->getInRangeIndex()) {
2228 Code = bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX;
2229 Record.push_back((*Idx << 1) | GO->isInBounds());
2230 } else if (GO->isInBounds())
2231 Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
2232 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
2233 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
2234 Record.push_back(VE.getValueID(C->getOperand(i)));
2238 case Instruction::Select:
2239 Code = bitc::CST_CODE_CE_SELECT;
2240 Record.push_back(VE.getValueID(C->getOperand(0)));
2241 Record.push_back(VE.getValueID(C->getOperand(1)));
2242 Record.push_back(VE.getValueID(C->getOperand(2)));
2244 case Instruction::ExtractElement:
2245 Code = bitc::CST_CODE_CE_EXTRACTELT;
2246 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2247 Record.push_back(VE.getValueID(C->getOperand(0)));
2248 Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
2249 Record.push_back(VE.getValueID(C->getOperand(1)));
2251 case Instruction::InsertElement:
2252 Code = bitc::CST_CODE_CE_INSERTELT;
2253 Record.push_back(VE.getValueID(C->getOperand(0)));
2254 Record.push_back(VE.getValueID(C->getOperand(1)));
2255 Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
2256 Record.push_back(VE.getValueID(C->getOperand(2)));
2258 case Instruction::ShuffleVector:
2259 // If the return type and argument types are the same, this is a
2260 // standard shufflevector instruction. If the types are different,
2261 // then the shuffle is widening or truncating the input vectors, and
2262 // the argument type must also be encoded.
2263 if (C->getType() == C->getOperand(0)->getType()) {
2264 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
2266 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
2267 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2269 Record.push_back(VE.getValueID(C->getOperand(0)));
2270 Record.push_back(VE.getValueID(C->getOperand(1)));
2271 Record.push_back(VE.getValueID(C->getOperand(2)));
2273 case Instruction::ICmp:
2274 case Instruction::FCmp:
2275 Code = bitc::CST_CODE_CE_CMP;
2276 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2277 Record.push_back(VE.getValueID(C->getOperand(0)));
2278 Record.push_back(VE.getValueID(C->getOperand(1)));
2279 Record.push_back(CE->getPredicate());
2282 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
2283 Code = bitc::CST_CODE_BLOCKADDRESS;
2284 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
2285 Record.push_back(VE.getValueID(BA->getFunction()));
2286 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
2291 llvm_unreachable("Unknown constant!");
2293 Stream.EmitRecord(Code, Record, AbbrevToUse);
2300 void ModuleBitcodeWriter::writeModuleConstants() {
2301 const ValueEnumerator::ValueList &Vals = VE.getValues();
2303 // Find the first constant to emit, which is the first non-globalvalue value.
2304 // We know globalvalues have been emitted by WriteModuleInfo.
2305 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
2306 if (!isa<GlobalValue>(Vals[i].first)) {
2307 writeConstants(i, Vals.size(), true);
2313 /// pushValueAndType - The file has to encode both the value and type id for
2314 /// many values, because we need to know what type to create for forward
2315 /// references. However, most operands are not forward references, so this type
2316 /// field is not needed.
2318 /// This function adds V's value ID to Vals. If the value ID is higher than the
2319 /// instruction ID, then it is a forward reference, and it also includes the
2320 /// type ID. The value ID that is written is encoded relative to the InstID.
2321 bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
2322 SmallVectorImpl<unsigned> &Vals) {
2323 unsigned ValID = VE.getValueID(V);
2324 // Make encoding relative to the InstID.
2325 Vals.push_back(InstID - ValID);
2326 if (ValID >= InstID) {
2327 Vals.push_back(VE.getTypeID(V->getType()));
2333 void ModuleBitcodeWriter::writeOperandBundles(ImmutableCallSite CS,
2335 SmallVector<unsigned, 64> Record;
2336 LLVMContext &C = CS.getInstruction()->getContext();
2338 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
2339 const auto &Bundle = CS.getOperandBundleAt(i);
2340 Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
2342 for (auto &Input : Bundle.Inputs)
2343 pushValueAndType(Input, InstID, Record);
2345 Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record);
2350 /// pushValue - Like pushValueAndType, but where the type of the value is
2351 /// omitted (perhaps it was already encoded in an earlier operand).
2352 void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
2353 SmallVectorImpl<unsigned> &Vals) {
2354 unsigned ValID = VE.getValueID(V);
2355 Vals.push_back(InstID - ValID);
2358 void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
2359 SmallVectorImpl<uint64_t> &Vals) {
2360 unsigned ValID = VE.getValueID(V);
2361 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
2362 emitSignedInt64(Vals, diff);
2365 /// WriteInstruction - Emit an instruction to the specified stream.
2366 void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
2368 SmallVectorImpl<unsigned> &Vals) {
2370 unsigned AbbrevToUse = 0;
2371 VE.setInstructionID(&I);
2372 switch (I.getOpcode()) {
2374 if (Instruction::isCast(I.getOpcode())) {
2375 Code = bitc::FUNC_CODE_INST_CAST;
2376 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2377 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
2378 Vals.push_back(VE.getTypeID(I.getType()));
2379 Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
2381 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
2382 Code = bitc::FUNC_CODE_INST_BINOP;
2383 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2384 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
2385 pushValue(I.getOperand(1), InstID, Vals);
2386 Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
2387 uint64_t Flags = getOptimizationFlags(&I);
2389 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
2390 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
2391 Vals.push_back(Flags);
2396 case Instruction::GetElementPtr: {
2397 Code = bitc::FUNC_CODE_INST_GEP;
2398 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
2399 auto &GEPInst = cast<GetElementPtrInst>(I);
2400 Vals.push_back(GEPInst.isInBounds());
2401 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
2402 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
2403 pushValueAndType(I.getOperand(i), InstID, Vals);
2406 case Instruction::ExtractValue: {
2407 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
2408 pushValueAndType(I.getOperand(0), InstID, Vals);
2409 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
2410 Vals.append(EVI->idx_begin(), EVI->idx_end());
2413 case Instruction::InsertValue: {
2414 Code = bitc::FUNC_CODE_INST_INSERTVAL;
2415 pushValueAndType(I.getOperand(0), InstID, Vals);
2416 pushValueAndType(I.getOperand(1), InstID, Vals);
2417 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
2418 Vals.append(IVI->idx_begin(), IVI->idx_end());
2421 case Instruction::Select:
2422 Code = bitc::FUNC_CODE_INST_VSELECT;
2423 pushValueAndType(I.getOperand(1), InstID, Vals);
2424 pushValue(I.getOperand(2), InstID, Vals);
2425 pushValueAndType(I.getOperand(0), InstID, Vals);
2427 case Instruction::ExtractElement:
2428 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
2429 pushValueAndType(I.getOperand(0), InstID, Vals);
2430 pushValueAndType(I.getOperand(1), InstID, Vals);
2432 case Instruction::InsertElement:
2433 Code = bitc::FUNC_CODE_INST_INSERTELT;
2434 pushValueAndType(I.getOperand(0), InstID, Vals);
2435 pushValue(I.getOperand(1), InstID, Vals);
2436 pushValueAndType(I.getOperand(2), InstID, Vals);
2438 case Instruction::ShuffleVector:
2439 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
2440 pushValueAndType(I.getOperand(0), InstID, Vals);
2441 pushValue(I.getOperand(1), InstID, Vals);
2442 pushValue(I.getOperand(2), InstID, Vals);
2444 case Instruction::ICmp:
2445 case Instruction::FCmp: {
2446 // compare returning Int1Ty or vector of Int1Ty
2447 Code = bitc::FUNC_CODE_INST_CMP2;
2448 pushValueAndType(I.getOperand(0), InstID, Vals);
2449 pushValue(I.getOperand(1), InstID, Vals);
2450 Vals.push_back(cast<CmpInst>(I).getPredicate());
2451 uint64_t Flags = getOptimizationFlags(&I);
2453 Vals.push_back(Flags);
2457 case Instruction::Ret:
2459 Code = bitc::FUNC_CODE_INST_RET;
2460 unsigned NumOperands = I.getNumOperands();
2461 if (NumOperands == 0)
2462 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
2463 else if (NumOperands == 1) {
2464 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2465 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
2467 for (unsigned i = 0, e = NumOperands; i != e; ++i)
2468 pushValueAndType(I.getOperand(i), InstID, Vals);
2472 case Instruction::Br:
2474 Code = bitc::FUNC_CODE_INST_BR;
2475 const BranchInst &II = cast<BranchInst>(I);
2476 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
2477 if (II.isConditional()) {
2478 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
2479 pushValue(II.getCondition(), InstID, Vals);
2483 case Instruction::Switch:
2485 Code = bitc::FUNC_CODE_INST_SWITCH;
2486 const SwitchInst &SI = cast<SwitchInst>(I);
2487 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
2488 pushValue(SI.getCondition(), InstID, Vals);
2489 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
2490 for (auto Case : SI.cases()) {
2491 Vals.push_back(VE.getValueID(Case.getCaseValue()));
2492 Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
2496 case Instruction::IndirectBr:
2497 Code = bitc::FUNC_CODE_INST_INDIRECTBR;
2498 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
2499 // Encode the address operand as relative, but not the basic blocks.
2500 pushValue(I.getOperand(0), InstID, Vals);
2501 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
2502 Vals.push_back(VE.getValueID(I.getOperand(i)));
2505 case Instruction::Invoke: {
2506 const InvokeInst *II = cast<InvokeInst>(&I);
2507 const Value *Callee = II->getCalledValue();
2508 FunctionType *FTy = II->getFunctionType();
2510 if (II->hasOperandBundles())
2511 writeOperandBundles(II, InstID);
2513 Code = bitc::FUNC_CODE_INST_INVOKE;
2515 Vals.push_back(VE.getAttributeListID(II->getAttributes()));
2516 Vals.push_back(II->getCallingConv() | 1 << 13);
2517 Vals.push_back(VE.getValueID(II->getNormalDest()));
2518 Vals.push_back(VE.getValueID(II->getUnwindDest()));
2519 Vals.push_back(VE.getTypeID(FTy));
2520 pushValueAndType(Callee, InstID, Vals);
2522 // Emit value #'s for the fixed parameters.
2523 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2524 pushValue(I.getOperand(i), InstID, Vals); // fixed param.
2526 // Emit type/value pairs for varargs params.
2527 if (FTy->isVarArg()) {
2528 for (unsigned i = FTy->getNumParams(), e = II->getNumArgOperands();
2530 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
2534 case Instruction::Resume:
2535 Code = bitc::FUNC_CODE_INST_RESUME;
2536 pushValueAndType(I.getOperand(0), InstID, Vals);
2538 case Instruction::CleanupRet: {
2539 Code = bitc::FUNC_CODE_INST_CLEANUPRET;
2540 const auto &CRI = cast<CleanupReturnInst>(I);
2541 pushValue(CRI.getCleanupPad(), InstID, Vals);
2542 if (CRI.hasUnwindDest())
2543 Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
2546 case Instruction::CatchRet: {
2547 Code = bitc::FUNC_CODE_INST_CATCHRET;
2548 const auto &CRI = cast<CatchReturnInst>(I);
2549 pushValue(CRI.getCatchPad(), InstID, Vals);
2550 Vals.push_back(VE.getValueID(CRI.getSuccessor()));
2553 case Instruction::CleanupPad:
2554 case Instruction::CatchPad: {
2555 const auto &FuncletPad = cast<FuncletPadInst>(I);
2556 Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
2557 : bitc::FUNC_CODE_INST_CLEANUPPAD;
2558 pushValue(FuncletPad.getParentPad(), InstID, Vals);
2560 unsigned NumArgOperands = FuncletPad.getNumArgOperands();
2561 Vals.push_back(NumArgOperands);
2562 for (unsigned Op = 0; Op != NumArgOperands; ++Op)
2563 pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
2566 case Instruction::CatchSwitch: {
2567 Code = bitc::FUNC_CODE_INST_CATCHSWITCH;
2568 const auto &CatchSwitch = cast<CatchSwitchInst>(I);
2570 pushValue(CatchSwitch.getParentPad(), InstID, Vals);
2572 unsigned NumHandlers = CatchSwitch.getNumHandlers();
2573 Vals.push_back(NumHandlers);
2574 for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
2575 Vals.push_back(VE.getValueID(CatchPadBB));
2577 if (CatchSwitch.hasUnwindDest())
2578 Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
2581 case Instruction::Unreachable:
2582 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
2583 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
2586 case Instruction::PHI: {
2587 const PHINode &PN = cast<PHINode>(I);
2588 Code = bitc::FUNC_CODE_INST_PHI;
2589 // With the newer instruction encoding, forward references could give
2590 // negative valued IDs. This is most common for PHIs, so we use
2592 SmallVector<uint64_t, 128> Vals64;
2593 Vals64.push_back(VE.getTypeID(PN.getType()));
2594 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
2595 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
2596 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
2598 // Emit a Vals64 vector and exit.
2599 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
2604 case Instruction::LandingPad: {
2605 const LandingPadInst &LP = cast<LandingPadInst>(I);
2606 Code = bitc::FUNC_CODE_INST_LANDINGPAD;
2607 Vals.push_back(VE.getTypeID(LP.getType()));
2608 Vals.push_back(LP.isCleanup());
2609 Vals.push_back(LP.getNumClauses());
2610 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
2612 Vals.push_back(LandingPadInst::Catch);
2614 Vals.push_back(LandingPadInst::Filter);
2615 pushValueAndType(LP.getClause(I), InstID, Vals);
2620 case Instruction::Alloca: {
2621 Code = bitc::FUNC_CODE_INST_ALLOCA;
2622 const AllocaInst &AI = cast<AllocaInst>(I);
2623 Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
2624 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
2625 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
2626 unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
2627 assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
2628 "not enough bits for maximum alignment");
2629 assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
2630 AlignRecord |= AI.isUsedWithInAlloca() << 5;
2631 AlignRecord |= 1 << 6;
2632 AlignRecord |= AI.isSwiftError() << 7;
2633 Vals.push_back(AlignRecord);
2637 case Instruction::Load:
2638 if (cast<LoadInst>(I).isAtomic()) {
2639 Code = bitc::FUNC_CODE_INST_LOADATOMIC;
2640 pushValueAndType(I.getOperand(0), InstID, Vals);
2642 Code = bitc::FUNC_CODE_INST_LOAD;
2643 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
2644 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
2646 Vals.push_back(VE.getTypeID(I.getType()));
2647 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
2648 Vals.push_back(cast<LoadInst>(I).isVolatile());
2649 if (cast<LoadInst>(I).isAtomic()) {
2650 Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
2651 Vals.push_back(getEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
2654 case Instruction::Store:
2655 if (cast<StoreInst>(I).isAtomic())
2656 Code = bitc::FUNC_CODE_INST_STOREATOMIC;
2658 Code = bitc::FUNC_CODE_INST_STORE;
2659 pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr
2660 pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val
2661 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
2662 Vals.push_back(cast<StoreInst>(I).isVolatile());
2663 if (cast<StoreInst>(I).isAtomic()) {
2664 Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
2665 Vals.push_back(getEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
2668 case Instruction::AtomicCmpXchg:
2669 Code = bitc::FUNC_CODE_INST_CMPXCHG;
2670 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2671 pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
2672 pushValue(I.getOperand(2), InstID, Vals); // newval.
2673 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
2675 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
2677 getEncodedSynchScope(cast<AtomicCmpXchgInst>(I).getSynchScope()));
2679 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
2680 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
2682 case Instruction::AtomicRMW:
2683 Code = bitc::FUNC_CODE_INST_ATOMICRMW;
2684 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2685 pushValue(I.getOperand(1), InstID, Vals); // val.
2687 getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
2688 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
2689 Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
2691 getEncodedSynchScope(cast<AtomicRMWInst>(I).getSynchScope()));
2693 case Instruction::Fence:
2694 Code = bitc::FUNC_CODE_INST_FENCE;
2695 Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
2696 Vals.push_back(getEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
2698 case Instruction::Call: {
2699 const CallInst &CI = cast<CallInst>(I);
2700 FunctionType *FTy = CI.getFunctionType();
2702 if (CI.hasOperandBundles())
2703 writeOperandBundles(&CI, InstID);
2705 Code = bitc::FUNC_CODE_INST_CALL;
2707 Vals.push_back(VE.getAttributeListID(CI.getAttributes()));
2709 unsigned Flags = getOptimizationFlags(&I);
2710 Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |
2711 unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
2712 unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
2713 1 << bitc::CALL_EXPLICIT_TYPE |
2714 unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
2715 unsigned(Flags != 0) << bitc::CALL_FMF);
2717 Vals.push_back(Flags);
2719 Vals.push_back(VE.getTypeID(FTy));
2720 pushValueAndType(CI.getCalledValue(), InstID, Vals); // Callee
2722 // Emit value #'s for the fixed parameters.
2723 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
2724 // Check for labels (can happen with asm labels).
2725 if (FTy->getParamType(i)->isLabelTy())
2726 Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
2728 pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
2731 // Emit type/value pairs for varargs params.
2732 if (FTy->isVarArg()) {
2733 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
2735 pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
2739 case Instruction::VAArg:
2740 Code = bitc::FUNC_CODE_INST_VAARG;
2741 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
2742 pushValue(I.getOperand(0), InstID, Vals); // valist.
2743 Vals.push_back(VE.getTypeID(I.getType())); // restype.
2747 Stream.EmitRecord(Code, Vals, AbbrevToUse);
2751 /// Write a GlobalValue VST to the module. The purpose of this data structure is
2752 /// to allow clients to efficiently find the function body.
2753 void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
2754 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
2755 // Get the offset of the VST we are writing, and backpatch it into
2756 // the VST forward declaration record.
2757 uint64_t VSTOffset = Stream.GetCurrentBitNo();
2758 // The BitcodeStartBit was the stream offset of the identification block.
2759 VSTOffset -= bitcodeStartBit();
2760 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
2761 // Note that we add 1 here because the offset is relative to one word
2762 // before the start of the identification block, which was historically
2763 // always the start of the regular bitcode header.
2764 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
2766 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
2768 auto Abbv = std::make_shared<BitCodeAbbrev>();
2769 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2770 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2771 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2772 unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2774 for (const Function &F : M) {
2777 if (F.isDeclaration())
2780 Record[0] = VE.getValueID(&F);
2782 // Save the word offset of the function (from the start of the
2783 // actual bitcode written to the stream).
2784 uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit();
2785 assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
2786 // Note that we add 1 here because the offset is relative to one word
2787 // before the start of the identification block, which was historically
2788 // always the start of the regular bitcode header.
2789 Record[1] = BitcodeIndex / 32 + 1;
2791 Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev);
2797 /// Emit names for arguments, instructions and basic blocks in a function.
2798 void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
2799 const ValueSymbolTable &VST) {
2803 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
2805 // FIXME: Set up the abbrev, we know how many values there are!
2806 // FIXME: We know if the type names can use 7-bit ascii.
2807 SmallVector<uint64_t, 64> NameVals;
2809 for (const ValueName &Name : VST) {
2810 // Figure out the encoding to use for the name.
2811 StringEncoding Bits = getStringEncoding(Name.getKey());
2813 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
2814 NameVals.push_back(VE.getValueID(Name.getValue()));
2816 // VST_CODE_ENTRY: [valueid, namechar x N]
2817 // VST_CODE_BBENTRY: [bbid, namechar x N]
2819 if (isa<BasicBlock>(Name.getValue())) {
2820 Code = bitc::VST_CODE_BBENTRY;
2821 if (Bits == SE_Char6)
2822 AbbrevToUse = VST_BBENTRY_6_ABBREV;
2824 Code = bitc::VST_CODE_ENTRY;
2825 if (Bits == SE_Char6)
2826 AbbrevToUse = VST_ENTRY_6_ABBREV;
2827 else if (Bits == SE_Fixed7)
2828 AbbrevToUse = VST_ENTRY_7_ABBREV;
2831 for (const auto P : Name.getKey())
2832 NameVals.push_back((unsigned char)P);
2834 // Emit the finished record.
2835 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
2842 void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
2843 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
2845 if (isa<BasicBlock>(Order.V))
2846 Code = bitc::USELIST_CODE_BB;
2848 Code = bitc::USELIST_CODE_DEFAULT;
2850 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
2851 Record.push_back(VE.getValueID(Order.V));
2852 Stream.EmitRecord(Code, Record);
2855 void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
2856 assert(VE.shouldPreserveUseListOrder() &&
2857 "Expected to be preserving use-list order");
2859 auto hasMore = [&]() {
2860 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
2866 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
2868 writeUseList(std::move(VE.UseListOrders.back()));
2869 VE.UseListOrders.pop_back();
2874 /// Emit a function body to the module stream.
2875 void ModuleBitcodeWriter::writeFunction(
2877 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
2878 // Save the bitcode index of the start of this function block for recording
2880 FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
2882 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
2883 VE.incorporateFunction(F);
2885 SmallVector<unsigned, 64> Vals;
2887 // Emit the number of basic blocks, so the reader can create them ahead of
2889 Vals.push_back(VE.getBasicBlocks().size());
2890 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
2893 // If there are function-local constants, emit them now.
2894 unsigned CstStart, CstEnd;
2895 VE.getFunctionConstantRange(CstStart, CstEnd);
2896 writeConstants(CstStart, CstEnd, false);
2898 // If there is function-local metadata, emit it now.
2899 writeFunctionMetadata(F);
2901 // Keep a running idea of what the instruction ID is.
2902 unsigned InstID = CstEnd;
2904 bool NeedsMetadataAttachment = F.hasMetadata();
2906 DILocation *LastDL = nullptr;
2907 // Finally, emit all the instructions, in order.
2908 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
2909 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
2911 writeInstruction(*I, InstID, Vals);
2913 if (!I->getType()->isVoidTy())
2916 // If the instruction has metadata, write a metadata attachment later.
2917 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
2919 // If the instruction has a debug location, emit it.
2920 DILocation *DL = I->getDebugLoc();
2925 // Just repeat the same debug loc as last time.
2926 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
2930 Vals.push_back(DL->getLine());
2931 Vals.push_back(DL->getColumn());
2932 Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
2933 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
2934 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
2940 // Emit names for all the instructions etc.
2941 if (auto *Symtab = F.getValueSymbolTable())
2942 writeFunctionLevelValueSymbolTable(*Symtab);
2944 if (NeedsMetadataAttachment)
2945 writeFunctionMetadataAttachment(F);
2946 if (VE.shouldPreserveUseListOrder())
2947 writeUseListBlock(&F);
2952 // Emit blockinfo, which defines the standard abbreviations etc.
2953 void ModuleBitcodeWriter::writeBlockInfo() {
2954 // We only want to emit block info records for blocks that have multiple
2955 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
2956 // Other blocks can define their abbrevs inline.
2957 Stream.EnterBlockInfoBlock();
2959 { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
2960 auto Abbv = std::make_shared<BitCodeAbbrev>();
2961 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
2962 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2963 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2964 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2965 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
2967 llvm_unreachable("Unexpected abbrev ordering!");
2970 { // 7-bit fixed width VST_CODE_ENTRY strings.
2971 auto Abbv = std::make_shared<BitCodeAbbrev>();
2972 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2973 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2974 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2975 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2976 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
2978 llvm_unreachable("Unexpected abbrev ordering!");
2980 { // 6-bit char6 VST_CODE_ENTRY strings.
2981 auto Abbv = std::make_shared<BitCodeAbbrev>();
2982 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2983 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2984 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2985 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2986 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
2988 llvm_unreachable("Unexpected abbrev ordering!");
2990 { // 6-bit char6 VST_CODE_BBENTRY strings.
2991 auto Abbv = std::make_shared<BitCodeAbbrev>();
2992 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
2993 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2994 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2995 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2996 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
2997 VST_BBENTRY_6_ABBREV)
2998 llvm_unreachable("Unexpected abbrev ordering!");
3003 { // SETTYPE abbrev for CONSTANTS_BLOCK.
3004 auto Abbv = std::make_shared<BitCodeAbbrev>();
3005 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
3006 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
3007 VE.computeBitsRequiredForTypeIndicies()));
3008 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3009 CONSTANTS_SETTYPE_ABBREV)
3010 llvm_unreachable("Unexpected abbrev ordering!");
3013 { // INTEGER abbrev for CONSTANTS_BLOCK.
3014 auto Abbv = std::make_shared<BitCodeAbbrev>();
3015 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
3016 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3017 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3018 CONSTANTS_INTEGER_ABBREV)
3019 llvm_unreachable("Unexpected abbrev ordering!");
3022 { // CE_CAST abbrev for CONSTANTS_BLOCK.
3023 auto Abbv = std::make_shared<BitCodeAbbrev>();
3024 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
3025 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
3026 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
3027 VE.computeBitsRequiredForTypeIndicies()));
3028 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3030 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3031 CONSTANTS_CE_CAST_Abbrev)
3032 llvm_unreachable("Unexpected abbrev ordering!");
3034 { // NULL abbrev for CONSTANTS_BLOCK.
3035 auto Abbv = std::make_shared<BitCodeAbbrev>();
3036 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
3037 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3038 CONSTANTS_NULL_Abbrev)
3039 llvm_unreachable("Unexpected abbrev ordering!");
3042 // FIXME: This should only use space for first class types!
3044 { // INST_LOAD abbrev for FUNCTION_BLOCK.
3045 auto Abbv = std::make_shared<BitCodeAbbrev>();
3046 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
3047 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
3048 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3049 VE.computeBitsRequiredForTypeIndicies()));
3050 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
3051 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
3052 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3053 FUNCTION_INST_LOAD_ABBREV)
3054 llvm_unreachable("Unexpected abbrev ordering!");
3056 { // INST_BINOP abbrev for FUNCTION_BLOCK.
3057 auto Abbv = std::make_shared<BitCodeAbbrev>();
3058 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3059 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3060 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3061 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3062 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3063 FUNCTION_INST_BINOP_ABBREV)
3064 llvm_unreachable("Unexpected abbrev ordering!");
3066 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
3067 auto Abbv = std::make_shared<BitCodeAbbrev>();
3068 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3069 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3070 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3071 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3072 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
3073 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3074 FUNCTION_INST_BINOP_FLAGS_ABBREV)
3075 llvm_unreachable("Unexpected abbrev ordering!");
3077 { // INST_CAST abbrev for FUNCTION_BLOCK.
3078 auto Abbv = std::make_shared<BitCodeAbbrev>();
3079 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
3080 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
3081 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3082 VE.computeBitsRequiredForTypeIndicies()));
3083 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3084 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3085 FUNCTION_INST_CAST_ABBREV)
3086 llvm_unreachable("Unexpected abbrev ordering!");
3089 { // INST_RET abbrev for FUNCTION_BLOCK.
3090 auto Abbv = std::make_shared<BitCodeAbbrev>();
3091 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
3092 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3093 FUNCTION_INST_RET_VOID_ABBREV)
3094 llvm_unreachable("Unexpected abbrev ordering!");
3096 { // INST_RET abbrev for FUNCTION_BLOCK.
3097 auto Abbv = std::make_shared<BitCodeAbbrev>();
3098 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
3099 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
3100 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3101 FUNCTION_INST_RET_VAL_ABBREV)
3102 llvm_unreachable("Unexpected abbrev ordering!");
3104 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
3105 auto Abbv = std::make_shared<BitCodeAbbrev>();
3106 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
3107 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3108 FUNCTION_INST_UNREACHABLE_ABBREV)
3109 llvm_unreachable("Unexpected abbrev ordering!");
3112 auto Abbv = std::make_shared<BitCodeAbbrev>();
3113 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
3114 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
3115 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3116 Log2_32_Ceil(VE.getTypes().size() + 1)));
3117 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3118 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
3119 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3120 FUNCTION_INST_GEP_ABBREV)
3121 llvm_unreachable("Unexpected abbrev ordering!");
3127 /// Write the module path strings, currently only used when generating
3128 /// a combined index file.
3129 void IndexBitcodeWriter::writeModStrings() {
3130 Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);
3132 // TODO: See which abbrev sizes we actually need to emit
3134 // 8-bit fixed-width MST_ENTRY strings.
3135 auto Abbv = std::make_shared<BitCodeAbbrev>();
3136 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3137 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3138 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3139 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
3140 unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
3142 // 7-bit fixed width MST_ENTRY strings.
3143 Abbv = std::make_shared<BitCodeAbbrev>();
3144 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3145 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3146 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3147 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
3148 unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
3150 // 6-bit char6 MST_ENTRY strings.
3151 Abbv = std::make_shared<BitCodeAbbrev>();
3152 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3153 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3154 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3155 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3156 unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
3158 // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
3159 Abbv = std::make_shared<BitCodeAbbrev>();
3160 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH));
3161 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3162 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3163 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3164 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3165 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3166 unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
3168 SmallVector<unsigned, 64> Vals;
3170 [&](const StringMapEntry<std::pair<uint64_t, ModuleHash>> &MPSE) {
3171 StringRef Key = MPSE.getKey();
3172 const auto &Value = MPSE.getValue();
3173 StringEncoding Bits = getStringEncoding(Key);
3174 unsigned AbbrevToUse = Abbrev8Bit;
3175 if (Bits == SE_Char6)
3176 AbbrevToUse = Abbrev6Bit;
3177 else if (Bits == SE_Fixed7)
3178 AbbrevToUse = Abbrev7Bit;
3180 Vals.push_back(Value.first);
3181 Vals.append(Key.begin(), Key.end());
3183 // Emit the finished record.
3184 Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
3186 // Emit an optional hash for the module now
3187 const auto &Hash = Value.second;
3188 if (llvm::any_of(Hash, [](uint32_t H) { return H; })) {
3189 Vals.assign(Hash.begin(), Hash.end());
3190 // Emit the hash record.
3191 Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
3199 /// Write the function type metadata related records that need to appear before
3200 /// a function summary entry (whether per-module or combined).
3201 static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream,
3202 FunctionSummary *FS) {
3203 if (!FS->type_tests().empty())
3204 Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
3206 SmallVector<uint64_t, 64> Record;
3208 auto WriteVFuncIdVec = [&](uint64_t Ty,
3209 ArrayRef<FunctionSummary::VFuncId> VFs) {
3213 for (auto &VF : VFs) {
3214 Record.push_back(VF.GUID);
3215 Record.push_back(VF.Offset);
3217 Stream.EmitRecord(Ty, Record);
3220 WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
3221 FS->type_test_assume_vcalls());
3222 WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
3223 FS->type_checked_load_vcalls());
3225 auto WriteConstVCallVec = [&](uint64_t Ty,
3226 ArrayRef<FunctionSummary::ConstVCall> VCs) {
3227 for (auto &VC : VCs) {
3229 Record.push_back(VC.VFunc.GUID);
3230 Record.push_back(VC.VFunc.Offset);
3231 Record.insert(Record.end(), VC.Args.begin(), VC.Args.end());
3232 Stream.EmitRecord(Ty, Record);
3236 WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
3237 FS->type_test_assume_const_vcalls());
3238 WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
3239 FS->type_checked_load_const_vcalls());
3242 // Helper to emit a single function summary record.
3243 void ModuleBitcodeWriter::writePerModuleFunctionSummaryRecord(
3244 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
3245 unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
3246 const Function &F) {
3247 NameVals.push_back(ValueID);
3249 FunctionSummary *FS = cast<FunctionSummary>(Summary);
3250 writeFunctionTypeMetadataRecords(Stream, FS);
3252 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
3253 NameVals.push_back(FS->instCount());
3254 NameVals.push_back(FS->refs().size());
3256 for (auto &RI : FS->refs())
3257 NameVals.push_back(VE.getValueID(RI.getValue()));
3259 bool HasProfileData = F.getEntryCount().hasValue();
3260 for (auto &ECI : FS->calls()) {
3261 NameVals.push_back(getValueId(ECI.first));
3263 NameVals.push_back(static_cast<uint8_t>(ECI.second.Hotness));
3266 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3268 (HasProfileData ? bitc::FS_PERMODULE_PROFILE : bitc::FS_PERMODULE);
3270 // Emit the finished record.
3271 Stream.EmitRecord(Code, NameVals, FSAbbrev);
3275 // Collect the global value references in the given variable's initializer,
3276 // and emit them in a summary record.
3277 void ModuleBitcodeWriter::writeModuleLevelReferences(
3278 const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
3279 unsigned FSModRefsAbbrev) {
3280 auto VI = Index->getValueInfo(GlobalValue::getGUID(V.getName()));
3281 if (!VI || VI.getSummaryList().empty()) {
3282 // Only declarations should not have a summary (a declaration might however
3283 // have a summary if the def was in module level asm).
3284 assert(V.isDeclaration());
3287 auto *Summary = VI.getSummaryList()[0].get();
3288 NameVals.push_back(VE.getValueID(&V));
3289 GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
3290 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
3292 unsigned SizeBeforeRefs = NameVals.size();
3293 for (auto &RI : VS->refs())
3294 NameVals.push_back(VE.getValueID(RI.getValue()));
3295 // Sort the refs for determinism output, the vector returned by FS->refs() has
3296 // been initialized from a DenseSet.
3297 std::sort(NameVals.begin() + SizeBeforeRefs, NameVals.end());
3299 Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals,
3304 // Current version for the summary.
3305 // This is bumped whenever we introduce changes in the way some record are
3306 // interpreted, like flags for instance.
3307 static const uint64_t INDEX_VERSION = 3;
3309 /// Emit the per-module summary section alongside the rest of
3310 /// the module's bitcode.
3311 void ModuleBitcodeWriter::writePerModuleGlobalValueSummary() {
3312 // By default we compile with ThinLTO if the module has a summary, but the
3313 // client can request full LTO with a module flag.
3314 bool IsThinLTO = true;
3316 mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
3317 IsThinLTO = MD->getZExtValue();
3318 Stream.EnterSubblock(IsThinLTO ? bitc::GLOBALVAL_SUMMARY_BLOCK_ID
3319 : bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID,
3322 Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
3324 if (Index->begin() == Index->end()) {
3329 for (const auto &GVI : valueIds()) {
3330 Stream.EmitRecord(bitc::FS_VALUE_GUID,
3331 ArrayRef<uint64_t>{GVI.second, GVI.first});
3334 // Abbrev for FS_PERMODULE.
3335 auto Abbv = std::make_shared<BitCodeAbbrev>();
3336 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE));
3337 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3338 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3339 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3340 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3341 // numrefs x valueid, n x (valueid)
3342 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3343 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3344 unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3346 // Abbrev for FS_PERMODULE_PROFILE.
3347 Abbv = std::make_shared<BitCodeAbbrev>();
3348 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));
3349 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3350 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3351 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3352 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3353 // numrefs x valueid, n x (valueid, hotness)
3354 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3355 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3356 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3358 // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
3359 Abbv = std::make_shared<BitCodeAbbrev>();
3360 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));
3361 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3362 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3363 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
3364 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3365 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3367 // Abbrev for FS_ALIAS.
3368 Abbv = std::make_shared<BitCodeAbbrev>();
3369 Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
3370 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3371 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3372 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3373 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3375 SmallVector<uint64_t, 64> NameVals;
3376 // Iterate over the list of functions instead of the Index to
3377 // ensure the ordering is stable.
3378 for (const Function &F : M) {
3379 // Summary emission does not support anonymous functions, they have to
3380 // renamed using the anonymous function renaming pass.
3382 report_fatal_error("Unexpected anonymous function when writing summary");
3384 ValueInfo VI = Index->getValueInfo(GlobalValue::getGUID(F.getName()));
3385 if (!VI || VI.getSummaryList().empty()) {
3386 // Only declarations should not have a summary (a declaration might
3387 // however have a summary if the def was in module level asm).
3388 assert(F.isDeclaration());
3391 auto *Summary = VI.getSummaryList()[0].get();
3392 writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.getValueID(&F),
3393 FSCallsAbbrev, FSCallsProfileAbbrev, F);
3396 // Capture references from GlobalVariable initializers, which are outside
3397 // of a function scope.
3398 for (const GlobalVariable &G : M.globals())
3399 writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev);
3401 for (const GlobalAlias &A : M.aliases()) {
3402 auto *Aliasee = A.getBaseObject();
3403 if (!Aliasee->hasName())
3404 // Nameless function don't have an entry in the summary, skip it.
3406 auto AliasId = VE.getValueID(&A);
3407 auto AliaseeId = VE.getValueID(Aliasee);
3408 NameVals.push_back(AliasId);
3409 auto *Summary = Index->getGlobalValueSummary(A);
3410 AliasSummary *AS = cast<AliasSummary>(Summary);
3411 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
3412 NameVals.push_back(AliaseeId);
3413 Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
3420 /// Emit the combined summary section into the combined index file.
3421 void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
3422 Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3);
3423 Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
3425 for (const auto &GVI : valueIds()) {
3426 Stream.EmitRecord(bitc::FS_VALUE_GUID,
3427 ArrayRef<uint64_t>{GVI.second, GVI.first});
3430 // Abbrev for FS_COMBINED.
3431 auto Abbv = std::make_shared<BitCodeAbbrev>();
3432 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED));
3433 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3434 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
3435 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3436 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3437 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3438 // numrefs x valueid, n x (valueid)
3439 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3440 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3441 unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3443 // Abbrev for FS_COMBINED_PROFILE.
3444 Abbv = std::make_shared<BitCodeAbbrev>();
3445 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));
3446 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3447 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
3448 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3449 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3450 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3451 // numrefs x valueid, n x (valueid, hotness)
3452 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3453 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3454 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3456 // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
3457 Abbv = std::make_shared<BitCodeAbbrev>();
3458 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));
3459 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3460 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
3461 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3462 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
3463 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3464 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3466 // Abbrev for FS_COMBINED_ALIAS.
3467 Abbv = std::make_shared<BitCodeAbbrev>();
3468 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS));
3469 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3470 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
3471 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3472 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3473 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3475 // The aliases are emitted as a post-pass, and will point to the value
3476 // id of the aliasee. Save them in a vector for post-processing.
3477 SmallVector<AliasSummary *, 64> Aliases;
3479 // Save the value id for each summary for alias emission.
3480 DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
3482 SmallVector<uint64_t, 64> NameVals;
3484 // For local linkage, we also emit the original name separately
3485 // immediately after the record.
3486 auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
3487 if (!GlobalValue::isLocalLinkage(S.linkage()))
3489 NameVals.push_back(S.getOriginalName());
3490 Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals);
3494 forEachSummary([&](GVInfo I) {
3495 GlobalValueSummary *S = I.second;
3498 auto ValueId = getValueId(I.first);
3500 SummaryToValueIdMap[S] = *ValueId;
3502 if (auto *AS = dyn_cast<AliasSummary>(S)) {
3503 // Will process aliases as a post-pass because the reader wants all
3504 // global to be loaded first.
3505 Aliases.push_back(AS);
3509 if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
3510 NameVals.push_back(*ValueId);
3511 NameVals.push_back(Index.getModuleId(VS->modulePath()));
3512 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
3513 for (auto &RI : VS->refs()) {
3514 auto RefValueId = getValueId(RI.getGUID());
3517 NameVals.push_back(*RefValueId);
3520 // Emit the finished record.
3521 Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals,
3524 MaybeEmitOriginalName(*S);
3528 auto *FS = cast<FunctionSummary>(S);
3529 writeFunctionTypeMetadataRecords(Stream, FS);
3531 NameVals.push_back(*ValueId);
3532 NameVals.push_back(Index.getModuleId(FS->modulePath()));
3533 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
3534 NameVals.push_back(FS->instCount());
3536 NameVals.push_back(0);
3539 for (auto &RI : FS->refs()) {
3540 auto RefValueId = getValueId(RI.getGUID());
3543 NameVals.push_back(*RefValueId);
3546 NameVals[4] = Count;
3548 bool HasProfileData = false;
3549 for (auto &EI : FS->calls()) {
3550 HasProfileData |= EI.second.Hotness != CalleeInfo::HotnessType::Unknown;
3555 for (auto &EI : FS->calls()) {
3556 // If this GUID doesn't have a value id, it doesn't have a function
3557 // summary and we don't need to record any calls to it.
3558 GlobalValue::GUID GUID = EI.first.getGUID();
3559 auto CallValueId = getValueId(GUID);
3561 // For SamplePGO, the indirect call targets for local functions will
3562 // have its original name annotated in profile. We try to find the
3563 // corresponding PGOFuncName as the GUID.
3564 GUID = Index.getGUIDFromOriginalID(GUID);
3567 CallValueId = getValueId(GUID);
3571 NameVals.push_back(*CallValueId);
3573 NameVals.push_back(static_cast<uint8_t>(EI.second.Hotness));
3576 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3578 (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED);
3580 // Emit the finished record.
3581 Stream.EmitRecord(Code, NameVals, FSAbbrev);
3583 MaybeEmitOriginalName(*S);
3586 for (auto *AS : Aliases) {
3587 auto AliasValueId = SummaryToValueIdMap[AS];
3588 assert(AliasValueId);
3589 NameVals.push_back(AliasValueId);
3590 NameVals.push_back(Index.getModuleId(AS->modulePath()));
3591 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
3592 auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()];
3593 assert(AliaseeValueId);
3594 NameVals.push_back(AliaseeValueId);
3596 // Emit the finished record.
3597 Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
3599 MaybeEmitOriginalName(*AS);
3602 if (!Index.cfiFunctionDefs().empty()) {
3603 for (auto &S : Index.cfiFunctionDefs()) {
3604 NameVals.push_back(StrtabBuilder.add(S));
3605 NameVals.push_back(S.size());
3607 Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DEFS, NameVals);
3611 if (!Index.cfiFunctionDecls().empty()) {
3612 for (auto &S : Index.cfiFunctionDecls()) {
3613 NameVals.push_back(StrtabBuilder.add(S));
3614 NameVals.push_back(S.size());
3616 Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DECLS, NameVals);
3623 /// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
3624 /// current llvm version, and a record for the epoch number.
3625 static void writeIdentificationBlock(BitstreamWriter &Stream) {
3626 Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);
3628 // Write the "user readable" string identifying the bitcode producer
3629 auto Abbv = std::make_shared<BitCodeAbbrev>();
3630 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING));
3631 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3632 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3633 auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3634 writeStringRecord(Stream, bitc::IDENTIFICATION_CODE_STRING,
3635 "LLVM" LLVM_VERSION_STRING, StringAbbrev);
3637 // Write the epoch version
3638 Abbv = std::make_shared<BitCodeAbbrev>();
3639 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH));
3640 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
3641 auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3642 SmallVector<unsigned, 1> Vals = {bitc::BITCODE_CURRENT_EPOCH};
3643 Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
3647 void ModuleBitcodeWriter::writeModuleHash(size_t BlockStartPos) {
3648 // Emit the module's hash.
3649 // MODULE_CODE_HASH: [5*i32]
3653 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&(Buffer)[BlockStartPos],
3654 Buffer.size() - BlockStartPos));
3655 StringRef Hash = Hasher.result();
3656 for (int Pos = 0; Pos < 20; Pos += 4) {
3657 Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);
3660 // Emit the finished record.
3661 Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
3664 // Save the written hash value.
3665 std::copy(std::begin(Vals), std::end(Vals), std::begin(*ModHash));
3667 Stream.EmitRecord(bitc::MODULE_CODE_HASH, ArrayRef<uint32_t>(*ModHash));
3670 void ModuleBitcodeWriter::write() {
3671 writeIdentificationBlock(Stream);
3673 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
3674 size_t BlockStartPos = Buffer.size();
3676 writeModuleVersion();
3678 // Emit blockinfo, which defines the standard abbreviations etc.
3681 // Emit information about attribute groups.
3682 writeAttributeGroupTable();
3684 // Emit information about parameter attributes.
3685 writeAttributeTable();
3687 // Emit information describing all of the types in the module.
3692 // Emit top-level description of module, including target triple, inline asm,
3693 // descriptors for global variables, and function prototype info.
3697 writeModuleConstants();
3699 // Emit metadata kind names.
3700 writeModuleMetadataKinds();
3703 writeModuleMetadata();
3705 // Emit module-level use-lists.
3706 if (VE.shouldPreserveUseListOrder())
3707 writeUseListBlock(nullptr);
3709 writeOperandBundleTags();
3711 // Emit function bodies.
3712 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
3713 for (Module::const_iterator F = M.begin(), E = M.end(); F != E; ++F)
3714 if (!F->isDeclaration())
3715 writeFunction(*F, FunctionToBitcodeIndex);
3717 // Need to write after the above call to WriteFunction which populates
3718 // the summary information in the index.
3720 writePerModuleGlobalValueSummary();
3722 writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
3724 writeModuleHash(BlockStartPos);
3729 static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
3730 uint32_t &Position) {
3731 support::endian::write32le(&Buffer[Position], Value);
3735 /// If generating a bc file on darwin, we have to emit a
3736 /// header and trailer to make it compatible with the system archiver. To do
3737 /// this we emit the following header, and then emit a trailer that pads the
3738 /// file out to be a multiple of 16 bytes.
3740 /// struct bc_header {
3741 /// uint32_t Magic; // 0x0B17C0DE
3742 /// uint32_t Version; // Version, currently always 0.
3743 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
3744 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
3745 /// uint32_t CPUType; // CPU specifier.
3746 /// ... potentially more later ...
3748 static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
3750 unsigned CPUType = ~0U;
3752 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
3753 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
3754 // number from /usr/include/mach/machine.h. It is ok to reproduce the
3755 // specific constants here because they are implicitly part of the Darwin ABI.
3757 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
3758 DARWIN_CPU_TYPE_X86 = 7,
3759 DARWIN_CPU_TYPE_ARM = 12,
3760 DARWIN_CPU_TYPE_POWERPC = 18
3763 Triple::ArchType Arch = TT.getArch();
3764 if (Arch == Triple::x86_64)
3765 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
3766 else if (Arch == Triple::x86)
3767 CPUType = DARWIN_CPU_TYPE_X86;
3768 else if (Arch == Triple::ppc)
3769 CPUType = DARWIN_CPU_TYPE_POWERPC;
3770 else if (Arch == Triple::ppc64)
3771 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
3772 else if (Arch == Triple::arm || Arch == Triple::thumb)
3773 CPUType = DARWIN_CPU_TYPE_ARM;
3775 // Traditional Bitcode starts after header.
3776 assert(Buffer.size() >= BWH_HeaderSize &&
3777 "Expected header size to be reserved");
3778 unsigned BCOffset = BWH_HeaderSize;
3779 unsigned BCSize = Buffer.size() - BWH_HeaderSize;
3781 // Write the magic and version.
3782 unsigned Position = 0;
3783 writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
3784 writeInt32ToBuffer(0, Buffer, Position); // Version.
3785 writeInt32ToBuffer(BCOffset, Buffer, Position);
3786 writeInt32ToBuffer(BCSize, Buffer, Position);
3787 writeInt32ToBuffer(CPUType, Buffer, Position);
3789 // If the file is not a multiple of 16 bytes, insert dummy padding.
3790 while (Buffer.size() & 15)
3791 Buffer.push_back(0);
3794 /// Helper to write the header common to all bitcode files.
3795 static void writeBitcodeHeader(BitstreamWriter &Stream) {
3796 // Emit the file header.
3797 Stream.Emit((unsigned)'B', 8);
3798 Stream.Emit((unsigned)'C', 8);
3799 Stream.Emit(0x0, 4);
3800 Stream.Emit(0xC, 4);
3801 Stream.Emit(0xE, 4);
3802 Stream.Emit(0xD, 4);
3805 BitcodeWriter::BitcodeWriter(SmallVectorImpl<char> &Buffer)
3806 : Buffer(Buffer), Stream(new BitstreamWriter(Buffer)) {
3807 writeBitcodeHeader(*Stream);
3810 BitcodeWriter::~BitcodeWriter() { assert(WroteStrtab); }
3812 void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) {
3813 Stream->EnterSubblock(Block, 3);
3815 auto Abbv = std::make_shared<BitCodeAbbrev>();
3816 Abbv->Add(BitCodeAbbrevOp(Record));
3817 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3818 auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv));
3820 Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob);
3822 Stream->ExitBlock();
3825 void BitcodeWriter::writeSymtab() {
3826 assert(!WroteStrtab && !WroteSymtab);
3828 // If any module has module-level inline asm, we will require a registered asm
3829 // parser for the target so that we can create an accurate symbol table for
3831 for (Module *M : Mods) {
3832 if (M->getModuleInlineAsm().empty())
3836 const Triple TT(M->getTargetTriple());
3837 const Target *T = TargetRegistry::lookupTarget(TT.str(), Err);
3838 if (!T || !T->hasMCAsmParser())
3843 SmallVector<char, 0> Symtab;
3844 // The irsymtab::build function may be unable to create a symbol table if the
3845 // module is malformed (e.g. it contains an invalid alias). Writing a symbol
3846 // table is not required for correctness, but we still want to be able to
3847 // write malformed modules to bitcode files, so swallow the error.
3848 if (Error E = irsymtab::build(Mods, Symtab, StrtabBuilder, Alloc)) {
3849 consumeError(std::move(E));
3853 writeBlob(bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB,
3854 {Symtab.data(), Symtab.size()});
3857 void BitcodeWriter::writeStrtab() {
3858 assert(!WroteStrtab);
3860 std::vector<char> Strtab;
3861 StrtabBuilder.finalizeInOrder();
3862 Strtab.resize(StrtabBuilder.getSize());
3863 StrtabBuilder.write((uint8_t *)Strtab.data());
3865 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB,
3866 {Strtab.data(), Strtab.size()});
3871 void BitcodeWriter::copyStrtab(StringRef Strtab) {
3872 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab);
3876 void BitcodeWriter::writeModule(const Module *M,
3877 bool ShouldPreserveUseListOrder,
3878 const ModuleSummaryIndex *Index,
3879 bool GenerateHash, ModuleHash *ModHash) {
3880 assert(!WroteStrtab);
3882 // The Mods vector is used by irsymtab::build, which requires non-const
3883 // Modules in case it needs to materialize metadata. But the bitcode writer
3884 // requires that the module is materialized, so we can cast to non-const here,
3885 // after checking that it is in fact materialized.
3886 assert(M->isMaterialized());
3887 Mods.push_back(const_cast<Module *>(M));
3889 ModuleBitcodeWriter ModuleWriter(M, Buffer, StrtabBuilder, *Stream,
3890 ShouldPreserveUseListOrder, Index,
3891 GenerateHash, ModHash);
3892 ModuleWriter.write();
3895 void BitcodeWriter::writeIndex(
3896 const ModuleSummaryIndex *Index,
3897 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
3898 IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index,
3899 ModuleToSummariesForIndex);
3900 IndexWriter.write();
3903 /// WriteBitcodeToFile - Write the specified module to the specified output
3905 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out,
3906 bool ShouldPreserveUseListOrder,
3907 const ModuleSummaryIndex *Index,
3908 bool GenerateHash, ModuleHash *ModHash) {
3909 SmallVector<char, 0> Buffer;
3910 Buffer.reserve(256*1024);
3912 // If this is darwin or another generic macho target, reserve space for the
3914 Triple TT(M->getTargetTriple());
3915 if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
3916 Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
3918 BitcodeWriter Writer(Buffer);
3919 Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
3921 Writer.writeSymtab();
3922 Writer.writeStrtab();
3924 if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
3925 emitDarwinBCHeaderAndTrailer(Buffer, TT);
3927 // Write the generated bitstream to "Out".
3928 Out.write((char*)&Buffer.front(), Buffer.size());
3931 void IndexBitcodeWriter::write() {
3932 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
3934 writeModuleVersion();
3936 // Write the module paths in the combined index.
3939 // Write the summary combined index records.
3940 writeCombinedGlobalValueSummary();
3945 // Write the specified module summary index to the given raw output stream,
3946 // where it will be written in a new bitcode block. This is used when
3947 // writing the combined index file for ThinLTO. When writing a subset of the
3948 // index for a distributed backend, provide a \p ModuleToSummariesForIndex map.
3949 void llvm::WriteIndexToFile(
3950 const ModuleSummaryIndex &Index, raw_ostream &Out,
3951 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
3952 SmallVector<char, 0> Buffer;
3953 Buffer.reserve(256 * 1024);
3955 BitcodeWriter Writer(Buffer);
3956 Writer.writeIndex(&Index, ModuleToSummariesForIndex);
3957 Writer.writeStrtab();
3959 Out.write((char *)&Buffer.front(), Buffer.size());