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::DereferenceableOrNull:
204 return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL;
205 case Attribute::NoRedZone:
206 return bitc::ATTR_KIND_NO_RED_ZONE;
207 case Attribute::NoReturn:
208 return bitc::ATTR_KIND_NO_RETURN;
209 case Attribute::NoUnwind:
210 return bitc::ATTR_KIND_NO_UNWIND;
211 case Attribute::OptimizeForSize:
212 return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
213 case Attribute::OptimizeNone:
214 return bitc::ATTR_KIND_OPTIMIZE_NONE;
215 case Attribute::ReadNone:
216 return bitc::ATTR_KIND_READ_NONE;
217 case Attribute::ReadOnly:
218 return bitc::ATTR_KIND_READ_ONLY;
219 case Attribute::Returned:
220 return bitc::ATTR_KIND_RETURNED;
221 case Attribute::ReturnsTwice:
222 return bitc::ATTR_KIND_RETURNS_TWICE;
223 case Attribute::SExt:
224 return bitc::ATTR_KIND_S_EXT;
225 case Attribute::StackAlignment:
226 return bitc::ATTR_KIND_STACK_ALIGNMENT;
227 case Attribute::StackProtect:
228 return bitc::ATTR_KIND_STACK_PROTECT;
229 case Attribute::StackProtectReq:
230 return bitc::ATTR_KIND_STACK_PROTECT_REQ;
231 case Attribute::StackProtectStrong:
232 return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
233 case Attribute::StructRet:
234 return bitc::ATTR_KIND_STRUCT_RET;
235 case Attribute::SanitizeAddress:
236 return bitc::ATTR_KIND_SANITIZE_ADDRESS;
237 case Attribute::SanitizeThread:
238 return bitc::ATTR_KIND_SANITIZE_THREAD;
239 case Attribute::SanitizeMemory:
240 return bitc::ATTR_KIND_SANITIZE_MEMORY;
241 case Attribute::UWTable:
242 return bitc::ATTR_KIND_UW_TABLE;
243 case Attribute::ZExt:
244 return bitc::ATTR_KIND_Z_EXT;
245 case Attribute::EndAttrKinds:
246 llvm_unreachable("Can not encode end-attribute kinds marker.");
247 case Attribute::None:
248 llvm_unreachable("Can not encode none-attribute.");
251 llvm_unreachable("Trying to encode unknown attribute");
254 static void WriteAttributeGroupTable(const ValueEnumerator &VE,
255 BitstreamWriter &Stream) {
256 const std::vector<AttributeSet> &AttrGrps = VE.getAttributeGroups();
257 if (AttrGrps.empty()) return;
259 Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
261 SmallVector<uint64_t, 64> Record;
262 for (unsigned i = 0, e = AttrGrps.size(); i != e; ++i) {
263 AttributeSet AS = AttrGrps[i];
264 for (unsigned i = 0, e = AS.getNumSlots(); i != e; ++i) {
265 AttributeSet A = AS.getSlotAttributes(i);
267 Record.push_back(VE.getAttributeGroupID(A));
268 Record.push_back(AS.getSlotIndex(i));
270 for (AttributeSet::iterator I = AS.begin(0), E = AS.end(0);
273 if (Attr.isEnumAttribute()) {
275 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
276 } else if (Attr.isIntAttribute()) {
278 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
279 Record.push_back(Attr.getValueAsInt());
281 StringRef Kind = Attr.getKindAsString();
282 StringRef Val = Attr.getValueAsString();
284 Record.push_back(Val.empty() ? 3 : 4);
285 Record.append(Kind.begin(), Kind.end());
288 Record.append(Val.begin(), Val.end());
294 Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
302 static void WriteAttributeTable(const ValueEnumerator &VE,
303 BitstreamWriter &Stream) {
304 const std::vector<AttributeSet> &Attrs = VE.getAttributes();
305 if (Attrs.empty()) return;
307 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
309 SmallVector<uint64_t, 64> Record;
310 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
311 const AttributeSet &A = Attrs[i];
312 for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i)
313 Record.push_back(VE.getAttributeGroupID(A.getSlotAttributes(i)));
315 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
322 /// WriteTypeTable - Write out the type table for a module.
323 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
324 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
326 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
327 SmallVector<uint64_t, 64> TypeVals;
329 uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies();
331 // Abbrev for TYPE_CODE_POINTER.
332 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
333 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
334 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
335 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
336 unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
338 // Abbrev for TYPE_CODE_FUNCTION.
339 Abbv = new BitCodeAbbrev();
340 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
341 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
342 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
343 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
345 unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
347 // Abbrev for TYPE_CODE_STRUCT_ANON.
348 Abbv = new BitCodeAbbrev();
349 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
350 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
351 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
352 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
354 unsigned StructAnonAbbrev = Stream.EmitAbbrev(Abbv);
356 // Abbrev for TYPE_CODE_STRUCT_NAME.
357 Abbv = new BitCodeAbbrev();
358 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
359 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
360 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
361 unsigned StructNameAbbrev = Stream.EmitAbbrev(Abbv);
363 // Abbrev for TYPE_CODE_STRUCT_NAMED.
364 Abbv = new BitCodeAbbrev();
365 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
366 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
367 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
368 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
370 unsigned StructNamedAbbrev = Stream.EmitAbbrev(Abbv);
372 // Abbrev for TYPE_CODE_ARRAY.
373 Abbv = new BitCodeAbbrev();
374 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
375 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
376 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
378 unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
380 // Emit an entry count so the reader can reserve space.
381 TypeVals.push_back(TypeList.size());
382 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
385 // Loop over all of the types, emitting each in turn.
386 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
387 Type *T = TypeList[i];
391 switch (T->getTypeID()) {
392 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
393 case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break;
394 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
395 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
396 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
397 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
398 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
399 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
400 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
401 case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break;
402 case Type::IntegerTyID:
404 Code = bitc::TYPE_CODE_INTEGER;
405 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
407 case Type::PointerTyID: {
408 PointerType *PTy = cast<PointerType>(T);
409 // POINTER: [pointee type, address space]
410 Code = bitc::TYPE_CODE_POINTER;
411 TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
412 unsigned AddressSpace = PTy->getAddressSpace();
413 TypeVals.push_back(AddressSpace);
414 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
417 case Type::FunctionTyID: {
418 FunctionType *FT = cast<FunctionType>(T);
419 // FUNCTION: [isvararg, retty, paramty x N]
420 Code = bitc::TYPE_CODE_FUNCTION;
421 TypeVals.push_back(FT->isVarArg());
422 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
423 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
424 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
425 AbbrevToUse = FunctionAbbrev;
428 case Type::StructTyID: {
429 StructType *ST = cast<StructType>(T);
430 // STRUCT: [ispacked, eltty x N]
431 TypeVals.push_back(ST->isPacked());
432 // Output all of the element types.
433 for (StructType::element_iterator I = ST->element_begin(),
434 E = ST->element_end(); I != E; ++I)
435 TypeVals.push_back(VE.getTypeID(*I));
437 if (ST->isLiteral()) {
438 Code = bitc::TYPE_CODE_STRUCT_ANON;
439 AbbrevToUse = StructAnonAbbrev;
441 if (ST->isOpaque()) {
442 Code = bitc::TYPE_CODE_OPAQUE;
444 Code = bitc::TYPE_CODE_STRUCT_NAMED;
445 AbbrevToUse = StructNamedAbbrev;
448 // Emit the name if it is present.
449 if (!ST->getName().empty())
450 WriteStringRecord(bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
451 StructNameAbbrev, Stream);
455 case Type::ArrayTyID: {
456 ArrayType *AT = cast<ArrayType>(T);
457 // ARRAY: [numelts, eltty]
458 Code = bitc::TYPE_CODE_ARRAY;
459 TypeVals.push_back(AT->getNumElements());
460 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
461 AbbrevToUse = ArrayAbbrev;
464 case Type::VectorTyID: {
465 VectorType *VT = cast<VectorType>(T);
466 // VECTOR [numelts, eltty]
467 Code = bitc::TYPE_CODE_VECTOR;
468 TypeVals.push_back(VT->getNumElements());
469 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
474 // Emit the finished record.
475 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
482 static unsigned getEncodedLinkage(const GlobalValue &GV) {
483 switch (GV.getLinkage()) {
484 case GlobalValue::ExternalLinkage:
486 case GlobalValue::WeakAnyLinkage:
488 case GlobalValue::AppendingLinkage:
490 case GlobalValue::InternalLinkage:
492 case GlobalValue::LinkOnceAnyLinkage:
494 case GlobalValue::ExternalWeakLinkage:
496 case GlobalValue::CommonLinkage:
498 case GlobalValue::PrivateLinkage:
500 case GlobalValue::WeakODRLinkage:
502 case GlobalValue::LinkOnceODRLinkage:
504 case GlobalValue::AvailableExternallyLinkage:
507 llvm_unreachable("Invalid linkage");
510 static unsigned getEncodedVisibility(const GlobalValue &GV) {
511 switch (GV.getVisibility()) {
512 case GlobalValue::DefaultVisibility: return 0;
513 case GlobalValue::HiddenVisibility: return 1;
514 case GlobalValue::ProtectedVisibility: return 2;
516 llvm_unreachable("Invalid visibility");
519 static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
520 switch (GV.getDLLStorageClass()) {
521 case GlobalValue::DefaultStorageClass: return 0;
522 case GlobalValue::DLLImportStorageClass: return 1;
523 case GlobalValue::DLLExportStorageClass: return 2;
525 llvm_unreachable("Invalid DLL storage class");
528 static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
529 switch (GV.getThreadLocalMode()) {
530 case GlobalVariable::NotThreadLocal: return 0;
531 case GlobalVariable::GeneralDynamicTLSModel: return 1;
532 case GlobalVariable::LocalDynamicTLSModel: return 2;
533 case GlobalVariable::InitialExecTLSModel: return 3;
534 case GlobalVariable::LocalExecTLSModel: return 4;
536 llvm_unreachable("Invalid TLS model");
539 static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
540 switch (C.getSelectionKind()) {
542 return bitc::COMDAT_SELECTION_KIND_ANY;
543 case Comdat::ExactMatch:
544 return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
545 case Comdat::Largest:
546 return bitc::COMDAT_SELECTION_KIND_LARGEST;
547 case Comdat::NoDuplicates:
548 return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
549 case Comdat::SameSize:
550 return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
552 llvm_unreachable("Invalid selection kind");
555 static void writeComdats(const ValueEnumerator &VE, BitstreamWriter &Stream) {
556 SmallVector<uint16_t, 64> Vals;
557 for (const Comdat *C : VE.getComdats()) {
558 // COMDAT: [selection_kind, name]
559 Vals.push_back(getEncodedComdatSelectionKind(*C));
560 size_t Size = C->getName().size();
561 assert(isUInt<16>(Size));
562 Vals.push_back(Size);
563 for (char Chr : C->getName())
564 Vals.push_back((unsigned char)Chr);
565 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
570 // Emit top-level description of module, including target triple, inline asm,
571 // descriptors for global variables, and function prototype info.
572 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
573 BitstreamWriter &Stream) {
574 // Emit various pieces of data attached to a module.
575 if (!M->getTargetTriple().empty())
576 WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
578 const std::string &DL = M->getDataLayoutStr();
580 WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/, Stream);
581 if (!M->getModuleInlineAsm().empty())
582 WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
585 // Emit information about sections and GC, computing how many there are. Also
586 // compute the maximum alignment value.
587 std::map<std::string, unsigned> SectionMap;
588 std::map<std::string, unsigned> GCMap;
589 unsigned MaxAlignment = 0;
590 unsigned MaxGlobalType = 0;
591 for (const GlobalValue &GV : M->globals()) {
592 MaxAlignment = std::max(MaxAlignment, GV.getAlignment());
593 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getType()));
594 if (GV.hasSection()) {
595 // Give section names unique ID's.
596 unsigned &Entry = SectionMap[GV.getSection()];
598 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
600 Entry = SectionMap.size();
604 for (const Function &F : *M) {
605 MaxAlignment = std::max(MaxAlignment, F.getAlignment());
606 if (F.hasSection()) {
607 // Give section names unique ID's.
608 unsigned &Entry = SectionMap[F.getSection()];
610 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
612 Entry = SectionMap.size();
616 // Same for GC names.
617 unsigned &Entry = GCMap[F.getGC()];
619 WriteStringRecord(bitc::MODULE_CODE_GCNAME, F.getGC(),
621 Entry = GCMap.size();
626 // Emit abbrev for globals, now that we know # sections and max alignment.
627 unsigned SimpleGVarAbbrev = 0;
628 if (!M->global_empty()) {
629 // Add an abbrev for common globals with no visibility or thread localness.
630 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
631 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
632 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
633 Log2_32_Ceil(MaxGlobalType+1)));
634 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Constant.
635 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
636 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
637 if (MaxAlignment == 0) // Alignment.
638 Abbv->Add(BitCodeAbbrevOp(0));
640 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
641 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
642 Log2_32_Ceil(MaxEncAlignment+1)));
644 if (SectionMap.empty()) // Section.
645 Abbv->Add(BitCodeAbbrevOp(0));
647 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
648 Log2_32_Ceil(SectionMap.size()+1)));
649 // Don't bother emitting vis + thread local.
650 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
653 // Emit the global variable information.
654 SmallVector<unsigned, 64> Vals;
655 for (const GlobalVariable &GV : M->globals()) {
656 unsigned AbbrevToUse = 0;
658 // GLOBALVAR: [type, isconst, initid,
659 // linkage, alignment, section, visibility, threadlocal,
660 // unnamed_addr, externally_initialized, dllstorageclass,
662 Vals.push_back(VE.getTypeID(GV.getType()));
663 Vals.push_back(GV.isConstant());
664 Vals.push_back(GV.isDeclaration() ? 0 :
665 (VE.getValueID(GV.getInitializer()) + 1));
666 Vals.push_back(getEncodedLinkage(GV));
667 Vals.push_back(Log2_32(GV.getAlignment())+1);
668 Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0);
669 if (GV.isThreadLocal() ||
670 GV.getVisibility() != GlobalValue::DefaultVisibility ||
671 GV.hasUnnamedAddr() || GV.isExternallyInitialized() ||
672 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
674 Vals.push_back(getEncodedVisibility(GV));
675 Vals.push_back(getEncodedThreadLocalMode(GV));
676 Vals.push_back(GV.hasUnnamedAddr());
677 Vals.push_back(GV.isExternallyInitialized());
678 Vals.push_back(getEncodedDLLStorageClass(GV));
679 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
681 AbbrevToUse = SimpleGVarAbbrev;
684 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
688 // Emit the function proto information.
689 for (const Function &F : *M) {
690 // FUNCTION: [type, callingconv, isproto, linkage, paramattrs, alignment,
691 // section, visibility, gc, unnamed_addr, prologuedata,
692 // dllstorageclass, comdat, prefixdata]
693 Vals.push_back(VE.getTypeID(F.getFunctionType()));
694 Vals.push_back(F.getCallingConv());
695 Vals.push_back(F.isDeclaration());
696 Vals.push_back(getEncodedLinkage(F));
697 Vals.push_back(VE.getAttributeID(F.getAttributes()));
698 Vals.push_back(Log2_32(F.getAlignment())+1);
699 Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0);
700 Vals.push_back(getEncodedVisibility(F));
701 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
702 Vals.push_back(F.hasUnnamedAddr());
703 Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
705 Vals.push_back(getEncodedDLLStorageClass(F));
706 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
707 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
710 unsigned AbbrevToUse = 0;
711 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
715 // Emit the alias information.
716 for (const GlobalAlias &A : M->aliases()) {
717 // ALIAS: [alias type, aliasee val#, linkage, visibility]
718 Vals.push_back(VE.getTypeID(A.getType()));
719 Vals.push_back(VE.getValueID(A.getAliasee()));
720 Vals.push_back(getEncodedLinkage(A));
721 Vals.push_back(getEncodedVisibility(A));
722 Vals.push_back(getEncodedDLLStorageClass(A));
723 Vals.push_back(getEncodedThreadLocalMode(A));
724 Vals.push_back(A.hasUnnamedAddr());
725 unsigned AbbrevToUse = 0;
726 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
731 static uint64_t GetOptimizationFlags(const Value *V) {
734 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
735 if (OBO->hasNoSignedWrap())
736 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
737 if (OBO->hasNoUnsignedWrap())
738 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
739 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
741 Flags |= 1 << bitc::PEO_EXACT;
742 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
743 if (FPMO->hasUnsafeAlgebra())
744 Flags |= FastMathFlags::UnsafeAlgebra;
745 if (FPMO->hasNoNaNs())
746 Flags |= FastMathFlags::NoNaNs;
747 if (FPMO->hasNoInfs())
748 Flags |= FastMathFlags::NoInfs;
749 if (FPMO->hasNoSignedZeros())
750 Flags |= FastMathFlags::NoSignedZeros;
751 if (FPMO->hasAllowReciprocal())
752 Flags |= FastMathFlags::AllowReciprocal;
758 static void WriteValueAsMetadata(const ValueAsMetadata *MD,
759 const ValueEnumerator &VE,
760 BitstreamWriter &Stream,
761 SmallVectorImpl<uint64_t> &Record) {
762 // Mimic an MDNode with a value as one operand.
763 Value *V = MD->getValue();
764 Record.push_back(VE.getTypeID(V->getType()));
765 Record.push_back(VE.getValueID(V));
766 Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
770 static void WriteMDTuple(const MDTuple *N, const ValueEnumerator &VE,
771 BitstreamWriter &Stream,
772 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
773 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
774 Metadata *MD = N->getOperand(i);
775 assert(!(MD && isa<LocalAsMetadata>(MD)) &&
776 "Unexpected function-local metadata");
777 Record.push_back(VE.getMetadataOrNullID(MD));
779 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
780 : bitc::METADATA_NODE,
785 static void WriteMDLocation(const MDLocation *N, const ValueEnumerator &VE,
786 BitstreamWriter &Stream,
787 SmallVectorImpl<uint64_t> &Record,
789 Record.push_back(N->isDistinct());
790 Record.push_back(N->getLine());
791 Record.push_back(N->getColumn());
792 Record.push_back(VE.getMetadataID(N->getScope()));
793 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
795 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
799 static void WriteGenericDebugNode(const GenericDebugNode *N,
800 const ValueEnumerator &VE,
801 BitstreamWriter &Stream,
802 SmallVectorImpl<uint64_t> &Record,
804 Record.push_back(N->isDistinct());
805 Record.push_back(N->getTag());
806 Record.push_back(0); // Per-tag version field; unused for now.
808 for (auto &I : N->operands())
809 Record.push_back(VE.getMetadataOrNullID(I));
811 Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
815 static uint64_t rotateSign(int64_t I) {
817 return I < 0 ? ~(U << 1) : U << 1;
820 static void WriteMDSubrange(const MDSubrange *N, const ValueEnumerator &,
821 BitstreamWriter &Stream,
822 SmallVectorImpl<uint64_t> &Record,
824 Record.push_back(N->isDistinct());
825 Record.push_back(N->getCount());
826 Record.push_back(rotateSign(N->getLowerBound()));
828 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
832 static void WriteMDEnumerator(const MDEnumerator *N, const ValueEnumerator &VE,
833 BitstreamWriter &Stream,
834 SmallVectorImpl<uint64_t> &Record,
836 Record.push_back(N->isDistinct());
837 Record.push_back(rotateSign(N->getValue()));
838 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
840 Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
844 static void WriteMDBasicType(const MDBasicType *N, const ValueEnumerator &VE,
845 BitstreamWriter &Stream,
846 SmallVectorImpl<uint64_t> &Record,
848 Record.push_back(N->isDistinct());
849 Record.push_back(N->getTag());
850 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
851 Record.push_back(N->getSizeInBits());
852 Record.push_back(N->getAlignInBits());
853 Record.push_back(N->getEncoding());
855 Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
859 static void WriteMDDerivedType(const MDDerivedType *N,
860 const ValueEnumerator &VE,
861 BitstreamWriter &Stream,
862 SmallVectorImpl<uint64_t> &Record,
864 Record.push_back(N->isDistinct());
865 Record.push_back(N->getTag());
866 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
867 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
868 Record.push_back(N->getLine());
869 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
870 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
871 Record.push_back(N->getSizeInBits());
872 Record.push_back(N->getAlignInBits());
873 Record.push_back(N->getOffsetInBits());
874 Record.push_back(N->getFlags());
875 Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
877 Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
881 static void WriteMDCompositeType(const MDCompositeType *N,
882 const ValueEnumerator &VE,
883 BitstreamWriter &Stream,
884 SmallVectorImpl<uint64_t> &Record,
886 Record.push_back(N->isDistinct());
887 Record.push_back(N->getTag());
888 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
889 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
890 Record.push_back(N->getLine());
891 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
892 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
893 Record.push_back(N->getSizeInBits());
894 Record.push_back(N->getAlignInBits());
895 Record.push_back(N->getOffsetInBits());
896 Record.push_back(N->getFlags());
897 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
898 Record.push_back(N->getRuntimeLang());
899 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
900 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
901 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
903 Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
907 static void WriteMDSubroutineType(const MDSubroutineType *N,
908 const ValueEnumerator &VE,
909 BitstreamWriter &Stream,
910 SmallVectorImpl<uint64_t> &Record,
912 Record.push_back(N->isDistinct());
913 Record.push_back(N->getFlags());
914 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
916 Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
920 static void WriteMDFile(const MDFile *N, const ValueEnumerator &VE,
921 BitstreamWriter &Stream,
922 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
923 Record.push_back(N->isDistinct());
924 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
925 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
927 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
931 static void WriteMDCompileUnit(const MDCompileUnit *N,
932 const ValueEnumerator &VE,
933 BitstreamWriter &Stream,
934 SmallVectorImpl<uint64_t> &Record,
936 Record.push_back(N->isDistinct());
937 Record.push_back(N->getSourceLanguage());
938 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
939 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
940 Record.push_back(N->isOptimized());
941 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
942 Record.push_back(N->getRuntimeVersion());
943 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
944 Record.push_back(N->getEmissionKind());
945 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
946 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
947 Record.push_back(VE.getMetadataOrNullID(N->getSubprograms().get()));
948 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
949 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
951 Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
955 static void WriteMDSubprogram(const MDSubprogram *N,
956 const ValueEnumerator &VE,
957 BitstreamWriter &Stream,
958 SmallVectorImpl<uint64_t> &Record,
960 Record.push_back(N->isDistinct());
961 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
962 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
963 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
964 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
965 Record.push_back(N->getLine());
966 Record.push_back(VE.getMetadataOrNullID(N->getType()));
967 Record.push_back(N->isLocalToUnit());
968 Record.push_back(N->isDefinition());
969 Record.push_back(N->getScopeLine());
970 Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
971 Record.push_back(N->getVirtuality());
972 Record.push_back(N->getVirtualIndex());
973 Record.push_back(N->getFlags());
974 Record.push_back(N->isOptimized());
975 Record.push_back(VE.getMetadataOrNullID(N->getRawFunction()));
976 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
977 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
978 Record.push_back(VE.getMetadataOrNullID(N->getVariables().get()));
980 Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
984 static void WriteMDLexicalBlock(const MDLexicalBlock *N,
985 const ValueEnumerator &VE,
986 BitstreamWriter &Stream,
987 SmallVectorImpl<uint64_t> &Record,
989 Record.push_back(N->isDistinct());
990 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
991 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
992 Record.push_back(N->getLine());
993 Record.push_back(N->getColumn());
995 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
999 static void WriteMDLexicalBlockFile(const MDLexicalBlockFile *N,
1000 const ValueEnumerator &VE,
1001 BitstreamWriter &Stream,
1002 SmallVectorImpl<uint64_t> &Record,
1004 Record.push_back(N->isDistinct());
1005 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1006 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1007 Record.push_back(N->getDiscriminator());
1009 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
1013 static void WriteMDNamespace(const MDNamespace *N, const ValueEnumerator &VE,
1014 BitstreamWriter &Stream,
1015 SmallVectorImpl<uint64_t> &Record,
1017 Record.push_back(N->isDistinct());
1018 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1019 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1020 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1021 Record.push_back(N->getLine());
1023 Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
1027 static void WriteMDTemplateTypeParameter(const MDTemplateTypeParameter *N,
1028 const ValueEnumerator &VE,
1029 BitstreamWriter &Stream,
1030 SmallVectorImpl<uint64_t> &Record,
1032 Record.push_back(N->isDistinct());
1033 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1034 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1036 Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
1040 static void WriteMDTemplateValueParameter(const MDTemplateValueParameter *N,
1041 const ValueEnumerator &VE,
1042 BitstreamWriter &Stream,
1043 SmallVectorImpl<uint64_t> &Record,
1045 Record.push_back(N->isDistinct());
1046 Record.push_back(N->getTag());
1047 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1048 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1049 Record.push_back(VE.getMetadataOrNullID(N->getValue()));
1051 Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
1055 static void WriteMDGlobalVariable(const MDGlobalVariable *N,
1056 const ValueEnumerator &VE,
1057 BitstreamWriter &Stream,
1058 SmallVectorImpl<uint64_t> &Record,
1060 Record.push_back(N->isDistinct());
1061 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1062 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1063 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1064 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1065 Record.push_back(N->getLine());
1066 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1067 Record.push_back(N->isLocalToUnit());
1068 Record.push_back(N->isDefinition());
1069 Record.push_back(VE.getMetadataOrNullID(N->getRawVariable()));
1070 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
1072 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
1076 static void WriteMDLocalVariable(const MDLocalVariable *N,
1077 const ValueEnumerator &VE,
1078 BitstreamWriter &Stream,
1079 SmallVectorImpl<uint64_t> &Record,
1081 Record.push_back(N->isDistinct());
1082 Record.push_back(N->getTag());
1083 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1084 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1085 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1086 Record.push_back(N->getLine());
1087 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1088 Record.push_back(N->getArg());
1089 Record.push_back(N->getFlags());
1091 Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
1095 static void WriteMDExpression(const MDExpression *N, const ValueEnumerator &,
1096 BitstreamWriter &Stream,
1097 SmallVectorImpl<uint64_t> &Record,
1099 Record.reserve(N->getElements().size() + 1);
1101 Record.push_back(N->isDistinct());
1102 Record.append(N->elements_begin(), N->elements_end());
1104 Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
1108 static void WriteMDObjCProperty(const MDObjCProperty *N,
1109 const ValueEnumerator &VE,
1110 BitstreamWriter &Stream,
1111 SmallVectorImpl<uint64_t> &Record,
1113 Record.push_back(N->isDistinct());
1114 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1115 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1116 Record.push_back(N->getLine());
1117 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
1118 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
1119 Record.push_back(N->getAttributes());
1120 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1122 Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
1126 static void WriteMDImportedEntity(const MDImportedEntity *N,
1127 const ValueEnumerator &VE,
1128 BitstreamWriter &Stream,
1129 SmallVectorImpl<uint64_t> &Record,
1131 Record.push_back(N->isDistinct());
1132 Record.push_back(N->getTag());
1133 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1134 Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
1135 Record.push_back(N->getLine());
1136 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1138 Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
1142 static void WriteModuleMetadata(const Module *M,
1143 const ValueEnumerator &VE,
1144 BitstreamWriter &Stream) {
1145 const auto &MDs = VE.getMDs();
1146 if (MDs.empty() && M->named_metadata_empty())
1149 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
1151 unsigned MDSAbbrev = 0;
1152 if (VE.hasMDString()) {
1153 // Abbrev for METADATA_STRING.
1154 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1155 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING));
1156 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1157 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1158 MDSAbbrev = Stream.EmitAbbrev(Abbv);
1161 // Initialize MDNode abbreviations.
1162 #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
1163 #include "llvm/IR/Metadata.def"
1165 if (VE.hasMDLocation()) {
1166 // Abbrev for METADATA_LOCATION.
1168 // Assume the column is usually under 128, and always output the inlined-at
1169 // location (it's never more expensive than building an array size 1).
1170 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1171 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
1172 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1173 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1174 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1175 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1176 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1177 MDLocationAbbrev = Stream.EmitAbbrev(Abbv);
1180 if (VE.hasGenericDebugNode()) {
1181 // Abbrev for METADATA_GENERIC_DEBUG.
1183 // Assume the column is usually under 128, and always output the inlined-at
1184 // location (it's never more expensive than building an array size 1).
1185 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1186 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
1187 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1188 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1189 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1190 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1191 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1192 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1193 GenericDebugNodeAbbrev = Stream.EmitAbbrev(Abbv);
1196 unsigned NameAbbrev = 0;
1197 if (!M->named_metadata_empty()) {
1198 // Abbrev for METADATA_NAME.
1199 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1200 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
1201 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1202 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1203 NameAbbrev = Stream.EmitAbbrev(Abbv);
1206 SmallVector<uint64_t, 64> Record;
1207 for (const Metadata *MD : MDs) {
1208 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
1209 assert(N->isResolved() && "Expected forward references to be resolved");
1211 switch (N->getMetadataID()) {
1213 llvm_unreachable("Invalid MDNode subclass");
1214 #define HANDLE_MDNODE_LEAF(CLASS) \
1215 case Metadata::CLASS##Kind: \
1216 Write##CLASS(cast<CLASS>(N), VE, Stream, Record, CLASS##Abbrev); \
1218 #include "llvm/IR/Metadata.def"
1221 if (const auto *MDC = dyn_cast<ConstantAsMetadata>(MD)) {
1222 WriteValueAsMetadata(MDC, VE, Stream, Record);
1225 const MDString *MDS = cast<MDString>(MD);
1226 // Code: [strchar x N]
1227 Record.append(MDS->bytes_begin(), MDS->bytes_end());
1229 // Emit the finished record.
1230 Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev);
1234 // Write named metadata.
1235 for (const NamedMDNode &NMD : M->named_metadata()) {
1237 StringRef Str = NMD.getName();
1238 Record.append(Str.bytes_begin(), Str.bytes_end());
1239 Stream.EmitRecord(bitc::METADATA_NAME, Record, NameAbbrev);
1242 // Write named metadata operands.
1243 for (const MDNode *N : NMD.operands())
1244 Record.push_back(VE.getMetadataID(N));
1245 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
1252 static void WriteFunctionLocalMetadata(const Function &F,
1253 const ValueEnumerator &VE,
1254 BitstreamWriter &Stream) {
1255 bool StartedMetadataBlock = false;
1256 SmallVector<uint64_t, 64> Record;
1257 const SmallVectorImpl<const LocalAsMetadata *> &MDs =
1258 VE.getFunctionLocalMDs();
1259 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
1260 assert(MDs[i] && "Expected valid function-local metadata");
1261 if (!StartedMetadataBlock) {
1262 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
1263 StartedMetadataBlock = true;
1265 WriteValueAsMetadata(MDs[i], VE, Stream, Record);
1268 if (StartedMetadataBlock)
1272 static void WriteMetadataAttachment(const Function &F,
1273 const ValueEnumerator &VE,
1274 BitstreamWriter &Stream) {
1275 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
1277 SmallVector<uint64_t, 64> Record;
1279 // Write metadata attachments
1280 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
1281 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1282 F.getAllMetadata(MDs);
1284 for (const auto &I : MDs) {
1285 Record.push_back(I.first);
1286 Record.push_back(VE.getMetadataID(I.second));
1288 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
1292 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1293 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1296 I->getAllMetadataOtherThanDebugLoc(MDs);
1298 // If no metadata, ignore instruction.
1299 if (MDs.empty()) continue;
1301 Record.push_back(VE.getInstructionID(I));
1303 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
1304 Record.push_back(MDs[i].first);
1305 Record.push_back(VE.getMetadataID(MDs[i].second));
1307 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
1314 static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) {
1315 SmallVector<uint64_t, 64> Record;
1317 // Write metadata kinds
1318 // METADATA_KIND - [n x [id, name]]
1319 SmallVector<StringRef, 8> Names;
1320 M->getMDKindNames(Names);
1322 if (Names.empty()) return;
1324 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
1326 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
1327 Record.push_back(MDKindID);
1328 StringRef KName = Names[MDKindID];
1329 Record.append(KName.begin(), KName.end());
1331 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
1338 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
1339 if ((int64_t)V >= 0)
1340 Vals.push_back(V << 1);
1342 Vals.push_back((-V << 1) | 1);
1345 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
1346 const ValueEnumerator &VE,
1347 BitstreamWriter &Stream, bool isGlobal) {
1348 if (FirstVal == LastVal) return;
1350 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
1352 unsigned AggregateAbbrev = 0;
1353 unsigned String8Abbrev = 0;
1354 unsigned CString7Abbrev = 0;
1355 unsigned CString6Abbrev = 0;
1356 // If this is a constant pool for the module, emit module-specific abbrevs.
1358 // Abbrev for CST_CODE_AGGREGATE.
1359 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1360 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
1361 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1362 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
1363 AggregateAbbrev = Stream.EmitAbbrev(Abbv);
1365 // Abbrev for CST_CODE_STRING.
1366 Abbv = new BitCodeAbbrev();
1367 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
1368 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1369 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1370 String8Abbrev = Stream.EmitAbbrev(Abbv);
1371 // Abbrev for CST_CODE_CSTRING.
1372 Abbv = new BitCodeAbbrev();
1373 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
1374 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1375 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1376 CString7Abbrev = Stream.EmitAbbrev(Abbv);
1377 // Abbrev for CST_CODE_CSTRING.
1378 Abbv = new BitCodeAbbrev();
1379 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
1380 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1381 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1382 CString6Abbrev = Stream.EmitAbbrev(Abbv);
1385 SmallVector<uint64_t, 64> Record;
1387 const ValueEnumerator::ValueList &Vals = VE.getValues();
1388 Type *LastTy = nullptr;
1389 for (unsigned i = FirstVal; i != LastVal; ++i) {
1390 const Value *V = Vals[i].first;
1391 // If we need to switch types, do so now.
1392 if (V->getType() != LastTy) {
1393 LastTy = V->getType();
1394 Record.push_back(VE.getTypeID(LastTy));
1395 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
1396 CONSTANTS_SETTYPE_ABBREV);
1400 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1401 Record.push_back(unsigned(IA->hasSideEffects()) |
1402 unsigned(IA->isAlignStack()) << 1 |
1403 unsigned(IA->getDialect()&1) << 2);
1405 // Add the asm string.
1406 const std::string &AsmStr = IA->getAsmString();
1407 Record.push_back(AsmStr.size());
1408 Record.append(AsmStr.begin(), AsmStr.end());
1410 // Add the constraint string.
1411 const std::string &ConstraintStr = IA->getConstraintString();
1412 Record.push_back(ConstraintStr.size());
1413 Record.append(ConstraintStr.begin(), ConstraintStr.end());
1414 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
1418 const Constant *C = cast<Constant>(V);
1419 unsigned Code = -1U;
1420 unsigned AbbrevToUse = 0;
1421 if (C->isNullValue()) {
1422 Code = bitc::CST_CODE_NULL;
1423 } else if (isa<UndefValue>(C)) {
1424 Code = bitc::CST_CODE_UNDEF;
1425 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
1426 if (IV->getBitWidth() <= 64) {
1427 uint64_t V = IV->getSExtValue();
1428 emitSignedInt64(Record, V);
1429 Code = bitc::CST_CODE_INTEGER;
1430 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
1431 } else { // Wide integers, > 64 bits in size.
1432 // We have an arbitrary precision integer value to write whose
1433 // bit width is > 64. However, in canonical unsigned integer
1434 // format it is likely that the high bits are going to be zero.
1435 // So, we only write the number of active words.
1436 unsigned NWords = IV->getValue().getActiveWords();
1437 const uint64_t *RawWords = IV->getValue().getRawData();
1438 for (unsigned i = 0; i != NWords; ++i) {
1439 emitSignedInt64(Record, RawWords[i]);
1441 Code = bitc::CST_CODE_WIDE_INTEGER;
1443 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
1444 Code = bitc::CST_CODE_FLOAT;
1445 Type *Ty = CFP->getType();
1446 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
1447 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
1448 } else if (Ty->isX86_FP80Ty()) {
1449 // api needed to prevent premature destruction
1450 // bits are not in the same order as a normal i80 APInt, compensate.
1451 APInt api = CFP->getValueAPF().bitcastToAPInt();
1452 const uint64_t *p = api.getRawData();
1453 Record.push_back((p[1] << 48) | (p[0] >> 16));
1454 Record.push_back(p[0] & 0xffffLL);
1455 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
1456 APInt api = CFP->getValueAPF().bitcastToAPInt();
1457 const uint64_t *p = api.getRawData();
1458 Record.push_back(p[0]);
1459 Record.push_back(p[1]);
1461 assert (0 && "Unknown FP type!");
1463 } else if (isa<ConstantDataSequential>(C) &&
1464 cast<ConstantDataSequential>(C)->isString()) {
1465 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
1466 // Emit constant strings specially.
1467 unsigned NumElts = Str->getNumElements();
1468 // If this is a null-terminated string, use the denser CSTRING encoding.
1469 if (Str->isCString()) {
1470 Code = bitc::CST_CODE_CSTRING;
1471 --NumElts; // Don't encode the null, which isn't allowed by char6.
1473 Code = bitc::CST_CODE_STRING;
1474 AbbrevToUse = String8Abbrev;
1476 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
1477 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
1478 for (unsigned i = 0; i != NumElts; ++i) {
1479 unsigned char V = Str->getElementAsInteger(i);
1480 Record.push_back(V);
1481 isCStr7 &= (V & 128) == 0;
1483 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
1487 AbbrevToUse = CString6Abbrev;
1489 AbbrevToUse = CString7Abbrev;
1490 } else if (const ConstantDataSequential *CDS =
1491 dyn_cast<ConstantDataSequential>(C)) {
1492 Code = bitc::CST_CODE_DATA;
1493 Type *EltTy = CDS->getType()->getElementType();
1494 if (isa<IntegerType>(EltTy)) {
1495 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
1496 Record.push_back(CDS->getElementAsInteger(i));
1497 } else if (EltTy->isFloatTy()) {
1498 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1499 union { float F; uint32_t I; };
1500 F = CDS->getElementAsFloat(i);
1501 Record.push_back(I);
1504 assert(EltTy->isDoubleTy() && "Unknown ConstantData element type");
1505 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1506 union { double F; uint64_t I; };
1507 F = CDS->getElementAsDouble(i);
1508 Record.push_back(I);
1511 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
1512 isa<ConstantVector>(C)) {
1513 Code = bitc::CST_CODE_AGGREGATE;
1514 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
1515 Record.push_back(VE.getValueID(C->getOperand(i)));
1516 AbbrevToUse = AggregateAbbrev;
1517 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1518 switch (CE->getOpcode()) {
1520 if (Instruction::isCast(CE->getOpcode())) {
1521 Code = bitc::CST_CODE_CE_CAST;
1522 Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
1523 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1524 Record.push_back(VE.getValueID(C->getOperand(0)));
1525 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
1527 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
1528 Code = bitc::CST_CODE_CE_BINOP;
1529 Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
1530 Record.push_back(VE.getValueID(C->getOperand(0)));
1531 Record.push_back(VE.getValueID(C->getOperand(1)));
1532 uint64_t Flags = GetOptimizationFlags(CE);
1534 Record.push_back(Flags);
1537 case Instruction::GetElementPtr: {
1538 Code = bitc::CST_CODE_CE_GEP;
1539 const auto *GO = cast<GEPOperator>(C);
1540 if (GO->isInBounds())
1541 Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
1542 Record.push_back(VE.getTypeID(GO->getSourceElementType()));
1543 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
1544 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
1545 Record.push_back(VE.getValueID(C->getOperand(i)));
1549 case Instruction::Select:
1550 Code = bitc::CST_CODE_CE_SELECT;
1551 Record.push_back(VE.getValueID(C->getOperand(0)));
1552 Record.push_back(VE.getValueID(C->getOperand(1)));
1553 Record.push_back(VE.getValueID(C->getOperand(2)));
1555 case Instruction::ExtractElement:
1556 Code = bitc::CST_CODE_CE_EXTRACTELT;
1557 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1558 Record.push_back(VE.getValueID(C->getOperand(0)));
1559 Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
1560 Record.push_back(VE.getValueID(C->getOperand(1)));
1562 case Instruction::InsertElement:
1563 Code = bitc::CST_CODE_CE_INSERTELT;
1564 Record.push_back(VE.getValueID(C->getOperand(0)));
1565 Record.push_back(VE.getValueID(C->getOperand(1)));
1566 Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
1567 Record.push_back(VE.getValueID(C->getOperand(2)));
1569 case Instruction::ShuffleVector:
1570 // If the return type and argument types are the same, this is a
1571 // standard shufflevector instruction. If the types are different,
1572 // then the shuffle is widening or truncating the input vectors, and
1573 // the argument type must also be encoded.
1574 if (C->getType() == C->getOperand(0)->getType()) {
1575 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
1577 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
1578 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1580 Record.push_back(VE.getValueID(C->getOperand(0)));
1581 Record.push_back(VE.getValueID(C->getOperand(1)));
1582 Record.push_back(VE.getValueID(C->getOperand(2)));
1584 case Instruction::ICmp:
1585 case Instruction::FCmp:
1586 Code = bitc::CST_CODE_CE_CMP;
1587 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1588 Record.push_back(VE.getValueID(C->getOperand(0)));
1589 Record.push_back(VE.getValueID(C->getOperand(1)));
1590 Record.push_back(CE->getPredicate());
1593 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
1594 Code = bitc::CST_CODE_BLOCKADDRESS;
1595 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
1596 Record.push_back(VE.getValueID(BA->getFunction()));
1597 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
1602 llvm_unreachable("Unknown constant!");
1604 Stream.EmitRecord(Code, Record, AbbrevToUse);
1611 static void WriteModuleConstants(const ValueEnumerator &VE,
1612 BitstreamWriter &Stream) {
1613 const ValueEnumerator::ValueList &Vals = VE.getValues();
1615 // Find the first constant to emit, which is the first non-globalvalue value.
1616 // We know globalvalues have been emitted by WriteModuleInfo.
1617 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1618 if (!isa<GlobalValue>(Vals[i].first)) {
1619 WriteConstants(i, Vals.size(), VE, Stream, true);
1625 /// PushValueAndType - The file has to encode both the value and type id for
1626 /// many values, because we need to know what type to create for forward
1627 /// references. However, most operands are not forward references, so this type
1628 /// field is not needed.
1630 /// This function adds V's value ID to Vals. If the value ID is higher than the
1631 /// instruction ID, then it is a forward reference, and it also includes the
1632 /// type ID. The value ID that is written is encoded relative to the InstID.
1633 static bool PushValueAndType(const Value *V, unsigned InstID,
1634 SmallVectorImpl<unsigned> &Vals,
1635 ValueEnumerator &VE) {
1636 unsigned ValID = VE.getValueID(V);
1637 // Make encoding relative to the InstID.
1638 Vals.push_back(InstID - ValID);
1639 if (ValID >= InstID) {
1640 Vals.push_back(VE.getTypeID(V->getType()));
1646 /// pushValue - Like PushValueAndType, but where the type of the value is
1647 /// omitted (perhaps it was already encoded in an earlier operand).
1648 static void pushValue(const Value *V, unsigned InstID,
1649 SmallVectorImpl<unsigned> &Vals,
1650 ValueEnumerator &VE) {
1651 unsigned ValID = VE.getValueID(V);
1652 Vals.push_back(InstID - ValID);
1655 static void pushValueSigned(const Value *V, unsigned InstID,
1656 SmallVectorImpl<uint64_t> &Vals,
1657 ValueEnumerator &VE) {
1658 unsigned ValID = VE.getValueID(V);
1659 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
1660 emitSignedInt64(Vals, diff);
1663 /// WriteInstruction - Emit an instruction to the specified stream.
1664 static void WriteInstruction(const Instruction &I, unsigned InstID,
1665 ValueEnumerator &VE, BitstreamWriter &Stream,
1666 SmallVectorImpl<unsigned> &Vals) {
1668 unsigned AbbrevToUse = 0;
1669 VE.setInstructionID(&I);
1670 switch (I.getOpcode()) {
1672 if (Instruction::isCast(I.getOpcode())) {
1673 Code = bitc::FUNC_CODE_INST_CAST;
1674 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1675 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
1676 Vals.push_back(VE.getTypeID(I.getType()));
1677 Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
1679 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
1680 Code = bitc::FUNC_CODE_INST_BINOP;
1681 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1682 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
1683 pushValue(I.getOperand(1), InstID, Vals, VE);
1684 Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
1685 uint64_t Flags = GetOptimizationFlags(&I);
1687 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
1688 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
1689 Vals.push_back(Flags);
1694 case Instruction::GetElementPtr: {
1695 Code = bitc::FUNC_CODE_INST_GEP;
1696 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
1697 auto &GEPInst = cast<GetElementPtrInst>(I);
1698 Vals.push_back(GEPInst.isInBounds());
1699 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
1700 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1701 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1704 case Instruction::ExtractValue: {
1705 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
1706 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1707 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
1708 Vals.append(EVI->idx_begin(), EVI->idx_end());
1711 case Instruction::InsertValue: {
1712 Code = bitc::FUNC_CODE_INST_INSERTVAL;
1713 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1714 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1715 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
1716 Vals.append(IVI->idx_begin(), IVI->idx_end());
1719 case Instruction::Select:
1720 Code = bitc::FUNC_CODE_INST_VSELECT;
1721 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1722 pushValue(I.getOperand(2), InstID, Vals, VE);
1723 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1725 case Instruction::ExtractElement:
1726 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
1727 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1728 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1730 case Instruction::InsertElement:
1731 Code = bitc::FUNC_CODE_INST_INSERTELT;
1732 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1733 pushValue(I.getOperand(1), InstID, Vals, VE);
1734 PushValueAndType(I.getOperand(2), InstID, Vals, VE);
1736 case Instruction::ShuffleVector:
1737 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
1738 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1739 pushValue(I.getOperand(1), InstID, Vals, VE);
1740 pushValue(I.getOperand(2), InstID, Vals, VE);
1742 case Instruction::ICmp:
1743 case Instruction::FCmp:
1744 // compare returning Int1Ty or vector of Int1Ty
1745 Code = bitc::FUNC_CODE_INST_CMP2;
1746 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1747 pushValue(I.getOperand(1), InstID, Vals, VE);
1748 Vals.push_back(cast<CmpInst>(I).getPredicate());
1751 case Instruction::Ret:
1753 Code = bitc::FUNC_CODE_INST_RET;
1754 unsigned NumOperands = I.getNumOperands();
1755 if (NumOperands == 0)
1756 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
1757 else if (NumOperands == 1) {
1758 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1759 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
1761 for (unsigned i = 0, e = NumOperands; i != e; ++i)
1762 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1766 case Instruction::Br:
1768 Code = bitc::FUNC_CODE_INST_BR;
1769 const BranchInst &II = cast<BranchInst>(I);
1770 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
1771 if (II.isConditional()) {
1772 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
1773 pushValue(II.getCondition(), InstID, Vals, VE);
1777 case Instruction::Switch:
1779 Code = bitc::FUNC_CODE_INST_SWITCH;
1780 const SwitchInst &SI = cast<SwitchInst>(I);
1781 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
1782 pushValue(SI.getCondition(), InstID, Vals, VE);
1783 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
1784 for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
1786 Vals.push_back(VE.getValueID(i.getCaseValue()));
1787 Vals.push_back(VE.getValueID(i.getCaseSuccessor()));
1791 case Instruction::IndirectBr:
1792 Code = bitc::FUNC_CODE_INST_INDIRECTBR;
1793 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1794 // Encode the address operand as relative, but not the basic blocks.
1795 pushValue(I.getOperand(0), InstID, Vals, VE);
1796 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
1797 Vals.push_back(VE.getValueID(I.getOperand(i)));
1800 case Instruction::Invoke: {
1801 const InvokeInst *II = cast<InvokeInst>(&I);
1802 const Value *Callee = II->getCalledValue();
1803 FunctionType *FTy = II->getFunctionType();
1804 Code = bitc::FUNC_CODE_INST_INVOKE;
1806 Vals.push_back(VE.getAttributeID(II->getAttributes()));
1807 Vals.push_back(II->getCallingConv() | 1 << 13);
1808 Vals.push_back(VE.getValueID(II->getNormalDest()));
1809 Vals.push_back(VE.getValueID(II->getUnwindDest()));
1810 Vals.push_back(VE.getTypeID(FTy));
1811 PushValueAndType(Callee, InstID, Vals, VE);
1813 // Emit value #'s for the fixed parameters.
1814 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1815 pushValue(I.getOperand(i), InstID, Vals, VE); // fixed param.
1817 // Emit type/value pairs for varargs params.
1818 if (FTy->isVarArg()) {
1819 for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
1821 PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
1825 case Instruction::Resume:
1826 Code = bitc::FUNC_CODE_INST_RESUME;
1827 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1829 case Instruction::Unreachable:
1830 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
1831 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
1834 case Instruction::PHI: {
1835 const PHINode &PN = cast<PHINode>(I);
1836 Code = bitc::FUNC_CODE_INST_PHI;
1837 // With the newer instruction encoding, forward references could give
1838 // negative valued IDs. This is most common for PHIs, so we use
1840 SmallVector<uint64_t, 128> Vals64;
1841 Vals64.push_back(VE.getTypeID(PN.getType()));
1842 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1843 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64, VE);
1844 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
1846 // Emit a Vals64 vector and exit.
1847 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
1852 case Instruction::LandingPad: {
1853 const LandingPadInst &LP = cast<LandingPadInst>(I);
1854 Code = bitc::FUNC_CODE_INST_LANDINGPAD;
1855 Vals.push_back(VE.getTypeID(LP.getType()));
1856 PushValueAndType(LP.getPersonalityFn(), InstID, Vals, VE);
1857 Vals.push_back(LP.isCleanup());
1858 Vals.push_back(LP.getNumClauses());
1859 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
1861 Vals.push_back(LandingPadInst::Catch);
1863 Vals.push_back(LandingPadInst::Filter);
1864 PushValueAndType(LP.getClause(I), InstID, Vals, VE);
1869 case Instruction::Alloca: {
1870 Code = bitc::FUNC_CODE_INST_ALLOCA;
1871 Vals.push_back(VE.getTypeID(I.getType()));
1872 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1873 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
1874 const AllocaInst &AI = cast<AllocaInst>(I);
1875 unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
1876 assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
1877 "not enough bits for maximum alignment");
1878 assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
1879 AlignRecord |= AI.isUsedWithInAlloca() << 5;
1880 Vals.push_back(AlignRecord);
1884 case Instruction::Load:
1885 if (cast<LoadInst>(I).isAtomic()) {
1886 Code = bitc::FUNC_CODE_INST_LOADATOMIC;
1887 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1889 Code = bitc::FUNC_CODE_INST_LOAD;
1890 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) // ptr
1891 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
1893 Vals.push_back(VE.getTypeID(I.getType()));
1894 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
1895 Vals.push_back(cast<LoadInst>(I).isVolatile());
1896 if (cast<LoadInst>(I).isAtomic()) {
1897 Vals.push_back(GetEncodedOrdering(cast<LoadInst>(I).getOrdering()));
1898 Vals.push_back(GetEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
1901 case Instruction::Store:
1902 if (cast<StoreInst>(I).isAtomic())
1903 Code = bitc::FUNC_CODE_INST_STOREATOMIC;
1905 Code = bitc::FUNC_CODE_INST_STORE;
1906 PushValueAndType(I.getOperand(1), InstID, Vals, VE); // ptrty + ptr
1907 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // valty + val
1908 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
1909 Vals.push_back(cast<StoreInst>(I).isVolatile());
1910 if (cast<StoreInst>(I).isAtomic()) {
1911 Vals.push_back(GetEncodedOrdering(cast<StoreInst>(I).getOrdering()));
1912 Vals.push_back(GetEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
1915 case Instruction::AtomicCmpXchg:
1916 Code = bitc::FUNC_CODE_INST_CMPXCHG;
1917 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr
1918 pushValue(I.getOperand(1), InstID, Vals, VE); // cmp.
1919 pushValue(I.getOperand(2), InstID, Vals, VE); // newval.
1920 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
1921 Vals.push_back(GetEncodedOrdering(
1922 cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
1923 Vals.push_back(GetEncodedSynchScope(
1924 cast<AtomicCmpXchgInst>(I).getSynchScope()));
1925 Vals.push_back(GetEncodedOrdering(
1926 cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
1927 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
1929 case Instruction::AtomicRMW:
1930 Code = bitc::FUNC_CODE_INST_ATOMICRMW;
1931 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr
1932 pushValue(I.getOperand(1), InstID, Vals, VE); // val.
1933 Vals.push_back(GetEncodedRMWOperation(
1934 cast<AtomicRMWInst>(I).getOperation()));
1935 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
1936 Vals.push_back(GetEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
1937 Vals.push_back(GetEncodedSynchScope(
1938 cast<AtomicRMWInst>(I).getSynchScope()));
1940 case Instruction::Fence:
1941 Code = bitc::FUNC_CODE_INST_FENCE;
1942 Vals.push_back(GetEncodedOrdering(cast<FenceInst>(I).getOrdering()));
1943 Vals.push_back(GetEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
1945 case Instruction::Call: {
1946 const CallInst &CI = cast<CallInst>(I);
1947 FunctionType *FTy = CI.getFunctionType();
1949 Code = bitc::FUNC_CODE_INST_CALL;
1951 Vals.push_back(VE.getAttributeID(CI.getAttributes()));
1952 Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall()) |
1953 unsigned(CI.isMustTailCall()) << 14 | 1 << 15);
1954 Vals.push_back(VE.getTypeID(FTy));
1955 PushValueAndType(CI.getCalledValue(), InstID, Vals, VE); // Callee
1957 // Emit value #'s for the fixed parameters.
1958 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
1959 // Check for labels (can happen with asm labels).
1960 if (FTy->getParamType(i)->isLabelTy())
1961 Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
1963 pushValue(CI.getArgOperand(i), InstID, Vals, VE); // fixed param.
1966 // Emit type/value pairs for varargs params.
1967 if (FTy->isVarArg()) {
1968 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
1970 PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE); // varargs
1974 case Instruction::VAArg:
1975 Code = bitc::FUNC_CODE_INST_VAARG;
1976 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
1977 pushValue(I.getOperand(0), InstID, Vals, VE); // valist.
1978 Vals.push_back(VE.getTypeID(I.getType())); // restype.
1982 Stream.EmitRecord(Code, Vals, AbbrevToUse);
1986 // Emit names for globals/functions etc.
1987 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
1988 const ValueEnumerator &VE,
1989 BitstreamWriter &Stream) {
1990 if (VST.empty()) return;
1991 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
1993 // FIXME: Set up the abbrev, we know how many values there are!
1994 // FIXME: We know if the type names can use 7-bit ascii.
1995 SmallVector<unsigned, 64> NameVals;
1997 for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
2000 const ValueName &Name = *SI;
2002 // Figure out the encoding to use for the name.
2004 bool isChar6 = true;
2005 for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
2008 isChar6 = BitCodeAbbrevOp::isChar6(*C);
2009 if ((unsigned char)*C & 128) {
2011 break; // don't bother scanning the rest.
2015 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
2017 // VST_ENTRY: [valueid, namechar x N]
2018 // VST_BBENTRY: [bbid, namechar x N]
2020 if (isa<BasicBlock>(SI->getValue())) {
2021 Code = bitc::VST_CODE_BBENTRY;
2023 AbbrevToUse = VST_BBENTRY_6_ABBREV;
2025 Code = bitc::VST_CODE_ENTRY;
2027 AbbrevToUse = VST_ENTRY_6_ABBREV;
2029 AbbrevToUse = VST_ENTRY_7_ABBREV;
2032 NameVals.push_back(VE.getValueID(SI->getValue()));
2033 for (const char *P = Name.getKeyData(),
2034 *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
2035 NameVals.push_back((unsigned char)*P);
2037 // Emit the finished record.
2038 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
2044 static void WriteUseList(ValueEnumerator &VE, UseListOrder &&Order,
2045 BitstreamWriter &Stream) {
2046 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
2048 if (isa<BasicBlock>(Order.V))
2049 Code = bitc::USELIST_CODE_BB;
2051 Code = bitc::USELIST_CODE_DEFAULT;
2053 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
2054 Record.push_back(VE.getValueID(Order.V));
2055 Stream.EmitRecord(Code, Record);
2058 static void WriteUseListBlock(const Function *F, ValueEnumerator &VE,
2059 BitstreamWriter &Stream) {
2060 assert(VE.shouldPreserveUseListOrder() &&
2061 "Expected to be preserving use-list order");
2063 auto hasMore = [&]() {
2064 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
2070 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
2072 WriteUseList(VE, std::move(VE.UseListOrders.back()), Stream);
2073 VE.UseListOrders.pop_back();
2078 /// WriteFunction - Emit a function body to the module stream.
2079 static void WriteFunction(const Function &F, ValueEnumerator &VE,
2080 BitstreamWriter &Stream) {
2081 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
2082 VE.incorporateFunction(F);
2084 SmallVector<unsigned, 64> Vals;
2086 // Emit the number of basic blocks, so the reader can create them ahead of
2088 Vals.push_back(VE.getBasicBlocks().size());
2089 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
2092 // If there are function-local constants, emit them now.
2093 unsigned CstStart, CstEnd;
2094 VE.getFunctionConstantRange(CstStart, CstEnd);
2095 WriteConstants(CstStart, CstEnd, VE, Stream, false);
2097 // If there is function-local metadata, emit it now.
2098 WriteFunctionLocalMetadata(F, VE, Stream);
2100 // Keep a running idea of what the instruction ID is.
2101 unsigned InstID = CstEnd;
2103 bool NeedsMetadataAttachment = F.hasMetadata();
2105 MDLocation *LastDL = nullptr;
2107 // Finally, emit all the instructions, in order.
2108 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
2109 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
2111 WriteInstruction(*I, InstID, VE, Stream, Vals);
2113 if (!I->getType()->isVoidTy())
2116 // If the instruction has metadata, write a metadata attachment later.
2117 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
2119 // If the instruction has a debug location, emit it.
2120 MDLocation *DL = I->getDebugLoc();
2125 // Just repeat the same debug loc as last time.
2126 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
2130 Vals.push_back(DL->getLine());
2131 Vals.push_back(DL->getColumn());
2132 Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
2133 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
2134 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
2138 // Emit names for all the instructions etc.
2139 WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
2141 if (NeedsMetadataAttachment)
2142 WriteMetadataAttachment(F, VE, Stream);
2143 if (VE.shouldPreserveUseListOrder())
2144 WriteUseListBlock(&F, VE, Stream);
2149 // Emit blockinfo, which defines the standard abbreviations etc.
2150 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
2151 // We only want to emit block info records for blocks that have multiple
2152 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
2153 // Other blocks can define their abbrevs inline.
2154 Stream.EnterBlockInfoBlock(2);
2156 { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
2157 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2158 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
2159 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2160 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2161 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2162 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2163 Abbv) != VST_ENTRY_8_ABBREV)
2164 llvm_unreachable("Unexpected abbrev ordering!");
2167 { // 7-bit fixed width VST_ENTRY strings.
2168 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2169 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2170 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2171 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2172 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2173 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2174 Abbv) != VST_ENTRY_7_ABBREV)
2175 llvm_unreachable("Unexpected abbrev ordering!");
2177 { // 6-bit char6 VST_ENTRY strings.
2178 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2179 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2180 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2181 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2182 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2183 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2184 Abbv) != VST_ENTRY_6_ABBREV)
2185 llvm_unreachable("Unexpected abbrev ordering!");
2187 { // 6-bit char6 VST_BBENTRY strings.
2188 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2189 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
2190 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2191 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2192 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2193 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2194 Abbv) != VST_BBENTRY_6_ABBREV)
2195 llvm_unreachable("Unexpected abbrev ordering!");
2200 { // SETTYPE abbrev for CONSTANTS_BLOCK.
2201 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2202 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
2203 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
2204 VE.computeBitsRequiredForTypeIndicies()));
2205 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2206 Abbv) != CONSTANTS_SETTYPE_ABBREV)
2207 llvm_unreachable("Unexpected abbrev ordering!");
2210 { // INTEGER abbrev for CONSTANTS_BLOCK.
2211 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2212 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
2213 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2214 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2215 Abbv) != CONSTANTS_INTEGER_ABBREV)
2216 llvm_unreachable("Unexpected abbrev ordering!");
2219 { // CE_CAST abbrev for CONSTANTS_BLOCK.
2220 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2221 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
2222 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
2223 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
2224 VE.computeBitsRequiredForTypeIndicies()));
2225 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2227 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2228 Abbv) != CONSTANTS_CE_CAST_Abbrev)
2229 llvm_unreachable("Unexpected abbrev ordering!");
2231 { // NULL abbrev for CONSTANTS_BLOCK.
2232 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2233 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
2234 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2235 Abbv) != CONSTANTS_NULL_Abbrev)
2236 llvm_unreachable("Unexpected abbrev ordering!");
2239 // FIXME: This should only use space for first class types!
2241 { // INST_LOAD abbrev for FUNCTION_BLOCK.
2242 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2243 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
2244 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
2245 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
2246 VE.computeBitsRequiredForTypeIndicies()));
2247 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
2248 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
2249 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2250 Abbv) != FUNCTION_INST_LOAD_ABBREV)
2251 llvm_unreachable("Unexpected abbrev ordering!");
2253 { // INST_BINOP abbrev for FUNCTION_BLOCK.
2254 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2255 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
2256 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
2257 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
2258 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2259 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2260 Abbv) != FUNCTION_INST_BINOP_ABBREV)
2261 llvm_unreachable("Unexpected abbrev ordering!");
2263 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
2264 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2265 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
2266 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
2267 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
2268 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2269 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
2270 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2271 Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV)
2272 llvm_unreachable("Unexpected abbrev ordering!");
2274 { // INST_CAST abbrev for FUNCTION_BLOCK.
2275 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2276 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
2277 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
2278 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
2279 VE.computeBitsRequiredForTypeIndicies()));
2280 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2281 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2282 Abbv) != FUNCTION_INST_CAST_ABBREV)
2283 llvm_unreachable("Unexpected abbrev ordering!");
2286 { // INST_RET abbrev for FUNCTION_BLOCK.
2287 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2288 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
2289 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2290 Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
2291 llvm_unreachable("Unexpected abbrev ordering!");
2293 { // INST_RET abbrev for FUNCTION_BLOCK.
2294 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2295 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
2296 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
2297 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2298 Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
2299 llvm_unreachable("Unexpected abbrev ordering!");
2301 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
2302 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2303 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
2304 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2305 Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
2306 llvm_unreachable("Unexpected abbrev ordering!");
2309 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2310 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
2311 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
2312 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
2313 Log2_32_Ceil(VE.getTypes().size() + 1)));
2314 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2315 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2316 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
2317 FUNCTION_INST_GEP_ABBREV)
2318 llvm_unreachable("Unexpected abbrev ordering!");
2324 /// WriteModule - Emit the specified module to the bitstream.
2325 static void WriteModule(const Module *M, BitstreamWriter &Stream,
2326 bool ShouldPreserveUseListOrder) {
2327 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
2329 SmallVector<unsigned, 1> Vals;
2330 unsigned CurVersion = 1;
2331 Vals.push_back(CurVersion);
2332 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
2334 // Analyze the module, enumerating globals, functions, etc.
2335 ValueEnumerator VE(*M, ShouldPreserveUseListOrder);
2337 // Emit blockinfo, which defines the standard abbreviations etc.
2338 WriteBlockInfo(VE, Stream);
2340 // Emit information about attribute groups.
2341 WriteAttributeGroupTable(VE, Stream);
2343 // Emit information about parameter attributes.
2344 WriteAttributeTable(VE, Stream);
2346 // Emit information describing all of the types in the module.
2347 WriteTypeTable(VE, Stream);
2349 writeComdats(VE, Stream);
2351 // Emit top-level description of module, including target triple, inline asm,
2352 // descriptors for global variables, and function prototype info.
2353 WriteModuleInfo(M, VE, Stream);
2356 WriteModuleConstants(VE, Stream);
2359 WriteModuleMetadata(M, VE, Stream);
2362 WriteModuleMetadataStore(M, Stream);
2364 // Emit names for globals/functions etc.
2365 WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
2367 // Emit module-level use-lists.
2368 if (VE.shouldPreserveUseListOrder())
2369 WriteUseListBlock(nullptr, VE, Stream);
2371 // Emit function bodies.
2372 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F)
2373 if (!F->isDeclaration())
2374 WriteFunction(*F, VE, Stream);
2379 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
2380 /// header and trailer to make it compatible with the system archiver. To do
2381 /// this we emit the following header, and then emit a trailer that pads the
2382 /// file out to be a multiple of 16 bytes.
2384 /// struct bc_header {
2385 /// uint32_t Magic; // 0x0B17C0DE
2386 /// uint32_t Version; // Version, currently always 0.
2387 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
2388 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
2389 /// uint32_t CPUType; // CPU specifier.
2390 /// ... potentially more later ...
2393 DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
2394 DarwinBCHeaderSize = 5*4
2397 static void WriteInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
2398 uint32_t &Position) {
2399 Buffer[Position + 0] = (unsigned char) (Value >> 0);
2400 Buffer[Position + 1] = (unsigned char) (Value >> 8);
2401 Buffer[Position + 2] = (unsigned char) (Value >> 16);
2402 Buffer[Position + 3] = (unsigned char) (Value >> 24);
2406 static void EmitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
2408 unsigned CPUType = ~0U;
2410 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
2411 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
2412 // number from /usr/include/mach/machine.h. It is ok to reproduce the
2413 // specific constants here because they are implicitly part of the Darwin ABI.
2415 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
2416 DARWIN_CPU_TYPE_X86 = 7,
2417 DARWIN_CPU_TYPE_ARM = 12,
2418 DARWIN_CPU_TYPE_POWERPC = 18
2421 Triple::ArchType Arch = TT.getArch();
2422 if (Arch == Triple::x86_64)
2423 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
2424 else if (Arch == Triple::x86)
2425 CPUType = DARWIN_CPU_TYPE_X86;
2426 else if (Arch == Triple::ppc)
2427 CPUType = DARWIN_CPU_TYPE_POWERPC;
2428 else if (Arch == Triple::ppc64)
2429 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
2430 else if (Arch == Triple::arm || Arch == Triple::thumb)
2431 CPUType = DARWIN_CPU_TYPE_ARM;
2433 // Traditional Bitcode starts after header.
2434 assert(Buffer.size() >= DarwinBCHeaderSize &&
2435 "Expected header size to be reserved");
2436 unsigned BCOffset = DarwinBCHeaderSize;
2437 unsigned BCSize = Buffer.size()-DarwinBCHeaderSize;
2439 // Write the magic and version.
2440 unsigned Position = 0;
2441 WriteInt32ToBuffer(0x0B17C0DE , Buffer, Position);
2442 WriteInt32ToBuffer(0 , Buffer, Position); // Version.
2443 WriteInt32ToBuffer(BCOffset , Buffer, Position);
2444 WriteInt32ToBuffer(BCSize , Buffer, Position);
2445 WriteInt32ToBuffer(CPUType , Buffer, Position);
2447 // If the file is not a multiple of 16 bytes, insert dummy padding.
2448 while (Buffer.size() & 15)
2449 Buffer.push_back(0);
2452 /// WriteBitcodeToFile - Write the specified module to the specified output
2454 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out,
2455 bool ShouldPreserveUseListOrder) {
2456 SmallVector<char, 0> Buffer;
2457 Buffer.reserve(256*1024);
2459 // If this is darwin or another generic macho target, reserve space for the
2461 Triple TT(M->getTargetTriple());
2462 if (TT.isOSDarwin())
2463 Buffer.insert(Buffer.begin(), DarwinBCHeaderSize, 0);
2465 // Emit the module into the buffer.
2467 BitstreamWriter Stream(Buffer);
2469 // Emit the file header.
2470 Stream.Emit((unsigned)'B', 8);
2471 Stream.Emit((unsigned)'C', 8);
2472 Stream.Emit(0x0, 4);
2473 Stream.Emit(0xC, 4);
2474 Stream.Emit(0xE, 4);
2475 Stream.Emit(0xD, 4);
2478 WriteModule(M, Stream, ShouldPreserveUseListOrder);
2481 if (TT.isOSDarwin())
2482 EmitDarwinBCHeaderAndTrailer(Buffer, TT);
2484 // Write the generated bitstream to "Out".
2485 Out.write((char*)&Buffer.front(), Buffer.size());