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/MDNode.h"
23 #include "llvm/Module.h"
24 #include "llvm/TypeSymbolTable.h"
25 #include "llvm/ValueSymbolTable.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/MathExtras.h"
28 #include "llvm/Support/Streams.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/System/Program.h"
33 /// These are manifest constants used by the bitcode writer. They do not need to
34 /// be kept in sync with the reader, but need to be consistent within this file.
38 // VALUE_SYMTAB_BLOCK abbrev id's.
39 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
44 // CONSTANTS_BLOCK abbrev id's.
45 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
46 CONSTANTS_INTEGER_ABBREV,
47 CONSTANTS_CE_CAST_Abbrev,
48 CONSTANTS_NULL_Abbrev,
50 // FUNCTION_BLOCK abbrev id's.
51 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
52 FUNCTION_INST_BINOP_ABBREV,
53 FUNCTION_INST_CAST_ABBREV,
54 FUNCTION_INST_RET_VOID_ABBREV,
55 FUNCTION_INST_RET_VAL_ABBREV,
56 FUNCTION_INST_UNREACHABLE_ABBREV
60 static unsigned GetEncodedCastOpcode(unsigned Opcode) {
62 default: LLVM_UNREACHABLE("Unknown cast instruction!");
63 case Instruction::Trunc : return bitc::CAST_TRUNC;
64 case Instruction::ZExt : return bitc::CAST_ZEXT;
65 case Instruction::SExt : return bitc::CAST_SEXT;
66 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
67 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
68 case Instruction::UIToFP : return bitc::CAST_UITOFP;
69 case Instruction::SIToFP : return bitc::CAST_SITOFP;
70 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
71 case Instruction::FPExt : return bitc::CAST_FPEXT;
72 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
73 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
74 case Instruction::BitCast : return bitc::CAST_BITCAST;
78 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
80 default: LLVM_UNREACHABLE("Unknown binary instruction!");
81 case Instruction::Add:
82 case Instruction::FAdd: return bitc::BINOP_ADD;
83 case Instruction::Sub:
84 case Instruction::FSub: return bitc::BINOP_SUB;
85 case Instruction::Mul:
86 case Instruction::FMul: return bitc::BINOP_MUL;
87 case Instruction::UDiv: return bitc::BINOP_UDIV;
88 case Instruction::FDiv:
89 case Instruction::SDiv: return bitc::BINOP_SDIV;
90 case Instruction::URem: return bitc::BINOP_UREM;
91 case Instruction::FRem:
92 case Instruction::SRem: return bitc::BINOP_SREM;
93 case Instruction::Shl: return bitc::BINOP_SHL;
94 case Instruction::LShr: return bitc::BINOP_LSHR;
95 case Instruction::AShr: return bitc::BINOP_ASHR;
96 case Instruction::And: return bitc::BINOP_AND;
97 case Instruction::Or: return bitc::BINOP_OR;
98 case Instruction::Xor: return bitc::BINOP_XOR;
104 static void WriteStringRecord(unsigned Code, const std::string &Str,
105 unsigned AbbrevToUse, BitstreamWriter &Stream) {
106 SmallVector<unsigned, 64> Vals;
108 // Code: [strchar x N]
109 for (unsigned i = 0, e = Str.size(); i != e; ++i)
110 Vals.push_back(Str[i]);
112 // Emit the finished record.
113 Stream.EmitRecord(Code, Vals, AbbrevToUse);
116 // Emit information about parameter attributes.
117 static void WriteAttributeTable(const ValueEnumerator &VE,
118 BitstreamWriter &Stream) {
119 const std::vector<AttrListPtr> &Attrs = VE.getAttributes();
120 if (Attrs.empty()) return;
122 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
124 SmallVector<uint64_t, 64> Record;
125 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
126 const AttrListPtr &A = Attrs[i];
127 for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i) {
128 const AttributeWithIndex &PAWI = A.getSlot(i);
129 Record.push_back(PAWI.Index);
131 // FIXME: remove in LLVM 3.0
132 // Store the alignment in the bitcode as a 16-bit raw value instead of a
133 // 5-bit log2 encoded value. Shift the bits above the alignment up by
135 uint64_t FauxAttr = PAWI.Attrs & 0xffff;
136 if (PAWI.Attrs & Attribute::Alignment)
137 FauxAttr |= (1ull<<16)<<(((PAWI.Attrs & Attribute::Alignment)-1) >> 16);
138 FauxAttr |= (PAWI.Attrs & (0x3FFull << 21)) << 11;
140 Record.push_back(FauxAttr);
143 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
150 /// WriteTypeTable - Write out the type table for a module.
151 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
152 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
154 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID, 4 /*count from # abbrevs */);
155 SmallVector<uint64_t, 64> TypeVals;
157 // Abbrev for TYPE_CODE_POINTER.
158 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
159 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
160 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
161 Log2_32_Ceil(VE.getTypes().size()+1)));
162 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
163 unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
165 // Abbrev for TYPE_CODE_FUNCTION.
166 Abbv = new BitCodeAbbrev();
167 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
168 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
169 Abbv->Add(BitCodeAbbrevOp(0)); // FIXME: DEAD value, remove in LLVM 3.0
170 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
171 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
172 Log2_32_Ceil(VE.getTypes().size()+1)));
173 unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
175 // Abbrev for TYPE_CODE_STRUCT.
176 Abbv = new BitCodeAbbrev();
177 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT));
178 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
179 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
180 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
181 Log2_32_Ceil(VE.getTypes().size()+1)));
182 unsigned StructAbbrev = Stream.EmitAbbrev(Abbv);
184 // Abbrev for TYPE_CODE_ARRAY.
185 Abbv = new BitCodeAbbrev();
186 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
187 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
188 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
189 Log2_32_Ceil(VE.getTypes().size()+1)));
190 unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
192 // Emit an entry count so the reader can reserve space.
193 TypeVals.push_back(TypeList.size());
194 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
197 // Loop over all of the types, emitting each in turn.
198 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
199 const Type *T = TypeList[i].first;
203 switch (T->getTypeID()) {
204 default: LLVM_UNREACHABLE("Unknown type!");
205 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
206 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
207 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
208 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
209 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
210 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
211 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
212 case Type::OpaqueTyID: Code = bitc::TYPE_CODE_OPAQUE; break;
213 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
214 case Type::IntegerTyID:
216 Code = bitc::TYPE_CODE_INTEGER;
217 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
219 case Type::PointerTyID: {
220 const PointerType *PTy = cast<PointerType>(T);
221 // POINTER: [pointee type, address space]
222 Code = bitc::TYPE_CODE_POINTER;
223 TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
224 unsigned AddressSpace = PTy->getAddressSpace();
225 TypeVals.push_back(AddressSpace);
226 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
229 case Type::FunctionTyID: {
230 const FunctionType *FT = cast<FunctionType>(T);
231 // FUNCTION: [isvararg, attrid, retty, paramty x N]
232 Code = bitc::TYPE_CODE_FUNCTION;
233 TypeVals.push_back(FT->isVarArg());
234 TypeVals.push_back(0); // FIXME: DEAD: remove in llvm 3.0
235 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
236 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
237 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
238 AbbrevToUse = FunctionAbbrev;
241 case Type::StructTyID: {
242 const StructType *ST = cast<StructType>(T);
243 // STRUCT: [ispacked, eltty x N]
244 Code = bitc::TYPE_CODE_STRUCT;
245 TypeVals.push_back(ST->isPacked());
246 // Output all of the element types.
247 for (StructType::element_iterator I = ST->element_begin(),
248 E = ST->element_end(); I != E; ++I)
249 TypeVals.push_back(VE.getTypeID(*I));
250 AbbrevToUse = StructAbbrev;
253 case Type::ArrayTyID: {
254 const ArrayType *AT = cast<ArrayType>(T);
255 // ARRAY: [numelts, eltty]
256 Code = bitc::TYPE_CODE_ARRAY;
257 TypeVals.push_back(AT->getNumElements());
258 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
259 AbbrevToUse = ArrayAbbrev;
262 case Type::VectorTyID: {
263 const VectorType *VT = cast<VectorType>(T);
264 // VECTOR [numelts, eltty]
265 Code = bitc::TYPE_CODE_VECTOR;
266 TypeVals.push_back(VT->getNumElements());
267 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
272 // Emit the finished record.
273 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
280 static unsigned getEncodedLinkage(const GlobalValue *GV) {
281 switch (GV->getLinkage()) {
282 default: LLVM_UNREACHABLE("Invalid linkage!");
283 case GlobalValue::GhostLinkage: // Map ghost linkage onto external.
284 case GlobalValue::ExternalLinkage: return 0;
285 case GlobalValue::WeakAnyLinkage: return 1;
286 case GlobalValue::AppendingLinkage: return 2;
287 case GlobalValue::InternalLinkage: return 3;
288 case GlobalValue::LinkOnceAnyLinkage: return 4;
289 case GlobalValue::DLLImportLinkage: return 5;
290 case GlobalValue::DLLExportLinkage: return 6;
291 case GlobalValue::ExternalWeakLinkage: return 7;
292 case GlobalValue::CommonLinkage: return 8;
293 case GlobalValue::PrivateLinkage: return 9;
294 case GlobalValue::WeakODRLinkage: return 10;
295 case GlobalValue::LinkOnceODRLinkage: return 11;
296 case GlobalValue::AvailableExternallyLinkage: return 12;
300 static unsigned getEncodedVisibility(const GlobalValue *GV) {
301 switch (GV->getVisibility()) {
302 default: LLVM_UNREACHABLE("Invalid visibility!");
303 case GlobalValue::DefaultVisibility: return 0;
304 case GlobalValue::HiddenVisibility: return 1;
305 case GlobalValue::ProtectedVisibility: return 2;
309 // Emit top-level description of module, including target triple, inline asm,
310 // descriptors for global variables, and function prototype info.
311 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
312 BitstreamWriter &Stream) {
313 // Emit the list of dependent libraries for the Module.
314 for (Module::lib_iterator I = M->lib_begin(), E = M->lib_end(); I != E; ++I)
315 WriteStringRecord(bitc::MODULE_CODE_DEPLIB, *I, 0/*TODO*/, Stream);
317 // Emit various pieces of data attached to a module.
318 if (!M->getTargetTriple().empty())
319 WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
321 if (!M->getDataLayout().empty())
322 WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(),
324 if (!M->getModuleInlineAsm().empty())
325 WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
328 // Emit information about sections and GC, computing how many there are. Also
329 // compute the maximum alignment value.
330 std::map<std::string, unsigned> SectionMap;
331 std::map<std::string, unsigned> GCMap;
332 unsigned MaxAlignment = 0;
333 unsigned MaxGlobalType = 0;
334 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
336 MaxAlignment = std::max(MaxAlignment, GV->getAlignment());
337 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType()));
339 if (!GV->hasSection()) continue;
340 // Give section names unique ID's.
341 unsigned &Entry = SectionMap[GV->getSection()];
342 if (Entry != 0) continue;
343 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(),
345 Entry = SectionMap.size();
347 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
348 MaxAlignment = std::max(MaxAlignment, F->getAlignment());
349 if (F->hasSection()) {
350 // Give section names unique ID's.
351 unsigned &Entry = SectionMap[F->getSection()];
353 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(),
355 Entry = SectionMap.size();
359 // Same for GC names.
360 unsigned &Entry = GCMap[F->getGC()];
362 WriteStringRecord(bitc::MODULE_CODE_GCNAME, F->getGC(),
364 Entry = GCMap.size();
369 // Emit abbrev for globals, now that we know # sections and max alignment.
370 unsigned SimpleGVarAbbrev = 0;
371 if (!M->global_empty()) {
372 // Add an abbrev for common globals with no visibility or thread localness.
373 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
374 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
375 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
376 Log2_32_Ceil(MaxGlobalType+1)));
377 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Constant.
378 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
379 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // Linkage.
380 if (MaxAlignment == 0) // Alignment.
381 Abbv->Add(BitCodeAbbrevOp(0));
383 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
384 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
385 Log2_32_Ceil(MaxEncAlignment+1)));
387 if (SectionMap.empty()) // Section.
388 Abbv->Add(BitCodeAbbrevOp(0));
390 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
391 Log2_32_Ceil(SectionMap.size()+1)));
392 // Don't bother emitting vis + thread local.
393 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
396 // Emit the global variable information.
397 SmallVector<unsigned, 64> Vals;
398 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
400 unsigned AbbrevToUse = 0;
402 // GLOBALVAR: [type, isconst, initid,
403 // linkage, alignment, section, visibility, threadlocal]
404 Vals.push_back(VE.getTypeID(GV->getType()));
405 Vals.push_back(GV->isConstant());
406 Vals.push_back(GV->isDeclaration() ? 0 :
407 (VE.getValueID(GV->getInitializer()) + 1));
408 Vals.push_back(getEncodedLinkage(GV));
409 Vals.push_back(Log2_32(GV->getAlignment())+1);
410 Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0);
411 if (GV->isThreadLocal() ||
412 GV->getVisibility() != GlobalValue::DefaultVisibility) {
413 Vals.push_back(getEncodedVisibility(GV));
414 Vals.push_back(GV->isThreadLocal());
416 AbbrevToUse = SimpleGVarAbbrev;
419 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
423 // Emit the function proto information.
424 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
425 // FUNCTION: [type, callingconv, isproto, paramattr,
426 // linkage, alignment, section, visibility, gc]
427 Vals.push_back(VE.getTypeID(F->getType()));
428 Vals.push_back(F->getCallingConv());
429 Vals.push_back(F->isDeclaration());
430 Vals.push_back(getEncodedLinkage(F));
431 Vals.push_back(VE.getAttributeID(F->getAttributes()));
432 Vals.push_back(Log2_32(F->getAlignment())+1);
433 Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
434 Vals.push_back(getEncodedVisibility(F));
435 Vals.push_back(F->hasGC() ? GCMap[F->getGC()] : 0);
437 unsigned AbbrevToUse = 0;
438 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
443 // Emit the alias information.
444 for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end();
446 Vals.push_back(VE.getTypeID(AI->getType()));
447 Vals.push_back(VE.getValueID(AI->getAliasee()));
448 Vals.push_back(getEncodedLinkage(AI));
449 Vals.push_back(getEncodedVisibility(AI));
450 unsigned AbbrevToUse = 0;
451 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
457 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
458 const ValueEnumerator &VE,
459 BitstreamWriter &Stream, bool isGlobal) {
460 if (FirstVal == LastVal) return;
462 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
464 unsigned AggregateAbbrev = 0;
465 unsigned String8Abbrev = 0;
466 unsigned CString7Abbrev = 0;
467 unsigned CString6Abbrev = 0;
468 unsigned MDString8Abbrev = 0;
469 unsigned MDString6Abbrev = 0;
470 // If this is a constant pool for the module, emit module-specific abbrevs.
472 // Abbrev for CST_CODE_AGGREGATE.
473 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
474 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
475 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
476 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
477 AggregateAbbrev = Stream.EmitAbbrev(Abbv);
479 // Abbrev for CST_CODE_STRING.
480 Abbv = new BitCodeAbbrev();
481 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
482 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
483 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
484 String8Abbrev = Stream.EmitAbbrev(Abbv);
485 // Abbrev for CST_CODE_CSTRING.
486 Abbv = new BitCodeAbbrev();
487 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
488 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
489 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
490 CString7Abbrev = Stream.EmitAbbrev(Abbv);
491 // Abbrev for CST_CODE_CSTRING.
492 Abbv = new BitCodeAbbrev();
493 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
494 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
495 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
496 CString6Abbrev = Stream.EmitAbbrev(Abbv);
498 // Abbrev for CST_CODE_MDSTRING.
499 Abbv = new BitCodeAbbrev();
500 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_MDSTRING));
501 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
502 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
503 MDString8Abbrev = Stream.EmitAbbrev(Abbv);
504 // Abbrev for CST_CODE_MDSTRING.
505 Abbv = new BitCodeAbbrev();
506 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_MDSTRING));
507 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
508 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
509 MDString6Abbrev = Stream.EmitAbbrev(Abbv);
512 SmallVector<uint64_t, 64> Record;
514 const ValueEnumerator::ValueList &Vals = VE.getValues();
515 const Type *LastTy = 0;
516 for (unsigned i = FirstVal; i != LastVal; ++i) {
517 const Value *V = Vals[i].first;
518 // If we need to switch types, do so now.
519 if (V->getType() != LastTy) {
520 LastTy = V->getType();
521 Record.push_back(VE.getTypeID(LastTy));
522 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
523 CONSTANTS_SETTYPE_ABBREV);
527 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
528 Record.push_back(unsigned(IA->hasSideEffects()));
530 // Add the asm string.
531 const std::string &AsmStr = IA->getAsmString();
532 Record.push_back(AsmStr.size());
533 for (unsigned i = 0, e = AsmStr.size(); i != e; ++i)
534 Record.push_back(AsmStr[i]);
536 // Add the constraint string.
537 const std::string &ConstraintStr = IA->getConstraintString();
538 Record.push_back(ConstraintStr.size());
539 for (unsigned i = 0, e = ConstraintStr.size(); i != e; ++i)
540 Record.push_back(ConstraintStr[i]);
541 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
545 const Constant *C = cast<Constant>(V);
547 unsigned AbbrevToUse = 0;
548 if (C->isNullValue()) {
549 Code = bitc::CST_CODE_NULL;
550 } else if (isa<UndefValue>(C)) {
551 Code = bitc::CST_CODE_UNDEF;
552 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
553 if (IV->getBitWidth() <= 64) {
554 int64_t V = IV->getSExtValue();
556 Record.push_back(V << 1);
558 Record.push_back((-V << 1) | 1);
559 Code = bitc::CST_CODE_INTEGER;
560 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
561 } else { // Wide integers, > 64 bits in size.
562 // We have an arbitrary precision integer value to write whose
563 // bit width is > 64. However, in canonical unsigned integer
564 // format it is likely that the high bits are going to be zero.
565 // So, we only write the number of active words.
566 unsigned NWords = IV->getValue().getActiveWords();
567 const uint64_t *RawWords = IV->getValue().getRawData();
568 for (unsigned i = 0; i != NWords; ++i) {
569 int64_t V = RawWords[i];
571 Record.push_back(V << 1);
573 Record.push_back((-V << 1) | 1);
575 Code = bitc::CST_CODE_WIDE_INTEGER;
577 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
578 Code = bitc::CST_CODE_FLOAT;
579 const Type *Ty = CFP->getType();
580 if (Ty == Type::FloatTy || Ty == Type::DoubleTy) {
581 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
582 } else if (Ty == Type::X86_FP80Ty) {
583 // api needed to prevent premature destruction
584 // bits are not in the same order as a normal i80 APInt, compensate.
585 APInt api = CFP->getValueAPF().bitcastToAPInt();
586 const uint64_t *p = api.getRawData();
587 Record.push_back((p[1] << 48) | (p[0] >> 16));
588 Record.push_back(p[0] & 0xffffLL);
589 } else if (Ty == Type::FP128Ty || Ty == Type::PPC_FP128Ty) {
590 APInt api = CFP->getValueAPF().bitcastToAPInt();
591 const uint64_t *p = api.getRawData();
592 Record.push_back(p[0]);
593 Record.push_back(p[1]);
595 assert (0 && "Unknown FP type!");
597 } else if (isa<ConstantArray>(C) && cast<ConstantArray>(C)->isString()) {
598 // Emit constant strings specially.
599 unsigned NumOps = C->getNumOperands();
600 // If this is a null-terminated string, use the denser CSTRING encoding.
601 if (C->getOperand(NumOps-1)->isNullValue()) {
602 Code = bitc::CST_CODE_CSTRING;
603 --NumOps; // Don't encode the null, which isn't allowed by char6.
605 Code = bitc::CST_CODE_STRING;
606 AbbrevToUse = String8Abbrev;
608 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
609 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
610 for (unsigned i = 0; i != NumOps; ++i) {
611 unsigned char V = cast<ConstantInt>(C->getOperand(i))->getZExtValue();
613 isCStr7 &= (V & 128) == 0;
615 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
619 AbbrevToUse = CString6Abbrev;
621 AbbrevToUse = CString7Abbrev;
622 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(V) ||
623 isa<ConstantVector>(V)) {
624 Code = bitc::CST_CODE_AGGREGATE;
625 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
626 Record.push_back(VE.getValueID(C->getOperand(i)));
627 AbbrevToUse = AggregateAbbrev;
628 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
629 switch (CE->getOpcode()) {
631 if (Instruction::isCast(CE->getOpcode())) {
632 Code = bitc::CST_CODE_CE_CAST;
633 Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
634 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
635 Record.push_back(VE.getValueID(C->getOperand(0)));
636 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
638 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
639 Code = bitc::CST_CODE_CE_BINOP;
640 Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
641 Record.push_back(VE.getValueID(C->getOperand(0)));
642 Record.push_back(VE.getValueID(C->getOperand(1)));
645 case Instruction::GetElementPtr:
646 Code = bitc::CST_CODE_CE_GEP;
647 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
648 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
649 Record.push_back(VE.getValueID(C->getOperand(i)));
652 case Instruction::Select:
653 Code = bitc::CST_CODE_CE_SELECT;
654 Record.push_back(VE.getValueID(C->getOperand(0)));
655 Record.push_back(VE.getValueID(C->getOperand(1)));
656 Record.push_back(VE.getValueID(C->getOperand(2)));
658 case Instruction::ExtractElement:
659 Code = bitc::CST_CODE_CE_EXTRACTELT;
660 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
661 Record.push_back(VE.getValueID(C->getOperand(0)));
662 Record.push_back(VE.getValueID(C->getOperand(1)));
664 case Instruction::InsertElement:
665 Code = bitc::CST_CODE_CE_INSERTELT;
666 Record.push_back(VE.getValueID(C->getOperand(0)));
667 Record.push_back(VE.getValueID(C->getOperand(1)));
668 Record.push_back(VE.getValueID(C->getOperand(2)));
670 case Instruction::ShuffleVector:
671 // If the return type and argument types are the same, this is a
672 // standard shufflevector instruction. If the types are different,
673 // then the shuffle is widening or truncating the input vectors, and
674 // the argument type must also be encoded.
675 if (C->getType() == C->getOperand(0)->getType()) {
676 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
678 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
679 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
681 Record.push_back(VE.getValueID(C->getOperand(0)));
682 Record.push_back(VE.getValueID(C->getOperand(1)));
683 Record.push_back(VE.getValueID(C->getOperand(2)));
685 case Instruction::ICmp:
686 case Instruction::FCmp:
687 Code = bitc::CST_CODE_CE_CMP;
688 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
689 Record.push_back(VE.getValueID(C->getOperand(0)));
690 Record.push_back(VE.getValueID(C->getOperand(1)));
691 Record.push_back(CE->getPredicate());
694 } else if (const MDString *S = dyn_cast<MDString>(C)) {
695 Code = bitc::CST_CODE_MDSTRING;
696 AbbrevToUse = MDString6Abbrev;
697 for (unsigned i = 0, e = S->size(); i != e; ++i) {
698 char V = S->begin()[i];
701 if (!BitCodeAbbrevOp::isChar6(V))
702 AbbrevToUse = MDString8Abbrev;
704 } else if (const MDNode *N = dyn_cast<MDNode>(C)) {
705 Code = bitc::CST_CODE_MDNODE;
706 for (unsigned i = 0, e = N->getNumElements(); i != e; ++i) {
707 if (N->getElement(i)) {
708 Record.push_back(VE.getTypeID(N->getElement(i)->getType()));
709 Record.push_back(VE.getValueID(N->getElement(i)));
711 Record.push_back(VE.getTypeID(Type::VoidTy));
716 LLVM_UNREACHABLE("Unknown constant!");
718 Stream.EmitRecord(Code, Record, AbbrevToUse);
725 static void WriteModuleConstants(const ValueEnumerator &VE,
726 BitstreamWriter &Stream) {
727 const ValueEnumerator::ValueList &Vals = VE.getValues();
729 // Find the first constant to emit, which is the first non-globalvalue value.
730 // We know globalvalues have been emitted by WriteModuleInfo.
731 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
732 if (!isa<GlobalValue>(Vals[i].first)) {
733 WriteConstants(i, Vals.size(), VE, Stream, true);
739 /// PushValueAndType - The file has to encode both the value and type id for
740 /// many values, because we need to know what type to create for forward
741 /// references. However, most operands are not forward references, so this type
742 /// field is not needed.
744 /// This function adds V's value ID to Vals. If the value ID is higher than the
745 /// instruction ID, then it is a forward reference, and it also includes the
747 static bool PushValueAndType(const Value *V, unsigned InstID,
748 SmallVector<unsigned, 64> &Vals,
749 ValueEnumerator &VE) {
750 unsigned ValID = VE.getValueID(V);
751 Vals.push_back(ValID);
752 if (ValID >= InstID) {
753 Vals.push_back(VE.getTypeID(V->getType()));
759 /// WriteInstruction - Emit an instruction to the specified stream.
760 static void WriteInstruction(const Instruction &I, unsigned InstID,
761 ValueEnumerator &VE, BitstreamWriter &Stream,
762 SmallVector<unsigned, 64> &Vals) {
764 unsigned AbbrevToUse = 0;
765 switch (I.getOpcode()) {
767 if (Instruction::isCast(I.getOpcode())) {
768 Code = bitc::FUNC_CODE_INST_CAST;
769 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
770 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
771 Vals.push_back(VE.getTypeID(I.getType()));
772 Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
774 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
775 Code = bitc::FUNC_CODE_INST_BINOP;
776 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
777 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
778 Vals.push_back(VE.getValueID(I.getOperand(1)));
779 Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
783 case Instruction::GetElementPtr:
784 Code = bitc::FUNC_CODE_INST_GEP;
785 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
786 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
788 case Instruction::ExtractValue: {
789 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
790 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
791 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
792 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
796 case Instruction::InsertValue: {
797 Code = bitc::FUNC_CODE_INST_INSERTVAL;
798 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
799 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
800 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
801 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
805 case Instruction::Select:
806 Code = bitc::FUNC_CODE_INST_VSELECT;
807 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
808 Vals.push_back(VE.getValueID(I.getOperand(2)));
809 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
811 case Instruction::ExtractElement:
812 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
813 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
814 Vals.push_back(VE.getValueID(I.getOperand(1)));
816 case Instruction::InsertElement:
817 Code = bitc::FUNC_CODE_INST_INSERTELT;
818 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
819 Vals.push_back(VE.getValueID(I.getOperand(1)));
820 Vals.push_back(VE.getValueID(I.getOperand(2)));
822 case Instruction::ShuffleVector:
823 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
824 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
825 Vals.push_back(VE.getValueID(I.getOperand(1)));
826 Vals.push_back(VE.getValueID(I.getOperand(2)));
828 case Instruction::ICmp:
829 case Instruction::FCmp:
830 // compare returning Int1Ty or vector of Int1Ty
831 Code = bitc::FUNC_CODE_INST_CMP2;
832 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
833 Vals.push_back(VE.getValueID(I.getOperand(1)));
834 Vals.push_back(cast<CmpInst>(I).getPredicate());
837 case Instruction::Ret:
839 Code = bitc::FUNC_CODE_INST_RET;
840 unsigned NumOperands = I.getNumOperands();
841 if (NumOperands == 0)
842 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
843 else if (NumOperands == 1) {
844 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
845 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
847 for (unsigned i = 0, e = NumOperands; i != e; ++i)
848 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
852 case Instruction::Br:
854 Code = bitc::FUNC_CODE_INST_BR;
855 BranchInst &II(cast<BranchInst>(I));
856 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
857 if (II.isConditional()) {
858 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
859 Vals.push_back(VE.getValueID(II.getCondition()));
863 case Instruction::Switch:
864 Code = bitc::FUNC_CODE_INST_SWITCH;
865 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
866 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
867 Vals.push_back(VE.getValueID(I.getOperand(i)));
869 case Instruction::Invoke: {
870 const InvokeInst *II = cast<InvokeInst>(&I);
871 const Value *Callee(II->getCalledValue());
872 const PointerType *PTy = cast<PointerType>(Callee->getType());
873 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
874 Code = bitc::FUNC_CODE_INST_INVOKE;
876 Vals.push_back(VE.getAttributeID(II->getAttributes()));
877 Vals.push_back(II->getCallingConv());
878 Vals.push_back(VE.getValueID(II->getNormalDest()));
879 Vals.push_back(VE.getValueID(II->getUnwindDest()));
880 PushValueAndType(Callee, InstID, Vals, VE);
882 // Emit value #'s for the fixed parameters.
883 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
884 Vals.push_back(VE.getValueID(I.getOperand(i+3))); // fixed param.
886 // Emit type/value pairs for varargs params.
887 if (FTy->isVarArg()) {
888 for (unsigned i = 3+FTy->getNumParams(), e = I.getNumOperands();
890 PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
894 case Instruction::Unwind:
895 Code = bitc::FUNC_CODE_INST_UNWIND;
897 case Instruction::Unreachable:
898 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
899 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
902 case Instruction::PHI:
903 Code = bitc::FUNC_CODE_INST_PHI;
904 Vals.push_back(VE.getTypeID(I.getType()));
905 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
906 Vals.push_back(VE.getValueID(I.getOperand(i)));
909 case Instruction::Malloc:
910 Code = bitc::FUNC_CODE_INST_MALLOC;
911 Vals.push_back(VE.getTypeID(I.getType()));
912 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
913 Vals.push_back(Log2_32(cast<MallocInst>(I).getAlignment())+1);
916 case Instruction::Free:
917 Code = bitc::FUNC_CODE_INST_FREE;
918 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
921 case Instruction::Alloca:
922 Code = bitc::FUNC_CODE_INST_ALLOCA;
923 Vals.push_back(VE.getTypeID(I.getType()));
924 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
925 Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1);
928 case Instruction::Load:
929 Code = bitc::FUNC_CODE_INST_LOAD;
930 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) // ptr
931 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
933 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
934 Vals.push_back(cast<LoadInst>(I).isVolatile());
936 case Instruction::Store:
937 Code = bitc::FUNC_CODE_INST_STORE2;
938 PushValueAndType(I.getOperand(1), InstID, Vals, VE); // ptrty + ptr
939 Vals.push_back(VE.getValueID(I.getOperand(0))); // val.
940 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
941 Vals.push_back(cast<StoreInst>(I).isVolatile());
943 case Instruction::Call: {
944 const PointerType *PTy = cast<PointerType>(I.getOperand(0)->getType());
945 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
947 Code = bitc::FUNC_CODE_INST_CALL;
949 const CallInst *CI = cast<CallInst>(&I);
950 Vals.push_back(VE.getAttributeID(CI->getAttributes()));
951 Vals.push_back((CI->getCallingConv() << 1) | unsigned(CI->isTailCall()));
952 PushValueAndType(CI->getOperand(0), InstID, Vals, VE); // Callee
954 // Emit value #'s for the fixed parameters.
955 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
956 Vals.push_back(VE.getValueID(I.getOperand(i+1))); // fixed param.
958 // Emit type/value pairs for varargs params.
959 if (FTy->isVarArg()) {
960 unsigned NumVarargs = I.getNumOperands()-1-FTy->getNumParams();
961 for (unsigned i = I.getNumOperands()-NumVarargs, e = I.getNumOperands();
963 PushValueAndType(I.getOperand(i), InstID, Vals, VE); // varargs
967 case Instruction::VAArg:
968 Code = bitc::FUNC_CODE_INST_VAARG;
969 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
970 Vals.push_back(VE.getValueID(I.getOperand(0))); // valist.
971 Vals.push_back(VE.getTypeID(I.getType())); // restype.
975 Stream.EmitRecord(Code, Vals, AbbrevToUse);
979 // Emit names for globals/functions etc.
980 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
981 const ValueEnumerator &VE,
982 BitstreamWriter &Stream) {
983 if (VST.empty()) return;
984 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
986 // FIXME: Set up the abbrev, we know how many values there are!
987 // FIXME: We know if the type names can use 7-bit ascii.
988 SmallVector<unsigned, 64> NameVals;
990 for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
993 const ValueName &Name = *SI;
995 // Figure out the encoding to use for the name.
998 for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
1001 isChar6 = BitCodeAbbrevOp::isChar6(*C);
1002 if ((unsigned char)*C & 128) {
1004 break; // don't bother scanning the rest.
1008 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
1010 // VST_ENTRY: [valueid, namechar x N]
1011 // VST_BBENTRY: [bbid, namechar x N]
1013 if (isa<BasicBlock>(SI->getValue())) {
1014 Code = bitc::VST_CODE_BBENTRY;
1016 AbbrevToUse = VST_BBENTRY_6_ABBREV;
1018 Code = bitc::VST_CODE_ENTRY;
1020 AbbrevToUse = VST_ENTRY_6_ABBREV;
1022 AbbrevToUse = VST_ENTRY_7_ABBREV;
1025 NameVals.push_back(VE.getValueID(SI->getValue()));
1026 for (const char *P = Name.getKeyData(),
1027 *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
1028 NameVals.push_back((unsigned char)*P);
1030 // Emit the finished record.
1031 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
1037 /// WriteFunction - Emit a function body to the module stream.
1038 static void WriteFunction(const Function &F, ValueEnumerator &VE,
1039 BitstreamWriter &Stream) {
1040 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
1041 VE.incorporateFunction(F);
1043 SmallVector<unsigned, 64> Vals;
1045 // Emit the number of basic blocks, so the reader can create them ahead of
1047 Vals.push_back(VE.getBasicBlocks().size());
1048 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
1051 // If there are function-local constants, emit them now.
1052 unsigned CstStart, CstEnd;
1053 VE.getFunctionConstantRange(CstStart, CstEnd);
1054 WriteConstants(CstStart, CstEnd, VE, Stream, false);
1056 // Keep a running idea of what the instruction ID is.
1057 unsigned InstID = CstEnd;
1059 // Finally, emit all the instructions, in order.
1060 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1061 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1063 WriteInstruction(*I, InstID, VE, Stream, Vals);
1064 if (I->getType() != Type::VoidTy)
1068 // Emit names for all the instructions etc.
1069 WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
1075 /// WriteTypeSymbolTable - Emit a block for the specified type symtab.
1076 static void WriteTypeSymbolTable(const TypeSymbolTable &TST,
1077 const ValueEnumerator &VE,
1078 BitstreamWriter &Stream) {
1079 if (TST.empty()) return;
1081 Stream.EnterSubblock(bitc::TYPE_SYMTAB_BLOCK_ID, 3);
1083 // 7-bit fixed width VST_CODE_ENTRY strings.
1084 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1085 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1086 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1087 Log2_32_Ceil(VE.getTypes().size()+1)));
1088 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1089 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1090 unsigned V7Abbrev = Stream.EmitAbbrev(Abbv);
1092 SmallVector<unsigned, 64> NameVals;
1094 for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end();
1096 // TST_ENTRY: [typeid, namechar x N]
1097 NameVals.push_back(VE.getTypeID(TI->second));
1099 const std::string &Str = TI->first;
1101 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1102 NameVals.push_back((unsigned char)Str[i]);
1107 // Emit the finished record.
1108 Stream.EmitRecord(bitc::VST_CODE_ENTRY, NameVals, is7Bit ? V7Abbrev : 0);
1115 // Emit blockinfo, which defines the standard abbreviations etc.
1116 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
1117 // We only want to emit block info records for blocks that have multiple
1118 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK. Other
1119 // blocks can defined their abbrevs inline.
1120 Stream.EnterBlockInfoBlock(2);
1122 { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
1123 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1124 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
1125 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1126 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1127 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1128 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1129 Abbv) != VST_ENTRY_8_ABBREV)
1130 LLVM_UNREACHABLE("Unexpected abbrev ordering!");
1133 { // 7-bit fixed width VST_ENTRY strings.
1134 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1135 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1136 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1137 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1138 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1139 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1140 Abbv) != VST_ENTRY_7_ABBREV)
1141 LLVM_UNREACHABLE("Unexpected abbrev ordering!");
1143 { // 6-bit char6 VST_ENTRY strings.
1144 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1145 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1146 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1147 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1148 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1149 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1150 Abbv) != VST_ENTRY_6_ABBREV)
1151 LLVM_UNREACHABLE("Unexpected abbrev ordering!");
1153 { // 6-bit char6 VST_BBENTRY strings.
1154 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1155 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
1156 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1157 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1158 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1159 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1160 Abbv) != VST_BBENTRY_6_ABBREV)
1161 LLVM_UNREACHABLE("Unexpected abbrev ordering!");
1166 { // SETTYPE abbrev for CONSTANTS_BLOCK.
1167 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1168 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
1169 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1170 Log2_32_Ceil(VE.getTypes().size()+1)));
1171 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1172 Abbv) != CONSTANTS_SETTYPE_ABBREV)
1173 LLVM_UNREACHABLE("Unexpected abbrev ordering!");
1176 { // INTEGER abbrev for CONSTANTS_BLOCK.
1177 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1178 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
1179 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1180 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1181 Abbv) != CONSTANTS_INTEGER_ABBREV)
1182 LLVM_UNREACHABLE("Unexpected abbrev ordering!");
1185 { // CE_CAST abbrev for CONSTANTS_BLOCK.
1186 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1187 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
1188 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
1189 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
1190 Log2_32_Ceil(VE.getTypes().size()+1)));
1191 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
1193 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1194 Abbv) != CONSTANTS_CE_CAST_Abbrev)
1195 LLVM_UNREACHABLE("Unexpected abbrev ordering!");
1197 { // NULL abbrev for CONSTANTS_BLOCK.
1198 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1199 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
1200 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1201 Abbv) != CONSTANTS_NULL_Abbrev)
1202 LLVM_UNREACHABLE("Unexpected abbrev ordering!");
1205 // FIXME: This should only use space for first class types!
1207 { // INST_LOAD abbrev for FUNCTION_BLOCK.
1208 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1209 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
1210 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
1211 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
1212 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
1213 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1214 Abbv) != FUNCTION_INST_LOAD_ABBREV)
1215 LLVM_UNREACHABLE("Unexpected abbrev ordering!");
1217 { // INST_BINOP abbrev for FUNCTION_BLOCK.
1218 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1219 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1220 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1221 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1222 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1223 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1224 Abbv) != FUNCTION_INST_BINOP_ABBREV)
1225 LLVM_UNREACHABLE("Unexpected abbrev ordering!");
1227 { // INST_CAST abbrev for FUNCTION_BLOCK.
1228 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1229 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
1230 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
1231 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
1232 Log2_32_Ceil(VE.getTypes().size()+1)));
1233 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1234 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1235 Abbv) != FUNCTION_INST_CAST_ABBREV)
1236 LLVM_UNREACHABLE("Unexpected abbrev ordering!");
1239 { // INST_RET abbrev for FUNCTION_BLOCK.
1240 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1241 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1242 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1243 Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
1244 LLVM_UNREACHABLE("Unexpected abbrev ordering!");
1246 { // INST_RET abbrev for FUNCTION_BLOCK.
1247 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1248 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1249 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
1250 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1251 Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
1252 LLVM_UNREACHABLE("Unexpected abbrev ordering!");
1254 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
1255 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1256 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
1257 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1258 Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
1259 LLVM_UNREACHABLE("Unexpected abbrev ordering!");
1266 /// WriteModule - Emit the specified module to the bitstream.
1267 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
1268 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
1270 // Emit the version number if it is non-zero.
1272 SmallVector<unsigned, 1> Vals;
1273 Vals.push_back(CurVersion);
1274 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
1277 // Analyze the module, enumerating globals, functions, etc.
1278 ValueEnumerator VE(M);
1280 // Emit blockinfo, which defines the standard abbreviations etc.
1281 WriteBlockInfo(VE, Stream);
1283 // Emit information about parameter attributes.
1284 WriteAttributeTable(VE, Stream);
1286 // Emit information describing all of the types in the module.
1287 WriteTypeTable(VE, Stream);
1289 // Emit top-level description of module, including target triple, inline asm,
1290 // descriptors for global variables, and function prototype info.
1291 WriteModuleInfo(M, VE, Stream);
1294 WriteModuleConstants(VE, Stream);
1296 // Emit function bodies.
1297 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1298 if (!I->isDeclaration())
1299 WriteFunction(*I, VE, Stream);
1301 // Emit the type symbol table information.
1302 WriteTypeSymbolTable(M->getTypeSymbolTable(), VE, Stream);
1304 // Emit names for globals/functions etc.
1305 WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
1310 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
1311 /// header and trailer to make it compatible with the system archiver. To do
1312 /// this we emit the following header, and then emit a trailer that pads the
1313 /// file out to be a multiple of 16 bytes.
1315 /// struct bc_header {
1316 /// uint32_t Magic; // 0x0B17C0DE
1317 /// uint32_t Version; // Version, currently always 0.
1318 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
1319 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
1320 /// uint32_t CPUType; // CPU specifier.
1321 /// ... potentially more later ...
1324 DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
1325 DarwinBCHeaderSize = 5*4
1328 static void EmitDarwinBCHeader(BitstreamWriter &Stream,
1329 const std::string &TT) {
1330 unsigned CPUType = ~0U;
1332 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*. The CPUType is a
1333 // magic number from /usr/include/mach/machine.h. It is ok to reproduce the
1334 // specific constants here because they are implicitly part of the Darwin ABI.
1336 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
1337 DARWIN_CPU_TYPE_X86 = 7,
1338 DARWIN_CPU_TYPE_POWERPC = 18
1341 if (TT.find("x86_64-") == 0)
1342 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
1343 else if (TT.size() >= 5 && TT[0] == 'i' && TT[2] == '8' && TT[3] == '6' &&
1344 TT[4] == '-' && TT[1] - '3' < 6)
1345 CPUType = DARWIN_CPU_TYPE_X86;
1346 else if (TT.find("powerpc-") == 0)
1347 CPUType = DARWIN_CPU_TYPE_POWERPC;
1348 else if (TT.find("powerpc64-") == 0)
1349 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
1351 // Traditional Bitcode starts after header.
1352 unsigned BCOffset = DarwinBCHeaderSize;
1354 Stream.Emit(0x0B17C0DE, 32);
1355 Stream.Emit(0 , 32); // Version.
1356 Stream.Emit(BCOffset , 32);
1357 Stream.Emit(0 , 32); // Filled in later.
1358 Stream.Emit(CPUType , 32);
1361 /// EmitDarwinBCTrailer - Emit the darwin epilog after the bitcode file and
1362 /// finalize the header.
1363 static void EmitDarwinBCTrailer(BitstreamWriter &Stream, unsigned BufferSize) {
1364 // Update the size field in the header.
1365 Stream.BackpatchWord(DarwinBCSizeFieldOffset, BufferSize-DarwinBCHeaderSize);
1367 // If the file is not a multiple of 16 bytes, insert dummy padding.
1368 while (BufferSize & 15) {
1375 /// WriteBitcodeToFile - Write the specified module to the specified output
1377 void llvm::WriteBitcodeToFile(const Module *M, std::ostream &Out) {
1378 raw_os_ostream RawOut(Out);
1379 // If writing to stdout, set binary mode.
1380 if (llvm::cout == Out)
1381 sys::Program::ChangeStdoutToBinary();
1382 WriteBitcodeToFile(M, RawOut);
1385 /// WriteBitcodeToFile - Write the specified module to the specified output
1387 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out) {
1388 std::vector<unsigned char> Buffer;
1389 BitstreamWriter Stream(Buffer);
1391 Buffer.reserve(256*1024);
1393 WriteBitcodeToStream( M, Stream );
1395 // If writing to stdout, set binary mode.
1396 if (&llvm::outs() == &Out)
1397 sys::Program::ChangeStdoutToBinary();
1399 // Write the generated bitstream to "Out".
1400 Out.write((char*)&Buffer.front(), Buffer.size());
1402 // Make sure it hits disk now.
1406 /// WriteBitcodeToStream - Write the specified module to the specified output
1408 void llvm::WriteBitcodeToStream(const Module *M, BitstreamWriter &Stream) {
1409 // If this is darwin, emit a file header and trailer if needed.
1410 bool isDarwin = M->getTargetTriple().find("-darwin") != std::string::npos;
1412 EmitDarwinBCHeader(Stream, M->getTargetTriple());
1414 // Emit the file header.
1415 Stream.Emit((unsigned)'B', 8);
1416 Stream.Emit((unsigned)'C', 8);
1417 Stream.Emit(0x0, 4);
1418 Stream.Emit(0xC, 4);
1419 Stream.Emit(0xE, 4);
1420 Stream.Emit(0xD, 4);
1423 WriteModule(M, Stream);
1426 EmitDarwinBCTrailer(Stream, Stream.getBuffer().size());