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::ArgMemOnly:
166 return bitc::ATTR_KIND_ARGMEMONLY;
167 case Attribute::Builtin:
168 return bitc::ATTR_KIND_BUILTIN;
169 case Attribute::ByVal:
170 return bitc::ATTR_KIND_BY_VAL;
171 case Attribute::Convergent:
172 return bitc::ATTR_KIND_CONVERGENT;
173 case Attribute::InAlloca:
174 return bitc::ATTR_KIND_IN_ALLOCA;
175 case Attribute::Cold:
176 return bitc::ATTR_KIND_COLD;
177 case Attribute::InlineHint:
178 return bitc::ATTR_KIND_INLINE_HINT;
179 case Attribute::InReg:
180 return bitc::ATTR_KIND_IN_REG;
181 case Attribute::JumpTable:
182 return bitc::ATTR_KIND_JUMP_TABLE;
183 case Attribute::MinSize:
184 return bitc::ATTR_KIND_MIN_SIZE;
185 case Attribute::Naked:
186 return bitc::ATTR_KIND_NAKED;
187 case Attribute::Nest:
188 return bitc::ATTR_KIND_NEST;
189 case Attribute::NoAlias:
190 return bitc::ATTR_KIND_NO_ALIAS;
191 case Attribute::NoBuiltin:
192 return bitc::ATTR_KIND_NO_BUILTIN;
193 case Attribute::NoCapture:
194 return bitc::ATTR_KIND_NO_CAPTURE;
195 case Attribute::NoDuplicate:
196 return bitc::ATTR_KIND_NO_DUPLICATE;
197 case Attribute::NoImplicitFloat:
198 return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
199 case Attribute::NoInline:
200 return bitc::ATTR_KIND_NO_INLINE;
201 case Attribute::NonLazyBind:
202 return bitc::ATTR_KIND_NON_LAZY_BIND;
203 case Attribute::NonNull:
204 return bitc::ATTR_KIND_NON_NULL;
205 case Attribute::Dereferenceable:
206 return bitc::ATTR_KIND_DEREFERENCEABLE;
207 case Attribute::DereferenceableOrNull:
208 return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL;
209 case Attribute::NoRedZone:
210 return bitc::ATTR_KIND_NO_RED_ZONE;
211 case Attribute::NoReturn:
212 return bitc::ATTR_KIND_NO_RETURN;
213 case Attribute::NoUnwind:
214 return bitc::ATTR_KIND_NO_UNWIND;
215 case Attribute::OptimizeForSize:
216 return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
217 case Attribute::OptimizeNone:
218 return bitc::ATTR_KIND_OPTIMIZE_NONE;
219 case Attribute::ReadNone:
220 return bitc::ATTR_KIND_READ_NONE;
221 case Attribute::ReadOnly:
222 return bitc::ATTR_KIND_READ_ONLY;
223 case Attribute::Returned:
224 return bitc::ATTR_KIND_RETURNED;
225 case Attribute::ReturnsTwice:
226 return bitc::ATTR_KIND_RETURNS_TWICE;
227 case Attribute::SExt:
228 return bitc::ATTR_KIND_S_EXT;
229 case Attribute::StackAlignment:
230 return bitc::ATTR_KIND_STACK_ALIGNMENT;
231 case Attribute::StackProtect:
232 return bitc::ATTR_KIND_STACK_PROTECT;
233 case Attribute::StackProtectReq:
234 return bitc::ATTR_KIND_STACK_PROTECT_REQ;
235 case Attribute::StackProtectStrong:
236 return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
237 case Attribute::SafeStack:
238 return bitc::ATTR_KIND_SAFESTACK;
239 case Attribute::StructRet:
240 return bitc::ATTR_KIND_STRUCT_RET;
241 case Attribute::SanitizeAddress:
242 return bitc::ATTR_KIND_SANITIZE_ADDRESS;
243 case Attribute::SanitizeThread:
244 return bitc::ATTR_KIND_SANITIZE_THREAD;
245 case Attribute::SanitizeMemory:
246 return bitc::ATTR_KIND_SANITIZE_MEMORY;
247 case Attribute::UWTable:
248 return bitc::ATTR_KIND_UW_TABLE;
249 case Attribute::ZExt:
250 return bitc::ATTR_KIND_Z_EXT;
251 case Attribute::EndAttrKinds:
252 llvm_unreachable("Can not encode end-attribute kinds marker.");
253 case Attribute::None:
254 llvm_unreachable("Can not encode none-attribute.");
257 llvm_unreachable("Trying to encode unknown attribute");
260 static void WriteAttributeGroupTable(const ValueEnumerator &VE,
261 BitstreamWriter &Stream) {
262 const std::vector<AttributeSet> &AttrGrps = VE.getAttributeGroups();
263 if (AttrGrps.empty()) return;
265 Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
267 SmallVector<uint64_t, 64> Record;
268 for (unsigned i = 0, e = AttrGrps.size(); i != e; ++i) {
269 AttributeSet AS = AttrGrps[i];
270 for (unsigned i = 0, e = AS.getNumSlots(); i != e; ++i) {
271 AttributeSet A = AS.getSlotAttributes(i);
273 Record.push_back(VE.getAttributeGroupID(A));
274 Record.push_back(AS.getSlotIndex(i));
276 for (AttributeSet::iterator I = AS.begin(0), E = AS.end(0);
279 if (Attr.isEnumAttribute()) {
281 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
282 } else if (Attr.isIntAttribute()) {
284 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
285 Record.push_back(Attr.getValueAsInt());
287 StringRef Kind = Attr.getKindAsString();
288 StringRef Val = Attr.getValueAsString();
290 Record.push_back(Val.empty() ? 3 : 4);
291 Record.append(Kind.begin(), Kind.end());
294 Record.append(Val.begin(), Val.end());
300 Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
308 static void WriteAttributeTable(const ValueEnumerator &VE,
309 BitstreamWriter &Stream) {
310 const std::vector<AttributeSet> &Attrs = VE.getAttributes();
311 if (Attrs.empty()) return;
313 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
315 SmallVector<uint64_t, 64> Record;
316 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
317 const AttributeSet &A = Attrs[i];
318 for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i)
319 Record.push_back(VE.getAttributeGroupID(A.getSlotAttributes(i)));
321 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
328 /// WriteTypeTable - Write out the type table for a module.
329 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
330 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
332 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
333 SmallVector<uint64_t, 64> TypeVals;
335 uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies();
337 // Abbrev for TYPE_CODE_POINTER.
338 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
339 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
340 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
341 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
342 unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
344 // Abbrev for TYPE_CODE_FUNCTION.
345 Abbv = new BitCodeAbbrev();
346 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
347 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
348 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
349 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
351 unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
353 // Abbrev for TYPE_CODE_STRUCT_ANON.
354 Abbv = new BitCodeAbbrev();
355 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
356 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
357 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
358 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
360 unsigned StructAnonAbbrev = Stream.EmitAbbrev(Abbv);
362 // Abbrev for TYPE_CODE_STRUCT_NAME.
363 Abbv = new BitCodeAbbrev();
364 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
365 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
366 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
367 unsigned StructNameAbbrev = Stream.EmitAbbrev(Abbv);
369 // Abbrev for TYPE_CODE_STRUCT_NAMED.
370 Abbv = new BitCodeAbbrev();
371 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
372 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
373 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
374 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
376 unsigned StructNamedAbbrev = Stream.EmitAbbrev(Abbv);
378 // Abbrev for TYPE_CODE_ARRAY.
379 Abbv = new BitCodeAbbrev();
380 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
381 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
382 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
384 unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
386 // Emit an entry count so the reader can reserve space.
387 TypeVals.push_back(TypeList.size());
388 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
391 // Loop over all of the types, emitting each in turn.
392 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
393 Type *T = TypeList[i];
397 switch (T->getTypeID()) {
398 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
399 case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break;
400 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
401 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
402 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
403 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
404 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
405 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
406 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
407 case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break;
408 case Type::TokenTyID: Code = bitc::TYPE_CODE_TOKEN; break;
409 case Type::IntegerTyID:
411 Code = bitc::TYPE_CODE_INTEGER;
412 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
414 case Type::PointerTyID: {
415 PointerType *PTy = cast<PointerType>(T);
416 // POINTER: [pointee type, address space]
417 Code = bitc::TYPE_CODE_POINTER;
418 TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
419 unsigned AddressSpace = PTy->getAddressSpace();
420 TypeVals.push_back(AddressSpace);
421 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
424 case Type::FunctionTyID: {
425 FunctionType *FT = cast<FunctionType>(T);
426 // FUNCTION: [isvararg, retty, paramty x N]
427 Code = bitc::TYPE_CODE_FUNCTION;
428 TypeVals.push_back(FT->isVarArg());
429 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
430 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
431 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
432 AbbrevToUse = FunctionAbbrev;
435 case Type::StructTyID: {
436 StructType *ST = cast<StructType>(T);
437 // STRUCT: [ispacked, eltty x N]
438 TypeVals.push_back(ST->isPacked());
439 // Output all of the element types.
440 for (StructType::element_iterator I = ST->element_begin(),
441 E = ST->element_end(); I != E; ++I)
442 TypeVals.push_back(VE.getTypeID(*I));
444 if (ST->isLiteral()) {
445 Code = bitc::TYPE_CODE_STRUCT_ANON;
446 AbbrevToUse = StructAnonAbbrev;
448 if (ST->isOpaque()) {
449 Code = bitc::TYPE_CODE_OPAQUE;
451 Code = bitc::TYPE_CODE_STRUCT_NAMED;
452 AbbrevToUse = StructNamedAbbrev;
455 // Emit the name if it is present.
456 if (!ST->getName().empty())
457 WriteStringRecord(bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
458 StructNameAbbrev, Stream);
462 case Type::ArrayTyID: {
463 ArrayType *AT = cast<ArrayType>(T);
464 // ARRAY: [numelts, eltty]
465 Code = bitc::TYPE_CODE_ARRAY;
466 TypeVals.push_back(AT->getNumElements());
467 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
468 AbbrevToUse = ArrayAbbrev;
471 case Type::VectorTyID: {
472 VectorType *VT = cast<VectorType>(T);
473 // VECTOR [numelts, eltty]
474 Code = bitc::TYPE_CODE_VECTOR;
475 TypeVals.push_back(VT->getNumElements());
476 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
481 // Emit the finished record.
482 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
489 static unsigned getEncodedLinkage(const GlobalValue &GV) {
490 switch (GV.getLinkage()) {
491 case GlobalValue::ExternalLinkage:
493 case GlobalValue::WeakAnyLinkage:
495 case GlobalValue::AppendingLinkage:
497 case GlobalValue::InternalLinkage:
499 case GlobalValue::LinkOnceAnyLinkage:
501 case GlobalValue::ExternalWeakLinkage:
503 case GlobalValue::CommonLinkage:
505 case GlobalValue::PrivateLinkage:
507 case GlobalValue::WeakODRLinkage:
509 case GlobalValue::LinkOnceODRLinkage:
511 case GlobalValue::AvailableExternallyLinkage:
514 llvm_unreachable("Invalid linkage");
517 static unsigned getEncodedVisibility(const GlobalValue &GV) {
518 switch (GV.getVisibility()) {
519 case GlobalValue::DefaultVisibility: return 0;
520 case GlobalValue::HiddenVisibility: return 1;
521 case GlobalValue::ProtectedVisibility: return 2;
523 llvm_unreachable("Invalid visibility");
526 static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
527 switch (GV.getDLLStorageClass()) {
528 case GlobalValue::DefaultStorageClass: return 0;
529 case GlobalValue::DLLImportStorageClass: return 1;
530 case GlobalValue::DLLExportStorageClass: return 2;
532 llvm_unreachable("Invalid DLL storage class");
535 static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
536 switch (GV.getThreadLocalMode()) {
537 case GlobalVariable::NotThreadLocal: return 0;
538 case GlobalVariable::GeneralDynamicTLSModel: return 1;
539 case GlobalVariable::LocalDynamicTLSModel: return 2;
540 case GlobalVariable::InitialExecTLSModel: return 3;
541 case GlobalVariable::LocalExecTLSModel: return 4;
543 llvm_unreachable("Invalid TLS model");
546 static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
547 switch (C.getSelectionKind()) {
549 return bitc::COMDAT_SELECTION_KIND_ANY;
550 case Comdat::ExactMatch:
551 return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
552 case Comdat::Largest:
553 return bitc::COMDAT_SELECTION_KIND_LARGEST;
554 case Comdat::NoDuplicates:
555 return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
556 case Comdat::SameSize:
557 return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
559 llvm_unreachable("Invalid selection kind");
562 static void writeComdats(const ValueEnumerator &VE, BitstreamWriter &Stream) {
563 SmallVector<uint16_t, 64> Vals;
564 for (const Comdat *C : VE.getComdats()) {
565 // COMDAT: [selection_kind, name]
566 Vals.push_back(getEncodedComdatSelectionKind(*C));
567 size_t Size = C->getName().size();
568 assert(isUInt<16>(Size));
569 Vals.push_back(Size);
570 for (char Chr : C->getName())
571 Vals.push_back((unsigned char)Chr);
572 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
577 /// Write a record that will eventually hold the word offset of the
578 /// module-level VST. For now the offset is 0, which will be backpatched
579 /// after the real VST is written. Returns the bit offset to backpatch.
580 static uint64_t WriteValueSymbolTableForwardDecl(const ValueSymbolTable &VST,
581 BitstreamWriter &Stream) {
582 if (VST.empty()) return 0;
584 // Write a placeholder value in for the offset of the real VST,
585 // which is written after the function blocks so that it can include
586 // the offset of each function. The placeholder offset will be
587 // updated when the real VST is written.
588 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
589 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET));
590 // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
591 // hold the real VST offset. Must use fixed instead of VBR as we don't
592 // know how many VBR chunks to reserve ahead of time.
593 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
594 unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(Abbv);
596 // Emit the placeholder
597 uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0};
598 Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
600 // Compute and return the bit offset to the placeholder, which will be
601 // patched when the real VST is written. We can simply subtract the 32-bit
602 // fixed size from the current bit number to get the location to backpatch.
603 return Stream.GetCurrentBitNo() - 32;
606 /// Emit top-level description of module, including target triple, inline asm,
607 /// descriptors for global variables, and function prototype info.
608 /// Returns the bit offset to backpatch with the location of the real VST.
609 static uint64_t WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
610 BitstreamWriter &Stream) {
611 // Emit various pieces of data attached to a module.
612 if (!M->getTargetTriple().empty())
613 WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
615 const std::string &DL = M->getDataLayoutStr();
617 WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/, Stream);
618 if (!M->getModuleInlineAsm().empty())
619 WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
622 // Emit information about sections and GC, computing how many there are. Also
623 // compute the maximum alignment value.
624 std::map<std::string, unsigned> SectionMap;
625 std::map<std::string, unsigned> GCMap;
626 unsigned MaxAlignment = 0;
627 unsigned MaxGlobalType = 0;
628 for (const GlobalValue &GV : M->globals()) {
629 MaxAlignment = std::max(MaxAlignment, GV.getAlignment());
630 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
631 if (GV.hasSection()) {
632 // Give section names unique ID's.
633 unsigned &Entry = SectionMap[GV.getSection()];
635 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
637 Entry = SectionMap.size();
641 for (const Function &F : *M) {
642 MaxAlignment = std::max(MaxAlignment, F.getAlignment());
643 if (F.hasSection()) {
644 // Give section names unique ID's.
645 unsigned &Entry = SectionMap[F.getSection()];
647 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
649 Entry = SectionMap.size();
653 // Same for GC names.
654 unsigned &Entry = GCMap[F.getGC()];
656 WriteStringRecord(bitc::MODULE_CODE_GCNAME, F.getGC(),
658 Entry = GCMap.size();
663 // Emit abbrev for globals, now that we know # sections and max alignment.
664 unsigned SimpleGVarAbbrev = 0;
665 if (!M->global_empty()) {
666 // Add an abbrev for common globals with no visibility or thread localness.
667 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
668 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
669 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
670 Log2_32_Ceil(MaxGlobalType+1)));
671 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2
672 //| explicitType << 1
674 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
675 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
676 if (MaxAlignment == 0) // Alignment.
677 Abbv->Add(BitCodeAbbrevOp(0));
679 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
680 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
681 Log2_32_Ceil(MaxEncAlignment+1)));
683 if (SectionMap.empty()) // Section.
684 Abbv->Add(BitCodeAbbrevOp(0));
686 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
687 Log2_32_Ceil(SectionMap.size()+1)));
688 // Don't bother emitting vis + thread local.
689 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
692 // Emit the global variable information.
693 SmallVector<unsigned, 64> Vals;
694 for (const GlobalVariable &GV : M->globals()) {
695 unsigned AbbrevToUse = 0;
697 // GLOBALVAR: [type, isconst, initid,
698 // linkage, alignment, section, visibility, threadlocal,
699 // unnamed_addr, externally_initialized, dllstorageclass,
701 Vals.push_back(VE.getTypeID(GV.getValueType()));
702 Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
703 Vals.push_back(GV.isDeclaration() ? 0 :
704 (VE.getValueID(GV.getInitializer()) + 1));
705 Vals.push_back(getEncodedLinkage(GV));
706 Vals.push_back(Log2_32(GV.getAlignment())+1);
707 Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0);
708 if (GV.isThreadLocal() ||
709 GV.getVisibility() != GlobalValue::DefaultVisibility ||
710 GV.hasUnnamedAddr() || GV.isExternallyInitialized() ||
711 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
713 Vals.push_back(getEncodedVisibility(GV));
714 Vals.push_back(getEncodedThreadLocalMode(GV));
715 Vals.push_back(GV.hasUnnamedAddr());
716 Vals.push_back(GV.isExternallyInitialized());
717 Vals.push_back(getEncodedDLLStorageClass(GV));
718 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
720 AbbrevToUse = SimpleGVarAbbrev;
723 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
727 // Emit the function proto information.
728 for (const Function &F : *M) {
729 // FUNCTION: [type, callingconv, isproto, linkage, paramattrs, alignment,
730 // section, visibility, gc, unnamed_addr, prologuedata,
731 // dllstorageclass, comdat, prefixdata, personalityfn]
732 Vals.push_back(VE.getTypeID(F.getFunctionType()));
733 Vals.push_back(F.getCallingConv());
734 Vals.push_back(F.isDeclaration());
735 Vals.push_back(getEncodedLinkage(F));
736 Vals.push_back(VE.getAttributeID(F.getAttributes()));
737 Vals.push_back(Log2_32(F.getAlignment())+1);
738 Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0);
739 Vals.push_back(getEncodedVisibility(F));
740 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
741 Vals.push_back(F.hasUnnamedAddr());
742 Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
744 Vals.push_back(getEncodedDLLStorageClass(F));
745 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
746 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
749 F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
751 unsigned AbbrevToUse = 0;
752 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
756 // Emit the alias information.
757 for (const GlobalAlias &A : M->aliases()) {
758 // ALIAS: [alias type, aliasee val#, linkage, visibility]
759 Vals.push_back(VE.getTypeID(A.getValueType()));
760 Vals.push_back(A.getType()->getAddressSpace());
761 Vals.push_back(VE.getValueID(A.getAliasee()));
762 Vals.push_back(getEncodedLinkage(A));
763 Vals.push_back(getEncodedVisibility(A));
764 Vals.push_back(getEncodedDLLStorageClass(A));
765 Vals.push_back(getEncodedThreadLocalMode(A));
766 Vals.push_back(A.hasUnnamedAddr());
767 unsigned AbbrevToUse = 0;
768 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
772 uint64_t VSTOffsetPlaceholder =
773 WriteValueSymbolTableForwardDecl(M->getValueSymbolTable(), Stream);
774 return VSTOffsetPlaceholder;
777 static uint64_t GetOptimizationFlags(const Value *V) {
780 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
781 if (OBO->hasNoSignedWrap())
782 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
783 if (OBO->hasNoUnsignedWrap())
784 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
785 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
787 Flags |= 1 << bitc::PEO_EXACT;
788 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
789 if (FPMO->hasUnsafeAlgebra())
790 Flags |= FastMathFlags::UnsafeAlgebra;
791 if (FPMO->hasNoNaNs())
792 Flags |= FastMathFlags::NoNaNs;
793 if (FPMO->hasNoInfs())
794 Flags |= FastMathFlags::NoInfs;
795 if (FPMO->hasNoSignedZeros())
796 Flags |= FastMathFlags::NoSignedZeros;
797 if (FPMO->hasAllowReciprocal())
798 Flags |= FastMathFlags::AllowReciprocal;
804 static void WriteValueAsMetadata(const ValueAsMetadata *MD,
805 const ValueEnumerator &VE,
806 BitstreamWriter &Stream,
807 SmallVectorImpl<uint64_t> &Record) {
808 // Mimic an MDNode with a value as one operand.
809 Value *V = MD->getValue();
810 Record.push_back(VE.getTypeID(V->getType()));
811 Record.push_back(VE.getValueID(V));
812 Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
816 static void WriteMDTuple(const MDTuple *N, const ValueEnumerator &VE,
817 BitstreamWriter &Stream,
818 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
819 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
820 Metadata *MD = N->getOperand(i);
821 assert(!(MD && isa<LocalAsMetadata>(MD)) &&
822 "Unexpected function-local metadata");
823 Record.push_back(VE.getMetadataOrNullID(MD));
825 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
826 : bitc::METADATA_NODE,
831 static void WriteDILocation(const DILocation *N, const ValueEnumerator &VE,
832 BitstreamWriter &Stream,
833 SmallVectorImpl<uint64_t> &Record,
835 Record.push_back(N->isDistinct());
836 Record.push_back(N->getLine());
837 Record.push_back(N->getColumn());
838 Record.push_back(VE.getMetadataID(N->getScope()));
839 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
841 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
845 static void WriteGenericDINode(const GenericDINode *N,
846 const ValueEnumerator &VE,
847 BitstreamWriter &Stream,
848 SmallVectorImpl<uint64_t> &Record,
850 Record.push_back(N->isDistinct());
851 Record.push_back(N->getTag());
852 Record.push_back(0); // Per-tag version field; unused for now.
854 for (auto &I : N->operands())
855 Record.push_back(VE.getMetadataOrNullID(I));
857 Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
861 static uint64_t rotateSign(int64_t I) {
863 return I < 0 ? ~(U << 1) : U << 1;
866 static void WriteDISubrange(const DISubrange *N, const ValueEnumerator &,
867 BitstreamWriter &Stream,
868 SmallVectorImpl<uint64_t> &Record,
870 Record.push_back(N->isDistinct());
871 Record.push_back(N->getCount());
872 Record.push_back(rotateSign(N->getLowerBound()));
874 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
878 static void WriteDIEnumerator(const DIEnumerator *N, const ValueEnumerator &VE,
879 BitstreamWriter &Stream,
880 SmallVectorImpl<uint64_t> &Record,
882 Record.push_back(N->isDistinct());
883 Record.push_back(rotateSign(N->getValue()));
884 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
886 Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
890 static void WriteDIBasicType(const DIBasicType *N, const ValueEnumerator &VE,
891 BitstreamWriter &Stream,
892 SmallVectorImpl<uint64_t> &Record,
894 Record.push_back(N->isDistinct());
895 Record.push_back(N->getTag());
896 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
897 Record.push_back(N->getSizeInBits());
898 Record.push_back(N->getAlignInBits());
899 Record.push_back(N->getEncoding());
901 Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
905 static void WriteDIDerivedType(const DIDerivedType *N,
906 const ValueEnumerator &VE,
907 BitstreamWriter &Stream,
908 SmallVectorImpl<uint64_t> &Record,
910 Record.push_back(N->isDistinct());
911 Record.push_back(N->getTag());
912 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
913 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
914 Record.push_back(N->getLine());
915 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
916 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
917 Record.push_back(N->getSizeInBits());
918 Record.push_back(N->getAlignInBits());
919 Record.push_back(N->getOffsetInBits());
920 Record.push_back(N->getFlags());
921 Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
923 Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
927 static void WriteDICompositeType(const DICompositeType *N,
928 const ValueEnumerator &VE,
929 BitstreamWriter &Stream,
930 SmallVectorImpl<uint64_t> &Record,
932 Record.push_back(N->isDistinct());
933 Record.push_back(N->getTag());
934 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
935 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
936 Record.push_back(N->getLine());
937 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
938 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
939 Record.push_back(N->getSizeInBits());
940 Record.push_back(N->getAlignInBits());
941 Record.push_back(N->getOffsetInBits());
942 Record.push_back(N->getFlags());
943 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
944 Record.push_back(N->getRuntimeLang());
945 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
946 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
947 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
949 Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
953 static void WriteDISubroutineType(const DISubroutineType *N,
954 const ValueEnumerator &VE,
955 BitstreamWriter &Stream,
956 SmallVectorImpl<uint64_t> &Record,
958 Record.push_back(N->isDistinct());
959 Record.push_back(N->getFlags());
960 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
962 Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
966 static void WriteDIFile(const DIFile *N, const ValueEnumerator &VE,
967 BitstreamWriter &Stream,
968 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
969 Record.push_back(N->isDistinct());
970 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
971 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
973 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
977 static void WriteDICompileUnit(const DICompileUnit *N,
978 const ValueEnumerator &VE,
979 BitstreamWriter &Stream,
980 SmallVectorImpl<uint64_t> &Record,
982 assert(N->isDistinct() && "Expected distinct compile units");
983 Record.push_back(/* IsDistinct */ true);
984 Record.push_back(N->getSourceLanguage());
985 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
986 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
987 Record.push_back(N->isOptimized());
988 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
989 Record.push_back(N->getRuntimeVersion());
990 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
991 Record.push_back(N->getEmissionKind());
992 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
993 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
994 Record.push_back(VE.getMetadataOrNullID(N->getSubprograms().get()));
995 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
996 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
997 Record.push_back(N->getDWOId());
999 Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
1003 static void WriteDISubprogram(const DISubprogram *N, const ValueEnumerator &VE,
1004 BitstreamWriter &Stream,
1005 SmallVectorImpl<uint64_t> &Record,
1007 Record.push_back(N->isDistinct());
1008 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1009 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1010 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1011 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1012 Record.push_back(N->getLine());
1013 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1014 Record.push_back(N->isLocalToUnit());
1015 Record.push_back(N->isDefinition());
1016 Record.push_back(N->getScopeLine());
1017 Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
1018 Record.push_back(N->getVirtuality());
1019 Record.push_back(N->getVirtualIndex());
1020 Record.push_back(N->getFlags());
1021 Record.push_back(N->isOptimized());
1022 Record.push_back(VE.getMetadataOrNullID(N->getRawFunction()));
1023 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1024 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
1025 Record.push_back(VE.getMetadataOrNullID(N->getVariables().get()));
1027 Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
1031 static void WriteDILexicalBlock(const DILexicalBlock *N,
1032 const ValueEnumerator &VE,
1033 BitstreamWriter &Stream,
1034 SmallVectorImpl<uint64_t> &Record,
1036 Record.push_back(N->isDistinct());
1037 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1038 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1039 Record.push_back(N->getLine());
1040 Record.push_back(N->getColumn());
1042 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
1046 static void WriteDILexicalBlockFile(const DILexicalBlockFile *N,
1047 const ValueEnumerator &VE,
1048 BitstreamWriter &Stream,
1049 SmallVectorImpl<uint64_t> &Record,
1051 Record.push_back(N->isDistinct());
1052 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1053 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1054 Record.push_back(N->getDiscriminator());
1056 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
1060 static void WriteDINamespace(const DINamespace *N, const ValueEnumerator &VE,
1061 BitstreamWriter &Stream,
1062 SmallVectorImpl<uint64_t> &Record,
1064 Record.push_back(N->isDistinct());
1065 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1066 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1067 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1068 Record.push_back(N->getLine());
1070 Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
1074 static void WriteDIModule(const DIModule *N, const ValueEnumerator &VE,
1075 BitstreamWriter &Stream,
1076 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
1077 Record.push_back(N->isDistinct());
1078 for (auto &I : N->operands())
1079 Record.push_back(VE.getMetadataOrNullID(I));
1081 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
1085 static void WriteDITemplateTypeParameter(const DITemplateTypeParameter *N,
1086 const ValueEnumerator &VE,
1087 BitstreamWriter &Stream,
1088 SmallVectorImpl<uint64_t> &Record,
1090 Record.push_back(N->isDistinct());
1091 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1092 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1094 Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
1098 static void WriteDITemplateValueParameter(const DITemplateValueParameter *N,
1099 const ValueEnumerator &VE,
1100 BitstreamWriter &Stream,
1101 SmallVectorImpl<uint64_t> &Record,
1103 Record.push_back(N->isDistinct());
1104 Record.push_back(N->getTag());
1105 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1106 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1107 Record.push_back(VE.getMetadataOrNullID(N->getValue()));
1109 Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
1113 static void WriteDIGlobalVariable(const DIGlobalVariable *N,
1114 const ValueEnumerator &VE,
1115 BitstreamWriter &Stream,
1116 SmallVectorImpl<uint64_t> &Record,
1118 Record.push_back(N->isDistinct());
1119 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1120 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1121 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1122 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1123 Record.push_back(N->getLine());
1124 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1125 Record.push_back(N->isLocalToUnit());
1126 Record.push_back(N->isDefinition());
1127 Record.push_back(VE.getMetadataOrNullID(N->getRawVariable()));
1128 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
1130 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
1134 static void WriteDILocalVariable(const DILocalVariable *N,
1135 const ValueEnumerator &VE,
1136 BitstreamWriter &Stream,
1137 SmallVectorImpl<uint64_t> &Record,
1139 Record.push_back(N->isDistinct());
1140 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1141 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1142 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1143 Record.push_back(N->getLine());
1144 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1145 Record.push_back(N->getArg());
1146 Record.push_back(N->getFlags());
1148 Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
1152 static void WriteDIExpression(const DIExpression *N, const ValueEnumerator &,
1153 BitstreamWriter &Stream,
1154 SmallVectorImpl<uint64_t> &Record,
1156 Record.reserve(N->getElements().size() + 1);
1158 Record.push_back(N->isDistinct());
1159 Record.append(N->elements_begin(), N->elements_end());
1161 Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
1165 static void WriteDIObjCProperty(const DIObjCProperty *N,
1166 const ValueEnumerator &VE,
1167 BitstreamWriter &Stream,
1168 SmallVectorImpl<uint64_t> &Record,
1170 Record.push_back(N->isDistinct());
1171 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1172 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1173 Record.push_back(N->getLine());
1174 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
1175 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
1176 Record.push_back(N->getAttributes());
1177 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1179 Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
1183 static void WriteDIImportedEntity(const DIImportedEntity *N,
1184 const ValueEnumerator &VE,
1185 BitstreamWriter &Stream,
1186 SmallVectorImpl<uint64_t> &Record,
1188 Record.push_back(N->isDistinct());
1189 Record.push_back(N->getTag());
1190 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1191 Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
1192 Record.push_back(N->getLine());
1193 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1195 Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
1199 static void WriteModuleMetadata(const Module *M,
1200 const ValueEnumerator &VE,
1201 BitstreamWriter &Stream) {
1202 const auto &MDs = VE.getMDs();
1203 if (MDs.empty() && M->named_metadata_empty())
1206 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
1208 unsigned MDSAbbrev = 0;
1209 if (VE.hasMDString()) {
1210 // Abbrev for METADATA_STRING.
1211 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1212 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING));
1213 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1214 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1215 MDSAbbrev = Stream.EmitAbbrev(Abbv);
1218 // Initialize MDNode abbreviations.
1219 #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
1220 #include "llvm/IR/Metadata.def"
1222 if (VE.hasDILocation()) {
1223 // Abbrev for METADATA_LOCATION.
1225 // Assume the column is usually under 128, and always output the inlined-at
1226 // location (it's never more expensive than building an array size 1).
1227 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1228 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
1229 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1230 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1231 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1232 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1233 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1234 DILocationAbbrev = Stream.EmitAbbrev(Abbv);
1237 if (VE.hasGenericDINode()) {
1238 // Abbrev for METADATA_GENERIC_DEBUG.
1240 // Assume the column is usually under 128, and always output the inlined-at
1241 // location (it's never more expensive than building an array size 1).
1242 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1243 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
1244 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1245 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1246 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1247 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1248 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1249 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1250 GenericDINodeAbbrev = Stream.EmitAbbrev(Abbv);
1253 unsigned NameAbbrev = 0;
1254 if (!M->named_metadata_empty()) {
1255 // Abbrev for METADATA_NAME.
1256 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1257 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
1258 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1259 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1260 NameAbbrev = Stream.EmitAbbrev(Abbv);
1263 SmallVector<uint64_t, 64> Record;
1264 for (const Metadata *MD : MDs) {
1265 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
1266 assert(N->isResolved() && "Expected forward references to be resolved");
1268 switch (N->getMetadataID()) {
1270 llvm_unreachable("Invalid MDNode subclass");
1271 #define HANDLE_MDNODE_LEAF(CLASS) \
1272 case Metadata::CLASS##Kind: \
1273 Write##CLASS(cast<CLASS>(N), VE, Stream, Record, CLASS##Abbrev); \
1275 #include "llvm/IR/Metadata.def"
1278 if (const auto *MDC = dyn_cast<ConstantAsMetadata>(MD)) {
1279 WriteValueAsMetadata(MDC, VE, Stream, Record);
1282 const MDString *MDS = cast<MDString>(MD);
1283 // Code: [strchar x N]
1284 Record.append(MDS->bytes_begin(), MDS->bytes_end());
1286 // Emit the finished record.
1287 Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev);
1291 // Write named metadata.
1292 for (const NamedMDNode &NMD : M->named_metadata()) {
1294 StringRef Str = NMD.getName();
1295 Record.append(Str.bytes_begin(), Str.bytes_end());
1296 Stream.EmitRecord(bitc::METADATA_NAME, Record, NameAbbrev);
1299 // Write named metadata operands.
1300 for (const MDNode *N : NMD.operands())
1301 Record.push_back(VE.getMetadataID(N));
1302 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
1309 static void WriteFunctionLocalMetadata(const Function &F,
1310 const ValueEnumerator &VE,
1311 BitstreamWriter &Stream) {
1312 bool StartedMetadataBlock = false;
1313 SmallVector<uint64_t, 64> Record;
1314 const SmallVectorImpl<const LocalAsMetadata *> &MDs =
1315 VE.getFunctionLocalMDs();
1316 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
1317 assert(MDs[i] && "Expected valid function-local metadata");
1318 if (!StartedMetadataBlock) {
1319 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
1320 StartedMetadataBlock = true;
1322 WriteValueAsMetadata(MDs[i], VE, Stream, Record);
1325 if (StartedMetadataBlock)
1329 static void WriteMetadataAttachment(const Function &F,
1330 const ValueEnumerator &VE,
1331 BitstreamWriter &Stream) {
1332 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
1334 SmallVector<uint64_t, 64> Record;
1336 // Write metadata attachments
1337 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
1338 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1339 F.getAllMetadata(MDs);
1341 for (const auto &I : MDs) {
1342 Record.push_back(I.first);
1343 Record.push_back(VE.getMetadataID(I.second));
1345 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
1349 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1350 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1353 I->getAllMetadataOtherThanDebugLoc(MDs);
1355 // If no metadata, ignore instruction.
1356 if (MDs.empty()) continue;
1358 Record.push_back(VE.getInstructionID(I));
1360 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
1361 Record.push_back(MDs[i].first);
1362 Record.push_back(VE.getMetadataID(MDs[i].second));
1364 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
1371 static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) {
1372 SmallVector<uint64_t, 64> Record;
1374 // Write metadata kinds
1375 // METADATA_KIND - [n x [id, name]]
1376 SmallVector<StringRef, 8> Names;
1377 M->getMDKindNames(Names);
1379 if (Names.empty()) return;
1381 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
1383 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
1384 Record.push_back(MDKindID);
1385 StringRef KName = Names[MDKindID];
1386 Record.append(KName.begin(), KName.end());
1388 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
1395 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
1396 if ((int64_t)V >= 0)
1397 Vals.push_back(V << 1);
1399 Vals.push_back((-V << 1) | 1);
1402 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
1403 const ValueEnumerator &VE,
1404 BitstreamWriter &Stream, bool isGlobal) {
1405 if (FirstVal == LastVal) return;
1407 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
1409 unsigned AggregateAbbrev = 0;
1410 unsigned String8Abbrev = 0;
1411 unsigned CString7Abbrev = 0;
1412 unsigned CString6Abbrev = 0;
1413 // If this is a constant pool for the module, emit module-specific abbrevs.
1415 // Abbrev for CST_CODE_AGGREGATE.
1416 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1417 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
1418 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1419 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
1420 AggregateAbbrev = Stream.EmitAbbrev(Abbv);
1422 // Abbrev for CST_CODE_STRING.
1423 Abbv = new BitCodeAbbrev();
1424 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
1425 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1426 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1427 String8Abbrev = Stream.EmitAbbrev(Abbv);
1428 // Abbrev for CST_CODE_CSTRING.
1429 Abbv = new BitCodeAbbrev();
1430 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
1431 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1432 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1433 CString7Abbrev = Stream.EmitAbbrev(Abbv);
1434 // Abbrev for CST_CODE_CSTRING.
1435 Abbv = new BitCodeAbbrev();
1436 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
1437 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1438 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1439 CString6Abbrev = Stream.EmitAbbrev(Abbv);
1442 SmallVector<uint64_t, 64> Record;
1444 const ValueEnumerator::ValueList &Vals = VE.getValues();
1445 Type *LastTy = nullptr;
1446 for (unsigned i = FirstVal; i != LastVal; ++i) {
1447 const Value *V = Vals[i].first;
1448 // If we need to switch types, do so now.
1449 if (V->getType() != LastTy) {
1450 LastTy = V->getType();
1451 Record.push_back(VE.getTypeID(LastTy));
1452 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
1453 CONSTANTS_SETTYPE_ABBREV);
1457 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1458 Record.push_back(unsigned(IA->hasSideEffects()) |
1459 unsigned(IA->isAlignStack()) << 1 |
1460 unsigned(IA->getDialect()&1) << 2);
1462 // Add the asm string.
1463 const std::string &AsmStr = IA->getAsmString();
1464 Record.push_back(AsmStr.size());
1465 Record.append(AsmStr.begin(), AsmStr.end());
1467 // Add the constraint string.
1468 const std::string &ConstraintStr = IA->getConstraintString();
1469 Record.push_back(ConstraintStr.size());
1470 Record.append(ConstraintStr.begin(), ConstraintStr.end());
1471 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
1475 const Constant *C = cast<Constant>(V);
1476 unsigned Code = -1U;
1477 unsigned AbbrevToUse = 0;
1478 if (C->isNullValue()) {
1479 Code = bitc::CST_CODE_NULL;
1480 } else if (isa<UndefValue>(C)) {
1481 Code = bitc::CST_CODE_UNDEF;
1482 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
1483 if (IV->getBitWidth() <= 64) {
1484 uint64_t V = IV->getSExtValue();
1485 emitSignedInt64(Record, V);
1486 Code = bitc::CST_CODE_INTEGER;
1487 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
1488 } else { // Wide integers, > 64 bits in size.
1489 // We have an arbitrary precision integer value to write whose
1490 // bit width is > 64. However, in canonical unsigned integer
1491 // format it is likely that the high bits are going to be zero.
1492 // So, we only write the number of active words.
1493 unsigned NWords = IV->getValue().getActiveWords();
1494 const uint64_t *RawWords = IV->getValue().getRawData();
1495 for (unsigned i = 0; i != NWords; ++i) {
1496 emitSignedInt64(Record, RawWords[i]);
1498 Code = bitc::CST_CODE_WIDE_INTEGER;
1500 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
1501 Code = bitc::CST_CODE_FLOAT;
1502 Type *Ty = CFP->getType();
1503 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
1504 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
1505 } else if (Ty->isX86_FP80Ty()) {
1506 // api needed to prevent premature destruction
1507 // bits are not in the same order as a normal i80 APInt, compensate.
1508 APInt api = CFP->getValueAPF().bitcastToAPInt();
1509 const uint64_t *p = api.getRawData();
1510 Record.push_back((p[1] << 48) | (p[0] >> 16));
1511 Record.push_back(p[0] & 0xffffLL);
1512 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
1513 APInt api = CFP->getValueAPF().bitcastToAPInt();
1514 const uint64_t *p = api.getRawData();
1515 Record.push_back(p[0]);
1516 Record.push_back(p[1]);
1518 assert (0 && "Unknown FP type!");
1520 } else if (isa<ConstantDataSequential>(C) &&
1521 cast<ConstantDataSequential>(C)->isString()) {
1522 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
1523 // Emit constant strings specially.
1524 unsigned NumElts = Str->getNumElements();
1525 // If this is a null-terminated string, use the denser CSTRING encoding.
1526 if (Str->isCString()) {
1527 Code = bitc::CST_CODE_CSTRING;
1528 --NumElts; // Don't encode the null, which isn't allowed by char6.
1530 Code = bitc::CST_CODE_STRING;
1531 AbbrevToUse = String8Abbrev;
1533 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
1534 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
1535 for (unsigned i = 0; i != NumElts; ++i) {
1536 unsigned char V = Str->getElementAsInteger(i);
1537 Record.push_back(V);
1538 isCStr7 &= (V & 128) == 0;
1540 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
1544 AbbrevToUse = CString6Abbrev;
1546 AbbrevToUse = CString7Abbrev;
1547 } else if (const ConstantDataSequential *CDS =
1548 dyn_cast<ConstantDataSequential>(C)) {
1549 Code = bitc::CST_CODE_DATA;
1550 Type *EltTy = CDS->getType()->getElementType();
1551 if (isa<IntegerType>(EltTy)) {
1552 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
1553 Record.push_back(CDS->getElementAsInteger(i));
1554 } else if (EltTy->isFloatTy()) {
1555 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1556 union { float F; uint32_t I; };
1557 F = CDS->getElementAsFloat(i);
1558 Record.push_back(I);
1561 assert(EltTy->isDoubleTy() && "Unknown ConstantData element type");
1562 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1563 union { double F; uint64_t I; };
1564 F = CDS->getElementAsDouble(i);
1565 Record.push_back(I);
1568 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
1569 isa<ConstantVector>(C)) {
1570 Code = bitc::CST_CODE_AGGREGATE;
1571 for (const Value *Op : C->operands())
1572 Record.push_back(VE.getValueID(Op));
1573 AbbrevToUse = AggregateAbbrev;
1574 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1575 switch (CE->getOpcode()) {
1577 if (Instruction::isCast(CE->getOpcode())) {
1578 Code = bitc::CST_CODE_CE_CAST;
1579 Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
1580 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1581 Record.push_back(VE.getValueID(C->getOperand(0)));
1582 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
1584 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
1585 Code = bitc::CST_CODE_CE_BINOP;
1586 Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
1587 Record.push_back(VE.getValueID(C->getOperand(0)));
1588 Record.push_back(VE.getValueID(C->getOperand(1)));
1589 uint64_t Flags = GetOptimizationFlags(CE);
1591 Record.push_back(Flags);
1594 case Instruction::GetElementPtr: {
1595 Code = bitc::CST_CODE_CE_GEP;
1596 const auto *GO = cast<GEPOperator>(C);
1597 if (GO->isInBounds())
1598 Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
1599 Record.push_back(VE.getTypeID(GO->getSourceElementType()));
1600 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
1601 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
1602 Record.push_back(VE.getValueID(C->getOperand(i)));
1606 case Instruction::Select:
1607 Code = bitc::CST_CODE_CE_SELECT;
1608 Record.push_back(VE.getValueID(C->getOperand(0)));
1609 Record.push_back(VE.getValueID(C->getOperand(1)));
1610 Record.push_back(VE.getValueID(C->getOperand(2)));
1612 case Instruction::ExtractElement:
1613 Code = bitc::CST_CODE_CE_EXTRACTELT;
1614 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1615 Record.push_back(VE.getValueID(C->getOperand(0)));
1616 Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
1617 Record.push_back(VE.getValueID(C->getOperand(1)));
1619 case Instruction::InsertElement:
1620 Code = bitc::CST_CODE_CE_INSERTELT;
1621 Record.push_back(VE.getValueID(C->getOperand(0)));
1622 Record.push_back(VE.getValueID(C->getOperand(1)));
1623 Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
1624 Record.push_back(VE.getValueID(C->getOperand(2)));
1626 case Instruction::ShuffleVector:
1627 // If the return type and argument types are the same, this is a
1628 // standard shufflevector instruction. If the types are different,
1629 // then the shuffle is widening or truncating the input vectors, and
1630 // the argument type must also be encoded.
1631 if (C->getType() == C->getOperand(0)->getType()) {
1632 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
1634 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
1635 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1637 Record.push_back(VE.getValueID(C->getOperand(0)));
1638 Record.push_back(VE.getValueID(C->getOperand(1)));
1639 Record.push_back(VE.getValueID(C->getOperand(2)));
1641 case Instruction::ICmp:
1642 case Instruction::FCmp:
1643 Code = bitc::CST_CODE_CE_CMP;
1644 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1645 Record.push_back(VE.getValueID(C->getOperand(0)));
1646 Record.push_back(VE.getValueID(C->getOperand(1)));
1647 Record.push_back(CE->getPredicate());
1650 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
1651 Code = bitc::CST_CODE_BLOCKADDRESS;
1652 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
1653 Record.push_back(VE.getValueID(BA->getFunction()));
1654 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
1659 llvm_unreachable("Unknown constant!");
1661 Stream.EmitRecord(Code, Record, AbbrevToUse);
1668 static void WriteModuleConstants(const ValueEnumerator &VE,
1669 BitstreamWriter &Stream) {
1670 const ValueEnumerator::ValueList &Vals = VE.getValues();
1672 // Find the first constant to emit, which is the first non-globalvalue value.
1673 // We know globalvalues have been emitted by WriteModuleInfo.
1674 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1675 if (!isa<GlobalValue>(Vals[i].first)) {
1676 WriteConstants(i, Vals.size(), VE, Stream, true);
1682 /// PushValueAndType - The file has to encode both the value and type id for
1683 /// many values, because we need to know what type to create for forward
1684 /// references. However, most operands are not forward references, so this type
1685 /// field is not needed.
1687 /// This function adds V's value ID to Vals. If the value ID is higher than the
1688 /// instruction ID, then it is a forward reference, and it also includes the
1689 /// type ID. The value ID that is written is encoded relative to the InstID.
1690 static bool PushValueAndType(const Value *V, unsigned InstID,
1691 SmallVectorImpl<unsigned> &Vals,
1692 ValueEnumerator &VE) {
1693 unsigned ValID = VE.getValueID(V);
1694 // Make encoding relative to the InstID.
1695 Vals.push_back(InstID - ValID);
1696 if (ValID >= InstID) {
1697 Vals.push_back(VE.getTypeID(V->getType()));
1703 /// pushValue - Like PushValueAndType, but where the type of the value is
1704 /// omitted (perhaps it was already encoded in an earlier operand).
1705 static void pushValue(const Value *V, unsigned InstID,
1706 SmallVectorImpl<unsigned> &Vals,
1707 ValueEnumerator &VE) {
1708 unsigned ValID = VE.getValueID(V);
1709 Vals.push_back(InstID - ValID);
1712 static void pushValueSigned(const Value *V, unsigned InstID,
1713 SmallVectorImpl<uint64_t> &Vals,
1714 ValueEnumerator &VE) {
1715 unsigned ValID = VE.getValueID(V);
1716 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
1717 emitSignedInt64(Vals, diff);
1720 /// WriteInstruction - Emit an instruction to the specified stream.
1721 static void WriteInstruction(const Instruction &I, unsigned InstID,
1722 ValueEnumerator &VE, BitstreamWriter &Stream,
1723 SmallVectorImpl<unsigned> &Vals) {
1725 unsigned AbbrevToUse = 0;
1726 VE.setInstructionID(&I);
1727 switch (I.getOpcode()) {
1729 if (Instruction::isCast(I.getOpcode())) {
1730 Code = bitc::FUNC_CODE_INST_CAST;
1731 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1732 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
1733 Vals.push_back(VE.getTypeID(I.getType()));
1734 Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
1736 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
1737 Code = bitc::FUNC_CODE_INST_BINOP;
1738 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1739 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
1740 pushValue(I.getOperand(1), InstID, Vals, VE);
1741 Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
1742 uint64_t Flags = GetOptimizationFlags(&I);
1744 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
1745 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
1746 Vals.push_back(Flags);
1751 case Instruction::GetElementPtr: {
1752 Code = bitc::FUNC_CODE_INST_GEP;
1753 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
1754 auto &GEPInst = cast<GetElementPtrInst>(I);
1755 Vals.push_back(GEPInst.isInBounds());
1756 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
1757 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1758 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1761 case Instruction::ExtractValue: {
1762 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
1763 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1764 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
1765 Vals.append(EVI->idx_begin(), EVI->idx_end());
1768 case Instruction::InsertValue: {
1769 Code = bitc::FUNC_CODE_INST_INSERTVAL;
1770 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1771 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1772 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
1773 Vals.append(IVI->idx_begin(), IVI->idx_end());
1776 case Instruction::Select:
1777 Code = bitc::FUNC_CODE_INST_VSELECT;
1778 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1779 pushValue(I.getOperand(2), InstID, Vals, VE);
1780 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1782 case Instruction::ExtractElement:
1783 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
1784 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1785 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1787 case Instruction::InsertElement:
1788 Code = bitc::FUNC_CODE_INST_INSERTELT;
1789 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1790 pushValue(I.getOperand(1), InstID, Vals, VE);
1791 PushValueAndType(I.getOperand(2), InstID, Vals, VE);
1793 case Instruction::ShuffleVector:
1794 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
1795 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1796 pushValue(I.getOperand(1), InstID, Vals, VE);
1797 pushValue(I.getOperand(2), InstID, Vals, VE);
1799 case Instruction::ICmp:
1800 case Instruction::FCmp: {
1801 // compare returning Int1Ty or vector of Int1Ty
1802 Code = bitc::FUNC_CODE_INST_CMP2;
1803 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1804 pushValue(I.getOperand(1), InstID, Vals, VE);
1805 Vals.push_back(cast<CmpInst>(I).getPredicate());
1806 uint64_t Flags = GetOptimizationFlags(&I);
1808 Vals.push_back(Flags);
1812 case Instruction::Ret:
1814 Code = bitc::FUNC_CODE_INST_RET;
1815 unsigned NumOperands = I.getNumOperands();
1816 if (NumOperands == 0)
1817 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
1818 else if (NumOperands == 1) {
1819 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1820 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
1822 for (unsigned i = 0, e = NumOperands; i != e; ++i)
1823 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1827 case Instruction::Br:
1829 Code = bitc::FUNC_CODE_INST_BR;
1830 const BranchInst &II = cast<BranchInst>(I);
1831 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
1832 if (II.isConditional()) {
1833 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
1834 pushValue(II.getCondition(), InstID, Vals, VE);
1838 case Instruction::Switch:
1840 Code = bitc::FUNC_CODE_INST_SWITCH;
1841 const SwitchInst &SI = cast<SwitchInst>(I);
1842 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
1843 pushValue(SI.getCondition(), InstID, Vals, VE);
1844 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
1845 for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
1847 Vals.push_back(VE.getValueID(i.getCaseValue()));
1848 Vals.push_back(VE.getValueID(i.getCaseSuccessor()));
1852 case Instruction::IndirectBr:
1853 Code = bitc::FUNC_CODE_INST_INDIRECTBR;
1854 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1855 // Encode the address operand as relative, but not the basic blocks.
1856 pushValue(I.getOperand(0), InstID, Vals, VE);
1857 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
1858 Vals.push_back(VE.getValueID(I.getOperand(i)));
1861 case Instruction::Invoke: {
1862 const InvokeInst *II = cast<InvokeInst>(&I);
1863 const Value *Callee = II->getCalledValue();
1864 FunctionType *FTy = II->getFunctionType();
1865 Code = bitc::FUNC_CODE_INST_INVOKE;
1867 Vals.push_back(VE.getAttributeID(II->getAttributes()));
1868 Vals.push_back(II->getCallingConv() | 1 << 13);
1869 Vals.push_back(VE.getValueID(II->getNormalDest()));
1870 Vals.push_back(VE.getValueID(II->getUnwindDest()));
1871 Vals.push_back(VE.getTypeID(FTy));
1872 PushValueAndType(Callee, InstID, Vals, VE);
1874 // Emit value #'s for the fixed parameters.
1875 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1876 pushValue(I.getOperand(i), InstID, Vals, VE); // fixed param.
1878 // Emit type/value pairs for varargs params.
1879 if (FTy->isVarArg()) {
1880 for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
1882 PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
1886 case Instruction::Resume:
1887 Code = bitc::FUNC_CODE_INST_RESUME;
1888 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1890 case Instruction::CleanupRet: {
1891 Code = bitc::FUNC_CODE_INST_CLEANUPRET;
1892 const auto &CRI = cast<CleanupReturnInst>(I);
1893 pushValue(CRI.getCleanupPad(), InstID, Vals, VE);
1894 if (CRI.hasUnwindDest())
1895 Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
1898 case Instruction::CatchRet: {
1899 Code = bitc::FUNC_CODE_INST_CATCHRET;
1900 const auto &CRI = cast<CatchReturnInst>(I);
1901 pushValue(CRI.getCatchPad(), InstID, Vals, VE);
1902 Vals.push_back(VE.getValueID(CRI.getSuccessor()));
1905 case Instruction::CatchPad: {
1906 Code = bitc::FUNC_CODE_INST_CATCHPAD;
1907 const auto &CPI = cast<CatchPadInst>(I);
1908 Vals.push_back(VE.getValueID(CPI.getNormalDest()));
1909 Vals.push_back(VE.getValueID(CPI.getUnwindDest()));
1910 unsigned NumArgOperands = CPI.getNumArgOperands();
1911 Vals.push_back(NumArgOperands);
1912 for (unsigned Op = 0; Op != NumArgOperands; ++Op)
1913 PushValueAndType(CPI.getArgOperand(Op), InstID, Vals, VE);
1916 case Instruction::TerminatePad: {
1917 Code = bitc::FUNC_CODE_INST_TERMINATEPAD;
1918 const auto &TPI = cast<TerminatePadInst>(I);
1919 Vals.push_back(TPI.hasUnwindDest());
1920 if (TPI.hasUnwindDest())
1921 Vals.push_back(VE.getValueID(TPI.getUnwindDest()));
1922 unsigned NumArgOperands = TPI.getNumArgOperands();
1923 Vals.push_back(NumArgOperands);
1924 for (unsigned Op = 0; Op != NumArgOperands; ++Op)
1925 PushValueAndType(TPI.getArgOperand(Op), InstID, Vals, VE);
1928 case Instruction::CleanupPad: {
1929 Code = bitc::FUNC_CODE_INST_CLEANUPPAD;
1930 const auto &CPI = cast<CleanupPadInst>(I);
1931 unsigned NumOperands = CPI.getNumOperands();
1932 Vals.push_back(NumOperands);
1933 for (unsigned Op = 0; Op != NumOperands; ++Op)
1934 PushValueAndType(CPI.getOperand(Op), InstID, Vals, VE);
1937 case Instruction::CatchEndPad: {
1938 Code = bitc::FUNC_CODE_INST_CATCHENDPAD;
1939 const auto &CEPI = cast<CatchEndPadInst>(I);
1940 if (CEPI.hasUnwindDest())
1941 Vals.push_back(VE.getValueID(CEPI.getUnwindDest()));
1944 case Instruction::CleanupEndPad: {
1945 Code = bitc::FUNC_CODE_INST_CLEANUPENDPAD;
1946 const auto &CEPI = cast<CleanupEndPadInst>(I);
1947 pushValue(CEPI.getCleanupPad(), InstID, Vals, VE);
1948 if (CEPI.hasUnwindDest())
1949 Vals.push_back(VE.getValueID(CEPI.getUnwindDest()));
1952 case Instruction::Unreachable:
1953 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
1954 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
1957 case Instruction::PHI: {
1958 const PHINode &PN = cast<PHINode>(I);
1959 Code = bitc::FUNC_CODE_INST_PHI;
1960 // With the newer instruction encoding, forward references could give
1961 // negative valued IDs. This is most common for PHIs, so we use
1963 SmallVector<uint64_t, 128> Vals64;
1964 Vals64.push_back(VE.getTypeID(PN.getType()));
1965 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1966 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64, VE);
1967 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
1969 // Emit a Vals64 vector and exit.
1970 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
1975 case Instruction::LandingPad: {
1976 const LandingPadInst &LP = cast<LandingPadInst>(I);
1977 Code = bitc::FUNC_CODE_INST_LANDINGPAD;
1978 Vals.push_back(VE.getTypeID(LP.getType()));
1979 Vals.push_back(LP.isCleanup());
1980 Vals.push_back(LP.getNumClauses());
1981 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
1983 Vals.push_back(LandingPadInst::Catch);
1985 Vals.push_back(LandingPadInst::Filter);
1986 PushValueAndType(LP.getClause(I), InstID, Vals, VE);
1991 case Instruction::Alloca: {
1992 Code = bitc::FUNC_CODE_INST_ALLOCA;
1993 const AllocaInst &AI = cast<AllocaInst>(I);
1994 Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
1995 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1996 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
1997 unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
1998 assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
1999 "not enough bits for maximum alignment");
2000 assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
2001 AlignRecord |= AI.isUsedWithInAlloca() << 5;
2002 AlignRecord |= 1 << 6;
2003 // Reserve bit 7 for SwiftError flag.
2004 // AlignRecord |= AI.isSwiftError() << 7;
2005 Vals.push_back(AlignRecord);
2009 case Instruction::Load:
2010 if (cast<LoadInst>(I).isAtomic()) {
2011 Code = bitc::FUNC_CODE_INST_LOADATOMIC;
2012 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
2014 Code = bitc::FUNC_CODE_INST_LOAD;
2015 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) // ptr
2016 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
2018 Vals.push_back(VE.getTypeID(I.getType()));
2019 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
2020 Vals.push_back(cast<LoadInst>(I).isVolatile());
2021 if (cast<LoadInst>(I).isAtomic()) {
2022 Vals.push_back(GetEncodedOrdering(cast<LoadInst>(I).getOrdering()));
2023 Vals.push_back(GetEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
2026 case Instruction::Store:
2027 if (cast<StoreInst>(I).isAtomic())
2028 Code = bitc::FUNC_CODE_INST_STOREATOMIC;
2030 Code = bitc::FUNC_CODE_INST_STORE;
2031 PushValueAndType(I.getOperand(1), InstID, Vals, VE); // ptrty + ptr
2032 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // valty + val
2033 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
2034 Vals.push_back(cast<StoreInst>(I).isVolatile());
2035 if (cast<StoreInst>(I).isAtomic()) {
2036 Vals.push_back(GetEncodedOrdering(cast<StoreInst>(I).getOrdering()));
2037 Vals.push_back(GetEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
2040 case Instruction::AtomicCmpXchg:
2041 Code = bitc::FUNC_CODE_INST_CMPXCHG;
2042 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr
2043 PushValueAndType(I.getOperand(1), InstID, Vals, VE); // cmp.
2044 pushValue(I.getOperand(2), InstID, Vals, VE); // newval.
2045 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
2046 Vals.push_back(GetEncodedOrdering(
2047 cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
2048 Vals.push_back(GetEncodedSynchScope(
2049 cast<AtomicCmpXchgInst>(I).getSynchScope()));
2050 Vals.push_back(GetEncodedOrdering(
2051 cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
2052 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
2054 case Instruction::AtomicRMW:
2055 Code = bitc::FUNC_CODE_INST_ATOMICRMW;
2056 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr
2057 pushValue(I.getOperand(1), InstID, Vals, VE); // val.
2058 Vals.push_back(GetEncodedRMWOperation(
2059 cast<AtomicRMWInst>(I).getOperation()));
2060 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
2061 Vals.push_back(GetEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
2062 Vals.push_back(GetEncodedSynchScope(
2063 cast<AtomicRMWInst>(I).getSynchScope()));
2065 case Instruction::Fence:
2066 Code = bitc::FUNC_CODE_INST_FENCE;
2067 Vals.push_back(GetEncodedOrdering(cast<FenceInst>(I).getOrdering()));
2068 Vals.push_back(GetEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
2070 case Instruction::Call: {
2071 const CallInst &CI = cast<CallInst>(I);
2072 FunctionType *FTy = CI.getFunctionType();
2074 Code = bitc::FUNC_CODE_INST_CALL;
2076 Vals.push_back(VE.getAttributeID(CI.getAttributes()));
2077 Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall()) |
2078 unsigned(CI.isMustTailCall()) << 14 | 1 << 15);
2079 Vals.push_back(VE.getTypeID(FTy));
2080 PushValueAndType(CI.getCalledValue(), InstID, Vals, VE); // Callee
2082 // Emit value #'s for the fixed parameters.
2083 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
2084 // Check for labels (can happen with asm labels).
2085 if (FTy->getParamType(i)->isLabelTy())
2086 Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
2088 pushValue(CI.getArgOperand(i), InstID, Vals, VE); // fixed param.
2091 // Emit type/value pairs for varargs params.
2092 if (FTy->isVarArg()) {
2093 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
2095 PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE); // varargs
2099 case Instruction::VAArg:
2100 Code = bitc::FUNC_CODE_INST_VAARG;
2101 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
2102 pushValue(I.getOperand(0), InstID, Vals, VE); // valist.
2103 Vals.push_back(VE.getTypeID(I.getType())); // restype.
2107 Stream.EmitRecord(Code, Vals, AbbrevToUse);
2111 enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 };
2113 /// Determine the encoding to use for the given string name and length.
2114 static StringEncoding getStringEncoding(const char *Str, unsigned StrLen) {
2115 bool isChar6 = true;
2116 for (const char *C = Str, *E = C + StrLen; C != E; ++C) {
2118 isChar6 = BitCodeAbbrevOp::isChar6(*C);
2119 if ((unsigned char)*C & 128)
2120 // don't bother scanning the rest.
2129 /// Emit names for globals/functions etc. The VSTOffsetPlaceholder,
2130 /// BitcodeStartBit and FunctionIndex are only passed for the module-level
2131 /// VST, where we are including a function bitcode index and need to
2132 /// backpatch the VST forward declaration record.
2133 static void WriteValueSymbolTable(
2134 const ValueSymbolTable &VST, const ValueEnumerator &VE,
2135 BitstreamWriter &Stream, uint64_t VSTOffsetPlaceholder = 0,
2136 uint64_t BitcodeStartBit = 0,
2137 DenseMap<const Function *, uint64_t> *FunctionIndex = nullptr) {
2139 // WriteValueSymbolTableForwardDecl should have returned early as
2140 // well. Ensure this handling remains in sync by asserting that
2141 // the placeholder offset is not set.
2142 assert(VSTOffsetPlaceholder == 0);
2146 if (VSTOffsetPlaceholder > 0) {
2147 // Get the offset of the VST we are writing, and backpatch it into
2148 // the VST forward declaration record.
2149 uint64_t VSTOffset = Stream.GetCurrentBitNo();
2150 // The BitcodeStartBit was the stream offset of the actual bitcode
2151 // (e.g. excluding any initial darwin header).
2152 VSTOffset -= BitcodeStartBit;
2153 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
2154 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32);
2157 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
2159 // For the module-level VST, add abbrev Ids for the VST_CODE_FNENTRY
2160 // records, which are not used in the per-function VSTs.
2161 unsigned FnEntry8BitAbbrev;
2162 unsigned FnEntry7BitAbbrev;
2163 unsigned FnEntry6BitAbbrev;
2164 if (VSTOffsetPlaceholder > 0) {
2165 // 8-bit fixed-width VST_FNENTRY function strings.
2166 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2167 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2168 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2169 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2170 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2171 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2172 FnEntry8BitAbbrev = Stream.EmitAbbrev(Abbv);
2174 // 7-bit fixed width VST_FNENTRY function strings.
2175 Abbv = new BitCodeAbbrev();
2176 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2177 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2178 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2179 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2180 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2181 FnEntry7BitAbbrev = Stream.EmitAbbrev(Abbv);
2183 // 6-bit char6 VST_FNENTRY function strings.
2184 Abbv = new BitCodeAbbrev();
2185 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2186 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2187 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2188 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2189 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2190 FnEntry6BitAbbrev = Stream.EmitAbbrev(Abbv);
2193 // FIXME: Set up the abbrev, we know how many values there are!
2194 // FIXME: We know if the type names can use 7-bit ascii.
2195 SmallVector<unsigned, 64> NameVals;
2197 for (const ValueName &Name : VST) {
2198 // Figure out the encoding to use for the name.
2199 StringEncoding Bits =
2200 getStringEncoding(Name.getKeyData(), Name.getKeyLength());
2202 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
2203 NameVals.push_back(VE.getValueID(Name.getValue()));
2205 Function *F = dyn_cast<Function>(Name.getValue());
2207 // If value is an alias, need to get the aliased base object to
2208 // see if it is a function.
2209 auto *GA = dyn_cast<GlobalAlias>(Name.getValue());
2210 if (GA && GA->getBaseObject())
2211 F = dyn_cast<Function>(GA->getBaseObject());
2214 // VST_ENTRY: [valueid, namechar x N]
2215 // VST_FNENTRY: [valueid, funcoffset, namechar x N]
2216 // VST_BBENTRY: [bbid, namechar x N]
2218 if (isa<BasicBlock>(Name.getValue())) {
2219 Code = bitc::VST_CODE_BBENTRY;
2220 if (Bits == SE_Char6)
2221 AbbrevToUse = VST_BBENTRY_6_ABBREV;
2222 } else if (F && !F->isDeclaration()) {
2223 // Must be the module-level VST, where we pass in the Index and
2224 // have a VSTOffsetPlaceholder. The function-level VST should not
2225 // contain any Function symbols.
2226 assert(FunctionIndex);
2227 assert(VSTOffsetPlaceholder > 0);
2229 // Save the word offset of the function (from the start of the
2230 // actual bitcode written to the stream).
2231 assert(FunctionIndex->count(F) == 1);
2232 uint64_t BitcodeIndex = (*FunctionIndex)[F] - BitcodeStartBit;
2233 assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
2234 NameVals.push_back(BitcodeIndex / 32);
2236 Code = bitc::VST_CODE_FNENTRY;
2237 AbbrevToUse = FnEntry8BitAbbrev;
2238 if (Bits == SE_Char6)
2239 AbbrevToUse = FnEntry6BitAbbrev;
2240 else if (Bits == SE_Fixed7)
2241 AbbrevToUse = FnEntry7BitAbbrev;
2243 Code = bitc::VST_CODE_ENTRY;
2244 if (Bits == SE_Char6)
2245 AbbrevToUse = VST_ENTRY_6_ABBREV;
2246 else if (Bits == SE_Fixed7)
2247 AbbrevToUse = VST_ENTRY_7_ABBREV;
2250 for (const char *P = Name.getKeyData(),
2251 *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
2252 NameVals.push_back((unsigned char)*P);
2254 // Emit the finished record.
2255 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
2261 static void WriteUseList(ValueEnumerator &VE, UseListOrder &&Order,
2262 BitstreamWriter &Stream) {
2263 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
2265 if (isa<BasicBlock>(Order.V))
2266 Code = bitc::USELIST_CODE_BB;
2268 Code = bitc::USELIST_CODE_DEFAULT;
2270 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
2271 Record.push_back(VE.getValueID(Order.V));
2272 Stream.EmitRecord(Code, Record);
2275 static void WriteUseListBlock(const Function *F, ValueEnumerator &VE,
2276 BitstreamWriter &Stream) {
2277 assert(VE.shouldPreserveUseListOrder() &&
2278 "Expected to be preserving use-list order");
2280 auto hasMore = [&]() {
2281 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
2287 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
2289 WriteUseList(VE, std::move(VE.UseListOrders.back()), Stream);
2290 VE.UseListOrders.pop_back();
2295 /// WriteFunction - Emit a function body to the module stream.
2296 static void WriteFunction(const Function &F, ValueEnumerator &VE,
2297 BitstreamWriter &Stream,
2298 DenseMap<const Function *, uint64_t> &FunctionIndex) {
2299 // Save the bitcode index of the start of this function block for recording
2301 uint64_t BitcodeIndex = Stream.GetCurrentBitNo();
2302 FunctionIndex[&F] = BitcodeIndex;
2304 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
2305 VE.incorporateFunction(F);
2307 SmallVector<unsigned, 64> Vals;
2309 // Emit the number of basic blocks, so the reader can create them ahead of
2311 Vals.push_back(VE.getBasicBlocks().size());
2312 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
2315 // If there are function-local constants, emit them now.
2316 unsigned CstStart, CstEnd;
2317 VE.getFunctionConstantRange(CstStart, CstEnd);
2318 WriteConstants(CstStart, CstEnd, VE, Stream, false);
2320 // If there is function-local metadata, emit it now.
2321 WriteFunctionLocalMetadata(F, VE, Stream);
2323 // Keep a running idea of what the instruction ID is.
2324 unsigned InstID = CstEnd;
2326 bool NeedsMetadataAttachment = F.hasMetadata();
2328 DILocation *LastDL = nullptr;
2330 // Finally, emit all the instructions, in order.
2331 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
2332 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
2334 WriteInstruction(*I, InstID, VE, Stream, Vals);
2336 if (!I->getType()->isVoidTy())
2339 // If the instruction has metadata, write a metadata attachment later.
2340 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
2342 // If the instruction has a debug location, emit it.
2343 DILocation *DL = I->getDebugLoc();
2348 // Just repeat the same debug loc as last time.
2349 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
2353 Vals.push_back(DL->getLine());
2354 Vals.push_back(DL->getColumn());
2355 Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
2356 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
2357 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
2363 // Emit names for all the instructions etc.
2364 WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
2366 if (NeedsMetadataAttachment)
2367 WriteMetadataAttachment(F, VE, Stream);
2368 if (VE.shouldPreserveUseListOrder())
2369 WriteUseListBlock(&F, VE, Stream);
2374 // Emit blockinfo, which defines the standard abbreviations etc.
2375 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
2376 // We only want to emit block info records for blocks that have multiple
2377 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
2378 // Other blocks can define their abbrevs inline.
2379 Stream.EnterBlockInfoBlock(2);
2381 { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
2382 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2383 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
2384 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2385 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2386 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2387 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2388 Abbv) != VST_ENTRY_8_ABBREV)
2389 llvm_unreachable("Unexpected abbrev ordering!");
2392 { // 7-bit fixed width VST_ENTRY strings.
2393 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2394 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2395 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2396 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2397 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2398 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2399 Abbv) != VST_ENTRY_7_ABBREV)
2400 llvm_unreachable("Unexpected abbrev ordering!");
2402 { // 6-bit char6 VST_ENTRY strings.
2403 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2404 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2405 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2406 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2407 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2408 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2409 Abbv) != VST_ENTRY_6_ABBREV)
2410 llvm_unreachable("Unexpected abbrev ordering!");
2412 { // 6-bit char6 VST_BBENTRY strings.
2413 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2414 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
2415 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2416 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2417 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2418 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2419 Abbv) != VST_BBENTRY_6_ABBREV)
2420 llvm_unreachable("Unexpected abbrev ordering!");
2425 { // SETTYPE abbrev for CONSTANTS_BLOCK.
2426 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2427 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
2428 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
2429 VE.computeBitsRequiredForTypeIndicies()));
2430 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2431 Abbv) != CONSTANTS_SETTYPE_ABBREV)
2432 llvm_unreachable("Unexpected abbrev ordering!");
2435 { // INTEGER abbrev for CONSTANTS_BLOCK.
2436 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2437 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
2438 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2439 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2440 Abbv) != CONSTANTS_INTEGER_ABBREV)
2441 llvm_unreachable("Unexpected abbrev ordering!");
2444 { // CE_CAST abbrev for CONSTANTS_BLOCK.
2445 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2446 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
2447 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
2448 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
2449 VE.computeBitsRequiredForTypeIndicies()));
2450 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2452 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2453 Abbv) != CONSTANTS_CE_CAST_Abbrev)
2454 llvm_unreachable("Unexpected abbrev ordering!");
2456 { // NULL abbrev for CONSTANTS_BLOCK.
2457 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2458 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
2459 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2460 Abbv) != CONSTANTS_NULL_Abbrev)
2461 llvm_unreachable("Unexpected abbrev ordering!");
2464 // FIXME: This should only use space for first class types!
2466 { // INST_LOAD abbrev for FUNCTION_BLOCK.
2467 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2468 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
2469 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
2470 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
2471 VE.computeBitsRequiredForTypeIndicies()));
2472 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
2473 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
2474 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2475 Abbv) != FUNCTION_INST_LOAD_ABBREV)
2476 llvm_unreachable("Unexpected abbrev ordering!");
2478 { // INST_BINOP abbrev for FUNCTION_BLOCK.
2479 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2480 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
2481 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
2482 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
2483 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2484 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2485 Abbv) != FUNCTION_INST_BINOP_ABBREV)
2486 llvm_unreachable("Unexpected abbrev ordering!");
2488 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
2489 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2490 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
2491 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
2492 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
2493 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2494 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
2495 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2496 Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV)
2497 llvm_unreachable("Unexpected abbrev ordering!");
2499 { // INST_CAST abbrev for FUNCTION_BLOCK.
2500 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2501 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
2502 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
2503 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
2504 VE.computeBitsRequiredForTypeIndicies()));
2505 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2506 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2507 Abbv) != FUNCTION_INST_CAST_ABBREV)
2508 llvm_unreachable("Unexpected abbrev ordering!");
2511 { // INST_RET abbrev for FUNCTION_BLOCK.
2512 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2513 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
2514 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2515 Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
2516 llvm_unreachable("Unexpected abbrev ordering!");
2518 { // INST_RET abbrev for FUNCTION_BLOCK.
2519 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2520 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
2521 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
2522 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2523 Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
2524 llvm_unreachable("Unexpected abbrev ordering!");
2526 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
2527 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2528 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
2529 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2530 Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
2531 llvm_unreachable("Unexpected abbrev ordering!");
2534 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2535 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
2536 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
2537 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
2538 Log2_32_Ceil(VE.getTypes().size() + 1)));
2539 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2540 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2541 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
2542 FUNCTION_INST_GEP_ABBREV)
2543 llvm_unreachable("Unexpected abbrev ordering!");
2549 /// WriteModule - Emit the specified module to the bitstream.
2550 static void WriteModule(const Module *M, BitstreamWriter &Stream,
2551 bool ShouldPreserveUseListOrder,
2552 uint64_t BitcodeStartBit) {
2553 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
2555 SmallVector<unsigned, 1> Vals;
2556 unsigned CurVersion = 1;
2557 Vals.push_back(CurVersion);
2558 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
2560 // Analyze the module, enumerating globals, functions, etc.
2561 ValueEnumerator VE(*M, ShouldPreserveUseListOrder);
2563 // Emit blockinfo, which defines the standard abbreviations etc.
2564 WriteBlockInfo(VE, Stream);
2566 // Emit information about attribute groups.
2567 WriteAttributeGroupTable(VE, Stream);
2569 // Emit information about parameter attributes.
2570 WriteAttributeTable(VE, Stream);
2572 // Emit information describing all of the types in the module.
2573 WriteTypeTable(VE, Stream);
2575 writeComdats(VE, Stream);
2577 // Emit top-level description of module, including target triple, inline asm,
2578 // descriptors for global variables, and function prototype info.
2579 uint64_t VSTOffsetPlaceholder = WriteModuleInfo(M, VE, Stream);
2582 WriteModuleConstants(VE, Stream);
2585 WriteModuleMetadata(M, VE, Stream);
2588 WriteModuleMetadataStore(M, Stream);
2590 // Emit module-level use-lists.
2591 if (VE.shouldPreserveUseListOrder())
2592 WriteUseListBlock(nullptr, VE, Stream);
2594 // Emit function bodies.
2595 DenseMap<const Function *, uint64_t> FunctionIndex;
2596 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F)
2597 if (!F->isDeclaration())
2598 WriteFunction(*F, VE, Stream, FunctionIndex);
2600 WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream,
2601 VSTOffsetPlaceholder, BitcodeStartBit, &FunctionIndex);
2606 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
2607 /// header and trailer to make it compatible with the system archiver. To do
2608 /// this we emit the following header, and then emit a trailer that pads the
2609 /// file out to be a multiple of 16 bytes.
2611 /// struct bc_header {
2612 /// uint32_t Magic; // 0x0B17C0DE
2613 /// uint32_t Version; // Version, currently always 0.
2614 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
2615 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
2616 /// uint32_t CPUType; // CPU specifier.
2617 /// ... potentially more later ...
2620 DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
2621 DarwinBCHeaderSize = 5*4
2624 static void WriteInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
2625 uint32_t &Position) {
2626 support::endian::write32le(&Buffer[Position], Value);
2630 static void EmitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
2632 unsigned CPUType = ~0U;
2634 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
2635 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
2636 // number from /usr/include/mach/machine.h. It is ok to reproduce the
2637 // specific constants here because they are implicitly part of the Darwin ABI.
2639 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
2640 DARWIN_CPU_TYPE_X86 = 7,
2641 DARWIN_CPU_TYPE_ARM = 12,
2642 DARWIN_CPU_TYPE_POWERPC = 18
2645 Triple::ArchType Arch = TT.getArch();
2646 if (Arch == Triple::x86_64)
2647 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
2648 else if (Arch == Triple::x86)
2649 CPUType = DARWIN_CPU_TYPE_X86;
2650 else if (Arch == Triple::ppc)
2651 CPUType = DARWIN_CPU_TYPE_POWERPC;
2652 else if (Arch == Triple::ppc64)
2653 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
2654 else if (Arch == Triple::arm || Arch == Triple::thumb)
2655 CPUType = DARWIN_CPU_TYPE_ARM;
2657 // Traditional Bitcode starts after header.
2658 assert(Buffer.size() >= DarwinBCHeaderSize &&
2659 "Expected header size to be reserved");
2660 unsigned BCOffset = DarwinBCHeaderSize;
2661 unsigned BCSize = Buffer.size()-DarwinBCHeaderSize;
2663 // Write the magic and version.
2664 unsigned Position = 0;
2665 WriteInt32ToBuffer(0x0B17C0DE , Buffer, Position);
2666 WriteInt32ToBuffer(0 , Buffer, Position); // Version.
2667 WriteInt32ToBuffer(BCOffset , Buffer, Position);
2668 WriteInt32ToBuffer(BCSize , Buffer, Position);
2669 WriteInt32ToBuffer(CPUType , Buffer, Position);
2671 // If the file is not a multiple of 16 bytes, insert dummy padding.
2672 while (Buffer.size() & 15)
2673 Buffer.push_back(0);
2676 /// WriteBitcodeToFile - Write the specified module to the specified output
2678 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out,
2679 bool ShouldPreserveUseListOrder) {
2680 SmallVector<char, 0> Buffer;
2681 Buffer.reserve(256*1024);
2683 // If this is darwin or another generic macho target, reserve space for the
2685 Triple TT(M->getTargetTriple());
2686 if (TT.isOSDarwin())
2687 Buffer.insert(Buffer.begin(), DarwinBCHeaderSize, 0);
2689 // Emit the module into the buffer.
2691 BitstreamWriter Stream(Buffer);
2692 // Save the start bit of the actual bitcode, in case there is space
2693 // saved at the start for the darwin header above. The reader stream
2694 // will start at the bitcode, and we need the offset of the VST
2696 uint64_t BitcodeStartBit = Stream.GetCurrentBitNo();
2698 // Emit the file header.
2699 Stream.Emit((unsigned)'B', 8);
2700 Stream.Emit((unsigned)'C', 8);
2701 Stream.Emit(0x0, 4);
2702 Stream.Emit(0xC, 4);
2703 Stream.Emit(0xE, 4);
2704 Stream.Emit(0xD, 4);
2707 WriteModule(M, Stream, ShouldPreserveUseListOrder, BitcodeStartBit);
2710 if (TT.isOSDarwin())
2711 EmitDarwinBCHeaderAndTrailer(Buffer, TT);
2713 // Write the generated bitstream to "Out".
2714 Out.write((char*)&Buffer.front(), Buffer.size());