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
62 static unsigned GetEncodedCastOpcode(unsigned Opcode) {
64 default: llvm_unreachable("Unknown cast instruction!");
65 case Instruction::Trunc : return bitc::CAST_TRUNC;
66 case Instruction::ZExt : return bitc::CAST_ZEXT;
67 case Instruction::SExt : return bitc::CAST_SEXT;
68 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
69 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
70 case Instruction::UIToFP : return bitc::CAST_UITOFP;
71 case Instruction::SIToFP : return bitc::CAST_SITOFP;
72 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
73 case Instruction::FPExt : return bitc::CAST_FPEXT;
74 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
75 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
76 case Instruction::BitCast : return bitc::CAST_BITCAST;
77 case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
81 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
83 default: llvm_unreachable("Unknown binary instruction!");
84 case Instruction::Add:
85 case Instruction::FAdd: return bitc::BINOP_ADD;
86 case Instruction::Sub:
87 case Instruction::FSub: return bitc::BINOP_SUB;
88 case Instruction::Mul:
89 case Instruction::FMul: return bitc::BINOP_MUL;
90 case Instruction::UDiv: return bitc::BINOP_UDIV;
91 case Instruction::FDiv:
92 case Instruction::SDiv: return bitc::BINOP_SDIV;
93 case Instruction::URem: return bitc::BINOP_UREM;
94 case Instruction::FRem:
95 case Instruction::SRem: return bitc::BINOP_SREM;
96 case Instruction::Shl: return bitc::BINOP_SHL;
97 case Instruction::LShr: return bitc::BINOP_LSHR;
98 case Instruction::AShr: return bitc::BINOP_ASHR;
99 case Instruction::And: return bitc::BINOP_AND;
100 case Instruction::Or: return bitc::BINOP_OR;
101 case Instruction::Xor: return bitc::BINOP_XOR;
105 static unsigned GetEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
107 default: llvm_unreachable("Unknown RMW operation!");
108 case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
109 case AtomicRMWInst::Add: return bitc::RMW_ADD;
110 case AtomicRMWInst::Sub: return bitc::RMW_SUB;
111 case AtomicRMWInst::And: return bitc::RMW_AND;
112 case AtomicRMWInst::Nand: return bitc::RMW_NAND;
113 case AtomicRMWInst::Or: return bitc::RMW_OR;
114 case AtomicRMWInst::Xor: return bitc::RMW_XOR;
115 case AtomicRMWInst::Max: return bitc::RMW_MAX;
116 case AtomicRMWInst::Min: return bitc::RMW_MIN;
117 case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
118 case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
122 static unsigned GetEncodedOrdering(AtomicOrdering Ordering) {
124 case NotAtomic: return bitc::ORDERING_NOTATOMIC;
125 case Unordered: return bitc::ORDERING_UNORDERED;
126 case Monotonic: return bitc::ORDERING_MONOTONIC;
127 case Acquire: return bitc::ORDERING_ACQUIRE;
128 case Release: return bitc::ORDERING_RELEASE;
129 case AcquireRelease: return bitc::ORDERING_ACQREL;
130 case SequentiallyConsistent: return bitc::ORDERING_SEQCST;
132 llvm_unreachable("Invalid ordering");
135 static unsigned GetEncodedSynchScope(SynchronizationScope SynchScope) {
136 switch (SynchScope) {
137 case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD;
138 case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD;
140 llvm_unreachable("Invalid synch scope");
143 static void WriteStringRecord(unsigned Code, StringRef Str,
144 unsigned AbbrevToUse, BitstreamWriter &Stream) {
145 SmallVector<unsigned, 64> Vals;
147 // Code: [strchar x N]
148 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
149 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
151 Vals.push_back(Str[i]);
154 // Emit the finished record.
155 Stream.EmitRecord(Code, Vals, AbbrevToUse);
158 static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
160 case Attribute::Alignment:
161 return bitc::ATTR_KIND_ALIGNMENT;
162 case Attribute::AlwaysInline:
163 return bitc::ATTR_KIND_ALWAYS_INLINE;
164 case Attribute::Builtin:
165 return bitc::ATTR_KIND_BUILTIN;
166 case Attribute::ByVal:
167 return bitc::ATTR_KIND_BY_VAL;
168 case Attribute::InAlloca:
169 return bitc::ATTR_KIND_IN_ALLOCA;
170 case Attribute::Cold:
171 return bitc::ATTR_KIND_COLD;
172 case Attribute::InlineHint:
173 return bitc::ATTR_KIND_INLINE_HINT;
174 case Attribute::InReg:
175 return bitc::ATTR_KIND_IN_REG;
176 case Attribute::JumpTable:
177 return bitc::ATTR_KIND_JUMP_TABLE;
178 case Attribute::MinSize:
179 return bitc::ATTR_KIND_MIN_SIZE;
180 case Attribute::Naked:
181 return bitc::ATTR_KIND_NAKED;
182 case Attribute::Nest:
183 return bitc::ATTR_KIND_NEST;
184 case Attribute::NoAlias:
185 return bitc::ATTR_KIND_NO_ALIAS;
186 case Attribute::NoBuiltin:
187 return bitc::ATTR_KIND_NO_BUILTIN;
188 case Attribute::NoCapture:
189 return bitc::ATTR_KIND_NO_CAPTURE;
190 case Attribute::NoDuplicate:
191 return bitc::ATTR_KIND_NO_DUPLICATE;
192 case Attribute::NoImplicitFloat:
193 return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
194 case Attribute::NoInline:
195 return bitc::ATTR_KIND_NO_INLINE;
196 case Attribute::NonLazyBind:
197 return bitc::ATTR_KIND_NON_LAZY_BIND;
198 case Attribute::NonNull:
199 return bitc::ATTR_KIND_NON_NULL;
200 case Attribute::Dereferenceable:
201 return bitc::ATTR_KIND_DEREFERENCEABLE;
202 case Attribute::NoRedZone:
203 return bitc::ATTR_KIND_NO_RED_ZONE;
204 case Attribute::NoReturn:
205 return bitc::ATTR_KIND_NO_RETURN;
206 case Attribute::NoUnwind:
207 return bitc::ATTR_KIND_NO_UNWIND;
208 case Attribute::OptimizeForSize:
209 return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
210 case Attribute::OptimizeNone:
211 return bitc::ATTR_KIND_OPTIMIZE_NONE;
212 case Attribute::ReadNone:
213 return bitc::ATTR_KIND_READ_NONE;
214 case Attribute::ReadOnly:
215 return bitc::ATTR_KIND_READ_ONLY;
216 case Attribute::Returned:
217 return bitc::ATTR_KIND_RETURNED;
218 case Attribute::ReturnsTwice:
219 return bitc::ATTR_KIND_RETURNS_TWICE;
220 case Attribute::SExt:
221 return bitc::ATTR_KIND_S_EXT;
222 case Attribute::StackAlignment:
223 return bitc::ATTR_KIND_STACK_ALIGNMENT;
224 case Attribute::StackProtect:
225 return bitc::ATTR_KIND_STACK_PROTECT;
226 case Attribute::StackProtectReq:
227 return bitc::ATTR_KIND_STACK_PROTECT_REQ;
228 case Attribute::StackProtectStrong:
229 return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
230 case Attribute::StructRet:
231 return bitc::ATTR_KIND_STRUCT_RET;
232 case Attribute::SanitizeAddress:
233 return bitc::ATTR_KIND_SANITIZE_ADDRESS;
234 case Attribute::SanitizeThread:
235 return bitc::ATTR_KIND_SANITIZE_THREAD;
236 case Attribute::SanitizeMemory:
237 return bitc::ATTR_KIND_SANITIZE_MEMORY;
238 case Attribute::UWTable:
239 return bitc::ATTR_KIND_UW_TABLE;
240 case Attribute::ZExt:
241 return bitc::ATTR_KIND_Z_EXT;
242 case Attribute::EndAttrKinds:
243 llvm_unreachable("Can not encode end-attribute kinds marker.");
244 case Attribute::None:
245 llvm_unreachable("Can not encode none-attribute.");
248 llvm_unreachable("Trying to encode unknown attribute");
251 static void WriteAttributeGroupTable(const ValueEnumerator &VE,
252 BitstreamWriter &Stream) {
253 const std::vector<AttributeSet> &AttrGrps = VE.getAttributeGroups();
254 if (AttrGrps.empty()) return;
256 Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
258 SmallVector<uint64_t, 64> Record;
259 for (unsigned i = 0, e = AttrGrps.size(); i != e; ++i) {
260 AttributeSet AS = AttrGrps[i];
261 for (unsigned i = 0, e = AS.getNumSlots(); i != e; ++i) {
262 AttributeSet A = AS.getSlotAttributes(i);
264 Record.push_back(VE.getAttributeGroupID(A));
265 Record.push_back(AS.getSlotIndex(i));
267 for (AttributeSet::iterator I = AS.begin(0), E = AS.end(0);
270 if (Attr.isEnumAttribute()) {
272 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
273 } else if (Attr.isIntAttribute()) {
275 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
276 Record.push_back(Attr.getValueAsInt());
278 StringRef Kind = Attr.getKindAsString();
279 StringRef Val = Attr.getValueAsString();
281 Record.push_back(Val.empty() ? 3 : 4);
282 Record.append(Kind.begin(), Kind.end());
285 Record.append(Val.begin(), Val.end());
291 Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
299 static void WriteAttributeTable(const ValueEnumerator &VE,
300 BitstreamWriter &Stream) {
301 const std::vector<AttributeSet> &Attrs = VE.getAttributes();
302 if (Attrs.empty()) return;
304 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
306 SmallVector<uint64_t, 64> Record;
307 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
308 const AttributeSet &A = Attrs[i];
309 for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i)
310 Record.push_back(VE.getAttributeGroupID(A.getSlotAttributes(i)));
312 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
319 /// WriteTypeTable - Write out the type table for a module.
320 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
321 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
323 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
324 SmallVector<uint64_t, 64> TypeVals;
326 uint64_t NumBits = Log2_32_Ceil(VE.getTypes().size()+1);
328 // Abbrev for TYPE_CODE_POINTER.
329 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
330 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
331 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
332 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
333 unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
335 // Abbrev for TYPE_CODE_FUNCTION.
336 Abbv = new BitCodeAbbrev();
337 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
338 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
339 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
340 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
342 unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
344 // Abbrev for TYPE_CODE_STRUCT_ANON.
345 Abbv = new BitCodeAbbrev();
346 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
347 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
348 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
349 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
351 unsigned StructAnonAbbrev = Stream.EmitAbbrev(Abbv);
353 // Abbrev for TYPE_CODE_STRUCT_NAME.
354 Abbv = new BitCodeAbbrev();
355 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
356 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
357 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
358 unsigned StructNameAbbrev = Stream.EmitAbbrev(Abbv);
360 // Abbrev for TYPE_CODE_STRUCT_NAMED.
361 Abbv = new BitCodeAbbrev();
362 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
363 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
364 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
365 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
367 unsigned StructNamedAbbrev = Stream.EmitAbbrev(Abbv);
369 // Abbrev for TYPE_CODE_ARRAY.
370 Abbv = new BitCodeAbbrev();
371 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
372 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
373 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
375 unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
377 // Emit an entry count so the reader can reserve space.
378 TypeVals.push_back(TypeList.size());
379 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
382 // Loop over all of the types, emitting each in turn.
383 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
384 Type *T = TypeList[i];
388 switch (T->getTypeID()) {
389 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
390 case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break;
391 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
392 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
393 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
394 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
395 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
396 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
397 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
398 case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break;
399 case Type::IntegerTyID:
401 Code = bitc::TYPE_CODE_INTEGER;
402 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
404 case Type::PointerTyID: {
405 PointerType *PTy = cast<PointerType>(T);
406 // POINTER: [pointee type, address space]
407 Code = bitc::TYPE_CODE_POINTER;
408 TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
409 unsigned AddressSpace = PTy->getAddressSpace();
410 TypeVals.push_back(AddressSpace);
411 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
414 case Type::FunctionTyID: {
415 FunctionType *FT = cast<FunctionType>(T);
416 // FUNCTION: [isvararg, retty, paramty x N]
417 Code = bitc::TYPE_CODE_FUNCTION;
418 TypeVals.push_back(FT->isVarArg());
419 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
420 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
421 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
422 AbbrevToUse = FunctionAbbrev;
425 case Type::StructTyID: {
426 StructType *ST = cast<StructType>(T);
427 // STRUCT: [ispacked, eltty x N]
428 TypeVals.push_back(ST->isPacked());
429 // Output all of the element types.
430 for (StructType::element_iterator I = ST->element_begin(),
431 E = ST->element_end(); I != E; ++I)
432 TypeVals.push_back(VE.getTypeID(*I));
434 if (ST->isLiteral()) {
435 Code = bitc::TYPE_CODE_STRUCT_ANON;
436 AbbrevToUse = StructAnonAbbrev;
438 if (ST->isOpaque()) {
439 Code = bitc::TYPE_CODE_OPAQUE;
441 Code = bitc::TYPE_CODE_STRUCT_NAMED;
442 AbbrevToUse = StructNamedAbbrev;
445 // Emit the name if it is present.
446 if (!ST->getName().empty())
447 WriteStringRecord(bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
448 StructNameAbbrev, Stream);
452 case Type::ArrayTyID: {
453 ArrayType *AT = cast<ArrayType>(T);
454 // ARRAY: [numelts, eltty]
455 Code = bitc::TYPE_CODE_ARRAY;
456 TypeVals.push_back(AT->getNumElements());
457 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
458 AbbrevToUse = ArrayAbbrev;
461 case Type::VectorTyID: {
462 VectorType *VT = cast<VectorType>(T);
463 // VECTOR [numelts, eltty]
464 Code = bitc::TYPE_CODE_VECTOR;
465 TypeVals.push_back(VT->getNumElements());
466 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
471 // Emit the finished record.
472 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
479 static unsigned getEncodedLinkage(const GlobalValue &GV) {
480 switch (GV.getLinkage()) {
481 case GlobalValue::ExternalLinkage:
483 case GlobalValue::WeakAnyLinkage:
485 case GlobalValue::AppendingLinkage:
487 case GlobalValue::InternalLinkage:
489 case GlobalValue::LinkOnceAnyLinkage:
491 case GlobalValue::ExternalWeakLinkage:
493 case GlobalValue::CommonLinkage:
495 case GlobalValue::PrivateLinkage:
497 case GlobalValue::WeakODRLinkage:
499 case GlobalValue::LinkOnceODRLinkage:
501 case GlobalValue::AvailableExternallyLinkage:
504 llvm_unreachable("Invalid linkage");
507 static unsigned getEncodedVisibility(const GlobalValue &GV) {
508 switch (GV.getVisibility()) {
509 case GlobalValue::DefaultVisibility: return 0;
510 case GlobalValue::HiddenVisibility: return 1;
511 case GlobalValue::ProtectedVisibility: return 2;
513 llvm_unreachable("Invalid visibility");
516 static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
517 switch (GV.getDLLStorageClass()) {
518 case GlobalValue::DefaultStorageClass: return 0;
519 case GlobalValue::DLLImportStorageClass: return 1;
520 case GlobalValue::DLLExportStorageClass: return 2;
522 llvm_unreachable("Invalid DLL storage class");
525 static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
526 switch (GV.getThreadLocalMode()) {
527 case GlobalVariable::NotThreadLocal: return 0;
528 case GlobalVariable::GeneralDynamicTLSModel: return 1;
529 case GlobalVariable::LocalDynamicTLSModel: return 2;
530 case GlobalVariable::InitialExecTLSModel: return 3;
531 case GlobalVariable::LocalExecTLSModel: return 4;
533 llvm_unreachable("Invalid TLS model");
536 static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
537 switch (C.getSelectionKind()) {
539 return bitc::COMDAT_SELECTION_KIND_ANY;
540 case Comdat::ExactMatch:
541 return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
542 case Comdat::Largest:
543 return bitc::COMDAT_SELECTION_KIND_LARGEST;
544 case Comdat::NoDuplicates:
545 return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
546 case Comdat::SameSize:
547 return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
549 llvm_unreachable("Invalid selection kind");
552 static void writeComdats(const ValueEnumerator &VE, BitstreamWriter &Stream) {
553 SmallVector<uint16_t, 64> Vals;
554 for (const Comdat *C : VE.getComdats()) {
555 // COMDAT: [selection_kind, name]
556 Vals.push_back(getEncodedComdatSelectionKind(*C));
557 size_t Size = C->getName().size();
558 assert(isUInt<16>(Size));
559 Vals.push_back(Size);
560 for (char Chr : C->getName())
561 Vals.push_back((unsigned char)Chr);
562 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
567 // Emit top-level description of module, including target triple, inline asm,
568 // descriptors for global variables, and function prototype info.
569 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
570 BitstreamWriter &Stream) {
571 // Emit various pieces of data attached to a module.
572 if (!M->getTargetTriple().empty())
573 WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
575 const std::string &DL = M->getDataLayoutStr();
577 WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/, Stream);
578 if (!M->getModuleInlineAsm().empty())
579 WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
582 // Emit information about sections and GC, computing how many there are. Also
583 // compute the maximum alignment value.
584 std::map<std::string, unsigned> SectionMap;
585 std::map<std::string, unsigned> GCMap;
586 unsigned MaxAlignment = 0;
587 unsigned MaxGlobalType = 0;
588 for (const GlobalValue &GV : M->globals()) {
589 MaxAlignment = std::max(MaxAlignment, GV.getAlignment());
590 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getType()));
591 if (GV.hasSection()) {
592 // Give section names unique ID's.
593 unsigned &Entry = SectionMap[GV.getSection()];
595 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
597 Entry = SectionMap.size();
601 for (const Function &F : *M) {
602 MaxAlignment = std::max(MaxAlignment, F.getAlignment());
603 if (F.hasSection()) {
604 // Give section names unique ID's.
605 unsigned &Entry = SectionMap[F.getSection()];
607 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
609 Entry = SectionMap.size();
613 // Same for GC names.
614 unsigned &Entry = GCMap[F.getGC()];
616 WriteStringRecord(bitc::MODULE_CODE_GCNAME, F.getGC(),
618 Entry = GCMap.size();
623 // Emit abbrev for globals, now that we know # sections and max alignment.
624 unsigned SimpleGVarAbbrev = 0;
625 if (!M->global_empty()) {
626 // Add an abbrev for common globals with no visibility or thread localness.
627 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
628 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
629 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
630 Log2_32_Ceil(MaxGlobalType+1)));
631 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Constant.
632 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
633 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
634 if (MaxAlignment == 0) // Alignment.
635 Abbv->Add(BitCodeAbbrevOp(0));
637 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
638 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
639 Log2_32_Ceil(MaxEncAlignment+1)));
641 if (SectionMap.empty()) // Section.
642 Abbv->Add(BitCodeAbbrevOp(0));
644 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
645 Log2_32_Ceil(SectionMap.size()+1)));
646 // Don't bother emitting vis + thread local.
647 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
650 // Emit the global variable information.
651 SmallVector<unsigned, 64> Vals;
652 for (const GlobalVariable &GV : M->globals()) {
653 unsigned AbbrevToUse = 0;
655 // GLOBALVAR: [type, isconst, initid,
656 // linkage, alignment, section, visibility, threadlocal,
657 // unnamed_addr, externally_initialized, dllstorageclass]
658 Vals.push_back(VE.getTypeID(GV.getType()));
659 Vals.push_back(GV.isConstant());
660 Vals.push_back(GV.isDeclaration() ? 0 :
661 (VE.getValueID(GV.getInitializer()) + 1));
662 Vals.push_back(getEncodedLinkage(GV));
663 Vals.push_back(Log2_32(GV.getAlignment())+1);
664 Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0);
665 if (GV.isThreadLocal() ||
666 GV.getVisibility() != GlobalValue::DefaultVisibility ||
667 GV.hasUnnamedAddr() || GV.isExternallyInitialized() ||
668 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
670 Vals.push_back(getEncodedVisibility(GV));
671 Vals.push_back(getEncodedThreadLocalMode(GV));
672 Vals.push_back(GV.hasUnnamedAddr());
673 Vals.push_back(GV.isExternallyInitialized());
674 Vals.push_back(getEncodedDLLStorageClass(GV));
675 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
677 AbbrevToUse = SimpleGVarAbbrev;
680 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
684 // Emit the function proto information.
685 for (const Function &F : *M) {
686 // FUNCTION: [type, callingconv, isproto, linkage, paramattrs, alignment,
687 // section, visibility, gc, unnamed_addr, prologuedata,
688 // dllstorageclass, comdat, prefixdata]
689 Vals.push_back(VE.getTypeID(F.getType()));
690 Vals.push_back(F.getCallingConv());
691 Vals.push_back(F.isDeclaration());
692 Vals.push_back(getEncodedLinkage(F));
693 Vals.push_back(VE.getAttributeID(F.getAttributes()));
694 Vals.push_back(Log2_32(F.getAlignment())+1);
695 Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0);
696 Vals.push_back(getEncodedVisibility(F));
697 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
698 Vals.push_back(F.hasUnnamedAddr());
699 Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
701 Vals.push_back(getEncodedDLLStorageClass(F));
702 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
703 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
706 unsigned AbbrevToUse = 0;
707 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
711 // Emit the alias information.
712 for (const GlobalAlias &A : M->aliases()) {
713 // ALIAS: [alias type, aliasee val#, linkage, visibility]
714 Vals.push_back(VE.getTypeID(A.getType()));
715 Vals.push_back(VE.getValueID(A.getAliasee()));
716 Vals.push_back(getEncodedLinkage(A));
717 Vals.push_back(getEncodedVisibility(A));
718 Vals.push_back(getEncodedDLLStorageClass(A));
719 Vals.push_back(getEncodedThreadLocalMode(A));
720 Vals.push_back(A.hasUnnamedAddr());
721 unsigned AbbrevToUse = 0;
722 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
727 static uint64_t GetOptimizationFlags(const Value *V) {
730 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
731 if (OBO->hasNoSignedWrap())
732 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
733 if (OBO->hasNoUnsignedWrap())
734 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
735 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
737 Flags |= 1 << bitc::PEO_EXACT;
738 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
739 if (FPMO->hasUnsafeAlgebra())
740 Flags |= FastMathFlags::UnsafeAlgebra;
741 if (FPMO->hasNoNaNs())
742 Flags |= FastMathFlags::NoNaNs;
743 if (FPMO->hasNoInfs())
744 Flags |= FastMathFlags::NoInfs;
745 if (FPMO->hasNoSignedZeros())
746 Flags |= FastMathFlags::NoSignedZeros;
747 if (FPMO->hasAllowReciprocal())
748 Flags |= FastMathFlags::AllowReciprocal;
754 static void WriteValueAsMetadata(const ValueAsMetadata *MD,
755 const ValueEnumerator &VE,
756 BitstreamWriter &Stream,
757 SmallVectorImpl<uint64_t> &Record) {
758 // Mimic an MDNode with a value as one operand.
759 Value *V = MD->getValue();
760 Record.push_back(VE.getTypeID(V->getType()));
761 Record.push_back(VE.getValueID(V));
762 Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
766 static void WriteMDTuple(const MDTuple *N, const ValueEnumerator &VE,
767 BitstreamWriter &Stream,
768 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
769 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
770 Metadata *MD = N->getOperand(i);
771 assert(!(MD && isa<LocalAsMetadata>(MD)) &&
772 "Unexpected function-local metadata");
773 Record.push_back(VE.getMetadataOrNullID(MD));
775 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
776 : bitc::METADATA_NODE,
781 static void WriteMDLocation(const MDLocation *N, const ValueEnumerator &VE,
782 BitstreamWriter &Stream,
783 SmallVectorImpl<uint64_t> &Record,
785 Record.push_back(N->isDistinct());
786 Record.push_back(N->getLine());
787 Record.push_back(N->getColumn());
788 Record.push_back(VE.getMetadataID(N->getScope()));
789 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
791 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
795 static void WriteGenericDebugNode(const GenericDebugNode *,
796 const ValueEnumerator &, BitstreamWriter &,
797 SmallVectorImpl<uint64_t> &, unsigned) {
798 llvm_unreachable("unimplemented");
801 static void WriteModuleMetadata(const Module *M,
802 const ValueEnumerator &VE,
803 BitstreamWriter &Stream) {
804 const auto &MDs = VE.getMDs();
805 if (MDs.empty() && M->named_metadata_empty())
808 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
810 unsigned MDSAbbrev = 0;
811 if (VE.hasMDString()) {
812 // Abbrev for METADATA_STRING.
813 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
814 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING));
815 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
816 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
817 MDSAbbrev = Stream.EmitAbbrev(Abbv);
820 unsigned MDLocationAbbrev = 0;
821 if (VE.hasMDLocation()) {
822 // Abbrev for METADATA_LOCATION.
824 // Assume the column is usually under 128, and always output the inlined-at
825 // location (it's never more expensive than building an array size 1).
826 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
827 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
828 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
829 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
830 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
831 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
832 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
833 MDLocationAbbrev = Stream.EmitAbbrev(Abbv);
836 unsigned NameAbbrev = 0;
837 if (!M->named_metadata_empty()) {
838 // Abbrev for METADATA_NAME.
839 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
840 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
841 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
842 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
843 NameAbbrev = Stream.EmitAbbrev(Abbv);
846 unsigned MDTupleAbbrev = 0;
847 unsigned GenericDebugNodeAbbrev = 0;
848 SmallVector<uint64_t, 64> Record;
849 for (const Metadata *MD : MDs) {
850 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
851 switch (N->getMetadataID()) {
853 llvm_unreachable("Invalid MDNode subclass");
854 #define HANDLE_MDNODE_LEAF(CLASS) \
855 case Metadata::CLASS##Kind: \
856 Write##CLASS(cast<CLASS>(N), VE, Stream, Record, CLASS##Abbrev); \
858 #include "llvm/IR/Metadata.def"
861 if (const auto *MDC = dyn_cast<ConstantAsMetadata>(MD)) {
862 WriteValueAsMetadata(MDC, VE, Stream, Record);
865 const MDString *MDS = cast<MDString>(MD);
866 // Code: [strchar x N]
867 Record.append(MDS->bytes_begin(), MDS->bytes_end());
869 // Emit the finished record.
870 Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev);
874 // Write named metadata.
875 for (const NamedMDNode &NMD : M->named_metadata()) {
877 StringRef Str = NMD.getName();
878 Record.append(Str.bytes_begin(), Str.bytes_end());
879 Stream.EmitRecord(bitc::METADATA_NAME, Record, NameAbbrev);
882 // Write named metadata operands.
883 for (const MDNode *N : NMD.operands())
884 Record.push_back(VE.getMetadataID(N));
885 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
892 static void WriteFunctionLocalMetadata(const Function &F,
893 const ValueEnumerator &VE,
894 BitstreamWriter &Stream) {
895 bool StartedMetadataBlock = false;
896 SmallVector<uint64_t, 64> Record;
897 const SmallVectorImpl<const LocalAsMetadata *> &MDs =
898 VE.getFunctionLocalMDs();
899 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
900 assert(MDs[i] && "Expected valid function-local metadata");
901 if (!StartedMetadataBlock) {
902 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
903 StartedMetadataBlock = true;
905 WriteValueAsMetadata(MDs[i], VE, Stream, Record);
908 if (StartedMetadataBlock)
912 static void WriteMetadataAttachment(const Function &F,
913 const ValueEnumerator &VE,
914 BitstreamWriter &Stream) {
915 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
917 SmallVector<uint64_t, 64> Record;
919 // Write metadata attachments
920 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
921 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
923 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
924 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
927 I->getAllMetadataOtherThanDebugLoc(MDs);
929 // If no metadata, ignore instruction.
930 if (MDs.empty()) continue;
932 Record.push_back(VE.getInstructionID(I));
934 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
935 Record.push_back(MDs[i].first);
936 Record.push_back(VE.getMetadataID(MDs[i].second));
938 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
945 static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) {
946 SmallVector<uint64_t, 64> Record;
948 // Write metadata kinds
949 // METADATA_KIND - [n x [id, name]]
950 SmallVector<StringRef, 8> Names;
951 M->getMDKindNames(Names);
953 if (Names.empty()) return;
955 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
957 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
958 Record.push_back(MDKindID);
959 StringRef KName = Names[MDKindID];
960 Record.append(KName.begin(), KName.end());
962 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
969 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
971 Vals.push_back(V << 1);
973 Vals.push_back((-V << 1) | 1);
976 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
977 const ValueEnumerator &VE,
978 BitstreamWriter &Stream, bool isGlobal) {
979 if (FirstVal == LastVal) return;
981 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
983 unsigned AggregateAbbrev = 0;
984 unsigned String8Abbrev = 0;
985 unsigned CString7Abbrev = 0;
986 unsigned CString6Abbrev = 0;
987 // If this is a constant pool for the module, emit module-specific abbrevs.
989 // Abbrev for CST_CODE_AGGREGATE.
990 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
991 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
992 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
993 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
994 AggregateAbbrev = Stream.EmitAbbrev(Abbv);
996 // Abbrev for CST_CODE_STRING.
997 Abbv = new BitCodeAbbrev();
998 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
999 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1000 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1001 String8Abbrev = Stream.EmitAbbrev(Abbv);
1002 // Abbrev for CST_CODE_CSTRING.
1003 Abbv = new BitCodeAbbrev();
1004 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
1005 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1006 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1007 CString7Abbrev = Stream.EmitAbbrev(Abbv);
1008 // Abbrev for CST_CODE_CSTRING.
1009 Abbv = new BitCodeAbbrev();
1010 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
1011 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1012 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1013 CString6Abbrev = Stream.EmitAbbrev(Abbv);
1016 SmallVector<uint64_t, 64> Record;
1018 const ValueEnumerator::ValueList &Vals = VE.getValues();
1019 Type *LastTy = nullptr;
1020 for (unsigned i = FirstVal; i != LastVal; ++i) {
1021 const Value *V = Vals[i].first;
1022 // If we need to switch types, do so now.
1023 if (V->getType() != LastTy) {
1024 LastTy = V->getType();
1025 Record.push_back(VE.getTypeID(LastTy));
1026 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
1027 CONSTANTS_SETTYPE_ABBREV);
1031 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1032 Record.push_back(unsigned(IA->hasSideEffects()) |
1033 unsigned(IA->isAlignStack()) << 1 |
1034 unsigned(IA->getDialect()&1) << 2);
1036 // Add the asm string.
1037 const std::string &AsmStr = IA->getAsmString();
1038 Record.push_back(AsmStr.size());
1039 for (unsigned i = 0, e = AsmStr.size(); i != e; ++i)
1040 Record.push_back(AsmStr[i]);
1042 // Add the constraint string.
1043 const std::string &ConstraintStr = IA->getConstraintString();
1044 Record.push_back(ConstraintStr.size());
1045 for (unsigned i = 0, e = ConstraintStr.size(); i != e; ++i)
1046 Record.push_back(ConstraintStr[i]);
1047 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
1051 const Constant *C = cast<Constant>(V);
1052 unsigned Code = -1U;
1053 unsigned AbbrevToUse = 0;
1054 if (C->isNullValue()) {
1055 Code = bitc::CST_CODE_NULL;
1056 } else if (isa<UndefValue>(C)) {
1057 Code = bitc::CST_CODE_UNDEF;
1058 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
1059 if (IV->getBitWidth() <= 64) {
1060 uint64_t V = IV->getSExtValue();
1061 emitSignedInt64(Record, V);
1062 Code = bitc::CST_CODE_INTEGER;
1063 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
1064 } else { // Wide integers, > 64 bits in size.
1065 // We have an arbitrary precision integer value to write whose
1066 // bit width is > 64. However, in canonical unsigned integer
1067 // format it is likely that the high bits are going to be zero.
1068 // So, we only write the number of active words.
1069 unsigned NWords = IV->getValue().getActiveWords();
1070 const uint64_t *RawWords = IV->getValue().getRawData();
1071 for (unsigned i = 0; i != NWords; ++i) {
1072 emitSignedInt64(Record, RawWords[i]);
1074 Code = bitc::CST_CODE_WIDE_INTEGER;
1076 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
1077 Code = bitc::CST_CODE_FLOAT;
1078 Type *Ty = CFP->getType();
1079 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
1080 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
1081 } else if (Ty->isX86_FP80Ty()) {
1082 // api needed to prevent premature destruction
1083 // bits are not in the same order as a normal i80 APInt, compensate.
1084 APInt api = CFP->getValueAPF().bitcastToAPInt();
1085 const uint64_t *p = api.getRawData();
1086 Record.push_back((p[1] << 48) | (p[0] >> 16));
1087 Record.push_back(p[0] & 0xffffLL);
1088 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
1089 APInt api = CFP->getValueAPF().bitcastToAPInt();
1090 const uint64_t *p = api.getRawData();
1091 Record.push_back(p[0]);
1092 Record.push_back(p[1]);
1094 assert (0 && "Unknown FP type!");
1096 } else if (isa<ConstantDataSequential>(C) &&
1097 cast<ConstantDataSequential>(C)->isString()) {
1098 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
1099 // Emit constant strings specially.
1100 unsigned NumElts = Str->getNumElements();
1101 // If this is a null-terminated string, use the denser CSTRING encoding.
1102 if (Str->isCString()) {
1103 Code = bitc::CST_CODE_CSTRING;
1104 --NumElts; // Don't encode the null, which isn't allowed by char6.
1106 Code = bitc::CST_CODE_STRING;
1107 AbbrevToUse = String8Abbrev;
1109 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
1110 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
1111 for (unsigned i = 0; i != NumElts; ++i) {
1112 unsigned char V = Str->getElementAsInteger(i);
1113 Record.push_back(V);
1114 isCStr7 &= (V & 128) == 0;
1116 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
1120 AbbrevToUse = CString6Abbrev;
1122 AbbrevToUse = CString7Abbrev;
1123 } else if (const ConstantDataSequential *CDS =
1124 dyn_cast<ConstantDataSequential>(C)) {
1125 Code = bitc::CST_CODE_DATA;
1126 Type *EltTy = CDS->getType()->getElementType();
1127 if (isa<IntegerType>(EltTy)) {
1128 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
1129 Record.push_back(CDS->getElementAsInteger(i));
1130 } else if (EltTy->isFloatTy()) {
1131 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1132 union { float F; uint32_t I; };
1133 F = CDS->getElementAsFloat(i);
1134 Record.push_back(I);
1137 assert(EltTy->isDoubleTy() && "Unknown ConstantData element type");
1138 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1139 union { double F; uint64_t I; };
1140 F = CDS->getElementAsDouble(i);
1141 Record.push_back(I);
1144 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
1145 isa<ConstantVector>(C)) {
1146 Code = bitc::CST_CODE_AGGREGATE;
1147 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
1148 Record.push_back(VE.getValueID(C->getOperand(i)));
1149 AbbrevToUse = AggregateAbbrev;
1150 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1151 switch (CE->getOpcode()) {
1153 if (Instruction::isCast(CE->getOpcode())) {
1154 Code = bitc::CST_CODE_CE_CAST;
1155 Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
1156 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1157 Record.push_back(VE.getValueID(C->getOperand(0)));
1158 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
1160 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
1161 Code = bitc::CST_CODE_CE_BINOP;
1162 Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
1163 Record.push_back(VE.getValueID(C->getOperand(0)));
1164 Record.push_back(VE.getValueID(C->getOperand(1)));
1165 uint64_t Flags = GetOptimizationFlags(CE);
1167 Record.push_back(Flags);
1170 case Instruction::GetElementPtr:
1171 Code = bitc::CST_CODE_CE_GEP;
1172 if (cast<GEPOperator>(C)->isInBounds())
1173 Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
1174 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
1175 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
1176 Record.push_back(VE.getValueID(C->getOperand(i)));
1179 case Instruction::Select:
1180 Code = bitc::CST_CODE_CE_SELECT;
1181 Record.push_back(VE.getValueID(C->getOperand(0)));
1182 Record.push_back(VE.getValueID(C->getOperand(1)));
1183 Record.push_back(VE.getValueID(C->getOperand(2)));
1185 case Instruction::ExtractElement:
1186 Code = bitc::CST_CODE_CE_EXTRACTELT;
1187 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1188 Record.push_back(VE.getValueID(C->getOperand(0)));
1189 Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
1190 Record.push_back(VE.getValueID(C->getOperand(1)));
1192 case Instruction::InsertElement:
1193 Code = bitc::CST_CODE_CE_INSERTELT;
1194 Record.push_back(VE.getValueID(C->getOperand(0)));
1195 Record.push_back(VE.getValueID(C->getOperand(1)));
1196 Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
1197 Record.push_back(VE.getValueID(C->getOperand(2)));
1199 case Instruction::ShuffleVector:
1200 // If the return type and argument types are the same, this is a
1201 // standard shufflevector instruction. If the types are different,
1202 // then the shuffle is widening or truncating the input vectors, and
1203 // the argument type must also be encoded.
1204 if (C->getType() == C->getOperand(0)->getType()) {
1205 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
1207 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
1208 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1210 Record.push_back(VE.getValueID(C->getOperand(0)));
1211 Record.push_back(VE.getValueID(C->getOperand(1)));
1212 Record.push_back(VE.getValueID(C->getOperand(2)));
1214 case Instruction::ICmp:
1215 case Instruction::FCmp:
1216 Code = bitc::CST_CODE_CE_CMP;
1217 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1218 Record.push_back(VE.getValueID(C->getOperand(0)));
1219 Record.push_back(VE.getValueID(C->getOperand(1)));
1220 Record.push_back(CE->getPredicate());
1223 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
1224 Code = bitc::CST_CODE_BLOCKADDRESS;
1225 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
1226 Record.push_back(VE.getValueID(BA->getFunction()));
1227 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
1232 llvm_unreachable("Unknown constant!");
1234 Stream.EmitRecord(Code, Record, AbbrevToUse);
1241 static void WriteModuleConstants(const ValueEnumerator &VE,
1242 BitstreamWriter &Stream) {
1243 const ValueEnumerator::ValueList &Vals = VE.getValues();
1245 // Find the first constant to emit, which is the first non-globalvalue value.
1246 // We know globalvalues have been emitted by WriteModuleInfo.
1247 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1248 if (!isa<GlobalValue>(Vals[i].first)) {
1249 WriteConstants(i, Vals.size(), VE, Stream, true);
1255 /// PushValueAndType - The file has to encode both the value and type id for
1256 /// many values, because we need to know what type to create for forward
1257 /// references. However, most operands are not forward references, so this type
1258 /// field is not needed.
1260 /// This function adds V's value ID to Vals. If the value ID is higher than the
1261 /// instruction ID, then it is a forward reference, and it also includes the
1262 /// type ID. The value ID that is written is encoded relative to the InstID.
1263 static bool PushValueAndType(const Value *V, unsigned InstID,
1264 SmallVectorImpl<unsigned> &Vals,
1265 ValueEnumerator &VE) {
1266 unsigned ValID = VE.getValueID(V);
1267 // Make encoding relative to the InstID.
1268 Vals.push_back(InstID - ValID);
1269 if (ValID >= InstID) {
1270 Vals.push_back(VE.getTypeID(V->getType()));
1276 /// pushValue - Like PushValueAndType, but where the type of the value is
1277 /// omitted (perhaps it was already encoded in an earlier operand).
1278 static void pushValue(const Value *V, unsigned InstID,
1279 SmallVectorImpl<unsigned> &Vals,
1280 ValueEnumerator &VE) {
1281 unsigned ValID = VE.getValueID(V);
1282 Vals.push_back(InstID - ValID);
1285 static void pushValueSigned(const Value *V, unsigned InstID,
1286 SmallVectorImpl<uint64_t> &Vals,
1287 ValueEnumerator &VE) {
1288 unsigned ValID = VE.getValueID(V);
1289 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
1290 emitSignedInt64(Vals, diff);
1293 /// WriteInstruction - Emit an instruction to the specified stream.
1294 static void WriteInstruction(const Instruction &I, unsigned InstID,
1295 ValueEnumerator &VE, BitstreamWriter &Stream,
1296 SmallVectorImpl<unsigned> &Vals) {
1298 unsigned AbbrevToUse = 0;
1299 VE.setInstructionID(&I);
1300 switch (I.getOpcode()) {
1302 if (Instruction::isCast(I.getOpcode())) {
1303 Code = bitc::FUNC_CODE_INST_CAST;
1304 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1305 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
1306 Vals.push_back(VE.getTypeID(I.getType()));
1307 Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
1309 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
1310 Code = bitc::FUNC_CODE_INST_BINOP;
1311 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1312 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
1313 pushValue(I.getOperand(1), InstID, Vals, VE);
1314 Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
1315 uint64_t Flags = GetOptimizationFlags(&I);
1317 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
1318 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
1319 Vals.push_back(Flags);
1324 case Instruction::GetElementPtr:
1325 Code = bitc::FUNC_CODE_INST_GEP;
1326 if (cast<GEPOperator>(&I)->isInBounds())
1327 Code = bitc::FUNC_CODE_INST_INBOUNDS_GEP;
1328 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1329 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1331 case Instruction::ExtractValue: {
1332 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
1333 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1334 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
1335 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1339 case Instruction::InsertValue: {
1340 Code = bitc::FUNC_CODE_INST_INSERTVAL;
1341 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1342 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1343 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
1344 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1348 case Instruction::Select:
1349 Code = bitc::FUNC_CODE_INST_VSELECT;
1350 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1351 pushValue(I.getOperand(2), InstID, Vals, VE);
1352 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1354 case Instruction::ExtractElement:
1355 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
1356 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1357 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1359 case Instruction::InsertElement:
1360 Code = bitc::FUNC_CODE_INST_INSERTELT;
1361 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1362 pushValue(I.getOperand(1), InstID, Vals, VE);
1363 PushValueAndType(I.getOperand(2), InstID, Vals, VE);
1365 case Instruction::ShuffleVector:
1366 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
1367 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1368 pushValue(I.getOperand(1), InstID, Vals, VE);
1369 pushValue(I.getOperand(2), InstID, Vals, VE);
1371 case Instruction::ICmp:
1372 case Instruction::FCmp:
1373 // compare returning Int1Ty or vector of Int1Ty
1374 Code = bitc::FUNC_CODE_INST_CMP2;
1375 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1376 pushValue(I.getOperand(1), InstID, Vals, VE);
1377 Vals.push_back(cast<CmpInst>(I).getPredicate());
1380 case Instruction::Ret:
1382 Code = bitc::FUNC_CODE_INST_RET;
1383 unsigned NumOperands = I.getNumOperands();
1384 if (NumOperands == 0)
1385 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
1386 else if (NumOperands == 1) {
1387 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1388 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
1390 for (unsigned i = 0, e = NumOperands; i != e; ++i)
1391 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1395 case Instruction::Br:
1397 Code = bitc::FUNC_CODE_INST_BR;
1398 const BranchInst &II = cast<BranchInst>(I);
1399 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
1400 if (II.isConditional()) {
1401 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
1402 pushValue(II.getCondition(), InstID, Vals, VE);
1406 case Instruction::Switch:
1408 Code = bitc::FUNC_CODE_INST_SWITCH;
1409 const SwitchInst &SI = cast<SwitchInst>(I);
1410 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
1411 pushValue(SI.getCondition(), InstID, Vals, VE);
1412 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
1413 for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
1415 Vals.push_back(VE.getValueID(i.getCaseValue()));
1416 Vals.push_back(VE.getValueID(i.getCaseSuccessor()));
1420 case Instruction::IndirectBr:
1421 Code = bitc::FUNC_CODE_INST_INDIRECTBR;
1422 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1423 // Encode the address operand as relative, but not the basic blocks.
1424 pushValue(I.getOperand(0), InstID, Vals, VE);
1425 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
1426 Vals.push_back(VE.getValueID(I.getOperand(i)));
1429 case Instruction::Invoke: {
1430 const InvokeInst *II = cast<InvokeInst>(&I);
1431 const Value *Callee(II->getCalledValue());
1432 PointerType *PTy = cast<PointerType>(Callee->getType());
1433 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1434 Code = bitc::FUNC_CODE_INST_INVOKE;
1436 Vals.push_back(VE.getAttributeID(II->getAttributes()));
1437 Vals.push_back(II->getCallingConv());
1438 Vals.push_back(VE.getValueID(II->getNormalDest()));
1439 Vals.push_back(VE.getValueID(II->getUnwindDest()));
1440 PushValueAndType(Callee, InstID, Vals, VE);
1442 // Emit value #'s for the fixed parameters.
1443 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1444 pushValue(I.getOperand(i), InstID, Vals, VE); // fixed param.
1446 // Emit type/value pairs for varargs params.
1447 if (FTy->isVarArg()) {
1448 for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
1450 PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
1454 case Instruction::Resume:
1455 Code = bitc::FUNC_CODE_INST_RESUME;
1456 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1458 case Instruction::Unreachable:
1459 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
1460 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
1463 case Instruction::PHI: {
1464 const PHINode &PN = cast<PHINode>(I);
1465 Code = bitc::FUNC_CODE_INST_PHI;
1466 // With the newer instruction encoding, forward references could give
1467 // negative valued IDs. This is most common for PHIs, so we use
1469 SmallVector<uint64_t, 128> Vals64;
1470 Vals64.push_back(VE.getTypeID(PN.getType()));
1471 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1472 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64, VE);
1473 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
1475 // Emit a Vals64 vector and exit.
1476 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
1481 case Instruction::LandingPad: {
1482 const LandingPadInst &LP = cast<LandingPadInst>(I);
1483 Code = bitc::FUNC_CODE_INST_LANDINGPAD;
1484 Vals.push_back(VE.getTypeID(LP.getType()));
1485 PushValueAndType(LP.getPersonalityFn(), InstID, Vals, VE);
1486 Vals.push_back(LP.isCleanup());
1487 Vals.push_back(LP.getNumClauses());
1488 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
1490 Vals.push_back(LandingPadInst::Catch);
1492 Vals.push_back(LandingPadInst::Filter);
1493 PushValueAndType(LP.getClause(I), InstID, Vals, VE);
1498 case Instruction::Alloca: {
1499 Code = bitc::FUNC_CODE_INST_ALLOCA;
1500 Vals.push_back(VE.getTypeID(I.getType()));
1501 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1502 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
1503 const AllocaInst &AI = cast<AllocaInst>(I);
1504 unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
1505 assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
1506 "not enough bits for maximum alignment");
1507 assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
1508 AlignRecord |= AI.isUsedWithInAlloca() << 5;
1509 Vals.push_back(AlignRecord);
1513 case Instruction::Load:
1514 if (cast<LoadInst>(I).isAtomic()) {
1515 Code = bitc::FUNC_CODE_INST_LOADATOMIC;
1516 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1518 Code = bitc::FUNC_CODE_INST_LOAD;
1519 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) // ptr
1520 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
1522 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
1523 Vals.push_back(cast<LoadInst>(I).isVolatile());
1524 if (cast<LoadInst>(I).isAtomic()) {
1525 Vals.push_back(GetEncodedOrdering(cast<LoadInst>(I).getOrdering()));
1526 Vals.push_back(GetEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
1529 case Instruction::Store:
1530 if (cast<StoreInst>(I).isAtomic())
1531 Code = bitc::FUNC_CODE_INST_STOREATOMIC;
1533 Code = bitc::FUNC_CODE_INST_STORE;
1534 PushValueAndType(I.getOperand(1), InstID, Vals, VE); // ptrty + ptr
1535 pushValue(I.getOperand(0), InstID, Vals, VE); // val.
1536 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
1537 Vals.push_back(cast<StoreInst>(I).isVolatile());
1538 if (cast<StoreInst>(I).isAtomic()) {
1539 Vals.push_back(GetEncodedOrdering(cast<StoreInst>(I).getOrdering()));
1540 Vals.push_back(GetEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
1543 case Instruction::AtomicCmpXchg:
1544 Code = bitc::FUNC_CODE_INST_CMPXCHG;
1545 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr
1546 pushValue(I.getOperand(1), InstID, Vals, VE); // cmp.
1547 pushValue(I.getOperand(2), InstID, Vals, VE); // newval.
1548 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
1549 Vals.push_back(GetEncodedOrdering(
1550 cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
1551 Vals.push_back(GetEncodedSynchScope(
1552 cast<AtomicCmpXchgInst>(I).getSynchScope()));
1553 Vals.push_back(GetEncodedOrdering(
1554 cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
1555 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
1557 case Instruction::AtomicRMW:
1558 Code = bitc::FUNC_CODE_INST_ATOMICRMW;
1559 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr
1560 pushValue(I.getOperand(1), InstID, Vals, VE); // val.
1561 Vals.push_back(GetEncodedRMWOperation(
1562 cast<AtomicRMWInst>(I).getOperation()));
1563 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
1564 Vals.push_back(GetEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
1565 Vals.push_back(GetEncodedSynchScope(
1566 cast<AtomicRMWInst>(I).getSynchScope()));
1568 case Instruction::Fence:
1569 Code = bitc::FUNC_CODE_INST_FENCE;
1570 Vals.push_back(GetEncodedOrdering(cast<FenceInst>(I).getOrdering()));
1571 Vals.push_back(GetEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
1573 case Instruction::Call: {
1574 const CallInst &CI = cast<CallInst>(I);
1575 PointerType *PTy = cast<PointerType>(CI.getCalledValue()->getType());
1576 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1578 Code = bitc::FUNC_CODE_INST_CALL;
1580 Vals.push_back(VE.getAttributeID(CI.getAttributes()));
1581 Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall()) |
1582 unsigned(CI.isMustTailCall()) << 14);
1583 PushValueAndType(CI.getCalledValue(), InstID, Vals, VE); // Callee
1585 // Emit value #'s for the fixed parameters.
1586 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
1587 // Check for labels (can happen with asm labels).
1588 if (FTy->getParamType(i)->isLabelTy())
1589 Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
1591 pushValue(CI.getArgOperand(i), InstID, Vals, VE); // fixed param.
1594 // Emit type/value pairs for varargs params.
1595 if (FTy->isVarArg()) {
1596 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
1598 PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE); // varargs
1602 case Instruction::VAArg:
1603 Code = bitc::FUNC_CODE_INST_VAARG;
1604 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
1605 pushValue(I.getOperand(0), InstID, Vals, VE); // valist.
1606 Vals.push_back(VE.getTypeID(I.getType())); // restype.
1610 Stream.EmitRecord(Code, Vals, AbbrevToUse);
1614 // Emit names for globals/functions etc.
1615 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
1616 const ValueEnumerator &VE,
1617 BitstreamWriter &Stream) {
1618 if (VST.empty()) return;
1619 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
1621 // FIXME: Set up the abbrev, we know how many values there are!
1622 // FIXME: We know if the type names can use 7-bit ascii.
1623 SmallVector<unsigned, 64> NameVals;
1625 for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
1628 const ValueName &Name = *SI;
1630 // Figure out the encoding to use for the name.
1632 bool isChar6 = true;
1633 for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
1636 isChar6 = BitCodeAbbrevOp::isChar6(*C);
1637 if ((unsigned char)*C & 128) {
1639 break; // don't bother scanning the rest.
1643 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
1645 // VST_ENTRY: [valueid, namechar x N]
1646 // VST_BBENTRY: [bbid, namechar x N]
1648 if (isa<BasicBlock>(SI->getValue())) {
1649 Code = bitc::VST_CODE_BBENTRY;
1651 AbbrevToUse = VST_BBENTRY_6_ABBREV;
1653 Code = bitc::VST_CODE_ENTRY;
1655 AbbrevToUse = VST_ENTRY_6_ABBREV;
1657 AbbrevToUse = VST_ENTRY_7_ABBREV;
1660 NameVals.push_back(VE.getValueID(SI->getValue()));
1661 for (const char *P = Name.getKeyData(),
1662 *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
1663 NameVals.push_back((unsigned char)*P);
1665 // Emit the finished record.
1666 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
1672 static void WriteUseList(ValueEnumerator &VE, UseListOrder &&Order,
1673 BitstreamWriter &Stream) {
1674 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
1676 if (isa<BasicBlock>(Order.V))
1677 Code = bitc::USELIST_CODE_BB;
1679 Code = bitc::USELIST_CODE_DEFAULT;
1681 SmallVector<uint64_t, 64> Record;
1682 for (unsigned I : Order.Shuffle)
1683 Record.push_back(I);
1684 Record.push_back(VE.getValueID(Order.V));
1685 Stream.EmitRecord(Code, Record);
1688 static void WriteUseListBlock(const Function *F, ValueEnumerator &VE,
1689 BitstreamWriter &Stream) {
1690 auto hasMore = [&]() {
1691 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
1697 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
1699 WriteUseList(VE, std::move(VE.UseListOrders.back()), Stream);
1700 VE.UseListOrders.pop_back();
1705 /// WriteFunction - Emit a function body to the module stream.
1706 static void WriteFunction(const Function &F, ValueEnumerator &VE,
1707 BitstreamWriter &Stream) {
1708 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
1709 VE.incorporateFunction(F);
1711 SmallVector<unsigned, 64> Vals;
1713 // Emit the number of basic blocks, so the reader can create them ahead of
1715 Vals.push_back(VE.getBasicBlocks().size());
1716 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
1719 // If there are function-local constants, emit them now.
1720 unsigned CstStart, CstEnd;
1721 VE.getFunctionConstantRange(CstStart, CstEnd);
1722 WriteConstants(CstStart, CstEnd, VE, Stream, false);
1724 // If there is function-local metadata, emit it now.
1725 WriteFunctionLocalMetadata(F, VE, Stream);
1727 // Keep a running idea of what the instruction ID is.
1728 unsigned InstID = CstEnd;
1730 bool NeedsMetadataAttachment = false;
1734 // Finally, emit all the instructions, in order.
1735 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1736 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1738 WriteInstruction(*I, InstID, VE, Stream, Vals);
1740 if (!I->getType()->isVoidTy())
1743 // If the instruction has metadata, write a metadata attachment later.
1744 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
1746 // If the instruction has a debug location, emit it.
1747 DebugLoc DL = I->getDebugLoc();
1748 if (DL.isUnknown()) {
1750 } else if (DL == LastDL) {
1751 // Just repeat the same debug loc as last time.
1752 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
1755 DL.getScopeAndInlinedAt(Scope, IA, I->getContext());
1756 assert(Scope && "Expected valid scope");
1758 Vals.push_back(DL.getLine());
1759 Vals.push_back(DL.getCol());
1760 Vals.push_back(VE.getMetadataOrNullID(Scope));
1761 Vals.push_back(VE.getMetadataOrNullID(IA));
1762 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
1769 // Emit names for all the instructions etc.
1770 WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
1772 if (NeedsMetadataAttachment)
1773 WriteMetadataAttachment(F, VE, Stream);
1774 if (shouldPreserveBitcodeUseListOrder())
1775 WriteUseListBlock(&F, VE, Stream);
1780 // Emit blockinfo, which defines the standard abbreviations etc.
1781 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
1782 // We only want to emit block info records for blocks that have multiple
1783 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
1784 // Other blocks can define their abbrevs inline.
1785 Stream.EnterBlockInfoBlock(2);
1787 { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
1788 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1789 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
1790 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1791 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1792 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1793 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1794 Abbv) != VST_ENTRY_8_ABBREV)
1795 llvm_unreachable("Unexpected abbrev ordering!");
1798 { // 7-bit fixed width VST_ENTRY strings.
1799 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1800 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1801 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1802 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1803 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1804 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1805 Abbv) != VST_ENTRY_7_ABBREV)
1806 llvm_unreachable("Unexpected abbrev ordering!");
1808 { // 6-bit char6 VST_ENTRY strings.
1809 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1810 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1811 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1812 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1813 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1814 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1815 Abbv) != VST_ENTRY_6_ABBREV)
1816 llvm_unreachable("Unexpected abbrev ordering!");
1818 { // 6-bit char6 VST_BBENTRY strings.
1819 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1820 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
1821 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1822 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1823 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1824 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1825 Abbv) != VST_BBENTRY_6_ABBREV)
1826 llvm_unreachable("Unexpected abbrev ordering!");
1831 { // SETTYPE abbrev for CONSTANTS_BLOCK.
1832 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1833 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
1834 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1835 Log2_32_Ceil(VE.getTypes().size()+1)));
1836 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1837 Abbv) != CONSTANTS_SETTYPE_ABBREV)
1838 llvm_unreachable("Unexpected abbrev ordering!");
1841 { // INTEGER abbrev for CONSTANTS_BLOCK.
1842 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1843 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
1844 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1845 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1846 Abbv) != CONSTANTS_INTEGER_ABBREV)
1847 llvm_unreachable("Unexpected abbrev ordering!");
1850 { // CE_CAST abbrev for CONSTANTS_BLOCK.
1851 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1852 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
1853 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
1854 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
1855 Log2_32_Ceil(VE.getTypes().size()+1)));
1856 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
1858 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1859 Abbv) != CONSTANTS_CE_CAST_Abbrev)
1860 llvm_unreachable("Unexpected abbrev ordering!");
1862 { // NULL abbrev for CONSTANTS_BLOCK.
1863 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1864 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
1865 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1866 Abbv) != CONSTANTS_NULL_Abbrev)
1867 llvm_unreachable("Unexpected abbrev ordering!");
1870 // FIXME: This should only use space for first class types!
1872 { // INST_LOAD abbrev for FUNCTION_BLOCK.
1873 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1874 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
1875 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
1876 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
1877 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
1878 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1879 Abbv) != FUNCTION_INST_LOAD_ABBREV)
1880 llvm_unreachable("Unexpected abbrev ordering!");
1882 { // INST_BINOP abbrev for FUNCTION_BLOCK.
1883 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1884 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1885 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1886 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1887 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1888 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1889 Abbv) != FUNCTION_INST_BINOP_ABBREV)
1890 llvm_unreachable("Unexpected abbrev ordering!");
1892 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
1893 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1894 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1895 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1896 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1897 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1898 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
1899 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1900 Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV)
1901 llvm_unreachable("Unexpected abbrev ordering!");
1903 { // INST_CAST abbrev for FUNCTION_BLOCK.
1904 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1905 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
1906 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
1907 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
1908 Log2_32_Ceil(VE.getTypes().size()+1)));
1909 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1910 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1911 Abbv) != FUNCTION_INST_CAST_ABBREV)
1912 llvm_unreachable("Unexpected abbrev ordering!");
1915 { // INST_RET abbrev for FUNCTION_BLOCK.
1916 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1917 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1918 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1919 Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
1920 llvm_unreachable("Unexpected abbrev ordering!");
1922 { // INST_RET abbrev for FUNCTION_BLOCK.
1923 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1924 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1925 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
1926 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1927 Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
1928 llvm_unreachable("Unexpected abbrev ordering!");
1930 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
1931 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1932 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
1933 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1934 Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
1935 llvm_unreachable("Unexpected abbrev ordering!");
1941 /// WriteModule - Emit the specified module to the bitstream.
1942 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
1943 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
1945 SmallVector<unsigned, 1> Vals;
1946 unsigned CurVersion = 1;
1947 Vals.push_back(CurVersion);
1948 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
1950 // Analyze the module, enumerating globals, functions, etc.
1951 ValueEnumerator VE(*M);
1953 // Emit blockinfo, which defines the standard abbreviations etc.
1954 WriteBlockInfo(VE, Stream);
1956 // Emit information about attribute groups.
1957 WriteAttributeGroupTable(VE, Stream);
1959 // Emit information about parameter attributes.
1960 WriteAttributeTable(VE, Stream);
1962 // Emit information describing all of the types in the module.
1963 WriteTypeTable(VE, Stream);
1965 writeComdats(VE, Stream);
1967 // Emit top-level description of module, including target triple, inline asm,
1968 // descriptors for global variables, and function prototype info.
1969 WriteModuleInfo(M, VE, Stream);
1972 WriteModuleConstants(VE, Stream);
1975 WriteModuleMetadata(M, VE, Stream);
1978 WriteModuleMetadataStore(M, Stream);
1980 // Emit names for globals/functions etc.
1981 WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
1983 // Emit module-level use-lists.
1984 if (shouldPreserveBitcodeUseListOrder())
1985 WriteUseListBlock(nullptr, VE, Stream);
1987 // Emit function bodies.
1988 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F)
1989 if (!F->isDeclaration())
1990 WriteFunction(*F, VE, Stream);
1995 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
1996 /// header and trailer to make it compatible with the system archiver. To do
1997 /// this we emit the following header, and then emit a trailer that pads the
1998 /// file out to be a multiple of 16 bytes.
2000 /// struct bc_header {
2001 /// uint32_t Magic; // 0x0B17C0DE
2002 /// uint32_t Version; // Version, currently always 0.
2003 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
2004 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
2005 /// uint32_t CPUType; // CPU specifier.
2006 /// ... potentially more later ...
2009 DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
2010 DarwinBCHeaderSize = 5*4
2013 static void WriteInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
2014 uint32_t &Position) {
2015 Buffer[Position + 0] = (unsigned char) (Value >> 0);
2016 Buffer[Position + 1] = (unsigned char) (Value >> 8);
2017 Buffer[Position + 2] = (unsigned char) (Value >> 16);
2018 Buffer[Position + 3] = (unsigned char) (Value >> 24);
2022 static void EmitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
2024 unsigned CPUType = ~0U;
2026 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
2027 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
2028 // number from /usr/include/mach/machine.h. It is ok to reproduce the
2029 // specific constants here because they are implicitly part of the Darwin ABI.
2031 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
2032 DARWIN_CPU_TYPE_X86 = 7,
2033 DARWIN_CPU_TYPE_ARM = 12,
2034 DARWIN_CPU_TYPE_POWERPC = 18
2037 Triple::ArchType Arch = TT.getArch();
2038 if (Arch == Triple::x86_64)
2039 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
2040 else if (Arch == Triple::x86)
2041 CPUType = DARWIN_CPU_TYPE_X86;
2042 else if (Arch == Triple::ppc)
2043 CPUType = DARWIN_CPU_TYPE_POWERPC;
2044 else if (Arch == Triple::ppc64)
2045 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
2046 else if (Arch == Triple::arm || Arch == Triple::thumb)
2047 CPUType = DARWIN_CPU_TYPE_ARM;
2049 // Traditional Bitcode starts after header.
2050 assert(Buffer.size() >= DarwinBCHeaderSize &&
2051 "Expected header size to be reserved");
2052 unsigned BCOffset = DarwinBCHeaderSize;
2053 unsigned BCSize = Buffer.size()-DarwinBCHeaderSize;
2055 // Write the magic and version.
2056 unsigned Position = 0;
2057 WriteInt32ToBuffer(0x0B17C0DE , Buffer, Position);
2058 WriteInt32ToBuffer(0 , Buffer, Position); // Version.
2059 WriteInt32ToBuffer(BCOffset , Buffer, Position);
2060 WriteInt32ToBuffer(BCSize , Buffer, Position);
2061 WriteInt32ToBuffer(CPUType , Buffer, Position);
2063 // If the file is not a multiple of 16 bytes, insert dummy padding.
2064 while (Buffer.size() & 15)
2065 Buffer.push_back(0);
2068 /// WriteBitcodeToFile - Write the specified module to the specified output
2070 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out) {
2071 SmallVector<char, 0> Buffer;
2072 Buffer.reserve(256*1024);
2074 // If this is darwin or another generic macho target, reserve space for the
2076 Triple TT(M->getTargetTriple());
2077 if (TT.isOSDarwin())
2078 Buffer.insert(Buffer.begin(), DarwinBCHeaderSize, 0);
2080 // Emit the module into the buffer.
2082 BitstreamWriter Stream(Buffer);
2084 // Emit the file header.
2085 Stream.Emit((unsigned)'B', 8);
2086 Stream.Emit((unsigned)'C', 8);
2087 Stream.Emit(0x0, 4);
2088 Stream.Emit(0xC, 4);
2089 Stream.Emit(0xE, 4);
2090 Stream.Emit(0xD, 4);
2093 WriteModule(M, Stream);
2096 if (TT.isOSDarwin())
2097 EmitDarwinBCHeaderAndTrailer(Buffer, TT);
2099 // Write the generated bitstream to "Out".
2100 Out.write((char*)&Buffer.front(), Buffer.size());