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,
659 Vals.push_back(VE.getTypeID(GV.getType()));
660 Vals.push_back(GV.isConstant());
661 Vals.push_back(GV.isDeclaration() ? 0 :
662 (VE.getValueID(GV.getInitializer()) + 1));
663 Vals.push_back(getEncodedLinkage(GV));
664 Vals.push_back(Log2_32(GV.getAlignment())+1);
665 Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0);
666 if (GV.isThreadLocal() ||
667 GV.getVisibility() != GlobalValue::DefaultVisibility ||
668 GV.hasUnnamedAddr() || GV.isExternallyInitialized() ||
669 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
671 Vals.push_back(getEncodedVisibility(GV));
672 Vals.push_back(getEncodedThreadLocalMode(GV));
673 Vals.push_back(GV.hasUnnamedAddr());
674 Vals.push_back(GV.isExternallyInitialized());
675 Vals.push_back(getEncodedDLLStorageClass(GV));
676 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
678 AbbrevToUse = SimpleGVarAbbrev;
681 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
685 // Emit the function proto information.
686 for (const Function &F : *M) {
687 // FUNCTION: [type, callingconv, isproto, linkage, paramattrs, alignment,
688 // section, visibility, gc, unnamed_addr, prologuedata,
689 // dllstorageclass, comdat, prefixdata]
690 Vals.push_back(VE.getTypeID(F.getType()));
691 Vals.push_back(F.getCallingConv());
692 Vals.push_back(F.isDeclaration());
693 Vals.push_back(getEncodedLinkage(F));
694 Vals.push_back(VE.getAttributeID(F.getAttributes()));
695 Vals.push_back(Log2_32(F.getAlignment())+1);
696 Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0);
697 Vals.push_back(getEncodedVisibility(F));
698 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
699 Vals.push_back(F.hasUnnamedAddr());
700 Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
702 Vals.push_back(getEncodedDLLStorageClass(F));
703 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
704 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
707 unsigned AbbrevToUse = 0;
708 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
712 // Emit the alias information.
713 for (const GlobalAlias &A : M->aliases()) {
714 // ALIAS: [alias type, aliasee val#, linkage, visibility]
715 Vals.push_back(VE.getTypeID(A.getType()));
716 Vals.push_back(VE.getValueID(A.getAliasee()));
717 Vals.push_back(getEncodedLinkage(A));
718 Vals.push_back(getEncodedVisibility(A));
719 Vals.push_back(getEncodedDLLStorageClass(A));
720 Vals.push_back(getEncodedThreadLocalMode(A));
721 Vals.push_back(A.hasUnnamedAddr());
722 unsigned AbbrevToUse = 0;
723 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
728 static uint64_t GetOptimizationFlags(const Value *V) {
731 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
732 if (OBO->hasNoSignedWrap())
733 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
734 if (OBO->hasNoUnsignedWrap())
735 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
736 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
738 Flags |= 1 << bitc::PEO_EXACT;
739 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
740 if (FPMO->hasUnsafeAlgebra())
741 Flags |= FastMathFlags::UnsafeAlgebra;
742 if (FPMO->hasNoNaNs())
743 Flags |= FastMathFlags::NoNaNs;
744 if (FPMO->hasNoInfs())
745 Flags |= FastMathFlags::NoInfs;
746 if (FPMO->hasNoSignedZeros())
747 Flags |= FastMathFlags::NoSignedZeros;
748 if (FPMO->hasAllowReciprocal())
749 Flags |= FastMathFlags::AllowReciprocal;
755 static void WriteValueAsMetadata(const ValueAsMetadata *MD,
756 const ValueEnumerator &VE,
757 BitstreamWriter &Stream,
758 SmallVectorImpl<uint64_t> &Record) {
759 // Mimic an MDNode with a value as one operand.
760 Value *V = MD->getValue();
761 Record.push_back(VE.getTypeID(V->getType()));
762 Record.push_back(VE.getValueID(V));
763 Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
767 static void WriteMDTuple(const MDTuple *N, const ValueEnumerator &VE,
768 BitstreamWriter &Stream,
769 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
770 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
771 Metadata *MD = N->getOperand(i);
772 assert(!(MD && isa<LocalAsMetadata>(MD)) &&
773 "Unexpected function-local metadata");
774 Record.push_back(VE.getMetadataOrNullID(MD));
776 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
777 : bitc::METADATA_NODE,
782 static void WriteMDLocation(const MDLocation *N, const ValueEnumerator &VE,
783 BitstreamWriter &Stream,
784 SmallVectorImpl<uint64_t> &Record,
786 Record.push_back(N->isDistinct());
787 Record.push_back(N->getLine());
788 Record.push_back(N->getColumn());
789 Record.push_back(VE.getMetadataID(N->getScope()));
790 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
792 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
796 static void WriteGenericDebugNode(const GenericDebugNode *N,
797 const ValueEnumerator &VE,
798 BitstreamWriter &Stream,
799 SmallVectorImpl<uint64_t> &Record,
801 Record.push_back(N->isDistinct());
802 Record.push_back(N->getTag());
803 Record.push_back(0); // Per-tag version field; unused for now.
805 for (auto &I : N->operands())
806 Record.push_back(VE.getMetadataOrNullID(I));
808 Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
812 static void WriteModuleMetadata(const Module *M,
813 const ValueEnumerator &VE,
814 BitstreamWriter &Stream) {
815 const auto &MDs = VE.getMDs();
816 if (MDs.empty() && M->named_metadata_empty())
819 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
821 unsigned MDSAbbrev = 0;
822 if (VE.hasMDString()) {
823 // Abbrev for METADATA_STRING.
824 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
825 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING));
826 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
827 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
828 MDSAbbrev = Stream.EmitAbbrev(Abbv);
831 unsigned MDLocationAbbrev = 0;
832 if (VE.hasMDLocation()) {
833 // Abbrev for METADATA_LOCATION.
835 // Assume the column is usually under 128, and always output the inlined-at
836 // location (it's never more expensive than building an array size 1).
837 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
838 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
839 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
840 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
841 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
842 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
843 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
844 MDLocationAbbrev = Stream.EmitAbbrev(Abbv);
847 unsigned GenericDebugNodeAbbrev = 0;
848 if (VE.hasGenericDebugNode()) {
849 // Abbrev for METADATA_GENERIC_DEBUG.
851 // Assume the column is usually under 128, and always output the inlined-at
852 // location (it's never more expensive than building an array size 1).
853 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
854 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
855 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
856 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
857 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
858 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
859 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
860 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
861 GenericDebugNodeAbbrev = Stream.EmitAbbrev(Abbv);
864 unsigned NameAbbrev = 0;
865 if (!M->named_metadata_empty()) {
866 // Abbrev for METADATA_NAME.
867 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
868 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
869 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
870 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
871 NameAbbrev = Stream.EmitAbbrev(Abbv);
874 unsigned MDTupleAbbrev = 0;
875 SmallVector<uint64_t, 64> Record;
876 for (const Metadata *MD : MDs) {
877 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
878 switch (N->getMetadataID()) {
880 llvm_unreachable("Invalid MDNode subclass");
881 #define HANDLE_MDNODE_LEAF(CLASS) \
882 case Metadata::CLASS##Kind: \
883 Write##CLASS(cast<CLASS>(N), VE, Stream, Record, CLASS##Abbrev); \
885 #include "llvm/IR/Metadata.def"
888 if (const auto *MDC = dyn_cast<ConstantAsMetadata>(MD)) {
889 WriteValueAsMetadata(MDC, VE, Stream, Record);
892 const MDString *MDS = cast<MDString>(MD);
893 // Code: [strchar x N]
894 Record.append(MDS->bytes_begin(), MDS->bytes_end());
896 // Emit the finished record.
897 Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev);
901 // Write named metadata.
902 for (const NamedMDNode &NMD : M->named_metadata()) {
904 StringRef Str = NMD.getName();
905 Record.append(Str.bytes_begin(), Str.bytes_end());
906 Stream.EmitRecord(bitc::METADATA_NAME, Record, NameAbbrev);
909 // Write named metadata operands.
910 for (const MDNode *N : NMD.operands())
911 Record.push_back(VE.getMetadataID(N));
912 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
919 static void WriteFunctionLocalMetadata(const Function &F,
920 const ValueEnumerator &VE,
921 BitstreamWriter &Stream) {
922 bool StartedMetadataBlock = false;
923 SmallVector<uint64_t, 64> Record;
924 const SmallVectorImpl<const LocalAsMetadata *> &MDs =
925 VE.getFunctionLocalMDs();
926 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
927 assert(MDs[i] && "Expected valid function-local metadata");
928 if (!StartedMetadataBlock) {
929 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
930 StartedMetadataBlock = true;
932 WriteValueAsMetadata(MDs[i], VE, Stream, Record);
935 if (StartedMetadataBlock)
939 static void WriteMetadataAttachment(const Function &F,
940 const ValueEnumerator &VE,
941 BitstreamWriter &Stream) {
942 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
944 SmallVector<uint64_t, 64> Record;
946 // Write metadata attachments
947 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
948 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
950 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
951 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
954 I->getAllMetadataOtherThanDebugLoc(MDs);
956 // If no metadata, ignore instruction.
957 if (MDs.empty()) continue;
959 Record.push_back(VE.getInstructionID(I));
961 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
962 Record.push_back(MDs[i].first);
963 Record.push_back(VE.getMetadataID(MDs[i].second));
965 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
972 static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) {
973 SmallVector<uint64_t, 64> Record;
975 // Write metadata kinds
976 // METADATA_KIND - [n x [id, name]]
977 SmallVector<StringRef, 8> Names;
978 M->getMDKindNames(Names);
980 if (Names.empty()) return;
982 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
984 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
985 Record.push_back(MDKindID);
986 StringRef KName = Names[MDKindID];
987 Record.append(KName.begin(), KName.end());
989 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
996 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
998 Vals.push_back(V << 1);
1000 Vals.push_back((-V << 1) | 1);
1003 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
1004 const ValueEnumerator &VE,
1005 BitstreamWriter &Stream, bool isGlobal) {
1006 if (FirstVal == LastVal) return;
1008 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
1010 unsigned AggregateAbbrev = 0;
1011 unsigned String8Abbrev = 0;
1012 unsigned CString7Abbrev = 0;
1013 unsigned CString6Abbrev = 0;
1014 // If this is a constant pool for the module, emit module-specific abbrevs.
1016 // Abbrev for CST_CODE_AGGREGATE.
1017 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1018 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
1019 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1020 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
1021 AggregateAbbrev = Stream.EmitAbbrev(Abbv);
1023 // Abbrev for CST_CODE_STRING.
1024 Abbv = new BitCodeAbbrev();
1025 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
1026 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1027 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1028 String8Abbrev = Stream.EmitAbbrev(Abbv);
1029 // Abbrev for CST_CODE_CSTRING.
1030 Abbv = new BitCodeAbbrev();
1031 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
1032 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1033 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1034 CString7Abbrev = Stream.EmitAbbrev(Abbv);
1035 // Abbrev for CST_CODE_CSTRING.
1036 Abbv = new BitCodeAbbrev();
1037 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
1038 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1039 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1040 CString6Abbrev = Stream.EmitAbbrev(Abbv);
1043 SmallVector<uint64_t, 64> Record;
1045 const ValueEnumerator::ValueList &Vals = VE.getValues();
1046 Type *LastTy = nullptr;
1047 for (unsigned i = FirstVal; i != LastVal; ++i) {
1048 const Value *V = Vals[i].first;
1049 // If we need to switch types, do so now.
1050 if (V->getType() != LastTy) {
1051 LastTy = V->getType();
1052 Record.push_back(VE.getTypeID(LastTy));
1053 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
1054 CONSTANTS_SETTYPE_ABBREV);
1058 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1059 Record.push_back(unsigned(IA->hasSideEffects()) |
1060 unsigned(IA->isAlignStack()) << 1 |
1061 unsigned(IA->getDialect()&1) << 2);
1063 // Add the asm string.
1064 const std::string &AsmStr = IA->getAsmString();
1065 Record.push_back(AsmStr.size());
1066 for (unsigned i = 0, e = AsmStr.size(); i != e; ++i)
1067 Record.push_back(AsmStr[i]);
1069 // Add the constraint string.
1070 const std::string &ConstraintStr = IA->getConstraintString();
1071 Record.push_back(ConstraintStr.size());
1072 for (unsigned i = 0, e = ConstraintStr.size(); i != e; ++i)
1073 Record.push_back(ConstraintStr[i]);
1074 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
1078 const Constant *C = cast<Constant>(V);
1079 unsigned Code = -1U;
1080 unsigned AbbrevToUse = 0;
1081 if (C->isNullValue()) {
1082 Code = bitc::CST_CODE_NULL;
1083 } else if (isa<UndefValue>(C)) {
1084 Code = bitc::CST_CODE_UNDEF;
1085 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
1086 if (IV->getBitWidth() <= 64) {
1087 uint64_t V = IV->getSExtValue();
1088 emitSignedInt64(Record, V);
1089 Code = bitc::CST_CODE_INTEGER;
1090 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
1091 } else { // Wide integers, > 64 bits in size.
1092 // We have an arbitrary precision integer value to write whose
1093 // bit width is > 64. However, in canonical unsigned integer
1094 // format it is likely that the high bits are going to be zero.
1095 // So, we only write the number of active words.
1096 unsigned NWords = IV->getValue().getActiveWords();
1097 const uint64_t *RawWords = IV->getValue().getRawData();
1098 for (unsigned i = 0; i != NWords; ++i) {
1099 emitSignedInt64(Record, RawWords[i]);
1101 Code = bitc::CST_CODE_WIDE_INTEGER;
1103 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
1104 Code = bitc::CST_CODE_FLOAT;
1105 Type *Ty = CFP->getType();
1106 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
1107 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
1108 } else if (Ty->isX86_FP80Ty()) {
1109 // api needed to prevent premature destruction
1110 // bits are not in the same order as a normal i80 APInt, compensate.
1111 APInt api = CFP->getValueAPF().bitcastToAPInt();
1112 const uint64_t *p = api.getRawData();
1113 Record.push_back((p[1] << 48) | (p[0] >> 16));
1114 Record.push_back(p[0] & 0xffffLL);
1115 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
1116 APInt api = CFP->getValueAPF().bitcastToAPInt();
1117 const uint64_t *p = api.getRawData();
1118 Record.push_back(p[0]);
1119 Record.push_back(p[1]);
1121 assert (0 && "Unknown FP type!");
1123 } else if (isa<ConstantDataSequential>(C) &&
1124 cast<ConstantDataSequential>(C)->isString()) {
1125 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
1126 // Emit constant strings specially.
1127 unsigned NumElts = Str->getNumElements();
1128 // If this is a null-terminated string, use the denser CSTRING encoding.
1129 if (Str->isCString()) {
1130 Code = bitc::CST_CODE_CSTRING;
1131 --NumElts; // Don't encode the null, which isn't allowed by char6.
1133 Code = bitc::CST_CODE_STRING;
1134 AbbrevToUse = String8Abbrev;
1136 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
1137 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
1138 for (unsigned i = 0; i != NumElts; ++i) {
1139 unsigned char V = Str->getElementAsInteger(i);
1140 Record.push_back(V);
1141 isCStr7 &= (V & 128) == 0;
1143 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
1147 AbbrevToUse = CString6Abbrev;
1149 AbbrevToUse = CString7Abbrev;
1150 } else if (const ConstantDataSequential *CDS =
1151 dyn_cast<ConstantDataSequential>(C)) {
1152 Code = bitc::CST_CODE_DATA;
1153 Type *EltTy = CDS->getType()->getElementType();
1154 if (isa<IntegerType>(EltTy)) {
1155 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
1156 Record.push_back(CDS->getElementAsInteger(i));
1157 } else if (EltTy->isFloatTy()) {
1158 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1159 union { float F; uint32_t I; };
1160 F = CDS->getElementAsFloat(i);
1161 Record.push_back(I);
1164 assert(EltTy->isDoubleTy() && "Unknown ConstantData element type");
1165 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1166 union { double F; uint64_t I; };
1167 F = CDS->getElementAsDouble(i);
1168 Record.push_back(I);
1171 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
1172 isa<ConstantVector>(C)) {
1173 Code = bitc::CST_CODE_AGGREGATE;
1174 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
1175 Record.push_back(VE.getValueID(C->getOperand(i)));
1176 AbbrevToUse = AggregateAbbrev;
1177 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1178 switch (CE->getOpcode()) {
1180 if (Instruction::isCast(CE->getOpcode())) {
1181 Code = bitc::CST_CODE_CE_CAST;
1182 Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
1183 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1184 Record.push_back(VE.getValueID(C->getOperand(0)));
1185 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
1187 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
1188 Code = bitc::CST_CODE_CE_BINOP;
1189 Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
1190 Record.push_back(VE.getValueID(C->getOperand(0)));
1191 Record.push_back(VE.getValueID(C->getOperand(1)));
1192 uint64_t Flags = GetOptimizationFlags(CE);
1194 Record.push_back(Flags);
1197 case Instruction::GetElementPtr:
1198 Code = bitc::CST_CODE_CE_GEP;
1199 if (cast<GEPOperator>(C)->isInBounds())
1200 Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
1201 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
1202 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
1203 Record.push_back(VE.getValueID(C->getOperand(i)));
1206 case Instruction::Select:
1207 Code = bitc::CST_CODE_CE_SELECT;
1208 Record.push_back(VE.getValueID(C->getOperand(0)));
1209 Record.push_back(VE.getValueID(C->getOperand(1)));
1210 Record.push_back(VE.getValueID(C->getOperand(2)));
1212 case Instruction::ExtractElement:
1213 Code = bitc::CST_CODE_CE_EXTRACTELT;
1214 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1215 Record.push_back(VE.getValueID(C->getOperand(0)));
1216 Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
1217 Record.push_back(VE.getValueID(C->getOperand(1)));
1219 case Instruction::InsertElement:
1220 Code = bitc::CST_CODE_CE_INSERTELT;
1221 Record.push_back(VE.getValueID(C->getOperand(0)));
1222 Record.push_back(VE.getValueID(C->getOperand(1)));
1223 Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
1224 Record.push_back(VE.getValueID(C->getOperand(2)));
1226 case Instruction::ShuffleVector:
1227 // If the return type and argument types are the same, this is a
1228 // standard shufflevector instruction. If the types are different,
1229 // then the shuffle is widening or truncating the input vectors, and
1230 // the argument type must also be encoded.
1231 if (C->getType() == C->getOperand(0)->getType()) {
1232 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
1234 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
1235 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1237 Record.push_back(VE.getValueID(C->getOperand(0)));
1238 Record.push_back(VE.getValueID(C->getOperand(1)));
1239 Record.push_back(VE.getValueID(C->getOperand(2)));
1241 case Instruction::ICmp:
1242 case Instruction::FCmp:
1243 Code = bitc::CST_CODE_CE_CMP;
1244 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1245 Record.push_back(VE.getValueID(C->getOperand(0)));
1246 Record.push_back(VE.getValueID(C->getOperand(1)));
1247 Record.push_back(CE->getPredicate());
1250 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
1251 Code = bitc::CST_CODE_BLOCKADDRESS;
1252 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
1253 Record.push_back(VE.getValueID(BA->getFunction()));
1254 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
1259 llvm_unreachable("Unknown constant!");
1261 Stream.EmitRecord(Code, Record, AbbrevToUse);
1268 static void WriteModuleConstants(const ValueEnumerator &VE,
1269 BitstreamWriter &Stream) {
1270 const ValueEnumerator::ValueList &Vals = VE.getValues();
1272 // Find the first constant to emit, which is the first non-globalvalue value.
1273 // We know globalvalues have been emitted by WriteModuleInfo.
1274 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1275 if (!isa<GlobalValue>(Vals[i].first)) {
1276 WriteConstants(i, Vals.size(), VE, Stream, true);
1282 /// PushValueAndType - The file has to encode both the value and type id for
1283 /// many values, because we need to know what type to create for forward
1284 /// references. However, most operands are not forward references, so this type
1285 /// field is not needed.
1287 /// This function adds V's value ID to Vals. If the value ID is higher than the
1288 /// instruction ID, then it is a forward reference, and it also includes the
1289 /// type ID. The value ID that is written is encoded relative to the InstID.
1290 static bool PushValueAndType(const Value *V, unsigned InstID,
1291 SmallVectorImpl<unsigned> &Vals,
1292 ValueEnumerator &VE) {
1293 unsigned ValID = VE.getValueID(V);
1294 // Make encoding relative to the InstID.
1295 Vals.push_back(InstID - ValID);
1296 if (ValID >= InstID) {
1297 Vals.push_back(VE.getTypeID(V->getType()));
1303 /// pushValue - Like PushValueAndType, but where the type of the value is
1304 /// omitted (perhaps it was already encoded in an earlier operand).
1305 static void pushValue(const Value *V, unsigned InstID,
1306 SmallVectorImpl<unsigned> &Vals,
1307 ValueEnumerator &VE) {
1308 unsigned ValID = VE.getValueID(V);
1309 Vals.push_back(InstID - ValID);
1312 static void pushValueSigned(const Value *V, unsigned InstID,
1313 SmallVectorImpl<uint64_t> &Vals,
1314 ValueEnumerator &VE) {
1315 unsigned ValID = VE.getValueID(V);
1316 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
1317 emitSignedInt64(Vals, diff);
1320 /// WriteInstruction - Emit an instruction to the specified stream.
1321 static void WriteInstruction(const Instruction &I, unsigned InstID,
1322 ValueEnumerator &VE, BitstreamWriter &Stream,
1323 SmallVectorImpl<unsigned> &Vals) {
1325 unsigned AbbrevToUse = 0;
1326 VE.setInstructionID(&I);
1327 switch (I.getOpcode()) {
1329 if (Instruction::isCast(I.getOpcode())) {
1330 Code = bitc::FUNC_CODE_INST_CAST;
1331 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1332 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
1333 Vals.push_back(VE.getTypeID(I.getType()));
1334 Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
1336 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
1337 Code = bitc::FUNC_CODE_INST_BINOP;
1338 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1339 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
1340 pushValue(I.getOperand(1), InstID, Vals, VE);
1341 Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
1342 uint64_t Flags = GetOptimizationFlags(&I);
1344 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
1345 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
1346 Vals.push_back(Flags);
1351 case Instruction::GetElementPtr:
1352 Code = bitc::FUNC_CODE_INST_GEP;
1353 if (cast<GEPOperator>(&I)->isInBounds())
1354 Code = bitc::FUNC_CODE_INST_INBOUNDS_GEP;
1355 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1356 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1358 case Instruction::ExtractValue: {
1359 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
1360 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1361 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
1362 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1366 case Instruction::InsertValue: {
1367 Code = bitc::FUNC_CODE_INST_INSERTVAL;
1368 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1369 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1370 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
1371 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1375 case Instruction::Select:
1376 Code = bitc::FUNC_CODE_INST_VSELECT;
1377 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1378 pushValue(I.getOperand(2), InstID, Vals, VE);
1379 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1381 case Instruction::ExtractElement:
1382 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
1383 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1384 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1386 case Instruction::InsertElement:
1387 Code = bitc::FUNC_CODE_INST_INSERTELT;
1388 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1389 pushValue(I.getOperand(1), InstID, Vals, VE);
1390 PushValueAndType(I.getOperand(2), InstID, Vals, VE);
1392 case Instruction::ShuffleVector:
1393 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
1394 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1395 pushValue(I.getOperand(1), InstID, Vals, VE);
1396 pushValue(I.getOperand(2), InstID, Vals, VE);
1398 case Instruction::ICmp:
1399 case Instruction::FCmp:
1400 // compare returning Int1Ty or vector of Int1Ty
1401 Code = bitc::FUNC_CODE_INST_CMP2;
1402 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1403 pushValue(I.getOperand(1), InstID, Vals, VE);
1404 Vals.push_back(cast<CmpInst>(I).getPredicate());
1407 case Instruction::Ret:
1409 Code = bitc::FUNC_CODE_INST_RET;
1410 unsigned NumOperands = I.getNumOperands();
1411 if (NumOperands == 0)
1412 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
1413 else if (NumOperands == 1) {
1414 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1415 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
1417 for (unsigned i = 0, e = NumOperands; i != e; ++i)
1418 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1422 case Instruction::Br:
1424 Code = bitc::FUNC_CODE_INST_BR;
1425 const BranchInst &II = cast<BranchInst>(I);
1426 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
1427 if (II.isConditional()) {
1428 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
1429 pushValue(II.getCondition(), InstID, Vals, VE);
1433 case Instruction::Switch:
1435 Code = bitc::FUNC_CODE_INST_SWITCH;
1436 const SwitchInst &SI = cast<SwitchInst>(I);
1437 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
1438 pushValue(SI.getCondition(), InstID, Vals, VE);
1439 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
1440 for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
1442 Vals.push_back(VE.getValueID(i.getCaseValue()));
1443 Vals.push_back(VE.getValueID(i.getCaseSuccessor()));
1447 case Instruction::IndirectBr:
1448 Code = bitc::FUNC_CODE_INST_INDIRECTBR;
1449 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1450 // Encode the address operand as relative, but not the basic blocks.
1451 pushValue(I.getOperand(0), InstID, Vals, VE);
1452 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
1453 Vals.push_back(VE.getValueID(I.getOperand(i)));
1456 case Instruction::Invoke: {
1457 const InvokeInst *II = cast<InvokeInst>(&I);
1458 const Value *Callee(II->getCalledValue());
1459 PointerType *PTy = cast<PointerType>(Callee->getType());
1460 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1461 Code = bitc::FUNC_CODE_INST_INVOKE;
1463 Vals.push_back(VE.getAttributeID(II->getAttributes()));
1464 Vals.push_back(II->getCallingConv());
1465 Vals.push_back(VE.getValueID(II->getNormalDest()));
1466 Vals.push_back(VE.getValueID(II->getUnwindDest()));
1467 PushValueAndType(Callee, InstID, Vals, VE);
1469 // Emit value #'s for the fixed parameters.
1470 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1471 pushValue(I.getOperand(i), InstID, Vals, VE); // fixed param.
1473 // Emit type/value pairs for varargs params.
1474 if (FTy->isVarArg()) {
1475 for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
1477 PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
1481 case Instruction::Resume:
1482 Code = bitc::FUNC_CODE_INST_RESUME;
1483 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1485 case Instruction::Unreachable:
1486 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
1487 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
1490 case Instruction::PHI: {
1491 const PHINode &PN = cast<PHINode>(I);
1492 Code = bitc::FUNC_CODE_INST_PHI;
1493 // With the newer instruction encoding, forward references could give
1494 // negative valued IDs. This is most common for PHIs, so we use
1496 SmallVector<uint64_t, 128> Vals64;
1497 Vals64.push_back(VE.getTypeID(PN.getType()));
1498 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1499 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64, VE);
1500 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
1502 // Emit a Vals64 vector and exit.
1503 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
1508 case Instruction::LandingPad: {
1509 const LandingPadInst &LP = cast<LandingPadInst>(I);
1510 Code = bitc::FUNC_CODE_INST_LANDINGPAD;
1511 Vals.push_back(VE.getTypeID(LP.getType()));
1512 PushValueAndType(LP.getPersonalityFn(), InstID, Vals, VE);
1513 Vals.push_back(LP.isCleanup());
1514 Vals.push_back(LP.getNumClauses());
1515 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
1517 Vals.push_back(LandingPadInst::Catch);
1519 Vals.push_back(LandingPadInst::Filter);
1520 PushValueAndType(LP.getClause(I), InstID, Vals, VE);
1525 case Instruction::Alloca: {
1526 Code = bitc::FUNC_CODE_INST_ALLOCA;
1527 Vals.push_back(VE.getTypeID(I.getType()));
1528 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1529 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
1530 const AllocaInst &AI = cast<AllocaInst>(I);
1531 unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
1532 assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
1533 "not enough bits for maximum alignment");
1534 assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
1535 AlignRecord |= AI.isUsedWithInAlloca() << 5;
1536 Vals.push_back(AlignRecord);
1540 case Instruction::Load:
1541 if (cast<LoadInst>(I).isAtomic()) {
1542 Code = bitc::FUNC_CODE_INST_LOADATOMIC;
1543 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1545 Code = bitc::FUNC_CODE_INST_LOAD;
1546 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) // ptr
1547 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
1549 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
1550 Vals.push_back(cast<LoadInst>(I).isVolatile());
1551 if (cast<LoadInst>(I).isAtomic()) {
1552 Vals.push_back(GetEncodedOrdering(cast<LoadInst>(I).getOrdering()));
1553 Vals.push_back(GetEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
1556 case Instruction::Store:
1557 if (cast<StoreInst>(I).isAtomic())
1558 Code = bitc::FUNC_CODE_INST_STOREATOMIC;
1560 Code = bitc::FUNC_CODE_INST_STORE;
1561 PushValueAndType(I.getOperand(1), InstID, Vals, VE); // ptrty + ptr
1562 pushValue(I.getOperand(0), InstID, Vals, VE); // val.
1563 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
1564 Vals.push_back(cast<StoreInst>(I).isVolatile());
1565 if (cast<StoreInst>(I).isAtomic()) {
1566 Vals.push_back(GetEncodedOrdering(cast<StoreInst>(I).getOrdering()));
1567 Vals.push_back(GetEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
1570 case Instruction::AtomicCmpXchg:
1571 Code = bitc::FUNC_CODE_INST_CMPXCHG;
1572 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr
1573 pushValue(I.getOperand(1), InstID, Vals, VE); // cmp.
1574 pushValue(I.getOperand(2), InstID, Vals, VE); // newval.
1575 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
1576 Vals.push_back(GetEncodedOrdering(
1577 cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
1578 Vals.push_back(GetEncodedSynchScope(
1579 cast<AtomicCmpXchgInst>(I).getSynchScope()));
1580 Vals.push_back(GetEncodedOrdering(
1581 cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
1582 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
1584 case Instruction::AtomicRMW:
1585 Code = bitc::FUNC_CODE_INST_ATOMICRMW;
1586 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr
1587 pushValue(I.getOperand(1), InstID, Vals, VE); // val.
1588 Vals.push_back(GetEncodedRMWOperation(
1589 cast<AtomicRMWInst>(I).getOperation()));
1590 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
1591 Vals.push_back(GetEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
1592 Vals.push_back(GetEncodedSynchScope(
1593 cast<AtomicRMWInst>(I).getSynchScope()));
1595 case Instruction::Fence:
1596 Code = bitc::FUNC_CODE_INST_FENCE;
1597 Vals.push_back(GetEncodedOrdering(cast<FenceInst>(I).getOrdering()));
1598 Vals.push_back(GetEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
1600 case Instruction::Call: {
1601 const CallInst &CI = cast<CallInst>(I);
1602 PointerType *PTy = cast<PointerType>(CI.getCalledValue()->getType());
1603 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1605 Code = bitc::FUNC_CODE_INST_CALL;
1607 Vals.push_back(VE.getAttributeID(CI.getAttributes()));
1608 Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall()) |
1609 unsigned(CI.isMustTailCall()) << 14);
1610 PushValueAndType(CI.getCalledValue(), InstID, Vals, VE); // Callee
1612 // Emit value #'s for the fixed parameters.
1613 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
1614 // Check for labels (can happen with asm labels).
1615 if (FTy->getParamType(i)->isLabelTy())
1616 Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
1618 pushValue(CI.getArgOperand(i), InstID, Vals, VE); // fixed param.
1621 // Emit type/value pairs for varargs params.
1622 if (FTy->isVarArg()) {
1623 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
1625 PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE); // varargs
1629 case Instruction::VAArg:
1630 Code = bitc::FUNC_CODE_INST_VAARG;
1631 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
1632 pushValue(I.getOperand(0), InstID, Vals, VE); // valist.
1633 Vals.push_back(VE.getTypeID(I.getType())); // restype.
1637 Stream.EmitRecord(Code, Vals, AbbrevToUse);
1641 // Emit names for globals/functions etc.
1642 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
1643 const ValueEnumerator &VE,
1644 BitstreamWriter &Stream) {
1645 if (VST.empty()) return;
1646 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
1648 // FIXME: Set up the abbrev, we know how many values there are!
1649 // FIXME: We know if the type names can use 7-bit ascii.
1650 SmallVector<unsigned, 64> NameVals;
1652 for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
1655 const ValueName &Name = *SI;
1657 // Figure out the encoding to use for the name.
1659 bool isChar6 = true;
1660 for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
1663 isChar6 = BitCodeAbbrevOp::isChar6(*C);
1664 if ((unsigned char)*C & 128) {
1666 break; // don't bother scanning the rest.
1670 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
1672 // VST_ENTRY: [valueid, namechar x N]
1673 // VST_BBENTRY: [bbid, namechar x N]
1675 if (isa<BasicBlock>(SI->getValue())) {
1676 Code = bitc::VST_CODE_BBENTRY;
1678 AbbrevToUse = VST_BBENTRY_6_ABBREV;
1680 Code = bitc::VST_CODE_ENTRY;
1682 AbbrevToUse = VST_ENTRY_6_ABBREV;
1684 AbbrevToUse = VST_ENTRY_7_ABBREV;
1687 NameVals.push_back(VE.getValueID(SI->getValue()));
1688 for (const char *P = Name.getKeyData(),
1689 *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
1690 NameVals.push_back((unsigned char)*P);
1692 // Emit the finished record.
1693 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
1699 static void WriteUseList(ValueEnumerator &VE, UseListOrder &&Order,
1700 BitstreamWriter &Stream) {
1701 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
1703 if (isa<BasicBlock>(Order.V))
1704 Code = bitc::USELIST_CODE_BB;
1706 Code = bitc::USELIST_CODE_DEFAULT;
1708 SmallVector<uint64_t, 64> Record;
1709 for (unsigned I : Order.Shuffle)
1710 Record.push_back(I);
1711 Record.push_back(VE.getValueID(Order.V));
1712 Stream.EmitRecord(Code, Record);
1715 static void WriteUseListBlock(const Function *F, ValueEnumerator &VE,
1716 BitstreamWriter &Stream) {
1717 auto hasMore = [&]() {
1718 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
1724 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
1726 WriteUseList(VE, std::move(VE.UseListOrders.back()), Stream);
1727 VE.UseListOrders.pop_back();
1732 /// WriteFunction - Emit a function body to the module stream.
1733 static void WriteFunction(const Function &F, ValueEnumerator &VE,
1734 BitstreamWriter &Stream) {
1735 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
1736 VE.incorporateFunction(F);
1738 SmallVector<unsigned, 64> Vals;
1740 // Emit the number of basic blocks, so the reader can create them ahead of
1742 Vals.push_back(VE.getBasicBlocks().size());
1743 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
1746 // If there are function-local constants, emit them now.
1747 unsigned CstStart, CstEnd;
1748 VE.getFunctionConstantRange(CstStart, CstEnd);
1749 WriteConstants(CstStart, CstEnd, VE, Stream, false);
1751 // If there is function-local metadata, emit it now.
1752 WriteFunctionLocalMetadata(F, VE, Stream);
1754 // Keep a running idea of what the instruction ID is.
1755 unsigned InstID = CstEnd;
1757 bool NeedsMetadataAttachment = false;
1761 // Finally, emit all the instructions, in order.
1762 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1763 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1765 WriteInstruction(*I, InstID, VE, Stream, Vals);
1767 if (!I->getType()->isVoidTy())
1770 // If the instruction has metadata, write a metadata attachment later.
1771 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
1773 // If the instruction has a debug location, emit it.
1774 DebugLoc DL = I->getDebugLoc();
1775 if (DL.isUnknown()) {
1777 } else if (DL == LastDL) {
1778 // Just repeat the same debug loc as last time.
1779 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
1782 DL.getScopeAndInlinedAt(Scope, IA, I->getContext());
1783 assert(Scope && "Expected valid scope");
1785 Vals.push_back(DL.getLine());
1786 Vals.push_back(DL.getCol());
1787 Vals.push_back(VE.getMetadataOrNullID(Scope));
1788 Vals.push_back(VE.getMetadataOrNullID(IA));
1789 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
1796 // Emit names for all the instructions etc.
1797 WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
1799 if (NeedsMetadataAttachment)
1800 WriteMetadataAttachment(F, VE, Stream);
1801 if (shouldPreserveBitcodeUseListOrder())
1802 WriteUseListBlock(&F, VE, Stream);
1807 // Emit blockinfo, which defines the standard abbreviations etc.
1808 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
1809 // We only want to emit block info records for blocks that have multiple
1810 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
1811 // Other blocks can define their abbrevs inline.
1812 Stream.EnterBlockInfoBlock(2);
1814 { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
1815 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1816 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
1817 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1818 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1819 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1820 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1821 Abbv) != VST_ENTRY_8_ABBREV)
1822 llvm_unreachable("Unexpected abbrev ordering!");
1825 { // 7-bit fixed width VST_ENTRY strings.
1826 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1827 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1828 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1829 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1830 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1831 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1832 Abbv) != VST_ENTRY_7_ABBREV)
1833 llvm_unreachable("Unexpected abbrev ordering!");
1835 { // 6-bit char6 VST_ENTRY strings.
1836 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1837 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1838 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1839 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1840 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1841 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1842 Abbv) != VST_ENTRY_6_ABBREV)
1843 llvm_unreachable("Unexpected abbrev ordering!");
1845 { // 6-bit char6 VST_BBENTRY strings.
1846 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1847 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
1848 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1849 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1850 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1851 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1852 Abbv) != VST_BBENTRY_6_ABBREV)
1853 llvm_unreachable("Unexpected abbrev ordering!");
1858 { // SETTYPE abbrev for CONSTANTS_BLOCK.
1859 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1860 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
1861 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1862 Log2_32_Ceil(VE.getTypes().size()+1)));
1863 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1864 Abbv) != CONSTANTS_SETTYPE_ABBREV)
1865 llvm_unreachable("Unexpected abbrev ordering!");
1868 { // INTEGER abbrev for CONSTANTS_BLOCK.
1869 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1870 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
1871 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1872 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1873 Abbv) != CONSTANTS_INTEGER_ABBREV)
1874 llvm_unreachable("Unexpected abbrev ordering!");
1877 { // CE_CAST abbrev for CONSTANTS_BLOCK.
1878 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1879 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
1880 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
1881 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
1882 Log2_32_Ceil(VE.getTypes().size()+1)));
1883 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
1885 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1886 Abbv) != CONSTANTS_CE_CAST_Abbrev)
1887 llvm_unreachable("Unexpected abbrev ordering!");
1889 { // NULL abbrev for CONSTANTS_BLOCK.
1890 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1891 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
1892 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1893 Abbv) != CONSTANTS_NULL_Abbrev)
1894 llvm_unreachable("Unexpected abbrev ordering!");
1897 // FIXME: This should only use space for first class types!
1899 { // INST_LOAD abbrev for FUNCTION_BLOCK.
1900 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1901 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
1902 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
1903 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
1904 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
1905 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1906 Abbv) != FUNCTION_INST_LOAD_ABBREV)
1907 llvm_unreachable("Unexpected abbrev ordering!");
1909 { // INST_BINOP abbrev for FUNCTION_BLOCK.
1910 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1911 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1912 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1913 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1914 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1915 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1916 Abbv) != FUNCTION_INST_BINOP_ABBREV)
1917 llvm_unreachable("Unexpected abbrev ordering!");
1919 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
1920 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1921 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1922 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1923 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1924 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1925 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
1926 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1927 Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV)
1928 llvm_unreachable("Unexpected abbrev ordering!");
1930 { // INST_CAST abbrev for FUNCTION_BLOCK.
1931 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1932 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
1933 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
1934 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
1935 Log2_32_Ceil(VE.getTypes().size()+1)));
1936 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1937 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1938 Abbv) != FUNCTION_INST_CAST_ABBREV)
1939 llvm_unreachable("Unexpected abbrev ordering!");
1942 { // INST_RET abbrev for FUNCTION_BLOCK.
1943 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1944 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1945 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1946 Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
1947 llvm_unreachable("Unexpected abbrev ordering!");
1949 { // INST_RET abbrev for FUNCTION_BLOCK.
1950 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1951 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1952 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
1953 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1954 Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
1955 llvm_unreachable("Unexpected abbrev ordering!");
1957 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
1958 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1959 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
1960 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1961 Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
1962 llvm_unreachable("Unexpected abbrev ordering!");
1968 /// WriteModule - Emit the specified module to the bitstream.
1969 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
1970 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
1972 SmallVector<unsigned, 1> Vals;
1973 unsigned CurVersion = 1;
1974 Vals.push_back(CurVersion);
1975 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
1977 // Analyze the module, enumerating globals, functions, etc.
1978 ValueEnumerator VE(*M);
1980 // Emit blockinfo, which defines the standard abbreviations etc.
1981 WriteBlockInfo(VE, Stream);
1983 // Emit information about attribute groups.
1984 WriteAttributeGroupTable(VE, Stream);
1986 // Emit information about parameter attributes.
1987 WriteAttributeTable(VE, Stream);
1989 // Emit information describing all of the types in the module.
1990 WriteTypeTable(VE, Stream);
1992 writeComdats(VE, Stream);
1994 // Emit top-level description of module, including target triple, inline asm,
1995 // descriptors for global variables, and function prototype info.
1996 WriteModuleInfo(M, VE, Stream);
1999 WriteModuleConstants(VE, Stream);
2002 WriteModuleMetadata(M, VE, Stream);
2005 WriteModuleMetadataStore(M, Stream);
2007 // Emit names for globals/functions etc.
2008 WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
2010 // Emit module-level use-lists.
2011 if (shouldPreserveBitcodeUseListOrder())
2012 WriteUseListBlock(nullptr, VE, Stream);
2014 // Emit function bodies.
2015 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F)
2016 if (!F->isDeclaration())
2017 WriteFunction(*F, VE, Stream);
2022 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
2023 /// header and trailer to make it compatible with the system archiver. To do
2024 /// this we emit the following header, and then emit a trailer that pads the
2025 /// file out to be a multiple of 16 bytes.
2027 /// struct bc_header {
2028 /// uint32_t Magic; // 0x0B17C0DE
2029 /// uint32_t Version; // Version, currently always 0.
2030 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
2031 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
2032 /// uint32_t CPUType; // CPU specifier.
2033 /// ... potentially more later ...
2036 DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
2037 DarwinBCHeaderSize = 5*4
2040 static void WriteInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
2041 uint32_t &Position) {
2042 Buffer[Position + 0] = (unsigned char) (Value >> 0);
2043 Buffer[Position + 1] = (unsigned char) (Value >> 8);
2044 Buffer[Position + 2] = (unsigned char) (Value >> 16);
2045 Buffer[Position + 3] = (unsigned char) (Value >> 24);
2049 static void EmitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
2051 unsigned CPUType = ~0U;
2053 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
2054 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
2055 // number from /usr/include/mach/machine.h. It is ok to reproduce the
2056 // specific constants here because they are implicitly part of the Darwin ABI.
2058 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
2059 DARWIN_CPU_TYPE_X86 = 7,
2060 DARWIN_CPU_TYPE_ARM = 12,
2061 DARWIN_CPU_TYPE_POWERPC = 18
2064 Triple::ArchType Arch = TT.getArch();
2065 if (Arch == Triple::x86_64)
2066 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
2067 else if (Arch == Triple::x86)
2068 CPUType = DARWIN_CPU_TYPE_X86;
2069 else if (Arch == Triple::ppc)
2070 CPUType = DARWIN_CPU_TYPE_POWERPC;
2071 else if (Arch == Triple::ppc64)
2072 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
2073 else if (Arch == Triple::arm || Arch == Triple::thumb)
2074 CPUType = DARWIN_CPU_TYPE_ARM;
2076 // Traditional Bitcode starts after header.
2077 assert(Buffer.size() >= DarwinBCHeaderSize &&
2078 "Expected header size to be reserved");
2079 unsigned BCOffset = DarwinBCHeaderSize;
2080 unsigned BCSize = Buffer.size()-DarwinBCHeaderSize;
2082 // Write the magic and version.
2083 unsigned Position = 0;
2084 WriteInt32ToBuffer(0x0B17C0DE , Buffer, Position);
2085 WriteInt32ToBuffer(0 , Buffer, Position); // Version.
2086 WriteInt32ToBuffer(BCOffset , Buffer, Position);
2087 WriteInt32ToBuffer(BCSize , Buffer, Position);
2088 WriteInt32ToBuffer(CPUType , Buffer, Position);
2090 // If the file is not a multiple of 16 bytes, insert dummy padding.
2091 while (Buffer.size() & 15)
2092 Buffer.push_back(0);
2095 /// WriteBitcodeToFile - Write the specified module to the specified output
2097 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out) {
2098 SmallVector<char, 0> Buffer;
2099 Buffer.reserve(256*1024);
2101 // If this is darwin or another generic macho target, reserve space for the
2103 Triple TT(M->getTargetTriple());
2104 if (TT.isOSDarwin())
2105 Buffer.insert(Buffer.begin(), DarwinBCHeaderSize, 0);
2107 // Emit the module into the buffer.
2109 BitstreamWriter Stream(Buffer);
2111 // Emit the file header.
2112 Stream.Emit((unsigned)'B', 8);
2113 Stream.Emit((unsigned)'C', 8);
2114 Stream.Emit(0x0, 4);
2115 Stream.Emit(0xC, 4);
2116 Stream.Emit(0xE, 4);
2117 Stream.Emit(0xD, 4);
2120 WriteModule(M, Stream);
2123 if (TT.isOSDarwin())
2124 EmitDarwinBCHeaderAndTrailer(Buffer, TT);
2126 // Write the generated bitstream to "Out".
2127 Out.write((char*)&Buffer.front(), Buffer.size());