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;
192 case GlobalValue::ProtectedVisibility: return 2;
196 // Emit top-level description of module, including target triple, inline asm,
197 // descriptors for global variables, and function prototype info.
198 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
199 BitstreamWriter &Stream) {
200 // Emit the list of dependent libraries for the Module.
201 for (Module::lib_iterator I = M->lib_begin(), E = M->lib_end(); I != E; ++I)
202 WriteStringRecord(bitc::MODULE_CODE_DEPLIB, *I, 0/*TODO*/, Stream);
204 // Emit various pieces of data attached to a module.
205 if (!M->getTargetTriple().empty())
206 WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
208 if (!M->getDataLayout().empty())
209 WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(),
211 if (!M->getModuleInlineAsm().empty())
212 WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
215 // Emit information about sections, computing how many there are. Also
216 // compute the maximum alignment value.
217 std::map<std::string, unsigned> SectionMap;
218 unsigned MaxAlignment = 0;
219 unsigned MaxGlobalType = 0;
220 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
222 MaxAlignment = std::max(MaxAlignment, GV->getAlignment());
223 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType()));
225 if (!GV->hasSection()) continue;
226 // Give section names unique ID's.
227 unsigned &Entry = SectionMap[GV->getSection()];
228 if (Entry != 0) continue;
229 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(),
231 Entry = SectionMap.size();
233 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
234 MaxAlignment = std::max(MaxAlignment, F->getAlignment());
235 if (!F->hasSection()) continue;
236 // Give section names unique ID's.
237 unsigned &Entry = SectionMap[F->getSection()];
238 if (Entry != 0) continue;
239 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(),
241 Entry = SectionMap.size();
244 // Emit abbrev for globals, now that we know # sections and max alignment.
245 unsigned SimpleGVarAbbrev = 0;
246 if (!M->global_empty()) {
247 // Add an abbrev for common globals with no visibility or thread localness.
248 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
249 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
250 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth,
251 Log2_32_Ceil(MaxGlobalType+1)));
252 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth, 1)); // Constant.
253 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
254 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth, 3)); // Linkage.
255 if (MaxAlignment == 0) // Alignment.
256 Abbv->Add(BitCodeAbbrevOp(0));
258 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
259 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth,
260 Log2_32_Ceil(MaxEncAlignment+1)));
262 if (SectionMap.empty()) // Section.
263 Abbv->Add(BitCodeAbbrevOp(0));
265 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth,
266 Log2_32_Ceil(SectionMap.size()+1)));
267 // Don't bother emitting vis + thread local.
268 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
271 // Emit the global variable information.
272 SmallVector<unsigned, 64> Vals;
273 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
275 unsigned AbbrevToUse = 0;
277 // GLOBALVAR: [type, isconst, initid,
278 // linkage, alignment, section, visibility, threadlocal]
279 Vals.push_back(VE.getTypeID(GV->getType()));
280 Vals.push_back(GV->isConstant());
281 Vals.push_back(GV->isDeclaration() ? 0 :
282 (VE.getValueID(GV->getInitializer()) + 1));
283 Vals.push_back(getEncodedLinkage(GV));
284 Vals.push_back(Log2_32(GV->getAlignment())+1);
285 Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0);
286 if (GV->isThreadLocal() ||
287 GV->getVisibility() != GlobalValue::DefaultVisibility) {
288 Vals.push_back(getEncodedVisibility(GV));
289 Vals.push_back(GV->isThreadLocal());
291 AbbrevToUse = SimpleGVarAbbrev;
294 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
298 // Emit the function proto information.
299 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
300 // FUNCTION: [type, callingconv, isproto, linkage, alignment, section,
302 Vals.push_back(VE.getTypeID(F->getType()));
303 Vals.push_back(F->getCallingConv());
304 Vals.push_back(F->isDeclaration());
305 Vals.push_back(getEncodedLinkage(F));
306 Vals.push_back(Log2_32(F->getAlignment())+1);
307 Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
308 Vals.push_back(getEncodedVisibility(F));
310 unsigned AbbrevToUse = 0;
311 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
316 // Emit the alias information.
317 for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end();
319 Vals.push_back(VE.getTypeID(AI->getType()));
320 Vals.push_back(VE.getValueID(AI->getAliasee()));
321 Vals.push_back(getEncodedLinkage(AI));
322 unsigned AbbrevToUse = 0;
323 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
329 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
330 const ValueEnumerator &VE,
331 BitstreamWriter &Stream) {
332 if (FirstVal == LastVal) return;
334 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 2);
336 // FIXME: Install and use abbrevs to reduce size. Install them globally so
337 // they don't need to be reemitted for each function body.
339 SmallVector<uint64_t, 64> Record;
341 const ValueEnumerator::ValueList &Vals = VE.getValues();
342 const Type *LastTy = 0;
343 for (unsigned i = FirstVal; i != LastVal; ++i) {
344 const Value *V = Vals[i].first;
345 // If we need to switch types, do so now.
346 if (V->getType() != LastTy) {
347 LastTy = V->getType();
348 Record.push_back(VE.getTypeID(LastTy));
349 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record);
353 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
354 assert(0 && IA && "FIXME: Inline asm writing unimp!");
357 const Constant *C = cast<Constant>(V);
359 unsigned AbbrevToUse = 0;
360 if (C->isNullValue()) {
361 Code = bitc::CST_CODE_NULL;
362 } else if (isa<UndefValue>(C)) {
363 Code = bitc::CST_CODE_UNDEF;
364 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
365 if (IV->getBitWidth() <= 64) {
366 int64_t V = IV->getSExtValue();
368 Record.push_back(V << 1);
370 Record.push_back((-V << 1) | 1);
371 Code = bitc::CST_CODE_INTEGER;
372 } else { // Wide integers, > 64 bits in size.
373 // We have an arbitrary precision integer value to write whose
374 // bit width is > 64. However, in canonical unsigned integer
375 // format it is likely that the high bits are going to be zero.
376 // So, we only write the number of active words.
377 unsigned NWords = IV->getValue().getActiveWords();
378 const uint64_t *RawWords = IV->getValue().getRawData();
379 Record.push_back(NWords);
380 for (unsigned i = 0; i != NWords; ++i) {
381 int64_t V = RawWords[i];
383 Record.push_back(V << 1);
385 Record.push_back((-V << 1) | 1);
387 Code = bitc::CST_CODE_WIDE_INTEGER;
389 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
390 Code = bitc::CST_CODE_FLOAT;
391 if (CFP->getType() == Type::FloatTy) {
392 Record.push_back(FloatToBits((float)CFP->getValue()));
394 assert (CFP->getType() == Type::DoubleTy && "Unknown FP type!");
395 Record.push_back(DoubleToBits((double)CFP->getValue()));
397 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(V) ||
398 isa<ConstantVector>(V)) {
399 Code = bitc::CST_CODE_AGGREGATE;
400 Record.push_back(C->getNumOperands());
401 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
402 Record.push_back(VE.getValueID(C->getOperand(i)));
403 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
404 switch (CE->getOpcode()) {
406 if (Instruction::isCast(CE->getOpcode())) {
407 Code = bitc::CST_CODE_CE_CAST;
408 Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
409 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
410 Record.push_back(VE.getValueID(C->getOperand(0)));
412 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
413 Code = bitc::CST_CODE_CE_BINOP;
414 Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
415 Record.push_back(VE.getValueID(C->getOperand(0)));
416 Record.push_back(VE.getValueID(C->getOperand(1)));
419 case Instruction::GetElementPtr:
420 Code = bitc::CST_CODE_CE_GEP;
421 Record.push_back(CE->getNumOperands());
422 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
423 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
424 Record.push_back(VE.getValueID(C->getOperand(i)));
427 case Instruction::Select:
428 Code = bitc::CST_CODE_CE_SELECT;
429 Record.push_back(VE.getValueID(C->getOperand(0)));
430 Record.push_back(VE.getValueID(C->getOperand(1)));
431 Record.push_back(VE.getValueID(C->getOperand(2)));
433 case Instruction::ExtractElement:
434 Code = bitc::CST_CODE_CE_EXTRACTELT;
435 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
436 Record.push_back(VE.getValueID(C->getOperand(0)));
437 Record.push_back(VE.getValueID(C->getOperand(1)));
439 case Instruction::InsertElement:
440 Code = bitc::CST_CODE_CE_INSERTELT;
441 Record.push_back(VE.getValueID(C->getOperand(0)));
442 Record.push_back(VE.getValueID(C->getOperand(1)));
443 Record.push_back(VE.getValueID(C->getOperand(2)));
445 case Instruction::ShuffleVector:
446 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
447 Record.push_back(VE.getValueID(C->getOperand(0)));
448 Record.push_back(VE.getValueID(C->getOperand(1)));
449 Record.push_back(VE.getValueID(C->getOperand(2)));
451 case Instruction::ICmp:
452 case Instruction::FCmp:
453 Code = bitc::CST_CODE_CE_CMP;
454 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
455 Record.push_back(VE.getValueID(C->getOperand(0)));
456 Record.push_back(VE.getValueID(C->getOperand(1)));
457 Record.push_back(CE->getPredicate());
461 assert(0 && "Unknown constant!");
463 Stream.EmitRecord(Code, Record, AbbrevToUse);
470 static void WriteModuleConstants(const ValueEnumerator &VE,
471 BitstreamWriter &Stream) {
472 const ValueEnumerator::ValueList &Vals = VE.getValues();
474 // Find the first constant to emit, which is the first non-globalvalue value.
475 // We know globalvalues have been emitted by WriteModuleInfo.
476 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
477 if (!isa<GlobalValue>(Vals[i].first)) {
478 WriteConstants(i, Vals.size(), VE, Stream);
484 /// WriteInstruction - Emit an instruction to the specified stream.
485 static void WriteInstruction(const Instruction &I, ValueEnumerator &VE,
486 BitstreamWriter &Stream,
487 SmallVector<unsigned, 64> &Vals) {
488 return; // FIXME: REMOVE
490 unsigned AbbrevToUse = 0;
491 switch (I.getOpcode()) {
493 if (Instruction::isCast(I.getOpcode())) {
494 Code = bitc::FUNC_CODE_INST_BINOP;
495 Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
496 Vals.push_back(VE.getTypeID(I.getType()));
497 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
498 Vals.push_back(VE.getValueID(I.getOperand(0)));
500 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
501 Code = bitc::CST_CODE_CE_BINOP;
502 Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
503 Vals.push_back(VE.getTypeID(I.getType()));
504 Vals.push_back(VE.getValueID(I.getOperand(0)));
505 Vals.push_back(VE.getValueID(I.getOperand(1)));
510 case Instruction::Unwind:
511 Code = bitc::FUNC_CODE_INST_UNWIND;
513 case Instruction::Unreachable:
514 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
519 Stream.EmitRecord(Code, Vals, AbbrevToUse);
523 /// WriteFunction - Emit a function body to the module stream.
524 static void WriteFunction(const Function &F, ValueEnumerator &VE,
525 BitstreamWriter &Stream) {
526 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 3);
527 VE.incorporateFunction(F);
529 SmallVector<unsigned, 64> Vals;
531 // Emit the number of basic blocks, so the reader can create them ahead of
533 Vals.push_back(VE.getBasicBlocks().size());
534 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
537 // FIXME: Function attributes?
539 // If there are function-local constants, emit them now.
540 unsigned CstStart, CstEnd;
541 VE.getFunctionConstantRange(CstStart, CstEnd);
542 WriteConstants(CstStart, CstEnd, VE, Stream);
544 // Finally, emit all the instructions, in order.
545 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
546 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
547 WriteInstruction(*I, VE, Stream, Vals);
553 /// WriteTypeSymbolTable - Emit a block for the specified type symtab.
554 static void WriteTypeSymbolTable(const TypeSymbolTable &TST,
555 const ValueEnumerator &VE,
556 BitstreamWriter &Stream) {
557 if (TST.empty()) return;
559 Stream.EnterSubblock(bitc::TYPE_SYMTAB_BLOCK_ID, 3);
561 // FIXME: Set up the abbrev, we know how many types there are!
562 // FIXME: We know if the type names can use 7-bit ascii.
564 SmallVector<unsigned, 64> NameVals;
566 for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end();
568 unsigned AbbrevToUse = 0;
570 // TST_ENTRY: [typeid, namelen, namechar x N]
571 NameVals.push_back(VE.getTypeID(TI->second));
573 const std::string &Str = TI->first;
574 NameVals.push_back(Str.size());
575 for (unsigned i = 0, e = Str.size(); i != e; ++i)
576 NameVals.push_back(Str[i]);
578 // Emit the finished record.
579 Stream.EmitRecord(bitc::VST_CODE_ENTRY, NameVals, AbbrevToUse);
586 // Emit names for globals/functions etc.
587 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
588 const ValueEnumerator &VE,
589 BitstreamWriter &Stream) {
590 if (VST.empty()) return;
591 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 3);
593 // FIXME: Set up the abbrev, we know how many values there are!
594 // FIXME: We know if the type names can use 7-bit ascii.
595 SmallVector<unsigned, 64> NameVals;
597 for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
599 unsigned AbbrevToUse = 0;
601 // VST_ENTRY: [valueid, namelen, namechar x N]
602 NameVals.push_back(VE.getValueID(SI->getValue()));
604 NameVals.push_back(SI->getKeyLength());
605 for (const char *P = SI->getKeyData(),
606 *E = SI->getKeyData()+SI->getKeyLength(); P != E; ++P)
607 NameVals.push_back((unsigned char)*P);
609 // Emit the finished record.
610 Stream.EmitRecord(bitc::VST_CODE_ENTRY, NameVals, AbbrevToUse);
617 /// WriteModule - Emit the specified module to the bitstream.
618 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
619 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
621 // Emit the version number if it is non-zero.
623 SmallVector<unsigned, 1> Vals;
624 Vals.push_back(CurVersion);
625 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
628 // Analyze the module, enumerating globals, functions, etc.
629 ValueEnumerator VE(M);
631 // Emit information describing all of the types in the module.
632 WriteTypeTable(VE, Stream);
634 // Emit top-level description of module, including target triple, inline asm,
635 // descriptors for global variables, and function prototype info.
636 WriteModuleInfo(M, VE, Stream);
639 WriteModuleConstants(VE, Stream);
641 // If we have any aggregate values in the value table, purge them - these can
642 // only be used to initialize global variables. Doing so makes the value
643 // namespace smaller for code in functions.
644 int NumNonAggregates = VE.PurgeAggregateValues();
645 if (NumNonAggregates != -1) {
646 SmallVector<unsigned, 1> Vals;
647 Vals.push_back(NumNonAggregates);
648 Stream.EmitRecord(bitc::MODULE_CODE_PURGEVALS, Vals);
651 // Emit function bodies.
652 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
653 if (!I->isDeclaration())
654 WriteFunction(*I, VE, Stream);
656 // Emit the type symbol table information.
657 WriteTypeSymbolTable(M->getTypeSymbolTable(), VE, Stream);
659 // Emit names for globals/functions etc.
660 WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
665 /// WriteBitcodeToFile - Write the specified module to the specified output
667 void llvm::WriteBitcodeToFile(const Module *M, std::ostream &Out) {
668 std::vector<unsigned char> Buffer;
669 BitstreamWriter Stream(Buffer);
671 Buffer.reserve(256*1024);
673 // Emit the file header.
674 Stream.Emit((unsigned)'B', 8);
675 Stream.Emit((unsigned)'C', 8);
682 WriteModule(M, Stream);
684 // Write the generated bitstream to "Out".
685 Out.write((char*)&Buffer.front(), Buffer.size());