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/Triple.h"
17 #include "llvm/Bitcode/BitstreamWriter.h"
18 #include "llvm/Bitcode/LLVMBitCodes.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/DebugInfoMetadata.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/IR/InlineAsm.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/IR/Operator.h"
26 #include "llvm/IR/UseListOrder.h"
27 #include "llvm/IR/ValueSymbolTable.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/MathExtras.h"
31 #include "llvm/Support/Program.h"
32 #include "llvm/Support/raw_ostream.h"
37 /// These are manifest constants used by the bitcode writer. They do not need to
38 /// be kept in sync with the reader, but need to be consistent within this file.
40 // VALUE_SYMTAB_BLOCK abbrev id's.
41 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
46 // CONSTANTS_BLOCK abbrev id's.
47 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
48 CONSTANTS_INTEGER_ABBREV,
49 CONSTANTS_CE_CAST_Abbrev,
50 CONSTANTS_NULL_Abbrev,
52 // FUNCTION_BLOCK abbrev id's.
53 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
54 FUNCTION_INST_BINOP_ABBREV,
55 FUNCTION_INST_BINOP_FLAGS_ABBREV,
56 FUNCTION_INST_CAST_ABBREV,
57 FUNCTION_INST_RET_VOID_ABBREV,
58 FUNCTION_INST_RET_VAL_ABBREV,
59 FUNCTION_INST_UNREACHABLE_ABBREV,
60 FUNCTION_INST_GEP_ABBREV,
63 static unsigned GetEncodedCastOpcode(unsigned Opcode) {
65 default: llvm_unreachable("Unknown cast instruction!");
66 case Instruction::Trunc : return bitc::CAST_TRUNC;
67 case Instruction::ZExt : return bitc::CAST_ZEXT;
68 case Instruction::SExt : return bitc::CAST_SEXT;
69 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
70 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
71 case Instruction::UIToFP : return bitc::CAST_UITOFP;
72 case Instruction::SIToFP : return bitc::CAST_SITOFP;
73 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
74 case Instruction::FPExt : return bitc::CAST_FPEXT;
75 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
76 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
77 case Instruction::BitCast : return bitc::CAST_BITCAST;
78 case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
82 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
84 default: llvm_unreachable("Unknown binary instruction!");
85 case Instruction::Add:
86 case Instruction::FAdd: return bitc::BINOP_ADD;
87 case Instruction::Sub:
88 case Instruction::FSub: return bitc::BINOP_SUB;
89 case Instruction::Mul:
90 case Instruction::FMul: return bitc::BINOP_MUL;
91 case Instruction::UDiv: return bitc::BINOP_UDIV;
92 case Instruction::FDiv:
93 case Instruction::SDiv: return bitc::BINOP_SDIV;
94 case Instruction::URem: return bitc::BINOP_UREM;
95 case Instruction::FRem:
96 case Instruction::SRem: return bitc::BINOP_SREM;
97 case Instruction::Shl: return bitc::BINOP_SHL;
98 case Instruction::LShr: return bitc::BINOP_LSHR;
99 case Instruction::AShr: return bitc::BINOP_ASHR;
100 case Instruction::And: return bitc::BINOP_AND;
101 case Instruction::Or: return bitc::BINOP_OR;
102 case Instruction::Xor: return bitc::BINOP_XOR;
106 static unsigned GetEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
108 default: llvm_unreachable("Unknown RMW operation!");
109 case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
110 case AtomicRMWInst::Add: return bitc::RMW_ADD;
111 case AtomicRMWInst::Sub: return bitc::RMW_SUB;
112 case AtomicRMWInst::And: return bitc::RMW_AND;
113 case AtomicRMWInst::Nand: return bitc::RMW_NAND;
114 case AtomicRMWInst::Or: return bitc::RMW_OR;
115 case AtomicRMWInst::Xor: return bitc::RMW_XOR;
116 case AtomicRMWInst::Max: return bitc::RMW_MAX;
117 case AtomicRMWInst::Min: return bitc::RMW_MIN;
118 case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
119 case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
123 static unsigned GetEncodedOrdering(AtomicOrdering Ordering) {
125 case NotAtomic: return bitc::ORDERING_NOTATOMIC;
126 case Unordered: return bitc::ORDERING_UNORDERED;
127 case Monotonic: return bitc::ORDERING_MONOTONIC;
128 case Acquire: return bitc::ORDERING_ACQUIRE;
129 case Release: return bitc::ORDERING_RELEASE;
130 case AcquireRelease: return bitc::ORDERING_ACQREL;
131 case SequentiallyConsistent: return bitc::ORDERING_SEQCST;
133 llvm_unreachable("Invalid ordering");
136 static unsigned GetEncodedSynchScope(SynchronizationScope SynchScope) {
137 switch (SynchScope) {
138 case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD;
139 case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD;
141 llvm_unreachable("Invalid synch scope");
144 static void WriteStringRecord(unsigned Code, StringRef Str,
145 unsigned AbbrevToUse, BitstreamWriter &Stream) {
146 SmallVector<unsigned, 64> Vals;
148 // Code: [strchar x N]
149 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
150 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
152 Vals.push_back(Str[i]);
155 // Emit the finished record.
156 Stream.EmitRecord(Code, Vals, AbbrevToUse);
159 static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
161 case Attribute::Alignment:
162 return bitc::ATTR_KIND_ALIGNMENT;
163 case Attribute::AlwaysInline:
164 return bitc::ATTR_KIND_ALWAYS_INLINE;
165 case Attribute::Builtin:
166 return bitc::ATTR_KIND_BUILTIN;
167 case Attribute::ByVal:
168 return bitc::ATTR_KIND_BY_VAL;
169 case Attribute::InAlloca:
170 return bitc::ATTR_KIND_IN_ALLOCA;
171 case Attribute::Cold:
172 return bitc::ATTR_KIND_COLD;
173 case Attribute::InlineHint:
174 return bitc::ATTR_KIND_INLINE_HINT;
175 case Attribute::InReg:
176 return bitc::ATTR_KIND_IN_REG;
177 case Attribute::JumpTable:
178 return bitc::ATTR_KIND_JUMP_TABLE;
179 case Attribute::MinSize:
180 return bitc::ATTR_KIND_MIN_SIZE;
181 case Attribute::Naked:
182 return bitc::ATTR_KIND_NAKED;
183 case Attribute::Nest:
184 return bitc::ATTR_KIND_NEST;
185 case Attribute::NoAlias:
186 return bitc::ATTR_KIND_NO_ALIAS;
187 case Attribute::NoBuiltin:
188 return bitc::ATTR_KIND_NO_BUILTIN;
189 case Attribute::NoCapture:
190 return bitc::ATTR_KIND_NO_CAPTURE;
191 case Attribute::NoDuplicate:
192 return bitc::ATTR_KIND_NO_DUPLICATE;
193 case Attribute::NoImplicitFloat:
194 return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
195 case Attribute::NoInline:
196 return bitc::ATTR_KIND_NO_INLINE;
197 case Attribute::NonLazyBind:
198 return bitc::ATTR_KIND_NON_LAZY_BIND;
199 case Attribute::NonNull:
200 return bitc::ATTR_KIND_NON_NULL;
201 case Attribute::Dereferenceable:
202 return bitc::ATTR_KIND_DEREFERENCEABLE;
203 case Attribute::NoRedZone:
204 return bitc::ATTR_KIND_NO_RED_ZONE;
205 case Attribute::NoReturn:
206 return bitc::ATTR_KIND_NO_RETURN;
207 case Attribute::NoUnwind:
208 return bitc::ATTR_KIND_NO_UNWIND;
209 case Attribute::OptimizeForSize:
210 return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
211 case Attribute::OptimizeNone:
212 return bitc::ATTR_KIND_OPTIMIZE_NONE;
213 case Attribute::ReadNone:
214 return bitc::ATTR_KIND_READ_NONE;
215 case Attribute::ReadOnly:
216 return bitc::ATTR_KIND_READ_ONLY;
217 case Attribute::Returned:
218 return bitc::ATTR_KIND_RETURNED;
219 case Attribute::ReturnsTwice:
220 return bitc::ATTR_KIND_RETURNS_TWICE;
221 case Attribute::SExt:
222 return bitc::ATTR_KIND_S_EXT;
223 case Attribute::StackAlignment:
224 return bitc::ATTR_KIND_STACK_ALIGNMENT;
225 case Attribute::StackProtect:
226 return bitc::ATTR_KIND_STACK_PROTECT;
227 case Attribute::StackProtectReq:
228 return bitc::ATTR_KIND_STACK_PROTECT_REQ;
229 case Attribute::StackProtectStrong:
230 return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
231 case Attribute::StructRet:
232 return bitc::ATTR_KIND_STRUCT_RET;
233 case Attribute::SanitizeAddress:
234 return bitc::ATTR_KIND_SANITIZE_ADDRESS;
235 case Attribute::SanitizeThread:
236 return bitc::ATTR_KIND_SANITIZE_THREAD;
237 case Attribute::SanitizeMemory:
238 return bitc::ATTR_KIND_SANITIZE_MEMORY;
239 case Attribute::UWTable:
240 return bitc::ATTR_KIND_UW_TABLE;
241 case Attribute::ZExt:
242 return bitc::ATTR_KIND_Z_EXT;
243 case Attribute::EndAttrKinds:
244 llvm_unreachable("Can not encode end-attribute kinds marker.");
245 case Attribute::None:
246 llvm_unreachable("Can not encode none-attribute.");
249 llvm_unreachable("Trying to encode unknown attribute");
252 static void WriteAttributeGroupTable(const ValueEnumerator &VE,
253 BitstreamWriter &Stream) {
254 const std::vector<AttributeSet> &AttrGrps = VE.getAttributeGroups();
255 if (AttrGrps.empty()) return;
257 Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
259 SmallVector<uint64_t, 64> Record;
260 for (unsigned i = 0, e = AttrGrps.size(); i != e; ++i) {
261 AttributeSet AS = AttrGrps[i];
262 for (unsigned i = 0, e = AS.getNumSlots(); i != e; ++i) {
263 AttributeSet A = AS.getSlotAttributes(i);
265 Record.push_back(VE.getAttributeGroupID(A));
266 Record.push_back(AS.getSlotIndex(i));
268 for (AttributeSet::iterator I = AS.begin(0), E = AS.end(0);
271 if (Attr.isEnumAttribute()) {
273 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
274 } else if (Attr.isIntAttribute()) {
276 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
277 Record.push_back(Attr.getValueAsInt());
279 StringRef Kind = Attr.getKindAsString();
280 StringRef Val = Attr.getValueAsString();
282 Record.push_back(Val.empty() ? 3 : 4);
283 Record.append(Kind.begin(), Kind.end());
286 Record.append(Val.begin(), Val.end());
292 Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
300 static void WriteAttributeTable(const ValueEnumerator &VE,
301 BitstreamWriter &Stream) {
302 const std::vector<AttributeSet> &Attrs = VE.getAttributes();
303 if (Attrs.empty()) return;
305 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
307 SmallVector<uint64_t, 64> Record;
308 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
309 const AttributeSet &A = Attrs[i];
310 for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i)
311 Record.push_back(VE.getAttributeGroupID(A.getSlotAttributes(i)));
313 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
320 /// WriteTypeTable - Write out the type table for a module.
321 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
322 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
324 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
325 SmallVector<uint64_t, 64> TypeVals;
327 uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies();
329 // Abbrev for TYPE_CODE_POINTER.
330 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
331 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
332 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
333 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
334 unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
336 // Abbrev for TYPE_CODE_FUNCTION.
337 Abbv = new BitCodeAbbrev();
338 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
339 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
340 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
341 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
343 unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
345 // Abbrev for TYPE_CODE_STRUCT_ANON.
346 Abbv = new BitCodeAbbrev();
347 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
348 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
349 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
350 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
352 unsigned StructAnonAbbrev = Stream.EmitAbbrev(Abbv);
354 // Abbrev for TYPE_CODE_STRUCT_NAME.
355 Abbv = new BitCodeAbbrev();
356 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
357 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
358 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
359 unsigned StructNameAbbrev = Stream.EmitAbbrev(Abbv);
361 // Abbrev for TYPE_CODE_STRUCT_NAMED.
362 Abbv = new BitCodeAbbrev();
363 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
364 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
365 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
366 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
368 unsigned StructNamedAbbrev = Stream.EmitAbbrev(Abbv);
370 // Abbrev for TYPE_CODE_ARRAY.
371 Abbv = new BitCodeAbbrev();
372 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
373 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
374 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
376 unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
378 // Emit an entry count so the reader can reserve space.
379 TypeVals.push_back(TypeList.size());
380 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
383 // Loop over all of the types, emitting each in turn.
384 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
385 Type *T = TypeList[i];
389 switch (T->getTypeID()) {
390 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
391 case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break;
392 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
393 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
394 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
395 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
396 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
397 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
398 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
399 case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break;
400 case Type::IntegerTyID:
402 Code = bitc::TYPE_CODE_INTEGER;
403 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
405 case Type::PointerTyID: {
406 PointerType *PTy = cast<PointerType>(T);
407 // POINTER: [pointee type, address space]
408 Code = bitc::TYPE_CODE_POINTER;
409 TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
410 unsigned AddressSpace = PTy->getAddressSpace();
411 TypeVals.push_back(AddressSpace);
412 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
415 case Type::FunctionTyID: {
416 FunctionType *FT = cast<FunctionType>(T);
417 // FUNCTION: [isvararg, retty, paramty x N]
418 Code = bitc::TYPE_CODE_FUNCTION;
419 TypeVals.push_back(FT->isVarArg());
420 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
421 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
422 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
423 AbbrevToUse = FunctionAbbrev;
426 case Type::StructTyID: {
427 StructType *ST = cast<StructType>(T);
428 // STRUCT: [ispacked, eltty x N]
429 TypeVals.push_back(ST->isPacked());
430 // Output all of the element types.
431 for (StructType::element_iterator I = ST->element_begin(),
432 E = ST->element_end(); I != E; ++I)
433 TypeVals.push_back(VE.getTypeID(*I));
435 if (ST->isLiteral()) {
436 Code = bitc::TYPE_CODE_STRUCT_ANON;
437 AbbrevToUse = StructAnonAbbrev;
439 if (ST->isOpaque()) {
440 Code = bitc::TYPE_CODE_OPAQUE;
442 Code = bitc::TYPE_CODE_STRUCT_NAMED;
443 AbbrevToUse = StructNamedAbbrev;
446 // Emit the name if it is present.
447 if (!ST->getName().empty())
448 WriteStringRecord(bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
449 StructNameAbbrev, Stream);
453 case Type::ArrayTyID: {
454 ArrayType *AT = cast<ArrayType>(T);
455 // ARRAY: [numelts, eltty]
456 Code = bitc::TYPE_CODE_ARRAY;
457 TypeVals.push_back(AT->getNumElements());
458 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
459 AbbrevToUse = ArrayAbbrev;
462 case Type::VectorTyID: {
463 VectorType *VT = cast<VectorType>(T);
464 // VECTOR [numelts, eltty]
465 Code = bitc::TYPE_CODE_VECTOR;
466 TypeVals.push_back(VT->getNumElements());
467 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
472 // Emit the finished record.
473 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
480 static unsigned getEncodedLinkage(const GlobalValue &GV) {
481 switch (GV.getLinkage()) {
482 case GlobalValue::ExternalLinkage:
484 case GlobalValue::WeakAnyLinkage:
486 case GlobalValue::AppendingLinkage:
488 case GlobalValue::InternalLinkage:
490 case GlobalValue::LinkOnceAnyLinkage:
492 case GlobalValue::ExternalWeakLinkage:
494 case GlobalValue::CommonLinkage:
496 case GlobalValue::PrivateLinkage:
498 case GlobalValue::WeakODRLinkage:
500 case GlobalValue::LinkOnceODRLinkage:
502 case GlobalValue::AvailableExternallyLinkage:
505 llvm_unreachable("Invalid linkage");
508 static unsigned getEncodedVisibility(const GlobalValue &GV) {
509 switch (GV.getVisibility()) {
510 case GlobalValue::DefaultVisibility: return 0;
511 case GlobalValue::HiddenVisibility: return 1;
512 case GlobalValue::ProtectedVisibility: return 2;
514 llvm_unreachable("Invalid visibility");
517 static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
518 switch (GV.getDLLStorageClass()) {
519 case GlobalValue::DefaultStorageClass: return 0;
520 case GlobalValue::DLLImportStorageClass: return 1;
521 case GlobalValue::DLLExportStorageClass: return 2;
523 llvm_unreachable("Invalid DLL storage class");
526 static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
527 switch (GV.getThreadLocalMode()) {
528 case GlobalVariable::NotThreadLocal: return 0;
529 case GlobalVariable::GeneralDynamicTLSModel: return 1;
530 case GlobalVariable::LocalDynamicTLSModel: return 2;
531 case GlobalVariable::InitialExecTLSModel: return 3;
532 case GlobalVariable::LocalExecTLSModel: return 4;
534 llvm_unreachable("Invalid TLS model");
537 static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
538 switch (C.getSelectionKind()) {
540 return bitc::COMDAT_SELECTION_KIND_ANY;
541 case Comdat::ExactMatch:
542 return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
543 case Comdat::Largest:
544 return bitc::COMDAT_SELECTION_KIND_LARGEST;
545 case Comdat::NoDuplicates:
546 return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
547 case Comdat::SameSize:
548 return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
550 llvm_unreachable("Invalid selection kind");
553 static void writeComdats(const ValueEnumerator &VE, BitstreamWriter &Stream) {
554 SmallVector<uint16_t, 64> Vals;
555 for (const Comdat *C : VE.getComdats()) {
556 // COMDAT: [selection_kind, name]
557 Vals.push_back(getEncodedComdatSelectionKind(*C));
558 size_t Size = C->getName().size();
559 assert(isUInt<16>(Size));
560 Vals.push_back(Size);
561 for (char Chr : C->getName())
562 Vals.push_back((unsigned char)Chr);
563 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
568 // Emit top-level description of module, including target triple, inline asm,
569 // descriptors for global variables, and function prototype info.
570 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
571 BitstreamWriter &Stream) {
572 // Emit various pieces of data attached to a module.
573 if (!M->getTargetTriple().empty())
574 WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
576 const std::string &DL = M->getDataLayoutStr();
578 WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/, Stream);
579 if (!M->getModuleInlineAsm().empty())
580 WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
583 // Emit information about sections and GC, computing how many there are. Also
584 // compute the maximum alignment value.
585 std::map<std::string, unsigned> SectionMap;
586 std::map<std::string, unsigned> GCMap;
587 unsigned MaxAlignment = 0;
588 unsigned MaxGlobalType = 0;
589 for (const GlobalValue &GV : M->globals()) {
590 MaxAlignment = std::max(MaxAlignment, GV.getAlignment());
591 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getType()));
592 if (GV.hasSection()) {
593 // Give section names unique ID's.
594 unsigned &Entry = SectionMap[GV.getSection()];
596 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
598 Entry = SectionMap.size();
602 for (const Function &F : *M) {
603 MaxAlignment = std::max(MaxAlignment, F.getAlignment());
604 if (F.hasSection()) {
605 // Give section names unique ID's.
606 unsigned &Entry = SectionMap[F.getSection()];
608 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
610 Entry = SectionMap.size();
614 // Same for GC names.
615 unsigned &Entry = GCMap[F.getGC()];
617 WriteStringRecord(bitc::MODULE_CODE_GCNAME, F.getGC(),
619 Entry = GCMap.size();
624 // Emit abbrev for globals, now that we know # sections and max alignment.
625 unsigned SimpleGVarAbbrev = 0;
626 if (!M->global_empty()) {
627 // Add an abbrev for common globals with no visibility or thread localness.
628 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
629 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
630 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
631 Log2_32_Ceil(MaxGlobalType+1)));
632 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Constant.
633 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
634 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
635 if (MaxAlignment == 0) // Alignment.
636 Abbv->Add(BitCodeAbbrevOp(0));
638 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
639 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
640 Log2_32_Ceil(MaxEncAlignment+1)));
642 if (SectionMap.empty()) // Section.
643 Abbv->Add(BitCodeAbbrevOp(0));
645 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
646 Log2_32_Ceil(SectionMap.size()+1)));
647 // Don't bother emitting vis + thread local.
648 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
651 // Emit the global variable information.
652 SmallVector<unsigned, 64> Vals;
653 for (const GlobalVariable &GV : M->globals()) {
654 unsigned AbbrevToUse = 0;
656 // GLOBALVAR: [type, isconst, initid,
657 // linkage, alignment, section, visibility, threadlocal,
658 // unnamed_addr, externally_initialized, dllstorageclass,
660 Vals.push_back(VE.getTypeID(GV.getType()));
661 Vals.push_back(GV.isConstant());
662 Vals.push_back(GV.isDeclaration() ? 0 :
663 (VE.getValueID(GV.getInitializer()) + 1));
664 Vals.push_back(getEncodedLinkage(GV));
665 Vals.push_back(Log2_32(GV.getAlignment())+1);
666 Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0);
667 if (GV.isThreadLocal() ||
668 GV.getVisibility() != GlobalValue::DefaultVisibility ||
669 GV.hasUnnamedAddr() || GV.isExternallyInitialized() ||
670 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
672 Vals.push_back(getEncodedVisibility(GV));
673 Vals.push_back(getEncodedThreadLocalMode(GV));
674 Vals.push_back(GV.hasUnnamedAddr());
675 Vals.push_back(GV.isExternallyInitialized());
676 Vals.push_back(getEncodedDLLStorageClass(GV));
677 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
679 AbbrevToUse = SimpleGVarAbbrev;
682 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
686 // Emit the function proto information.
687 for (const Function &F : *M) {
688 // FUNCTION: [type, callingconv, isproto, linkage, paramattrs, alignment,
689 // section, visibility, gc, unnamed_addr, prologuedata,
690 // dllstorageclass, comdat, prefixdata]
691 Vals.push_back(VE.getTypeID(F.getType()));
692 Vals.push_back(F.getCallingConv());
693 Vals.push_back(F.isDeclaration());
694 Vals.push_back(getEncodedLinkage(F));
695 Vals.push_back(VE.getAttributeID(F.getAttributes()));
696 Vals.push_back(Log2_32(F.getAlignment())+1);
697 Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0);
698 Vals.push_back(getEncodedVisibility(F));
699 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
700 Vals.push_back(F.hasUnnamedAddr());
701 Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
703 Vals.push_back(getEncodedDLLStorageClass(F));
704 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
705 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
708 unsigned AbbrevToUse = 0;
709 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
713 // Emit the alias information.
714 for (const GlobalAlias &A : M->aliases()) {
715 // ALIAS: [alias type, aliasee val#, linkage, visibility]
716 Vals.push_back(VE.getTypeID(A.getType()));
717 Vals.push_back(VE.getValueID(A.getAliasee()));
718 Vals.push_back(getEncodedLinkage(A));
719 Vals.push_back(getEncodedVisibility(A));
720 Vals.push_back(getEncodedDLLStorageClass(A));
721 Vals.push_back(getEncodedThreadLocalMode(A));
722 Vals.push_back(A.hasUnnamedAddr());
723 unsigned AbbrevToUse = 0;
724 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
729 static uint64_t GetOptimizationFlags(const Value *V) {
732 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
733 if (OBO->hasNoSignedWrap())
734 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
735 if (OBO->hasNoUnsignedWrap())
736 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
737 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
739 Flags |= 1 << bitc::PEO_EXACT;
740 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
741 if (FPMO->hasUnsafeAlgebra())
742 Flags |= FastMathFlags::UnsafeAlgebra;
743 if (FPMO->hasNoNaNs())
744 Flags |= FastMathFlags::NoNaNs;
745 if (FPMO->hasNoInfs())
746 Flags |= FastMathFlags::NoInfs;
747 if (FPMO->hasNoSignedZeros())
748 Flags |= FastMathFlags::NoSignedZeros;
749 if (FPMO->hasAllowReciprocal())
750 Flags |= FastMathFlags::AllowReciprocal;
756 static void WriteValueAsMetadata(const ValueAsMetadata *MD,
757 const ValueEnumerator &VE,
758 BitstreamWriter &Stream,
759 SmallVectorImpl<uint64_t> &Record) {
760 // Mimic an MDNode with a value as one operand.
761 Value *V = MD->getValue();
762 Record.push_back(VE.getTypeID(V->getType()));
763 Record.push_back(VE.getValueID(V));
764 Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
768 static void WriteMDTuple(const MDTuple *N, const ValueEnumerator &VE,
769 BitstreamWriter &Stream,
770 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
771 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
772 Metadata *MD = N->getOperand(i);
773 assert(!(MD && isa<LocalAsMetadata>(MD)) &&
774 "Unexpected function-local metadata");
775 Record.push_back(VE.getMetadataOrNullID(MD));
777 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
778 : bitc::METADATA_NODE,
783 static void WriteMDLocation(const MDLocation *N, const ValueEnumerator &VE,
784 BitstreamWriter &Stream,
785 SmallVectorImpl<uint64_t> &Record,
787 Record.push_back(N->isDistinct());
788 Record.push_back(N->getLine());
789 Record.push_back(N->getColumn());
790 Record.push_back(VE.getMetadataID(N->getScope()));
791 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
793 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
797 static void WriteGenericDebugNode(const GenericDebugNode *N,
798 const ValueEnumerator &VE,
799 BitstreamWriter &Stream,
800 SmallVectorImpl<uint64_t> &Record,
802 Record.push_back(N->isDistinct());
803 Record.push_back(N->getTag());
804 Record.push_back(0); // Per-tag version field; unused for now.
806 for (auto &I : N->operands())
807 Record.push_back(VE.getMetadataOrNullID(I));
809 Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
813 static uint64_t rotateSign(int64_t I) {
815 return I < 0 ? ~(U << 1) : U << 1;
818 static void WriteMDSubrange(const MDSubrange *N, const ValueEnumerator &,
819 BitstreamWriter &Stream,
820 SmallVectorImpl<uint64_t> &Record,
822 Record.push_back(N->isDistinct());
823 Record.push_back(N->getCount());
824 Record.push_back(rotateSign(N->getLowerBound()));
826 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
830 static void WriteMDEnumerator(const MDEnumerator *N, const ValueEnumerator &VE,
831 BitstreamWriter &Stream,
832 SmallVectorImpl<uint64_t> &Record,
834 Record.push_back(N->isDistinct());
835 Record.push_back(rotateSign(N->getValue()));
836 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
838 Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
842 static void WriteMDBasicType(const MDBasicType *N, const ValueEnumerator &VE,
843 BitstreamWriter &Stream,
844 SmallVectorImpl<uint64_t> &Record,
846 Record.push_back(N->isDistinct());
847 Record.push_back(N->getTag());
848 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
849 Record.push_back(N->getSizeInBits());
850 Record.push_back(N->getAlignInBits());
851 Record.push_back(N->getEncoding());
853 Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
857 static void WriteMDDerivedType(const MDDerivedType *N,
858 const ValueEnumerator &VE,
859 BitstreamWriter &Stream,
860 SmallVectorImpl<uint64_t> &Record,
862 Record.push_back(N->isDistinct());
863 Record.push_back(N->getTag());
864 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
865 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
866 Record.push_back(N->getLine());
867 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
868 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
869 Record.push_back(N->getSizeInBits());
870 Record.push_back(N->getAlignInBits());
871 Record.push_back(N->getOffsetInBits());
872 Record.push_back(N->getFlags());
873 Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
875 Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
879 static void WriteMDCompositeType(const MDCompositeType *N,
880 const ValueEnumerator &VE,
881 BitstreamWriter &Stream,
882 SmallVectorImpl<uint64_t> &Record,
884 Record.push_back(N->isDistinct());
885 Record.push_back(N->getTag());
886 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
887 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
888 Record.push_back(N->getLine());
889 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
890 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
891 Record.push_back(N->getSizeInBits());
892 Record.push_back(N->getAlignInBits());
893 Record.push_back(N->getOffsetInBits());
894 Record.push_back(N->getFlags());
895 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
896 Record.push_back(N->getRuntimeLang());
897 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
898 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
899 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
901 Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
905 static void WriteMDSubroutineType(const MDSubroutineType *N,
906 const ValueEnumerator &VE,
907 BitstreamWriter &Stream,
908 SmallVectorImpl<uint64_t> &Record,
910 Record.push_back(N->isDistinct());
911 Record.push_back(N->getFlags());
912 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
914 Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
918 static void WriteMDFile(const MDFile *N, const ValueEnumerator &VE,
919 BitstreamWriter &Stream,
920 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
921 Record.push_back(N->isDistinct());
922 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
923 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
925 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
929 static void WriteMDCompileUnit(const MDCompileUnit *N,
930 const ValueEnumerator &VE,
931 BitstreamWriter &Stream,
932 SmallVectorImpl<uint64_t> &Record,
934 Record.push_back(N->isDistinct());
935 Record.push_back(N->getSourceLanguage());
936 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
937 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
938 Record.push_back(N->isOptimized());
939 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
940 Record.push_back(N->getRuntimeVersion());
941 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
942 Record.push_back(N->getEmissionKind());
943 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
944 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
945 Record.push_back(VE.getMetadataOrNullID(N->getSubprograms().get()));
946 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
947 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
949 Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
953 static void WriteMDSubprogram(const MDSubprogram *N,
954 const ValueEnumerator &VE,
955 BitstreamWriter &Stream,
956 SmallVectorImpl<uint64_t> &Record,
958 Record.push_back(N->isDistinct());
959 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
960 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
961 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
962 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
963 Record.push_back(N->getLine());
964 Record.push_back(VE.getMetadataOrNullID(N->getType()));
965 Record.push_back(N->isLocalToUnit());
966 Record.push_back(N->isDefinition());
967 Record.push_back(N->getScopeLine());
968 Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
969 Record.push_back(N->getVirtuality());
970 Record.push_back(N->getVirtualIndex());
971 Record.push_back(N->getFlags());
972 Record.push_back(N->isOptimized());
973 Record.push_back(VE.getMetadataOrNullID(N->getRawFunction()));
974 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
975 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
976 Record.push_back(VE.getMetadataOrNullID(N->getVariables().get()));
978 Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
982 static void WriteMDLexicalBlock(const MDLexicalBlock *N,
983 const ValueEnumerator &VE,
984 BitstreamWriter &Stream,
985 SmallVectorImpl<uint64_t> &Record,
987 Record.push_back(N->isDistinct());
988 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
989 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
990 Record.push_back(N->getLine());
991 Record.push_back(N->getColumn());
993 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
997 static void WriteMDLexicalBlockFile(const MDLexicalBlockFile *N,
998 const ValueEnumerator &VE,
999 BitstreamWriter &Stream,
1000 SmallVectorImpl<uint64_t> &Record,
1002 Record.push_back(N->isDistinct());
1003 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1004 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1005 Record.push_back(N->getDiscriminator());
1007 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
1011 static void WriteMDNamespace(const MDNamespace *N, const ValueEnumerator &VE,
1012 BitstreamWriter &Stream,
1013 SmallVectorImpl<uint64_t> &Record,
1015 Record.push_back(N->isDistinct());
1016 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1017 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1018 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1019 Record.push_back(N->getLine());
1021 Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
1025 static void WriteMDTemplateTypeParameter(const MDTemplateTypeParameter *N,
1026 const ValueEnumerator &VE,
1027 BitstreamWriter &Stream,
1028 SmallVectorImpl<uint64_t> &Record,
1030 Record.push_back(N->isDistinct());
1031 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1032 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1034 Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
1038 static void WriteMDTemplateValueParameter(const MDTemplateValueParameter *N,
1039 const ValueEnumerator &VE,
1040 BitstreamWriter &Stream,
1041 SmallVectorImpl<uint64_t> &Record,
1043 Record.push_back(N->isDistinct());
1044 Record.push_back(N->getTag());
1045 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1046 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1047 Record.push_back(VE.getMetadataOrNullID(N->getValue()));
1049 Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
1053 static void WriteMDGlobalVariable(const MDGlobalVariable *N,
1054 const ValueEnumerator &VE,
1055 BitstreamWriter &Stream,
1056 SmallVectorImpl<uint64_t> &Record,
1058 Record.push_back(N->isDistinct());
1059 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1060 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1061 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1062 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1063 Record.push_back(N->getLine());
1064 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1065 Record.push_back(N->isLocalToUnit());
1066 Record.push_back(N->isDefinition());
1067 Record.push_back(VE.getMetadataOrNullID(N->getRawVariable()));
1068 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
1070 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
1074 static void WriteMDLocalVariable(const MDLocalVariable *N,
1075 const ValueEnumerator &VE,
1076 BitstreamWriter &Stream,
1077 SmallVectorImpl<uint64_t> &Record,
1079 Record.push_back(N->isDistinct());
1080 Record.push_back(N->getTag());
1081 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1082 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1083 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1084 Record.push_back(N->getLine());
1085 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1086 Record.push_back(N->getArg());
1087 Record.push_back(N->getFlags());
1089 Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
1093 static void WriteMDExpression(const MDExpression *N, const ValueEnumerator &,
1094 BitstreamWriter &Stream,
1095 SmallVectorImpl<uint64_t> &Record,
1097 Record.reserve(N->getElements().size() + 1);
1099 Record.push_back(N->isDistinct());
1100 Record.append(N->elements_begin(), N->elements_end());
1102 Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
1106 static void WriteMDObjCProperty(const MDObjCProperty *N,
1107 const ValueEnumerator &VE,
1108 BitstreamWriter &Stream,
1109 SmallVectorImpl<uint64_t> &Record,
1111 Record.push_back(N->isDistinct());
1112 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1113 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1114 Record.push_back(N->getLine());
1115 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
1116 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
1117 Record.push_back(N->getAttributes());
1118 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1120 Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
1124 static void WriteMDImportedEntity(const MDImportedEntity *N,
1125 const ValueEnumerator &VE,
1126 BitstreamWriter &Stream,
1127 SmallVectorImpl<uint64_t> &Record,
1129 Record.push_back(N->isDistinct());
1130 Record.push_back(N->getTag());
1131 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1132 Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
1133 Record.push_back(N->getLine());
1134 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1136 Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
1140 static void WriteModuleMetadata(const Module *M,
1141 const ValueEnumerator &VE,
1142 BitstreamWriter &Stream) {
1143 const auto &MDs = VE.getMDs();
1144 if (MDs.empty() && M->named_metadata_empty())
1147 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
1149 unsigned MDSAbbrev = 0;
1150 if (VE.hasMDString()) {
1151 // Abbrev for METADATA_STRING.
1152 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1153 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING));
1154 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1155 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1156 MDSAbbrev = Stream.EmitAbbrev(Abbv);
1159 // Initialize MDNode abbreviations.
1160 #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
1161 #include "llvm/IR/Metadata.def"
1163 if (VE.hasMDLocation()) {
1164 // Abbrev for METADATA_LOCATION.
1166 // Assume the column is usually under 128, and always output the inlined-at
1167 // location (it's never more expensive than building an array size 1).
1168 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1169 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
1170 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1171 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1172 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1173 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1174 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1175 MDLocationAbbrev = Stream.EmitAbbrev(Abbv);
1178 if (VE.hasGenericDebugNode()) {
1179 // Abbrev for METADATA_GENERIC_DEBUG.
1181 // Assume the column is usually under 128, and always output the inlined-at
1182 // location (it's never more expensive than building an array size 1).
1183 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1184 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
1185 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1186 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1187 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1188 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1189 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1190 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1191 GenericDebugNodeAbbrev = Stream.EmitAbbrev(Abbv);
1194 unsigned NameAbbrev = 0;
1195 if (!M->named_metadata_empty()) {
1196 // Abbrev for METADATA_NAME.
1197 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1198 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
1199 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1200 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1201 NameAbbrev = Stream.EmitAbbrev(Abbv);
1204 SmallVector<uint64_t, 64> Record;
1205 for (const Metadata *MD : MDs) {
1206 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
1207 assert(N->isResolved() && "Expected forward references to be resolved");
1209 switch (N->getMetadataID()) {
1211 llvm_unreachable("Invalid MDNode subclass");
1212 #define HANDLE_MDNODE_LEAF(CLASS) \
1213 case Metadata::CLASS##Kind: \
1214 Write##CLASS(cast<CLASS>(N), VE, Stream, Record, CLASS##Abbrev); \
1216 #include "llvm/IR/Metadata.def"
1219 if (const auto *MDC = dyn_cast<ConstantAsMetadata>(MD)) {
1220 WriteValueAsMetadata(MDC, VE, Stream, Record);
1223 const MDString *MDS = cast<MDString>(MD);
1224 // Code: [strchar x N]
1225 Record.append(MDS->bytes_begin(), MDS->bytes_end());
1227 // Emit the finished record.
1228 Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev);
1232 // Write named metadata.
1233 for (const NamedMDNode &NMD : M->named_metadata()) {
1235 StringRef Str = NMD.getName();
1236 Record.append(Str.bytes_begin(), Str.bytes_end());
1237 Stream.EmitRecord(bitc::METADATA_NAME, Record, NameAbbrev);
1240 // Write named metadata operands.
1241 for (const MDNode *N : NMD.operands())
1242 Record.push_back(VE.getMetadataID(N));
1243 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
1250 static void WriteFunctionLocalMetadata(const Function &F,
1251 const ValueEnumerator &VE,
1252 BitstreamWriter &Stream) {
1253 bool StartedMetadataBlock = false;
1254 SmallVector<uint64_t, 64> Record;
1255 const SmallVectorImpl<const LocalAsMetadata *> &MDs =
1256 VE.getFunctionLocalMDs();
1257 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
1258 assert(MDs[i] && "Expected valid function-local metadata");
1259 if (!StartedMetadataBlock) {
1260 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
1261 StartedMetadataBlock = true;
1263 WriteValueAsMetadata(MDs[i], VE, Stream, Record);
1266 if (StartedMetadataBlock)
1270 static void WriteMetadataAttachment(const Function &F,
1271 const ValueEnumerator &VE,
1272 BitstreamWriter &Stream) {
1273 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
1275 SmallVector<uint64_t, 64> Record;
1277 // Write metadata attachments
1278 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
1279 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1281 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1282 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1285 I->getAllMetadataOtherThanDebugLoc(MDs);
1287 // If no metadata, ignore instruction.
1288 if (MDs.empty()) continue;
1290 Record.push_back(VE.getInstructionID(I));
1292 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
1293 Record.push_back(MDs[i].first);
1294 Record.push_back(VE.getMetadataID(MDs[i].second));
1296 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
1303 static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) {
1304 SmallVector<uint64_t, 64> Record;
1306 // Write metadata kinds
1307 // METADATA_KIND - [n x [id, name]]
1308 SmallVector<StringRef, 8> Names;
1309 M->getMDKindNames(Names);
1311 if (Names.empty()) return;
1313 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
1315 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
1316 Record.push_back(MDKindID);
1317 StringRef KName = Names[MDKindID];
1318 Record.append(KName.begin(), KName.end());
1320 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
1327 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
1328 if ((int64_t)V >= 0)
1329 Vals.push_back(V << 1);
1331 Vals.push_back((-V << 1) | 1);
1334 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
1335 const ValueEnumerator &VE,
1336 BitstreamWriter &Stream, bool isGlobal) {
1337 if (FirstVal == LastVal) return;
1339 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
1341 unsigned AggregateAbbrev = 0;
1342 unsigned String8Abbrev = 0;
1343 unsigned CString7Abbrev = 0;
1344 unsigned CString6Abbrev = 0;
1345 // If this is a constant pool for the module, emit module-specific abbrevs.
1347 // Abbrev for CST_CODE_AGGREGATE.
1348 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1349 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
1350 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1351 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
1352 AggregateAbbrev = Stream.EmitAbbrev(Abbv);
1354 // Abbrev for CST_CODE_STRING.
1355 Abbv = new BitCodeAbbrev();
1356 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
1357 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1358 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1359 String8Abbrev = Stream.EmitAbbrev(Abbv);
1360 // Abbrev for CST_CODE_CSTRING.
1361 Abbv = new BitCodeAbbrev();
1362 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
1363 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1364 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1365 CString7Abbrev = Stream.EmitAbbrev(Abbv);
1366 // Abbrev for CST_CODE_CSTRING.
1367 Abbv = new BitCodeAbbrev();
1368 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
1369 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1370 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1371 CString6Abbrev = Stream.EmitAbbrev(Abbv);
1374 SmallVector<uint64_t, 64> Record;
1376 const ValueEnumerator::ValueList &Vals = VE.getValues();
1377 Type *LastTy = nullptr;
1378 for (unsigned i = FirstVal; i != LastVal; ++i) {
1379 const Value *V = Vals[i].first;
1380 // If we need to switch types, do so now.
1381 if (V->getType() != LastTy) {
1382 LastTy = V->getType();
1383 Record.push_back(VE.getTypeID(LastTy));
1384 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
1385 CONSTANTS_SETTYPE_ABBREV);
1389 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1390 Record.push_back(unsigned(IA->hasSideEffects()) |
1391 unsigned(IA->isAlignStack()) << 1 |
1392 unsigned(IA->getDialect()&1) << 2);
1394 // Add the asm string.
1395 const std::string &AsmStr = IA->getAsmString();
1396 Record.push_back(AsmStr.size());
1397 Record.append(AsmStr.begin(), AsmStr.end());
1399 // Add the constraint string.
1400 const std::string &ConstraintStr = IA->getConstraintString();
1401 Record.push_back(ConstraintStr.size());
1402 Record.append(ConstraintStr.begin(), ConstraintStr.end());
1403 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
1407 const Constant *C = cast<Constant>(V);
1408 unsigned Code = -1U;
1409 unsigned AbbrevToUse = 0;
1410 if (C->isNullValue()) {
1411 Code = bitc::CST_CODE_NULL;
1412 } else if (isa<UndefValue>(C)) {
1413 Code = bitc::CST_CODE_UNDEF;
1414 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
1415 if (IV->getBitWidth() <= 64) {
1416 uint64_t V = IV->getSExtValue();
1417 emitSignedInt64(Record, V);
1418 Code = bitc::CST_CODE_INTEGER;
1419 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
1420 } else { // Wide integers, > 64 bits in size.
1421 // We have an arbitrary precision integer value to write whose
1422 // bit width is > 64. However, in canonical unsigned integer
1423 // format it is likely that the high bits are going to be zero.
1424 // So, we only write the number of active words.
1425 unsigned NWords = IV->getValue().getActiveWords();
1426 const uint64_t *RawWords = IV->getValue().getRawData();
1427 for (unsigned i = 0; i != NWords; ++i) {
1428 emitSignedInt64(Record, RawWords[i]);
1430 Code = bitc::CST_CODE_WIDE_INTEGER;
1432 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
1433 Code = bitc::CST_CODE_FLOAT;
1434 Type *Ty = CFP->getType();
1435 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
1436 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
1437 } else if (Ty->isX86_FP80Ty()) {
1438 // api needed to prevent premature destruction
1439 // bits are not in the same order as a normal i80 APInt, compensate.
1440 APInt api = CFP->getValueAPF().bitcastToAPInt();
1441 const uint64_t *p = api.getRawData();
1442 Record.push_back((p[1] << 48) | (p[0] >> 16));
1443 Record.push_back(p[0] & 0xffffLL);
1444 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
1445 APInt api = CFP->getValueAPF().bitcastToAPInt();
1446 const uint64_t *p = api.getRawData();
1447 Record.push_back(p[0]);
1448 Record.push_back(p[1]);
1450 assert (0 && "Unknown FP type!");
1452 } else if (isa<ConstantDataSequential>(C) &&
1453 cast<ConstantDataSequential>(C)->isString()) {
1454 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
1455 // Emit constant strings specially.
1456 unsigned NumElts = Str->getNumElements();
1457 // If this is a null-terminated string, use the denser CSTRING encoding.
1458 if (Str->isCString()) {
1459 Code = bitc::CST_CODE_CSTRING;
1460 --NumElts; // Don't encode the null, which isn't allowed by char6.
1462 Code = bitc::CST_CODE_STRING;
1463 AbbrevToUse = String8Abbrev;
1465 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
1466 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
1467 for (unsigned i = 0; i != NumElts; ++i) {
1468 unsigned char V = Str->getElementAsInteger(i);
1469 Record.push_back(V);
1470 isCStr7 &= (V & 128) == 0;
1472 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
1476 AbbrevToUse = CString6Abbrev;
1478 AbbrevToUse = CString7Abbrev;
1479 } else if (const ConstantDataSequential *CDS =
1480 dyn_cast<ConstantDataSequential>(C)) {
1481 Code = bitc::CST_CODE_DATA;
1482 Type *EltTy = CDS->getType()->getElementType();
1483 if (isa<IntegerType>(EltTy)) {
1484 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
1485 Record.push_back(CDS->getElementAsInteger(i));
1486 } else if (EltTy->isFloatTy()) {
1487 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1488 union { float F; uint32_t I; };
1489 F = CDS->getElementAsFloat(i);
1490 Record.push_back(I);
1493 assert(EltTy->isDoubleTy() && "Unknown ConstantData element type");
1494 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1495 union { double F; uint64_t I; };
1496 F = CDS->getElementAsDouble(i);
1497 Record.push_back(I);
1500 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
1501 isa<ConstantVector>(C)) {
1502 Code = bitc::CST_CODE_AGGREGATE;
1503 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
1504 Record.push_back(VE.getValueID(C->getOperand(i)));
1505 AbbrevToUse = AggregateAbbrev;
1506 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1507 switch (CE->getOpcode()) {
1509 if (Instruction::isCast(CE->getOpcode())) {
1510 Code = bitc::CST_CODE_CE_CAST;
1511 Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
1512 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1513 Record.push_back(VE.getValueID(C->getOperand(0)));
1514 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
1516 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
1517 Code = bitc::CST_CODE_CE_BINOP;
1518 Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
1519 Record.push_back(VE.getValueID(C->getOperand(0)));
1520 Record.push_back(VE.getValueID(C->getOperand(1)));
1521 uint64_t Flags = GetOptimizationFlags(CE);
1523 Record.push_back(Flags);
1526 case Instruction::GetElementPtr: {
1527 Code = bitc::CST_CODE_CE_GEP;
1528 const auto *GO = cast<GEPOperator>(C);
1529 if (GO->isInBounds())
1530 Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
1531 Record.push_back(VE.getTypeID(GO->getSourceElementType()));
1532 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
1533 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
1534 Record.push_back(VE.getValueID(C->getOperand(i)));
1538 case Instruction::Select:
1539 Code = bitc::CST_CODE_CE_SELECT;
1540 Record.push_back(VE.getValueID(C->getOperand(0)));
1541 Record.push_back(VE.getValueID(C->getOperand(1)));
1542 Record.push_back(VE.getValueID(C->getOperand(2)));
1544 case Instruction::ExtractElement:
1545 Code = bitc::CST_CODE_CE_EXTRACTELT;
1546 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1547 Record.push_back(VE.getValueID(C->getOperand(0)));
1548 Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
1549 Record.push_back(VE.getValueID(C->getOperand(1)));
1551 case Instruction::InsertElement:
1552 Code = bitc::CST_CODE_CE_INSERTELT;
1553 Record.push_back(VE.getValueID(C->getOperand(0)));
1554 Record.push_back(VE.getValueID(C->getOperand(1)));
1555 Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
1556 Record.push_back(VE.getValueID(C->getOperand(2)));
1558 case Instruction::ShuffleVector:
1559 // If the return type and argument types are the same, this is a
1560 // standard shufflevector instruction. If the types are different,
1561 // then the shuffle is widening or truncating the input vectors, and
1562 // the argument type must also be encoded.
1563 if (C->getType() == C->getOperand(0)->getType()) {
1564 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
1566 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
1567 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1569 Record.push_back(VE.getValueID(C->getOperand(0)));
1570 Record.push_back(VE.getValueID(C->getOperand(1)));
1571 Record.push_back(VE.getValueID(C->getOperand(2)));
1573 case Instruction::ICmp:
1574 case Instruction::FCmp:
1575 Code = bitc::CST_CODE_CE_CMP;
1576 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1577 Record.push_back(VE.getValueID(C->getOperand(0)));
1578 Record.push_back(VE.getValueID(C->getOperand(1)));
1579 Record.push_back(CE->getPredicate());
1582 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
1583 Code = bitc::CST_CODE_BLOCKADDRESS;
1584 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
1585 Record.push_back(VE.getValueID(BA->getFunction()));
1586 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
1591 llvm_unreachable("Unknown constant!");
1593 Stream.EmitRecord(Code, Record, AbbrevToUse);
1600 static void WriteModuleConstants(const ValueEnumerator &VE,
1601 BitstreamWriter &Stream) {
1602 const ValueEnumerator::ValueList &Vals = VE.getValues();
1604 // Find the first constant to emit, which is the first non-globalvalue value.
1605 // We know globalvalues have been emitted by WriteModuleInfo.
1606 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1607 if (!isa<GlobalValue>(Vals[i].first)) {
1608 WriteConstants(i, Vals.size(), VE, Stream, true);
1614 /// PushValueAndType - The file has to encode both the value and type id for
1615 /// many values, because we need to know what type to create for forward
1616 /// references. However, most operands are not forward references, so this type
1617 /// field is not needed.
1619 /// This function adds V's value ID to Vals. If the value ID is higher than the
1620 /// instruction ID, then it is a forward reference, and it also includes the
1621 /// type ID. The value ID that is written is encoded relative to the InstID.
1622 static bool PushValueAndType(const Value *V, unsigned InstID,
1623 SmallVectorImpl<unsigned> &Vals,
1624 ValueEnumerator &VE) {
1625 unsigned ValID = VE.getValueID(V);
1626 // Make encoding relative to the InstID.
1627 Vals.push_back(InstID - ValID);
1628 if (ValID >= InstID) {
1629 Vals.push_back(VE.getTypeID(V->getType()));
1635 /// pushValue - Like PushValueAndType, but where the type of the value is
1636 /// omitted (perhaps it was already encoded in an earlier operand).
1637 static void pushValue(const Value *V, unsigned InstID,
1638 SmallVectorImpl<unsigned> &Vals,
1639 ValueEnumerator &VE) {
1640 unsigned ValID = VE.getValueID(V);
1641 Vals.push_back(InstID - ValID);
1644 static void pushValueSigned(const Value *V, unsigned InstID,
1645 SmallVectorImpl<uint64_t> &Vals,
1646 ValueEnumerator &VE) {
1647 unsigned ValID = VE.getValueID(V);
1648 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
1649 emitSignedInt64(Vals, diff);
1652 /// WriteInstruction - Emit an instruction to the specified stream.
1653 static void WriteInstruction(const Instruction &I, unsigned InstID,
1654 ValueEnumerator &VE, BitstreamWriter &Stream,
1655 SmallVectorImpl<unsigned> &Vals) {
1657 unsigned AbbrevToUse = 0;
1658 VE.setInstructionID(&I);
1659 switch (I.getOpcode()) {
1661 if (Instruction::isCast(I.getOpcode())) {
1662 Code = bitc::FUNC_CODE_INST_CAST;
1663 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1664 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
1665 Vals.push_back(VE.getTypeID(I.getType()));
1666 Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
1668 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
1669 Code = bitc::FUNC_CODE_INST_BINOP;
1670 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1671 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
1672 pushValue(I.getOperand(1), InstID, Vals, VE);
1673 Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
1674 uint64_t Flags = GetOptimizationFlags(&I);
1676 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
1677 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
1678 Vals.push_back(Flags);
1683 case Instruction::GetElementPtr: {
1684 Code = bitc::FUNC_CODE_INST_GEP;
1685 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
1686 auto &GEPInst = cast<GetElementPtrInst>(I);
1687 Vals.push_back(GEPInst.isInBounds());
1688 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
1689 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1690 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1693 case Instruction::ExtractValue: {
1694 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
1695 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1696 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
1697 Vals.append(EVI->idx_begin(), EVI->idx_end());
1700 case Instruction::InsertValue: {
1701 Code = bitc::FUNC_CODE_INST_INSERTVAL;
1702 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1703 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1704 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
1705 Vals.append(IVI->idx_begin(), IVI->idx_end());
1708 case Instruction::Select:
1709 Code = bitc::FUNC_CODE_INST_VSELECT;
1710 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1711 pushValue(I.getOperand(2), InstID, Vals, VE);
1712 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1714 case Instruction::ExtractElement:
1715 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
1716 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1717 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1719 case Instruction::InsertElement:
1720 Code = bitc::FUNC_CODE_INST_INSERTELT;
1721 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1722 pushValue(I.getOperand(1), InstID, Vals, VE);
1723 PushValueAndType(I.getOperand(2), InstID, Vals, VE);
1725 case Instruction::ShuffleVector:
1726 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
1727 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1728 pushValue(I.getOperand(1), InstID, Vals, VE);
1729 pushValue(I.getOperand(2), InstID, Vals, VE);
1731 case Instruction::ICmp:
1732 case Instruction::FCmp:
1733 // compare returning Int1Ty or vector of Int1Ty
1734 Code = bitc::FUNC_CODE_INST_CMP2;
1735 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1736 pushValue(I.getOperand(1), InstID, Vals, VE);
1737 Vals.push_back(cast<CmpInst>(I).getPredicate());
1740 case Instruction::Ret:
1742 Code = bitc::FUNC_CODE_INST_RET;
1743 unsigned NumOperands = I.getNumOperands();
1744 if (NumOperands == 0)
1745 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
1746 else if (NumOperands == 1) {
1747 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1748 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
1750 for (unsigned i = 0, e = NumOperands; i != e; ++i)
1751 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1755 case Instruction::Br:
1757 Code = bitc::FUNC_CODE_INST_BR;
1758 const BranchInst &II = cast<BranchInst>(I);
1759 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
1760 if (II.isConditional()) {
1761 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
1762 pushValue(II.getCondition(), InstID, Vals, VE);
1766 case Instruction::Switch:
1768 Code = bitc::FUNC_CODE_INST_SWITCH;
1769 const SwitchInst &SI = cast<SwitchInst>(I);
1770 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
1771 pushValue(SI.getCondition(), InstID, Vals, VE);
1772 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
1773 for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
1775 Vals.push_back(VE.getValueID(i.getCaseValue()));
1776 Vals.push_back(VE.getValueID(i.getCaseSuccessor()));
1780 case Instruction::IndirectBr:
1781 Code = bitc::FUNC_CODE_INST_INDIRECTBR;
1782 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1783 // Encode the address operand as relative, but not the basic blocks.
1784 pushValue(I.getOperand(0), InstID, Vals, VE);
1785 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
1786 Vals.push_back(VE.getValueID(I.getOperand(i)));
1789 case Instruction::Invoke: {
1790 const InvokeInst *II = cast<InvokeInst>(&I);
1791 const Value *Callee(II->getCalledValue());
1792 PointerType *PTy = cast<PointerType>(Callee->getType());
1793 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1794 Code = bitc::FUNC_CODE_INST_INVOKE;
1796 Vals.push_back(VE.getAttributeID(II->getAttributes()));
1797 Vals.push_back(II->getCallingConv());
1798 Vals.push_back(VE.getValueID(II->getNormalDest()));
1799 Vals.push_back(VE.getValueID(II->getUnwindDest()));
1800 PushValueAndType(Callee, InstID, Vals, VE);
1802 // Emit value #'s for the fixed parameters.
1803 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1804 pushValue(I.getOperand(i), InstID, Vals, VE); // fixed param.
1806 // Emit type/value pairs for varargs params.
1807 if (FTy->isVarArg()) {
1808 for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
1810 PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
1814 case Instruction::Resume:
1815 Code = bitc::FUNC_CODE_INST_RESUME;
1816 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1818 case Instruction::Unreachable:
1819 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
1820 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
1823 case Instruction::PHI: {
1824 const PHINode &PN = cast<PHINode>(I);
1825 Code = bitc::FUNC_CODE_INST_PHI;
1826 // With the newer instruction encoding, forward references could give
1827 // negative valued IDs. This is most common for PHIs, so we use
1829 SmallVector<uint64_t, 128> Vals64;
1830 Vals64.push_back(VE.getTypeID(PN.getType()));
1831 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1832 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64, VE);
1833 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
1835 // Emit a Vals64 vector and exit.
1836 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
1841 case Instruction::LandingPad: {
1842 const LandingPadInst &LP = cast<LandingPadInst>(I);
1843 Code = bitc::FUNC_CODE_INST_LANDINGPAD;
1844 Vals.push_back(VE.getTypeID(LP.getType()));
1845 PushValueAndType(LP.getPersonalityFn(), InstID, Vals, VE);
1846 Vals.push_back(LP.isCleanup());
1847 Vals.push_back(LP.getNumClauses());
1848 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
1850 Vals.push_back(LandingPadInst::Catch);
1852 Vals.push_back(LandingPadInst::Filter);
1853 PushValueAndType(LP.getClause(I), InstID, Vals, VE);
1858 case Instruction::Alloca: {
1859 Code = bitc::FUNC_CODE_INST_ALLOCA;
1860 Vals.push_back(VE.getTypeID(I.getType()));
1861 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1862 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
1863 const AllocaInst &AI = cast<AllocaInst>(I);
1864 unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
1865 assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
1866 "not enough bits for maximum alignment");
1867 assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
1868 AlignRecord |= AI.isUsedWithInAlloca() << 5;
1869 Vals.push_back(AlignRecord);
1873 case Instruction::Load:
1874 if (cast<LoadInst>(I).isAtomic()) {
1875 Code = bitc::FUNC_CODE_INST_LOADATOMIC;
1876 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1878 Code = bitc::FUNC_CODE_INST_LOAD;
1879 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) // ptr
1880 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
1882 Vals.push_back(VE.getTypeID(I.getType()));
1883 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
1884 Vals.push_back(cast<LoadInst>(I).isVolatile());
1885 if (cast<LoadInst>(I).isAtomic()) {
1886 Vals.push_back(GetEncodedOrdering(cast<LoadInst>(I).getOrdering()));
1887 Vals.push_back(GetEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
1890 case Instruction::Store:
1891 if (cast<StoreInst>(I).isAtomic())
1892 Code = bitc::FUNC_CODE_INST_STOREATOMIC;
1894 Code = bitc::FUNC_CODE_INST_STORE;
1895 PushValueAndType(I.getOperand(1), InstID, Vals, VE); // ptrty + ptr
1896 pushValue(I.getOperand(0), InstID, Vals, VE); // val.
1897 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
1898 Vals.push_back(cast<StoreInst>(I).isVolatile());
1899 if (cast<StoreInst>(I).isAtomic()) {
1900 Vals.push_back(GetEncodedOrdering(cast<StoreInst>(I).getOrdering()));
1901 Vals.push_back(GetEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
1904 case Instruction::AtomicCmpXchg:
1905 Code = bitc::FUNC_CODE_INST_CMPXCHG;
1906 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr
1907 pushValue(I.getOperand(1), InstID, Vals, VE); // cmp.
1908 pushValue(I.getOperand(2), InstID, Vals, VE); // newval.
1909 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
1910 Vals.push_back(GetEncodedOrdering(
1911 cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
1912 Vals.push_back(GetEncodedSynchScope(
1913 cast<AtomicCmpXchgInst>(I).getSynchScope()));
1914 Vals.push_back(GetEncodedOrdering(
1915 cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
1916 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
1918 case Instruction::AtomicRMW:
1919 Code = bitc::FUNC_CODE_INST_ATOMICRMW;
1920 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr
1921 pushValue(I.getOperand(1), InstID, Vals, VE); // val.
1922 Vals.push_back(GetEncodedRMWOperation(
1923 cast<AtomicRMWInst>(I).getOperation()));
1924 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
1925 Vals.push_back(GetEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
1926 Vals.push_back(GetEncodedSynchScope(
1927 cast<AtomicRMWInst>(I).getSynchScope()));
1929 case Instruction::Fence:
1930 Code = bitc::FUNC_CODE_INST_FENCE;
1931 Vals.push_back(GetEncodedOrdering(cast<FenceInst>(I).getOrdering()));
1932 Vals.push_back(GetEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
1934 case Instruction::Call: {
1935 const CallInst &CI = cast<CallInst>(I);
1936 PointerType *PTy = cast<PointerType>(CI.getCalledValue()->getType());
1937 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1939 Code = bitc::FUNC_CODE_INST_CALL;
1941 Vals.push_back(VE.getAttributeID(CI.getAttributes()));
1942 Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall()) |
1943 unsigned(CI.isMustTailCall()) << 14);
1944 PushValueAndType(CI.getCalledValue(), InstID, Vals, VE); // Callee
1946 // Emit value #'s for the fixed parameters.
1947 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
1948 // Check for labels (can happen with asm labels).
1949 if (FTy->getParamType(i)->isLabelTy())
1950 Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
1952 pushValue(CI.getArgOperand(i), InstID, Vals, VE); // fixed param.
1955 // Emit type/value pairs for varargs params.
1956 if (FTy->isVarArg()) {
1957 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
1959 PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE); // varargs
1963 case Instruction::VAArg:
1964 Code = bitc::FUNC_CODE_INST_VAARG;
1965 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
1966 pushValue(I.getOperand(0), InstID, Vals, VE); // valist.
1967 Vals.push_back(VE.getTypeID(I.getType())); // restype.
1971 Stream.EmitRecord(Code, Vals, AbbrevToUse);
1975 // Emit names for globals/functions etc.
1976 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
1977 const ValueEnumerator &VE,
1978 BitstreamWriter &Stream) {
1979 if (VST.empty()) return;
1980 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
1982 // FIXME: Set up the abbrev, we know how many values there are!
1983 // FIXME: We know if the type names can use 7-bit ascii.
1984 SmallVector<unsigned, 64> NameVals;
1986 for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
1989 const ValueName &Name = *SI;
1991 // Figure out the encoding to use for the name.
1993 bool isChar6 = true;
1994 for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
1997 isChar6 = BitCodeAbbrevOp::isChar6(*C);
1998 if ((unsigned char)*C & 128) {
2000 break; // don't bother scanning the rest.
2004 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
2006 // VST_ENTRY: [valueid, namechar x N]
2007 // VST_BBENTRY: [bbid, namechar x N]
2009 if (isa<BasicBlock>(SI->getValue())) {
2010 Code = bitc::VST_CODE_BBENTRY;
2012 AbbrevToUse = VST_BBENTRY_6_ABBREV;
2014 Code = bitc::VST_CODE_ENTRY;
2016 AbbrevToUse = VST_ENTRY_6_ABBREV;
2018 AbbrevToUse = VST_ENTRY_7_ABBREV;
2021 NameVals.push_back(VE.getValueID(SI->getValue()));
2022 for (const char *P = Name.getKeyData(),
2023 *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
2024 NameVals.push_back((unsigned char)*P);
2026 // Emit the finished record.
2027 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
2033 static void WriteUseList(ValueEnumerator &VE, UseListOrder &&Order,
2034 BitstreamWriter &Stream) {
2035 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
2037 if (isa<BasicBlock>(Order.V))
2038 Code = bitc::USELIST_CODE_BB;
2040 Code = bitc::USELIST_CODE_DEFAULT;
2042 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
2043 Record.push_back(VE.getValueID(Order.V));
2044 Stream.EmitRecord(Code, Record);
2047 static void WriteUseListBlock(const Function *F, ValueEnumerator &VE,
2048 BitstreamWriter &Stream) {
2049 assert(VE.shouldPreserveUseListOrder() &&
2050 "Expected to be preserving use-list order");
2052 auto hasMore = [&]() {
2053 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
2059 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
2061 WriteUseList(VE, std::move(VE.UseListOrders.back()), Stream);
2062 VE.UseListOrders.pop_back();
2067 /// WriteFunction - Emit a function body to the module stream.
2068 static void WriteFunction(const Function &F, ValueEnumerator &VE,
2069 BitstreamWriter &Stream) {
2070 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
2071 VE.incorporateFunction(F);
2073 SmallVector<unsigned, 64> Vals;
2075 // Emit the number of basic blocks, so the reader can create them ahead of
2077 Vals.push_back(VE.getBasicBlocks().size());
2078 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
2081 // If there are function-local constants, emit them now.
2082 unsigned CstStart, CstEnd;
2083 VE.getFunctionConstantRange(CstStart, CstEnd);
2084 WriteConstants(CstStart, CstEnd, VE, Stream, false);
2086 // If there is function-local metadata, emit it now.
2087 WriteFunctionLocalMetadata(F, VE, Stream);
2089 // Keep a running idea of what the instruction ID is.
2090 unsigned InstID = CstEnd;
2092 bool NeedsMetadataAttachment = false;
2094 MDLocation *LastDL = nullptr;
2096 // Finally, emit all the instructions, in order.
2097 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
2098 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
2100 WriteInstruction(*I, InstID, VE, Stream, Vals);
2102 if (!I->getType()->isVoidTy())
2105 // If the instruction has metadata, write a metadata attachment later.
2106 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
2108 // If the instruction has a debug location, emit it.
2109 MDLocation *DL = I->getDebugLoc();
2114 // Just repeat the same debug loc as last time.
2115 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
2119 Vals.push_back(DL->getLine());
2120 Vals.push_back(DL->getColumn());
2121 Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
2122 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
2123 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
2127 // Emit names for all the instructions etc.
2128 WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
2130 if (NeedsMetadataAttachment)
2131 WriteMetadataAttachment(F, VE, Stream);
2132 if (VE.shouldPreserveUseListOrder())
2133 WriteUseListBlock(&F, VE, Stream);
2138 // Emit blockinfo, which defines the standard abbreviations etc.
2139 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
2140 // We only want to emit block info records for blocks that have multiple
2141 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
2142 // Other blocks can define their abbrevs inline.
2143 Stream.EnterBlockInfoBlock(2);
2145 { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
2146 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2147 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
2148 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2149 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2150 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2151 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2152 Abbv) != VST_ENTRY_8_ABBREV)
2153 llvm_unreachable("Unexpected abbrev ordering!");
2156 { // 7-bit fixed width VST_ENTRY strings.
2157 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2158 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2159 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2160 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2161 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2162 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2163 Abbv) != VST_ENTRY_7_ABBREV)
2164 llvm_unreachable("Unexpected abbrev ordering!");
2166 { // 6-bit char6 VST_ENTRY strings.
2167 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2168 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2169 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2170 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2171 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2172 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2173 Abbv) != VST_ENTRY_6_ABBREV)
2174 llvm_unreachable("Unexpected abbrev ordering!");
2176 { // 6-bit char6 VST_BBENTRY strings.
2177 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2178 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
2179 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2180 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2181 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2182 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2183 Abbv) != VST_BBENTRY_6_ABBREV)
2184 llvm_unreachable("Unexpected abbrev ordering!");
2189 { // SETTYPE abbrev for CONSTANTS_BLOCK.
2190 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2191 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
2192 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
2193 VE.computeBitsRequiredForTypeIndicies()));
2194 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2195 Abbv) != CONSTANTS_SETTYPE_ABBREV)
2196 llvm_unreachable("Unexpected abbrev ordering!");
2199 { // INTEGER abbrev for CONSTANTS_BLOCK.
2200 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2201 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
2202 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2203 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2204 Abbv) != CONSTANTS_INTEGER_ABBREV)
2205 llvm_unreachable("Unexpected abbrev ordering!");
2208 { // CE_CAST abbrev for CONSTANTS_BLOCK.
2209 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2210 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
2211 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
2212 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
2213 VE.computeBitsRequiredForTypeIndicies()));
2214 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2216 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2217 Abbv) != CONSTANTS_CE_CAST_Abbrev)
2218 llvm_unreachable("Unexpected abbrev ordering!");
2220 { // NULL abbrev for CONSTANTS_BLOCK.
2221 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2222 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
2223 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2224 Abbv) != CONSTANTS_NULL_Abbrev)
2225 llvm_unreachable("Unexpected abbrev ordering!");
2228 // FIXME: This should only use space for first class types!
2230 { // INST_LOAD abbrev for FUNCTION_BLOCK.
2231 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2232 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
2233 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
2234 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
2235 VE.computeBitsRequiredForTypeIndicies()));
2236 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
2237 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
2238 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2239 Abbv) != FUNCTION_INST_LOAD_ABBREV)
2240 llvm_unreachable("Unexpected abbrev ordering!");
2242 { // INST_BINOP abbrev for FUNCTION_BLOCK.
2243 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2244 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
2245 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
2246 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
2247 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2248 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2249 Abbv) != FUNCTION_INST_BINOP_ABBREV)
2250 llvm_unreachable("Unexpected abbrev ordering!");
2252 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
2253 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2254 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
2255 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
2256 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
2257 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2258 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
2259 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2260 Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV)
2261 llvm_unreachable("Unexpected abbrev ordering!");
2263 { // INST_CAST abbrev for FUNCTION_BLOCK.
2264 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2265 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
2266 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
2267 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
2268 VE.computeBitsRequiredForTypeIndicies()));
2269 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2270 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2271 Abbv) != FUNCTION_INST_CAST_ABBREV)
2272 llvm_unreachable("Unexpected abbrev ordering!");
2275 { // INST_RET abbrev for FUNCTION_BLOCK.
2276 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2277 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
2278 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2279 Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
2280 llvm_unreachable("Unexpected abbrev ordering!");
2282 { // INST_RET abbrev for FUNCTION_BLOCK.
2283 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2284 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
2285 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
2286 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2287 Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
2288 llvm_unreachable("Unexpected abbrev ordering!");
2290 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
2291 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2292 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
2293 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2294 Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
2295 llvm_unreachable("Unexpected abbrev ordering!");
2298 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2299 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
2300 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
2301 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
2302 Log2_32_Ceil(VE.getTypes().size() + 1)));
2303 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2304 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2305 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
2306 FUNCTION_INST_GEP_ABBREV)
2307 llvm_unreachable("Unexpected abbrev ordering!");
2313 /// WriteModule - Emit the specified module to the bitstream.
2314 static void WriteModule(const Module *M, BitstreamWriter &Stream,
2315 bool ShouldPreserveUseListOrder) {
2316 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
2318 SmallVector<unsigned, 1> Vals;
2319 unsigned CurVersion = 1;
2320 Vals.push_back(CurVersion);
2321 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
2323 // Analyze the module, enumerating globals, functions, etc.
2324 ValueEnumerator VE(*M, ShouldPreserveUseListOrder);
2326 // Emit blockinfo, which defines the standard abbreviations etc.
2327 WriteBlockInfo(VE, Stream);
2329 // Emit information about attribute groups.
2330 WriteAttributeGroupTable(VE, Stream);
2332 // Emit information about parameter attributes.
2333 WriteAttributeTable(VE, Stream);
2335 // Emit information describing all of the types in the module.
2336 WriteTypeTable(VE, Stream);
2338 writeComdats(VE, Stream);
2340 // Emit top-level description of module, including target triple, inline asm,
2341 // descriptors for global variables, and function prototype info.
2342 WriteModuleInfo(M, VE, Stream);
2345 WriteModuleConstants(VE, Stream);
2348 WriteModuleMetadata(M, VE, Stream);
2351 WriteModuleMetadataStore(M, Stream);
2353 // Emit names for globals/functions etc.
2354 WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
2356 // Emit module-level use-lists.
2357 if (VE.shouldPreserveUseListOrder())
2358 WriteUseListBlock(nullptr, VE, Stream);
2360 // Emit function bodies.
2361 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F)
2362 if (!F->isDeclaration())
2363 WriteFunction(*F, VE, Stream);
2368 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
2369 /// header and trailer to make it compatible with the system archiver. To do
2370 /// this we emit the following header, and then emit a trailer that pads the
2371 /// file out to be a multiple of 16 bytes.
2373 /// struct bc_header {
2374 /// uint32_t Magic; // 0x0B17C0DE
2375 /// uint32_t Version; // Version, currently always 0.
2376 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
2377 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
2378 /// uint32_t CPUType; // CPU specifier.
2379 /// ... potentially more later ...
2382 DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
2383 DarwinBCHeaderSize = 5*4
2386 static void WriteInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
2387 uint32_t &Position) {
2388 Buffer[Position + 0] = (unsigned char) (Value >> 0);
2389 Buffer[Position + 1] = (unsigned char) (Value >> 8);
2390 Buffer[Position + 2] = (unsigned char) (Value >> 16);
2391 Buffer[Position + 3] = (unsigned char) (Value >> 24);
2395 static void EmitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
2397 unsigned CPUType = ~0U;
2399 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
2400 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
2401 // number from /usr/include/mach/machine.h. It is ok to reproduce the
2402 // specific constants here because they are implicitly part of the Darwin ABI.
2404 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
2405 DARWIN_CPU_TYPE_X86 = 7,
2406 DARWIN_CPU_TYPE_ARM = 12,
2407 DARWIN_CPU_TYPE_POWERPC = 18
2410 Triple::ArchType Arch = TT.getArch();
2411 if (Arch == Triple::x86_64)
2412 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
2413 else if (Arch == Triple::x86)
2414 CPUType = DARWIN_CPU_TYPE_X86;
2415 else if (Arch == Triple::ppc)
2416 CPUType = DARWIN_CPU_TYPE_POWERPC;
2417 else if (Arch == Triple::ppc64)
2418 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
2419 else if (Arch == Triple::arm || Arch == Triple::thumb)
2420 CPUType = DARWIN_CPU_TYPE_ARM;
2422 // Traditional Bitcode starts after header.
2423 assert(Buffer.size() >= DarwinBCHeaderSize &&
2424 "Expected header size to be reserved");
2425 unsigned BCOffset = DarwinBCHeaderSize;
2426 unsigned BCSize = Buffer.size()-DarwinBCHeaderSize;
2428 // Write the magic and version.
2429 unsigned Position = 0;
2430 WriteInt32ToBuffer(0x0B17C0DE , Buffer, Position);
2431 WriteInt32ToBuffer(0 , Buffer, Position); // Version.
2432 WriteInt32ToBuffer(BCOffset , Buffer, Position);
2433 WriteInt32ToBuffer(BCSize , Buffer, Position);
2434 WriteInt32ToBuffer(CPUType , Buffer, Position);
2436 // If the file is not a multiple of 16 bytes, insert dummy padding.
2437 while (Buffer.size() & 15)
2438 Buffer.push_back(0);
2441 /// WriteBitcodeToFile - Write the specified module to the specified output
2443 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out,
2444 bool ShouldPreserveUseListOrder) {
2445 SmallVector<char, 0> Buffer;
2446 Buffer.reserve(256*1024);
2448 // If this is darwin or another generic macho target, reserve space for the
2450 Triple TT(M->getTargetTriple());
2451 if (TT.isOSDarwin())
2452 Buffer.insert(Buffer.begin(), DarwinBCHeaderSize, 0);
2454 // Emit the module into the buffer.
2456 BitstreamWriter Stream(Buffer);
2458 // Emit the file header.
2459 Stream.Emit((unsigned)'B', 8);
2460 Stream.Emit((unsigned)'C', 8);
2461 Stream.Emit(0x0, 4);
2462 Stream.Emit(0xC, 4);
2463 Stream.Emit(0xE, 4);
2464 Stream.Emit(0xD, 4);
2467 WriteModule(M, Stream, ShouldPreserveUseListOrder);
2470 if (TT.isOSDarwin())
2471 EmitDarwinBCHeaderAndTrailer(Buffer, TT);
2473 // Write the generated bitstream to "Out".
2474 Out.write((char*)&Buffer.front(), Buffer.size());