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::NonLazyBind:
206 return bitc::ATTR_KIND_NON_LAZY_BIND;
207 case Attribute::NonNull:
208 return bitc::ATTR_KIND_NON_NULL;
209 case Attribute::Dereferenceable:
210 return bitc::ATTR_KIND_DEREFERENCEABLE;
211 case Attribute::DereferenceableOrNull:
212 return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL;
213 case Attribute::NoRedZone:
214 return bitc::ATTR_KIND_NO_RED_ZONE;
215 case Attribute::NoReturn:
216 return bitc::ATTR_KIND_NO_RETURN;
217 case Attribute::NoUnwind:
218 return bitc::ATTR_KIND_NO_UNWIND;
219 case Attribute::OptimizeForSize:
220 return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
221 case Attribute::OptimizeNone:
222 return bitc::ATTR_KIND_OPTIMIZE_NONE;
223 case Attribute::ReadNone:
224 return bitc::ATTR_KIND_READ_NONE;
225 case Attribute::ReadOnly:
226 return bitc::ATTR_KIND_READ_ONLY;
227 case Attribute::Returned:
228 return bitc::ATTR_KIND_RETURNED;
229 case Attribute::ReturnsTwice:
230 return bitc::ATTR_KIND_RETURNS_TWICE;
231 case Attribute::SExt:
232 return bitc::ATTR_KIND_S_EXT;
233 case Attribute::StackAlignment:
234 return bitc::ATTR_KIND_STACK_ALIGNMENT;
235 case Attribute::StackProtect:
236 return bitc::ATTR_KIND_STACK_PROTECT;
237 case Attribute::StackProtectReq:
238 return bitc::ATTR_KIND_STACK_PROTECT_REQ;
239 case Attribute::StackProtectStrong:
240 return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
241 case Attribute::SafeStack:
242 return bitc::ATTR_KIND_SAFESTACK;
243 case Attribute::StructRet:
244 return bitc::ATTR_KIND_STRUCT_RET;
245 case Attribute::SanitizeAddress:
246 return bitc::ATTR_KIND_SANITIZE_ADDRESS;
247 case Attribute::SanitizeThread:
248 return bitc::ATTR_KIND_SANITIZE_THREAD;
249 case Attribute::SanitizeMemory:
250 return bitc::ATTR_KIND_SANITIZE_MEMORY;
251 case Attribute::UWTable:
252 return bitc::ATTR_KIND_UW_TABLE;
253 case Attribute::ZExt:
254 return bitc::ATTR_KIND_Z_EXT;
255 case Attribute::EndAttrKinds:
256 llvm_unreachable("Can not encode end-attribute kinds marker.");
257 case Attribute::None:
258 llvm_unreachable("Can not encode none-attribute.");
261 llvm_unreachable("Trying to encode unknown attribute");
264 static void WriteAttributeGroupTable(const ValueEnumerator &VE,
265 BitstreamWriter &Stream) {
266 const std::vector<AttributeSet> &AttrGrps = VE.getAttributeGroups();
267 if (AttrGrps.empty()) return;
269 Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
271 SmallVector<uint64_t, 64> Record;
272 for (unsigned i = 0, e = AttrGrps.size(); i != e; ++i) {
273 AttributeSet AS = AttrGrps[i];
274 for (unsigned i = 0, e = AS.getNumSlots(); i != e; ++i) {
275 AttributeSet A = AS.getSlotAttributes(i);
277 Record.push_back(VE.getAttributeGroupID(A));
278 Record.push_back(AS.getSlotIndex(i));
280 for (AttributeSet::iterator I = AS.begin(0), E = AS.end(0);
283 if (Attr.isEnumAttribute()) {
285 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
286 } else if (Attr.isIntAttribute()) {
288 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
289 Record.push_back(Attr.getValueAsInt());
291 StringRef Kind = Attr.getKindAsString();
292 StringRef Val = Attr.getValueAsString();
294 Record.push_back(Val.empty() ? 3 : 4);
295 Record.append(Kind.begin(), Kind.end());
298 Record.append(Val.begin(), Val.end());
304 Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
312 static void WriteAttributeTable(const ValueEnumerator &VE,
313 BitstreamWriter &Stream) {
314 const std::vector<AttributeSet> &Attrs = VE.getAttributes();
315 if (Attrs.empty()) return;
317 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
319 SmallVector<uint64_t, 64> Record;
320 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
321 const AttributeSet &A = Attrs[i];
322 for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i)
323 Record.push_back(VE.getAttributeGroupID(A.getSlotAttributes(i)));
325 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
332 /// WriteTypeTable - Write out the type table for a module.
333 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
334 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
336 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
337 SmallVector<uint64_t, 64> TypeVals;
339 uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies();
341 // Abbrev for TYPE_CODE_POINTER.
342 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
343 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
344 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
345 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
346 unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
348 // Abbrev for TYPE_CODE_FUNCTION.
349 Abbv = new BitCodeAbbrev();
350 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
351 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
352 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
353 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
355 unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
357 // Abbrev for TYPE_CODE_STRUCT_ANON.
358 Abbv = new BitCodeAbbrev();
359 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
360 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
361 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
362 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
364 unsigned StructAnonAbbrev = Stream.EmitAbbrev(Abbv);
366 // Abbrev for TYPE_CODE_STRUCT_NAME.
367 Abbv = new BitCodeAbbrev();
368 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
369 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
370 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
371 unsigned StructNameAbbrev = Stream.EmitAbbrev(Abbv);
373 // Abbrev for TYPE_CODE_STRUCT_NAMED.
374 Abbv = new BitCodeAbbrev();
375 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
376 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
377 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
378 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
380 unsigned StructNamedAbbrev = Stream.EmitAbbrev(Abbv);
382 // Abbrev for TYPE_CODE_ARRAY.
383 Abbv = new BitCodeAbbrev();
384 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
385 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
386 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
388 unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
390 // Emit an entry count so the reader can reserve space.
391 TypeVals.push_back(TypeList.size());
392 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
395 // Loop over all of the types, emitting each in turn.
396 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
397 Type *T = TypeList[i];
401 switch (T->getTypeID()) {
402 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
403 case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break;
404 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
405 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
406 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
407 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
408 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
409 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
410 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
411 case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break;
412 case Type::TokenTyID: Code = bitc::TYPE_CODE_TOKEN; break;
413 case Type::IntegerTyID:
415 Code = bitc::TYPE_CODE_INTEGER;
416 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
418 case Type::PointerTyID: {
419 PointerType *PTy = cast<PointerType>(T);
420 // POINTER: [pointee type, address space]
421 Code = bitc::TYPE_CODE_POINTER;
422 TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
423 unsigned AddressSpace = PTy->getAddressSpace();
424 TypeVals.push_back(AddressSpace);
425 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
428 case Type::FunctionTyID: {
429 FunctionType *FT = cast<FunctionType>(T);
430 // FUNCTION: [isvararg, retty, paramty x N]
431 Code = bitc::TYPE_CODE_FUNCTION;
432 TypeVals.push_back(FT->isVarArg());
433 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
434 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
435 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
436 AbbrevToUse = FunctionAbbrev;
439 case Type::StructTyID: {
440 StructType *ST = cast<StructType>(T);
441 // STRUCT: [ispacked, eltty x N]
442 TypeVals.push_back(ST->isPacked());
443 // Output all of the element types.
444 for (StructType::element_iterator I = ST->element_begin(),
445 E = ST->element_end(); I != E; ++I)
446 TypeVals.push_back(VE.getTypeID(*I));
448 if (ST->isLiteral()) {
449 Code = bitc::TYPE_CODE_STRUCT_ANON;
450 AbbrevToUse = StructAnonAbbrev;
452 if (ST->isOpaque()) {
453 Code = bitc::TYPE_CODE_OPAQUE;
455 Code = bitc::TYPE_CODE_STRUCT_NAMED;
456 AbbrevToUse = StructNamedAbbrev;
459 // Emit the name if it is present.
460 if (!ST->getName().empty())
461 WriteStringRecord(bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
462 StructNameAbbrev, Stream);
466 case Type::ArrayTyID: {
467 ArrayType *AT = cast<ArrayType>(T);
468 // ARRAY: [numelts, eltty]
469 Code = bitc::TYPE_CODE_ARRAY;
470 TypeVals.push_back(AT->getNumElements());
471 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
472 AbbrevToUse = ArrayAbbrev;
475 case Type::VectorTyID: {
476 VectorType *VT = cast<VectorType>(T);
477 // VECTOR [numelts, eltty]
478 Code = bitc::TYPE_CODE_VECTOR;
479 TypeVals.push_back(VT->getNumElements());
480 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
485 // Emit the finished record.
486 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
493 static unsigned getEncodedLinkage(const GlobalValue &GV) {
494 switch (GV.getLinkage()) {
495 case GlobalValue::ExternalLinkage:
497 case GlobalValue::WeakAnyLinkage:
499 case GlobalValue::AppendingLinkage:
501 case GlobalValue::InternalLinkage:
503 case GlobalValue::LinkOnceAnyLinkage:
505 case GlobalValue::ExternalWeakLinkage:
507 case GlobalValue::CommonLinkage:
509 case GlobalValue::PrivateLinkage:
511 case GlobalValue::WeakODRLinkage:
513 case GlobalValue::LinkOnceODRLinkage:
515 case GlobalValue::AvailableExternallyLinkage:
518 llvm_unreachable("Invalid linkage");
521 static unsigned getEncodedVisibility(const GlobalValue &GV) {
522 switch (GV.getVisibility()) {
523 case GlobalValue::DefaultVisibility: return 0;
524 case GlobalValue::HiddenVisibility: return 1;
525 case GlobalValue::ProtectedVisibility: return 2;
527 llvm_unreachable("Invalid visibility");
530 static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
531 switch (GV.getDLLStorageClass()) {
532 case GlobalValue::DefaultStorageClass: return 0;
533 case GlobalValue::DLLImportStorageClass: return 1;
534 case GlobalValue::DLLExportStorageClass: return 2;
536 llvm_unreachable("Invalid DLL storage class");
539 static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
540 switch (GV.getThreadLocalMode()) {
541 case GlobalVariable::NotThreadLocal: return 0;
542 case GlobalVariable::GeneralDynamicTLSModel: return 1;
543 case GlobalVariable::LocalDynamicTLSModel: return 2;
544 case GlobalVariable::InitialExecTLSModel: return 3;
545 case GlobalVariable::LocalExecTLSModel: return 4;
547 llvm_unreachable("Invalid TLS model");
550 static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
551 switch (C.getSelectionKind()) {
553 return bitc::COMDAT_SELECTION_KIND_ANY;
554 case Comdat::ExactMatch:
555 return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
556 case Comdat::Largest:
557 return bitc::COMDAT_SELECTION_KIND_LARGEST;
558 case Comdat::NoDuplicates:
559 return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
560 case Comdat::SameSize:
561 return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
563 llvm_unreachable("Invalid selection kind");
566 static void writeComdats(const ValueEnumerator &VE, BitstreamWriter &Stream) {
567 SmallVector<uint16_t, 64> Vals;
568 for (const Comdat *C : VE.getComdats()) {
569 // COMDAT: [selection_kind, name]
570 Vals.push_back(getEncodedComdatSelectionKind(*C));
571 size_t Size = C->getName().size();
572 assert(isUInt<16>(Size));
573 Vals.push_back(Size);
574 for (char Chr : C->getName())
575 Vals.push_back((unsigned char)Chr);
576 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
581 /// Write a record that will eventually hold the word offset of the
582 /// module-level VST. For now the offset is 0, which will be backpatched
583 /// after the real VST is written. Returns the bit offset to backpatch.
584 static uint64_t WriteValueSymbolTableForwardDecl(const ValueSymbolTable &VST,
585 BitstreamWriter &Stream) {
586 if (VST.empty()) return 0;
588 // Write a placeholder value in for the offset of the real VST,
589 // which is written after the function blocks so that it can include
590 // the offset of each function. The placeholder offset will be
591 // updated when the real VST is written.
592 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
593 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET));
594 // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
595 // hold the real VST offset. Must use fixed instead of VBR as we don't
596 // know how many VBR chunks to reserve ahead of time.
597 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
598 unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(Abbv);
600 // Emit the placeholder
601 uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0};
602 Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
604 // Compute and return the bit offset to the placeholder, which will be
605 // patched when the real VST is written. We can simply subtract the 32-bit
606 // fixed size from the current bit number to get the location to backpatch.
607 return Stream.GetCurrentBitNo() - 32;
610 /// Emit top-level description of module, including target triple, inline asm,
611 /// descriptors for global variables, and function prototype info.
612 /// Returns the bit offset to backpatch with the location of the real VST.
613 static uint64_t WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
614 BitstreamWriter &Stream) {
615 // Emit various pieces of data attached to a module.
616 if (!M->getTargetTriple().empty())
617 WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
619 const std::string &DL = M->getDataLayoutStr();
621 WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/, Stream);
622 if (!M->getModuleInlineAsm().empty())
623 WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
626 // Emit information about sections and GC, computing how many there are. Also
627 // compute the maximum alignment value.
628 std::map<std::string, unsigned> SectionMap;
629 std::map<std::string, unsigned> GCMap;
630 unsigned MaxAlignment = 0;
631 unsigned MaxGlobalType = 0;
632 for (const GlobalValue &GV : M->globals()) {
633 MaxAlignment = std::max(MaxAlignment, GV.getAlignment());
634 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
635 if (GV.hasSection()) {
636 // Give section names unique ID's.
637 unsigned &Entry = SectionMap[GV.getSection()];
639 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
641 Entry = SectionMap.size();
645 for (const Function &F : *M) {
646 MaxAlignment = std::max(MaxAlignment, F.getAlignment());
647 if (F.hasSection()) {
648 // Give section names unique ID's.
649 unsigned &Entry = SectionMap[F.getSection()];
651 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
653 Entry = SectionMap.size();
657 // Same for GC names.
658 unsigned &Entry = GCMap[F.getGC()];
660 WriteStringRecord(bitc::MODULE_CODE_GCNAME, F.getGC(),
662 Entry = GCMap.size();
667 // Emit abbrev for globals, now that we know # sections and max alignment.
668 unsigned SimpleGVarAbbrev = 0;
669 if (!M->global_empty()) {
670 // Add an abbrev for common globals with no visibility or thread localness.
671 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
672 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
673 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
674 Log2_32_Ceil(MaxGlobalType+1)));
675 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2
676 //| explicitType << 1
678 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
679 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
680 if (MaxAlignment == 0) // Alignment.
681 Abbv->Add(BitCodeAbbrevOp(0));
683 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
684 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
685 Log2_32_Ceil(MaxEncAlignment+1)));
687 if (SectionMap.empty()) // Section.
688 Abbv->Add(BitCodeAbbrevOp(0));
690 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
691 Log2_32_Ceil(SectionMap.size()+1)));
692 // Don't bother emitting vis + thread local.
693 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
696 // Emit the global variable information.
697 SmallVector<unsigned, 64> Vals;
698 for (const GlobalVariable &GV : M->globals()) {
699 unsigned AbbrevToUse = 0;
701 // GLOBALVAR: [type, isconst, initid,
702 // linkage, alignment, section, visibility, threadlocal,
703 // unnamed_addr, externally_initialized, dllstorageclass,
705 Vals.push_back(VE.getTypeID(GV.getValueType()));
706 Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
707 Vals.push_back(GV.isDeclaration() ? 0 :
708 (VE.getValueID(GV.getInitializer()) + 1));
709 Vals.push_back(getEncodedLinkage(GV));
710 Vals.push_back(Log2_32(GV.getAlignment())+1);
711 Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0);
712 if (GV.isThreadLocal() ||
713 GV.getVisibility() != GlobalValue::DefaultVisibility ||
714 GV.hasUnnamedAddr() || GV.isExternallyInitialized() ||
715 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
717 Vals.push_back(getEncodedVisibility(GV));
718 Vals.push_back(getEncodedThreadLocalMode(GV));
719 Vals.push_back(GV.hasUnnamedAddr());
720 Vals.push_back(GV.isExternallyInitialized());
721 Vals.push_back(getEncodedDLLStorageClass(GV));
722 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
724 AbbrevToUse = SimpleGVarAbbrev;
727 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
731 // Emit the function proto information.
732 for (const Function &F : *M) {
733 // FUNCTION: [type, callingconv, isproto, linkage, paramattrs, alignment,
734 // section, visibility, gc, unnamed_addr, prologuedata,
735 // dllstorageclass, comdat, prefixdata, personalityfn]
736 Vals.push_back(VE.getTypeID(F.getFunctionType()));
737 Vals.push_back(F.getCallingConv());
738 Vals.push_back(F.isDeclaration());
739 Vals.push_back(getEncodedLinkage(F));
740 Vals.push_back(VE.getAttributeID(F.getAttributes()));
741 Vals.push_back(Log2_32(F.getAlignment())+1);
742 Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0);
743 Vals.push_back(getEncodedVisibility(F));
744 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
745 Vals.push_back(F.hasUnnamedAddr());
746 Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
748 Vals.push_back(getEncodedDLLStorageClass(F));
749 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
750 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
753 F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
755 unsigned AbbrevToUse = 0;
756 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
760 // Emit the alias information.
761 for (const GlobalAlias &A : M->aliases()) {
762 // ALIAS: [alias type, aliasee val#, linkage, visibility]
763 Vals.push_back(VE.getTypeID(A.getValueType()));
764 Vals.push_back(A.getType()->getAddressSpace());
765 Vals.push_back(VE.getValueID(A.getAliasee()));
766 Vals.push_back(getEncodedLinkage(A));
767 Vals.push_back(getEncodedVisibility(A));
768 Vals.push_back(getEncodedDLLStorageClass(A));
769 Vals.push_back(getEncodedThreadLocalMode(A));
770 Vals.push_back(A.hasUnnamedAddr());
771 unsigned AbbrevToUse = 0;
772 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
776 uint64_t VSTOffsetPlaceholder =
777 WriteValueSymbolTableForwardDecl(M->getValueSymbolTable(), Stream);
778 return VSTOffsetPlaceholder;
781 static uint64_t GetOptimizationFlags(const Value *V) {
784 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
785 if (OBO->hasNoSignedWrap())
786 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
787 if (OBO->hasNoUnsignedWrap())
788 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
789 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
791 Flags |= 1 << bitc::PEO_EXACT;
792 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
793 if (FPMO->hasUnsafeAlgebra())
794 Flags |= FastMathFlags::UnsafeAlgebra;
795 if (FPMO->hasNoNaNs())
796 Flags |= FastMathFlags::NoNaNs;
797 if (FPMO->hasNoInfs())
798 Flags |= FastMathFlags::NoInfs;
799 if (FPMO->hasNoSignedZeros())
800 Flags |= FastMathFlags::NoSignedZeros;
801 if (FPMO->hasAllowReciprocal())
802 Flags |= FastMathFlags::AllowReciprocal;
808 static void WriteValueAsMetadata(const ValueAsMetadata *MD,
809 const ValueEnumerator &VE,
810 BitstreamWriter &Stream,
811 SmallVectorImpl<uint64_t> &Record) {
812 // Mimic an MDNode with a value as one operand.
813 Value *V = MD->getValue();
814 Record.push_back(VE.getTypeID(V->getType()));
815 Record.push_back(VE.getValueID(V));
816 Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
820 static void WriteMDTuple(const MDTuple *N, const ValueEnumerator &VE,
821 BitstreamWriter &Stream,
822 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
823 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
824 Metadata *MD = N->getOperand(i);
825 assert(!(MD && isa<LocalAsMetadata>(MD)) &&
826 "Unexpected function-local metadata");
827 Record.push_back(VE.getMetadataOrNullID(MD));
829 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
830 : bitc::METADATA_NODE,
835 static void WriteDILocation(const DILocation *N, const ValueEnumerator &VE,
836 BitstreamWriter &Stream,
837 SmallVectorImpl<uint64_t> &Record,
839 Record.push_back(N->isDistinct());
840 Record.push_back(N->getLine());
841 Record.push_back(N->getColumn());
842 Record.push_back(VE.getMetadataID(N->getScope()));
843 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
845 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
849 static void WriteGenericDINode(const GenericDINode *N,
850 const ValueEnumerator &VE,
851 BitstreamWriter &Stream,
852 SmallVectorImpl<uint64_t> &Record,
854 Record.push_back(N->isDistinct());
855 Record.push_back(N->getTag());
856 Record.push_back(0); // Per-tag version field; unused for now.
858 for (auto &I : N->operands())
859 Record.push_back(VE.getMetadataOrNullID(I));
861 Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
865 static uint64_t rotateSign(int64_t I) {
867 return I < 0 ? ~(U << 1) : U << 1;
870 static void WriteDISubrange(const DISubrange *N, const ValueEnumerator &,
871 BitstreamWriter &Stream,
872 SmallVectorImpl<uint64_t> &Record,
874 Record.push_back(N->isDistinct());
875 Record.push_back(N->getCount());
876 Record.push_back(rotateSign(N->getLowerBound()));
878 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
882 static void WriteDIEnumerator(const DIEnumerator *N, const ValueEnumerator &VE,
883 BitstreamWriter &Stream,
884 SmallVectorImpl<uint64_t> &Record,
886 Record.push_back(N->isDistinct());
887 Record.push_back(rotateSign(N->getValue()));
888 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
890 Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
894 static void WriteDIBasicType(const DIBasicType *N, const ValueEnumerator &VE,
895 BitstreamWriter &Stream,
896 SmallVectorImpl<uint64_t> &Record,
898 Record.push_back(N->isDistinct());
899 Record.push_back(N->getTag());
900 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
901 Record.push_back(N->getSizeInBits());
902 Record.push_back(N->getAlignInBits());
903 Record.push_back(N->getEncoding());
905 Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
909 static void WriteDIDerivedType(const DIDerivedType *N,
910 const ValueEnumerator &VE,
911 BitstreamWriter &Stream,
912 SmallVectorImpl<uint64_t> &Record,
914 Record.push_back(N->isDistinct());
915 Record.push_back(N->getTag());
916 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
917 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
918 Record.push_back(N->getLine());
919 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
920 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
921 Record.push_back(N->getSizeInBits());
922 Record.push_back(N->getAlignInBits());
923 Record.push_back(N->getOffsetInBits());
924 Record.push_back(N->getFlags());
925 Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
927 Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
931 static void WriteDICompositeType(const DICompositeType *N,
932 const ValueEnumerator &VE,
933 BitstreamWriter &Stream,
934 SmallVectorImpl<uint64_t> &Record,
936 Record.push_back(N->isDistinct());
937 Record.push_back(N->getTag());
938 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
939 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
940 Record.push_back(N->getLine());
941 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
942 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
943 Record.push_back(N->getSizeInBits());
944 Record.push_back(N->getAlignInBits());
945 Record.push_back(N->getOffsetInBits());
946 Record.push_back(N->getFlags());
947 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
948 Record.push_back(N->getRuntimeLang());
949 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
950 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
951 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
953 Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
957 static void WriteDISubroutineType(const DISubroutineType *N,
958 const ValueEnumerator &VE,
959 BitstreamWriter &Stream,
960 SmallVectorImpl<uint64_t> &Record,
962 Record.push_back(N->isDistinct());
963 Record.push_back(N->getFlags());
964 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
966 Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
970 static void WriteDIFile(const DIFile *N, const ValueEnumerator &VE,
971 BitstreamWriter &Stream,
972 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
973 Record.push_back(N->isDistinct());
974 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
975 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
977 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
981 static void WriteDICompileUnit(const DICompileUnit *N,
982 const ValueEnumerator &VE,
983 BitstreamWriter &Stream,
984 SmallVectorImpl<uint64_t> &Record,
986 assert(N->isDistinct() && "Expected distinct compile units");
987 Record.push_back(/* IsDistinct */ true);
988 Record.push_back(N->getSourceLanguage());
989 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
990 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
991 Record.push_back(N->isOptimized());
992 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
993 Record.push_back(N->getRuntimeVersion());
994 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
995 Record.push_back(N->getEmissionKind());
996 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
997 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
998 Record.push_back(VE.getMetadataOrNullID(N->getSubprograms().get()));
999 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
1000 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
1001 Record.push_back(N->getDWOId());
1003 Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
1007 static void WriteDISubprogram(const DISubprogram *N, const ValueEnumerator &VE,
1008 BitstreamWriter &Stream,
1009 SmallVectorImpl<uint64_t> &Record,
1011 Record.push_back(N->isDistinct());
1012 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1013 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1014 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1015 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1016 Record.push_back(N->getLine());
1017 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1018 Record.push_back(N->isLocalToUnit());
1019 Record.push_back(N->isDefinition());
1020 Record.push_back(N->getScopeLine());
1021 Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
1022 Record.push_back(N->getVirtuality());
1023 Record.push_back(N->getVirtualIndex());
1024 Record.push_back(N->getFlags());
1025 Record.push_back(N->isOptimized());
1026 Record.push_back(VE.getMetadataOrNullID(N->getRawFunction()));
1027 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1028 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
1029 Record.push_back(VE.getMetadataOrNullID(N->getVariables().get()));
1031 Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
1035 static void WriteDILexicalBlock(const DILexicalBlock *N,
1036 const ValueEnumerator &VE,
1037 BitstreamWriter &Stream,
1038 SmallVectorImpl<uint64_t> &Record,
1040 Record.push_back(N->isDistinct());
1041 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1042 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1043 Record.push_back(N->getLine());
1044 Record.push_back(N->getColumn());
1046 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
1050 static void WriteDILexicalBlockFile(const DILexicalBlockFile *N,
1051 const ValueEnumerator &VE,
1052 BitstreamWriter &Stream,
1053 SmallVectorImpl<uint64_t> &Record,
1055 Record.push_back(N->isDistinct());
1056 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1057 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1058 Record.push_back(N->getDiscriminator());
1060 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
1064 static void WriteDINamespace(const DINamespace *N, const ValueEnumerator &VE,
1065 BitstreamWriter &Stream,
1066 SmallVectorImpl<uint64_t> &Record,
1068 Record.push_back(N->isDistinct());
1069 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1070 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1071 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1072 Record.push_back(N->getLine());
1074 Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
1078 static void WriteDIModule(const DIModule *N, const ValueEnumerator &VE,
1079 BitstreamWriter &Stream,
1080 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
1081 Record.push_back(N->isDistinct());
1082 for (auto &I : N->operands())
1083 Record.push_back(VE.getMetadataOrNullID(I));
1085 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
1089 static void WriteDITemplateTypeParameter(const DITemplateTypeParameter *N,
1090 const ValueEnumerator &VE,
1091 BitstreamWriter &Stream,
1092 SmallVectorImpl<uint64_t> &Record,
1094 Record.push_back(N->isDistinct());
1095 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1096 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1098 Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
1102 static void WriteDITemplateValueParameter(const DITemplateValueParameter *N,
1103 const ValueEnumerator &VE,
1104 BitstreamWriter &Stream,
1105 SmallVectorImpl<uint64_t> &Record,
1107 Record.push_back(N->isDistinct());
1108 Record.push_back(N->getTag());
1109 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1110 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1111 Record.push_back(VE.getMetadataOrNullID(N->getValue()));
1113 Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
1117 static void WriteDIGlobalVariable(const DIGlobalVariable *N,
1118 const ValueEnumerator &VE,
1119 BitstreamWriter &Stream,
1120 SmallVectorImpl<uint64_t> &Record,
1122 Record.push_back(N->isDistinct());
1123 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1124 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1125 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1126 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1127 Record.push_back(N->getLine());
1128 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1129 Record.push_back(N->isLocalToUnit());
1130 Record.push_back(N->isDefinition());
1131 Record.push_back(VE.getMetadataOrNullID(N->getRawVariable()));
1132 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
1134 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
1138 static void WriteDILocalVariable(const DILocalVariable *N,
1139 const ValueEnumerator &VE,
1140 BitstreamWriter &Stream,
1141 SmallVectorImpl<uint64_t> &Record,
1143 Record.push_back(N->isDistinct());
1144 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1145 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1146 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1147 Record.push_back(N->getLine());
1148 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1149 Record.push_back(N->getArg());
1150 Record.push_back(N->getFlags());
1152 Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
1156 static void WriteDIExpression(const DIExpression *N, const ValueEnumerator &,
1157 BitstreamWriter &Stream,
1158 SmallVectorImpl<uint64_t> &Record,
1160 Record.reserve(N->getElements().size() + 1);
1162 Record.push_back(N->isDistinct());
1163 Record.append(N->elements_begin(), N->elements_end());
1165 Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
1169 static void WriteDIObjCProperty(const DIObjCProperty *N,
1170 const ValueEnumerator &VE,
1171 BitstreamWriter &Stream,
1172 SmallVectorImpl<uint64_t> &Record,
1174 Record.push_back(N->isDistinct());
1175 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1176 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1177 Record.push_back(N->getLine());
1178 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
1179 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
1180 Record.push_back(N->getAttributes());
1181 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1183 Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
1187 static void WriteDIImportedEntity(const DIImportedEntity *N,
1188 const ValueEnumerator &VE,
1189 BitstreamWriter &Stream,
1190 SmallVectorImpl<uint64_t> &Record,
1192 Record.push_back(N->isDistinct());
1193 Record.push_back(N->getTag());
1194 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1195 Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
1196 Record.push_back(N->getLine());
1197 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1199 Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
1203 static void WriteModuleMetadata(const Module *M,
1204 const ValueEnumerator &VE,
1205 BitstreamWriter &Stream) {
1206 const auto &MDs = VE.getMDs();
1207 if (MDs.empty() && M->named_metadata_empty())
1210 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
1212 unsigned MDSAbbrev = 0;
1213 if (VE.hasMDString()) {
1214 // Abbrev for METADATA_STRING.
1215 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1216 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING));
1217 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1218 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1219 MDSAbbrev = Stream.EmitAbbrev(Abbv);
1222 // Initialize MDNode abbreviations.
1223 #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
1224 #include "llvm/IR/Metadata.def"
1226 if (VE.hasDILocation()) {
1227 // Abbrev for METADATA_LOCATION.
1229 // Assume the column is usually under 128, and always output the inlined-at
1230 // location (it's never more expensive than building an array size 1).
1231 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1232 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
1233 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1234 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1235 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1236 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1237 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1238 DILocationAbbrev = Stream.EmitAbbrev(Abbv);
1241 if (VE.hasGenericDINode()) {
1242 // Abbrev for METADATA_GENERIC_DEBUG.
1244 // Assume the column is usually under 128, and always output the inlined-at
1245 // location (it's never more expensive than building an array size 1).
1246 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1247 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
1248 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1249 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1250 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1251 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1252 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1253 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1254 GenericDINodeAbbrev = Stream.EmitAbbrev(Abbv);
1257 unsigned NameAbbrev = 0;
1258 if (!M->named_metadata_empty()) {
1259 // Abbrev for METADATA_NAME.
1260 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1261 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
1262 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1263 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1264 NameAbbrev = Stream.EmitAbbrev(Abbv);
1267 SmallVector<uint64_t, 64> Record;
1268 for (const Metadata *MD : MDs) {
1269 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
1270 assert(N->isResolved() && "Expected forward references to be resolved");
1272 switch (N->getMetadataID()) {
1274 llvm_unreachable("Invalid MDNode subclass");
1275 #define HANDLE_MDNODE_LEAF(CLASS) \
1276 case Metadata::CLASS##Kind: \
1277 Write##CLASS(cast<CLASS>(N), VE, Stream, Record, CLASS##Abbrev); \
1279 #include "llvm/IR/Metadata.def"
1282 if (const auto *MDC = dyn_cast<ConstantAsMetadata>(MD)) {
1283 WriteValueAsMetadata(MDC, VE, Stream, Record);
1286 const MDString *MDS = cast<MDString>(MD);
1287 // Code: [strchar x N]
1288 Record.append(MDS->bytes_begin(), MDS->bytes_end());
1290 // Emit the finished record.
1291 Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev);
1295 // Write named metadata.
1296 for (const NamedMDNode &NMD : M->named_metadata()) {
1298 StringRef Str = NMD.getName();
1299 Record.append(Str.bytes_begin(), Str.bytes_end());
1300 Stream.EmitRecord(bitc::METADATA_NAME, Record, NameAbbrev);
1303 // Write named metadata operands.
1304 for (const MDNode *N : NMD.operands())
1305 Record.push_back(VE.getMetadataID(N));
1306 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
1313 static void WriteFunctionLocalMetadata(const Function &F,
1314 const ValueEnumerator &VE,
1315 BitstreamWriter &Stream) {
1316 bool StartedMetadataBlock = false;
1317 SmallVector<uint64_t, 64> Record;
1318 const SmallVectorImpl<const LocalAsMetadata *> &MDs =
1319 VE.getFunctionLocalMDs();
1320 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
1321 assert(MDs[i] && "Expected valid function-local metadata");
1322 if (!StartedMetadataBlock) {
1323 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
1324 StartedMetadataBlock = true;
1326 WriteValueAsMetadata(MDs[i], VE, Stream, Record);
1329 if (StartedMetadataBlock)
1333 static void WriteMetadataAttachment(const Function &F,
1334 const ValueEnumerator &VE,
1335 BitstreamWriter &Stream) {
1336 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
1338 SmallVector<uint64_t, 64> Record;
1340 // Write metadata attachments
1341 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
1342 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1343 F.getAllMetadata(MDs);
1345 for (const auto &I : MDs) {
1346 Record.push_back(I.first);
1347 Record.push_back(VE.getMetadataID(I.second));
1349 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
1353 for (const BasicBlock &BB : F)
1354 for (const Instruction &I : BB) {
1356 I.getAllMetadataOtherThanDebugLoc(MDs);
1358 // If no metadata, ignore instruction.
1359 if (MDs.empty()) continue;
1361 Record.push_back(VE.getInstructionID(&I));
1363 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
1364 Record.push_back(MDs[i].first);
1365 Record.push_back(VE.getMetadataID(MDs[i].second));
1367 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
1374 static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) {
1375 SmallVector<uint64_t, 64> Record;
1377 // Write metadata kinds
1378 // METADATA_KIND - [n x [id, name]]
1379 SmallVector<StringRef, 8> Names;
1380 M->getMDKindNames(Names);
1382 if (Names.empty()) return;
1384 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
1386 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
1387 Record.push_back(MDKindID);
1388 StringRef KName = Names[MDKindID];
1389 Record.append(KName.begin(), KName.end());
1391 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
1398 static void WriteOperandBundleTags(const Module *M, BitstreamWriter &Stream) {
1399 // Write metadata kinds
1401 // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
1403 // OPERAND_BUNDLE_TAG - [strchr x N]
1405 SmallVector<StringRef, 8> Tags;
1406 M->getOperandBundleTags(Tags);
1411 Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3);
1413 SmallVector<uint64_t, 64> Record;
1415 for (auto Tag : Tags) {
1416 Record.append(Tag.begin(), Tag.end());
1418 Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
1425 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
1426 if ((int64_t)V >= 0)
1427 Vals.push_back(V << 1);
1429 Vals.push_back((-V << 1) | 1);
1432 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
1433 const ValueEnumerator &VE,
1434 BitstreamWriter &Stream, bool isGlobal) {
1435 if (FirstVal == LastVal) return;
1437 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
1439 unsigned AggregateAbbrev = 0;
1440 unsigned String8Abbrev = 0;
1441 unsigned CString7Abbrev = 0;
1442 unsigned CString6Abbrev = 0;
1443 // If this is a constant pool for the module, emit module-specific abbrevs.
1445 // Abbrev for CST_CODE_AGGREGATE.
1446 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1447 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
1448 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1449 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
1450 AggregateAbbrev = Stream.EmitAbbrev(Abbv);
1452 // Abbrev for CST_CODE_STRING.
1453 Abbv = new BitCodeAbbrev();
1454 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
1455 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1456 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1457 String8Abbrev = Stream.EmitAbbrev(Abbv);
1458 // Abbrev for CST_CODE_CSTRING.
1459 Abbv = new BitCodeAbbrev();
1460 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
1461 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1462 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1463 CString7Abbrev = Stream.EmitAbbrev(Abbv);
1464 // Abbrev for CST_CODE_CSTRING.
1465 Abbv = new BitCodeAbbrev();
1466 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
1467 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1468 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1469 CString6Abbrev = Stream.EmitAbbrev(Abbv);
1472 SmallVector<uint64_t, 64> Record;
1474 const ValueEnumerator::ValueList &Vals = VE.getValues();
1475 Type *LastTy = nullptr;
1476 for (unsigned i = FirstVal; i != LastVal; ++i) {
1477 const Value *V = Vals[i].first;
1478 // If we need to switch types, do so now.
1479 if (V->getType() != LastTy) {
1480 LastTy = V->getType();
1481 Record.push_back(VE.getTypeID(LastTy));
1482 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
1483 CONSTANTS_SETTYPE_ABBREV);
1487 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1488 Record.push_back(unsigned(IA->hasSideEffects()) |
1489 unsigned(IA->isAlignStack()) << 1 |
1490 unsigned(IA->getDialect()&1) << 2);
1492 // Add the asm string.
1493 const std::string &AsmStr = IA->getAsmString();
1494 Record.push_back(AsmStr.size());
1495 Record.append(AsmStr.begin(), AsmStr.end());
1497 // Add the constraint string.
1498 const std::string &ConstraintStr = IA->getConstraintString();
1499 Record.push_back(ConstraintStr.size());
1500 Record.append(ConstraintStr.begin(), ConstraintStr.end());
1501 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
1505 const Constant *C = cast<Constant>(V);
1506 unsigned Code = -1U;
1507 unsigned AbbrevToUse = 0;
1508 if (C->isNullValue()) {
1509 Code = bitc::CST_CODE_NULL;
1510 } else if (isa<UndefValue>(C)) {
1511 Code = bitc::CST_CODE_UNDEF;
1512 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
1513 if (IV->getBitWidth() <= 64) {
1514 uint64_t V = IV->getSExtValue();
1515 emitSignedInt64(Record, V);
1516 Code = bitc::CST_CODE_INTEGER;
1517 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
1518 } else { // Wide integers, > 64 bits in size.
1519 // We have an arbitrary precision integer value to write whose
1520 // bit width is > 64. However, in canonical unsigned integer
1521 // format it is likely that the high bits are going to be zero.
1522 // So, we only write the number of active words.
1523 unsigned NWords = IV->getValue().getActiveWords();
1524 const uint64_t *RawWords = IV->getValue().getRawData();
1525 for (unsigned i = 0; i != NWords; ++i) {
1526 emitSignedInt64(Record, RawWords[i]);
1528 Code = bitc::CST_CODE_WIDE_INTEGER;
1530 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
1531 Code = bitc::CST_CODE_FLOAT;
1532 Type *Ty = CFP->getType();
1533 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
1534 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
1535 } else if (Ty->isX86_FP80Ty()) {
1536 // api needed to prevent premature destruction
1537 // bits are not in the same order as a normal i80 APInt, compensate.
1538 APInt api = CFP->getValueAPF().bitcastToAPInt();
1539 const uint64_t *p = api.getRawData();
1540 Record.push_back((p[1] << 48) | (p[0] >> 16));
1541 Record.push_back(p[0] & 0xffffLL);
1542 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
1543 APInt api = CFP->getValueAPF().bitcastToAPInt();
1544 const uint64_t *p = api.getRawData();
1545 Record.push_back(p[0]);
1546 Record.push_back(p[1]);
1548 assert (0 && "Unknown FP type!");
1550 } else if (isa<ConstantDataSequential>(C) &&
1551 cast<ConstantDataSequential>(C)->isString()) {
1552 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
1553 // Emit constant strings specially.
1554 unsigned NumElts = Str->getNumElements();
1555 // If this is a null-terminated string, use the denser CSTRING encoding.
1556 if (Str->isCString()) {
1557 Code = bitc::CST_CODE_CSTRING;
1558 --NumElts; // Don't encode the null, which isn't allowed by char6.
1560 Code = bitc::CST_CODE_STRING;
1561 AbbrevToUse = String8Abbrev;
1563 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
1564 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
1565 for (unsigned i = 0; i != NumElts; ++i) {
1566 unsigned char V = Str->getElementAsInteger(i);
1567 Record.push_back(V);
1568 isCStr7 &= (V & 128) == 0;
1570 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
1574 AbbrevToUse = CString6Abbrev;
1576 AbbrevToUse = CString7Abbrev;
1577 } else if (const ConstantDataSequential *CDS =
1578 dyn_cast<ConstantDataSequential>(C)) {
1579 Code = bitc::CST_CODE_DATA;
1580 Type *EltTy = CDS->getType()->getElementType();
1581 if (isa<IntegerType>(EltTy)) {
1582 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
1583 Record.push_back(CDS->getElementAsInteger(i));
1584 } else if (EltTy->isFloatTy()) {
1585 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1586 union { float F; uint32_t I; };
1587 F = CDS->getElementAsFloat(i);
1588 Record.push_back(I);
1591 assert(EltTy->isDoubleTy() && "Unknown ConstantData element type");
1592 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1593 union { double F; uint64_t I; };
1594 F = CDS->getElementAsDouble(i);
1595 Record.push_back(I);
1598 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
1599 isa<ConstantVector>(C)) {
1600 Code = bitc::CST_CODE_AGGREGATE;
1601 for (const Value *Op : C->operands())
1602 Record.push_back(VE.getValueID(Op));
1603 AbbrevToUse = AggregateAbbrev;
1604 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1605 switch (CE->getOpcode()) {
1607 if (Instruction::isCast(CE->getOpcode())) {
1608 Code = bitc::CST_CODE_CE_CAST;
1609 Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
1610 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1611 Record.push_back(VE.getValueID(C->getOperand(0)));
1612 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
1614 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
1615 Code = bitc::CST_CODE_CE_BINOP;
1616 Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
1617 Record.push_back(VE.getValueID(C->getOperand(0)));
1618 Record.push_back(VE.getValueID(C->getOperand(1)));
1619 uint64_t Flags = GetOptimizationFlags(CE);
1621 Record.push_back(Flags);
1624 case Instruction::GetElementPtr: {
1625 Code = bitc::CST_CODE_CE_GEP;
1626 const auto *GO = cast<GEPOperator>(C);
1627 if (GO->isInBounds())
1628 Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
1629 Record.push_back(VE.getTypeID(GO->getSourceElementType()));
1630 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
1631 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
1632 Record.push_back(VE.getValueID(C->getOperand(i)));
1636 case Instruction::Select:
1637 Code = bitc::CST_CODE_CE_SELECT;
1638 Record.push_back(VE.getValueID(C->getOperand(0)));
1639 Record.push_back(VE.getValueID(C->getOperand(1)));
1640 Record.push_back(VE.getValueID(C->getOperand(2)));
1642 case Instruction::ExtractElement:
1643 Code = bitc::CST_CODE_CE_EXTRACTELT;
1644 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1645 Record.push_back(VE.getValueID(C->getOperand(0)));
1646 Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
1647 Record.push_back(VE.getValueID(C->getOperand(1)));
1649 case Instruction::InsertElement:
1650 Code = bitc::CST_CODE_CE_INSERTELT;
1651 Record.push_back(VE.getValueID(C->getOperand(0)));
1652 Record.push_back(VE.getValueID(C->getOperand(1)));
1653 Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
1654 Record.push_back(VE.getValueID(C->getOperand(2)));
1656 case Instruction::ShuffleVector:
1657 // If the return type and argument types are the same, this is a
1658 // standard shufflevector instruction. If the types are different,
1659 // then the shuffle is widening or truncating the input vectors, and
1660 // the argument type must also be encoded.
1661 if (C->getType() == C->getOperand(0)->getType()) {
1662 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
1664 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
1665 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1667 Record.push_back(VE.getValueID(C->getOperand(0)));
1668 Record.push_back(VE.getValueID(C->getOperand(1)));
1669 Record.push_back(VE.getValueID(C->getOperand(2)));
1671 case Instruction::ICmp:
1672 case Instruction::FCmp:
1673 Code = bitc::CST_CODE_CE_CMP;
1674 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1675 Record.push_back(VE.getValueID(C->getOperand(0)));
1676 Record.push_back(VE.getValueID(C->getOperand(1)));
1677 Record.push_back(CE->getPredicate());
1680 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
1681 Code = bitc::CST_CODE_BLOCKADDRESS;
1682 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
1683 Record.push_back(VE.getValueID(BA->getFunction()));
1684 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
1689 llvm_unreachable("Unknown constant!");
1691 Stream.EmitRecord(Code, Record, AbbrevToUse);
1698 static void WriteModuleConstants(const ValueEnumerator &VE,
1699 BitstreamWriter &Stream) {
1700 const ValueEnumerator::ValueList &Vals = VE.getValues();
1702 // Find the first constant to emit, which is the first non-globalvalue value.
1703 // We know globalvalues have been emitted by WriteModuleInfo.
1704 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1705 if (!isa<GlobalValue>(Vals[i].first)) {
1706 WriteConstants(i, Vals.size(), VE, Stream, true);
1712 /// PushValueAndType - The file has to encode both the value and type id for
1713 /// many values, because we need to know what type to create for forward
1714 /// references. However, most operands are not forward references, so this type
1715 /// field is not needed.
1717 /// This function adds V's value ID to Vals. If the value ID is higher than the
1718 /// instruction ID, then it is a forward reference, and it also includes the
1719 /// type ID. The value ID that is written is encoded relative to the InstID.
1720 static bool PushValueAndType(const Value *V, unsigned InstID,
1721 SmallVectorImpl<unsigned> &Vals,
1722 ValueEnumerator &VE) {
1723 unsigned ValID = VE.getValueID(V);
1724 // Make encoding relative to the InstID.
1725 Vals.push_back(InstID - ValID);
1726 if (ValID >= InstID) {
1727 Vals.push_back(VE.getTypeID(V->getType()));
1733 static void WriteOperandBundles(BitstreamWriter &Stream, ImmutableCallSite CS,
1734 unsigned InstID, ValueEnumerator &VE) {
1735 SmallVector<unsigned, 64> Record;
1736 LLVMContext &C = CS.getInstruction()->getContext();
1738 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
1739 const auto &Bundle = CS.getOperandBundle(i);
1740 Record.push_back(C.getOperandBundleTagID(Bundle.Tag));
1742 for (auto &Input : Bundle.Inputs)
1743 PushValueAndType(Input, InstID, Record, VE);
1745 Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record);
1750 /// pushValue - Like PushValueAndType, but where the type of the value is
1751 /// omitted (perhaps it was already encoded in an earlier operand).
1752 static void pushValue(const Value *V, unsigned InstID,
1753 SmallVectorImpl<unsigned> &Vals,
1754 ValueEnumerator &VE) {
1755 unsigned ValID = VE.getValueID(V);
1756 Vals.push_back(InstID - ValID);
1759 static void pushValueSigned(const Value *V, unsigned InstID,
1760 SmallVectorImpl<uint64_t> &Vals,
1761 ValueEnumerator &VE) {
1762 unsigned ValID = VE.getValueID(V);
1763 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
1764 emitSignedInt64(Vals, diff);
1767 /// WriteInstruction - Emit an instruction to the specified stream.
1768 static void WriteInstruction(const Instruction &I, unsigned InstID,
1769 ValueEnumerator &VE, BitstreamWriter &Stream,
1770 SmallVectorImpl<unsigned> &Vals) {
1772 unsigned AbbrevToUse = 0;
1773 VE.setInstructionID(&I);
1774 switch (I.getOpcode()) {
1776 if (Instruction::isCast(I.getOpcode())) {
1777 Code = bitc::FUNC_CODE_INST_CAST;
1778 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1779 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
1780 Vals.push_back(VE.getTypeID(I.getType()));
1781 Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
1783 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
1784 Code = bitc::FUNC_CODE_INST_BINOP;
1785 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1786 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
1787 pushValue(I.getOperand(1), InstID, Vals, VE);
1788 Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
1789 uint64_t Flags = GetOptimizationFlags(&I);
1791 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
1792 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
1793 Vals.push_back(Flags);
1798 case Instruction::GetElementPtr: {
1799 Code = bitc::FUNC_CODE_INST_GEP;
1800 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
1801 auto &GEPInst = cast<GetElementPtrInst>(I);
1802 Vals.push_back(GEPInst.isInBounds());
1803 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
1804 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1805 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1808 case Instruction::ExtractValue: {
1809 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
1810 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1811 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
1812 Vals.append(EVI->idx_begin(), EVI->idx_end());
1815 case Instruction::InsertValue: {
1816 Code = bitc::FUNC_CODE_INST_INSERTVAL;
1817 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1818 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1819 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
1820 Vals.append(IVI->idx_begin(), IVI->idx_end());
1823 case Instruction::Select:
1824 Code = bitc::FUNC_CODE_INST_VSELECT;
1825 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1826 pushValue(I.getOperand(2), InstID, Vals, VE);
1827 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1829 case Instruction::ExtractElement:
1830 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
1831 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1832 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1834 case Instruction::InsertElement:
1835 Code = bitc::FUNC_CODE_INST_INSERTELT;
1836 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1837 pushValue(I.getOperand(1), InstID, Vals, VE);
1838 PushValueAndType(I.getOperand(2), InstID, Vals, VE);
1840 case Instruction::ShuffleVector:
1841 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
1842 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1843 pushValue(I.getOperand(1), InstID, Vals, VE);
1844 pushValue(I.getOperand(2), InstID, Vals, VE);
1846 case Instruction::ICmp:
1847 case Instruction::FCmp: {
1848 // compare returning Int1Ty or vector of Int1Ty
1849 Code = bitc::FUNC_CODE_INST_CMP2;
1850 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1851 pushValue(I.getOperand(1), InstID, Vals, VE);
1852 Vals.push_back(cast<CmpInst>(I).getPredicate());
1853 uint64_t Flags = GetOptimizationFlags(&I);
1855 Vals.push_back(Flags);
1859 case Instruction::Ret:
1861 Code = bitc::FUNC_CODE_INST_RET;
1862 unsigned NumOperands = I.getNumOperands();
1863 if (NumOperands == 0)
1864 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
1865 else if (NumOperands == 1) {
1866 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1867 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
1869 for (unsigned i = 0, e = NumOperands; i != e; ++i)
1870 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1874 case Instruction::Br:
1876 Code = bitc::FUNC_CODE_INST_BR;
1877 const BranchInst &II = cast<BranchInst>(I);
1878 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
1879 if (II.isConditional()) {
1880 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
1881 pushValue(II.getCondition(), InstID, Vals, VE);
1885 case Instruction::Switch:
1887 Code = bitc::FUNC_CODE_INST_SWITCH;
1888 const SwitchInst &SI = cast<SwitchInst>(I);
1889 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
1890 pushValue(SI.getCondition(), InstID, Vals, VE);
1891 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
1892 for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
1894 Vals.push_back(VE.getValueID(i.getCaseValue()));
1895 Vals.push_back(VE.getValueID(i.getCaseSuccessor()));
1899 case Instruction::IndirectBr:
1900 Code = bitc::FUNC_CODE_INST_INDIRECTBR;
1901 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1902 // Encode the address operand as relative, but not the basic blocks.
1903 pushValue(I.getOperand(0), InstID, Vals, VE);
1904 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
1905 Vals.push_back(VE.getValueID(I.getOperand(i)));
1908 case Instruction::Invoke: {
1909 const InvokeInst *II = cast<InvokeInst>(&I);
1910 const Value *Callee = II->getCalledValue();
1911 FunctionType *FTy = II->getFunctionType();
1913 if (II->hasOperandBundles())
1914 WriteOperandBundles(Stream, II, InstID, VE);
1916 Code = bitc::FUNC_CODE_INST_INVOKE;
1918 Vals.push_back(VE.getAttributeID(II->getAttributes()));
1919 Vals.push_back(II->getCallingConv() | 1 << 13);
1920 Vals.push_back(VE.getValueID(II->getNormalDest()));
1921 Vals.push_back(VE.getValueID(II->getUnwindDest()));
1922 Vals.push_back(VE.getTypeID(FTy));
1923 PushValueAndType(Callee, InstID, Vals, VE);
1925 // Emit value #'s for the fixed parameters.
1926 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1927 pushValue(I.getOperand(i), InstID, Vals, VE); // fixed param.
1929 // Emit type/value pairs for varargs params.
1930 if (FTy->isVarArg()) {
1931 for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
1933 PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
1937 case Instruction::Resume:
1938 Code = bitc::FUNC_CODE_INST_RESUME;
1939 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1941 case Instruction::CleanupRet: {
1942 Code = bitc::FUNC_CODE_INST_CLEANUPRET;
1943 const auto &CRI = cast<CleanupReturnInst>(I);
1944 pushValue(CRI.getCleanupPad(), InstID, Vals, VE);
1945 if (CRI.hasUnwindDest())
1946 Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
1949 case Instruction::CatchRet: {
1950 Code = bitc::FUNC_CODE_INST_CATCHRET;
1951 const auto &CRI = cast<CatchReturnInst>(I);
1952 pushValue(CRI.getCatchPad(), InstID, Vals, VE);
1953 Vals.push_back(VE.getValueID(CRI.getSuccessor()));
1956 case Instruction::CatchPad: {
1957 Code = bitc::FUNC_CODE_INST_CATCHPAD;
1958 const auto &CPI = cast<CatchPadInst>(I);
1959 Vals.push_back(VE.getValueID(CPI.getNormalDest()));
1960 Vals.push_back(VE.getValueID(CPI.getUnwindDest()));
1961 unsigned NumArgOperands = CPI.getNumArgOperands();
1962 Vals.push_back(NumArgOperands);
1963 for (unsigned Op = 0; Op != NumArgOperands; ++Op)
1964 PushValueAndType(CPI.getArgOperand(Op), InstID, Vals, VE);
1967 case Instruction::TerminatePad: {
1968 Code = bitc::FUNC_CODE_INST_TERMINATEPAD;
1969 const auto &TPI = cast<TerminatePadInst>(I);
1970 Vals.push_back(TPI.hasUnwindDest());
1971 if (TPI.hasUnwindDest())
1972 Vals.push_back(VE.getValueID(TPI.getUnwindDest()));
1973 unsigned NumArgOperands = TPI.getNumArgOperands();
1974 Vals.push_back(NumArgOperands);
1975 for (unsigned Op = 0; Op != NumArgOperands; ++Op)
1976 PushValueAndType(TPI.getArgOperand(Op), InstID, Vals, VE);
1979 case Instruction::CleanupPad: {
1980 Code = bitc::FUNC_CODE_INST_CLEANUPPAD;
1981 const auto &CPI = cast<CleanupPadInst>(I);
1982 unsigned NumOperands = CPI.getNumOperands();
1983 Vals.push_back(NumOperands);
1984 for (unsigned Op = 0; Op != NumOperands; ++Op)
1985 PushValueAndType(CPI.getOperand(Op), InstID, Vals, VE);
1988 case Instruction::CatchEndPad: {
1989 Code = bitc::FUNC_CODE_INST_CATCHENDPAD;
1990 const auto &CEPI = cast<CatchEndPadInst>(I);
1991 if (CEPI.hasUnwindDest())
1992 Vals.push_back(VE.getValueID(CEPI.getUnwindDest()));
1995 case Instruction::CleanupEndPad: {
1996 Code = bitc::FUNC_CODE_INST_CLEANUPENDPAD;
1997 const auto &CEPI = cast<CleanupEndPadInst>(I);
1998 pushValue(CEPI.getCleanupPad(), InstID, Vals, VE);
1999 if (CEPI.hasUnwindDest())
2000 Vals.push_back(VE.getValueID(CEPI.getUnwindDest()));
2003 case Instruction::Unreachable:
2004 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
2005 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
2008 case Instruction::PHI: {
2009 const PHINode &PN = cast<PHINode>(I);
2010 Code = bitc::FUNC_CODE_INST_PHI;
2011 // With the newer instruction encoding, forward references could give
2012 // negative valued IDs. This is most common for PHIs, so we use
2014 SmallVector<uint64_t, 128> Vals64;
2015 Vals64.push_back(VE.getTypeID(PN.getType()));
2016 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
2017 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64, VE);
2018 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
2020 // Emit a Vals64 vector and exit.
2021 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
2026 case Instruction::LandingPad: {
2027 const LandingPadInst &LP = cast<LandingPadInst>(I);
2028 Code = bitc::FUNC_CODE_INST_LANDINGPAD;
2029 Vals.push_back(VE.getTypeID(LP.getType()));
2030 Vals.push_back(LP.isCleanup());
2031 Vals.push_back(LP.getNumClauses());
2032 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
2034 Vals.push_back(LandingPadInst::Catch);
2036 Vals.push_back(LandingPadInst::Filter);
2037 PushValueAndType(LP.getClause(I), InstID, Vals, VE);
2042 case Instruction::Alloca: {
2043 Code = bitc::FUNC_CODE_INST_ALLOCA;
2044 const AllocaInst &AI = cast<AllocaInst>(I);
2045 Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
2046 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
2047 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
2048 unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
2049 assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
2050 "not enough bits for maximum alignment");
2051 assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
2052 AlignRecord |= AI.isUsedWithInAlloca() << 5;
2053 AlignRecord |= 1 << 6;
2054 // Reserve bit 7 for SwiftError flag.
2055 // AlignRecord |= AI.isSwiftError() << 7;
2056 Vals.push_back(AlignRecord);
2060 case Instruction::Load:
2061 if (cast<LoadInst>(I).isAtomic()) {
2062 Code = bitc::FUNC_CODE_INST_LOADATOMIC;
2063 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
2065 Code = bitc::FUNC_CODE_INST_LOAD;
2066 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) // ptr
2067 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
2069 Vals.push_back(VE.getTypeID(I.getType()));
2070 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
2071 Vals.push_back(cast<LoadInst>(I).isVolatile());
2072 if (cast<LoadInst>(I).isAtomic()) {
2073 Vals.push_back(GetEncodedOrdering(cast<LoadInst>(I).getOrdering()));
2074 Vals.push_back(GetEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
2077 case Instruction::Store:
2078 if (cast<StoreInst>(I).isAtomic())
2079 Code = bitc::FUNC_CODE_INST_STOREATOMIC;
2081 Code = bitc::FUNC_CODE_INST_STORE;
2082 PushValueAndType(I.getOperand(1), InstID, Vals, VE); // ptrty + ptr
2083 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // valty + val
2084 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
2085 Vals.push_back(cast<StoreInst>(I).isVolatile());
2086 if (cast<StoreInst>(I).isAtomic()) {
2087 Vals.push_back(GetEncodedOrdering(cast<StoreInst>(I).getOrdering()));
2088 Vals.push_back(GetEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
2091 case Instruction::AtomicCmpXchg:
2092 Code = bitc::FUNC_CODE_INST_CMPXCHG;
2093 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr
2094 PushValueAndType(I.getOperand(1), InstID, Vals, VE); // cmp.
2095 pushValue(I.getOperand(2), InstID, Vals, VE); // newval.
2096 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
2097 Vals.push_back(GetEncodedOrdering(
2098 cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
2099 Vals.push_back(GetEncodedSynchScope(
2100 cast<AtomicCmpXchgInst>(I).getSynchScope()));
2101 Vals.push_back(GetEncodedOrdering(
2102 cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
2103 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
2105 case Instruction::AtomicRMW:
2106 Code = bitc::FUNC_CODE_INST_ATOMICRMW;
2107 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr
2108 pushValue(I.getOperand(1), InstID, Vals, VE); // val.
2109 Vals.push_back(GetEncodedRMWOperation(
2110 cast<AtomicRMWInst>(I).getOperation()));
2111 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
2112 Vals.push_back(GetEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
2113 Vals.push_back(GetEncodedSynchScope(
2114 cast<AtomicRMWInst>(I).getSynchScope()));
2116 case Instruction::Fence:
2117 Code = bitc::FUNC_CODE_INST_FENCE;
2118 Vals.push_back(GetEncodedOrdering(cast<FenceInst>(I).getOrdering()));
2119 Vals.push_back(GetEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
2121 case Instruction::Call: {
2122 const CallInst &CI = cast<CallInst>(I);
2123 FunctionType *FTy = CI.getFunctionType();
2125 if (CI.hasOperandBundles())
2126 WriteOperandBundles(Stream, &CI, InstID, VE);
2128 Code = bitc::FUNC_CODE_INST_CALL;
2130 Vals.push_back(VE.getAttributeID(CI.getAttributes()));
2131 Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall()) |
2132 unsigned(CI.isMustTailCall()) << 14 | 1 << 15);
2133 Vals.push_back(VE.getTypeID(FTy));
2134 PushValueAndType(CI.getCalledValue(), InstID, Vals, VE); // Callee
2136 // Emit value #'s for the fixed parameters.
2137 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
2138 // Check for labels (can happen with asm labels).
2139 if (FTy->getParamType(i)->isLabelTy())
2140 Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
2142 pushValue(CI.getArgOperand(i), InstID, Vals, VE); // fixed param.
2145 // Emit type/value pairs for varargs params.
2146 if (FTy->isVarArg()) {
2147 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
2149 PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE); // varargs
2153 case Instruction::VAArg:
2154 Code = bitc::FUNC_CODE_INST_VAARG;
2155 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
2156 pushValue(I.getOperand(0), InstID, Vals, VE); // valist.
2157 Vals.push_back(VE.getTypeID(I.getType())); // restype.
2161 Stream.EmitRecord(Code, Vals, AbbrevToUse);
2165 enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 };
2167 /// Determine the encoding to use for the given string name and length.
2168 static StringEncoding getStringEncoding(const char *Str, unsigned StrLen) {
2169 bool isChar6 = true;
2170 for (const char *C = Str, *E = C + StrLen; C != E; ++C) {
2172 isChar6 = BitCodeAbbrevOp::isChar6(*C);
2173 if ((unsigned char)*C & 128)
2174 // don't bother scanning the rest.
2183 /// Emit names for globals/functions etc. The VSTOffsetPlaceholder,
2184 /// BitcodeStartBit and FunctionIndex are only passed for the module-level
2185 /// VST, where we are including a function bitcode index and need to
2186 /// backpatch the VST forward declaration record.
2187 static void WriteValueSymbolTable(
2188 const ValueSymbolTable &VST, const ValueEnumerator &VE,
2189 BitstreamWriter &Stream, uint64_t VSTOffsetPlaceholder = 0,
2190 uint64_t BitcodeStartBit = 0,
2191 DenseMap<const Function *, std::unique_ptr<FunctionInfo>> *FunctionIndex =
2194 // WriteValueSymbolTableForwardDecl should have returned early as
2195 // well. Ensure this handling remains in sync by asserting that
2196 // the placeholder offset is not set.
2197 assert(VSTOffsetPlaceholder == 0);
2201 if (VSTOffsetPlaceholder > 0) {
2202 // Get the offset of the VST we are writing, and backpatch it into
2203 // the VST forward declaration record.
2204 uint64_t VSTOffset = Stream.GetCurrentBitNo();
2205 // The BitcodeStartBit was the stream offset of the actual bitcode
2206 // (e.g. excluding any initial darwin header).
2207 VSTOffset -= BitcodeStartBit;
2208 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
2209 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32);
2212 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
2214 // For the module-level VST, add abbrev Ids for the VST_CODE_FNENTRY
2215 // records, which are not used in the per-function VSTs.
2216 unsigned FnEntry8BitAbbrev;
2217 unsigned FnEntry7BitAbbrev;
2218 unsigned FnEntry6BitAbbrev;
2219 if (VSTOffsetPlaceholder > 0) {
2220 // 8-bit fixed-width VST_FNENTRY function strings.
2221 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2222 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2223 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2224 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2225 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2226 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2227 FnEntry8BitAbbrev = Stream.EmitAbbrev(Abbv);
2229 // 7-bit fixed width VST_FNENTRY function strings.
2230 Abbv = new BitCodeAbbrev();
2231 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2232 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2233 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2234 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2235 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2236 FnEntry7BitAbbrev = Stream.EmitAbbrev(Abbv);
2238 // 6-bit char6 VST_FNENTRY function strings.
2239 Abbv = new BitCodeAbbrev();
2240 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2241 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2242 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2243 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2244 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2245 FnEntry6BitAbbrev = Stream.EmitAbbrev(Abbv);
2248 // FIXME: Set up the abbrev, we know how many values there are!
2249 // FIXME: We know if the type names can use 7-bit ascii.
2250 SmallVector<unsigned, 64> NameVals;
2252 for (const ValueName &Name : VST) {
2253 // Figure out the encoding to use for the name.
2254 StringEncoding Bits =
2255 getStringEncoding(Name.getKeyData(), Name.getKeyLength());
2257 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
2258 NameVals.push_back(VE.getValueID(Name.getValue()));
2260 Function *F = dyn_cast<Function>(Name.getValue());
2262 // If value is an alias, need to get the aliased base object to
2263 // see if it is a function.
2264 auto *GA = dyn_cast<GlobalAlias>(Name.getValue());
2265 if (GA && GA->getBaseObject())
2266 F = dyn_cast<Function>(GA->getBaseObject());
2269 // VST_ENTRY: [valueid, namechar x N]
2270 // VST_FNENTRY: [valueid, funcoffset, namechar x N]
2271 // VST_BBENTRY: [bbid, namechar x N]
2273 if (isa<BasicBlock>(Name.getValue())) {
2274 Code = bitc::VST_CODE_BBENTRY;
2275 if (Bits == SE_Char6)
2276 AbbrevToUse = VST_BBENTRY_6_ABBREV;
2277 } else if (F && !F->isDeclaration()) {
2278 // Must be the module-level VST, where we pass in the Index and
2279 // have a VSTOffsetPlaceholder. The function-level VST should not
2280 // contain any Function symbols.
2281 assert(FunctionIndex);
2282 assert(VSTOffsetPlaceholder > 0);
2284 // Save the word offset of the function (from the start of the
2285 // actual bitcode written to the stream).
2286 assert(FunctionIndex->count(F) == 1);
2287 uint64_t BitcodeIndex =
2288 (*FunctionIndex)[F]->bitcodeIndex() - BitcodeStartBit;
2289 assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
2290 NameVals.push_back(BitcodeIndex / 32);
2292 Code = bitc::VST_CODE_FNENTRY;
2293 AbbrevToUse = FnEntry8BitAbbrev;
2294 if (Bits == SE_Char6)
2295 AbbrevToUse = FnEntry6BitAbbrev;
2296 else if (Bits == SE_Fixed7)
2297 AbbrevToUse = FnEntry7BitAbbrev;
2299 Code = bitc::VST_CODE_ENTRY;
2300 if (Bits == SE_Char6)
2301 AbbrevToUse = VST_ENTRY_6_ABBREV;
2302 else if (Bits == SE_Fixed7)
2303 AbbrevToUse = VST_ENTRY_7_ABBREV;
2306 for (const auto P : Name.getKey()) NameVals.push_back((unsigned char)P);
2308 // Emit the finished record.
2309 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
2315 /// Emit function names and summary offsets for the combined index
2316 /// used by ThinLTO.
2317 static void WriteCombinedValueSymbolTable(const FunctionInfoIndex &Index,
2318 BitstreamWriter &Stream) {
2319 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
2321 // 8-bit fixed-width VST_COMBINED_FNENTRY function strings.
2322 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2323 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_COMBINED_FNENTRY));
2324 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2325 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2326 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2327 unsigned FnEntry8BitAbbrev = Stream.EmitAbbrev(Abbv);
2329 // 7-bit fixed width VST_COMBINED_FNENTRY function strings.
2330 Abbv = new BitCodeAbbrev();
2331 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_COMBINED_FNENTRY));
2332 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2333 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2334 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2335 unsigned FnEntry7BitAbbrev = Stream.EmitAbbrev(Abbv);
2337 // 6-bit char6 VST_COMBINED_FNENTRY function strings.
2338 Abbv = new BitCodeAbbrev();
2339 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_COMBINED_FNENTRY));
2340 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2341 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2342 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2343 unsigned FnEntry6BitAbbrev = Stream.EmitAbbrev(Abbv);
2345 // FIXME: We know if the type names can use 7-bit ascii.
2346 SmallVector<unsigned, 64> NameVals;
2348 for (const auto &FII : Index) {
2349 for (const auto &FI : FII.getValue()) {
2350 NameVals.push_back(FI->bitcodeIndex());
2352 StringRef FuncName = FII.first();
2354 // Figure out the encoding to use for the name.
2355 StringEncoding Bits = getStringEncoding(FuncName.data(), FuncName.size());
2357 // VST_COMBINED_FNENTRY: [funcsumoffset, namechar x N]
2358 unsigned AbbrevToUse = FnEntry8BitAbbrev;
2359 if (Bits == SE_Char6)
2360 AbbrevToUse = FnEntry6BitAbbrev;
2361 else if (Bits == SE_Fixed7)
2362 AbbrevToUse = FnEntry7BitAbbrev;
2364 for (const auto P : FuncName) NameVals.push_back((unsigned char)P);
2366 // Emit the finished record.
2367 Stream.EmitRecord(bitc::VST_CODE_COMBINED_FNENTRY, NameVals, AbbrevToUse);
2374 static void WriteUseList(ValueEnumerator &VE, UseListOrder &&Order,
2375 BitstreamWriter &Stream) {
2376 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
2378 if (isa<BasicBlock>(Order.V))
2379 Code = bitc::USELIST_CODE_BB;
2381 Code = bitc::USELIST_CODE_DEFAULT;
2383 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
2384 Record.push_back(VE.getValueID(Order.V));
2385 Stream.EmitRecord(Code, Record);
2388 static void WriteUseListBlock(const Function *F, ValueEnumerator &VE,
2389 BitstreamWriter &Stream) {
2390 assert(VE.shouldPreserveUseListOrder() &&
2391 "Expected to be preserving use-list order");
2393 auto hasMore = [&]() {
2394 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
2400 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
2402 WriteUseList(VE, std::move(VE.UseListOrders.back()), Stream);
2403 VE.UseListOrders.pop_back();
2408 /// \brief Save information for the given function into the function index.
2410 /// At a minimum this saves the bitcode index of the function record that
2411 /// was just written. However, if we are emitting function summary information,
2412 /// for example for ThinLTO, then a \a FunctionSummary object is created
2413 /// to hold the provided summary information.
2414 static void SaveFunctionInfo(
2416 DenseMap<const Function *, std::unique_ptr<FunctionInfo>> &FunctionIndex,
2417 unsigned NumInsts, uint64_t BitcodeIndex, bool EmitFunctionSummary) {
2418 std::unique_ptr<FunctionSummary> FuncSummary;
2419 if (EmitFunctionSummary) {
2420 FuncSummary = llvm::make_unique<FunctionSummary>(NumInsts);
2421 FuncSummary->setLocalFunction(F.hasLocalLinkage());
2424 llvm::make_unique<FunctionInfo>(BitcodeIndex, std::move(FuncSummary));
2427 /// Emit a function body to the module stream.
2428 static void WriteFunction(
2429 const Function &F, ValueEnumerator &VE, BitstreamWriter &Stream,
2430 DenseMap<const Function *, std::unique_ptr<FunctionInfo>> &FunctionIndex,
2431 bool EmitFunctionSummary) {
2432 // Save the bitcode index of the start of this function block for recording
2434 uint64_t BitcodeIndex = Stream.GetCurrentBitNo();
2436 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
2437 VE.incorporateFunction(F);
2439 SmallVector<unsigned, 64> Vals;
2441 // Emit the number of basic blocks, so the reader can create them ahead of
2443 Vals.push_back(VE.getBasicBlocks().size());
2444 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
2447 // If there are function-local constants, emit them now.
2448 unsigned CstStart, CstEnd;
2449 VE.getFunctionConstantRange(CstStart, CstEnd);
2450 WriteConstants(CstStart, CstEnd, VE, Stream, false);
2452 // If there is function-local metadata, emit it now.
2453 WriteFunctionLocalMetadata(F, VE, Stream);
2455 // Keep a running idea of what the instruction ID is.
2456 unsigned InstID = CstEnd;
2458 bool NeedsMetadataAttachment = F.hasMetadata();
2460 DILocation *LastDL = nullptr;
2461 unsigned NumInsts = 0;
2463 // Finally, emit all the instructions, in order.
2464 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
2465 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
2467 WriteInstruction(*I, InstID, VE, Stream, Vals);
2469 if (!isa<DbgInfoIntrinsic>(I)) ++NumInsts;
2471 if (!I->getType()->isVoidTy())
2474 // If the instruction has metadata, write a metadata attachment later.
2475 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
2477 // If the instruction has a debug location, emit it.
2478 DILocation *DL = I->getDebugLoc();
2483 // Just repeat the same debug loc as last time.
2484 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
2488 Vals.push_back(DL->getLine());
2489 Vals.push_back(DL->getColumn());
2490 Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
2491 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
2492 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
2498 // Emit names for all the instructions etc.
2499 WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
2501 if (NeedsMetadataAttachment)
2502 WriteMetadataAttachment(F, VE, Stream);
2503 if (VE.shouldPreserveUseListOrder())
2504 WriteUseListBlock(&F, VE, Stream);
2508 SaveFunctionInfo(F, FunctionIndex, NumInsts, BitcodeIndex,
2509 EmitFunctionSummary);
2512 // Emit blockinfo, which defines the standard abbreviations etc.
2513 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
2514 // We only want to emit block info records for blocks that have multiple
2515 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
2516 // Other blocks can define their abbrevs inline.
2517 Stream.EnterBlockInfoBlock(2);
2519 { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
2520 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2521 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
2522 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2523 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2524 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2525 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2526 Abbv) != VST_ENTRY_8_ABBREV)
2527 llvm_unreachable("Unexpected abbrev ordering!");
2530 { // 7-bit fixed width VST_ENTRY strings.
2531 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2532 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2533 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2534 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2535 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2536 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2537 Abbv) != VST_ENTRY_7_ABBREV)
2538 llvm_unreachable("Unexpected abbrev ordering!");
2540 { // 6-bit char6 VST_ENTRY strings.
2541 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2542 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2543 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2544 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2545 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2546 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2547 Abbv) != VST_ENTRY_6_ABBREV)
2548 llvm_unreachable("Unexpected abbrev ordering!");
2550 { // 6-bit char6 VST_BBENTRY strings.
2551 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2552 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
2553 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2554 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2555 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2556 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2557 Abbv) != VST_BBENTRY_6_ABBREV)
2558 llvm_unreachable("Unexpected abbrev ordering!");
2563 { // SETTYPE abbrev for CONSTANTS_BLOCK.
2564 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2565 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
2566 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
2567 VE.computeBitsRequiredForTypeIndicies()));
2568 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2569 Abbv) != CONSTANTS_SETTYPE_ABBREV)
2570 llvm_unreachable("Unexpected abbrev ordering!");
2573 { // INTEGER abbrev for CONSTANTS_BLOCK.
2574 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2575 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
2576 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2577 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2578 Abbv) != CONSTANTS_INTEGER_ABBREV)
2579 llvm_unreachable("Unexpected abbrev ordering!");
2582 { // CE_CAST abbrev for CONSTANTS_BLOCK.
2583 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2584 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
2585 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
2586 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
2587 VE.computeBitsRequiredForTypeIndicies()));
2588 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2590 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2591 Abbv) != CONSTANTS_CE_CAST_Abbrev)
2592 llvm_unreachable("Unexpected abbrev ordering!");
2594 { // NULL abbrev for CONSTANTS_BLOCK.
2595 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2596 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
2597 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2598 Abbv) != CONSTANTS_NULL_Abbrev)
2599 llvm_unreachable("Unexpected abbrev ordering!");
2602 // FIXME: This should only use space for first class types!
2604 { // INST_LOAD abbrev for FUNCTION_BLOCK.
2605 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2606 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
2607 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
2608 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
2609 VE.computeBitsRequiredForTypeIndicies()));
2610 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
2611 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
2612 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2613 Abbv) != FUNCTION_INST_LOAD_ABBREV)
2614 llvm_unreachable("Unexpected abbrev ordering!");
2616 { // INST_BINOP abbrev for FUNCTION_BLOCK.
2617 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2618 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
2619 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
2620 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
2621 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2622 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2623 Abbv) != FUNCTION_INST_BINOP_ABBREV)
2624 llvm_unreachable("Unexpected abbrev ordering!");
2626 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
2627 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2628 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
2629 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
2630 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
2631 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2632 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
2633 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2634 Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV)
2635 llvm_unreachable("Unexpected abbrev ordering!");
2637 { // INST_CAST abbrev for FUNCTION_BLOCK.
2638 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2639 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
2640 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
2641 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
2642 VE.computeBitsRequiredForTypeIndicies()));
2643 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2644 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2645 Abbv) != FUNCTION_INST_CAST_ABBREV)
2646 llvm_unreachable("Unexpected abbrev ordering!");
2649 { // INST_RET abbrev for FUNCTION_BLOCK.
2650 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2651 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
2652 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2653 Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
2654 llvm_unreachable("Unexpected abbrev ordering!");
2656 { // INST_RET abbrev for FUNCTION_BLOCK.
2657 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2658 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
2659 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
2660 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2661 Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
2662 llvm_unreachable("Unexpected abbrev ordering!");
2664 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
2665 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2666 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
2667 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2668 Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
2669 llvm_unreachable("Unexpected abbrev ordering!");
2672 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2673 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
2674 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
2675 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
2676 Log2_32_Ceil(VE.getTypes().size() + 1)));
2677 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2678 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2679 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
2680 FUNCTION_INST_GEP_ABBREV)
2681 llvm_unreachable("Unexpected abbrev ordering!");
2687 /// Write the module path strings, currently only used when generating
2688 /// a combined index file.
2689 static void WriteModStrings(const FunctionInfoIndex &I,
2690 BitstreamWriter &Stream) {
2691 Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);
2693 // TODO: See which abbrev sizes we actually need to emit
2695 // 8-bit fixed-width MST_ENTRY strings.
2696 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2697 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
2698 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2699 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2700 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2701 unsigned Abbrev8Bit = Stream.EmitAbbrev(Abbv);
2703 // 7-bit fixed width MST_ENTRY strings.
2704 Abbv = new BitCodeAbbrev();
2705 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
2706 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2707 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2708 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2709 unsigned Abbrev7Bit = Stream.EmitAbbrev(Abbv);
2711 // 6-bit char6 MST_ENTRY strings.
2712 Abbv = new BitCodeAbbrev();
2713 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
2714 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2715 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2716 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2717 unsigned Abbrev6Bit = Stream.EmitAbbrev(Abbv);
2719 SmallVector<unsigned, 64> NameVals;
2720 for (const StringMapEntry<uint64_t> &MPSE : I.modPathStringEntries()) {
2721 StringEncoding Bits =
2722 getStringEncoding(MPSE.getKey().data(), MPSE.getKey().size());
2723 unsigned AbbrevToUse = Abbrev8Bit;
2724 if (Bits == SE_Char6)
2725 AbbrevToUse = Abbrev6Bit;
2726 else if (Bits == SE_Fixed7)
2727 AbbrevToUse = Abbrev7Bit;
2729 NameVals.push_back(MPSE.getValue());
2731 for (const auto P : MPSE.getKey()) NameVals.push_back((unsigned char)P);
2733 // Emit the finished record.
2734 Stream.EmitRecord(bitc::MST_CODE_ENTRY, NameVals, AbbrevToUse);
2740 // Helper to emit a single function summary record.
2741 static void WritePerModuleFunctionSummaryRecord(
2742 SmallVector<unsigned, 64> &NameVals, FunctionSummary *FS, unsigned ValueID,
2743 unsigned FSAbbrev, BitstreamWriter &Stream) {
2745 NameVals.push_back(ValueID);
2746 NameVals.push_back(FS->isLocalFunction());
2747 NameVals.push_back(FS->instCount());
2749 // Emit the finished record.
2750 Stream.EmitRecord(bitc::FS_CODE_PERMODULE_ENTRY, NameVals, FSAbbrev);
2754 /// Emit the per-module function summary section alongside the rest of
2755 /// the module's bitcode.
2756 static void WritePerModuleFunctionSummary(
2757 DenseMap<const Function *, std::unique_ptr<FunctionInfo>> &FunctionIndex,
2758 const Module *M, const ValueEnumerator &VE, BitstreamWriter &Stream) {
2759 Stream.EnterSubblock(bitc::FUNCTION_SUMMARY_BLOCK_ID, 3);
2761 // Abbrev for FS_CODE_PERMODULE_ENTRY.
2762 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2763 Abbv->Add(BitCodeAbbrevOp(bitc::FS_CODE_PERMODULE_ENTRY));
2764 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
2765 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // islocal
2766 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
2767 unsigned FSAbbrev = Stream.EmitAbbrev(Abbv);
2769 SmallVector<unsigned, 64> NameVals;
2770 for (auto &I : FunctionIndex) {
2771 // Skip anonymous functions. We will emit a function summary for
2772 // any aliases below.
2773 if (!I.first->hasName()) continue;
2775 WritePerModuleFunctionSummaryRecord(
2776 NameVals, I.second->functionSummary(),
2777 VE.getValueID(M->getValueSymbolTable().lookup(I.first->getName())),
2781 for (const GlobalAlias &A : M->aliases()) {
2782 if (!A.getBaseObject()) continue;
2783 const Function *F = dyn_cast<Function>(A.getBaseObject());
2784 if (!F || F->isDeclaration()) continue;
2786 assert(FunctionIndex.count(F) == 1);
2787 WritePerModuleFunctionSummaryRecord(
2788 NameVals, FunctionIndex[F]->functionSummary(),
2789 VE.getValueID(M->getValueSymbolTable().lookup(A.getName())), FSAbbrev,
2796 /// Emit the combined function summary section into the combined index
2798 static void WriteCombinedFunctionSummary(const FunctionInfoIndex &I,
2799 BitstreamWriter &Stream) {
2800 Stream.EnterSubblock(bitc::FUNCTION_SUMMARY_BLOCK_ID, 3);
2802 // Abbrev for FS_CODE_COMBINED_ENTRY.
2803 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2804 Abbv->Add(BitCodeAbbrevOp(bitc::FS_CODE_COMBINED_ENTRY));
2805 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
2806 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
2807 unsigned FSAbbrev = Stream.EmitAbbrev(Abbv);
2809 SmallVector<unsigned, 64> NameVals;
2810 for (const auto &FII : I) {
2811 for (auto &FI : FII.getValue()) {
2812 FunctionSummary *FS = FI->functionSummary();
2815 NameVals.push_back(I.getModuleId(FS->modulePath()));
2816 NameVals.push_back(FS->instCount());
2818 // Record the starting offset of this summary entry for use
2819 // in the VST entry. Add the current code size since the
2820 // reader will invoke readRecord after the abbrev id read.
2821 FI->setBitcodeIndex(Stream.GetCurrentBitNo() + Stream.GetAbbrevIDWidth());
2823 // Emit the finished record.
2824 Stream.EmitRecord(bitc::FS_CODE_COMBINED_ENTRY, NameVals, FSAbbrev);
2832 // Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
2833 // current llvm version, and a record for the epoch number.
2834 static void WriteIdentificationBlock(const Module *M, BitstreamWriter &Stream) {
2835 Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);
2837 // Write the "user readable" string identifying the bitcode producer
2838 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2839 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING));
2840 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2841 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2842 auto StringAbbrev = Stream.EmitAbbrev(Abbv);
2843 WriteStringRecord(bitc::IDENTIFICATION_CODE_STRING,
2844 "LLVM" LLVM_VERSION_STRING, StringAbbrev, Stream);
2846 // Write the epoch version
2847 Abbv = new BitCodeAbbrev();
2848 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH));
2849 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2850 SmallVector<unsigned, 1> Vals = {bitc::BITCODE_CURRENT_EPOCH};
2851 Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals);
2855 /// WriteModule - Emit the specified module to the bitstream.
2856 static void WriteModule(const Module *M, BitstreamWriter &Stream,
2857 bool ShouldPreserveUseListOrder,
2858 uint64_t BitcodeStartBit, bool EmitFunctionSummary) {
2859 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
2861 SmallVector<unsigned, 1> Vals;
2862 unsigned CurVersion = 1;
2863 Vals.push_back(CurVersion);
2864 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
2866 // Analyze the module, enumerating globals, functions, etc.
2867 ValueEnumerator VE(*M, ShouldPreserveUseListOrder);
2869 // Emit blockinfo, which defines the standard abbreviations etc.
2870 WriteBlockInfo(VE, Stream);
2872 // Emit information about attribute groups.
2873 WriteAttributeGroupTable(VE, Stream);
2875 // Emit information about parameter attributes.
2876 WriteAttributeTable(VE, Stream);
2878 // Emit information describing all of the types in the module.
2879 WriteTypeTable(VE, Stream);
2881 writeComdats(VE, Stream);
2883 // Emit top-level description of module, including target triple, inline asm,
2884 // descriptors for global variables, and function prototype info.
2885 uint64_t VSTOffsetPlaceholder = WriteModuleInfo(M, VE, Stream);
2888 WriteModuleConstants(VE, Stream);
2891 WriteModuleMetadata(M, VE, Stream);
2894 WriteModuleMetadataStore(M, Stream);
2896 // Emit module-level use-lists.
2897 if (VE.shouldPreserveUseListOrder())
2898 WriteUseListBlock(nullptr, VE, Stream);
2900 WriteOperandBundleTags(M, Stream);
2902 // Emit function bodies.
2903 DenseMap<const Function *, std::unique_ptr<FunctionInfo>> FunctionIndex;
2904 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F)
2905 if (!F->isDeclaration())
2906 WriteFunction(*F, VE, Stream, FunctionIndex, EmitFunctionSummary);
2908 // Need to write after the above call to WriteFunction which populates
2909 // the summary information in the index.
2910 if (EmitFunctionSummary)
2911 WritePerModuleFunctionSummary(FunctionIndex, M, VE, Stream);
2913 WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream,
2914 VSTOffsetPlaceholder, BitcodeStartBit, &FunctionIndex);
2919 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
2920 /// header and trailer to make it compatible with the system archiver. To do
2921 /// this we emit the following header, and then emit a trailer that pads the
2922 /// file out to be a multiple of 16 bytes.
2924 /// struct bc_header {
2925 /// uint32_t Magic; // 0x0B17C0DE
2926 /// uint32_t Version; // Version, currently always 0.
2927 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
2928 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
2929 /// uint32_t CPUType; // CPU specifier.
2930 /// ... potentially more later ...
2933 DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
2934 DarwinBCHeaderSize = 5*4
2937 static void WriteInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
2938 uint32_t &Position) {
2939 support::endian::write32le(&Buffer[Position], Value);
2943 static void EmitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
2945 unsigned CPUType = ~0U;
2947 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
2948 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
2949 // number from /usr/include/mach/machine.h. It is ok to reproduce the
2950 // specific constants here because they are implicitly part of the Darwin ABI.
2952 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
2953 DARWIN_CPU_TYPE_X86 = 7,
2954 DARWIN_CPU_TYPE_ARM = 12,
2955 DARWIN_CPU_TYPE_POWERPC = 18
2958 Triple::ArchType Arch = TT.getArch();
2959 if (Arch == Triple::x86_64)
2960 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
2961 else if (Arch == Triple::x86)
2962 CPUType = DARWIN_CPU_TYPE_X86;
2963 else if (Arch == Triple::ppc)
2964 CPUType = DARWIN_CPU_TYPE_POWERPC;
2965 else if (Arch == Triple::ppc64)
2966 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
2967 else if (Arch == Triple::arm || Arch == Triple::thumb)
2968 CPUType = DARWIN_CPU_TYPE_ARM;
2970 // Traditional Bitcode starts after header.
2971 assert(Buffer.size() >= DarwinBCHeaderSize &&
2972 "Expected header size to be reserved");
2973 unsigned BCOffset = DarwinBCHeaderSize;
2974 unsigned BCSize = Buffer.size()-DarwinBCHeaderSize;
2976 // Write the magic and version.
2977 unsigned Position = 0;
2978 WriteInt32ToBuffer(0x0B17C0DE , Buffer, Position);
2979 WriteInt32ToBuffer(0 , Buffer, Position); // Version.
2980 WriteInt32ToBuffer(BCOffset , Buffer, Position);
2981 WriteInt32ToBuffer(BCSize , Buffer, Position);
2982 WriteInt32ToBuffer(CPUType , Buffer, Position);
2984 // If the file is not a multiple of 16 bytes, insert dummy padding.
2985 while (Buffer.size() & 15)
2986 Buffer.push_back(0);
2989 /// Helper to write the header common to all bitcode files.
2990 static void WriteBitcodeHeader(BitstreamWriter &Stream) {
2991 // Emit the file header.
2992 Stream.Emit((unsigned)'B', 8);
2993 Stream.Emit((unsigned)'C', 8);
2994 Stream.Emit(0x0, 4);
2995 Stream.Emit(0xC, 4);
2996 Stream.Emit(0xE, 4);
2997 Stream.Emit(0xD, 4);
3000 /// WriteBitcodeToFile - Write the specified module to the specified output
3002 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out,
3003 bool ShouldPreserveUseListOrder,
3004 bool EmitFunctionSummary) {
3005 SmallVector<char, 0> Buffer;
3006 Buffer.reserve(256*1024);
3008 // If this is darwin or another generic macho target, reserve space for the
3010 Triple TT(M->getTargetTriple());
3011 if (TT.isOSDarwin())
3012 Buffer.insert(Buffer.begin(), DarwinBCHeaderSize, 0);
3014 // Emit the module into the buffer.
3016 BitstreamWriter Stream(Buffer);
3017 // Save the start bit of the actual bitcode, in case there is space
3018 // saved at the start for the darwin header above. The reader stream
3019 // will start at the bitcode, and we need the offset of the VST
3021 uint64_t BitcodeStartBit = Stream.GetCurrentBitNo();
3023 // Emit the file header.
3024 WriteBitcodeHeader(Stream);
3026 WriteIdentificationBlock(M, Stream);
3029 WriteModule(M, Stream, ShouldPreserveUseListOrder, BitcodeStartBit,
3030 EmitFunctionSummary);
3033 if (TT.isOSDarwin())
3034 EmitDarwinBCHeaderAndTrailer(Buffer, TT);
3036 // Write the generated bitstream to "Out".
3037 Out.write((char*)&Buffer.front(), Buffer.size());
3040 // Write the specified function summary index to the given raw output stream,
3041 // where it will be written in a new bitcode block. This is used when
3042 // writing the combined index file for ThinLTO.
3043 void llvm::WriteFunctionSummaryToFile(const FunctionInfoIndex &Index,
3045 SmallVector<char, 0> Buffer;
3046 Buffer.reserve(256 * 1024);
3048 BitstreamWriter Stream(Buffer);
3050 // Emit the bitcode header.
3051 WriteBitcodeHeader(Stream);
3053 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
3055 SmallVector<unsigned, 1> Vals;
3056 unsigned CurVersion = 1;
3057 Vals.push_back(CurVersion);
3058 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
3060 // Write the module paths in the combined index.
3061 WriteModStrings(Index, Stream);
3063 // Write the function summary combined index records.
3064 WriteCombinedFunctionSummary(Index, Stream);
3066 // Need a special VST writer for the combined index (we don't have a
3067 // real VST and real values when this is invoked).
3068 WriteCombinedValueSymbolTable(Index, Stream);
3072 Out.write((char *)&Buffer.front(), Buffer.size());