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/ReaderWriter.h"
15 #include "ValueEnumerator.h"
16 #include "llvm/ADT/STLExtras.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/IntrinsicInst.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/Operator.h"
30 #include "llvm/IR/UseListOrder.h"
31 #include "llvm/IR/ValueSymbolTable.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/Program.h"
36 #include "llvm/Support/raw_ostream.h"
41 /// These are manifest constants used by the bitcode writer. They do not need to
42 /// be kept in sync with the reader, but need to be consistent within this file.
44 // VALUE_SYMTAB_BLOCK abbrev id's.
45 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
50 // CONSTANTS_BLOCK abbrev id's.
51 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
52 CONSTANTS_INTEGER_ABBREV,
53 CONSTANTS_CE_CAST_Abbrev,
54 CONSTANTS_NULL_Abbrev,
56 // FUNCTION_BLOCK abbrev id's.
57 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
58 FUNCTION_INST_BINOP_ABBREV,
59 FUNCTION_INST_BINOP_FLAGS_ABBREV,
60 FUNCTION_INST_CAST_ABBREV,
61 FUNCTION_INST_RET_VOID_ABBREV,
62 FUNCTION_INST_RET_VAL_ABBREV,
63 FUNCTION_INST_UNREACHABLE_ABBREV,
64 FUNCTION_INST_GEP_ABBREV,
67 static unsigned GetEncodedCastOpcode(unsigned Opcode) {
69 default: llvm_unreachable("Unknown cast instruction!");
70 case Instruction::Trunc : return bitc::CAST_TRUNC;
71 case Instruction::ZExt : return bitc::CAST_ZEXT;
72 case Instruction::SExt : return bitc::CAST_SEXT;
73 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
74 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
75 case Instruction::UIToFP : return bitc::CAST_UITOFP;
76 case Instruction::SIToFP : return bitc::CAST_SITOFP;
77 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
78 case Instruction::FPExt : return bitc::CAST_FPEXT;
79 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
80 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
81 case Instruction::BitCast : return bitc::CAST_BITCAST;
82 case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
86 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
88 default: llvm_unreachable("Unknown binary instruction!");
89 case Instruction::Add:
90 case Instruction::FAdd: return bitc::BINOP_ADD;
91 case Instruction::Sub:
92 case Instruction::FSub: return bitc::BINOP_SUB;
93 case Instruction::Mul:
94 case Instruction::FMul: return bitc::BINOP_MUL;
95 case Instruction::UDiv: return bitc::BINOP_UDIV;
96 case Instruction::FDiv:
97 case Instruction::SDiv: return bitc::BINOP_SDIV;
98 case Instruction::URem: return bitc::BINOP_UREM;
99 case Instruction::FRem:
100 case Instruction::SRem: return bitc::BINOP_SREM;
101 case Instruction::Shl: return bitc::BINOP_SHL;
102 case Instruction::LShr: return bitc::BINOP_LSHR;
103 case Instruction::AShr: return bitc::BINOP_ASHR;
104 case Instruction::And: return bitc::BINOP_AND;
105 case Instruction::Or: return bitc::BINOP_OR;
106 case Instruction::Xor: return bitc::BINOP_XOR;
110 static unsigned GetEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
112 default: llvm_unreachable("Unknown RMW operation!");
113 case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
114 case AtomicRMWInst::Add: return bitc::RMW_ADD;
115 case AtomicRMWInst::Sub: return bitc::RMW_SUB;
116 case AtomicRMWInst::And: return bitc::RMW_AND;
117 case AtomicRMWInst::Nand: return bitc::RMW_NAND;
118 case AtomicRMWInst::Or: return bitc::RMW_OR;
119 case AtomicRMWInst::Xor: return bitc::RMW_XOR;
120 case AtomicRMWInst::Max: return bitc::RMW_MAX;
121 case AtomicRMWInst::Min: return bitc::RMW_MIN;
122 case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
123 case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
127 static unsigned GetEncodedOrdering(AtomicOrdering Ordering) {
129 case NotAtomic: return bitc::ORDERING_NOTATOMIC;
130 case Unordered: return bitc::ORDERING_UNORDERED;
131 case Monotonic: return bitc::ORDERING_MONOTONIC;
132 case Acquire: return bitc::ORDERING_ACQUIRE;
133 case Release: return bitc::ORDERING_RELEASE;
134 case AcquireRelease: return bitc::ORDERING_ACQREL;
135 case SequentiallyConsistent: return bitc::ORDERING_SEQCST;
137 llvm_unreachable("Invalid ordering");
140 static unsigned GetEncodedSynchScope(SynchronizationScope SynchScope) {
141 switch (SynchScope) {
142 case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD;
143 case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD;
145 llvm_unreachable("Invalid synch scope");
148 static void WriteStringRecord(unsigned Code, StringRef Str,
149 unsigned AbbrevToUse, BitstreamWriter &Stream) {
150 SmallVector<unsigned, 64> Vals;
152 // Code: [strchar x N]
153 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
154 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
156 Vals.push_back(Str[i]);
159 // Emit the finished record.
160 Stream.EmitRecord(Code, Vals, AbbrevToUse);
163 static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
165 case Attribute::Alignment:
166 return bitc::ATTR_KIND_ALIGNMENT;
167 case Attribute::AlwaysInline:
168 return bitc::ATTR_KIND_ALWAYS_INLINE;
169 case Attribute::ArgMemOnly:
170 return bitc::ATTR_KIND_ARGMEMONLY;
171 case Attribute::Builtin:
172 return bitc::ATTR_KIND_BUILTIN;
173 case Attribute::ByVal:
174 return bitc::ATTR_KIND_BY_VAL;
175 case Attribute::Convergent:
176 return bitc::ATTR_KIND_CONVERGENT;
177 case Attribute::InAlloca:
178 return bitc::ATTR_KIND_IN_ALLOCA;
179 case Attribute::Cold:
180 return bitc::ATTR_KIND_COLD;
181 case Attribute::InlineHint:
182 return bitc::ATTR_KIND_INLINE_HINT;
183 case Attribute::InReg:
184 return bitc::ATTR_KIND_IN_REG;
185 case Attribute::JumpTable:
186 return bitc::ATTR_KIND_JUMP_TABLE;
187 case Attribute::MinSize:
188 return bitc::ATTR_KIND_MIN_SIZE;
189 case Attribute::Naked:
190 return bitc::ATTR_KIND_NAKED;
191 case Attribute::Nest:
192 return bitc::ATTR_KIND_NEST;
193 case Attribute::NoAlias:
194 return bitc::ATTR_KIND_NO_ALIAS;
195 case Attribute::NoBuiltin:
196 return bitc::ATTR_KIND_NO_BUILTIN;
197 case Attribute::NoCapture:
198 return bitc::ATTR_KIND_NO_CAPTURE;
199 case Attribute::NoDuplicate:
200 return bitc::ATTR_KIND_NO_DUPLICATE;
201 case Attribute::NoImplicitFloat:
202 return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
203 case Attribute::NoInline:
204 return bitc::ATTR_KIND_NO_INLINE;
205 case Attribute::NoRecurse:
206 return bitc::ATTR_KIND_NO_RECURSE;
207 case Attribute::NonLazyBind:
208 return bitc::ATTR_KIND_NON_LAZY_BIND;
209 case Attribute::NonNull:
210 return bitc::ATTR_KIND_NON_NULL;
211 case Attribute::Dereferenceable:
212 return bitc::ATTR_KIND_DEREFERENCEABLE;
213 case Attribute::DereferenceableOrNull:
214 return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL;
215 case Attribute::NoRedZone:
216 return bitc::ATTR_KIND_NO_RED_ZONE;
217 case Attribute::NoReturn:
218 return bitc::ATTR_KIND_NO_RETURN;
219 case Attribute::NoUnwind:
220 return bitc::ATTR_KIND_NO_UNWIND;
221 case Attribute::OptimizeForSize:
222 return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
223 case Attribute::OptimizeNone:
224 return bitc::ATTR_KIND_OPTIMIZE_NONE;
225 case Attribute::ReadNone:
226 return bitc::ATTR_KIND_READ_NONE;
227 case Attribute::ReadOnly:
228 return bitc::ATTR_KIND_READ_ONLY;
229 case Attribute::Returned:
230 return bitc::ATTR_KIND_RETURNED;
231 case Attribute::ReturnsTwice:
232 return bitc::ATTR_KIND_RETURNS_TWICE;
233 case Attribute::SExt:
234 return bitc::ATTR_KIND_S_EXT;
235 case Attribute::StackAlignment:
236 return bitc::ATTR_KIND_STACK_ALIGNMENT;
237 case Attribute::StackProtect:
238 return bitc::ATTR_KIND_STACK_PROTECT;
239 case Attribute::StackProtectReq:
240 return bitc::ATTR_KIND_STACK_PROTECT_REQ;
241 case Attribute::StackProtectStrong:
242 return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
243 case Attribute::SafeStack:
244 return bitc::ATTR_KIND_SAFESTACK;
245 case Attribute::StructRet:
246 return bitc::ATTR_KIND_STRUCT_RET;
247 case Attribute::SanitizeAddress:
248 return bitc::ATTR_KIND_SANITIZE_ADDRESS;
249 case Attribute::SanitizeThread:
250 return bitc::ATTR_KIND_SANITIZE_THREAD;
251 case Attribute::SanitizeMemory:
252 return bitc::ATTR_KIND_SANITIZE_MEMORY;
253 case Attribute::UWTable:
254 return bitc::ATTR_KIND_UW_TABLE;
255 case Attribute::ZExt:
256 return bitc::ATTR_KIND_Z_EXT;
257 case Attribute::EndAttrKinds:
258 llvm_unreachable("Can not encode end-attribute kinds marker.");
259 case Attribute::None:
260 llvm_unreachable("Can not encode none-attribute.");
263 llvm_unreachable("Trying to encode unknown attribute");
266 static void WriteAttributeGroupTable(const ValueEnumerator &VE,
267 BitstreamWriter &Stream) {
268 const std::vector<AttributeSet> &AttrGrps = VE.getAttributeGroups();
269 if (AttrGrps.empty()) return;
271 Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
273 SmallVector<uint64_t, 64> Record;
274 for (unsigned i = 0, e = AttrGrps.size(); i != e; ++i) {
275 AttributeSet AS = AttrGrps[i];
276 for (unsigned i = 0, e = AS.getNumSlots(); i != e; ++i) {
277 AttributeSet A = AS.getSlotAttributes(i);
279 Record.push_back(VE.getAttributeGroupID(A));
280 Record.push_back(AS.getSlotIndex(i));
282 for (AttributeSet::iterator I = AS.begin(0), E = AS.end(0);
285 if (Attr.isEnumAttribute()) {
287 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
288 } else if (Attr.isIntAttribute()) {
290 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
291 Record.push_back(Attr.getValueAsInt());
293 StringRef Kind = Attr.getKindAsString();
294 StringRef Val = Attr.getValueAsString();
296 Record.push_back(Val.empty() ? 3 : 4);
297 Record.append(Kind.begin(), Kind.end());
300 Record.append(Val.begin(), Val.end());
306 Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
314 static void WriteAttributeTable(const ValueEnumerator &VE,
315 BitstreamWriter &Stream) {
316 const std::vector<AttributeSet> &Attrs = VE.getAttributes();
317 if (Attrs.empty()) return;
319 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
321 SmallVector<uint64_t, 64> Record;
322 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
323 const AttributeSet &A = Attrs[i];
324 for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i)
325 Record.push_back(VE.getAttributeGroupID(A.getSlotAttributes(i)));
327 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
334 /// WriteTypeTable - Write out the type table for a module.
335 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
336 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
338 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
339 SmallVector<uint64_t, 64> TypeVals;
341 uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies();
343 // Abbrev for TYPE_CODE_POINTER.
344 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
345 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
346 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
347 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
348 unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
350 // Abbrev for TYPE_CODE_FUNCTION.
351 Abbv = new BitCodeAbbrev();
352 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
353 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
354 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
355 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
357 unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
359 // Abbrev for TYPE_CODE_STRUCT_ANON.
360 Abbv = new BitCodeAbbrev();
361 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
362 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
363 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
364 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
366 unsigned StructAnonAbbrev = Stream.EmitAbbrev(Abbv);
368 // Abbrev for TYPE_CODE_STRUCT_NAME.
369 Abbv = new BitCodeAbbrev();
370 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
371 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
372 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
373 unsigned StructNameAbbrev = Stream.EmitAbbrev(Abbv);
375 // Abbrev for TYPE_CODE_STRUCT_NAMED.
376 Abbv = new BitCodeAbbrev();
377 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
378 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
379 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
380 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
382 unsigned StructNamedAbbrev = Stream.EmitAbbrev(Abbv);
384 // Abbrev for TYPE_CODE_ARRAY.
385 Abbv = new BitCodeAbbrev();
386 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
387 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
388 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
390 unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
392 // Emit an entry count so the reader can reserve space.
393 TypeVals.push_back(TypeList.size());
394 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
397 // Loop over all of the types, emitting each in turn.
398 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
399 Type *T = TypeList[i];
403 switch (T->getTypeID()) {
404 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
405 case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break;
406 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
407 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
408 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
409 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
410 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
411 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
412 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
413 case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break;
414 case Type::TokenTyID: Code = bitc::TYPE_CODE_TOKEN; break;
415 case Type::IntegerTyID:
417 Code = bitc::TYPE_CODE_INTEGER;
418 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
420 case Type::PointerTyID: {
421 PointerType *PTy = cast<PointerType>(T);
422 // POINTER: [pointee type, address space]
423 Code = bitc::TYPE_CODE_POINTER;
424 TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
425 unsigned AddressSpace = PTy->getAddressSpace();
426 TypeVals.push_back(AddressSpace);
427 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
430 case Type::FunctionTyID: {
431 FunctionType *FT = cast<FunctionType>(T);
432 // FUNCTION: [isvararg, retty, paramty x N]
433 Code = bitc::TYPE_CODE_FUNCTION;
434 TypeVals.push_back(FT->isVarArg());
435 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
436 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
437 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
438 AbbrevToUse = FunctionAbbrev;
441 case Type::StructTyID: {
442 StructType *ST = cast<StructType>(T);
443 // STRUCT: [ispacked, eltty x N]
444 TypeVals.push_back(ST->isPacked());
445 // Output all of the element types.
446 for (StructType::element_iterator I = ST->element_begin(),
447 E = ST->element_end(); I != E; ++I)
448 TypeVals.push_back(VE.getTypeID(*I));
450 if (ST->isLiteral()) {
451 Code = bitc::TYPE_CODE_STRUCT_ANON;
452 AbbrevToUse = StructAnonAbbrev;
454 if (ST->isOpaque()) {
455 Code = bitc::TYPE_CODE_OPAQUE;
457 Code = bitc::TYPE_CODE_STRUCT_NAMED;
458 AbbrevToUse = StructNamedAbbrev;
461 // Emit the name if it is present.
462 if (!ST->getName().empty())
463 WriteStringRecord(bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
464 StructNameAbbrev, Stream);
468 case Type::ArrayTyID: {
469 ArrayType *AT = cast<ArrayType>(T);
470 // ARRAY: [numelts, eltty]
471 Code = bitc::TYPE_CODE_ARRAY;
472 TypeVals.push_back(AT->getNumElements());
473 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
474 AbbrevToUse = ArrayAbbrev;
477 case Type::VectorTyID: {
478 VectorType *VT = cast<VectorType>(T);
479 // VECTOR [numelts, eltty]
480 Code = bitc::TYPE_CODE_VECTOR;
481 TypeVals.push_back(VT->getNumElements());
482 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
487 // Emit the finished record.
488 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
495 static unsigned getEncodedLinkage(const GlobalValue &GV) {
496 switch (GV.getLinkage()) {
497 case GlobalValue::ExternalLinkage:
499 case GlobalValue::WeakAnyLinkage:
501 case GlobalValue::AppendingLinkage:
503 case GlobalValue::InternalLinkage:
505 case GlobalValue::LinkOnceAnyLinkage:
507 case GlobalValue::ExternalWeakLinkage:
509 case GlobalValue::CommonLinkage:
511 case GlobalValue::PrivateLinkage:
513 case GlobalValue::WeakODRLinkage:
515 case GlobalValue::LinkOnceODRLinkage:
517 case GlobalValue::AvailableExternallyLinkage:
520 llvm_unreachable("Invalid linkage");
523 static unsigned getEncodedVisibility(const GlobalValue &GV) {
524 switch (GV.getVisibility()) {
525 case GlobalValue::DefaultVisibility: return 0;
526 case GlobalValue::HiddenVisibility: return 1;
527 case GlobalValue::ProtectedVisibility: return 2;
529 llvm_unreachable("Invalid visibility");
532 static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
533 switch (GV.getDLLStorageClass()) {
534 case GlobalValue::DefaultStorageClass: return 0;
535 case GlobalValue::DLLImportStorageClass: return 1;
536 case GlobalValue::DLLExportStorageClass: return 2;
538 llvm_unreachable("Invalid DLL storage class");
541 static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
542 switch (GV.getThreadLocalMode()) {
543 case GlobalVariable::NotThreadLocal: return 0;
544 case GlobalVariable::GeneralDynamicTLSModel: return 1;
545 case GlobalVariable::LocalDynamicTLSModel: return 2;
546 case GlobalVariable::InitialExecTLSModel: return 3;
547 case GlobalVariable::LocalExecTLSModel: return 4;
549 llvm_unreachable("Invalid TLS model");
552 static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
553 switch (C.getSelectionKind()) {
555 return bitc::COMDAT_SELECTION_KIND_ANY;
556 case Comdat::ExactMatch:
557 return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
558 case Comdat::Largest:
559 return bitc::COMDAT_SELECTION_KIND_LARGEST;
560 case Comdat::NoDuplicates:
561 return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
562 case Comdat::SameSize:
563 return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
565 llvm_unreachable("Invalid selection kind");
568 static void writeComdats(const ValueEnumerator &VE, BitstreamWriter &Stream) {
569 SmallVector<uint16_t, 64> Vals;
570 for (const Comdat *C : VE.getComdats()) {
571 // COMDAT: [selection_kind, name]
572 Vals.push_back(getEncodedComdatSelectionKind(*C));
573 size_t Size = C->getName().size();
574 assert(isUInt<16>(Size));
575 Vals.push_back(Size);
576 for (char Chr : C->getName())
577 Vals.push_back((unsigned char)Chr);
578 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
583 /// Write a record that will eventually hold the word offset of the
584 /// module-level VST. For now the offset is 0, which will be backpatched
585 /// after the real VST is written. Returns the bit offset to backpatch.
586 static uint64_t WriteValueSymbolTableForwardDecl(const ValueSymbolTable &VST,
587 BitstreamWriter &Stream) {
591 // Write a placeholder value in for the offset of the real VST,
592 // which is written after the function blocks so that it can include
593 // the offset of each function. The placeholder offset will be
594 // updated when the real VST is written.
595 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
596 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET));
597 // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
598 // hold the real VST offset. Must use fixed instead of VBR as we don't
599 // know how many VBR chunks to reserve ahead of time.
600 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
601 unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(Abbv);
603 // Emit the placeholder
604 uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0};
605 Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
607 // Compute and return the bit offset to the placeholder, which will be
608 // patched when the real VST is written. We can simply subtract the 32-bit
609 // fixed size from the current bit number to get the location to backpatch.
610 return Stream.GetCurrentBitNo() - 32;
613 /// Emit top-level description of module, including target triple, inline asm,
614 /// descriptors for global variables, and function prototype info.
615 /// Returns the bit offset to backpatch with the location of the real VST.
616 static uint64_t WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
617 BitstreamWriter &Stream) {
618 // Emit various pieces of data attached to a module.
619 if (!M->getTargetTriple().empty())
620 WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
622 const std::string &DL = M->getDataLayoutStr();
624 WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/, Stream);
625 if (!M->getModuleInlineAsm().empty())
626 WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
629 // Emit information about sections and GC, computing how many there are. Also
630 // compute the maximum alignment value.
631 std::map<std::string, unsigned> SectionMap;
632 std::map<std::string, unsigned> GCMap;
633 unsigned MaxAlignment = 0;
634 unsigned MaxGlobalType = 0;
635 for (const GlobalValue &GV : M->globals()) {
636 MaxAlignment = std::max(MaxAlignment, GV.getAlignment());
637 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
638 if (GV.hasSection()) {
639 // Give section names unique ID's.
640 unsigned &Entry = SectionMap[GV.getSection()];
642 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
644 Entry = SectionMap.size();
648 for (const Function &F : *M) {
649 MaxAlignment = std::max(MaxAlignment, F.getAlignment());
650 if (F.hasSection()) {
651 // Give section names unique ID's.
652 unsigned &Entry = SectionMap[F.getSection()];
654 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
656 Entry = SectionMap.size();
660 // Same for GC names.
661 unsigned &Entry = GCMap[F.getGC()];
663 WriteStringRecord(bitc::MODULE_CODE_GCNAME, F.getGC(),
665 Entry = GCMap.size();
670 // Emit abbrev for globals, now that we know # sections and max alignment.
671 unsigned SimpleGVarAbbrev = 0;
672 if (!M->global_empty()) {
673 // Add an abbrev for common globals with no visibility or thread localness.
674 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
675 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
676 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
677 Log2_32_Ceil(MaxGlobalType+1)));
678 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2
679 //| explicitType << 1
681 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
682 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
683 if (MaxAlignment == 0) // Alignment.
684 Abbv->Add(BitCodeAbbrevOp(0));
686 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
687 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
688 Log2_32_Ceil(MaxEncAlignment+1)));
690 if (SectionMap.empty()) // Section.
691 Abbv->Add(BitCodeAbbrevOp(0));
693 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
694 Log2_32_Ceil(SectionMap.size()+1)));
695 // Don't bother emitting vis + thread local.
696 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
699 // Emit the global variable information.
700 SmallVector<unsigned, 64> Vals;
701 for (const GlobalVariable &GV : M->globals()) {
702 unsigned AbbrevToUse = 0;
704 // GLOBALVAR: [type, isconst, initid,
705 // linkage, alignment, section, visibility, threadlocal,
706 // unnamed_addr, externally_initialized, dllstorageclass,
708 Vals.push_back(VE.getTypeID(GV.getValueType()));
709 Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
710 Vals.push_back(GV.isDeclaration() ? 0 :
711 (VE.getValueID(GV.getInitializer()) + 1));
712 Vals.push_back(getEncodedLinkage(GV));
713 Vals.push_back(Log2_32(GV.getAlignment())+1);
714 Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0);
715 if (GV.isThreadLocal() ||
716 GV.getVisibility() != GlobalValue::DefaultVisibility ||
717 GV.hasUnnamedAddr() || GV.isExternallyInitialized() ||
718 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
720 Vals.push_back(getEncodedVisibility(GV));
721 Vals.push_back(getEncodedThreadLocalMode(GV));
722 Vals.push_back(GV.hasUnnamedAddr());
723 Vals.push_back(GV.isExternallyInitialized());
724 Vals.push_back(getEncodedDLLStorageClass(GV));
725 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
727 AbbrevToUse = SimpleGVarAbbrev;
730 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
734 // Emit the function proto information.
735 for (const Function &F : *M) {
736 // FUNCTION: [type, callingconv, isproto, linkage, paramattrs, alignment,
737 // section, visibility, gc, unnamed_addr, prologuedata,
738 // dllstorageclass, comdat, prefixdata, personalityfn]
739 Vals.push_back(VE.getTypeID(F.getFunctionType()));
740 Vals.push_back(F.getCallingConv());
741 Vals.push_back(F.isDeclaration());
742 Vals.push_back(getEncodedLinkage(F));
743 Vals.push_back(VE.getAttributeID(F.getAttributes()));
744 Vals.push_back(Log2_32(F.getAlignment())+1);
745 Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0);
746 Vals.push_back(getEncodedVisibility(F));
747 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
748 Vals.push_back(F.hasUnnamedAddr());
749 Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
751 Vals.push_back(getEncodedDLLStorageClass(F));
752 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
753 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
756 F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
758 unsigned AbbrevToUse = 0;
759 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
763 // Emit the alias information.
764 for (const GlobalAlias &A : M->aliases()) {
765 // ALIAS: [alias type, aliasee val#, linkage, visibility]
766 Vals.push_back(VE.getTypeID(A.getValueType()));
767 Vals.push_back(A.getType()->getAddressSpace());
768 Vals.push_back(VE.getValueID(A.getAliasee()));
769 Vals.push_back(getEncodedLinkage(A));
770 Vals.push_back(getEncodedVisibility(A));
771 Vals.push_back(getEncodedDLLStorageClass(A));
772 Vals.push_back(getEncodedThreadLocalMode(A));
773 Vals.push_back(A.hasUnnamedAddr());
774 unsigned AbbrevToUse = 0;
775 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
779 // Write a record indicating the number of module-level metadata IDs
780 // This is needed because the ids of metadata are assigned implicitly
781 // based on their ordering in the bitcode, with the function-level
782 // metadata ids starting after the module-level metadata ids. For
783 // function importing where we lazy load the metadata as a postpass,
784 // we want to avoid parsing the module-level metadata before parsing
785 // the imported functions.
786 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
787 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_METADATA_VALUES));
788 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
789 unsigned MDValsAbbrev = Stream.EmitAbbrev(Abbv);
790 Vals.push_back(VE.numMDs());
791 Stream.EmitRecord(bitc::MODULE_CODE_METADATA_VALUES, Vals, MDValsAbbrev);
794 uint64_t VSTOffsetPlaceholder =
795 WriteValueSymbolTableForwardDecl(M->getValueSymbolTable(), Stream);
796 return VSTOffsetPlaceholder;
799 static uint64_t GetOptimizationFlags(const Value *V) {
802 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
803 if (OBO->hasNoSignedWrap())
804 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
805 if (OBO->hasNoUnsignedWrap())
806 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
807 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
809 Flags |= 1 << bitc::PEO_EXACT;
810 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
811 if (FPMO->hasUnsafeAlgebra())
812 Flags |= FastMathFlags::UnsafeAlgebra;
813 if (FPMO->hasNoNaNs())
814 Flags |= FastMathFlags::NoNaNs;
815 if (FPMO->hasNoInfs())
816 Flags |= FastMathFlags::NoInfs;
817 if (FPMO->hasNoSignedZeros())
818 Flags |= FastMathFlags::NoSignedZeros;
819 if (FPMO->hasAllowReciprocal())
820 Flags |= FastMathFlags::AllowReciprocal;
826 static void WriteValueAsMetadata(const ValueAsMetadata *MD,
827 const ValueEnumerator &VE,
828 BitstreamWriter &Stream,
829 SmallVectorImpl<uint64_t> &Record) {
830 // Mimic an MDNode with a value as one operand.
831 Value *V = MD->getValue();
832 Record.push_back(VE.getTypeID(V->getType()));
833 Record.push_back(VE.getValueID(V));
834 Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
838 static void WriteMDTuple(const MDTuple *N, const ValueEnumerator &VE,
839 BitstreamWriter &Stream,
840 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
841 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
842 Metadata *MD = N->getOperand(i);
843 assert(!(MD && isa<LocalAsMetadata>(MD)) &&
844 "Unexpected function-local metadata");
845 Record.push_back(VE.getMetadataOrNullID(MD));
847 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
848 : bitc::METADATA_NODE,
853 static void WriteDILocation(const DILocation *N, const ValueEnumerator &VE,
854 BitstreamWriter &Stream,
855 SmallVectorImpl<uint64_t> &Record,
857 Record.push_back(N->isDistinct());
858 Record.push_back(N->getLine());
859 Record.push_back(N->getColumn());
860 Record.push_back(VE.getMetadataID(N->getScope()));
861 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
863 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
867 static void WriteGenericDINode(const GenericDINode *N,
868 const ValueEnumerator &VE,
869 BitstreamWriter &Stream,
870 SmallVectorImpl<uint64_t> &Record,
872 Record.push_back(N->isDistinct());
873 Record.push_back(N->getTag());
874 Record.push_back(0); // Per-tag version field; unused for now.
876 for (auto &I : N->operands())
877 Record.push_back(VE.getMetadataOrNullID(I));
879 Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
883 static uint64_t rotateSign(int64_t I) {
885 return I < 0 ? ~(U << 1) : U << 1;
888 static void WriteDISubrange(const DISubrange *N, const ValueEnumerator &,
889 BitstreamWriter &Stream,
890 SmallVectorImpl<uint64_t> &Record,
892 Record.push_back(N->isDistinct());
893 Record.push_back(N->getCount());
894 Record.push_back(rotateSign(N->getLowerBound()));
896 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
900 static void WriteDIEnumerator(const DIEnumerator *N, const ValueEnumerator &VE,
901 BitstreamWriter &Stream,
902 SmallVectorImpl<uint64_t> &Record,
904 Record.push_back(N->isDistinct());
905 Record.push_back(rotateSign(N->getValue()));
906 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
908 Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
912 static void WriteDIBasicType(const DIBasicType *N, const ValueEnumerator &VE,
913 BitstreamWriter &Stream,
914 SmallVectorImpl<uint64_t> &Record,
916 Record.push_back(N->isDistinct());
917 Record.push_back(N->getTag());
918 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
919 Record.push_back(N->getSizeInBits());
920 Record.push_back(N->getAlignInBits());
921 Record.push_back(N->getEncoding());
923 Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
927 static void WriteDIDerivedType(const DIDerivedType *N,
928 const ValueEnumerator &VE,
929 BitstreamWriter &Stream,
930 SmallVectorImpl<uint64_t> &Record,
932 Record.push_back(N->isDistinct());
933 Record.push_back(N->getTag());
934 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
935 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
936 Record.push_back(N->getLine());
937 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
938 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
939 Record.push_back(N->getSizeInBits());
940 Record.push_back(N->getAlignInBits());
941 Record.push_back(N->getOffsetInBits());
942 Record.push_back(N->getFlags());
943 Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
945 Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
949 static void WriteDICompositeType(const DICompositeType *N,
950 const ValueEnumerator &VE,
951 BitstreamWriter &Stream,
952 SmallVectorImpl<uint64_t> &Record,
954 Record.push_back(N->isDistinct());
955 Record.push_back(N->getTag());
956 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
957 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
958 Record.push_back(N->getLine());
959 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
960 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
961 Record.push_back(N->getSizeInBits());
962 Record.push_back(N->getAlignInBits());
963 Record.push_back(N->getOffsetInBits());
964 Record.push_back(N->getFlags());
965 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
966 Record.push_back(N->getRuntimeLang());
967 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
968 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
969 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
971 Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
975 static void WriteDISubroutineType(const DISubroutineType *N,
976 const ValueEnumerator &VE,
977 BitstreamWriter &Stream,
978 SmallVectorImpl<uint64_t> &Record,
980 Record.push_back(N->isDistinct());
981 Record.push_back(N->getFlags());
982 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
984 Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
988 static void WriteDIFile(const DIFile *N, const ValueEnumerator &VE,
989 BitstreamWriter &Stream,
990 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
991 Record.push_back(N->isDistinct());
992 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
993 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
995 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
999 static void WriteDICompileUnit(const DICompileUnit *N,
1000 const ValueEnumerator &VE,
1001 BitstreamWriter &Stream,
1002 SmallVectorImpl<uint64_t> &Record,
1004 assert(N->isDistinct() && "Expected distinct compile units");
1005 Record.push_back(/* IsDistinct */ true);
1006 Record.push_back(N->getSourceLanguage());
1007 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1008 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
1009 Record.push_back(N->isOptimized());
1010 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
1011 Record.push_back(N->getRuntimeVersion());
1012 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
1013 Record.push_back(N->getEmissionKind());
1014 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
1015 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
1016 Record.push_back(VE.getMetadataOrNullID(N->getSubprograms().get()));
1017 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
1018 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
1019 Record.push_back(N->getDWOId());
1020 Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
1022 Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
1026 static void WriteDISubprogram(const DISubprogram *N, const ValueEnumerator &VE,
1027 BitstreamWriter &Stream,
1028 SmallVectorImpl<uint64_t> &Record,
1030 Record.push_back(N->isDistinct());
1031 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1032 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1033 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1034 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1035 Record.push_back(N->getLine());
1036 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1037 Record.push_back(N->isLocalToUnit());
1038 Record.push_back(N->isDefinition());
1039 Record.push_back(N->getScopeLine());
1040 Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
1041 Record.push_back(N->getVirtuality());
1042 Record.push_back(N->getVirtualIndex());
1043 Record.push_back(N->getFlags());
1044 Record.push_back(N->isOptimized());
1045 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1046 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
1047 Record.push_back(VE.getMetadataOrNullID(N->getVariables().get()));
1049 Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
1053 static void WriteDILexicalBlock(const DILexicalBlock *N,
1054 const ValueEnumerator &VE,
1055 BitstreamWriter &Stream,
1056 SmallVectorImpl<uint64_t> &Record,
1058 Record.push_back(N->isDistinct());
1059 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1060 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1061 Record.push_back(N->getLine());
1062 Record.push_back(N->getColumn());
1064 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
1068 static void WriteDILexicalBlockFile(const DILexicalBlockFile *N,
1069 const ValueEnumerator &VE,
1070 BitstreamWriter &Stream,
1071 SmallVectorImpl<uint64_t> &Record,
1073 Record.push_back(N->isDistinct());
1074 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1075 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1076 Record.push_back(N->getDiscriminator());
1078 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
1082 static void WriteDINamespace(const DINamespace *N, const ValueEnumerator &VE,
1083 BitstreamWriter &Stream,
1084 SmallVectorImpl<uint64_t> &Record,
1086 Record.push_back(N->isDistinct());
1087 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1088 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1089 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1090 Record.push_back(N->getLine());
1092 Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
1096 static void WriteDIMacro(const DIMacro *N, const ValueEnumerator &VE,
1097 BitstreamWriter &Stream,
1098 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
1099 Record.push_back(N->isDistinct());
1100 Record.push_back(N->getMacinfoType());
1101 Record.push_back(N->getLine());
1102 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1103 Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
1105 Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
1109 static void WriteDIMacroFile(const DIMacroFile *N, const ValueEnumerator &VE,
1110 BitstreamWriter &Stream,
1111 SmallVectorImpl<uint64_t> &Record,
1113 Record.push_back(N->isDistinct());
1114 Record.push_back(N->getMacinfoType());
1115 Record.push_back(N->getLine());
1116 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1117 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1119 Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
1123 static void WriteDIModule(const DIModule *N, const ValueEnumerator &VE,
1124 BitstreamWriter &Stream,
1125 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
1126 Record.push_back(N->isDistinct());
1127 for (auto &I : N->operands())
1128 Record.push_back(VE.getMetadataOrNullID(I));
1130 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
1134 static void WriteDITemplateTypeParameter(const DITemplateTypeParameter *N,
1135 const ValueEnumerator &VE,
1136 BitstreamWriter &Stream,
1137 SmallVectorImpl<uint64_t> &Record,
1139 Record.push_back(N->isDistinct());
1140 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1141 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1143 Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
1147 static void WriteDITemplateValueParameter(const DITemplateValueParameter *N,
1148 const ValueEnumerator &VE,
1149 BitstreamWriter &Stream,
1150 SmallVectorImpl<uint64_t> &Record,
1152 Record.push_back(N->isDistinct());
1153 Record.push_back(N->getTag());
1154 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1155 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1156 Record.push_back(VE.getMetadataOrNullID(N->getValue()));
1158 Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
1162 static void WriteDIGlobalVariable(const DIGlobalVariable *N,
1163 const ValueEnumerator &VE,
1164 BitstreamWriter &Stream,
1165 SmallVectorImpl<uint64_t> &Record,
1167 Record.push_back(N->isDistinct());
1168 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1169 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1170 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1171 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1172 Record.push_back(N->getLine());
1173 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1174 Record.push_back(N->isLocalToUnit());
1175 Record.push_back(N->isDefinition());
1176 Record.push_back(VE.getMetadataOrNullID(N->getRawVariable()));
1177 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
1179 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
1183 static void WriteDILocalVariable(const DILocalVariable *N,
1184 const ValueEnumerator &VE,
1185 BitstreamWriter &Stream,
1186 SmallVectorImpl<uint64_t> &Record,
1188 Record.push_back(N->isDistinct());
1189 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1190 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1191 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1192 Record.push_back(N->getLine());
1193 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1194 Record.push_back(N->getArg());
1195 Record.push_back(N->getFlags());
1197 Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
1201 static void WriteDIExpression(const DIExpression *N, const ValueEnumerator &,
1202 BitstreamWriter &Stream,
1203 SmallVectorImpl<uint64_t> &Record,
1205 Record.reserve(N->getElements().size() + 1);
1207 Record.push_back(N->isDistinct());
1208 Record.append(N->elements_begin(), N->elements_end());
1210 Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
1214 static void WriteDIObjCProperty(const DIObjCProperty *N,
1215 const ValueEnumerator &VE,
1216 BitstreamWriter &Stream,
1217 SmallVectorImpl<uint64_t> &Record,
1219 Record.push_back(N->isDistinct());
1220 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1221 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1222 Record.push_back(N->getLine());
1223 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
1224 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
1225 Record.push_back(N->getAttributes());
1226 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1228 Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
1232 static void WriteDIImportedEntity(const DIImportedEntity *N,
1233 const ValueEnumerator &VE,
1234 BitstreamWriter &Stream,
1235 SmallVectorImpl<uint64_t> &Record,
1237 Record.push_back(N->isDistinct());
1238 Record.push_back(N->getTag());
1239 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1240 Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
1241 Record.push_back(N->getLine());
1242 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1244 Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
1248 static void WriteModuleMetadata(const Module *M,
1249 const ValueEnumerator &VE,
1250 BitstreamWriter &Stream) {
1251 const auto &MDs = VE.getMDs();
1252 if (MDs.empty() && M->named_metadata_empty())
1255 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
1257 unsigned MDSAbbrev = 0;
1258 if (VE.hasMDString()) {
1259 // Abbrev for METADATA_STRING.
1260 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1261 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING));
1262 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1263 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1264 MDSAbbrev = Stream.EmitAbbrev(Abbv);
1267 // Initialize MDNode abbreviations.
1268 #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
1269 #include "llvm/IR/Metadata.def"
1271 if (VE.hasDILocation()) {
1272 // Abbrev for METADATA_LOCATION.
1274 // Assume the column is usually under 128, and always output the inlined-at
1275 // location (it's never more expensive than building an array size 1).
1276 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1277 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
1278 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1279 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1280 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1281 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1282 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1283 DILocationAbbrev = Stream.EmitAbbrev(Abbv);
1286 if (VE.hasGenericDINode()) {
1287 // Abbrev for METADATA_GENERIC_DEBUG.
1289 // Assume the column is usually under 128, and always output the inlined-at
1290 // location (it's never more expensive than building an array size 1).
1291 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1292 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
1293 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1294 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1295 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1296 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1297 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1298 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1299 GenericDINodeAbbrev = Stream.EmitAbbrev(Abbv);
1302 unsigned NameAbbrev = 0;
1303 if (!M->named_metadata_empty()) {
1304 // Abbrev for METADATA_NAME.
1305 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1306 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
1307 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1308 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1309 NameAbbrev = Stream.EmitAbbrev(Abbv);
1312 SmallVector<uint64_t, 64> Record;
1313 for (const Metadata *MD : MDs) {
1314 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
1315 assert(N->isResolved() && "Expected forward references to be resolved");
1317 switch (N->getMetadataID()) {
1319 llvm_unreachable("Invalid MDNode subclass");
1320 #define HANDLE_MDNODE_LEAF(CLASS) \
1321 case Metadata::CLASS##Kind: \
1322 Write##CLASS(cast<CLASS>(N), VE, Stream, Record, CLASS##Abbrev); \
1324 #include "llvm/IR/Metadata.def"
1327 if (const auto *MDC = dyn_cast<ConstantAsMetadata>(MD)) {
1328 WriteValueAsMetadata(MDC, VE, Stream, Record);
1331 const MDString *MDS = cast<MDString>(MD);
1332 // Code: [strchar x N]
1333 Record.append(MDS->bytes_begin(), MDS->bytes_end());
1335 // Emit the finished record.
1336 Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev);
1340 // Write named metadata.
1341 for (const NamedMDNode &NMD : M->named_metadata()) {
1343 StringRef Str = NMD.getName();
1344 Record.append(Str.bytes_begin(), Str.bytes_end());
1345 Stream.EmitRecord(bitc::METADATA_NAME, Record, NameAbbrev);
1348 // Write named metadata operands.
1349 for (const MDNode *N : NMD.operands())
1350 Record.push_back(VE.getMetadataID(N));
1351 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
1358 static void WriteFunctionLocalMetadata(const Function &F,
1359 const ValueEnumerator &VE,
1360 BitstreamWriter &Stream) {
1361 bool StartedMetadataBlock = false;
1362 SmallVector<uint64_t, 64> Record;
1363 const SmallVectorImpl<const LocalAsMetadata *> &MDs =
1364 VE.getFunctionLocalMDs();
1365 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
1366 assert(MDs[i] && "Expected valid function-local metadata");
1367 if (!StartedMetadataBlock) {
1368 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
1369 StartedMetadataBlock = true;
1371 WriteValueAsMetadata(MDs[i], VE, Stream, Record);
1374 if (StartedMetadataBlock)
1378 static void WriteMetadataAttachment(const Function &F,
1379 const ValueEnumerator &VE,
1380 BitstreamWriter &Stream) {
1381 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
1383 SmallVector<uint64_t, 64> Record;
1385 // Write metadata attachments
1386 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
1387 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1388 F.getAllMetadata(MDs);
1390 for (const auto &I : MDs) {
1391 Record.push_back(I.first);
1392 Record.push_back(VE.getMetadataID(I.second));
1394 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
1398 for (const BasicBlock &BB : F)
1399 for (const Instruction &I : BB) {
1401 I.getAllMetadataOtherThanDebugLoc(MDs);
1403 // If no metadata, ignore instruction.
1404 if (MDs.empty()) continue;
1406 Record.push_back(VE.getInstructionID(&I));
1408 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
1409 Record.push_back(MDs[i].first);
1410 Record.push_back(VE.getMetadataID(MDs[i].second));
1412 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
1419 static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) {
1420 SmallVector<uint64_t, 64> Record;
1422 // Write metadata kinds
1423 // METADATA_KIND - [n x [id, name]]
1424 SmallVector<StringRef, 8> Names;
1425 M->getMDKindNames(Names);
1427 if (Names.empty()) return;
1429 Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3);
1431 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
1432 Record.push_back(MDKindID);
1433 StringRef KName = Names[MDKindID];
1434 Record.append(KName.begin(), KName.end());
1436 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
1443 static void WriteOperandBundleTags(const Module *M, BitstreamWriter &Stream) {
1444 // Write metadata kinds
1446 // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
1448 // OPERAND_BUNDLE_TAG - [strchr x N]
1450 SmallVector<StringRef, 8> Tags;
1451 M->getOperandBundleTags(Tags);
1456 Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3);
1458 SmallVector<uint64_t, 64> Record;
1460 for (auto Tag : Tags) {
1461 Record.append(Tag.begin(), Tag.end());
1463 Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
1470 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
1471 if ((int64_t)V >= 0)
1472 Vals.push_back(V << 1);
1474 Vals.push_back((-V << 1) | 1);
1477 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
1478 const ValueEnumerator &VE,
1479 BitstreamWriter &Stream, bool isGlobal) {
1480 if (FirstVal == LastVal) return;
1482 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
1484 unsigned AggregateAbbrev = 0;
1485 unsigned String8Abbrev = 0;
1486 unsigned CString7Abbrev = 0;
1487 unsigned CString6Abbrev = 0;
1488 // If this is a constant pool for the module, emit module-specific abbrevs.
1490 // Abbrev for CST_CODE_AGGREGATE.
1491 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1492 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
1493 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1494 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
1495 AggregateAbbrev = Stream.EmitAbbrev(Abbv);
1497 // Abbrev for CST_CODE_STRING.
1498 Abbv = new BitCodeAbbrev();
1499 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
1500 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1501 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1502 String8Abbrev = Stream.EmitAbbrev(Abbv);
1503 // Abbrev for CST_CODE_CSTRING.
1504 Abbv = new BitCodeAbbrev();
1505 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
1506 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1507 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1508 CString7Abbrev = Stream.EmitAbbrev(Abbv);
1509 // Abbrev for CST_CODE_CSTRING.
1510 Abbv = new BitCodeAbbrev();
1511 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
1512 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1513 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1514 CString6Abbrev = Stream.EmitAbbrev(Abbv);
1517 SmallVector<uint64_t, 64> Record;
1519 const ValueEnumerator::ValueList &Vals = VE.getValues();
1520 Type *LastTy = nullptr;
1521 for (unsigned i = FirstVal; i != LastVal; ++i) {
1522 const Value *V = Vals[i].first;
1523 // If we need to switch types, do so now.
1524 if (V->getType() != LastTy) {
1525 LastTy = V->getType();
1526 Record.push_back(VE.getTypeID(LastTy));
1527 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
1528 CONSTANTS_SETTYPE_ABBREV);
1532 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1533 Record.push_back(unsigned(IA->hasSideEffects()) |
1534 unsigned(IA->isAlignStack()) << 1 |
1535 unsigned(IA->getDialect()&1) << 2);
1537 // Add the asm string.
1538 const std::string &AsmStr = IA->getAsmString();
1539 Record.push_back(AsmStr.size());
1540 Record.append(AsmStr.begin(), AsmStr.end());
1542 // Add the constraint string.
1543 const std::string &ConstraintStr = IA->getConstraintString();
1544 Record.push_back(ConstraintStr.size());
1545 Record.append(ConstraintStr.begin(), ConstraintStr.end());
1546 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
1550 const Constant *C = cast<Constant>(V);
1551 unsigned Code = -1U;
1552 unsigned AbbrevToUse = 0;
1553 if (C->isNullValue()) {
1554 Code = bitc::CST_CODE_NULL;
1555 } else if (isa<UndefValue>(C)) {
1556 Code = bitc::CST_CODE_UNDEF;
1557 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
1558 if (IV->getBitWidth() <= 64) {
1559 uint64_t V = IV->getSExtValue();
1560 emitSignedInt64(Record, V);
1561 Code = bitc::CST_CODE_INTEGER;
1562 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
1563 } else { // Wide integers, > 64 bits in size.
1564 // We have an arbitrary precision integer value to write whose
1565 // bit width is > 64. However, in canonical unsigned integer
1566 // format it is likely that the high bits are going to be zero.
1567 // So, we only write the number of active words.
1568 unsigned NWords = IV->getValue().getActiveWords();
1569 const uint64_t *RawWords = IV->getValue().getRawData();
1570 for (unsigned i = 0; i != NWords; ++i) {
1571 emitSignedInt64(Record, RawWords[i]);
1573 Code = bitc::CST_CODE_WIDE_INTEGER;
1575 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
1576 Code = bitc::CST_CODE_FLOAT;
1577 Type *Ty = CFP->getType();
1578 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
1579 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
1580 } else if (Ty->isX86_FP80Ty()) {
1581 // api needed to prevent premature destruction
1582 // bits are not in the same order as a normal i80 APInt, compensate.
1583 APInt api = CFP->getValueAPF().bitcastToAPInt();
1584 const uint64_t *p = api.getRawData();
1585 Record.push_back((p[1] << 48) | (p[0] >> 16));
1586 Record.push_back(p[0] & 0xffffLL);
1587 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
1588 APInt api = CFP->getValueAPF().bitcastToAPInt();
1589 const uint64_t *p = api.getRawData();
1590 Record.push_back(p[0]);
1591 Record.push_back(p[1]);
1593 assert (0 && "Unknown FP type!");
1595 } else if (isa<ConstantDataSequential>(C) &&
1596 cast<ConstantDataSequential>(C)->isString()) {
1597 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
1598 // Emit constant strings specially.
1599 unsigned NumElts = Str->getNumElements();
1600 // If this is a null-terminated string, use the denser CSTRING encoding.
1601 if (Str->isCString()) {
1602 Code = bitc::CST_CODE_CSTRING;
1603 --NumElts; // Don't encode the null, which isn't allowed by char6.
1605 Code = bitc::CST_CODE_STRING;
1606 AbbrevToUse = String8Abbrev;
1608 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
1609 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
1610 for (unsigned i = 0; i != NumElts; ++i) {
1611 unsigned char V = Str->getElementAsInteger(i);
1612 Record.push_back(V);
1613 isCStr7 &= (V & 128) == 0;
1615 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
1619 AbbrevToUse = CString6Abbrev;
1621 AbbrevToUse = CString7Abbrev;
1622 } else if (const ConstantDataSequential *CDS =
1623 dyn_cast<ConstantDataSequential>(C)) {
1624 Code = bitc::CST_CODE_DATA;
1625 Type *EltTy = CDS->getType()->getElementType();
1626 if (isa<IntegerType>(EltTy)) {
1627 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
1628 Record.push_back(CDS->getElementAsInteger(i));
1629 } else if (EltTy->isFloatTy()) {
1630 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1631 union { float F; uint32_t I; };
1632 F = CDS->getElementAsFloat(i);
1633 Record.push_back(I);
1636 assert(EltTy->isDoubleTy() && "Unknown ConstantData element type");
1637 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1638 union { double F; uint64_t I; };
1639 F = CDS->getElementAsDouble(i);
1640 Record.push_back(I);
1643 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
1644 isa<ConstantVector>(C)) {
1645 Code = bitc::CST_CODE_AGGREGATE;
1646 for (const Value *Op : C->operands())
1647 Record.push_back(VE.getValueID(Op));
1648 AbbrevToUse = AggregateAbbrev;
1649 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1650 switch (CE->getOpcode()) {
1652 if (Instruction::isCast(CE->getOpcode())) {
1653 Code = bitc::CST_CODE_CE_CAST;
1654 Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
1655 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1656 Record.push_back(VE.getValueID(C->getOperand(0)));
1657 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
1659 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
1660 Code = bitc::CST_CODE_CE_BINOP;
1661 Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
1662 Record.push_back(VE.getValueID(C->getOperand(0)));
1663 Record.push_back(VE.getValueID(C->getOperand(1)));
1664 uint64_t Flags = GetOptimizationFlags(CE);
1666 Record.push_back(Flags);
1669 case Instruction::GetElementPtr: {
1670 Code = bitc::CST_CODE_CE_GEP;
1671 const auto *GO = cast<GEPOperator>(C);
1672 if (GO->isInBounds())
1673 Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
1674 Record.push_back(VE.getTypeID(GO->getSourceElementType()));
1675 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
1676 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
1677 Record.push_back(VE.getValueID(C->getOperand(i)));
1681 case Instruction::Select:
1682 Code = bitc::CST_CODE_CE_SELECT;
1683 Record.push_back(VE.getValueID(C->getOperand(0)));
1684 Record.push_back(VE.getValueID(C->getOperand(1)));
1685 Record.push_back(VE.getValueID(C->getOperand(2)));
1687 case Instruction::ExtractElement:
1688 Code = bitc::CST_CODE_CE_EXTRACTELT;
1689 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1690 Record.push_back(VE.getValueID(C->getOperand(0)));
1691 Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
1692 Record.push_back(VE.getValueID(C->getOperand(1)));
1694 case Instruction::InsertElement:
1695 Code = bitc::CST_CODE_CE_INSERTELT;
1696 Record.push_back(VE.getValueID(C->getOperand(0)));
1697 Record.push_back(VE.getValueID(C->getOperand(1)));
1698 Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
1699 Record.push_back(VE.getValueID(C->getOperand(2)));
1701 case Instruction::ShuffleVector:
1702 // If the return type and argument types are the same, this is a
1703 // standard shufflevector instruction. If the types are different,
1704 // then the shuffle is widening or truncating the input vectors, and
1705 // the argument type must also be encoded.
1706 if (C->getType() == C->getOperand(0)->getType()) {
1707 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
1709 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
1710 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1712 Record.push_back(VE.getValueID(C->getOperand(0)));
1713 Record.push_back(VE.getValueID(C->getOperand(1)));
1714 Record.push_back(VE.getValueID(C->getOperand(2)));
1716 case Instruction::ICmp:
1717 case Instruction::FCmp:
1718 Code = bitc::CST_CODE_CE_CMP;
1719 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1720 Record.push_back(VE.getValueID(C->getOperand(0)));
1721 Record.push_back(VE.getValueID(C->getOperand(1)));
1722 Record.push_back(CE->getPredicate());
1725 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
1726 Code = bitc::CST_CODE_BLOCKADDRESS;
1727 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
1728 Record.push_back(VE.getValueID(BA->getFunction()));
1729 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
1734 llvm_unreachable("Unknown constant!");
1736 Stream.EmitRecord(Code, Record, AbbrevToUse);
1743 static void WriteModuleConstants(const ValueEnumerator &VE,
1744 BitstreamWriter &Stream) {
1745 const ValueEnumerator::ValueList &Vals = VE.getValues();
1747 // Find the first constant to emit, which is the first non-globalvalue value.
1748 // We know globalvalues have been emitted by WriteModuleInfo.
1749 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1750 if (!isa<GlobalValue>(Vals[i].first)) {
1751 WriteConstants(i, Vals.size(), VE, Stream, true);
1757 /// PushValueAndType - The file has to encode both the value and type id for
1758 /// many values, because we need to know what type to create for forward
1759 /// references. However, most operands are not forward references, so this type
1760 /// field is not needed.
1762 /// This function adds V's value ID to Vals. If the value ID is higher than the
1763 /// instruction ID, then it is a forward reference, and it also includes the
1764 /// type ID. The value ID that is written is encoded relative to the InstID.
1765 static bool PushValueAndType(const Value *V, unsigned InstID,
1766 SmallVectorImpl<unsigned> &Vals,
1767 ValueEnumerator &VE) {
1768 unsigned ValID = VE.getValueID(V);
1769 // Make encoding relative to the InstID.
1770 Vals.push_back(InstID - ValID);
1771 if (ValID >= InstID) {
1772 Vals.push_back(VE.getTypeID(V->getType()));
1778 static void WriteOperandBundles(BitstreamWriter &Stream, ImmutableCallSite CS,
1779 unsigned InstID, ValueEnumerator &VE) {
1780 SmallVector<unsigned, 64> Record;
1781 LLVMContext &C = CS.getInstruction()->getContext();
1783 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
1784 const auto &Bundle = CS.getOperandBundleAt(i);
1785 Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
1787 for (auto &Input : Bundle.Inputs)
1788 PushValueAndType(Input, InstID, Record, VE);
1790 Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record);
1795 /// pushValue - Like PushValueAndType, but where the type of the value is
1796 /// omitted (perhaps it was already encoded in an earlier operand).
1797 static void pushValue(const Value *V, unsigned InstID,
1798 SmallVectorImpl<unsigned> &Vals,
1799 ValueEnumerator &VE) {
1800 unsigned ValID = VE.getValueID(V);
1801 Vals.push_back(InstID - ValID);
1804 static void pushValueSigned(const Value *V, unsigned InstID,
1805 SmallVectorImpl<uint64_t> &Vals,
1806 ValueEnumerator &VE) {
1807 unsigned ValID = VE.getValueID(V);
1808 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
1809 emitSignedInt64(Vals, diff);
1812 /// WriteInstruction - Emit an instruction to the specified stream.
1813 static void WriteInstruction(const Instruction &I, unsigned InstID,
1814 ValueEnumerator &VE, BitstreamWriter &Stream,
1815 SmallVectorImpl<unsigned> &Vals) {
1817 unsigned AbbrevToUse = 0;
1818 VE.setInstructionID(&I);
1819 switch (I.getOpcode()) {
1821 if (Instruction::isCast(I.getOpcode())) {
1822 Code = bitc::FUNC_CODE_INST_CAST;
1823 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1824 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
1825 Vals.push_back(VE.getTypeID(I.getType()));
1826 Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
1828 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
1829 Code = bitc::FUNC_CODE_INST_BINOP;
1830 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1831 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
1832 pushValue(I.getOperand(1), InstID, Vals, VE);
1833 Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
1834 uint64_t Flags = GetOptimizationFlags(&I);
1836 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
1837 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
1838 Vals.push_back(Flags);
1843 case Instruction::GetElementPtr: {
1844 Code = bitc::FUNC_CODE_INST_GEP;
1845 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
1846 auto &GEPInst = cast<GetElementPtrInst>(I);
1847 Vals.push_back(GEPInst.isInBounds());
1848 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
1849 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1850 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1853 case Instruction::ExtractValue: {
1854 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
1855 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1856 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
1857 Vals.append(EVI->idx_begin(), EVI->idx_end());
1860 case Instruction::InsertValue: {
1861 Code = bitc::FUNC_CODE_INST_INSERTVAL;
1862 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1863 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1864 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
1865 Vals.append(IVI->idx_begin(), IVI->idx_end());
1868 case Instruction::Select:
1869 Code = bitc::FUNC_CODE_INST_VSELECT;
1870 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1871 pushValue(I.getOperand(2), InstID, Vals, VE);
1872 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1874 case Instruction::ExtractElement:
1875 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
1876 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1877 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1879 case Instruction::InsertElement:
1880 Code = bitc::FUNC_CODE_INST_INSERTELT;
1881 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1882 pushValue(I.getOperand(1), InstID, Vals, VE);
1883 PushValueAndType(I.getOperand(2), InstID, Vals, VE);
1885 case Instruction::ShuffleVector:
1886 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
1887 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1888 pushValue(I.getOperand(1), InstID, Vals, VE);
1889 pushValue(I.getOperand(2), InstID, Vals, VE);
1891 case Instruction::ICmp:
1892 case Instruction::FCmp: {
1893 // compare returning Int1Ty or vector of Int1Ty
1894 Code = bitc::FUNC_CODE_INST_CMP2;
1895 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1896 pushValue(I.getOperand(1), InstID, Vals, VE);
1897 Vals.push_back(cast<CmpInst>(I).getPredicate());
1898 uint64_t Flags = GetOptimizationFlags(&I);
1900 Vals.push_back(Flags);
1904 case Instruction::Ret:
1906 Code = bitc::FUNC_CODE_INST_RET;
1907 unsigned NumOperands = I.getNumOperands();
1908 if (NumOperands == 0)
1909 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
1910 else if (NumOperands == 1) {
1911 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1912 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
1914 for (unsigned i = 0, e = NumOperands; i != e; ++i)
1915 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1919 case Instruction::Br:
1921 Code = bitc::FUNC_CODE_INST_BR;
1922 const BranchInst &II = cast<BranchInst>(I);
1923 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
1924 if (II.isConditional()) {
1925 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
1926 pushValue(II.getCondition(), InstID, Vals, VE);
1930 case Instruction::Switch:
1932 Code = bitc::FUNC_CODE_INST_SWITCH;
1933 const SwitchInst &SI = cast<SwitchInst>(I);
1934 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
1935 pushValue(SI.getCondition(), InstID, Vals, VE);
1936 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
1937 for (SwitchInst::ConstCaseIt Case : SI.cases()) {
1938 Vals.push_back(VE.getValueID(Case.getCaseValue()));
1939 Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
1943 case Instruction::IndirectBr:
1944 Code = bitc::FUNC_CODE_INST_INDIRECTBR;
1945 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1946 // Encode the address operand as relative, but not the basic blocks.
1947 pushValue(I.getOperand(0), InstID, Vals, VE);
1948 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
1949 Vals.push_back(VE.getValueID(I.getOperand(i)));
1952 case Instruction::Invoke: {
1953 const InvokeInst *II = cast<InvokeInst>(&I);
1954 const Value *Callee = II->getCalledValue();
1955 FunctionType *FTy = II->getFunctionType();
1957 if (II->hasOperandBundles())
1958 WriteOperandBundles(Stream, II, InstID, VE);
1960 Code = bitc::FUNC_CODE_INST_INVOKE;
1962 Vals.push_back(VE.getAttributeID(II->getAttributes()));
1963 Vals.push_back(II->getCallingConv() | 1 << 13);
1964 Vals.push_back(VE.getValueID(II->getNormalDest()));
1965 Vals.push_back(VE.getValueID(II->getUnwindDest()));
1966 Vals.push_back(VE.getTypeID(FTy));
1967 PushValueAndType(Callee, InstID, Vals, VE);
1969 // Emit value #'s for the fixed parameters.
1970 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1971 pushValue(I.getOperand(i), InstID, Vals, VE); // fixed param.
1973 // Emit type/value pairs for varargs params.
1974 if (FTy->isVarArg()) {
1975 for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
1977 PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
1981 case Instruction::Resume:
1982 Code = bitc::FUNC_CODE_INST_RESUME;
1983 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1985 case Instruction::CleanupRet: {
1986 Code = bitc::FUNC_CODE_INST_CLEANUPRET;
1987 const auto &CRI = cast<CleanupReturnInst>(I);
1988 pushValue(CRI.getCleanupPad(), InstID, Vals, VE);
1989 if (CRI.hasUnwindDest())
1990 Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
1993 case Instruction::CatchRet: {
1994 Code = bitc::FUNC_CODE_INST_CATCHRET;
1995 const auto &CRI = cast<CatchReturnInst>(I);
1996 pushValue(CRI.getCatchPad(), InstID, Vals, VE);
1997 Vals.push_back(VE.getValueID(CRI.getSuccessor()));
2000 case Instruction::CleanupPad:
2001 case Instruction::CatchPad: {
2002 const auto &FuncletPad = cast<FuncletPadInst>(I);
2003 Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
2004 : bitc::FUNC_CODE_INST_CLEANUPPAD;
2005 pushValue(FuncletPad.getParentPad(), InstID, Vals, VE);
2007 unsigned NumArgOperands = FuncletPad.getNumArgOperands();
2008 Vals.push_back(NumArgOperands);
2009 for (unsigned Op = 0; Op != NumArgOperands; ++Op)
2010 PushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals, VE);
2013 case Instruction::CatchSwitch: {
2014 Code = bitc::FUNC_CODE_INST_CATCHSWITCH;
2015 const auto &CatchSwitch = cast<CatchSwitchInst>(I);
2017 pushValue(CatchSwitch.getParentPad(), InstID, Vals, VE);
2019 unsigned NumHandlers = CatchSwitch.getNumHandlers();
2020 Vals.push_back(NumHandlers);
2021 for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
2022 Vals.push_back(VE.getValueID(CatchPadBB));
2024 if (CatchSwitch.hasUnwindDest())
2025 Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
2028 case Instruction::Unreachable:
2029 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
2030 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
2033 case Instruction::PHI: {
2034 const PHINode &PN = cast<PHINode>(I);
2035 Code = bitc::FUNC_CODE_INST_PHI;
2036 // With the newer instruction encoding, forward references could give
2037 // negative valued IDs. This is most common for PHIs, so we use
2039 SmallVector<uint64_t, 128> Vals64;
2040 Vals64.push_back(VE.getTypeID(PN.getType()));
2041 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
2042 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64, VE);
2043 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
2045 // Emit a Vals64 vector and exit.
2046 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
2051 case Instruction::LandingPad: {
2052 const LandingPadInst &LP = cast<LandingPadInst>(I);
2053 Code = bitc::FUNC_CODE_INST_LANDINGPAD;
2054 Vals.push_back(VE.getTypeID(LP.getType()));
2055 Vals.push_back(LP.isCleanup());
2056 Vals.push_back(LP.getNumClauses());
2057 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
2059 Vals.push_back(LandingPadInst::Catch);
2061 Vals.push_back(LandingPadInst::Filter);
2062 PushValueAndType(LP.getClause(I), InstID, Vals, VE);
2067 case Instruction::Alloca: {
2068 Code = bitc::FUNC_CODE_INST_ALLOCA;
2069 const AllocaInst &AI = cast<AllocaInst>(I);
2070 Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
2071 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
2072 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
2073 unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
2074 assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
2075 "not enough bits for maximum alignment");
2076 assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
2077 AlignRecord |= AI.isUsedWithInAlloca() << 5;
2078 AlignRecord |= 1 << 6;
2079 // Reserve bit 7 for SwiftError flag.
2080 // AlignRecord |= AI.isSwiftError() << 7;
2081 Vals.push_back(AlignRecord);
2085 case Instruction::Load:
2086 if (cast<LoadInst>(I).isAtomic()) {
2087 Code = bitc::FUNC_CODE_INST_LOADATOMIC;
2088 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
2090 Code = bitc::FUNC_CODE_INST_LOAD;
2091 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) // ptr
2092 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
2094 Vals.push_back(VE.getTypeID(I.getType()));
2095 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
2096 Vals.push_back(cast<LoadInst>(I).isVolatile());
2097 if (cast<LoadInst>(I).isAtomic()) {
2098 Vals.push_back(GetEncodedOrdering(cast<LoadInst>(I).getOrdering()));
2099 Vals.push_back(GetEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
2102 case Instruction::Store:
2103 if (cast<StoreInst>(I).isAtomic())
2104 Code = bitc::FUNC_CODE_INST_STOREATOMIC;
2106 Code = bitc::FUNC_CODE_INST_STORE;
2107 PushValueAndType(I.getOperand(1), InstID, Vals, VE); // ptrty + ptr
2108 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // valty + val
2109 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
2110 Vals.push_back(cast<StoreInst>(I).isVolatile());
2111 if (cast<StoreInst>(I).isAtomic()) {
2112 Vals.push_back(GetEncodedOrdering(cast<StoreInst>(I).getOrdering()));
2113 Vals.push_back(GetEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
2116 case Instruction::AtomicCmpXchg:
2117 Code = bitc::FUNC_CODE_INST_CMPXCHG;
2118 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr
2119 PushValueAndType(I.getOperand(1), InstID, Vals, VE); // cmp.
2120 pushValue(I.getOperand(2), InstID, Vals, VE); // newval.
2121 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
2122 Vals.push_back(GetEncodedOrdering(
2123 cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
2124 Vals.push_back(GetEncodedSynchScope(
2125 cast<AtomicCmpXchgInst>(I).getSynchScope()));
2126 Vals.push_back(GetEncodedOrdering(
2127 cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
2128 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
2130 case Instruction::AtomicRMW:
2131 Code = bitc::FUNC_CODE_INST_ATOMICRMW;
2132 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr
2133 pushValue(I.getOperand(1), InstID, Vals, VE); // val.
2134 Vals.push_back(GetEncodedRMWOperation(
2135 cast<AtomicRMWInst>(I).getOperation()));
2136 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
2137 Vals.push_back(GetEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
2138 Vals.push_back(GetEncodedSynchScope(
2139 cast<AtomicRMWInst>(I).getSynchScope()));
2141 case Instruction::Fence:
2142 Code = bitc::FUNC_CODE_INST_FENCE;
2143 Vals.push_back(GetEncodedOrdering(cast<FenceInst>(I).getOrdering()));
2144 Vals.push_back(GetEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
2146 case Instruction::Call: {
2147 const CallInst &CI = cast<CallInst>(I);
2148 FunctionType *FTy = CI.getFunctionType();
2150 if (CI.hasOperandBundles())
2151 WriteOperandBundles(Stream, &CI, InstID, VE);
2153 Code = bitc::FUNC_CODE_INST_CALL;
2155 Vals.push_back(VE.getAttributeID(CI.getAttributes()));
2157 unsigned Flags = GetOptimizationFlags(&I);
2158 Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |
2159 unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
2160 unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
2161 1 << bitc::CALL_EXPLICIT_TYPE |
2162 unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
2163 unsigned(Flags != 0) << bitc::CALL_FMF);
2165 Vals.push_back(Flags);
2167 Vals.push_back(VE.getTypeID(FTy));
2168 PushValueAndType(CI.getCalledValue(), InstID, Vals, VE); // Callee
2170 // Emit value #'s for the fixed parameters.
2171 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
2172 // Check for labels (can happen with asm labels).
2173 if (FTy->getParamType(i)->isLabelTy())
2174 Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
2176 pushValue(CI.getArgOperand(i), InstID, Vals, VE); // fixed param.
2179 // Emit type/value pairs for varargs params.
2180 if (FTy->isVarArg()) {
2181 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
2183 PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE); // varargs
2187 case Instruction::VAArg:
2188 Code = bitc::FUNC_CODE_INST_VAARG;
2189 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
2190 pushValue(I.getOperand(0), InstID, Vals, VE); // valist.
2191 Vals.push_back(VE.getTypeID(I.getType())); // restype.
2195 Stream.EmitRecord(Code, Vals, AbbrevToUse);
2199 enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 };
2201 /// Determine the encoding to use for the given string name and length.
2202 static StringEncoding getStringEncoding(const char *Str, unsigned StrLen) {
2203 bool isChar6 = true;
2204 for (const char *C = Str, *E = C + StrLen; C != E; ++C) {
2206 isChar6 = BitCodeAbbrevOp::isChar6(*C);
2207 if ((unsigned char)*C & 128)
2208 // don't bother scanning the rest.
2217 /// Emit names for globals/functions etc. The VSTOffsetPlaceholder,
2218 /// BitcodeStartBit and FunctionIndex are only passed for the module-level
2219 /// VST, where we are including a function bitcode index and need to
2220 /// backpatch the VST forward declaration record.
2221 static void WriteValueSymbolTable(
2222 const ValueSymbolTable &VST, const ValueEnumerator &VE,
2223 BitstreamWriter &Stream, uint64_t VSTOffsetPlaceholder = 0,
2224 uint64_t BitcodeStartBit = 0,
2225 DenseMap<const Function *, std::unique_ptr<FunctionInfo>> *FunctionIndex =
2228 // WriteValueSymbolTableForwardDecl should have returned early as
2229 // well. Ensure this handling remains in sync by asserting that
2230 // the placeholder offset is not set.
2231 assert(VSTOffsetPlaceholder == 0);
2235 if (VSTOffsetPlaceholder > 0) {
2236 // Get the offset of the VST we are writing, and backpatch it into
2237 // the VST forward declaration record.
2238 uint64_t VSTOffset = Stream.GetCurrentBitNo();
2239 // The BitcodeStartBit was the stream offset of the actual bitcode
2240 // (e.g. excluding any initial darwin header).
2241 VSTOffset -= BitcodeStartBit;
2242 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
2243 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32);
2246 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
2248 // For the module-level VST, add abbrev Ids for the VST_CODE_FNENTRY
2249 // records, which are not used in the per-function VSTs.
2250 unsigned FnEntry8BitAbbrev;
2251 unsigned FnEntry7BitAbbrev;
2252 unsigned FnEntry6BitAbbrev;
2253 if (VSTOffsetPlaceholder > 0) {
2254 // 8-bit fixed-width VST_FNENTRY function strings.
2255 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2256 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2257 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2258 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2259 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2260 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2261 FnEntry8BitAbbrev = Stream.EmitAbbrev(Abbv);
2263 // 7-bit fixed width VST_FNENTRY function strings.
2264 Abbv = new BitCodeAbbrev();
2265 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2266 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2267 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2268 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2269 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2270 FnEntry7BitAbbrev = Stream.EmitAbbrev(Abbv);
2272 // 6-bit char6 VST_FNENTRY function strings.
2273 Abbv = new BitCodeAbbrev();
2274 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2275 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2276 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2277 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2278 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2279 FnEntry6BitAbbrev = Stream.EmitAbbrev(Abbv);
2282 // FIXME: Set up the abbrev, we know how many values there are!
2283 // FIXME: We know if the type names can use 7-bit ascii.
2284 SmallVector<unsigned, 64> NameVals;
2286 for (const ValueName &Name : VST) {
2287 // Figure out the encoding to use for the name.
2288 StringEncoding Bits =
2289 getStringEncoding(Name.getKeyData(), Name.getKeyLength());
2291 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
2292 NameVals.push_back(VE.getValueID(Name.getValue()));
2294 Function *F = dyn_cast<Function>(Name.getValue());
2296 // If value is an alias, need to get the aliased base object to
2297 // see if it is a function.
2298 auto *GA = dyn_cast<GlobalAlias>(Name.getValue());
2299 if (GA && GA->getBaseObject())
2300 F = dyn_cast<Function>(GA->getBaseObject());
2303 // VST_ENTRY: [valueid, namechar x N]
2304 // VST_FNENTRY: [valueid, funcoffset, namechar x N]
2305 // VST_BBENTRY: [bbid, namechar x N]
2307 if (isa<BasicBlock>(Name.getValue())) {
2308 Code = bitc::VST_CODE_BBENTRY;
2309 if (Bits == SE_Char6)
2310 AbbrevToUse = VST_BBENTRY_6_ABBREV;
2311 } else if (F && !F->isDeclaration()) {
2312 // Must be the module-level VST, where we pass in the Index and
2313 // have a VSTOffsetPlaceholder. The function-level VST should not
2314 // contain any Function symbols.
2315 assert(FunctionIndex);
2316 assert(VSTOffsetPlaceholder > 0);
2318 // Save the word offset of the function (from the start of the
2319 // actual bitcode written to the stream).
2320 assert(FunctionIndex->count(F) == 1);
2321 uint64_t BitcodeIndex =
2322 (*FunctionIndex)[F]->bitcodeIndex() - BitcodeStartBit;
2323 assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
2324 NameVals.push_back(BitcodeIndex / 32);
2326 Code = bitc::VST_CODE_FNENTRY;
2327 AbbrevToUse = FnEntry8BitAbbrev;
2328 if (Bits == SE_Char6)
2329 AbbrevToUse = FnEntry6BitAbbrev;
2330 else if (Bits == SE_Fixed7)
2331 AbbrevToUse = FnEntry7BitAbbrev;
2333 Code = bitc::VST_CODE_ENTRY;
2334 if (Bits == SE_Char6)
2335 AbbrevToUse = VST_ENTRY_6_ABBREV;
2336 else if (Bits == SE_Fixed7)
2337 AbbrevToUse = VST_ENTRY_7_ABBREV;
2340 for (const auto P : Name.getKey())
2341 NameVals.push_back((unsigned char)P);
2343 // Emit the finished record.
2344 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
2350 /// Emit function names and summary offsets for the combined index
2351 /// used by ThinLTO.
2352 static void WriteCombinedValueSymbolTable(const FunctionInfoIndex &Index,
2353 BitstreamWriter &Stream) {
2354 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
2356 // 8-bit fixed-width VST_COMBINED_FNENTRY function strings.
2357 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2358 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_COMBINED_FNENTRY));
2359 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2360 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2361 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2362 unsigned FnEntry8BitAbbrev = Stream.EmitAbbrev(Abbv);
2364 // 7-bit fixed width VST_COMBINED_FNENTRY function strings.
2365 Abbv = new BitCodeAbbrev();
2366 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_COMBINED_FNENTRY));
2367 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2368 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2369 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2370 unsigned FnEntry7BitAbbrev = Stream.EmitAbbrev(Abbv);
2372 // 6-bit char6 VST_COMBINED_FNENTRY function strings.
2373 Abbv = new BitCodeAbbrev();
2374 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_COMBINED_FNENTRY));
2375 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2376 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2377 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2378 unsigned FnEntry6BitAbbrev = Stream.EmitAbbrev(Abbv);
2380 // FIXME: We know if the type names can use 7-bit ascii.
2381 SmallVector<unsigned, 64> NameVals;
2383 for (const auto &FII : Index) {
2384 for (const auto &FI : FII.getValue()) {
2385 NameVals.push_back(FI->bitcodeIndex());
2387 StringRef FuncName = FII.first();
2389 // Figure out the encoding to use for the name.
2390 StringEncoding Bits = getStringEncoding(FuncName.data(), FuncName.size());
2392 // VST_COMBINED_FNENTRY: [funcsumoffset, namechar x N]
2393 unsigned AbbrevToUse = FnEntry8BitAbbrev;
2394 if (Bits == SE_Char6)
2395 AbbrevToUse = FnEntry6BitAbbrev;
2396 else if (Bits == SE_Fixed7)
2397 AbbrevToUse = FnEntry7BitAbbrev;
2399 for (const auto P : FuncName)
2400 NameVals.push_back((unsigned char)P);
2402 // Emit the finished record.
2403 Stream.EmitRecord(bitc::VST_CODE_COMBINED_FNENTRY, NameVals, AbbrevToUse);
2410 static void WriteUseList(ValueEnumerator &VE, UseListOrder &&Order,
2411 BitstreamWriter &Stream) {
2412 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
2414 if (isa<BasicBlock>(Order.V))
2415 Code = bitc::USELIST_CODE_BB;
2417 Code = bitc::USELIST_CODE_DEFAULT;
2419 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
2420 Record.push_back(VE.getValueID(Order.V));
2421 Stream.EmitRecord(Code, Record);
2424 static void WriteUseListBlock(const Function *F, ValueEnumerator &VE,
2425 BitstreamWriter &Stream) {
2426 assert(VE.shouldPreserveUseListOrder() &&
2427 "Expected to be preserving use-list order");
2429 auto hasMore = [&]() {
2430 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
2436 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
2438 WriteUseList(VE, std::move(VE.UseListOrders.back()), Stream);
2439 VE.UseListOrders.pop_back();
2444 /// \brief Save information for the given function into the function index.
2446 /// At a minimum this saves the bitcode index of the function record that
2447 /// was just written. However, if we are emitting function summary information,
2448 /// for example for ThinLTO, then a \a FunctionSummary object is created
2449 /// to hold the provided summary information.
2450 static void SaveFunctionInfo(
2452 DenseMap<const Function *, std::unique_ptr<FunctionInfo>> &FunctionIndex,
2453 unsigned NumInsts, uint64_t BitcodeIndex, bool EmitFunctionSummary) {
2454 std::unique_ptr<FunctionSummary> FuncSummary;
2455 if (EmitFunctionSummary) {
2456 FuncSummary = llvm::make_unique<FunctionSummary>(NumInsts);
2457 FuncSummary->setLocalFunction(F.hasLocalLinkage());
2460 llvm::make_unique<FunctionInfo>(BitcodeIndex, std::move(FuncSummary));
2463 /// Emit a function body to the module stream.
2464 static void WriteFunction(
2465 const Function &F, ValueEnumerator &VE, BitstreamWriter &Stream,
2466 DenseMap<const Function *, std::unique_ptr<FunctionInfo>> &FunctionIndex,
2467 bool EmitFunctionSummary) {
2468 // Save the bitcode index of the start of this function block for recording
2470 uint64_t BitcodeIndex = Stream.GetCurrentBitNo();
2472 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
2473 VE.incorporateFunction(F);
2475 SmallVector<unsigned, 64> Vals;
2477 // Emit the number of basic blocks, so the reader can create them ahead of
2479 Vals.push_back(VE.getBasicBlocks().size());
2480 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
2483 // If there are function-local constants, emit them now.
2484 unsigned CstStart, CstEnd;
2485 VE.getFunctionConstantRange(CstStart, CstEnd);
2486 WriteConstants(CstStart, CstEnd, VE, Stream, false);
2488 // If there is function-local metadata, emit it now.
2489 WriteFunctionLocalMetadata(F, VE, Stream);
2491 // Keep a running idea of what the instruction ID is.
2492 unsigned InstID = CstEnd;
2494 bool NeedsMetadataAttachment = F.hasMetadata();
2496 DILocation *LastDL = nullptr;
2497 unsigned NumInsts = 0;
2499 // Finally, emit all the instructions, in order.
2500 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
2501 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
2503 WriteInstruction(*I, InstID, VE, Stream, Vals);
2505 if (!isa<DbgInfoIntrinsic>(I))
2508 if (!I->getType()->isVoidTy())
2511 // If the instruction has metadata, write a metadata attachment later.
2512 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
2514 // If the instruction has a debug location, emit it.
2515 DILocation *DL = I->getDebugLoc();
2520 // Just repeat the same debug loc as last time.
2521 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
2525 Vals.push_back(DL->getLine());
2526 Vals.push_back(DL->getColumn());
2527 Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
2528 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
2529 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
2535 // Emit names for all the instructions etc.
2536 WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
2538 if (NeedsMetadataAttachment)
2539 WriteMetadataAttachment(F, VE, Stream);
2540 if (VE.shouldPreserveUseListOrder())
2541 WriteUseListBlock(&F, VE, Stream);
2545 SaveFunctionInfo(F, FunctionIndex, NumInsts, BitcodeIndex,
2546 EmitFunctionSummary);
2549 // Emit blockinfo, which defines the standard abbreviations etc.
2550 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
2551 // We only want to emit block info records for blocks that have multiple
2552 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
2553 // Other blocks can define their abbrevs inline.
2554 Stream.EnterBlockInfoBlock(2);
2556 { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
2557 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2558 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
2559 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2560 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2561 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2562 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2563 Abbv) != VST_ENTRY_8_ABBREV)
2564 llvm_unreachable("Unexpected abbrev ordering!");
2567 { // 7-bit fixed width VST_ENTRY strings.
2568 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2569 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2570 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2571 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2572 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2573 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2574 Abbv) != VST_ENTRY_7_ABBREV)
2575 llvm_unreachable("Unexpected abbrev ordering!");
2577 { // 6-bit char6 VST_ENTRY strings.
2578 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2579 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2580 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2581 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2582 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2583 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2584 Abbv) != VST_ENTRY_6_ABBREV)
2585 llvm_unreachable("Unexpected abbrev ordering!");
2587 { // 6-bit char6 VST_BBENTRY strings.
2588 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2589 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
2590 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2591 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2592 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2593 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2594 Abbv) != VST_BBENTRY_6_ABBREV)
2595 llvm_unreachable("Unexpected abbrev ordering!");
2600 { // SETTYPE abbrev for CONSTANTS_BLOCK.
2601 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2602 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
2603 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
2604 VE.computeBitsRequiredForTypeIndicies()));
2605 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2606 Abbv) != CONSTANTS_SETTYPE_ABBREV)
2607 llvm_unreachable("Unexpected abbrev ordering!");
2610 { // INTEGER abbrev for CONSTANTS_BLOCK.
2611 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2612 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
2613 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2614 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2615 Abbv) != CONSTANTS_INTEGER_ABBREV)
2616 llvm_unreachable("Unexpected abbrev ordering!");
2619 { // CE_CAST abbrev for CONSTANTS_BLOCK.
2620 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2621 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
2622 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
2623 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
2624 VE.computeBitsRequiredForTypeIndicies()));
2625 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2627 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2628 Abbv) != CONSTANTS_CE_CAST_Abbrev)
2629 llvm_unreachable("Unexpected abbrev ordering!");
2631 { // NULL abbrev for CONSTANTS_BLOCK.
2632 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2633 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
2634 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2635 Abbv) != CONSTANTS_NULL_Abbrev)
2636 llvm_unreachable("Unexpected abbrev ordering!");
2639 // FIXME: This should only use space for first class types!
2641 { // INST_LOAD abbrev for FUNCTION_BLOCK.
2642 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2643 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
2644 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
2645 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
2646 VE.computeBitsRequiredForTypeIndicies()));
2647 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
2648 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
2649 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2650 Abbv) != FUNCTION_INST_LOAD_ABBREV)
2651 llvm_unreachable("Unexpected abbrev ordering!");
2653 { // INST_BINOP abbrev for FUNCTION_BLOCK.
2654 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2655 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
2656 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
2657 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
2658 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2659 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2660 Abbv) != FUNCTION_INST_BINOP_ABBREV)
2661 llvm_unreachable("Unexpected abbrev ordering!");
2663 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
2664 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2665 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
2666 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
2667 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
2668 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2669 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
2670 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2671 Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV)
2672 llvm_unreachable("Unexpected abbrev ordering!");
2674 { // INST_CAST abbrev for FUNCTION_BLOCK.
2675 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2676 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
2677 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
2678 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
2679 VE.computeBitsRequiredForTypeIndicies()));
2680 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2681 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2682 Abbv) != FUNCTION_INST_CAST_ABBREV)
2683 llvm_unreachable("Unexpected abbrev ordering!");
2686 { // INST_RET abbrev for FUNCTION_BLOCK.
2687 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2688 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
2689 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2690 Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
2691 llvm_unreachable("Unexpected abbrev ordering!");
2693 { // INST_RET abbrev for FUNCTION_BLOCK.
2694 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2695 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
2696 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
2697 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2698 Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
2699 llvm_unreachable("Unexpected abbrev ordering!");
2701 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
2702 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2703 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
2704 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2705 Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
2706 llvm_unreachable("Unexpected abbrev ordering!");
2709 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2710 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
2711 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
2712 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
2713 Log2_32_Ceil(VE.getTypes().size() + 1)));
2714 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2715 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2716 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
2717 FUNCTION_INST_GEP_ABBREV)
2718 llvm_unreachable("Unexpected abbrev ordering!");
2724 /// Write the module path strings, currently only used when generating
2725 /// a combined index file.
2726 static void WriteModStrings(const FunctionInfoIndex &I,
2727 BitstreamWriter &Stream) {
2728 Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);
2730 // TODO: See which abbrev sizes we actually need to emit
2732 // 8-bit fixed-width MST_ENTRY strings.
2733 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2734 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
2735 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2736 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2737 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2738 unsigned Abbrev8Bit = Stream.EmitAbbrev(Abbv);
2740 // 7-bit fixed width MST_ENTRY strings.
2741 Abbv = new BitCodeAbbrev();
2742 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
2743 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2744 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2745 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2746 unsigned Abbrev7Bit = Stream.EmitAbbrev(Abbv);
2748 // 6-bit char6 MST_ENTRY strings.
2749 Abbv = new BitCodeAbbrev();
2750 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
2751 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2752 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2753 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2754 unsigned Abbrev6Bit = Stream.EmitAbbrev(Abbv);
2756 SmallVector<unsigned, 64> NameVals;
2757 for (const StringMapEntry<uint64_t> &MPSE : I.modPathStringEntries()) {
2758 StringEncoding Bits =
2759 getStringEncoding(MPSE.getKey().data(), MPSE.getKey().size());
2760 unsigned AbbrevToUse = Abbrev8Bit;
2761 if (Bits == SE_Char6)
2762 AbbrevToUse = Abbrev6Bit;
2763 else if (Bits == SE_Fixed7)
2764 AbbrevToUse = Abbrev7Bit;
2766 NameVals.push_back(MPSE.getValue());
2768 for (const auto P : MPSE.getKey())
2769 NameVals.push_back((unsigned char)P);
2771 // Emit the finished record.
2772 Stream.EmitRecord(bitc::MST_CODE_ENTRY, NameVals, AbbrevToUse);
2778 // Helper to emit a single function summary record.
2779 static void WritePerModuleFunctionSummaryRecord(
2780 SmallVector<unsigned, 64> &NameVals, FunctionSummary *FS, unsigned ValueID,
2781 unsigned FSAbbrev, BitstreamWriter &Stream) {
2783 NameVals.push_back(ValueID);
2784 NameVals.push_back(FS->isLocalFunction());
2785 NameVals.push_back(FS->instCount());
2787 // Emit the finished record.
2788 Stream.EmitRecord(bitc::FS_CODE_PERMODULE_ENTRY, NameVals, FSAbbrev);
2792 /// Emit the per-module function summary section alongside the rest of
2793 /// the module's bitcode.
2794 static void WritePerModuleFunctionSummary(
2795 DenseMap<const Function *, std::unique_ptr<FunctionInfo>> &FunctionIndex,
2796 const Module *M, const ValueEnumerator &VE, BitstreamWriter &Stream) {
2797 Stream.EnterSubblock(bitc::FUNCTION_SUMMARY_BLOCK_ID, 3);
2799 // Abbrev for FS_CODE_PERMODULE_ENTRY.
2800 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2801 Abbv->Add(BitCodeAbbrevOp(bitc::FS_CODE_PERMODULE_ENTRY));
2802 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
2803 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // islocal
2804 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
2805 unsigned FSAbbrev = Stream.EmitAbbrev(Abbv);
2807 SmallVector<unsigned, 64> NameVals;
2808 for (auto &I : FunctionIndex) {
2809 // Skip anonymous functions. We will emit a function summary for
2810 // any aliases below.
2811 if (!I.first->hasName())
2814 WritePerModuleFunctionSummaryRecord(
2815 NameVals, I.second->functionSummary(),
2816 VE.getValueID(M->getValueSymbolTable().lookup(I.first->getName())),
2820 for (const GlobalAlias &A : M->aliases()) {
2821 if (!A.getBaseObject())
2823 const Function *F = dyn_cast<Function>(A.getBaseObject());
2824 if (!F || F->isDeclaration())
2827 assert(FunctionIndex.count(F) == 1);
2828 WritePerModuleFunctionSummaryRecord(
2829 NameVals, FunctionIndex[F]->functionSummary(),
2830 VE.getValueID(M->getValueSymbolTable().lookup(A.getName())), FSAbbrev,
2837 /// Emit the combined function summary section into the combined index
2839 static void WriteCombinedFunctionSummary(const FunctionInfoIndex &I,
2840 BitstreamWriter &Stream) {
2841 Stream.EnterSubblock(bitc::FUNCTION_SUMMARY_BLOCK_ID, 3);
2843 // Abbrev for FS_CODE_COMBINED_ENTRY.
2844 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2845 Abbv->Add(BitCodeAbbrevOp(bitc::FS_CODE_COMBINED_ENTRY));
2846 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
2847 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
2848 unsigned FSAbbrev = Stream.EmitAbbrev(Abbv);
2850 SmallVector<unsigned, 64> NameVals;
2851 for (const auto &FII : I) {
2852 for (auto &FI : FII.getValue()) {
2853 FunctionSummary *FS = FI->functionSummary();
2856 NameVals.push_back(I.getModuleId(FS->modulePath()));
2857 NameVals.push_back(FS->instCount());
2859 // Record the starting offset of this summary entry for use
2860 // in the VST entry. Add the current code size since the
2861 // reader will invoke readRecord after the abbrev id read.
2862 FI->setBitcodeIndex(Stream.GetCurrentBitNo() + Stream.GetAbbrevIDWidth());
2864 // Emit the finished record.
2865 Stream.EmitRecord(bitc::FS_CODE_COMBINED_ENTRY, NameVals, FSAbbrev);
2873 // Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
2874 // current llvm version, and a record for the epoch number.
2875 static void WriteIdentificationBlock(const Module *M, BitstreamWriter &Stream) {
2876 Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);
2878 // Write the "user readable" string identifying the bitcode producer
2879 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2880 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING));
2881 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2882 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2883 auto StringAbbrev = Stream.EmitAbbrev(Abbv);
2884 WriteStringRecord(bitc::IDENTIFICATION_CODE_STRING,
2885 "LLVM" LLVM_VERSION_STRING, StringAbbrev, Stream);
2887 // Write the epoch version
2888 Abbv = new BitCodeAbbrev();
2889 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH));
2890 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2891 auto EpochAbbrev = Stream.EmitAbbrev(Abbv);
2892 SmallVector<unsigned, 1> Vals = {bitc::BITCODE_CURRENT_EPOCH};
2893 Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
2897 /// WriteModule - Emit the specified module to the bitstream.
2898 static void WriteModule(const Module *M, BitstreamWriter &Stream,
2899 bool ShouldPreserveUseListOrder,
2900 uint64_t BitcodeStartBit, bool EmitFunctionSummary) {
2901 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
2903 SmallVector<unsigned, 1> Vals;
2904 unsigned CurVersion = 1;
2905 Vals.push_back(CurVersion);
2906 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
2908 // Analyze the module, enumerating globals, functions, etc.
2909 ValueEnumerator VE(*M, ShouldPreserveUseListOrder);
2911 // Emit blockinfo, which defines the standard abbreviations etc.
2912 WriteBlockInfo(VE, Stream);
2914 // Emit information about attribute groups.
2915 WriteAttributeGroupTable(VE, Stream);
2917 // Emit information about parameter attributes.
2918 WriteAttributeTable(VE, Stream);
2920 // Emit information describing all of the types in the module.
2921 WriteTypeTable(VE, Stream);
2923 writeComdats(VE, Stream);
2925 // Emit top-level description of module, including target triple, inline asm,
2926 // descriptors for global variables, and function prototype info.
2927 uint64_t VSTOffsetPlaceholder = WriteModuleInfo(M, VE, Stream);
2930 WriteModuleConstants(VE, Stream);
2933 WriteModuleMetadata(M, VE, Stream);
2936 WriteModuleMetadataStore(M, Stream);
2938 // Emit module-level use-lists.
2939 if (VE.shouldPreserveUseListOrder())
2940 WriteUseListBlock(nullptr, VE, Stream);
2942 WriteOperandBundleTags(M, Stream);
2944 // Emit function bodies.
2945 DenseMap<const Function *, std::unique_ptr<FunctionInfo>> FunctionIndex;
2946 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F)
2947 if (!F->isDeclaration())
2948 WriteFunction(*F, VE, Stream, FunctionIndex, EmitFunctionSummary);
2950 // Need to write after the above call to WriteFunction which populates
2951 // the summary information in the index.
2952 if (EmitFunctionSummary)
2953 WritePerModuleFunctionSummary(FunctionIndex, M, VE, Stream);
2955 WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream,
2956 VSTOffsetPlaceholder, BitcodeStartBit, &FunctionIndex);
2961 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
2962 /// header and trailer to make it compatible with the system archiver. To do
2963 /// this we emit the following header, and then emit a trailer that pads the
2964 /// file out to be a multiple of 16 bytes.
2966 /// struct bc_header {
2967 /// uint32_t Magic; // 0x0B17C0DE
2968 /// uint32_t Version; // Version, currently always 0.
2969 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
2970 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
2971 /// uint32_t CPUType; // CPU specifier.
2972 /// ... potentially more later ...
2975 DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
2976 DarwinBCHeaderSize = 5*4
2979 static void WriteInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
2980 uint32_t &Position) {
2981 support::endian::write32le(&Buffer[Position], Value);
2985 static void EmitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
2987 unsigned CPUType = ~0U;
2989 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
2990 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
2991 // number from /usr/include/mach/machine.h. It is ok to reproduce the
2992 // specific constants here because they are implicitly part of the Darwin ABI.
2994 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
2995 DARWIN_CPU_TYPE_X86 = 7,
2996 DARWIN_CPU_TYPE_ARM = 12,
2997 DARWIN_CPU_TYPE_POWERPC = 18
3000 Triple::ArchType Arch = TT.getArch();
3001 if (Arch == Triple::x86_64)
3002 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
3003 else if (Arch == Triple::x86)
3004 CPUType = DARWIN_CPU_TYPE_X86;
3005 else if (Arch == Triple::ppc)
3006 CPUType = DARWIN_CPU_TYPE_POWERPC;
3007 else if (Arch == Triple::ppc64)
3008 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
3009 else if (Arch == Triple::arm || Arch == Triple::thumb)
3010 CPUType = DARWIN_CPU_TYPE_ARM;
3012 // Traditional Bitcode starts after header.
3013 assert(Buffer.size() >= DarwinBCHeaderSize &&
3014 "Expected header size to be reserved");
3015 unsigned BCOffset = DarwinBCHeaderSize;
3016 unsigned BCSize = Buffer.size()-DarwinBCHeaderSize;
3018 // Write the magic and version.
3019 unsigned Position = 0;
3020 WriteInt32ToBuffer(0x0B17C0DE , Buffer, Position);
3021 WriteInt32ToBuffer(0 , Buffer, Position); // Version.
3022 WriteInt32ToBuffer(BCOffset , Buffer, Position);
3023 WriteInt32ToBuffer(BCSize , Buffer, Position);
3024 WriteInt32ToBuffer(CPUType , Buffer, Position);
3026 // If the file is not a multiple of 16 bytes, insert dummy padding.
3027 while (Buffer.size() & 15)
3028 Buffer.push_back(0);
3031 /// Helper to write the header common to all bitcode files.
3032 static void WriteBitcodeHeader(BitstreamWriter &Stream) {
3033 // Emit the file header.
3034 Stream.Emit((unsigned)'B', 8);
3035 Stream.Emit((unsigned)'C', 8);
3036 Stream.Emit(0x0, 4);
3037 Stream.Emit(0xC, 4);
3038 Stream.Emit(0xE, 4);
3039 Stream.Emit(0xD, 4);
3042 /// WriteBitcodeToFile - Write the specified module to the specified output
3044 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out,
3045 bool ShouldPreserveUseListOrder,
3046 bool EmitFunctionSummary) {
3047 SmallVector<char, 0> Buffer;
3048 Buffer.reserve(256*1024);
3050 // If this is darwin or another generic macho target, reserve space for the
3052 Triple TT(M->getTargetTriple());
3053 if (TT.isOSDarwin())
3054 Buffer.insert(Buffer.begin(), DarwinBCHeaderSize, 0);
3056 // Emit the module into the buffer.
3058 BitstreamWriter Stream(Buffer);
3059 // Save the start bit of the actual bitcode, in case there is space
3060 // saved at the start for the darwin header above. The reader stream
3061 // will start at the bitcode, and we need the offset of the VST
3063 uint64_t BitcodeStartBit = Stream.GetCurrentBitNo();
3065 // Emit the file header.
3066 WriteBitcodeHeader(Stream);
3068 WriteIdentificationBlock(M, Stream);
3071 WriteModule(M, Stream, ShouldPreserveUseListOrder, BitcodeStartBit,
3072 EmitFunctionSummary);
3075 if (TT.isOSDarwin())
3076 EmitDarwinBCHeaderAndTrailer(Buffer, TT);
3078 // Write the generated bitstream to "Out".
3079 Out.write((char*)&Buffer.front(), Buffer.size());
3082 // Write the specified function summary index to the given raw output stream,
3083 // where it will be written in a new bitcode block. This is used when
3084 // writing the combined index file for ThinLTO.
3085 void llvm::WriteFunctionSummaryToFile(const FunctionInfoIndex &Index,
3087 SmallVector<char, 0> Buffer;
3088 Buffer.reserve(256 * 1024);
3090 BitstreamWriter Stream(Buffer);
3092 // Emit the bitcode header.
3093 WriteBitcodeHeader(Stream);
3095 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
3097 SmallVector<unsigned, 1> Vals;
3098 unsigned CurVersion = 1;
3099 Vals.push_back(CurVersion);
3100 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
3102 // Write the module paths in the combined index.
3103 WriteModStrings(Index, Stream);
3105 // Write the function summary combined index records.
3106 WriteCombinedFunctionSummary(Index, Stream);
3108 // Need a special VST writer for the combined index (we don't have a
3109 // real VST and real values when this is invoked).
3110 WriteCombinedValueSymbolTable(Index, Stream);
3114 Out.write((char *)&Buffer.front(), Buffer.size());