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.getType()));
760 Vals.push_back(VE.getValueID(A.getAliasee()));
761 Vals.push_back(getEncodedLinkage(A));
762 Vals.push_back(getEncodedVisibility(A));
763 Vals.push_back(getEncodedDLLStorageClass(A));
764 Vals.push_back(getEncodedThreadLocalMode(A));
765 Vals.push_back(A.hasUnnamedAddr());
766 unsigned AbbrevToUse = 0;
767 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
771 uint64_t VSTOffsetPlaceholder =
772 WriteValueSymbolTableForwardDecl(M->getValueSymbolTable(), Stream);
773 return VSTOffsetPlaceholder;
776 static uint64_t GetOptimizationFlags(const Value *V) {
779 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
780 if (OBO->hasNoSignedWrap())
781 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
782 if (OBO->hasNoUnsignedWrap())
783 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
784 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
786 Flags |= 1 << bitc::PEO_EXACT;
787 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
788 if (FPMO->hasUnsafeAlgebra())
789 Flags |= FastMathFlags::UnsafeAlgebra;
790 if (FPMO->hasNoNaNs())
791 Flags |= FastMathFlags::NoNaNs;
792 if (FPMO->hasNoInfs())
793 Flags |= FastMathFlags::NoInfs;
794 if (FPMO->hasNoSignedZeros())
795 Flags |= FastMathFlags::NoSignedZeros;
796 if (FPMO->hasAllowReciprocal())
797 Flags |= FastMathFlags::AllowReciprocal;
803 static void WriteValueAsMetadata(const ValueAsMetadata *MD,
804 const ValueEnumerator &VE,
805 BitstreamWriter &Stream,
806 SmallVectorImpl<uint64_t> &Record) {
807 // Mimic an MDNode with a value as one operand.
808 Value *V = MD->getValue();
809 Record.push_back(VE.getTypeID(V->getType()));
810 Record.push_back(VE.getValueID(V));
811 Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
815 static void WriteMDTuple(const MDTuple *N, const ValueEnumerator &VE,
816 BitstreamWriter &Stream,
817 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
818 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
819 Metadata *MD = N->getOperand(i);
820 assert(!(MD && isa<LocalAsMetadata>(MD)) &&
821 "Unexpected function-local metadata");
822 Record.push_back(VE.getMetadataOrNullID(MD));
824 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
825 : bitc::METADATA_NODE,
830 static void WriteDILocation(const DILocation *N, const ValueEnumerator &VE,
831 BitstreamWriter &Stream,
832 SmallVectorImpl<uint64_t> &Record,
834 Record.push_back(N->isDistinct());
835 Record.push_back(N->getLine());
836 Record.push_back(N->getColumn());
837 Record.push_back(VE.getMetadataID(N->getScope()));
838 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
840 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
844 static void WriteGenericDINode(const GenericDINode *N,
845 const ValueEnumerator &VE,
846 BitstreamWriter &Stream,
847 SmallVectorImpl<uint64_t> &Record,
849 Record.push_back(N->isDistinct());
850 Record.push_back(N->getTag());
851 Record.push_back(0); // Per-tag version field; unused for now.
853 for (auto &I : N->operands())
854 Record.push_back(VE.getMetadataOrNullID(I));
856 Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
860 static uint64_t rotateSign(int64_t I) {
862 return I < 0 ? ~(U << 1) : U << 1;
865 static void WriteDISubrange(const DISubrange *N, const ValueEnumerator &,
866 BitstreamWriter &Stream,
867 SmallVectorImpl<uint64_t> &Record,
869 Record.push_back(N->isDistinct());
870 Record.push_back(N->getCount());
871 Record.push_back(rotateSign(N->getLowerBound()));
873 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
877 static void WriteDIEnumerator(const DIEnumerator *N, const ValueEnumerator &VE,
878 BitstreamWriter &Stream,
879 SmallVectorImpl<uint64_t> &Record,
881 Record.push_back(N->isDistinct());
882 Record.push_back(rotateSign(N->getValue()));
883 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
885 Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
889 static void WriteDIBasicType(const DIBasicType *N, const ValueEnumerator &VE,
890 BitstreamWriter &Stream,
891 SmallVectorImpl<uint64_t> &Record,
893 Record.push_back(N->isDistinct());
894 Record.push_back(N->getTag());
895 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
896 Record.push_back(N->getSizeInBits());
897 Record.push_back(N->getAlignInBits());
898 Record.push_back(N->getEncoding());
900 Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
904 static void WriteDIDerivedType(const DIDerivedType *N,
905 const ValueEnumerator &VE,
906 BitstreamWriter &Stream,
907 SmallVectorImpl<uint64_t> &Record,
909 Record.push_back(N->isDistinct());
910 Record.push_back(N->getTag());
911 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
912 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
913 Record.push_back(N->getLine());
914 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
915 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
916 Record.push_back(N->getSizeInBits());
917 Record.push_back(N->getAlignInBits());
918 Record.push_back(N->getOffsetInBits());
919 Record.push_back(N->getFlags());
920 Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
922 Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
926 static void WriteDICompositeType(const DICompositeType *N,
927 const ValueEnumerator &VE,
928 BitstreamWriter &Stream,
929 SmallVectorImpl<uint64_t> &Record,
931 Record.push_back(N->isDistinct());
932 Record.push_back(N->getTag());
933 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
934 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
935 Record.push_back(N->getLine());
936 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
937 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
938 Record.push_back(N->getSizeInBits());
939 Record.push_back(N->getAlignInBits());
940 Record.push_back(N->getOffsetInBits());
941 Record.push_back(N->getFlags());
942 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
943 Record.push_back(N->getRuntimeLang());
944 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
945 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
946 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
948 Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
952 static void WriteDISubroutineType(const DISubroutineType *N,
953 const ValueEnumerator &VE,
954 BitstreamWriter &Stream,
955 SmallVectorImpl<uint64_t> &Record,
957 Record.push_back(N->isDistinct());
958 Record.push_back(N->getFlags());
959 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
961 Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
965 static void WriteDIFile(const DIFile *N, const ValueEnumerator &VE,
966 BitstreamWriter &Stream,
967 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
968 Record.push_back(N->isDistinct());
969 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
970 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
972 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
976 static void WriteDICompileUnit(const DICompileUnit *N,
977 const ValueEnumerator &VE,
978 BitstreamWriter &Stream,
979 SmallVectorImpl<uint64_t> &Record,
981 assert(N->isDistinct() && "Expected distinct compile units");
982 Record.push_back(/* IsDistinct */ true);
983 Record.push_back(N->getSourceLanguage());
984 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
985 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
986 Record.push_back(N->isOptimized());
987 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
988 Record.push_back(N->getRuntimeVersion());
989 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
990 Record.push_back(N->getEmissionKind());
991 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
992 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
993 Record.push_back(VE.getMetadataOrNullID(N->getSubprograms().get()));
994 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
995 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
996 Record.push_back(N->getDWOId());
998 Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
1002 static void WriteDISubprogram(const DISubprogram *N, const ValueEnumerator &VE,
1003 BitstreamWriter &Stream,
1004 SmallVectorImpl<uint64_t> &Record,
1006 Record.push_back(N->isDistinct());
1007 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1008 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1009 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1010 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1011 Record.push_back(N->getLine());
1012 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1013 Record.push_back(N->isLocalToUnit());
1014 Record.push_back(N->isDefinition());
1015 Record.push_back(N->getScopeLine());
1016 Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
1017 Record.push_back(N->getVirtuality());
1018 Record.push_back(N->getVirtualIndex());
1019 Record.push_back(N->getFlags());
1020 Record.push_back(N->isOptimized());
1021 Record.push_back(VE.getMetadataOrNullID(N->getRawFunction()));
1022 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1023 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
1024 Record.push_back(VE.getMetadataOrNullID(N->getVariables().get()));
1026 Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
1030 static void WriteDILexicalBlock(const DILexicalBlock *N,
1031 const ValueEnumerator &VE,
1032 BitstreamWriter &Stream,
1033 SmallVectorImpl<uint64_t> &Record,
1035 Record.push_back(N->isDistinct());
1036 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1037 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1038 Record.push_back(N->getLine());
1039 Record.push_back(N->getColumn());
1041 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
1045 static void WriteDILexicalBlockFile(const DILexicalBlockFile *N,
1046 const ValueEnumerator &VE,
1047 BitstreamWriter &Stream,
1048 SmallVectorImpl<uint64_t> &Record,
1050 Record.push_back(N->isDistinct());
1051 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1052 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1053 Record.push_back(N->getDiscriminator());
1055 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
1059 static void WriteDINamespace(const DINamespace *N, const ValueEnumerator &VE,
1060 BitstreamWriter &Stream,
1061 SmallVectorImpl<uint64_t> &Record,
1063 Record.push_back(N->isDistinct());
1064 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1065 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1066 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1067 Record.push_back(N->getLine());
1069 Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
1073 static void WriteDIModule(const DIModule *N, const ValueEnumerator &VE,
1074 BitstreamWriter &Stream,
1075 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
1076 Record.push_back(N->isDistinct());
1077 for (auto &I : N->operands())
1078 Record.push_back(VE.getMetadataOrNullID(I));
1080 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
1084 static void WriteDITemplateTypeParameter(const DITemplateTypeParameter *N,
1085 const ValueEnumerator &VE,
1086 BitstreamWriter &Stream,
1087 SmallVectorImpl<uint64_t> &Record,
1089 Record.push_back(N->isDistinct());
1090 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1091 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1093 Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
1097 static void WriteDITemplateValueParameter(const DITemplateValueParameter *N,
1098 const ValueEnumerator &VE,
1099 BitstreamWriter &Stream,
1100 SmallVectorImpl<uint64_t> &Record,
1102 Record.push_back(N->isDistinct());
1103 Record.push_back(N->getTag());
1104 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1105 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1106 Record.push_back(VE.getMetadataOrNullID(N->getValue()));
1108 Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
1112 static void WriteDIGlobalVariable(const DIGlobalVariable *N,
1113 const ValueEnumerator &VE,
1114 BitstreamWriter &Stream,
1115 SmallVectorImpl<uint64_t> &Record,
1117 Record.push_back(N->isDistinct());
1118 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1119 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1120 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1121 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1122 Record.push_back(N->getLine());
1123 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1124 Record.push_back(N->isLocalToUnit());
1125 Record.push_back(N->isDefinition());
1126 Record.push_back(VE.getMetadataOrNullID(N->getRawVariable()));
1127 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
1129 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
1133 static void WriteDILocalVariable(const DILocalVariable *N,
1134 const ValueEnumerator &VE,
1135 BitstreamWriter &Stream,
1136 SmallVectorImpl<uint64_t> &Record,
1138 Record.push_back(N->isDistinct());
1139 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1140 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1141 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1142 Record.push_back(N->getLine());
1143 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1144 Record.push_back(N->getArg());
1145 Record.push_back(N->getFlags());
1147 Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
1151 static void WriteDIExpression(const DIExpression *N, const ValueEnumerator &,
1152 BitstreamWriter &Stream,
1153 SmallVectorImpl<uint64_t> &Record,
1155 Record.reserve(N->getElements().size() + 1);
1157 Record.push_back(N->isDistinct());
1158 Record.append(N->elements_begin(), N->elements_end());
1160 Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
1164 static void WriteDIObjCProperty(const DIObjCProperty *N,
1165 const ValueEnumerator &VE,
1166 BitstreamWriter &Stream,
1167 SmallVectorImpl<uint64_t> &Record,
1169 Record.push_back(N->isDistinct());
1170 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1171 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1172 Record.push_back(N->getLine());
1173 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
1174 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
1175 Record.push_back(N->getAttributes());
1176 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1178 Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
1182 static void WriteDIImportedEntity(const DIImportedEntity *N,
1183 const ValueEnumerator &VE,
1184 BitstreamWriter &Stream,
1185 SmallVectorImpl<uint64_t> &Record,
1187 Record.push_back(N->isDistinct());
1188 Record.push_back(N->getTag());
1189 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1190 Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
1191 Record.push_back(N->getLine());
1192 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1194 Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
1198 static void WriteModuleMetadata(const Module *M,
1199 const ValueEnumerator &VE,
1200 BitstreamWriter &Stream) {
1201 const auto &MDs = VE.getMDs();
1202 if (MDs.empty() && M->named_metadata_empty())
1205 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
1207 unsigned MDSAbbrev = 0;
1208 if (VE.hasMDString()) {
1209 // Abbrev for METADATA_STRING.
1210 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1211 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING));
1212 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1213 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1214 MDSAbbrev = Stream.EmitAbbrev(Abbv);
1217 // Initialize MDNode abbreviations.
1218 #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
1219 #include "llvm/IR/Metadata.def"
1221 if (VE.hasDILocation()) {
1222 // Abbrev for METADATA_LOCATION.
1224 // Assume the column is usually under 128, and always output the inlined-at
1225 // location (it's never more expensive than building an array size 1).
1226 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1227 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
1228 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1229 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1230 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1231 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1232 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1233 DILocationAbbrev = Stream.EmitAbbrev(Abbv);
1236 if (VE.hasGenericDINode()) {
1237 // Abbrev for METADATA_GENERIC_DEBUG.
1239 // Assume the column is usually under 128, and always output the inlined-at
1240 // location (it's never more expensive than building an array size 1).
1241 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1242 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
1243 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1244 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1245 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1246 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1247 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1248 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1249 GenericDINodeAbbrev = Stream.EmitAbbrev(Abbv);
1252 unsigned NameAbbrev = 0;
1253 if (!M->named_metadata_empty()) {
1254 // Abbrev for METADATA_NAME.
1255 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1256 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
1257 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1258 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1259 NameAbbrev = Stream.EmitAbbrev(Abbv);
1262 SmallVector<uint64_t, 64> Record;
1263 for (const Metadata *MD : MDs) {
1264 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
1265 assert(N->isResolved() && "Expected forward references to be resolved");
1267 switch (N->getMetadataID()) {
1269 llvm_unreachable("Invalid MDNode subclass");
1270 #define HANDLE_MDNODE_LEAF(CLASS) \
1271 case Metadata::CLASS##Kind: \
1272 Write##CLASS(cast<CLASS>(N), VE, Stream, Record, CLASS##Abbrev); \
1274 #include "llvm/IR/Metadata.def"
1277 if (const auto *MDC = dyn_cast<ConstantAsMetadata>(MD)) {
1278 WriteValueAsMetadata(MDC, VE, Stream, Record);
1281 const MDString *MDS = cast<MDString>(MD);
1282 // Code: [strchar x N]
1283 Record.append(MDS->bytes_begin(), MDS->bytes_end());
1285 // Emit the finished record.
1286 Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev);
1290 // Write named metadata.
1291 for (const NamedMDNode &NMD : M->named_metadata()) {
1293 StringRef Str = NMD.getName();
1294 Record.append(Str.bytes_begin(), Str.bytes_end());
1295 Stream.EmitRecord(bitc::METADATA_NAME, Record, NameAbbrev);
1298 // Write named metadata operands.
1299 for (const MDNode *N : NMD.operands())
1300 Record.push_back(VE.getMetadataID(N));
1301 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
1308 static void WriteFunctionLocalMetadata(const Function &F,
1309 const ValueEnumerator &VE,
1310 BitstreamWriter &Stream) {
1311 bool StartedMetadataBlock = false;
1312 SmallVector<uint64_t, 64> Record;
1313 const SmallVectorImpl<const LocalAsMetadata *> &MDs =
1314 VE.getFunctionLocalMDs();
1315 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
1316 assert(MDs[i] && "Expected valid function-local metadata");
1317 if (!StartedMetadataBlock) {
1318 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
1319 StartedMetadataBlock = true;
1321 WriteValueAsMetadata(MDs[i], VE, Stream, Record);
1324 if (StartedMetadataBlock)
1328 static void WriteMetadataAttachment(const Function &F,
1329 const ValueEnumerator &VE,
1330 BitstreamWriter &Stream) {
1331 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
1333 SmallVector<uint64_t, 64> Record;
1335 // Write metadata attachments
1336 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
1337 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1338 F.getAllMetadata(MDs);
1340 for (const auto &I : MDs) {
1341 Record.push_back(I.first);
1342 Record.push_back(VE.getMetadataID(I.second));
1344 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
1348 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1349 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1352 I->getAllMetadataOtherThanDebugLoc(MDs);
1354 // If no metadata, ignore instruction.
1355 if (MDs.empty()) continue;
1357 Record.push_back(VE.getInstructionID(I));
1359 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
1360 Record.push_back(MDs[i].first);
1361 Record.push_back(VE.getMetadataID(MDs[i].second));
1363 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
1370 static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) {
1371 SmallVector<uint64_t, 64> Record;
1373 // Write metadata kinds
1374 // METADATA_KIND - [n x [id, name]]
1375 SmallVector<StringRef, 8> Names;
1376 M->getMDKindNames(Names);
1378 if (Names.empty()) return;
1380 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
1382 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
1383 Record.push_back(MDKindID);
1384 StringRef KName = Names[MDKindID];
1385 Record.append(KName.begin(), KName.end());
1387 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
1394 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
1395 if ((int64_t)V >= 0)
1396 Vals.push_back(V << 1);
1398 Vals.push_back((-V << 1) | 1);
1401 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
1402 const ValueEnumerator &VE,
1403 BitstreamWriter &Stream, bool isGlobal) {
1404 if (FirstVal == LastVal) return;
1406 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
1408 unsigned AggregateAbbrev = 0;
1409 unsigned String8Abbrev = 0;
1410 unsigned CString7Abbrev = 0;
1411 unsigned CString6Abbrev = 0;
1412 // If this is a constant pool for the module, emit module-specific abbrevs.
1414 // Abbrev for CST_CODE_AGGREGATE.
1415 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1416 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
1417 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1418 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
1419 AggregateAbbrev = Stream.EmitAbbrev(Abbv);
1421 // Abbrev for CST_CODE_STRING.
1422 Abbv = new BitCodeAbbrev();
1423 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
1424 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1425 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1426 String8Abbrev = Stream.EmitAbbrev(Abbv);
1427 // Abbrev for CST_CODE_CSTRING.
1428 Abbv = new BitCodeAbbrev();
1429 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
1430 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1431 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1432 CString7Abbrev = Stream.EmitAbbrev(Abbv);
1433 // Abbrev for CST_CODE_CSTRING.
1434 Abbv = new BitCodeAbbrev();
1435 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
1436 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1437 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1438 CString6Abbrev = Stream.EmitAbbrev(Abbv);
1441 SmallVector<uint64_t, 64> Record;
1443 const ValueEnumerator::ValueList &Vals = VE.getValues();
1444 Type *LastTy = nullptr;
1445 for (unsigned i = FirstVal; i != LastVal; ++i) {
1446 const Value *V = Vals[i].first;
1447 // If we need to switch types, do so now.
1448 if (V->getType() != LastTy) {
1449 LastTy = V->getType();
1450 Record.push_back(VE.getTypeID(LastTy));
1451 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
1452 CONSTANTS_SETTYPE_ABBREV);
1456 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1457 Record.push_back(unsigned(IA->hasSideEffects()) |
1458 unsigned(IA->isAlignStack()) << 1 |
1459 unsigned(IA->getDialect()&1) << 2);
1461 // Add the asm string.
1462 const std::string &AsmStr = IA->getAsmString();
1463 Record.push_back(AsmStr.size());
1464 Record.append(AsmStr.begin(), AsmStr.end());
1466 // Add the constraint string.
1467 const std::string &ConstraintStr = IA->getConstraintString();
1468 Record.push_back(ConstraintStr.size());
1469 Record.append(ConstraintStr.begin(), ConstraintStr.end());
1470 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
1474 const Constant *C = cast<Constant>(V);
1475 unsigned Code = -1U;
1476 unsigned AbbrevToUse = 0;
1477 if (C->isNullValue()) {
1478 Code = bitc::CST_CODE_NULL;
1479 } else if (isa<UndefValue>(C)) {
1480 Code = bitc::CST_CODE_UNDEF;
1481 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
1482 if (IV->getBitWidth() <= 64) {
1483 uint64_t V = IV->getSExtValue();
1484 emitSignedInt64(Record, V);
1485 Code = bitc::CST_CODE_INTEGER;
1486 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
1487 } else { // Wide integers, > 64 bits in size.
1488 // We have an arbitrary precision integer value to write whose
1489 // bit width is > 64. However, in canonical unsigned integer
1490 // format it is likely that the high bits are going to be zero.
1491 // So, we only write the number of active words.
1492 unsigned NWords = IV->getValue().getActiveWords();
1493 const uint64_t *RawWords = IV->getValue().getRawData();
1494 for (unsigned i = 0; i != NWords; ++i) {
1495 emitSignedInt64(Record, RawWords[i]);
1497 Code = bitc::CST_CODE_WIDE_INTEGER;
1499 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
1500 Code = bitc::CST_CODE_FLOAT;
1501 Type *Ty = CFP->getType();
1502 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
1503 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
1504 } else if (Ty->isX86_FP80Ty()) {
1505 // api needed to prevent premature destruction
1506 // bits are not in the same order as a normal i80 APInt, compensate.
1507 APInt api = CFP->getValueAPF().bitcastToAPInt();
1508 const uint64_t *p = api.getRawData();
1509 Record.push_back((p[1] << 48) | (p[0] >> 16));
1510 Record.push_back(p[0] & 0xffffLL);
1511 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
1512 APInt api = CFP->getValueAPF().bitcastToAPInt();
1513 const uint64_t *p = api.getRawData();
1514 Record.push_back(p[0]);
1515 Record.push_back(p[1]);
1517 assert (0 && "Unknown FP type!");
1519 } else if (isa<ConstantDataSequential>(C) &&
1520 cast<ConstantDataSequential>(C)->isString()) {
1521 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
1522 // Emit constant strings specially.
1523 unsigned NumElts = Str->getNumElements();
1524 // If this is a null-terminated string, use the denser CSTRING encoding.
1525 if (Str->isCString()) {
1526 Code = bitc::CST_CODE_CSTRING;
1527 --NumElts; // Don't encode the null, which isn't allowed by char6.
1529 Code = bitc::CST_CODE_STRING;
1530 AbbrevToUse = String8Abbrev;
1532 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
1533 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
1534 for (unsigned i = 0; i != NumElts; ++i) {
1535 unsigned char V = Str->getElementAsInteger(i);
1536 Record.push_back(V);
1537 isCStr7 &= (V & 128) == 0;
1539 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
1543 AbbrevToUse = CString6Abbrev;
1545 AbbrevToUse = CString7Abbrev;
1546 } else if (const ConstantDataSequential *CDS =
1547 dyn_cast<ConstantDataSequential>(C)) {
1548 Code = bitc::CST_CODE_DATA;
1549 Type *EltTy = CDS->getType()->getElementType();
1550 if (isa<IntegerType>(EltTy)) {
1551 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
1552 Record.push_back(CDS->getElementAsInteger(i));
1553 } else if (EltTy->isFloatTy()) {
1554 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1555 union { float F; uint32_t I; };
1556 F = CDS->getElementAsFloat(i);
1557 Record.push_back(I);
1560 assert(EltTy->isDoubleTy() && "Unknown ConstantData element type");
1561 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1562 union { double F; uint64_t I; };
1563 F = CDS->getElementAsDouble(i);
1564 Record.push_back(I);
1567 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
1568 isa<ConstantVector>(C)) {
1569 Code = bitc::CST_CODE_AGGREGATE;
1570 for (const Value *Op : C->operands())
1571 Record.push_back(VE.getValueID(Op));
1572 AbbrevToUse = AggregateAbbrev;
1573 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1574 switch (CE->getOpcode()) {
1576 if (Instruction::isCast(CE->getOpcode())) {
1577 Code = bitc::CST_CODE_CE_CAST;
1578 Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
1579 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1580 Record.push_back(VE.getValueID(C->getOperand(0)));
1581 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
1583 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
1584 Code = bitc::CST_CODE_CE_BINOP;
1585 Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
1586 Record.push_back(VE.getValueID(C->getOperand(0)));
1587 Record.push_back(VE.getValueID(C->getOperand(1)));
1588 uint64_t Flags = GetOptimizationFlags(CE);
1590 Record.push_back(Flags);
1593 case Instruction::GetElementPtr: {
1594 Code = bitc::CST_CODE_CE_GEP;
1595 const auto *GO = cast<GEPOperator>(C);
1596 if (GO->isInBounds())
1597 Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
1598 Record.push_back(VE.getTypeID(GO->getSourceElementType()));
1599 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
1600 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
1601 Record.push_back(VE.getValueID(C->getOperand(i)));
1605 case Instruction::Select:
1606 Code = bitc::CST_CODE_CE_SELECT;
1607 Record.push_back(VE.getValueID(C->getOperand(0)));
1608 Record.push_back(VE.getValueID(C->getOperand(1)));
1609 Record.push_back(VE.getValueID(C->getOperand(2)));
1611 case Instruction::ExtractElement:
1612 Code = bitc::CST_CODE_CE_EXTRACTELT;
1613 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1614 Record.push_back(VE.getValueID(C->getOperand(0)));
1615 Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
1616 Record.push_back(VE.getValueID(C->getOperand(1)));
1618 case Instruction::InsertElement:
1619 Code = bitc::CST_CODE_CE_INSERTELT;
1620 Record.push_back(VE.getValueID(C->getOperand(0)));
1621 Record.push_back(VE.getValueID(C->getOperand(1)));
1622 Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
1623 Record.push_back(VE.getValueID(C->getOperand(2)));
1625 case Instruction::ShuffleVector:
1626 // If the return type and argument types are the same, this is a
1627 // standard shufflevector instruction. If the types are different,
1628 // then the shuffle is widening or truncating the input vectors, and
1629 // the argument type must also be encoded.
1630 if (C->getType() == C->getOperand(0)->getType()) {
1631 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
1633 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
1634 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1636 Record.push_back(VE.getValueID(C->getOperand(0)));
1637 Record.push_back(VE.getValueID(C->getOperand(1)));
1638 Record.push_back(VE.getValueID(C->getOperand(2)));
1640 case Instruction::ICmp:
1641 case Instruction::FCmp:
1642 Code = bitc::CST_CODE_CE_CMP;
1643 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1644 Record.push_back(VE.getValueID(C->getOperand(0)));
1645 Record.push_back(VE.getValueID(C->getOperand(1)));
1646 Record.push_back(CE->getPredicate());
1649 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
1650 Code = bitc::CST_CODE_BLOCKADDRESS;
1651 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
1652 Record.push_back(VE.getValueID(BA->getFunction()));
1653 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
1658 llvm_unreachable("Unknown constant!");
1660 Stream.EmitRecord(Code, Record, AbbrevToUse);
1667 static void WriteModuleConstants(const ValueEnumerator &VE,
1668 BitstreamWriter &Stream) {
1669 const ValueEnumerator::ValueList &Vals = VE.getValues();
1671 // Find the first constant to emit, which is the first non-globalvalue value.
1672 // We know globalvalues have been emitted by WriteModuleInfo.
1673 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1674 if (!isa<GlobalValue>(Vals[i].first)) {
1675 WriteConstants(i, Vals.size(), VE, Stream, true);
1681 /// PushValueAndType - The file has to encode both the value and type id for
1682 /// many values, because we need to know what type to create for forward
1683 /// references. However, most operands are not forward references, so this type
1684 /// field is not needed.
1686 /// This function adds V's value ID to Vals. If the value ID is higher than the
1687 /// instruction ID, then it is a forward reference, and it also includes the
1688 /// type ID. The value ID that is written is encoded relative to the InstID.
1689 static bool PushValueAndType(const Value *V, unsigned InstID,
1690 SmallVectorImpl<unsigned> &Vals,
1691 ValueEnumerator &VE) {
1692 unsigned ValID = VE.getValueID(V);
1693 // Make encoding relative to the InstID.
1694 Vals.push_back(InstID - ValID);
1695 if (ValID >= InstID) {
1696 Vals.push_back(VE.getTypeID(V->getType()));
1702 /// pushValue - Like PushValueAndType, but where the type of the value is
1703 /// omitted (perhaps it was already encoded in an earlier operand).
1704 static void pushValue(const Value *V, unsigned InstID,
1705 SmallVectorImpl<unsigned> &Vals,
1706 ValueEnumerator &VE) {
1707 unsigned ValID = VE.getValueID(V);
1708 Vals.push_back(InstID - ValID);
1711 static void pushValueSigned(const Value *V, unsigned InstID,
1712 SmallVectorImpl<uint64_t> &Vals,
1713 ValueEnumerator &VE) {
1714 unsigned ValID = VE.getValueID(V);
1715 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
1716 emitSignedInt64(Vals, diff);
1719 /// WriteInstruction - Emit an instruction to the specified stream.
1720 static void WriteInstruction(const Instruction &I, unsigned InstID,
1721 ValueEnumerator &VE, BitstreamWriter &Stream,
1722 SmallVectorImpl<unsigned> &Vals) {
1724 unsigned AbbrevToUse = 0;
1725 VE.setInstructionID(&I);
1726 switch (I.getOpcode()) {
1728 if (Instruction::isCast(I.getOpcode())) {
1729 Code = bitc::FUNC_CODE_INST_CAST;
1730 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1731 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
1732 Vals.push_back(VE.getTypeID(I.getType()));
1733 Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
1735 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
1736 Code = bitc::FUNC_CODE_INST_BINOP;
1737 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1738 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
1739 pushValue(I.getOperand(1), InstID, Vals, VE);
1740 Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
1741 uint64_t Flags = GetOptimizationFlags(&I);
1743 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
1744 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
1745 Vals.push_back(Flags);
1750 case Instruction::GetElementPtr: {
1751 Code = bitc::FUNC_CODE_INST_GEP;
1752 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
1753 auto &GEPInst = cast<GetElementPtrInst>(I);
1754 Vals.push_back(GEPInst.isInBounds());
1755 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
1756 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1757 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1760 case Instruction::ExtractValue: {
1761 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
1762 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1763 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
1764 Vals.append(EVI->idx_begin(), EVI->idx_end());
1767 case Instruction::InsertValue: {
1768 Code = bitc::FUNC_CODE_INST_INSERTVAL;
1769 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1770 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1771 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
1772 Vals.append(IVI->idx_begin(), IVI->idx_end());
1775 case Instruction::Select:
1776 Code = bitc::FUNC_CODE_INST_VSELECT;
1777 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1778 pushValue(I.getOperand(2), InstID, Vals, VE);
1779 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1781 case Instruction::ExtractElement:
1782 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
1783 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1784 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1786 case Instruction::InsertElement:
1787 Code = bitc::FUNC_CODE_INST_INSERTELT;
1788 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1789 pushValue(I.getOperand(1), InstID, Vals, VE);
1790 PushValueAndType(I.getOperand(2), InstID, Vals, VE);
1792 case Instruction::ShuffleVector:
1793 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
1794 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1795 pushValue(I.getOperand(1), InstID, Vals, VE);
1796 pushValue(I.getOperand(2), InstID, Vals, VE);
1798 case Instruction::ICmp:
1799 case Instruction::FCmp: {
1800 // compare returning Int1Ty or vector of Int1Ty
1801 Code = bitc::FUNC_CODE_INST_CMP2;
1802 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1803 pushValue(I.getOperand(1), InstID, Vals, VE);
1804 Vals.push_back(cast<CmpInst>(I).getPredicate());
1805 uint64_t Flags = GetOptimizationFlags(&I);
1807 Vals.push_back(Flags);
1811 case Instruction::Ret:
1813 Code = bitc::FUNC_CODE_INST_RET;
1814 unsigned NumOperands = I.getNumOperands();
1815 if (NumOperands == 0)
1816 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
1817 else if (NumOperands == 1) {
1818 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1819 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
1821 for (unsigned i = 0, e = NumOperands; i != e; ++i)
1822 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1826 case Instruction::Br:
1828 Code = bitc::FUNC_CODE_INST_BR;
1829 const BranchInst &II = cast<BranchInst>(I);
1830 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
1831 if (II.isConditional()) {
1832 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
1833 pushValue(II.getCondition(), InstID, Vals, VE);
1837 case Instruction::Switch:
1839 Code = bitc::FUNC_CODE_INST_SWITCH;
1840 const SwitchInst &SI = cast<SwitchInst>(I);
1841 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
1842 pushValue(SI.getCondition(), InstID, Vals, VE);
1843 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
1844 for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
1846 Vals.push_back(VE.getValueID(i.getCaseValue()));
1847 Vals.push_back(VE.getValueID(i.getCaseSuccessor()));
1851 case Instruction::IndirectBr:
1852 Code = bitc::FUNC_CODE_INST_INDIRECTBR;
1853 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1854 // Encode the address operand as relative, but not the basic blocks.
1855 pushValue(I.getOperand(0), InstID, Vals, VE);
1856 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
1857 Vals.push_back(VE.getValueID(I.getOperand(i)));
1860 case Instruction::Invoke: {
1861 const InvokeInst *II = cast<InvokeInst>(&I);
1862 const Value *Callee = II->getCalledValue();
1863 FunctionType *FTy = II->getFunctionType();
1864 Code = bitc::FUNC_CODE_INST_INVOKE;
1866 Vals.push_back(VE.getAttributeID(II->getAttributes()));
1867 Vals.push_back(II->getCallingConv() | 1 << 13);
1868 Vals.push_back(VE.getValueID(II->getNormalDest()));
1869 Vals.push_back(VE.getValueID(II->getUnwindDest()));
1870 Vals.push_back(VE.getTypeID(FTy));
1871 PushValueAndType(Callee, InstID, Vals, VE);
1873 // Emit value #'s for the fixed parameters.
1874 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1875 pushValue(I.getOperand(i), InstID, Vals, VE); // fixed param.
1877 // Emit type/value pairs for varargs params.
1878 if (FTy->isVarArg()) {
1879 for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
1881 PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
1885 case Instruction::Resume:
1886 Code = bitc::FUNC_CODE_INST_RESUME;
1887 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1889 case Instruction::CleanupRet: {
1890 Code = bitc::FUNC_CODE_INST_CLEANUPRET;
1891 const auto &CRI = cast<CleanupReturnInst>(I);
1892 pushValue(CRI.getCleanupPad(), InstID, Vals, VE);
1893 if (CRI.hasUnwindDest())
1894 Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
1897 case Instruction::CatchRet: {
1898 Code = bitc::FUNC_CODE_INST_CATCHRET;
1899 const auto &CRI = cast<CatchReturnInst>(I);
1900 pushValue(CRI.getCatchPad(), InstID, Vals, VE);
1901 Vals.push_back(VE.getValueID(CRI.getSuccessor()));
1904 case Instruction::CatchPad: {
1905 Code = bitc::FUNC_CODE_INST_CATCHPAD;
1906 const auto &CPI = cast<CatchPadInst>(I);
1907 Vals.push_back(VE.getValueID(CPI.getNormalDest()));
1908 Vals.push_back(VE.getValueID(CPI.getUnwindDest()));
1909 unsigned NumArgOperands = CPI.getNumArgOperands();
1910 Vals.push_back(NumArgOperands);
1911 for (unsigned Op = 0; Op != NumArgOperands; ++Op)
1912 PushValueAndType(CPI.getArgOperand(Op), InstID, Vals, VE);
1915 case Instruction::TerminatePad: {
1916 Code = bitc::FUNC_CODE_INST_TERMINATEPAD;
1917 const auto &TPI = cast<TerminatePadInst>(I);
1918 Vals.push_back(TPI.hasUnwindDest());
1919 if (TPI.hasUnwindDest())
1920 Vals.push_back(VE.getValueID(TPI.getUnwindDest()));
1921 unsigned NumArgOperands = TPI.getNumArgOperands();
1922 Vals.push_back(NumArgOperands);
1923 for (unsigned Op = 0; Op != NumArgOperands; ++Op)
1924 PushValueAndType(TPI.getArgOperand(Op), InstID, Vals, VE);
1927 case Instruction::CleanupPad: {
1928 Code = bitc::FUNC_CODE_INST_CLEANUPPAD;
1929 const auto &CPI = cast<CleanupPadInst>(I);
1930 unsigned NumOperands = CPI.getNumOperands();
1931 Vals.push_back(NumOperands);
1932 for (unsigned Op = 0; Op != NumOperands; ++Op)
1933 PushValueAndType(CPI.getOperand(Op), InstID, Vals, VE);
1936 case Instruction::CatchEndPad: {
1937 Code = bitc::FUNC_CODE_INST_CATCHENDPAD;
1938 const auto &CEPI = cast<CatchEndPadInst>(I);
1939 if (CEPI.hasUnwindDest())
1940 Vals.push_back(VE.getValueID(CEPI.getUnwindDest()));
1943 case Instruction::CleanupEndPad: {
1944 Code = bitc::FUNC_CODE_INST_CLEANUPENDPAD;
1945 const auto &CEPI = cast<CleanupEndPadInst>(I);
1946 pushValue(CEPI.getCleanupPad(), InstID, Vals, VE);
1947 if (CEPI.hasUnwindDest())
1948 Vals.push_back(VE.getValueID(CEPI.getUnwindDest()));
1951 case Instruction::Unreachable:
1952 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
1953 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
1956 case Instruction::PHI: {
1957 const PHINode &PN = cast<PHINode>(I);
1958 Code = bitc::FUNC_CODE_INST_PHI;
1959 // With the newer instruction encoding, forward references could give
1960 // negative valued IDs. This is most common for PHIs, so we use
1962 SmallVector<uint64_t, 128> Vals64;
1963 Vals64.push_back(VE.getTypeID(PN.getType()));
1964 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1965 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64, VE);
1966 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
1968 // Emit a Vals64 vector and exit.
1969 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
1974 case Instruction::LandingPad: {
1975 const LandingPadInst &LP = cast<LandingPadInst>(I);
1976 Code = bitc::FUNC_CODE_INST_LANDINGPAD;
1977 Vals.push_back(VE.getTypeID(LP.getType()));
1978 Vals.push_back(LP.isCleanup());
1979 Vals.push_back(LP.getNumClauses());
1980 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
1982 Vals.push_back(LandingPadInst::Catch);
1984 Vals.push_back(LandingPadInst::Filter);
1985 PushValueAndType(LP.getClause(I), InstID, Vals, VE);
1990 case Instruction::Alloca: {
1991 Code = bitc::FUNC_CODE_INST_ALLOCA;
1992 const AllocaInst &AI = cast<AllocaInst>(I);
1993 Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
1994 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1995 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
1996 unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
1997 assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
1998 "not enough bits for maximum alignment");
1999 assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
2000 AlignRecord |= AI.isUsedWithInAlloca() << 5;
2001 AlignRecord |= 1 << 6;
2002 // Reserve bit 7 for SwiftError flag.
2003 // AlignRecord |= AI.isSwiftError() << 7;
2004 Vals.push_back(AlignRecord);
2008 case Instruction::Load:
2009 if (cast<LoadInst>(I).isAtomic()) {
2010 Code = bitc::FUNC_CODE_INST_LOADATOMIC;
2011 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
2013 Code = bitc::FUNC_CODE_INST_LOAD;
2014 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) // ptr
2015 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
2017 Vals.push_back(VE.getTypeID(I.getType()));
2018 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
2019 Vals.push_back(cast<LoadInst>(I).isVolatile());
2020 if (cast<LoadInst>(I).isAtomic()) {
2021 Vals.push_back(GetEncodedOrdering(cast<LoadInst>(I).getOrdering()));
2022 Vals.push_back(GetEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
2025 case Instruction::Store:
2026 if (cast<StoreInst>(I).isAtomic())
2027 Code = bitc::FUNC_CODE_INST_STOREATOMIC;
2029 Code = bitc::FUNC_CODE_INST_STORE;
2030 PushValueAndType(I.getOperand(1), InstID, Vals, VE); // ptrty + ptr
2031 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // valty + val
2032 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
2033 Vals.push_back(cast<StoreInst>(I).isVolatile());
2034 if (cast<StoreInst>(I).isAtomic()) {
2035 Vals.push_back(GetEncodedOrdering(cast<StoreInst>(I).getOrdering()));
2036 Vals.push_back(GetEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
2039 case Instruction::AtomicCmpXchg:
2040 Code = bitc::FUNC_CODE_INST_CMPXCHG;
2041 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr
2042 PushValueAndType(I.getOperand(1), InstID, Vals, VE); // cmp.
2043 pushValue(I.getOperand(2), InstID, Vals, VE); // newval.
2044 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
2045 Vals.push_back(GetEncodedOrdering(
2046 cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
2047 Vals.push_back(GetEncodedSynchScope(
2048 cast<AtomicCmpXchgInst>(I).getSynchScope()));
2049 Vals.push_back(GetEncodedOrdering(
2050 cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
2051 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
2053 case Instruction::AtomicRMW:
2054 Code = bitc::FUNC_CODE_INST_ATOMICRMW;
2055 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr
2056 pushValue(I.getOperand(1), InstID, Vals, VE); // val.
2057 Vals.push_back(GetEncodedRMWOperation(
2058 cast<AtomicRMWInst>(I).getOperation()));
2059 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
2060 Vals.push_back(GetEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
2061 Vals.push_back(GetEncodedSynchScope(
2062 cast<AtomicRMWInst>(I).getSynchScope()));
2064 case Instruction::Fence:
2065 Code = bitc::FUNC_CODE_INST_FENCE;
2066 Vals.push_back(GetEncodedOrdering(cast<FenceInst>(I).getOrdering()));
2067 Vals.push_back(GetEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
2069 case Instruction::Call: {
2070 const CallInst &CI = cast<CallInst>(I);
2071 FunctionType *FTy = CI.getFunctionType();
2073 Code = bitc::FUNC_CODE_INST_CALL;
2075 Vals.push_back(VE.getAttributeID(CI.getAttributes()));
2076 Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall()) |
2077 unsigned(CI.isMustTailCall()) << 14 | 1 << 15);
2078 Vals.push_back(VE.getTypeID(FTy));
2079 PushValueAndType(CI.getCalledValue(), InstID, Vals, VE); // Callee
2081 // Emit value #'s for the fixed parameters.
2082 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
2083 // Check for labels (can happen with asm labels).
2084 if (FTy->getParamType(i)->isLabelTy())
2085 Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
2087 pushValue(CI.getArgOperand(i), InstID, Vals, VE); // fixed param.
2090 // Emit type/value pairs for varargs params.
2091 if (FTy->isVarArg()) {
2092 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
2094 PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE); // varargs
2098 case Instruction::VAArg:
2099 Code = bitc::FUNC_CODE_INST_VAARG;
2100 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
2101 pushValue(I.getOperand(0), InstID, Vals, VE); // valist.
2102 Vals.push_back(VE.getTypeID(I.getType())); // restype.
2106 Stream.EmitRecord(Code, Vals, AbbrevToUse);
2110 enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 };
2112 /// Determine the encoding to use for the given string name and length.
2113 static StringEncoding getStringEncoding(const char *Str, unsigned StrLen) {
2114 bool isChar6 = true;
2115 for (const char *C = Str, *E = C + StrLen; C != E; ++C) {
2117 isChar6 = BitCodeAbbrevOp::isChar6(*C);
2118 if ((unsigned char)*C & 128)
2119 // don't bother scanning the rest.
2128 /// Emit names for globals/functions etc. The VSTOffsetPlaceholder,
2129 /// BitcodeStartBit and FunctionIndex are only passed for the module-level
2130 /// VST, where we are including a function bitcode index and need to
2131 /// backpatch the VST forward declaration record.
2132 static void WriteValueSymbolTable(
2133 const ValueSymbolTable &VST, const ValueEnumerator &VE,
2134 BitstreamWriter &Stream, uint64_t VSTOffsetPlaceholder = 0,
2135 uint64_t BitcodeStartBit = 0,
2136 DenseMap<const Function *, uint64_t> *FunctionIndex = nullptr) {
2138 // WriteValueSymbolTableForwardDecl should have returned early as
2139 // well. Ensure this handling remains in sync by asserting that
2140 // the placeholder offset is not set.
2141 assert(VSTOffsetPlaceholder == 0);
2145 if (VSTOffsetPlaceholder > 0) {
2146 // Get the offset of the VST we are writing, and backpatch it into
2147 // the VST forward declaration record.
2148 uint64_t VSTOffset = Stream.GetCurrentBitNo();
2149 // The BitcodeStartBit was the stream offset of the actual bitcode
2150 // (e.g. excluding any initial darwin header).
2151 VSTOffset -= BitcodeStartBit;
2152 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
2153 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32);
2156 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
2158 // For the module-level VST, add abbrev Ids for the VST_CODE_FNENTRY
2159 // records, which are not used in the per-function VSTs.
2160 unsigned FnEntry8BitAbbrev;
2161 unsigned FnEntry7BitAbbrev;
2162 unsigned FnEntry6BitAbbrev;
2163 if (VSTOffsetPlaceholder > 0) {
2164 // 8-bit fixed-width VST_FNENTRY function strings.
2165 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2166 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2167 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2168 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2169 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2170 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2171 FnEntry8BitAbbrev = Stream.EmitAbbrev(Abbv);
2173 // 7-bit fixed width VST_FNENTRY function strings.
2174 Abbv = new BitCodeAbbrev();
2175 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2176 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2177 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2178 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2179 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2180 FnEntry7BitAbbrev = Stream.EmitAbbrev(Abbv);
2182 // 6-bit char6 VST_FNENTRY function strings.
2183 Abbv = new BitCodeAbbrev();
2184 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2185 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2186 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2187 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2188 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2189 FnEntry6BitAbbrev = Stream.EmitAbbrev(Abbv);
2192 // FIXME: Set up the abbrev, we know how many values there are!
2193 // FIXME: We know if the type names can use 7-bit ascii.
2194 SmallVector<unsigned, 64> NameVals;
2196 for (const ValueName &Name : VST) {
2197 // Figure out the encoding to use for the name.
2198 StringEncoding Bits =
2199 getStringEncoding(Name.getKeyData(), Name.getKeyLength());
2201 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
2202 NameVals.push_back(VE.getValueID(Name.getValue()));
2204 Function *F = dyn_cast<Function>(Name.getValue());
2206 // If value is an alias, need to get the aliased base object to
2207 // see if it is a function.
2208 auto *GA = dyn_cast<GlobalAlias>(Name.getValue());
2209 if (GA && GA->getBaseObject())
2210 F = dyn_cast<Function>(GA->getBaseObject());
2213 // VST_ENTRY: [valueid, namechar x N]
2214 // VST_FNENTRY: [valueid, funcoffset, namechar x N]
2215 // VST_BBENTRY: [bbid, namechar x N]
2217 if (isa<BasicBlock>(Name.getValue())) {
2218 Code = bitc::VST_CODE_BBENTRY;
2219 if (Bits == SE_Char6)
2220 AbbrevToUse = VST_BBENTRY_6_ABBREV;
2221 } else if (F && !F->isDeclaration()) {
2222 // Must be the module-level VST, where we pass in the Index and
2223 // have a VSTOffsetPlaceholder. The function-level VST should not
2224 // contain any Function symbols.
2225 assert(FunctionIndex);
2226 assert(VSTOffsetPlaceholder > 0);
2228 // Save the word offset of the function (from the start of the
2229 // actual bitcode written to the stream).
2230 assert(FunctionIndex->count(F) == 1);
2231 uint64_t BitcodeIndex = (*FunctionIndex)[F] - BitcodeStartBit;
2232 assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
2233 NameVals.push_back(BitcodeIndex / 32);
2235 Code = bitc::VST_CODE_FNENTRY;
2236 AbbrevToUse = FnEntry8BitAbbrev;
2237 if (Bits == SE_Char6)
2238 AbbrevToUse = FnEntry6BitAbbrev;
2239 else if (Bits == SE_Fixed7)
2240 AbbrevToUse = FnEntry7BitAbbrev;
2242 Code = bitc::VST_CODE_ENTRY;
2243 if (Bits == SE_Char6)
2244 AbbrevToUse = VST_ENTRY_6_ABBREV;
2245 else if (Bits == SE_Fixed7)
2246 AbbrevToUse = VST_ENTRY_7_ABBREV;
2249 for (const char *P = Name.getKeyData(),
2250 *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
2251 NameVals.push_back((unsigned char)*P);
2253 // Emit the finished record.
2254 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
2260 static void WriteUseList(ValueEnumerator &VE, UseListOrder &&Order,
2261 BitstreamWriter &Stream) {
2262 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
2264 if (isa<BasicBlock>(Order.V))
2265 Code = bitc::USELIST_CODE_BB;
2267 Code = bitc::USELIST_CODE_DEFAULT;
2269 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
2270 Record.push_back(VE.getValueID(Order.V));
2271 Stream.EmitRecord(Code, Record);
2274 static void WriteUseListBlock(const Function *F, ValueEnumerator &VE,
2275 BitstreamWriter &Stream) {
2276 assert(VE.shouldPreserveUseListOrder() &&
2277 "Expected to be preserving use-list order");
2279 auto hasMore = [&]() {
2280 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
2286 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
2288 WriteUseList(VE, std::move(VE.UseListOrders.back()), Stream);
2289 VE.UseListOrders.pop_back();
2294 /// WriteFunction - Emit a function body to the module stream.
2295 static void WriteFunction(const Function &F, ValueEnumerator &VE,
2296 BitstreamWriter &Stream,
2297 DenseMap<const Function *, uint64_t> &FunctionIndex) {
2298 // Save the bitcode index of the start of this function block for recording
2300 uint64_t BitcodeIndex = Stream.GetCurrentBitNo();
2301 FunctionIndex[&F] = BitcodeIndex;
2303 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
2304 VE.incorporateFunction(F);
2306 SmallVector<unsigned, 64> Vals;
2308 // Emit the number of basic blocks, so the reader can create them ahead of
2310 Vals.push_back(VE.getBasicBlocks().size());
2311 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
2314 // If there are function-local constants, emit them now.
2315 unsigned CstStart, CstEnd;
2316 VE.getFunctionConstantRange(CstStart, CstEnd);
2317 WriteConstants(CstStart, CstEnd, VE, Stream, false);
2319 // If there is function-local metadata, emit it now.
2320 WriteFunctionLocalMetadata(F, VE, Stream);
2322 // Keep a running idea of what the instruction ID is.
2323 unsigned InstID = CstEnd;
2325 bool NeedsMetadataAttachment = F.hasMetadata();
2327 DILocation *LastDL = nullptr;
2329 // Finally, emit all the instructions, in order.
2330 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
2331 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
2333 WriteInstruction(*I, InstID, VE, Stream, Vals);
2335 if (!I->getType()->isVoidTy())
2338 // If the instruction has metadata, write a metadata attachment later.
2339 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
2341 // If the instruction has a debug location, emit it.
2342 DILocation *DL = I->getDebugLoc();
2347 // Just repeat the same debug loc as last time.
2348 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
2352 Vals.push_back(DL->getLine());
2353 Vals.push_back(DL->getColumn());
2354 Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
2355 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
2356 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
2362 // Emit names for all the instructions etc.
2363 WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
2365 if (NeedsMetadataAttachment)
2366 WriteMetadataAttachment(F, VE, Stream);
2367 if (VE.shouldPreserveUseListOrder())
2368 WriteUseListBlock(&F, VE, Stream);
2373 // Emit blockinfo, which defines the standard abbreviations etc.
2374 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
2375 // We only want to emit block info records for blocks that have multiple
2376 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
2377 // Other blocks can define their abbrevs inline.
2378 Stream.EnterBlockInfoBlock(2);
2380 { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
2381 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2382 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
2383 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2384 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2385 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2386 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2387 Abbv) != VST_ENTRY_8_ABBREV)
2388 llvm_unreachable("Unexpected abbrev ordering!");
2391 { // 7-bit fixed width VST_ENTRY strings.
2392 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2393 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2394 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2395 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2396 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2397 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2398 Abbv) != VST_ENTRY_7_ABBREV)
2399 llvm_unreachable("Unexpected abbrev ordering!");
2401 { // 6-bit char6 VST_ENTRY strings.
2402 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2403 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2404 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2405 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2406 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2407 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2408 Abbv) != VST_ENTRY_6_ABBREV)
2409 llvm_unreachable("Unexpected abbrev ordering!");
2411 { // 6-bit char6 VST_BBENTRY strings.
2412 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2413 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
2414 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2415 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2416 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2417 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2418 Abbv) != VST_BBENTRY_6_ABBREV)
2419 llvm_unreachable("Unexpected abbrev ordering!");
2424 { // SETTYPE abbrev for CONSTANTS_BLOCK.
2425 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2426 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
2427 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
2428 VE.computeBitsRequiredForTypeIndicies()));
2429 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2430 Abbv) != CONSTANTS_SETTYPE_ABBREV)
2431 llvm_unreachable("Unexpected abbrev ordering!");
2434 { // INTEGER abbrev for CONSTANTS_BLOCK.
2435 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2436 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
2437 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2438 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2439 Abbv) != CONSTANTS_INTEGER_ABBREV)
2440 llvm_unreachable("Unexpected abbrev ordering!");
2443 { // CE_CAST abbrev for CONSTANTS_BLOCK.
2444 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2445 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
2446 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
2447 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
2448 VE.computeBitsRequiredForTypeIndicies()));
2449 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2451 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2452 Abbv) != CONSTANTS_CE_CAST_Abbrev)
2453 llvm_unreachable("Unexpected abbrev ordering!");
2455 { // NULL abbrev for CONSTANTS_BLOCK.
2456 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2457 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
2458 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2459 Abbv) != CONSTANTS_NULL_Abbrev)
2460 llvm_unreachable("Unexpected abbrev ordering!");
2463 // FIXME: This should only use space for first class types!
2465 { // INST_LOAD abbrev for FUNCTION_BLOCK.
2466 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2467 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
2468 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
2469 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
2470 VE.computeBitsRequiredForTypeIndicies()));
2471 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
2472 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
2473 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2474 Abbv) != FUNCTION_INST_LOAD_ABBREV)
2475 llvm_unreachable("Unexpected abbrev ordering!");
2477 { // INST_BINOP abbrev for FUNCTION_BLOCK.
2478 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2479 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
2480 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
2481 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
2482 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2483 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2484 Abbv) != FUNCTION_INST_BINOP_ABBREV)
2485 llvm_unreachable("Unexpected abbrev ordering!");
2487 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
2488 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2489 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
2490 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
2491 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
2492 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2493 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
2494 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2495 Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV)
2496 llvm_unreachable("Unexpected abbrev ordering!");
2498 { // INST_CAST abbrev for FUNCTION_BLOCK.
2499 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2500 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
2501 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
2502 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
2503 VE.computeBitsRequiredForTypeIndicies()));
2504 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2505 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2506 Abbv) != FUNCTION_INST_CAST_ABBREV)
2507 llvm_unreachable("Unexpected abbrev ordering!");
2510 { // INST_RET abbrev for FUNCTION_BLOCK.
2511 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2512 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
2513 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2514 Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
2515 llvm_unreachable("Unexpected abbrev ordering!");
2517 { // INST_RET abbrev for FUNCTION_BLOCK.
2518 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2519 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
2520 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
2521 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2522 Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
2523 llvm_unreachable("Unexpected abbrev ordering!");
2525 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
2526 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2527 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
2528 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2529 Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
2530 llvm_unreachable("Unexpected abbrev ordering!");
2533 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2534 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
2535 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
2536 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
2537 Log2_32_Ceil(VE.getTypes().size() + 1)));
2538 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2539 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2540 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
2541 FUNCTION_INST_GEP_ABBREV)
2542 llvm_unreachable("Unexpected abbrev ordering!");
2548 /// WriteModule - Emit the specified module to the bitstream.
2549 static void WriteModule(const Module *M, BitstreamWriter &Stream,
2550 bool ShouldPreserveUseListOrder,
2551 uint64_t BitcodeStartBit) {
2552 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
2554 SmallVector<unsigned, 1> Vals;
2555 unsigned CurVersion = 1;
2556 Vals.push_back(CurVersion);
2557 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
2559 // Analyze the module, enumerating globals, functions, etc.
2560 ValueEnumerator VE(*M, ShouldPreserveUseListOrder);
2562 // Emit blockinfo, which defines the standard abbreviations etc.
2563 WriteBlockInfo(VE, Stream);
2565 // Emit information about attribute groups.
2566 WriteAttributeGroupTable(VE, Stream);
2568 // Emit information about parameter attributes.
2569 WriteAttributeTable(VE, Stream);
2571 // Emit information describing all of the types in the module.
2572 WriteTypeTable(VE, Stream);
2574 writeComdats(VE, Stream);
2576 // Emit top-level description of module, including target triple, inline asm,
2577 // descriptors for global variables, and function prototype info.
2578 uint64_t VSTOffsetPlaceholder = WriteModuleInfo(M, VE, Stream);
2581 WriteModuleConstants(VE, Stream);
2584 WriteModuleMetadata(M, VE, Stream);
2587 WriteModuleMetadataStore(M, Stream);
2589 // Emit module-level use-lists.
2590 if (VE.shouldPreserveUseListOrder())
2591 WriteUseListBlock(nullptr, VE, Stream);
2593 // Emit function bodies.
2594 DenseMap<const Function *, uint64_t> FunctionIndex;
2595 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F)
2596 if (!F->isDeclaration())
2597 WriteFunction(*F, VE, Stream, FunctionIndex);
2599 WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream,
2600 VSTOffsetPlaceholder, BitcodeStartBit, &FunctionIndex);
2605 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
2606 /// header and trailer to make it compatible with the system archiver. To do
2607 /// this we emit the following header, and then emit a trailer that pads the
2608 /// file out to be a multiple of 16 bytes.
2610 /// struct bc_header {
2611 /// uint32_t Magic; // 0x0B17C0DE
2612 /// uint32_t Version; // Version, currently always 0.
2613 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
2614 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
2615 /// uint32_t CPUType; // CPU specifier.
2616 /// ... potentially more later ...
2619 DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
2620 DarwinBCHeaderSize = 5*4
2623 static void WriteInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
2624 uint32_t &Position) {
2625 support::endian::write32le(&Buffer[Position], Value);
2629 static void EmitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
2631 unsigned CPUType = ~0U;
2633 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
2634 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
2635 // number from /usr/include/mach/machine.h. It is ok to reproduce the
2636 // specific constants here because they are implicitly part of the Darwin ABI.
2638 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
2639 DARWIN_CPU_TYPE_X86 = 7,
2640 DARWIN_CPU_TYPE_ARM = 12,
2641 DARWIN_CPU_TYPE_POWERPC = 18
2644 Triple::ArchType Arch = TT.getArch();
2645 if (Arch == Triple::x86_64)
2646 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
2647 else if (Arch == Triple::x86)
2648 CPUType = DARWIN_CPU_TYPE_X86;
2649 else if (Arch == Triple::ppc)
2650 CPUType = DARWIN_CPU_TYPE_POWERPC;
2651 else if (Arch == Triple::ppc64)
2652 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
2653 else if (Arch == Triple::arm || Arch == Triple::thumb)
2654 CPUType = DARWIN_CPU_TYPE_ARM;
2656 // Traditional Bitcode starts after header.
2657 assert(Buffer.size() >= DarwinBCHeaderSize &&
2658 "Expected header size to be reserved");
2659 unsigned BCOffset = DarwinBCHeaderSize;
2660 unsigned BCSize = Buffer.size()-DarwinBCHeaderSize;
2662 // Write the magic and version.
2663 unsigned Position = 0;
2664 WriteInt32ToBuffer(0x0B17C0DE , Buffer, Position);
2665 WriteInt32ToBuffer(0 , Buffer, Position); // Version.
2666 WriteInt32ToBuffer(BCOffset , Buffer, Position);
2667 WriteInt32ToBuffer(BCSize , Buffer, Position);
2668 WriteInt32ToBuffer(CPUType , Buffer, Position);
2670 // If the file is not a multiple of 16 bytes, insert dummy padding.
2671 while (Buffer.size() & 15)
2672 Buffer.push_back(0);
2675 /// WriteBitcodeToFile - Write the specified module to the specified output
2677 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out,
2678 bool ShouldPreserveUseListOrder) {
2679 SmallVector<char, 0> Buffer;
2680 Buffer.reserve(256*1024);
2682 // If this is darwin or another generic macho target, reserve space for the
2684 Triple TT(M->getTargetTriple());
2685 if (TT.isOSDarwin())
2686 Buffer.insert(Buffer.begin(), DarwinBCHeaderSize, 0);
2688 // Emit the module into the buffer.
2690 BitstreamWriter Stream(Buffer);
2691 // Save the start bit of the actual bitcode, in case there is space
2692 // saved at the start for the darwin header above. The reader stream
2693 // will start at the bitcode, and we need the offset of the VST
2695 uint64_t BitcodeStartBit = Stream.GetCurrentBitNo();
2697 // Emit the file header.
2698 Stream.Emit((unsigned)'B', 8);
2699 Stream.Emit((unsigned)'C', 8);
2700 Stream.Emit(0x0, 4);
2701 Stream.Emit(0xC, 4);
2702 Stream.Emit(0xE, 4);
2703 Stream.Emit(0xD, 4);
2706 WriteModule(M, Stream, ShouldPreserveUseListOrder, BitcodeStartBit);
2709 if (TT.isOSDarwin())
2710 EmitDarwinBCHeaderAndTrailer(Buffer, TT);
2712 // Write the generated bitstream to "Out".
2713 Out.write((char*)&Buffer.front(), Buffer.size());