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 "llvm/Bitcode/BitstreamWriter.h"
16 #include "llvm/Bitcode/LLVMBitCodes.h"
17 #include "ValueEnumerator.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/InlineAsm.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/Module.h"
23 #include "llvm/Operator.h"
24 #include "llvm/ValueSymbolTable.h"
25 #include "llvm/ADT/Triple.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/MathExtras.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/Support/Program.h"
34 /// These are manifest constants used by the bitcode writer. They do not need to
35 /// be kept in sync with the reader, but need to be consistent within this file.
39 // VALUE_SYMTAB_BLOCK abbrev id's.
40 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
45 // CONSTANTS_BLOCK abbrev id's.
46 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
47 CONSTANTS_INTEGER_ABBREV,
48 CONSTANTS_CE_CAST_Abbrev,
49 CONSTANTS_NULL_Abbrev,
51 // FUNCTION_BLOCK abbrev id's.
52 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
53 FUNCTION_INST_BINOP_ABBREV,
54 FUNCTION_INST_BINOP_FLAGS_ABBREV,
55 FUNCTION_INST_CAST_ABBREV,
56 FUNCTION_INST_RET_VOID_ABBREV,
57 FUNCTION_INST_RET_VAL_ABBREV,
58 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;
80 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
82 default: llvm_unreachable("Unknown binary instruction!");
83 case Instruction::Add:
84 case Instruction::FAdd: return bitc::BINOP_ADD;
85 case Instruction::Sub:
86 case Instruction::FSub: return bitc::BINOP_SUB;
87 case Instruction::Mul:
88 case Instruction::FMul: return bitc::BINOP_MUL;
89 case Instruction::UDiv: return bitc::BINOP_UDIV;
90 case Instruction::FDiv:
91 case Instruction::SDiv: return bitc::BINOP_SDIV;
92 case Instruction::URem: return bitc::BINOP_UREM;
93 case Instruction::FRem:
94 case Instruction::SRem: return bitc::BINOP_SREM;
95 case Instruction::Shl: return bitc::BINOP_SHL;
96 case Instruction::LShr: return bitc::BINOP_LSHR;
97 case Instruction::AShr: return bitc::BINOP_ASHR;
98 case Instruction::And: return bitc::BINOP_AND;
99 case Instruction::Or: return bitc::BINOP_OR;
100 case Instruction::Xor: return bitc::BINOP_XOR;
104 static unsigned GetEncodedOrdering(AtomicOrdering Ordering) {
106 default: llvm_unreachable("Unknown atomic ordering");
107 case NotAtomic: return bitc::ORDERING_NOTATOMIC;
108 case Unordered: return bitc::ORDERING_UNORDERED;
109 case Monotonic: return bitc::ORDERING_MONOTONIC;
110 case Acquire: return bitc::ORDERING_ACQUIRE;
111 case Release: return bitc::ORDERING_RELEASE;
112 case AcquireRelease: return bitc::ORDERING_ACQREL;
113 case SequentiallyConsistent: return bitc::ORDERING_SEQCST;
117 static unsigned GetEncodedSynchScope(SynchronizationScope SynchScope) {
118 switch (SynchScope) {
119 default: llvm_unreachable("Unknown synchronization scope");
120 case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD;
121 case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD;
125 static void WriteStringRecord(unsigned Code, StringRef Str,
126 unsigned AbbrevToUse, BitstreamWriter &Stream) {
127 SmallVector<unsigned, 64> Vals;
129 // Code: [strchar x N]
130 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
131 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
133 Vals.push_back(Str[i]);
136 // Emit the finished record.
137 Stream.EmitRecord(Code, Vals, AbbrevToUse);
140 // Emit information about parameter attributes.
141 static void WriteAttributeTable(const ValueEnumerator &VE,
142 BitstreamWriter &Stream) {
143 const std::vector<AttrListPtr> &Attrs = VE.getAttributes();
144 if (Attrs.empty()) return;
146 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
148 SmallVector<uint64_t, 64> Record;
149 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
150 const AttrListPtr &A = Attrs[i];
151 for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i) {
152 const AttributeWithIndex &PAWI = A.getSlot(i);
153 Record.push_back(PAWI.Index);
155 // FIXME: remove in LLVM 3.0
156 // Store the alignment in the bitcode as a 16-bit raw value instead of a
157 // 5-bit log2 encoded value. Shift the bits above the alignment up by
159 uint64_t FauxAttr = PAWI.Attrs & 0xffff;
160 if (PAWI.Attrs & Attribute::Alignment)
161 FauxAttr |= (1ull<<16)<<(((PAWI.Attrs & Attribute::Alignment)-1) >> 16);
162 FauxAttr |= (PAWI.Attrs & (0x3FFull << 21)) << 11;
164 Record.push_back(FauxAttr);
167 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
174 /// WriteTypeTable - Write out the type table for a module.
175 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
176 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
178 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
179 SmallVector<uint64_t, 64> TypeVals;
181 // Abbrev for TYPE_CODE_POINTER.
182 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
183 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
184 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
185 Log2_32_Ceil(VE.getTypes().size()+1)));
186 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
187 unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
189 // Abbrev for TYPE_CODE_FUNCTION.
190 Abbv = new BitCodeAbbrev();
191 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
192 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
193 Abbv->Add(BitCodeAbbrevOp(0)); // FIXME: DEAD value, remove in LLVM 3.0
194 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
195 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
196 Log2_32_Ceil(VE.getTypes().size()+1)));
197 unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
199 // Abbrev for TYPE_CODE_STRUCT_ANON.
200 Abbv = new BitCodeAbbrev();
201 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
202 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
203 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
204 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
205 Log2_32_Ceil(VE.getTypes().size()+1)));
206 unsigned StructAnonAbbrev = Stream.EmitAbbrev(Abbv);
208 // Abbrev for TYPE_CODE_STRUCT_NAME.
209 Abbv = new BitCodeAbbrev();
210 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
211 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
212 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
213 unsigned StructNameAbbrev = Stream.EmitAbbrev(Abbv);
215 // Abbrev for TYPE_CODE_STRUCT_NAMED.
216 Abbv = new BitCodeAbbrev();
217 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
218 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
219 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
220 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
221 Log2_32_Ceil(VE.getTypes().size()+1)));
222 unsigned StructNamedAbbrev = Stream.EmitAbbrev(Abbv);
225 // Abbrev for TYPE_CODE_ARRAY.
226 Abbv = new BitCodeAbbrev();
227 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
228 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
229 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
230 Log2_32_Ceil(VE.getTypes().size()+1)));
231 unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
233 // Emit an entry count so the reader can reserve space.
234 TypeVals.push_back(TypeList.size());
235 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
238 // Loop over all of the types, emitting each in turn.
239 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
240 Type *T = TypeList[i];
244 switch (T->getTypeID()) {
245 default: llvm_unreachable("Unknown type!");
246 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
247 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
248 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
249 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
250 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
251 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
252 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
253 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
254 case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break;
255 case Type::IntegerTyID:
257 Code = bitc::TYPE_CODE_INTEGER;
258 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
260 case Type::PointerTyID: {
261 PointerType *PTy = cast<PointerType>(T);
262 // POINTER: [pointee type, address space]
263 Code = bitc::TYPE_CODE_POINTER;
264 TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
265 unsigned AddressSpace = PTy->getAddressSpace();
266 TypeVals.push_back(AddressSpace);
267 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
270 case Type::FunctionTyID: {
271 FunctionType *FT = cast<FunctionType>(T);
272 // FUNCTION: [isvararg, attrid, retty, paramty x N]
273 Code = bitc::TYPE_CODE_FUNCTION;
274 TypeVals.push_back(FT->isVarArg());
275 TypeVals.push_back(0); // FIXME: DEAD: remove in llvm 3.0
276 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
277 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
278 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
279 AbbrevToUse = FunctionAbbrev;
282 case Type::StructTyID: {
283 StructType *ST = cast<StructType>(T);
284 // STRUCT: [ispacked, eltty x N]
285 TypeVals.push_back(ST->isPacked());
286 // Output all of the element types.
287 for (StructType::element_iterator I = ST->element_begin(),
288 E = ST->element_end(); I != E; ++I)
289 TypeVals.push_back(VE.getTypeID(*I));
291 if (ST->isAnonymous()) {
292 Code = bitc::TYPE_CODE_STRUCT_ANON;
293 AbbrevToUse = StructAnonAbbrev;
295 if (ST->isOpaque()) {
296 Code = bitc::TYPE_CODE_OPAQUE;
298 Code = bitc::TYPE_CODE_STRUCT_NAMED;
299 AbbrevToUse = StructNamedAbbrev;
302 // Emit the name if it is present.
303 if (!ST->getName().empty())
304 WriteStringRecord(bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
305 StructNameAbbrev, Stream);
309 case Type::ArrayTyID: {
310 ArrayType *AT = cast<ArrayType>(T);
311 // ARRAY: [numelts, eltty]
312 Code = bitc::TYPE_CODE_ARRAY;
313 TypeVals.push_back(AT->getNumElements());
314 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
315 AbbrevToUse = ArrayAbbrev;
318 case Type::VectorTyID: {
319 VectorType *VT = cast<VectorType>(T);
320 // VECTOR [numelts, eltty]
321 Code = bitc::TYPE_CODE_VECTOR;
322 TypeVals.push_back(VT->getNumElements());
323 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
328 // Emit the finished record.
329 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
336 static unsigned getEncodedLinkage(const GlobalValue *GV) {
337 switch (GV->getLinkage()) {
338 default: llvm_unreachable("Invalid linkage!");
339 case GlobalValue::ExternalLinkage: return 0;
340 case GlobalValue::WeakAnyLinkage: return 1;
341 case GlobalValue::AppendingLinkage: return 2;
342 case GlobalValue::InternalLinkage: return 3;
343 case GlobalValue::LinkOnceAnyLinkage: return 4;
344 case GlobalValue::DLLImportLinkage: return 5;
345 case GlobalValue::DLLExportLinkage: return 6;
346 case GlobalValue::ExternalWeakLinkage: return 7;
347 case GlobalValue::CommonLinkage: return 8;
348 case GlobalValue::PrivateLinkage: return 9;
349 case GlobalValue::WeakODRLinkage: return 10;
350 case GlobalValue::LinkOnceODRLinkage: return 11;
351 case GlobalValue::AvailableExternallyLinkage: return 12;
352 case GlobalValue::LinkerPrivateLinkage: return 13;
353 case GlobalValue::LinkerPrivateWeakLinkage: return 14;
354 case GlobalValue::LinkerPrivateWeakDefAutoLinkage: return 15;
358 static unsigned getEncodedVisibility(const GlobalValue *GV) {
359 switch (GV->getVisibility()) {
360 default: llvm_unreachable("Invalid visibility!");
361 case GlobalValue::DefaultVisibility: return 0;
362 case GlobalValue::HiddenVisibility: return 1;
363 case GlobalValue::ProtectedVisibility: return 2;
367 // Emit top-level description of module, including target triple, inline asm,
368 // descriptors for global variables, and function prototype info.
369 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
370 BitstreamWriter &Stream) {
371 // Emit the list of dependent libraries for the Module.
372 for (Module::lib_iterator I = M->lib_begin(), E = M->lib_end(); I != E; ++I)
373 WriteStringRecord(bitc::MODULE_CODE_DEPLIB, *I, 0/*TODO*/, Stream);
375 // Emit various pieces of data attached to a module.
376 if (!M->getTargetTriple().empty())
377 WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
379 if (!M->getDataLayout().empty())
380 WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(),
382 if (!M->getModuleInlineAsm().empty())
383 WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
386 // Emit information about sections and GC, computing how many there are. Also
387 // compute the maximum alignment value.
388 std::map<std::string, unsigned> SectionMap;
389 std::map<std::string, unsigned> GCMap;
390 unsigned MaxAlignment = 0;
391 unsigned MaxGlobalType = 0;
392 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
394 MaxAlignment = std::max(MaxAlignment, GV->getAlignment());
395 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType()));
397 if (!GV->hasSection()) continue;
398 // Give section names unique ID's.
399 unsigned &Entry = SectionMap[GV->getSection()];
400 if (Entry != 0) continue;
401 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(),
403 Entry = SectionMap.size();
405 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
406 MaxAlignment = std::max(MaxAlignment, F->getAlignment());
407 if (F->hasSection()) {
408 // Give section names unique ID's.
409 unsigned &Entry = SectionMap[F->getSection()];
411 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(),
413 Entry = SectionMap.size();
417 // Same for GC names.
418 unsigned &Entry = GCMap[F->getGC()];
420 WriteStringRecord(bitc::MODULE_CODE_GCNAME, F->getGC(),
422 Entry = GCMap.size();
427 // Emit abbrev for globals, now that we know # sections and max alignment.
428 unsigned SimpleGVarAbbrev = 0;
429 if (!M->global_empty()) {
430 // Add an abbrev for common globals with no visibility or thread localness.
431 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
432 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
433 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
434 Log2_32_Ceil(MaxGlobalType+1)));
435 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Constant.
436 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
437 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // Linkage.
438 if (MaxAlignment == 0) // Alignment.
439 Abbv->Add(BitCodeAbbrevOp(0));
441 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
442 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
443 Log2_32_Ceil(MaxEncAlignment+1)));
445 if (SectionMap.empty()) // Section.
446 Abbv->Add(BitCodeAbbrevOp(0));
448 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
449 Log2_32_Ceil(SectionMap.size()+1)));
450 // Don't bother emitting vis + thread local.
451 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
454 // Emit the global variable information.
455 SmallVector<unsigned, 64> Vals;
456 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
458 unsigned AbbrevToUse = 0;
460 // GLOBALVAR: [type, isconst, initid,
461 // linkage, alignment, section, visibility, threadlocal,
463 Vals.push_back(VE.getTypeID(GV->getType()));
464 Vals.push_back(GV->isConstant());
465 Vals.push_back(GV->isDeclaration() ? 0 :
466 (VE.getValueID(GV->getInitializer()) + 1));
467 Vals.push_back(getEncodedLinkage(GV));
468 Vals.push_back(Log2_32(GV->getAlignment())+1);
469 Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0);
470 if (GV->isThreadLocal() ||
471 GV->getVisibility() != GlobalValue::DefaultVisibility ||
472 GV->hasUnnamedAddr()) {
473 Vals.push_back(getEncodedVisibility(GV));
474 Vals.push_back(GV->isThreadLocal());
475 Vals.push_back(GV->hasUnnamedAddr());
477 AbbrevToUse = SimpleGVarAbbrev;
480 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
484 // Emit the function proto information.
485 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
486 // FUNCTION: [type, callingconv, isproto, paramattr,
487 // linkage, alignment, section, visibility, gc, unnamed_addr]
488 Vals.push_back(VE.getTypeID(F->getType()));
489 Vals.push_back(F->getCallingConv());
490 Vals.push_back(F->isDeclaration());
491 Vals.push_back(getEncodedLinkage(F));
492 Vals.push_back(VE.getAttributeID(F->getAttributes()));
493 Vals.push_back(Log2_32(F->getAlignment())+1);
494 Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
495 Vals.push_back(getEncodedVisibility(F));
496 Vals.push_back(F->hasGC() ? GCMap[F->getGC()] : 0);
497 Vals.push_back(F->hasUnnamedAddr());
499 unsigned AbbrevToUse = 0;
500 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
504 // Emit the alias information.
505 for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end();
507 Vals.push_back(VE.getTypeID(AI->getType()));
508 Vals.push_back(VE.getValueID(AI->getAliasee()));
509 Vals.push_back(getEncodedLinkage(AI));
510 Vals.push_back(getEncodedVisibility(AI));
511 unsigned AbbrevToUse = 0;
512 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
517 static uint64_t GetOptimizationFlags(const Value *V) {
520 if (const OverflowingBinaryOperator *OBO =
521 dyn_cast<OverflowingBinaryOperator>(V)) {
522 if (OBO->hasNoSignedWrap())
523 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
524 if (OBO->hasNoUnsignedWrap())
525 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
526 } else if (const PossiblyExactOperator *PEO =
527 dyn_cast<PossiblyExactOperator>(V)) {
529 Flags |= 1 << bitc::PEO_EXACT;
535 static void WriteMDNode(const MDNode *N,
536 const ValueEnumerator &VE,
537 BitstreamWriter &Stream,
538 SmallVector<uint64_t, 64> &Record) {
539 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
540 if (N->getOperand(i)) {
541 Record.push_back(VE.getTypeID(N->getOperand(i)->getType()));
542 Record.push_back(VE.getValueID(N->getOperand(i)));
544 Record.push_back(VE.getTypeID(Type::getVoidTy(N->getContext())));
548 unsigned MDCode = N->isFunctionLocal() ? bitc::METADATA_FN_NODE :
550 Stream.EmitRecord(MDCode, Record, 0);
554 static void WriteModuleMetadata(const Module *M,
555 const ValueEnumerator &VE,
556 BitstreamWriter &Stream) {
557 const ValueEnumerator::ValueList &Vals = VE.getMDValues();
558 bool StartedMetadataBlock = false;
559 unsigned MDSAbbrev = 0;
560 SmallVector<uint64_t, 64> Record;
561 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
563 if (const MDNode *N = dyn_cast<MDNode>(Vals[i].first)) {
564 if (!N->isFunctionLocal() || !N->getFunction()) {
565 if (!StartedMetadataBlock) {
566 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
567 StartedMetadataBlock = true;
569 WriteMDNode(N, VE, Stream, Record);
571 } else if (const MDString *MDS = dyn_cast<MDString>(Vals[i].first)) {
572 if (!StartedMetadataBlock) {
573 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
575 // Abbrev for METADATA_STRING.
576 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
577 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING));
578 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
579 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
580 MDSAbbrev = Stream.EmitAbbrev(Abbv);
581 StartedMetadataBlock = true;
584 // Code: [strchar x N]
585 Record.append(MDS->begin(), MDS->end());
587 // Emit the finished record.
588 Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev);
593 // Write named metadata.
594 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
595 E = M->named_metadata_end(); I != E; ++I) {
596 const NamedMDNode *NMD = I;
597 if (!StartedMetadataBlock) {
598 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
599 StartedMetadataBlock = true;
603 StringRef Str = NMD->getName();
604 for (unsigned i = 0, e = Str.size(); i != e; ++i)
605 Record.push_back(Str[i]);
606 Stream.EmitRecord(bitc::METADATA_NAME, Record, 0/*TODO*/);
609 // Write named metadata operands.
610 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
611 Record.push_back(VE.getValueID(NMD->getOperand(i)));
612 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
616 if (StartedMetadataBlock)
620 static void WriteFunctionLocalMetadata(const Function &F,
621 const ValueEnumerator &VE,
622 BitstreamWriter &Stream) {
623 bool StartedMetadataBlock = false;
624 SmallVector<uint64_t, 64> Record;
625 const SmallVector<const MDNode *, 8> &Vals = VE.getFunctionLocalMDValues();
626 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
627 if (const MDNode *N = Vals[i])
628 if (N->isFunctionLocal() && N->getFunction() == &F) {
629 if (!StartedMetadataBlock) {
630 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
631 StartedMetadataBlock = true;
633 WriteMDNode(N, VE, Stream, Record);
636 if (StartedMetadataBlock)
640 static void WriteMetadataAttachment(const Function &F,
641 const ValueEnumerator &VE,
642 BitstreamWriter &Stream) {
643 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
645 SmallVector<uint64_t, 64> Record;
647 // Write metadata attachments
648 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
649 SmallVector<std::pair<unsigned, MDNode*>, 4> MDs;
651 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
652 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
655 I->getAllMetadataOtherThanDebugLoc(MDs);
657 // If no metadata, ignore instruction.
658 if (MDs.empty()) continue;
660 Record.push_back(VE.getInstructionID(I));
662 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
663 Record.push_back(MDs[i].first);
664 Record.push_back(VE.getValueID(MDs[i].second));
666 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
673 static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) {
674 SmallVector<uint64_t, 64> Record;
676 // Write metadata kinds
677 // METADATA_KIND - [n x [id, name]]
678 SmallVector<StringRef, 4> Names;
679 M->getMDKindNames(Names);
681 if (Names.empty()) return;
683 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
685 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
686 Record.push_back(MDKindID);
687 StringRef KName = Names[MDKindID];
688 Record.append(KName.begin(), KName.end());
690 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
697 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
698 const ValueEnumerator &VE,
699 BitstreamWriter &Stream, bool isGlobal) {
700 if (FirstVal == LastVal) return;
702 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
704 unsigned AggregateAbbrev = 0;
705 unsigned String8Abbrev = 0;
706 unsigned CString7Abbrev = 0;
707 unsigned CString6Abbrev = 0;
708 // If this is a constant pool for the module, emit module-specific abbrevs.
710 // Abbrev for CST_CODE_AGGREGATE.
711 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
712 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
713 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
714 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
715 AggregateAbbrev = Stream.EmitAbbrev(Abbv);
717 // Abbrev for CST_CODE_STRING.
718 Abbv = new BitCodeAbbrev();
719 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
720 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
721 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
722 String8Abbrev = Stream.EmitAbbrev(Abbv);
723 // Abbrev for CST_CODE_CSTRING.
724 Abbv = new BitCodeAbbrev();
725 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
726 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
727 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
728 CString7Abbrev = Stream.EmitAbbrev(Abbv);
729 // Abbrev for CST_CODE_CSTRING.
730 Abbv = new BitCodeAbbrev();
731 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
732 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
733 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
734 CString6Abbrev = Stream.EmitAbbrev(Abbv);
737 SmallVector<uint64_t, 64> Record;
739 const ValueEnumerator::ValueList &Vals = VE.getValues();
741 for (unsigned i = FirstVal; i != LastVal; ++i) {
742 const Value *V = Vals[i].first;
743 // If we need to switch types, do so now.
744 if (V->getType() != LastTy) {
745 LastTy = V->getType();
746 Record.push_back(VE.getTypeID(LastTy));
747 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
748 CONSTANTS_SETTYPE_ABBREV);
752 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
753 Record.push_back(unsigned(IA->hasSideEffects()) |
754 unsigned(IA->isAlignStack()) << 1);
756 // Add the asm string.
757 const std::string &AsmStr = IA->getAsmString();
758 Record.push_back(AsmStr.size());
759 for (unsigned i = 0, e = AsmStr.size(); i != e; ++i)
760 Record.push_back(AsmStr[i]);
762 // Add the constraint string.
763 const std::string &ConstraintStr = IA->getConstraintString();
764 Record.push_back(ConstraintStr.size());
765 for (unsigned i = 0, e = ConstraintStr.size(); i != e; ++i)
766 Record.push_back(ConstraintStr[i]);
767 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
771 const Constant *C = cast<Constant>(V);
773 unsigned AbbrevToUse = 0;
774 if (C->isNullValue()) {
775 Code = bitc::CST_CODE_NULL;
776 } else if (isa<UndefValue>(C)) {
777 Code = bitc::CST_CODE_UNDEF;
778 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
779 if (IV->getBitWidth() <= 64) {
780 uint64_t V = IV->getSExtValue();
782 Record.push_back(V << 1);
784 Record.push_back((-V << 1) | 1);
785 Code = bitc::CST_CODE_INTEGER;
786 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
787 } else { // Wide integers, > 64 bits in size.
788 // We have an arbitrary precision integer value to write whose
789 // bit width is > 64. However, in canonical unsigned integer
790 // format it is likely that the high bits are going to be zero.
791 // So, we only write the number of active words.
792 unsigned NWords = IV->getValue().getActiveWords();
793 const uint64_t *RawWords = IV->getValue().getRawData();
794 for (unsigned i = 0; i != NWords; ++i) {
795 int64_t V = RawWords[i];
797 Record.push_back(V << 1);
799 Record.push_back((-V << 1) | 1);
801 Code = bitc::CST_CODE_WIDE_INTEGER;
803 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
804 Code = bitc::CST_CODE_FLOAT;
805 Type *Ty = CFP->getType();
806 if (Ty->isFloatTy() || Ty->isDoubleTy()) {
807 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
808 } else if (Ty->isX86_FP80Ty()) {
809 // api needed to prevent premature destruction
810 // bits are not in the same order as a normal i80 APInt, compensate.
811 APInt api = CFP->getValueAPF().bitcastToAPInt();
812 const uint64_t *p = api.getRawData();
813 Record.push_back((p[1] << 48) | (p[0] >> 16));
814 Record.push_back(p[0] & 0xffffLL);
815 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
816 APInt api = CFP->getValueAPF().bitcastToAPInt();
817 const uint64_t *p = api.getRawData();
818 Record.push_back(p[0]);
819 Record.push_back(p[1]);
821 assert (0 && "Unknown FP type!");
823 } else if (isa<ConstantArray>(C) && cast<ConstantArray>(C)->isString()) {
824 const ConstantArray *CA = cast<ConstantArray>(C);
825 // Emit constant strings specially.
826 unsigned NumOps = CA->getNumOperands();
827 // If this is a null-terminated string, use the denser CSTRING encoding.
828 if (CA->getOperand(NumOps-1)->isNullValue()) {
829 Code = bitc::CST_CODE_CSTRING;
830 --NumOps; // Don't encode the null, which isn't allowed by char6.
832 Code = bitc::CST_CODE_STRING;
833 AbbrevToUse = String8Abbrev;
835 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
836 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
837 for (unsigned i = 0; i != NumOps; ++i) {
838 unsigned char V = cast<ConstantInt>(CA->getOperand(i))->getZExtValue();
840 isCStr7 &= (V & 128) == 0;
842 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
846 AbbrevToUse = CString6Abbrev;
848 AbbrevToUse = CString7Abbrev;
849 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(V) ||
850 isa<ConstantVector>(V)) {
851 Code = bitc::CST_CODE_AGGREGATE;
852 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
853 Record.push_back(VE.getValueID(C->getOperand(i)));
854 AbbrevToUse = AggregateAbbrev;
855 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
856 switch (CE->getOpcode()) {
858 if (Instruction::isCast(CE->getOpcode())) {
859 Code = bitc::CST_CODE_CE_CAST;
860 Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
861 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
862 Record.push_back(VE.getValueID(C->getOperand(0)));
863 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
865 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
866 Code = bitc::CST_CODE_CE_BINOP;
867 Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
868 Record.push_back(VE.getValueID(C->getOperand(0)));
869 Record.push_back(VE.getValueID(C->getOperand(1)));
870 uint64_t Flags = GetOptimizationFlags(CE);
872 Record.push_back(Flags);
875 case Instruction::GetElementPtr:
876 Code = bitc::CST_CODE_CE_GEP;
877 if (cast<GEPOperator>(C)->isInBounds())
878 Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
879 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
880 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
881 Record.push_back(VE.getValueID(C->getOperand(i)));
884 case Instruction::Select:
885 Code = bitc::CST_CODE_CE_SELECT;
886 Record.push_back(VE.getValueID(C->getOperand(0)));
887 Record.push_back(VE.getValueID(C->getOperand(1)));
888 Record.push_back(VE.getValueID(C->getOperand(2)));
890 case Instruction::ExtractElement:
891 Code = bitc::CST_CODE_CE_EXTRACTELT;
892 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
893 Record.push_back(VE.getValueID(C->getOperand(0)));
894 Record.push_back(VE.getValueID(C->getOperand(1)));
896 case Instruction::InsertElement:
897 Code = bitc::CST_CODE_CE_INSERTELT;
898 Record.push_back(VE.getValueID(C->getOperand(0)));
899 Record.push_back(VE.getValueID(C->getOperand(1)));
900 Record.push_back(VE.getValueID(C->getOperand(2)));
902 case Instruction::ShuffleVector:
903 // If the return type and argument types are the same, this is a
904 // standard shufflevector instruction. If the types are different,
905 // then the shuffle is widening or truncating the input vectors, and
906 // the argument type must also be encoded.
907 if (C->getType() == C->getOperand(0)->getType()) {
908 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
910 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
911 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
913 Record.push_back(VE.getValueID(C->getOperand(0)));
914 Record.push_back(VE.getValueID(C->getOperand(1)));
915 Record.push_back(VE.getValueID(C->getOperand(2)));
917 case Instruction::ICmp:
918 case Instruction::FCmp:
919 Code = bitc::CST_CODE_CE_CMP;
920 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
921 Record.push_back(VE.getValueID(C->getOperand(0)));
922 Record.push_back(VE.getValueID(C->getOperand(1)));
923 Record.push_back(CE->getPredicate());
926 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
927 Code = bitc::CST_CODE_BLOCKADDRESS;
928 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
929 Record.push_back(VE.getValueID(BA->getFunction()));
930 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
935 llvm_unreachable("Unknown constant!");
937 Stream.EmitRecord(Code, Record, AbbrevToUse);
944 static void WriteModuleConstants(const ValueEnumerator &VE,
945 BitstreamWriter &Stream) {
946 const ValueEnumerator::ValueList &Vals = VE.getValues();
948 // Find the first constant to emit, which is the first non-globalvalue value.
949 // We know globalvalues have been emitted by WriteModuleInfo.
950 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
951 if (!isa<GlobalValue>(Vals[i].first)) {
952 WriteConstants(i, Vals.size(), VE, Stream, true);
958 /// PushValueAndType - The file has to encode both the value and type id for
959 /// many values, because we need to know what type to create for forward
960 /// references. However, most operands are not forward references, so this type
961 /// field is not needed.
963 /// This function adds V's value ID to Vals. If the value ID is higher than the
964 /// instruction ID, then it is a forward reference, and it also includes the
966 static bool PushValueAndType(const Value *V, unsigned InstID,
967 SmallVector<unsigned, 64> &Vals,
968 ValueEnumerator &VE) {
969 unsigned ValID = VE.getValueID(V);
970 Vals.push_back(ValID);
971 if (ValID >= InstID) {
972 Vals.push_back(VE.getTypeID(V->getType()));
978 /// WriteInstruction - Emit an instruction to the specified stream.
979 static void WriteInstruction(const Instruction &I, unsigned InstID,
980 ValueEnumerator &VE, BitstreamWriter &Stream,
981 SmallVector<unsigned, 64> &Vals) {
983 unsigned AbbrevToUse = 0;
984 VE.setInstructionID(&I);
985 switch (I.getOpcode()) {
987 if (Instruction::isCast(I.getOpcode())) {
988 Code = bitc::FUNC_CODE_INST_CAST;
989 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
990 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
991 Vals.push_back(VE.getTypeID(I.getType()));
992 Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
994 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
995 Code = bitc::FUNC_CODE_INST_BINOP;
996 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
997 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
998 Vals.push_back(VE.getValueID(I.getOperand(1)));
999 Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
1000 uint64_t Flags = GetOptimizationFlags(&I);
1002 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
1003 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
1004 Vals.push_back(Flags);
1009 case Instruction::GetElementPtr:
1010 Code = bitc::FUNC_CODE_INST_GEP;
1011 if (cast<GEPOperator>(&I)->isInBounds())
1012 Code = bitc::FUNC_CODE_INST_INBOUNDS_GEP;
1013 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1014 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1016 case Instruction::ExtractValue: {
1017 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
1018 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1019 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
1020 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1024 case Instruction::InsertValue: {
1025 Code = bitc::FUNC_CODE_INST_INSERTVAL;
1026 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1027 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1028 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
1029 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1033 case Instruction::Select:
1034 Code = bitc::FUNC_CODE_INST_VSELECT;
1035 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1036 Vals.push_back(VE.getValueID(I.getOperand(2)));
1037 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1039 case Instruction::ExtractElement:
1040 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
1041 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1042 Vals.push_back(VE.getValueID(I.getOperand(1)));
1044 case Instruction::InsertElement:
1045 Code = bitc::FUNC_CODE_INST_INSERTELT;
1046 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1047 Vals.push_back(VE.getValueID(I.getOperand(1)));
1048 Vals.push_back(VE.getValueID(I.getOperand(2)));
1050 case Instruction::ShuffleVector:
1051 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
1052 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1053 Vals.push_back(VE.getValueID(I.getOperand(1)));
1054 Vals.push_back(VE.getValueID(I.getOperand(2)));
1056 case Instruction::ICmp:
1057 case Instruction::FCmp:
1058 // compare returning Int1Ty or vector of Int1Ty
1059 Code = bitc::FUNC_CODE_INST_CMP2;
1060 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1061 Vals.push_back(VE.getValueID(I.getOperand(1)));
1062 Vals.push_back(cast<CmpInst>(I).getPredicate());
1065 case Instruction::Ret:
1067 Code = bitc::FUNC_CODE_INST_RET;
1068 unsigned NumOperands = I.getNumOperands();
1069 if (NumOperands == 0)
1070 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
1071 else if (NumOperands == 1) {
1072 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1073 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
1075 for (unsigned i = 0, e = NumOperands; i != e; ++i)
1076 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1080 case Instruction::Br:
1082 Code = bitc::FUNC_CODE_INST_BR;
1083 BranchInst &II = cast<BranchInst>(I);
1084 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
1085 if (II.isConditional()) {
1086 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
1087 Vals.push_back(VE.getValueID(II.getCondition()));
1091 case Instruction::Switch:
1092 Code = bitc::FUNC_CODE_INST_SWITCH;
1093 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1094 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1095 Vals.push_back(VE.getValueID(I.getOperand(i)));
1097 case Instruction::IndirectBr:
1098 Code = bitc::FUNC_CODE_INST_INDIRECTBR;
1099 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1100 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1101 Vals.push_back(VE.getValueID(I.getOperand(i)));
1104 case Instruction::Invoke: {
1105 const InvokeInst *II = cast<InvokeInst>(&I);
1106 const Value *Callee(II->getCalledValue());
1107 PointerType *PTy = cast<PointerType>(Callee->getType());
1108 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1109 Code = bitc::FUNC_CODE_INST_INVOKE;
1111 Vals.push_back(VE.getAttributeID(II->getAttributes()));
1112 Vals.push_back(II->getCallingConv());
1113 Vals.push_back(VE.getValueID(II->getNormalDest()));
1114 Vals.push_back(VE.getValueID(II->getUnwindDest()));
1115 PushValueAndType(Callee, InstID, Vals, VE);
1117 // Emit value #'s for the fixed parameters.
1118 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1119 Vals.push_back(VE.getValueID(I.getOperand(i))); // fixed param.
1121 // Emit type/value pairs for varargs params.
1122 if (FTy->isVarArg()) {
1123 for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
1125 PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
1129 case Instruction::Unwind:
1130 Code = bitc::FUNC_CODE_INST_UNWIND;
1132 case Instruction::Unreachable:
1133 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
1134 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
1137 case Instruction::PHI: {
1138 const PHINode &PN = cast<PHINode>(I);
1139 Code = bitc::FUNC_CODE_INST_PHI;
1140 Vals.push_back(VE.getTypeID(PN.getType()));
1141 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1142 Vals.push_back(VE.getValueID(PN.getIncomingValue(i)));
1143 Vals.push_back(VE.getValueID(PN.getIncomingBlock(i)));
1148 case Instruction::Alloca:
1149 Code = bitc::FUNC_CODE_INST_ALLOCA;
1150 Vals.push_back(VE.getTypeID(I.getType()));
1151 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1152 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
1153 Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1);
1156 case Instruction::Load:
1157 Code = bitc::FUNC_CODE_INST_LOAD;
1158 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) // ptr
1159 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
1161 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
1162 Vals.push_back(cast<LoadInst>(I).isVolatile());
1164 case Instruction::Store:
1165 Code = bitc::FUNC_CODE_INST_STORE;
1166 PushValueAndType(I.getOperand(1), InstID, Vals, VE); // ptrty + ptr
1167 Vals.push_back(VE.getValueID(I.getOperand(0))); // val.
1168 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
1169 Vals.push_back(cast<StoreInst>(I).isVolatile());
1171 case Instruction::Fence:
1172 Code = bitc::FUNC_CODE_INST_FENCE;
1173 Vals.push_back(GetEncodedOrdering(cast<FenceInst>(I).getOrdering()));
1174 Vals.push_back(GetEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
1176 case Instruction::Call: {
1177 const CallInst &CI = cast<CallInst>(I);
1178 PointerType *PTy = cast<PointerType>(CI.getCalledValue()->getType());
1179 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1181 Code = bitc::FUNC_CODE_INST_CALL;
1183 Vals.push_back(VE.getAttributeID(CI.getAttributes()));
1184 Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall()));
1185 PushValueAndType(CI.getCalledValue(), InstID, Vals, VE); // Callee
1187 // Emit value #'s for the fixed parameters.
1188 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1189 Vals.push_back(VE.getValueID(CI.getArgOperand(i))); // fixed param.
1191 // Emit type/value pairs for varargs params.
1192 if (FTy->isVarArg()) {
1193 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
1195 PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE); // varargs
1199 case Instruction::VAArg:
1200 Code = bitc::FUNC_CODE_INST_VAARG;
1201 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
1202 Vals.push_back(VE.getValueID(I.getOperand(0))); // valist.
1203 Vals.push_back(VE.getTypeID(I.getType())); // restype.
1207 Stream.EmitRecord(Code, Vals, AbbrevToUse);
1211 // Emit names for globals/functions etc.
1212 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
1213 const ValueEnumerator &VE,
1214 BitstreamWriter &Stream) {
1215 if (VST.empty()) return;
1216 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
1218 // FIXME: Set up the abbrev, we know how many values there are!
1219 // FIXME: We know if the type names can use 7-bit ascii.
1220 SmallVector<unsigned, 64> NameVals;
1222 for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
1225 const ValueName &Name = *SI;
1227 // Figure out the encoding to use for the name.
1229 bool isChar6 = true;
1230 for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
1233 isChar6 = BitCodeAbbrevOp::isChar6(*C);
1234 if ((unsigned char)*C & 128) {
1236 break; // don't bother scanning the rest.
1240 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
1242 // VST_ENTRY: [valueid, namechar x N]
1243 // VST_BBENTRY: [bbid, namechar x N]
1245 if (isa<BasicBlock>(SI->getValue())) {
1246 Code = bitc::VST_CODE_BBENTRY;
1248 AbbrevToUse = VST_BBENTRY_6_ABBREV;
1250 Code = bitc::VST_CODE_ENTRY;
1252 AbbrevToUse = VST_ENTRY_6_ABBREV;
1254 AbbrevToUse = VST_ENTRY_7_ABBREV;
1257 NameVals.push_back(VE.getValueID(SI->getValue()));
1258 for (const char *P = Name.getKeyData(),
1259 *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
1260 NameVals.push_back((unsigned char)*P);
1262 // Emit the finished record.
1263 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
1269 /// WriteFunction - Emit a function body to the module stream.
1270 static void WriteFunction(const Function &F, ValueEnumerator &VE,
1271 BitstreamWriter &Stream) {
1272 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
1273 VE.incorporateFunction(F);
1275 SmallVector<unsigned, 64> Vals;
1277 // Emit the number of basic blocks, so the reader can create them ahead of
1279 Vals.push_back(VE.getBasicBlocks().size());
1280 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
1283 // If there are function-local constants, emit them now.
1284 unsigned CstStart, CstEnd;
1285 VE.getFunctionConstantRange(CstStart, CstEnd);
1286 WriteConstants(CstStart, CstEnd, VE, Stream, false);
1288 // If there is function-local metadata, emit it now.
1289 WriteFunctionLocalMetadata(F, VE, Stream);
1291 // Keep a running idea of what the instruction ID is.
1292 unsigned InstID = CstEnd;
1294 bool NeedsMetadataAttachment = false;
1298 // Finally, emit all the instructions, in order.
1299 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1300 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1302 WriteInstruction(*I, InstID, VE, Stream, Vals);
1304 if (!I->getType()->isVoidTy())
1307 // If the instruction has metadata, write a metadata attachment later.
1308 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
1310 // If the instruction has a debug location, emit it.
1311 DebugLoc DL = I->getDebugLoc();
1312 if (DL.isUnknown()) {
1314 } else if (DL == LastDL) {
1315 // Just repeat the same debug loc as last time.
1316 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
1319 DL.getScopeAndInlinedAt(Scope, IA, I->getContext());
1321 Vals.push_back(DL.getLine());
1322 Vals.push_back(DL.getCol());
1323 Vals.push_back(Scope ? VE.getValueID(Scope)+1 : 0);
1324 Vals.push_back(IA ? VE.getValueID(IA)+1 : 0);
1325 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
1332 // Emit names for all the instructions etc.
1333 WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
1335 if (NeedsMetadataAttachment)
1336 WriteMetadataAttachment(F, VE, Stream);
1341 // Emit blockinfo, which defines the standard abbreviations etc.
1342 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
1343 // We only want to emit block info records for blocks that have multiple
1344 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK. Other
1345 // blocks can defined their abbrevs inline.
1346 Stream.EnterBlockInfoBlock(2);
1348 { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
1349 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1350 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
1351 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1352 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1353 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1354 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1355 Abbv) != VST_ENTRY_8_ABBREV)
1356 llvm_unreachable("Unexpected abbrev ordering!");
1359 { // 7-bit fixed width VST_ENTRY strings.
1360 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1361 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1362 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1363 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1364 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1365 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1366 Abbv) != VST_ENTRY_7_ABBREV)
1367 llvm_unreachable("Unexpected abbrev ordering!");
1369 { // 6-bit char6 VST_ENTRY strings.
1370 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1371 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1372 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1373 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1374 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1375 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1376 Abbv) != VST_ENTRY_6_ABBREV)
1377 llvm_unreachable("Unexpected abbrev ordering!");
1379 { // 6-bit char6 VST_BBENTRY strings.
1380 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1381 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
1382 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1383 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1384 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1385 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1386 Abbv) != VST_BBENTRY_6_ABBREV)
1387 llvm_unreachable("Unexpected abbrev ordering!");
1392 { // SETTYPE abbrev for CONSTANTS_BLOCK.
1393 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1394 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
1395 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1396 Log2_32_Ceil(VE.getTypes().size()+1)));
1397 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1398 Abbv) != CONSTANTS_SETTYPE_ABBREV)
1399 llvm_unreachable("Unexpected abbrev ordering!");
1402 { // INTEGER abbrev for CONSTANTS_BLOCK.
1403 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1404 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
1405 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1406 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1407 Abbv) != CONSTANTS_INTEGER_ABBREV)
1408 llvm_unreachable("Unexpected abbrev ordering!");
1411 { // CE_CAST abbrev for CONSTANTS_BLOCK.
1412 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1413 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
1414 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
1415 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
1416 Log2_32_Ceil(VE.getTypes().size()+1)));
1417 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
1419 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1420 Abbv) != CONSTANTS_CE_CAST_Abbrev)
1421 llvm_unreachable("Unexpected abbrev ordering!");
1423 { // NULL abbrev for CONSTANTS_BLOCK.
1424 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1425 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
1426 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1427 Abbv) != CONSTANTS_NULL_Abbrev)
1428 llvm_unreachable("Unexpected abbrev ordering!");
1431 // FIXME: This should only use space for first class types!
1433 { // INST_LOAD abbrev for FUNCTION_BLOCK.
1434 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1435 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
1436 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
1437 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
1438 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
1439 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1440 Abbv) != FUNCTION_INST_LOAD_ABBREV)
1441 llvm_unreachable("Unexpected abbrev ordering!");
1443 { // INST_BINOP abbrev for FUNCTION_BLOCK.
1444 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1445 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1446 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1447 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1448 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1449 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1450 Abbv) != FUNCTION_INST_BINOP_ABBREV)
1451 llvm_unreachable("Unexpected abbrev ordering!");
1453 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
1454 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1455 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1456 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1457 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1458 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1459 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
1460 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1461 Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV)
1462 llvm_unreachable("Unexpected abbrev ordering!");
1464 { // INST_CAST abbrev for FUNCTION_BLOCK.
1465 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1466 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
1467 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
1468 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
1469 Log2_32_Ceil(VE.getTypes().size()+1)));
1470 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1471 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1472 Abbv) != FUNCTION_INST_CAST_ABBREV)
1473 llvm_unreachable("Unexpected abbrev ordering!");
1476 { // INST_RET abbrev for FUNCTION_BLOCK.
1477 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1478 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1479 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1480 Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
1481 llvm_unreachable("Unexpected abbrev ordering!");
1483 { // INST_RET abbrev for FUNCTION_BLOCK.
1484 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1485 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1486 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
1487 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1488 Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
1489 llvm_unreachable("Unexpected abbrev ordering!");
1491 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
1492 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1493 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
1494 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1495 Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
1496 llvm_unreachable("Unexpected abbrev ordering!");
1503 /// WriteModule - Emit the specified module to the bitstream.
1504 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
1505 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
1507 // Emit the version number if it is non-zero.
1509 SmallVector<unsigned, 1> Vals;
1510 Vals.push_back(CurVersion);
1511 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
1514 // Analyze the module, enumerating globals, functions, etc.
1515 ValueEnumerator VE(M);
1517 // Emit blockinfo, which defines the standard abbreviations etc.
1518 WriteBlockInfo(VE, Stream);
1520 // Emit information about parameter attributes.
1521 WriteAttributeTable(VE, Stream);
1523 // Emit information describing all of the types in the module.
1524 WriteTypeTable(VE, Stream);
1526 // Emit top-level description of module, including target triple, inline asm,
1527 // descriptors for global variables, and function prototype info.
1528 WriteModuleInfo(M, VE, Stream);
1531 WriteModuleConstants(VE, Stream);
1534 WriteModuleMetadata(M, VE, Stream);
1536 // Emit function bodies.
1537 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F)
1538 if (!F->isDeclaration())
1539 WriteFunction(*F, VE, Stream);
1542 WriteModuleMetadataStore(M, Stream);
1544 // Emit names for globals/functions etc.
1545 WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
1550 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
1551 /// header and trailer to make it compatible with the system archiver. To do
1552 /// this we emit the following header, and then emit a trailer that pads the
1553 /// file out to be a multiple of 16 bytes.
1555 /// struct bc_header {
1556 /// uint32_t Magic; // 0x0B17C0DE
1557 /// uint32_t Version; // Version, currently always 0.
1558 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
1559 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
1560 /// uint32_t CPUType; // CPU specifier.
1561 /// ... potentially more later ...
1564 DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
1565 DarwinBCHeaderSize = 5*4
1568 static void EmitDarwinBCHeader(BitstreamWriter &Stream, const Triple &TT) {
1569 unsigned CPUType = ~0U;
1571 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
1572 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
1573 // number from /usr/include/mach/machine.h. It is ok to reproduce the
1574 // specific constants here because they are implicitly part of the Darwin ABI.
1576 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
1577 DARWIN_CPU_TYPE_X86 = 7,
1578 DARWIN_CPU_TYPE_ARM = 12,
1579 DARWIN_CPU_TYPE_POWERPC = 18
1582 Triple::ArchType Arch = TT.getArch();
1583 if (Arch == Triple::x86_64)
1584 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
1585 else if (Arch == Triple::x86)
1586 CPUType = DARWIN_CPU_TYPE_X86;
1587 else if (Arch == Triple::ppc)
1588 CPUType = DARWIN_CPU_TYPE_POWERPC;
1589 else if (Arch == Triple::ppc64)
1590 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
1591 else if (Arch == Triple::arm || Arch == Triple::thumb)
1592 CPUType = DARWIN_CPU_TYPE_ARM;
1594 // Traditional Bitcode starts after header.
1595 unsigned BCOffset = DarwinBCHeaderSize;
1597 Stream.Emit(0x0B17C0DE, 32);
1598 Stream.Emit(0 , 32); // Version.
1599 Stream.Emit(BCOffset , 32);
1600 Stream.Emit(0 , 32); // Filled in later.
1601 Stream.Emit(CPUType , 32);
1604 /// EmitDarwinBCTrailer - Emit the darwin epilog after the bitcode file and
1605 /// finalize the header.
1606 static void EmitDarwinBCTrailer(BitstreamWriter &Stream, unsigned BufferSize) {
1607 // Update the size field in the header.
1608 Stream.BackpatchWord(DarwinBCSizeFieldOffset, BufferSize-DarwinBCHeaderSize);
1610 // If the file is not a multiple of 16 bytes, insert dummy padding.
1611 while (BufferSize & 15) {
1618 /// WriteBitcodeToFile - Write the specified module to the specified output
1620 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out) {
1621 std::vector<unsigned char> Buffer;
1622 BitstreamWriter Stream(Buffer);
1624 Buffer.reserve(256*1024);
1626 WriteBitcodeToStream( M, Stream );
1628 // Write the generated bitstream to "Out".
1629 Out.write((char*)&Buffer.front(), Buffer.size());
1632 /// WriteBitcodeToStream - Write the specified module to the specified output
1634 void llvm::WriteBitcodeToStream(const Module *M, BitstreamWriter &Stream) {
1635 // If this is darwin or another generic macho target, emit a file header and
1636 // trailer if needed.
1637 Triple TT(M->getTargetTriple());
1638 if (TT.isOSDarwin())
1639 EmitDarwinBCHeader(Stream, TT);
1641 // Emit the file header.
1642 Stream.Emit((unsigned)'B', 8);
1643 Stream.Emit((unsigned)'C', 8);
1644 Stream.Emit(0x0, 4);
1645 Stream.Emit(0xC, 4);
1646 Stream.Emit(0xE, 4);
1647 Stream.Emit(0xD, 4);
1650 WriteModule(M, Stream);
1652 if (TT.isOSDarwin())
1653 EmitDarwinBCTrailer(Stream, Stream.getBuffer().size());