1 //===--- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source 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/Instructions.h"
21 #include "llvm/Module.h"
22 #include "llvm/TypeSymbolTable.h"
23 #include "llvm/ValueSymbolTable.h"
24 #include "llvm/Support/MathExtras.h"
27 static const unsigned CurVersion = 0;
29 static unsigned GetEncodedCastOpcode(unsigned Opcode) {
31 default: assert(0 && "Unknown cast instruction!");
32 case Instruction::Trunc : return bitc::CAST_TRUNC;
33 case Instruction::ZExt : return bitc::CAST_ZEXT;
34 case Instruction::SExt : return bitc::CAST_SEXT;
35 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
36 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
37 case Instruction::UIToFP : return bitc::CAST_UITOFP;
38 case Instruction::SIToFP : return bitc::CAST_SITOFP;
39 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
40 case Instruction::FPExt : return bitc::CAST_FPEXT;
41 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
42 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
43 case Instruction::BitCast : return bitc::CAST_BITCAST;
47 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
49 default: assert(0 && "Unknown binary instruction!");
50 case Instruction::Add: return bitc::BINOP_ADD;
51 case Instruction::Sub: return bitc::BINOP_SUB;
52 case Instruction::Mul: return bitc::BINOP_MUL;
53 case Instruction::UDiv: return bitc::BINOP_UDIV;
54 case Instruction::FDiv:
55 case Instruction::SDiv: return bitc::BINOP_SDIV;
56 case Instruction::URem: return bitc::BINOP_UREM;
57 case Instruction::FRem:
58 case Instruction::SRem: return bitc::BINOP_SREM;
59 case Instruction::Shl: return bitc::BINOP_SHL;
60 case Instruction::LShr: return bitc::BINOP_LSHR;
61 case Instruction::AShr: return bitc::BINOP_ASHR;
62 case Instruction::And: return bitc::BINOP_AND;
63 case Instruction::Or: return bitc::BINOP_OR;
64 case Instruction::Xor: return bitc::BINOP_XOR;
70 static void WriteStringRecord(unsigned Code, const std::string &Str,
71 unsigned AbbrevToUse, BitstreamWriter &Stream) {
72 SmallVector<unsigned, 64> Vals;
74 // Code: [strlen, strchar x N]
75 Vals.push_back(Str.size());
76 for (unsigned i = 0, e = Str.size(); i != e; ++i)
77 Vals.push_back(Str[i]);
79 // Emit the finished record.
80 Stream.EmitRecord(Code, Vals, AbbrevToUse);
84 /// WriteTypeTable - Write out the type table for a module.
85 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
86 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
88 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID, 4 /*count from # abbrevs */);
89 SmallVector<uint64_t, 64> TypeVals;
91 // FIXME: Set up abbrevs now that we know the width of the type fields, etc.
93 // Emit an entry count so the reader can reserve space.
94 TypeVals.push_back(TypeList.size());
95 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
98 // Loop over all of the types, emitting each in turn.
99 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
100 const Type *T = TypeList[i].first;
104 switch (T->getTypeID()) {
105 case Type::PackedStructTyID: // FIXME: Delete Type::PackedStructTyID.
106 default: assert(0 && "Unknown type!");
107 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
108 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
109 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
110 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
111 case Type::OpaqueTyID: Code = bitc::TYPE_CODE_OPAQUE; break;
112 case Type::IntegerTyID:
114 Code = bitc::TYPE_CODE_INTEGER;
115 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
117 case Type::PointerTyID:
118 // POINTER: [pointee type]
119 Code = bitc::TYPE_CODE_POINTER;
120 TypeVals.push_back(VE.getTypeID(cast<PointerType>(T)->getElementType()));
123 case Type::FunctionTyID: {
124 const FunctionType *FT = cast<FunctionType>(T);
125 // FUNCTION: [isvararg, #pararms, paramty x N]
126 Code = bitc::TYPE_CODE_FUNCTION;
127 TypeVals.push_back(FT->isVarArg());
128 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
129 // FIXME: PARAM ATTR ID!
130 TypeVals.push_back(FT->getNumParams());
131 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
132 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
135 case Type::StructTyID: {
136 const StructType *ST = cast<StructType>(T);
137 // STRUCT: [ispacked, #elts, eltty x N]
138 Code = bitc::TYPE_CODE_STRUCT;
139 TypeVals.push_back(ST->isPacked());
140 TypeVals.push_back(ST->getNumElements());
141 // Output all of the element types...
142 for (StructType::element_iterator I = ST->element_begin(),
143 E = ST->element_end(); I != E; ++I)
144 TypeVals.push_back(VE.getTypeID(*I));
147 case Type::ArrayTyID: {
148 const ArrayType *AT = cast<ArrayType>(T);
149 // ARRAY: [numelts, eltty]
150 Code = bitc::TYPE_CODE_ARRAY;
151 TypeVals.push_back(AT->getNumElements());
152 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
155 case Type::VectorTyID: {
156 const VectorType *VT = cast<VectorType>(T);
157 // VECTOR [numelts, eltty]
158 Code = bitc::TYPE_CODE_VECTOR;
159 TypeVals.push_back(VT->getNumElements());
160 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
165 // Emit the finished record.
166 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
173 static unsigned getEncodedLinkage(const GlobalValue *GV) {
174 switch (GV->getLinkage()) {
175 default: assert(0 && "Invalid linkage!");
176 case GlobalValue::ExternalLinkage: return 0;
177 case GlobalValue::WeakLinkage: return 1;
178 case GlobalValue::AppendingLinkage: return 2;
179 case GlobalValue::InternalLinkage: return 3;
180 case GlobalValue::LinkOnceLinkage: return 4;
181 case GlobalValue::DLLImportLinkage: return 5;
182 case GlobalValue::DLLExportLinkage: return 6;
183 case GlobalValue::ExternalWeakLinkage: return 7;
187 static unsigned getEncodedVisibility(const GlobalValue *GV) {
188 switch (GV->getVisibility()) {
189 default: assert(0 && "Invalid visibility!");
190 case GlobalValue::DefaultVisibility: return 0;
191 case GlobalValue::HiddenVisibility: return 1;
195 // Emit top-level description of module, including target triple, inline asm,
196 // descriptors for global variables, and function prototype info.
197 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
198 BitstreamWriter &Stream) {
199 // Emit the list of dependent libraries for the Module.
200 for (Module::lib_iterator I = M->lib_begin(), E = M->lib_end(); I != E; ++I)
201 WriteStringRecord(bitc::MODULE_CODE_DEPLIB, *I, 0/*TODO*/, Stream);
203 // Emit various pieces of data attached to a module.
204 if (!M->getTargetTriple().empty())
205 WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
207 if (!M->getDataLayout().empty())
208 WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(),
210 if (!M->getModuleInlineAsm().empty())
211 WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
214 // Emit information about sections, computing how many there are. Also
215 // compute the maximum alignment value.
216 std::map<std::string, unsigned> SectionMap;
217 unsigned MaxAlignment = 0;
218 unsigned MaxGlobalType = 0;
219 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
221 MaxAlignment = std::max(MaxAlignment, GV->getAlignment());
222 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType()));
224 if (!GV->hasSection()) continue;
225 // Give section names unique ID's.
226 unsigned &Entry = SectionMap[GV->getSection()];
227 if (Entry != 0) continue;
228 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(),
230 Entry = SectionMap.size();
232 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
233 MaxAlignment = std::max(MaxAlignment, F->getAlignment());
234 if (!F->hasSection()) continue;
235 // Give section names unique ID's.
236 unsigned &Entry = SectionMap[F->getSection()];
237 if (Entry != 0) continue;
238 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(),
240 Entry = SectionMap.size();
243 // Emit abbrev for globals, now that we know # sections and max alignment.
244 unsigned SimpleGVarAbbrev = 0;
245 if (!M->global_empty()) {
246 // Add an abbrev for common globals with no visibility or thread localness.
247 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
248 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
249 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth,
250 Log2_32_Ceil(MaxGlobalType+1)));
251 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth, 1)); // Constant.
252 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
253 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth, 3)); // Linkage.
254 if (MaxAlignment == 0) // Alignment.
255 Abbv->Add(BitCodeAbbrevOp(0));
257 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
258 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth,
259 Log2_32_Ceil(MaxEncAlignment+1)));
261 if (SectionMap.empty()) // Section.
262 Abbv->Add(BitCodeAbbrevOp(0));
264 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth,
265 Log2_32_Ceil(SectionMap.size()+1)));
266 // Don't bother emitting vis + thread local.
267 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
270 // Emit the global variable information.
271 SmallVector<unsigned, 64> Vals;
272 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
274 unsigned AbbrevToUse = 0;
276 // GLOBALVAR: [type, isconst, initid,
277 // linkage, alignment, section, visibility, threadlocal]
278 Vals.push_back(VE.getTypeID(GV->getType()));
279 Vals.push_back(GV->isConstant());
280 Vals.push_back(GV->isDeclaration() ? 0 :
281 (VE.getValueID(GV->getInitializer()) + 1));
282 Vals.push_back(getEncodedLinkage(GV));
283 Vals.push_back(Log2_32(GV->getAlignment())+1);
284 Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0);
285 if (GV->isThreadLocal() ||
286 GV->getVisibility() != GlobalValue::DefaultVisibility) {
287 Vals.push_back(getEncodedVisibility(GV));
288 Vals.push_back(GV->isThreadLocal());
290 AbbrevToUse = SimpleGVarAbbrev;
293 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
297 // Emit the function proto information.
298 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
299 // FUNCTION: [type, callingconv, isproto, linkage, alignment, section,
301 Vals.push_back(VE.getTypeID(F->getType()));
302 Vals.push_back(F->getCallingConv());
303 Vals.push_back(F->isDeclaration());
304 Vals.push_back(getEncodedLinkage(F));
305 Vals.push_back(Log2_32(F->getAlignment())+1);
306 Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
307 Vals.push_back(getEncodedVisibility(F));
309 unsigned AbbrevToUse = 0;
310 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
315 // Emit the alias information.
316 for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end();
318 Vals.push_back(VE.getTypeID(AI->getType()));
319 Vals.push_back(VE.getValueID(AI->getAliasee()));
320 Vals.push_back(getEncodedLinkage(AI));
321 unsigned AbbrevToUse = 0;
322 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
328 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
329 const ValueEnumerator &VE,
330 BitstreamWriter &Stream) {
331 if (FirstVal == LastVal) return;
333 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 2);
335 // FIXME: Install and use abbrevs to reduce size. Install them globally so
336 // they don't need to be reemitted for each function body.
338 SmallVector<uint64_t, 64> Record;
340 const ValueEnumerator::ValueList &Vals = VE.getValues();
341 const Type *LastTy = 0;
342 for (unsigned i = FirstVal; i != LastVal; ++i) {
343 const Value *V = Vals[i].first;
344 // If we need to switch types, do so now.
345 if (V->getType() != LastTy) {
346 LastTy = V->getType();
347 Record.push_back(VE.getTypeID(LastTy));
348 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record);
352 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
353 assert(0 && IA && "FIXME: Inline asm writing unimp!");
356 const Constant *C = cast<Constant>(V);
358 unsigned AbbrevToUse = 0;
359 if (C->isNullValue()) {
360 Code = bitc::CST_CODE_NULL;
361 } else if (isa<UndefValue>(C)) {
362 Code = bitc::CST_CODE_UNDEF;
363 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
364 if (IV->getBitWidth() <= 64) {
365 int64_t V = IV->getSExtValue();
367 Record.push_back(V << 1);
369 Record.push_back((-V << 1) | 1);
370 Code = bitc::CST_CODE_INTEGER;
371 } else { // Wide integers, > 64 bits in size.
372 // We have an arbitrary precision integer value to write whose
373 // bit width is > 64. However, in canonical unsigned integer
374 // format it is likely that the high bits are going to be zero.
375 // So, we only write the number of active words.
376 unsigned NWords = IV->getValue().getActiveWords();
377 const uint64_t *RawWords = IV->getValue().getRawData();
378 Record.push_back(NWords);
379 for (unsigned i = 0; i != NWords; ++i) {
380 int64_t V = RawWords[i];
382 Record.push_back(V << 1);
384 Record.push_back((-V << 1) | 1);
386 Code = bitc::CST_CODE_WIDE_INTEGER;
388 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
389 Code = bitc::CST_CODE_FLOAT;
390 if (CFP->getType() == Type::FloatTy) {
391 Record.push_back(FloatToBits((float)CFP->getValue()));
393 assert (CFP->getType() == Type::DoubleTy && "Unknown FP type!");
394 Record.push_back(DoubleToBits((double)CFP->getValue()));
396 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(V) ||
397 isa<ConstantVector>(V)) {
398 Code = bitc::CST_CODE_AGGREGATE;
399 Record.push_back(C->getNumOperands());
400 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
401 Record.push_back(VE.getValueID(C->getOperand(i)));
402 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
403 switch (CE->getOpcode()) {
405 if (Instruction::isCast(CE->getOpcode())) {
406 Code = bitc::CST_CODE_CE_CAST;
407 Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
408 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
409 Record.push_back(VE.getValueID(C->getOperand(0)));
411 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
412 Code = bitc::CST_CODE_CE_BINOP;
413 Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
414 Record.push_back(VE.getValueID(C->getOperand(0)));
415 Record.push_back(VE.getValueID(C->getOperand(1)));
418 case Instruction::GetElementPtr:
419 Code = bitc::CST_CODE_CE_GEP;
420 Record.push_back(CE->getNumOperands());
421 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
422 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
423 Record.push_back(VE.getValueID(C->getOperand(i)));
426 case Instruction::Select:
427 Code = bitc::CST_CODE_CE_SELECT;
428 Record.push_back(VE.getValueID(C->getOperand(0)));
429 Record.push_back(VE.getValueID(C->getOperand(1)));
430 Record.push_back(VE.getValueID(C->getOperand(2)));
432 case Instruction::ExtractElement:
433 Code = bitc::CST_CODE_CE_EXTRACTELT;
434 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
435 Record.push_back(VE.getValueID(C->getOperand(0)));
436 Record.push_back(VE.getValueID(C->getOperand(1)));
438 case Instruction::InsertElement:
439 Code = bitc::CST_CODE_CE_INSERTELT;
440 Record.push_back(VE.getValueID(C->getOperand(0)));
441 Record.push_back(VE.getValueID(C->getOperand(1)));
442 Record.push_back(VE.getValueID(C->getOperand(2)));
444 case Instruction::ShuffleVector:
445 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
446 Record.push_back(VE.getValueID(C->getOperand(0)));
447 Record.push_back(VE.getValueID(C->getOperand(1)));
448 Record.push_back(VE.getValueID(C->getOperand(2)));
450 case Instruction::ICmp:
451 case Instruction::FCmp:
452 Code = bitc::CST_CODE_CE_CMP;
453 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
454 Record.push_back(VE.getValueID(C->getOperand(0)));
455 Record.push_back(VE.getValueID(C->getOperand(1)));
456 Record.push_back(CE->getPredicate());
460 assert(0 && "Unknown constant!");
462 Stream.EmitRecord(Code, Record, AbbrevToUse);
469 static void WriteModuleConstants(const ValueEnumerator &VE,
470 BitstreamWriter &Stream) {
471 const ValueEnumerator::ValueList &Vals = VE.getValues();
473 // Find the first constant to emit, which is the first non-globalvalue value.
474 // We know globalvalues have been emitted by WriteModuleInfo.
475 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
476 if (!isa<GlobalValue>(Vals[i].first)) {
477 WriteConstants(i, Vals.size(), VE, Stream);
483 /// WriteInstruction - Emit an instruction to the specified stream.
484 static void WriteInstruction(const Instruction &I, ValueEnumerator &VE,
485 BitstreamWriter &Stream,
486 SmallVector<unsigned, 64> &Vals) {
487 return; // FIXME: REMOVE
491 unsigned AbbrevToUse = 0;
492 switch (I.getOpcode()) {
494 if (Instruction::isCast(I.getOpcode())) {
495 Code = bitc::FUNC_CODE_INST_BINOP;
496 Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
497 Vals.push_back(VE.getTypeID(I.getType()));
498 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
499 Vals.push_back(VE.getValueID(I.getOperand(0)));
501 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
502 Code = bitc::CST_CODE_CE_BINOP;
503 Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
504 Vals.push_back(VE.getTypeID(I.getType()));
505 Vals.push_back(VE.getValueID(I.getOperand(0)));
506 Vals.push_back(VE.getValueID(I.getOperand(1)));
511 case Instruction::Unwind:
512 Code = bitc::FUNC_CODE_INST_UNWIND;
514 case Instruction::Unreachable:
515 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
520 Stream.EmitRecord(Code, Vals, AbbrevToUse);
524 /// WriteFunction - Emit a function body to the module stream.
525 static void WriteFunction(const Function &F, ValueEnumerator &VE,
526 BitstreamWriter &Stream) {
527 Stream.EnterSubblock(bitc::TYPE_SYMTAB_BLOCK_ID, 3);
528 VE.incorporateFunction(F);
530 SmallVector<unsigned, 64> Vals;
532 // Emit the number of basic blocks, so the reader can create them ahead of
534 Vals.push_back(VE.getBasicBlocks().size());
535 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
538 // FIXME: Function attributes?
540 // If there are function-local constants, emit them now.
541 unsigned CstStart, CstEnd;
542 VE.getFunctionConstantRange(CstStart, CstEnd);
543 WriteConstants(CstStart, CstEnd, VE, Stream);
545 // Finally, emit all the instructions, in order.
546 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
547 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
548 WriteInstruction(*I, VE, Stream, Vals);
554 /// WriteTypeSymbolTable - Emit a block for the specified type symtab.
555 static void WriteTypeSymbolTable(const TypeSymbolTable &TST,
556 const ValueEnumerator &VE,
557 BitstreamWriter &Stream) {
558 if (TST.empty()) return;
560 Stream.EnterSubblock(bitc::TYPE_SYMTAB_BLOCK_ID, 3);
562 // FIXME: Set up the abbrev, we know how many types there are!
563 // FIXME: We know if the type names can use 7-bit ascii.
565 SmallVector<unsigned, 64> NameVals;
567 for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end();
569 unsigned AbbrevToUse = 0;
571 // TST_ENTRY: [typeid, namelen, namechar x N]
572 NameVals.push_back(VE.getTypeID(TI->second));
574 const std::string &Str = TI->first;
575 NameVals.push_back(Str.size());
576 for (unsigned i = 0, e = Str.size(); i != e; ++i)
577 NameVals.push_back(Str[i]);
579 // Emit the finished record.
580 Stream.EmitRecord(bitc::VST_CODE_ENTRY, NameVals, AbbrevToUse);
587 // Emit names for globals/functions etc.
588 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
589 const ValueEnumerator &VE,
590 BitstreamWriter &Stream) {
591 if (VST.empty()) return;
592 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 3);
594 // FIXME: Set up the abbrev, we know how many values there are!
595 // FIXME: We know if the type names can use 7-bit ascii.
596 SmallVector<unsigned, 64> NameVals;
598 for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
600 unsigned AbbrevToUse = 0;
602 // VST_ENTRY: [valueid, namelen, namechar x N]
603 NameVals.push_back(VE.getValueID(SI->getValue()));
605 NameVals.push_back(SI->getKeyLength());
606 for (const char *P = SI->getKeyData(),
607 *E = SI->getKeyData()+SI->getKeyLength(); P != E; ++P)
608 NameVals.push_back((unsigned char)*P);
610 // Emit the finished record.
611 Stream.EmitRecord(bitc::VST_CODE_ENTRY, NameVals, AbbrevToUse);
618 /// WriteModule - Emit the specified module to the bitstream.
619 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
620 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
622 // Emit the version number if it is non-zero.
624 SmallVector<unsigned, 1> Vals;
625 Vals.push_back(CurVersion);
626 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
629 // Analyze the module, enumerating globals, functions, etc.
630 ValueEnumerator VE(M);
632 // Emit information describing all of the types in the module.
633 WriteTypeTable(VE, Stream);
635 // Emit top-level description of module, including target triple, inline asm,
636 // descriptors for global variables, and function prototype info.
637 WriteModuleInfo(M, VE, Stream);
640 WriteModuleConstants(VE, Stream);
642 // If we have any aggregate values in the value table, purge them - these can
643 // only be used to initialize global variables. Doing so makes the value
644 // namespace smaller for code in functions.
645 int NumNonAggregates = VE.PurgeAggregateValues();
646 if (NumNonAggregates != -1) {
647 SmallVector<unsigned, 1> Vals;
648 Vals.push_back(NumNonAggregates);
649 Stream.EmitRecord(bitc::MODULE_CODE_PURGEVALS, Vals);
652 // Emit function bodies.
653 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
654 if (!I->isDeclaration())
655 WriteFunction(*I, VE, Stream);
657 // Emit the type symbol table information.
658 WriteTypeSymbolTable(M->getTypeSymbolTable(), VE, Stream);
660 // Emit names for globals/functions etc.
661 WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
666 /// WriteBitcodeToFile - Write the specified module to the specified output
668 void llvm::WriteBitcodeToFile(const Module *M, std::ostream &Out) {
669 std::vector<unsigned char> Buffer;
670 BitstreamWriter Stream(Buffer);
672 Buffer.reserve(256*1024);
674 // Emit the file header.
675 Stream.Emit((unsigned)'B', 8);
676 Stream.Emit((unsigned)'C', 8);
683 WriteModule(M, Stream);
685 // Write the generated bitstream to "Out".
686 Out.write((char*)&Buffer.front(), Buffer.size());