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->getLo()));
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()));
896 Record.push_back(N->getRuntimeLang());
897 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
898 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams()));
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()));
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()));
944 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes()));
945 Record.push_back(VE.getMetadataOrNullID(N->getSubprograms()));
946 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables()));
947 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities()));
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->getFunction()));
974 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams()));
975 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
976 Record.push_back(VE.getMetadataOrNullID(N->getVariables()));
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->getVariable()));
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());
1088 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
1090 Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
1094 static void WriteMDExpression(const MDExpression *N, const ValueEnumerator &,
1095 BitstreamWriter &Stream,
1096 SmallVectorImpl<uint64_t> &Record,
1098 Record.reserve(N->getElements().size() + 1);
1100 Record.push_back(N->isDistinct());
1101 Record.append(N->elements_begin(), N->elements_end());
1103 Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
1107 static void WriteMDObjCProperty(const MDObjCProperty *N,
1108 const ValueEnumerator &VE,
1109 BitstreamWriter &Stream,
1110 SmallVectorImpl<uint64_t> &Record,
1112 Record.push_back(N->isDistinct());
1113 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1114 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1115 Record.push_back(N->getLine());
1116 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
1117 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
1118 Record.push_back(N->getAttributes());
1119 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1121 Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
1125 static void WriteMDImportedEntity(const MDImportedEntity *N,
1126 const ValueEnumerator &VE,
1127 BitstreamWriter &Stream,
1128 SmallVectorImpl<uint64_t> &Record,
1130 Record.push_back(N->isDistinct());
1131 Record.push_back(N->getTag());
1132 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1133 Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
1134 Record.push_back(N->getLine());
1135 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1137 Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
1141 static void WriteModuleMetadata(const Module *M,
1142 const ValueEnumerator &VE,
1143 BitstreamWriter &Stream) {
1144 const auto &MDs = VE.getMDs();
1145 if (MDs.empty() && M->named_metadata_empty())
1148 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
1150 unsigned MDSAbbrev = 0;
1151 if (VE.hasMDString()) {
1152 // Abbrev for METADATA_STRING.
1153 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1154 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING));
1155 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1156 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1157 MDSAbbrev = Stream.EmitAbbrev(Abbv);
1160 // Initialize MDNode abbreviations.
1161 #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
1162 #include "llvm/IR/Metadata.def"
1164 if (VE.hasMDLocation()) {
1165 // Abbrev for METADATA_LOCATION.
1167 // Assume the column is usually under 128, and always output the inlined-at
1168 // location (it's never more expensive than building an array size 1).
1169 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1170 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
1171 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1172 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1173 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1174 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1175 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1176 MDLocationAbbrev = Stream.EmitAbbrev(Abbv);
1179 if (VE.hasGenericDebugNode()) {
1180 // Abbrev for METADATA_GENERIC_DEBUG.
1182 // Assume the column is usually under 128, and always output the inlined-at
1183 // location (it's never more expensive than building an array size 1).
1184 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1185 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
1186 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1187 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1188 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1189 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1190 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1191 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1192 GenericDebugNodeAbbrev = Stream.EmitAbbrev(Abbv);
1195 unsigned NameAbbrev = 0;
1196 if (!M->named_metadata_empty()) {
1197 // Abbrev for METADATA_NAME.
1198 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1199 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
1200 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1201 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1202 NameAbbrev = Stream.EmitAbbrev(Abbv);
1205 SmallVector<uint64_t, 64> Record;
1206 for (const Metadata *MD : MDs) {
1207 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
1208 switch (N->getMetadataID()) {
1210 llvm_unreachable("Invalid MDNode subclass");
1211 #define HANDLE_MDNODE_LEAF(CLASS) \
1212 case Metadata::CLASS##Kind: \
1213 Write##CLASS(cast<CLASS>(N), VE, Stream, Record, CLASS##Abbrev); \
1215 #include "llvm/IR/Metadata.def"
1218 if (const auto *MDC = dyn_cast<ConstantAsMetadata>(MD)) {
1219 WriteValueAsMetadata(MDC, VE, Stream, Record);
1222 const MDString *MDS = cast<MDString>(MD);
1223 // Code: [strchar x N]
1224 Record.append(MDS->bytes_begin(), MDS->bytes_end());
1226 // Emit the finished record.
1227 Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev);
1231 // Write named metadata.
1232 for (const NamedMDNode &NMD : M->named_metadata()) {
1234 StringRef Str = NMD.getName();
1235 Record.append(Str.bytes_begin(), Str.bytes_end());
1236 Stream.EmitRecord(bitc::METADATA_NAME, Record, NameAbbrev);
1239 // Write named metadata operands.
1240 for (const MDNode *N : NMD.operands())
1241 Record.push_back(VE.getMetadataID(N));
1242 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
1249 static void WriteFunctionLocalMetadata(const Function &F,
1250 const ValueEnumerator &VE,
1251 BitstreamWriter &Stream) {
1252 bool StartedMetadataBlock = false;
1253 SmallVector<uint64_t, 64> Record;
1254 const SmallVectorImpl<const LocalAsMetadata *> &MDs =
1255 VE.getFunctionLocalMDs();
1256 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
1257 assert(MDs[i] && "Expected valid function-local metadata");
1258 if (!StartedMetadataBlock) {
1259 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
1260 StartedMetadataBlock = true;
1262 WriteValueAsMetadata(MDs[i], VE, Stream, Record);
1265 if (StartedMetadataBlock)
1269 static void WriteMetadataAttachment(const Function &F,
1270 const ValueEnumerator &VE,
1271 BitstreamWriter &Stream) {
1272 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
1274 SmallVector<uint64_t, 64> Record;
1276 // Write metadata attachments
1277 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
1278 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1280 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1281 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1284 I->getAllMetadataOtherThanDebugLoc(MDs);
1286 // If no metadata, ignore instruction.
1287 if (MDs.empty()) continue;
1289 Record.push_back(VE.getInstructionID(I));
1291 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
1292 Record.push_back(MDs[i].first);
1293 Record.push_back(VE.getMetadataID(MDs[i].second));
1295 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
1302 static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) {
1303 SmallVector<uint64_t, 64> Record;
1305 // Write metadata kinds
1306 // METADATA_KIND - [n x [id, name]]
1307 SmallVector<StringRef, 8> Names;
1308 M->getMDKindNames(Names);
1310 if (Names.empty()) return;
1312 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
1314 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
1315 Record.push_back(MDKindID);
1316 StringRef KName = Names[MDKindID];
1317 Record.append(KName.begin(), KName.end());
1319 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
1326 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
1327 if ((int64_t)V >= 0)
1328 Vals.push_back(V << 1);
1330 Vals.push_back((-V << 1) | 1);
1333 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
1334 const ValueEnumerator &VE,
1335 BitstreamWriter &Stream, bool isGlobal) {
1336 if (FirstVal == LastVal) return;
1338 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
1340 unsigned AggregateAbbrev = 0;
1341 unsigned String8Abbrev = 0;
1342 unsigned CString7Abbrev = 0;
1343 unsigned CString6Abbrev = 0;
1344 // If this is a constant pool for the module, emit module-specific abbrevs.
1346 // Abbrev for CST_CODE_AGGREGATE.
1347 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1348 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
1349 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1350 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
1351 AggregateAbbrev = Stream.EmitAbbrev(Abbv);
1353 // Abbrev for CST_CODE_STRING.
1354 Abbv = new BitCodeAbbrev();
1355 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
1356 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1357 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1358 String8Abbrev = Stream.EmitAbbrev(Abbv);
1359 // Abbrev for CST_CODE_CSTRING.
1360 Abbv = new BitCodeAbbrev();
1361 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
1362 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1363 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1364 CString7Abbrev = Stream.EmitAbbrev(Abbv);
1365 // Abbrev for CST_CODE_CSTRING.
1366 Abbv = new BitCodeAbbrev();
1367 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
1368 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1369 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1370 CString6Abbrev = Stream.EmitAbbrev(Abbv);
1373 SmallVector<uint64_t, 64> Record;
1375 const ValueEnumerator::ValueList &Vals = VE.getValues();
1376 Type *LastTy = nullptr;
1377 for (unsigned i = FirstVal; i != LastVal; ++i) {
1378 const Value *V = Vals[i].first;
1379 // If we need to switch types, do so now.
1380 if (V->getType() != LastTy) {
1381 LastTy = V->getType();
1382 Record.push_back(VE.getTypeID(LastTy));
1383 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
1384 CONSTANTS_SETTYPE_ABBREV);
1388 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1389 Record.push_back(unsigned(IA->hasSideEffects()) |
1390 unsigned(IA->isAlignStack()) << 1 |
1391 unsigned(IA->getDialect()&1) << 2);
1393 // Add the asm string.
1394 const std::string &AsmStr = IA->getAsmString();
1395 Record.push_back(AsmStr.size());
1396 Record.append(AsmStr.begin(), AsmStr.end());
1398 // Add the constraint string.
1399 const std::string &ConstraintStr = IA->getConstraintString();
1400 Record.push_back(ConstraintStr.size());
1401 Record.append(ConstraintStr.begin(), ConstraintStr.end());
1402 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
1406 const Constant *C = cast<Constant>(V);
1407 unsigned Code = -1U;
1408 unsigned AbbrevToUse = 0;
1409 if (C->isNullValue()) {
1410 Code = bitc::CST_CODE_NULL;
1411 } else if (isa<UndefValue>(C)) {
1412 Code = bitc::CST_CODE_UNDEF;
1413 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
1414 if (IV->getBitWidth() <= 64) {
1415 uint64_t V = IV->getSExtValue();
1416 emitSignedInt64(Record, V);
1417 Code = bitc::CST_CODE_INTEGER;
1418 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
1419 } else { // Wide integers, > 64 bits in size.
1420 // We have an arbitrary precision integer value to write whose
1421 // bit width is > 64. However, in canonical unsigned integer
1422 // format it is likely that the high bits are going to be zero.
1423 // So, we only write the number of active words.
1424 unsigned NWords = IV->getValue().getActiveWords();
1425 const uint64_t *RawWords = IV->getValue().getRawData();
1426 for (unsigned i = 0; i != NWords; ++i) {
1427 emitSignedInt64(Record, RawWords[i]);
1429 Code = bitc::CST_CODE_WIDE_INTEGER;
1431 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
1432 Code = bitc::CST_CODE_FLOAT;
1433 Type *Ty = CFP->getType();
1434 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
1435 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
1436 } else if (Ty->isX86_FP80Ty()) {
1437 // api needed to prevent premature destruction
1438 // bits are not in the same order as a normal i80 APInt, compensate.
1439 APInt api = CFP->getValueAPF().bitcastToAPInt();
1440 const uint64_t *p = api.getRawData();
1441 Record.push_back((p[1] << 48) | (p[0] >> 16));
1442 Record.push_back(p[0] & 0xffffLL);
1443 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
1444 APInt api = CFP->getValueAPF().bitcastToAPInt();
1445 const uint64_t *p = api.getRawData();
1446 Record.push_back(p[0]);
1447 Record.push_back(p[1]);
1449 assert (0 && "Unknown FP type!");
1451 } else if (isa<ConstantDataSequential>(C) &&
1452 cast<ConstantDataSequential>(C)->isString()) {
1453 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
1454 // Emit constant strings specially.
1455 unsigned NumElts = Str->getNumElements();
1456 // If this is a null-terminated string, use the denser CSTRING encoding.
1457 if (Str->isCString()) {
1458 Code = bitc::CST_CODE_CSTRING;
1459 --NumElts; // Don't encode the null, which isn't allowed by char6.
1461 Code = bitc::CST_CODE_STRING;
1462 AbbrevToUse = String8Abbrev;
1464 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
1465 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
1466 for (unsigned i = 0; i != NumElts; ++i) {
1467 unsigned char V = Str->getElementAsInteger(i);
1468 Record.push_back(V);
1469 isCStr7 &= (V & 128) == 0;
1471 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
1475 AbbrevToUse = CString6Abbrev;
1477 AbbrevToUse = CString7Abbrev;
1478 } else if (const ConstantDataSequential *CDS =
1479 dyn_cast<ConstantDataSequential>(C)) {
1480 Code = bitc::CST_CODE_DATA;
1481 Type *EltTy = CDS->getType()->getElementType();
1482 if (isa<IntegerType>(EltTy)) {
1483 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
1484 Record.push_back(CDS->getElementAsInteger(i));
1485 } else if (EltTy->isFloatTy()) {
1486 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1487 union { float F; uint32_t I; };
1488 F = CDS->getElementAsFloat(i);
1489 Record.push_back(I);
1492 assert(EltTy->isDoubleTy() && "Unknown ConstantData element type");
1493 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1494 union { double F; uint64_t I; };
1495 F = CDS->getElementAsDouble(i);
1496 Record.push_back(I);
1499 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
1500 isa<ConstantVector>(C)) {
1501 Code = bitc::CST_CODE_AGGREGATE;
1502 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
1503 Record.push_back(VE.getValueID(C->getOperand(i)));
1504 AbbrevToUse = AggregateAbbrev;
1505 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1506 switch (CE->getOpcode()) {
1508 if (Instruction::isCast(CE->getOpcode())) {
1509 Code = bitc::CST_CODE_CE_CAST;
1510 Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
1511 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1512 Record.push_back(VE.getValueID(C->getOperand(0)));
1513 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
1515 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
1516 Code = bitc::CST_CODE_CE_BINOP;
1517 Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
1518 Record.push_back(VE.getValueID(C->getOperand(0)));
1519 Record.push_back(VE.getValueID(C->getOperand(1)));
1520 uint64_t Flags = GetOptimizationFlags(CE);
1522 Record.push_back(Flags);
1525 case Instruction::GetElementPtr:
1526 Code = bitc::CST_CODE_CE_GEP;
1527 if (cast<GEPOperator>(C)->isInBounds())
1528 Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
1529 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
1530 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
1531 Record.push_back(VE.getValueID(C->getOperand(i)));
1534 case Instruction::Select:
1535 Code = bitc::CST_CODE_CE_SELECT;
1536 Record.push_back(VE.getValueID(C->getOperand(0)));
1537 Record.push_back(VE.getValueID(C->getOperand(1)));
1538 Record.push_back(VE.getValueID(C->getOperand(2)));
1540 case Instruction::ExtractElement:
1541 Code = bitc::CST_CODE_CE_EXTRACTELT;
1542 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1543 Record.push_back(VE.getValueID(C->getOperand(0)));
1544 Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
1545 Record.push_back(VE.getValueID(C->getOperand(1)));
1547 case Instruction::InsertElement:
1548 Code = bitc::CST_CODE_CE_INSERTELT;
1549 Record.push_back(VE.getValueID(C->getOperand(0)));
1550 Record.push_back(VE.getValueID(C->getOperand(1)));
1551 Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
1552 Record.push_back(VE.getValueID(C->getOperand(2)));
1554 case Instruction::ShuffleVector:
1555 // If the return type and argument types are the same, this is a
1556 // standard shufflevector instruction. If the types are different,
1557 // then the shuffle is widening or truncating the input vectors, and
1558 // the argument type must also be encoded.
1559 if (C->getType() == C->getOperand(0)->getType()) {
1560 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
1562 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
1563 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1565 Record.push_back(VE.getValueID(C->getOperand(0)));
1566 Record.push_back(VE.getValueID(C->getOperand(1)));
1567 Record.push_back(VE.getValueID(C->getOperand(2)));
1569 case Instruction::ICmp:
1570 case Instruction::FCmp:
1571 Code = bitc::CST_CODE_CE_CMP;
1572 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1573 Record.push_back(VE.getValueID(C->getOperand(0)));
1574 Record.push_back(VE.getValueID(C->getOperand(1)));
1575 Record.push_back(CE->getPredicate());
1578 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
1579 Code = bitc::CST_CODE_BLOCKADDRESS;
1580 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
1581 Record.push_back(VE.getValueID(BA->getFunction()));
1582 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
1587 llvm_unreachable("Unknown constant!");
1589 Stream.EmitRecord(Code, Record, AbbrevToUse);
1596 static void WriteModuleConstants(const ValueEnumerator &VE,
1597 BitstreamWriter &Stream) {
1598 const ValueEnumerator::ValueList &Vals = VE.getValues();
1600 // Find the first constant to emit, which is the first non-globalvalue value.
1601 // We know globalvalues have been emitted by WriteModuleInfo.
1602 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1603 if (!isa<GlobalValue>(Vals[i].first)) {
1604 WriteConstants(i, Vals.size(), VE, Stream, true);
1610 /// PushValueAndType - The file has to encode both the value and type id for
1611 /// many values, because we need to know what type to create for forward
1612 /// references. However, most operands are not forward references, so this type
1613 /// field is not needed.
1615 /// This function adds V's value ID to Vals. If the value ID is higher than the
1616 /// instruction ID, then it is a forward reference, and it also includes the
1617 /// type ID. The value ID that is written is encoded relative to the InstID.
1618 static bool PushValueAndType(const Value *V, unsigned InstID,
1619 SmallVectorImpl<unsigned> &Vals,
1620 ValueEnumerator &VE) {
1621 unsigned ValID = VE.getValueID(V);
1622 // Make encoding relative to the InstID.
1623 Vals.push_back(InstID - ValID);
1624 if (ValID >= InstID) {
1625 Vals.push_back(VE.getTypeID(V->getType()));
1631 /// pushValue - Like PushValueAndType, but where the type of the value is
1632 /// omitted (perhaps it was already encoded in an earlier operand).
1633 static void pushValue(const Value *V, unsigned InstID,
1634 SmallVectorImpl<unsigned> &Vals,
1635 ValueEnumerator &VE) {
1636 unsigned ValID = VE.getValueID(V);
1637 Vals.push_back(InstID - ValID);
1640 static void pushValueSigned(const Value *V, unsigned InstID,
1641 SmallVectorImpl<uint64_t> &Vals,
1642 ValueEnumerator &VE) {
1643 unsigned ValID = VE.getValueID(V);
1644 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
1645 emitSignedInt64(Vals, diff);
1648 /// WriteInstruction - Emit an instruction to the specified stream.
1649 static void WriteInstruction(const Instruction &I, unsigned InstID,
1650 ValueEnumerator &VE, BitstreamWriter &Stream,
1651 SmallVectorImpl<unsigned> &Vals) {
1653 unsigned AbbrevToUse = 0;
1654 VE.setInstructionID(&I);
1655 switch (I.getOpcode()) {
1657 if (Instruction::isCast(I.getOpcode())) {
1658 Code = bitc::FUNC_CODE_INST_CAST;
1659 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1660 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
1661 Vals.push_back(VE.getTypeID(I.getType()));
1662 Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
1664 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
1665 Code = bitc::FUNC_CODE_INST_BINOP;
1666 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1667 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
1668 pushValue(I.getOperand(1), InstID, Vals, VE);
1669 Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
1670 uint64_t Flags = GetOptimizationFlags(&I);
1672 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
1673 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
1674 Vals.push_back(Flags);
1679 case Instruction::GetElementPtr: {
1680 Code = bitc::FUNC_CODE_INST_GEP;
1681 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
1682 auto &GEPInst = cast<GetElementPtrInst>(I);
1683 Vals.push_back(GEPInst.isInBounds());
1684 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
1685 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1686 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1689 case Instruction::ExtractValue: {
1690 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
1691 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1692 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
1693 Vals.append(EVI->idx_begin(), EVI->idx_end());
1696 case Instruction::InsertValue: {
1697 Code = bitc::FUNC_CODE_INST_INSERTVAL;
1698 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1699 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1700 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
1701 Vals.append(IVI->idx_begin(), IVI->idx_end());
1704 case Instruction::Select:
1705 Code = bitc::FUNC_CODE_INST_VSELECT;
1706 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1707 pushValue(I.getOperand(2), InstID, Vals, VE);
1708 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1710 case Instruction::ExtractElement:
1711 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
1712 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1713 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1715 case Instruction::InsertElement:
1716 Code = bitc::FUNC_CODE_INST_INSERTELT;
1717 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1718 pushValue(I.getOperand(1), InstID, Vals, VE);
1719 PushValueAndType(I.getOperand(2), InstID, Vals, VE);
1721 case Instruction::ShuffleVector:
1722 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
1723 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1724 pushValue(I.getOperand(1), InstID, Vals, VE);
1725 pushValue(I.getOperand(2), InstID, Vals, VE);
1727 case Instruction::ICmp:
1728 case Instruction::FCmp:
1729 // compare returning Int1Ty or vector of Int1Ty
1730 Code = bitc::FUNC_CODE_INST_CMP2;
1731 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1732 pushValue(I.getOperand(1), InstID, Vals, VE);
1733 Vals.push_back(cast<CmpInst>(I).getPredicate());
1736 case Instruction::Ret:
1738 Code = bitc::FUNC_CODE_INST_RET;
1739 unsigned NumOperands = I.getNumOperands();
1740 if (NumOperands == 0)
1741 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
1742 else if (NumOperands == 1) {
1743 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1744 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
1746 for (unsigned i = 0, e = NumOperands; i != e; ++i)
1747 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1751 case Instruction::Br:
1753 Code = bitc::FUNC_CODE_INST_BR;
1754 const BranchInst &II = cast<BranchInst>(I);
1755 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
1756 if (II.isConditional()) {
1757 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
1758 pushValue(II.getCondition(), InstID, Vals, VE);
1762 case Instruction::Switch:
1764 Code = bitc::FUNC_CODE_INST_SWITCH;
1765 const SwitchInst &SI = cast<SwitchInst>(I);
1766 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
1767 pushValue(SI.getCondition(), InstID, Vals, VE);
1768 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
1769 for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
1771 Vals.push_back(VE.getValueID(i.getCaseValue()));
1772 Vals.push_back(VE.getValueID(i.getCaseSuccessor()));
1776 case Instruction::IndirectBr:
1777 Code = bitc::FUNC_CODE_INST_INDIRECTBR;
1778 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1779 // Encode the address operand as relative, but not the basic blocks.
1780 pushValue(I.getOperand(0), InstID, Vals, VE);
1781 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
1782 Vals.push_back(VE.getValueID(I.getOperand(i)));
1785 case Instruction::Invoke: {
1786 const InvokeInst *II = cast<InvokeInst>(&I);
1787 const Value *Callee(II->getCalledValue());
1788 PointerType *PTy = cast<PointerType>(Callee->getType());
1789 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1790 Code = bitc::FUNC_CODE_INST_INVOKE;
1792 Vals.push_back(VE.getAttributeID(II->getAttributes()));
1793 Vals.push_back(II->getCallingConv());
1794 Vals.push_back(VE.getValueID(II->getNormalDest()));
1795 Vals.push_back(VE.getValueID(II->getUnwindDest()));
1796 PushValueAndType(Callee, InstID, Vals, VE);
1798 // Emit value #'s for the fixed parameters.
1799 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1800 pushValue(I.getOperand(i), InstID, Vals, VE); // fixed param.
1802 // Emit type/value pairs for varargs params.
1803 if (FTy->isVarArg()) {
1804 for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
1806 PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
1810 case Instruction::Resume:
1811 Code = bitc::FUNC_CODE_INST_RESUME;
1812 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1814 case Instruction::Unreachable:
1815 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
1816 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
1819 case Instruction::PHI: {
1820 const PHINode &PN = cast<PHINode>(I);
1821 Code = bitc::FUNC_CODE_INST_PHI;
1822 // With the newer instruction encoding, forward references could give
1823 // negative valued IDs. This is most common for PHIs, so we use
1825 SmallVector<uint64_t, 128> Vals64;
1826 Vals64.push_back(VE.getTypeID(PN.getType()));
1827 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1828 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64, VE);
1829 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
1831 // Emit a Vals64 vector and exit.
1832 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
1837 case Instruction::LandingPad: {
1838 const LandingPadInst &LP = cast<LandingPadInst>(I);
1839 Code = bitc::FUNC_CODE_INST_LANDINGPAD;
1840 Vals.push_back(VE.getTypeID(LP.getType()));
1841 PushValueAndType(LP.getPersonalityFn(), InstID, Vals, VE);
1842 Vals.push_back(LP.isCleanup());
1843 Vals.push_back(LP.getNumClauses());
1844 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
1846 Vals.push_back(LandingPadInst::Catch);
1848 Vals.push_back(LandingPadInst::Filter);
1849 PushValueAndType(LP.getClause(I), InstID, Vals, VE);
1854 case Instruction::Alloca: {
1855 Code = bitc::FUNC_CODE_INST_ALLOCA;
1856 Vals.push_back(VE.getTypeID(I.getType()));
1857 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1858 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
1859 const AllocaInst &AI = cast<AllocaInst>(I);
1860 unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
1861 assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
1862 "not enough bits for maximum alignment");
1863 assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
1864 AlignRecord |= AI.isUsedWithInAlloca() << 5;
1865 Vals.push_back(AlignRecord);
1869 case Instruction::Load:
1870 if (cast<LoadInst>(I).isAtomic()) {
1871 Code = bitc::FUNC_CODE_INST_LOADATOMIC;
1872 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1874 Code = bitc::FUNC_CODE_INST_LOAD;
1875 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) // ptr
1876 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
1878 Vals.push_back(VE.getTypeID(I.getType()));
1879 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
1880 Vals.push_back(cast<LoadInst>(I).isVolatile());
1881 if (cast<LoadInst>(I).isAtomic()) {
1882 Vals.push_back(GetEncodedOrdering(cast<LoadInst>(I).getOrdering()));
1883 Vals.push_back(GetEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
1886 case Instruction::Store:
1887 if (cast<StoreInst>(I).isAtomic())
1888 Code = bitc::FUNC_CODE_INST_STOREATOMIC;
1890 Code = bitc::FUNC_CODE_INST_STORE;
1891 PushValueAndType(I.getOperand(1), InstID, Vals, VE); // ptrty + ptr
1892 pushValue(I.getOperand(0), InstID, Vals, VE); // val.
1893 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
1894 Vals.push_back(cast<StoreInst>(I).isVolatile());
1895 if (cast<StoreInst>(I).isAtomic()) {
1896 Vals.push_back(GetEncodedOrdering(cast<StoreInst>(I).getOrdering()));
1897 Vals.push_back(GetEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
1900 case Instruction::AtomicCmpXchg:
1901 Code = bitc::FUNC_CODE_INST_CMPXCHG;
1902 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr
1903 pushValue(I.getOperand(1), InstID, Vals, VE); // cmp.
1904 pushValue(I.getOperand(2), InstID, Vals, VE); // newval.
1905 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
1906 Vals.push_back(GetEncodedOrdering(
1907 cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
1908 Vals.push_back(GetEncodedSynchScope(
1909 cast<AtomicCmpXchgInst>(I).getSynchScope()));
1910 Vals.push_back(GetEncodedOrdering(
1911 cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
1912 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
1914 case Instruction::AtomicRMW:
1915 Code = bitc::FUNC_CODE_INST_ATOMICRMW;
1916 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr
1917 pushValue(I.getOperand(1), InstID, Vals, VE); // val.
1918 Vals.push_back(GetEncodedRMWOperation(
1919 cast<AtomicRMWInst>(I).getOperation()));
1920 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
1921 Vals.push_back(GetEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
1922 Vals.push_back(GetEncodedSynchScope(
1923 cast<AtomicRMWInst>(I).getSynchScope()));
1925 case Instruction::Fence:
1926 Code = bitc::FUNC_CODE_INST_FENCE;
1927 Vals.push_back(GetEncodedOrdering(cast<FenceInst>(I).getOrdering()));
1928 Vals.push_back(GetEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
1930 case Instruction::Call: {
1931 const CallInst &CI = cast<CallInst>(I);
1932 PointerType *PTy = cast<PointerType>(CI.getCalledValue()->getType());
1933 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1935 Code = bitc::FUNC_CODE_INST_CALL;
1937 Vals.push_back(VE.getAttributeID(CI.getAttributes()));
1938 Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall()) |
1939 unsigned(CI.isMustTailCall()) << 14);
1940 PushValueAndType(CI.getCalledValue(), InstID, Vals, VE); // Callee
1942 // Emit value #'s for the fixed parameters.
1943 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
1944 // Check for labels (can happen with asm labels).
1945 if (FTy->getParamType(i)->isLabelTy())
1946 Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
1948 pushValue(CI.getArgOperand(i), InstID, Vals, VE); // fixed param.
1951 // Emit type/value pairs for varargs params.
1952 if (FTy->isVarArg()) {
1953 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
1955 PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE); // varargs
1959 case Instruction::VAArg:
1960 Code = bitc::FUNC_CODE_INST_VAARG;
1961 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
1962 pushValue(I.getOperand(0), InstID, Vals, VE); // valist.
1963 Vals.push_back(VE.getTypeID(I.getType())); // restype.
1967 Stream.EmitRecord(Code, Vals, AbbrevToUse);
1971 // Emit names for globals/functions etc.
1972 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
1973 const ValueEnumerator &VE,
1974 BitstreamWriter &Stream) {
1975 if (VST.empty()) return;
1976 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
1978 // FIXME: Set up the abbrev, we know how many values there are!
1979 // FIXME: We know if the type names can use 7-bit ascii.
1980 SmallVector<unsigned, 64> NameVals;
1982 for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
1985 const ValueName &Name = *SI;
1987 // Figure out the encoding to use for the name.
1989 bool isChar6 = true;
1990 for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
1993 isChar6 = BitCodeAbbrevOp::isChar6(*C);
1994 if ((unsigned char)*C & 128) {
1996 break; // don't bother scanning the rest.
2000 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
2002 // VST_ENTRY: [valueid, namechar x N]
2003 // VST_BBENTRY: [bbid, namechar x N]
2005 if (isa<BasicBlock>(SI->getValue())) {
2006 Code = bitc::VST_CODE_BBENTRY;
2008 AbbrevToUse = VST_BBENTRY_6_ABBREV;
2010 Code = bitc::VST_CODE_ENTRY;
2012 AbbrevToUse = VST_ENTRY_6_ABBREV;
2014 AbbrevToUse = VST_ENTRY_7_ABBREV;
2017 NameVals.push_back(VE.getValueID(SI->getValue()));
2018 for (const char *P = Name.getKeyData(),
2019 *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
2020 NameVals.push_back((unsigned char)*P);
2022 // Emit the finished record.
2023 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
2029 static void WriteUseList(ValueEnumerator &VE, UseListOrder &&Order,
2030 BitstreamWriter &Stream) {
2031 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
2033 if (isa<BasicBlock>(Order.V))
2034 Code = bitc::USELIST_CODE_BB;
2036 Code = bitc::USELIST_CODE_DEFAULT;
2038 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
2039 Record.push_back(VE.getValueID(Order.V));
2040 Stream.EmitRecord(Code, Record);
2043 static void WriteUseListBlock(const Function *F, ValueEnumerator &VE,
2044 BitstreamWriter &Stream) {
2045 auto hasMore = [&]() {
2046 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
2052 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
2054 WriteUseList(VE, std::move(VE.UseListOrders.back()), Stream);
2055 VE.UseListOrders.pop_back();
2060 /// WriteFunction - Emit a function body to the module stream.
2061 static void WriteFunction(const Function &F, ValueEnumerator &VE,
2062 BitstreamWriter &Stream) {
2063 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
2064 VE.incorporateFunction(F);
2066 SmallVector<unsigned, 64> Vals;
2068 // Emit the number of basic blocks, so the reader can create them ahead of
2070 Vals.push_back(VE.getBasicBlocks().size());
2071 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
2074 // If there are function-local constants, emit them now.
2075 unsigned CstStart, CstEnd;
2076 VE.getFunctionConstantRange(CstStart, CstEnd);
2077 WriteConstants(CstStart, CstEnd, VE, Stream, false);
2079 // If there is function-local metadata, emit it now.
2080 WriteFunctionLocalMetadata(F, VE, Stream);
2082 // Keep a running idea of what the instruction ID is.
2083 unsigned InstID = CstEnd;
2085 bool NeedsMetadataAttachment = false;
2089 // Finally, emit all the instructions, in order.
2090 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
2091 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
2093 WriteInstruction(*I, InstID, VE, Stream, Vals);
2095 if (!I->getType()->isVoidTy())
2098 // If the instruction has metadata, write a metadata attachment later.
2099 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
2101 // If the instruction has a debug location, emit it.
2102 DebugLoc DL = I->getDebugLoc();
2103 if (DL.isUnknown()) {
2105 } else if (DL == LastDL) {
2106 // Just repeat the same debug loc as last time.
2107 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
2110 DL.getScopeAndInlinedAt(Scope, IA, I->getContext());
2111 assert(Scope && "Expected valid scope");
2113 Vals.push_back(DL.getLine());
2114 Vals.push_back(DL.getCol());
2115 Vals.push_back(VE.getMetadataOrNullID(Scope));
2116 Vals.push_back(VE.getMetadataOrNullID(IA));
2117 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
2124 // Emit names for all the instructions etc.
2125 WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
2127 if (NeedsMetadataAttachment)
2128 WriteMetadataAttachment(F, VE, Stream);
2129 if (shouldPreserveBitcodeUseListOrder())
2130 WriteUseListBlock(&F, VE, Stream);
2135 // Emit blockinfo, which defines the standard abbreviations etc.
2136 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
2137 // We only want to emit block info records for blocks that have multiple
2138 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
2139 // Other blocks can define their abbrevs inline.
2140 Stream.EnterBlockInfoBlock(2);
2142 { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
2143 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2144 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
2145 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2146 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2147 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2148 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2149 Abbv) != VST_ENTRY_8_ABBREV)
2150 llvm_unreachable("Unexpected abbrev ordering!");
2153 { // 7-bit fixed width VST_ENTRY strings.
2154 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2155 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2156 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2157 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2158 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2159 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2160 Abbv) != VST_ENTRY_7_ABBREV)
2161 llvm_unreachable("Unexpected abbrev ordering!");
2163 { // 6-bit char6 VST_ENTRY strings.
2164 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2165 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2166 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2167 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2168 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2169 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2170 Abbv) != VST_ENTRY_6_ABBREV)
2171 llvm_unreachable("Unexpected abbrev ordering!");
2173 { // 6-bit char6 VST_BBENTRY strings.
2174 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2175 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
2176 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2177 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2178 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2179 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2180 Abbv) != VST_BBENTRY_6_ABBREV)
2181 llvm_unreachable("Unexpected abbrev ordering!");
2186 { // SETTYPE abbrev for CONSTANTS_BLOCK.
2187 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2188 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
2189 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
2190 VE.computeBitsRequiredForTypeIndicies()));
2191 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2192 Abbv) != CONSTANTS_SETTYPE_ABBREV)
2193 llvm_unreachable("Unexpected abbrev ordering!");
2196 { // INTEGER abbrev for CONSTANTS_BLOCK.
2197 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2198 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
2199 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2200 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2201 Abbv) != CONSTANTS_INTEGER_ABBREV)
2202 llvm_unreachable("Unexpected abbrev ordering!");
2205 { // CE_CAST abbrev for CONSTANTS_BLOCK.
2206 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2207 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
2208 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
2209 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
2210 VE.computeBitsRequiredForTypeIndicies()));
2211 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2213 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2214 Abbv) != CONSTANTS_CE_CAST_Abbrev)
2215 llvm_unreachable("Unexpected abbrev ordering!");
2217 { // NULL abbrev for CONSTANTS_BLOCK.
2218 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2219 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
2220 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2221 Abbv) != CONSTANTS_NULL_Abbrev)
2222 llvm_unreachable("Unexpected abbrev ordering!");
2225 // FIXME: This should only use space for first class types!
2227 { // INST_LOAD abbrev for FUNCTION_BLOCK.
2228 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2229 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
2230 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
2231 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
2232 VE.computeBitsRequiredForTypeIndicies()));
2233 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
2234 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
2235 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2236 Abbv) != FUNCTION_INST_LOAD_ABBREV)
2237 llvm_unreachable("Unexpected abbrev ordering!");
2239 { // INST_BINOP abbrev for FUNCTION_BLOCK.
2240 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2241 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
2242 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
2243 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
2244 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2245 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2246 Abbv) != FUNCTION_INST_BINOP_ABBREV)
2247 llvm_unreachable("Unexpected abbrev ordering!");
2249 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
2250 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2251 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
2252 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
2253 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
2254 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2255 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
2256 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2257 Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV)
2258 llvm_unreachable("Unexpected abbrev ordering!");
2260 { // INST_CAST abbrev for FUNCTION_BLOCK.
2261 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2262 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
2263 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
2264 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
2265 VE.computeBitsRequiredForTypeIndicies()));
2266 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2267 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2268 Abbv) != FUNCTION_INST_CAST_ABBREV)
2269 llvm_unreachable("Unexpected abbrev ordering!");
2272 { // INST_RET abbrev for FUNCTION_BLOCK.
2273 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2274 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
2275 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2276 Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
2277 llvm_unreachable("Unexpected abbrev ordering!");
2279 { // INST_RET abbrev for FUNCTION_BLOCK.
2280 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2281 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
2282 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
2283 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2284 Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
2285 llvm_unreachable("Unexpected abbrev ordering!");
2287 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
2288 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2289 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
2290 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2291 Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
2292 llvm_unreachable("Unexpected abbrev ordering!");
2295 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2296 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
2297 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
2298 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
2299 Log2_32_Ceil(VE.getTypes().size() + 1)));
2300 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2301 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2302 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
2303 FUNCTION_INST_GEP_ABBREV)
2304 llvm_unreachable("Unexpected abbrev ordering!");
2310 /// WriteModule - Emit the specified module to the bitstream.
2311 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
2312 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
2314 SmallVector<unsigned, 1> Vals;
2315 unsigned CurVersion = 1;
2316 Vals.push_back(CurVersion);
2317 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
2319 // Analyze the module, enumerating globals, functions, etc.
2320 ValueEnumerator VE(*M);
2322 // Emit blockinfo, which defines the standard abbreviations etc.
2323 WriteBlockInfo(VE, Stream);
2325 // Emit information about attribute groups.
2326 WriteAttributeGroupTable(VE, Stream);
2328 // Emit information about parameter attributes.
2329 WriteAttributeTable(VE, Stream);
2331 // Emit information describing all of the types in the module.
2332 WriteTypeTable(VE, Stream);
2334 writeComdats(VE, Stream);
2336 // Emit top-level description of module, including target triple, inline asm,
2337 // descriptors for global variables, and function prototype info.
2338 WriteModuleInfo(M, VE, Stream);
2341 WriteModuleConstants(VE, Stream);
2344 WriteModuleMetadata(M, VE, Stream);
2347 WriteModuleMetadataStore(M, Stream);
2349 // Emit names for globals/functions etc.
2350 WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
2352 // Emit module-level use-lists.
2353 if (shouldPreserveBitcodeUseListOrder())
2354 WriteUseListBlock(nullptr, VE, Stream);
2356 // Emit function bodies.
2357 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F)
2358 if (!F->isDeclaration())
2359 WriteFunction(*F, VE, Stream);
2364 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
2365 /// header and trailer to make it compatible with the system archiver. To do
2366 /// this we emit the following header, and then emit a trailer that pads the
2367 /// file out to be a multiple of 16 bytes.
2369 /// struct bc_header {
2370 /// uint32_t Magic; // 0x0B17C0DE
2371 /// uint32_t Version; // Version, currently always 0.
2372 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
2373 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
2374 /// uint32_t CPUType; // CPU specifier.
2375 /// ... potentially more later ...
2378 DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
2379 DarwinBCHeaderSize = 5*4
2382 static void WriteInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
2383 uint32_t &Position) {
2384 Buffer[Position + 0] = (unsigned char) (Value >> 0);
2385 Buffer[Position + 1] = (unsigned char) (Value >> 8);
2386 Buffer[Position + 2] = (unsigned char) (Value >> 16);
2387 Buffer[Position + 3] = (unsigned char) (Value >> 24);
2391 static void EmitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
2393 unsigned CPUType = ~0U;
2395 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
2396 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
2397 // number from /usr/include/mach/machine.h. It is ok to reproduce the
2398 // specific constants here because they are implicitly part of the Darwin ABI.
2400 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
2401 DARWIN_CPU_TYPE_X86 = 7,
2402 DARWIN_CPU_TYPE_ARM = 12,
2403 DARWIN_CPU_TYPE_POWERPC = 18
2406 Triple::ArchType Arch = TT.getArch();
2407 if (Arch == Triple::x86_64)
2408 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
2409 else if (Arch == Triple::x86)
2410 CPUType = DARWIN_CPU_TYPE_X86;
2411 else if (Arch == Triple::ppc)
2412 CPUType = DARWIN_CPU_TYPE_POWERPC;
2413 else if (Arch == Triple::ppc64)
2414 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
2415 else if (Arch == Triple::arm || Arch == Triple::thumb)
2416 CPUType = DARWIN_CPU_TYPE_ARM;
2418 // Traditional Bitcode starts after header.
2419 assert(Buffer.size() >= DarwinBCHeaderSize &&
2420 "Expected header size to be reserved");
2421 unsigned BCOffset = DarwinBCHeaderSize;
2422 unsigned BCSize = Buffer.size()-DarwinBCHeaderSize;
2424 // Write the magic and version.
2425 unsigned Position = 0;
2426 WriteInt32ToBuffer(0x0B17C0DE , Buffer, Position);
2427 WriteInt32ToBuffer(0 , Buffer, Position); // Version.
2428 WriteInt32ToBuffer(BCOffset , Buffer, Position);
2429 WriteInt32ToBuffer(BCSize , Buffer, Position);
2430 WriteInt32ToBuffer(CPUType , Buffer, Position);
2432 // If the file is not a multiple of 16 bytes, insert dummy padding.
2433 while (Buffer.size() & 15)
2434 Buffer.push_back(0);
2437 /// WriteBitcodeToFile - Write the specified module to the specified output
2439 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out) {
2440 SmallVector<char, 0> Buffer;
2441 Buffer.reserve(256*1024);
2443 // If this is darwin or another generic macho target, reserve space for the
2445 Triple TT(M->getTargetTriple());
2446 if (TT.isOSDarwin())
2447 Buffer.insert(Buffer.begin(), DarwinBCHeaderSize, 0);
2449 // Emit the module into the buffer.
2451 BitstreamWriter Stream(Buffer);
2453 // Emit the file header.
2454 Stream.Emit((unsigned)'B', 8);
2455 Stream.Emit((unsigned)'C', 8);
2456 Stream.Emit(0x0, 4);
2457 Stream.Emit(0xC, 4);
2458 Stream.Emit(0xE, 4);
2459 Stream.Emit(0xD, 4);
2462 WriteModule(M, Stream);
2465 if (TT.isOSDarwin())
2466 EmitDarwinBCHeaderAndTrailer(Buffer, TT);
2468 // Write the generated bitstream to "Out".
2469 Out.write((char*)&Buffer.front(), Buffer.size());