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/ParameterAttributes.h"
23 #include "llvm/TypeSymbolTable.h"
24 #include "llvm/ValueSymbolTable.h"
25 #include "llvm/Support/MathExtras.h"
28 static const unsigned CurVersion = 0;
30 static unsigned GetEncodedCastOpcode(unsigned Opcode) {
32 default: assert(0 && "Unknown cast instruction!");
33 case Instruction::Trunc : return bitc::CAST_TRUNC;
34 case Instruction::ZExt : return bitc::CAST_ZEXT;
35 case Instruction::SExt : return bitc::CAST_SEXT;
36 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
37 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
38 case Instruction::UIToFP : return bitc::CAST_UITOFP;
39 case Instruction::SIToFP : return bitc::CAST_SITOFP;
40 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
41 case Instruction::FPExt : return bitc::CAST_FPEXT;
42 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
43 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
44 case Instruction::BitCast : return bitc::CAST_BITCAST;
48 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
50 default: assert(0 && "Unknown binary instruction!");
51 case Instruction::Add: return bitc::BINOP_ADD;
52 case Instruction::Sub: return bitc::BINOP_SUB;
53 case Instruction::Mul: return bitc::BINOP_MUL;
54 case Instruction::UDiv: return bitc::BINOP_UDIV;
55 case Instruction::FDiv:
56 case Instruction::SDiv: return bitc::BINOP_SDIV;
57 case Instruction::URem: return bitc::BINOP_UREM;
58 case Instruction::FRem:
59 case Instruction::SRem: return bitc::BINOP_SREM;
60 case Instruction::Shl: return bitc::BINOP_SHL;
61 case Instruction::LShr: return bitc::BINOP_LSHR;
62 case Instruction::AShr: return bitc::BINOP_ASHR;
63 case Instruction::And: return bitc::BINOP_AND;
64 case Instruction::Or: return bitc::BINOP_OR;
65 case Instruction::Xor: return bitc::BINOP_XOR;
71 static void WriteStringRecord(unsigned Code, const std::string &Str,
72 unsigned AbbrevToUse, BitstreamWriter &Stream) {
73 SmallVector<unsigned, 64> Vals;
75 // Code: [strlen, strchar x N]
76 Vals.push_back(Str.size());
77 for (unsigned i = 0, e = Str.size(); i != e; ++i)
78 Vals.push_back(Str[i]);
80 // Emit the finished record.
81 Stream.EmitRecord(Code, Vals, AbbrevToUse);
84 // Emit information about parameter attributes.
85 static void WriteParamAttrTable(const ValueEnumerator &VE,
86 BitstreamWriter &Stream) {
87 const std::vector<const ParamAttrsList*> &Attrs = VE.getParamAttrs();
88 if (Attrs.empty()) return;
90 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
92 SmallVector<uint64_t, 64> Record;
93 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
94 const ParamAttrsList *A = Attrs[i];
95 for (unsigned op = 0, e = A->size(); op != e; ++op) {
96 Record.push_back(A->getParamIndex(op));
97 Record.push_back(A->getParamAttrsAtIndex(op));
100 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
107 /// WriteTypeTable - Write out the type table for a module.
108 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
109 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
111 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID, 4 /*count from # abbrevs */);
112 SmallVector<uint64_t, 64> TypeVals;
114 // FIXME: Set up abbrevs now that we know the width of the type fields, etc.
116 // Emit an entry count so the reader can reserve space.
117 TypeVals.push_back(TypeList.size());
118 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
121 // Loop over all of the types, emitting each in turn.
122 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
123 const Type *T = TypeList[i].first;
127 switch (T->getTypeID()) {
128 case Type::PackedStructTyID: // FIXME: Delete Type::PackedStructTyID.
129 default: assert(0 && "Unknown type!");
130 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
131 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
132 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
133 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
134 case Type::OpaqueTyID: Code = bitc::TYPE_CODE_OPAQUE; break;
135 case Type::IntegerTyID:
137 Code = bitc::TYPE_CODE_INTEGER;
138 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
140 case Type::PointerTyID:
141 // POINTER: [pointee type]
142 Code = bitc::TYPE_CODE_POINTER;
143 TypeVals.push_back(VE.getTypeID(cast<PointerType>(T)->getElementType()));
146 case Type::FunctionTyID: {
147 const FunctionType *FT = cast<FunctionType>(T);
148 // FUNCTION: [isvararg, attrid, #pararms, paramty x N]
149 Code = bitc::TYPE_CODE_FUNCTION;
150 TypeVals.push_back(FT->isVarArg());
151 TypeVals.push_back(VE.getParamAttrID(FT->getParamAttrs()));
152 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
153 TypeVals.push_back(FT->getNumParams());
154 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
155 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
158 case Type::StructTyID: {
159 const StructType *ST = cast<StructType>(T);
160 // STRUCT: [ispacked, #elts, eltty x N]
161 Code = bitc::TYPE_CODE_STRUCT;
162 TypeVals.push_back(ST->isPacked());
163 TypeVals.push_back(ST->getNumElements());
164 // Output all of the element types...
165 for (StructType::element_iterator I = ST->element_begin(),
166 E = ST->element_end(); I != E; ++I)
167 TypeVals.push_back(VE.getTypeID(*I));
170 case Type::ArrayTyID: {
171 const ArrayType *AT = cast<ArrayType>(T);
172 // ARRAY: [numelts, eltty]
173 Code = bitc::TYPE_CODE_ARRAY;
174 TypeVals.push_back(AT->getNumElements());
175 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
178 case Type::VectorTyID: {
179 const VectorType *VT = cast<VectorType>(T);
180 // VECTOR [numelts, eltty]
181 Code = bitc::TYPE_CODE_VECTOR;
182 TypeVals.push_back(VT->getNumElements());
183 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
188 // Emit the finished record.
189 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
196 static unsigned getEncodedLinkage(const GlobalValue *GV) {
197 switch (GV->getLinkage()) {
198 default: assert(0 && "Invalid linkage!");
199 case GlobalValue::ExternalLinkage: return 0;
200 case GlobalValue::WeakLinkage: return 1;
201 case GlobalValue::AppendingLinkage: return 2;
202 case GlobalValue::InternalLinkage: return 3;
203 case GlobalValue::LinkOnceLinkage: return 4;
204 case GlobalValue::DLLImportLinkage: return 5;
205 case GlobalValue::DLLExportLinkage: return 6;
206 case GlobalValue::ExternalWeakLinkage: return 7;
210 static unsigned getEncodedVisibility(const GlobalValue *GV) {
211 switch (GV->getVisibility()) {
212 default: assert(0 && "Invalid visibility!");
213 case GlobalValue::DefaultVisibility: return 0;
214 case GlobalValue::HiddenVisibility: return 1;
215 case GlobalValue::ProtectedVisibility: return 2;
219 // Emit top-level description of module, including target triple, inline asm,
220 // descriptors for global variables, and function prototype info.
221 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
222 BitstreamWriter &Stream) {
223 // Emit the list of dependent libraries for the Module.
224 for (Module::lib_iterator I = M->lib_begin(), E = M->lib_end(); I != E; ++I)
225 WriteStringRecord(bitc::MODULE_CODE_DEPLIB, *I, 0/*TODO*/, Stream);
227 // Emit various pieces of data attached to a module.
228 if (!M->getTargetTriple().empty())
229 WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
231 if (!M->getDataLayout().empty())
232 WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(),
234 if (!M->getModuleInlineAsm().empty())
235 WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
238 // Emit information about sections, computing how many there are. Also
239 // compute the maximum alignment value.
240 std::map<std::string, unsigned> SectionMap;
241 unsigned MaxAlignment = 0;
242 unsigned MaxGlobalType = 0;
243 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
245 MaxAlignment = std::max(MaxAlignment, GV->getAlignment());
246 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType()));
248 if (!GV->hasSection()) continue;
249 // Give section names unique ID's.
250 unsigned &Entry = SectionMap[GV->getSection()];
251 if (Entry != 0) continue;
252 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(),
254 Entry = SectionMap.size();
256 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
257 MaxAlignment = std::max(MaxAlignment, F->getAlignment());
258 if (!F->hasSection()) continue;
259 // Give section names unique ID's.
260 unsigned &Entry = SectionMap[F->getSection()];
261 if (Entry != 0) continue;
262 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(),
264 Entry = SectionMap.size();
267 // Emit abbrev for globals, now that we know # sections and max alignment.
268 unsigned SimpleGVarAbbrev = 0;
269 if (!M->global_empty()) {
270 // Add an abbrev for common globals with no visibility or thread localness.
271 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
272 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
273 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth,
274 Log2_32_Ceil(MaxGlobalType+1)));
275 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth, 1)); // Constant.
276 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
277 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth, 3)); // Linkage.
278 if (MaxAlignment == 0) // Alignment.
279 Abbv->Add(BitCodeAbbrevOp(0));
281 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
282 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth,
283 Log2_32_Ceil(MaxEncAlignment+1)));
285 if (SectionMap.empty()) // Section.
286 Abbv->Add(BitCodeAbbrevOp(0));
288 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth,
289 Log2_32_Ceil(SectionMap.size()+1)));
290 // Don't bother emitting vis + thread local.
291 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
294 // Emit the global variable information.
295 SmallVector<unsigned, 64> Vals;
296 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
298 unsigned AbbrevToUse = 0;
300 // GLOBALVAR: [type, isconst, initid,
301 // linkage, alignment, section, visibility, threadlocal]
302 Vals.push_back(VE.getTypeID(GV->getType()));
303 Vals.push_back(GV->isConstant());
304 Vals.push_back(GV->isDeclaration() ? 0 :
305 (VE.getValueID(GV->getInitializer()) + 1));
306 Vals.push_back(getEncodedLinkage(GV));
307 Vals.push_back(Log2_32(GV->getAlignment())+1);
308 Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0);
309 if (GV->isThreadLocal() ||
310 GV->getVisibility() != GlobalValue::DefaultVisibility) {
311 Vals.push_back(getEncodedVisibility(GV));
312 Vals.push_back(GV->isThreadLocal());
314 AbbrevToUse = SimpleGVarAbbrev;
317 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
321 // Emit the function proto information.
322 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
323 // FUNCTION: [type, callingconv, isproto, linkage, alignment, section,
325 Vals.push_back(VE.getTypeID(F->getType()));
326 Vals.push_back(F->getCallingConv());
327 Vals.push_back(F->isDeclaration());
328 Vals.push_back(getEncodedLinkage(F));
329 Vals.push_back(Log2_32(F->getAlignment())+1);
330 Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
331 Vals.push_back(getEncodedVisibility(F));
333 unsigned AbbrevToUse = 0;
334 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
339 // Emit the alias information.
340 for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end();
342 Vals.push_back(VE.getTypeID(AI->getType()));
343 Vals.push_back(VE.getValueID(AI->getAliasee()));
344 Vals.push_back(getEncodedLinkage(AI));
345 unsigned AbbrevToUse = 0;
346 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
352 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
353 const ValueEnumerator &VE,
354 BitstreamWriter &Stream) {
355 if (FirstVal == LastVal) return;
357 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 2);
359 // FIXME: Install and use abbrevs to reduce size. Install them globally so
360 // they don't need to be reemitted for each function body.
362 SmallVector<uint64_t, 64> Record;
364 const ValueEnumerator::ValueList &Vals = VE.getValues();
365 const Type *LastTy = 0;
366 for (unsigned i = FirstVal; i != LastVal; ++i) {
367 const Value *V = Vals[i].first;
368 // If we need to switch types, do so now.
369 if (V->getType() != LastTy) {
370 LastTy = V->getType();
371 Record.push_back(VE.getTypeID(LastTy));
372 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record);
376 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
377 assert(0 && IA && "FIXME: Inline asm writing unimp!");
380 const Constant *C = cast<Constant>(V);
382 unsigned AbbrevToUse = 0;
383 if (C->isNullValue()) {
384 Code = bitc::CST_CODE_NULL;
385 } else if (isa<UndefValue>(C)) {
386 Code = bitc::CST_CODE_UNDEF;
387 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
388 if (IV->getBitWidth() <= 64) {
389 int64_t V = IV->getSExtValue();
391 Record.push_back(V << 1);
393 Record.push_back((-V << 1) | 1);
394 Code = bitc::CST_CODE_INTEGER;
395 } else { // Wide integers, > 64 bits in size.
396 // We have an arbitrary precision integer value to write whose
397 // bit width is > 64. However, in canonical unsigned integer
398 // format it is likely that the high bits are going to be zero.
399 // So, we only write the number of active words.
400 unsigned NWords = IV->getValue().getActiveWords();
401 const uint64_t *RawWords = IV->getValue().getRawData();
402 Record.push_back(NWords);
403 for (unsigned i = 0; i != NWords; ++i) {
404 int64_t V = RawWords[i];
406 Record.push_back(V << 1);
408 Record.push_back((-V << 1) | 1);
410 Code = bitc::CST_CODE_WIDE_INTEGER;
412 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
413 Code = bitc::CST_CODE_FLOAT;
414 if (CFP->getType() == Type::FloatTy) {
415 Record.push_back(FloatToBits((float)CFP->getValue()));
417 assert (CFP->getType() == Type::DoubleTy && "Unknown FP type!");
418 Record.push_back(DoubleToBits((double)CFP->getValue()));
420 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(V) ||
421 isa<ConstantVector>(V)) {
422 Code = bitc::CST_CODE_AGGREGATE;
423 Record.push_back(C->getNumOperands());
424 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
425 Record.push_back(VE.getValueID(C->getOperand(i)));
426 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
427 switch (CE->getOpcode()) {
429 if (Instruction::isCast(CE->getOpcode())) {
430 Code = bitc::CST_CODE_CE_CAST;
431 Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
432 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
433 Record.push_back(VE.getValueID(C->getOperand(0)));
435 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
436 Code = bitc::CST_CODE_CE_BINOP;
437 Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
438 Record.push_back(VE.getValueID(C->getOperand(0)));
439 Record.push_back(VE.getValueID(C->getOperand(1)));
442 case Instruction::GetElementPtr:
443 Code = bitc::CST_CODE_CE_GEP;
444 Record.push_back(CE->getNumOperands());
445 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
446 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
447 Record.push_back(VE.getValueID(C->getOperand(i)));
450 case Instruction::Select:
451 Code = bitc::CST_CODE_CE_SELECT;
452 Record.push_back(VE.getValueID(C->getOperand(0)));
453 Record.push_back(VE.getValueID(C->getOperand(1)));
454 Record.push_back(VE.getValueID(C->getOperand(2)));
456 case Instruction::ExtractElement:
457 Code = bitc::CST_CODE_CE_EXTRACTELT;
458 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
459 Record.push_back(VE.getValueID(C->getOperand(0)));
460 Record.push_back(VE.getValueID(C->getOperand(1)));
462 case Instruction::InsertElement:
463 Code = bitc::CST_CODE_CE_INSERTELT;
464 Record.push_back(VE.getValueID(C->getOperand(0)));
465 Record.push_back(VE.getValueID(C->getOperand(1)));
466 Record.push_back(VE.getValueID(C->getOperand(2)));
468 case Instruction::ShuffleVector:
469 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
470 Record.push_back(VE.getValueID(C->getOperand(0)));
471 Record.push_back(VE.getValueID(C->getOperand(1)));
472 Record.push_back(VE.getValueID(C->getOperand(2)));
474 case Instruction::ICmp:
475 case Instruction::FCmp:
476 Code = bitc::CST_CODE_CE_CMP;
477 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
478 Record.push_back(VE.getValueID(C->getOperand(0)));
479 Record.push_back(VE.getValueID(C->getOperand(1)));
480 Record.push_back(CE->getPredicate());
484 assert(0 && "Unknown constant!");
486 Stream.EmitRecord(Code, Record, AbbrevToUse);
493 static void WriteModuleConstants(const ValueEnumerator &VE,
494 BitstreamWriter &Stream) {
495 const ValueEnumerator::ValueList &Vals = VE.getValues();
497 // Find the first constant to emit, which is the first non-globalvalue value.
498 // We know globalvalues have been emitted by WriteModuleInfo.
499 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
500 if (!isa<GlobalValue>(Vals[i].first)) {
501 WriteConstants(i, Vals.size(), VE, Stream);
507 /// WriteInstruction - Emit an instruction to the specified stream.
508 static void WriteInstruction(const Instruction &I, ValueEnumerator &VE,
509 BitstreamWriter &Stream,
510 SmallVector<unsigned, 64> &Vals) {
512 unsigned AbbrevToUse = 0;
513 switch (I.getOpcode()) {
515 if (Instruction::isCast(I.getOpcode())) {
516 Code = bitc::FUNC_CODE_INST_CAST;
517 Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
518 Vals.push_back(VE.getTypeID(I.getType()));
519 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
520 Vals.push_back(VE.getValueID(I.getOperand(0)));
522 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
523 Code = bitc::FUNC_CODE_INST_BINOP;
524 Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
525 Vals.push_back(VE.getTypeID(I.getType()));
526 Vals.push_back(VE.getValueID(I.getOperand(0)));
527 Vals.push_back(VE.getValueID(I.getOperand(1)));
531 case Instruction::GetElementPtr:
532 Code = bitc::FUNC_CODE_INST_GEP;
533 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
534 Vals.push_back(VE.getTypeID(I.getOperand(i)->getType()));
535 Vals.push_back(VE.getValueID(I.getOperand(i)));
538 case Instruction::Select:
539 Code = bitc::FUNC_CODE_INST_SELECT;
540 Vals.push_back(VE.getTypeID(I.getType()));
541 Vals.push_back(VE.getValueID(I.getOperand(0)));
542 Vals.push_back(VE.getValueID(I.getOperand(1)));
543 Vals.push_back(VE.getValueID(I.getOperand(2)));
545 case Instruction::ExtractElement:
546 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
547 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
548 Vals.push_back(VE.getValueID(I.getOperand(0)));
549 Vals.push_back(VE.getValueID(I.getOperand(1)));
551 case Instruction::InsertElement:
552 Code = bitc::FUNC_CODE_INST_INSERTELT;
553 Vals.push_back(VE.getTypeID(I.getType()));
554 Vals.push_back(VE.getValueID(I.getOperand(0)));
555 Vals.push_back(VE.getValueID(I.getOperand(1)));
556 Vals.push_back(VE.getValueID(I.getOperand(2)));
558 case Instruction::ShuffleVector:
559 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
560 Vals.push_back(VE.getTypeID(I.getType()));
561 Vals.push_back(VE.getValueID(I.getOperand(0)));
562 Vals.push_back(VE.getValueID(I.getOperand(1)));
563 Vals.push_back(VE.getValueID(I.getOperand(2)));
565 case Instruction::ICmp:
566 case Instruction::FCmp:
567 Code = bitc::FUNC_CODE_INST_CMP;
568 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
569 Vals.push_back(VE.getValueID(I.getOperand(0)));
570 Vals.push_back(VE.getValueID(I.getOperand(1)));
571 Vals.push_back(cast<CmpInst>(I).getPredicate());
574 case Instruction::Ret:
575 Code = bitc::FUNC_CODE_INST_RET;
576 if (I.getNumOperands()) {
577 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
578 Vals.push_back(VE.getValueID(I.getOperand(0)));
581 case Instruction::Br:
582 Code = bitc::FUNC_CODE_INST_BR;
583 Vals.push_back(VE.getValueID(I.getOperand(0)));
584 if (cast<BranchInst>(I).isConditional()) {
585 Vals.push_back(VE.getValueID(I.getOperand(1)));
586 Vals.push_back(VE.getValueID(I.getOperand(2)));
589 case Instruction::Switch:
590 Code = bitc::FUNC_CODE_INST_SWITCH;
591 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
592 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
593 Vals.push_back(VE.getValueID(I.getOperand(i)));
595 case Instruction::Invoke: {
596 Code = bitc::FUNC_CODE_INST_INVOKE;
597 Vals.push_back(cast<InvokeInst>(I).getCallingConv());
598 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
599 Vals.push_back(VE.getValueID(I.getOperand(0))); // callee
600 Vals.push_back(VE.getValueID(I.getOperand(1))); // normal
601 Vals.push_back(VE.getValueID(I.getOperand(2))); // unwind
603 // Emit value #'s for the fixed parameters.
604 const PointerType *PTy = cast<PointerType>(I.getOperand(0)->getType());
605 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
606 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
607 Vals.push_back(VE.getValueID(I.getOperand(i+3))); // fixed param.
609 // Emit type/value pairs for varargs params.
610 if (FTy->isVarArg()) {
611 unsigned NumVarargs = I.getNumOperands()-3-FTy->getNumParams();
612 for (unsigned i = I.getNumOperands()-NumVarargs, e = I.getNumOperands();
614 Vals.push_back(VE.getTypeID(I.getOperand(i)->getType()));
615 Vals.push_back(VE.getValueID(I.getOperand(i)));
620 case Instruction::Unwind:
621 Code = bitc::FUNC_CODE_INST_UNWIND;
623 case Instruction::Unreachable:
624 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
627 case Instruction::PHI:
628 Code = bitc::FUNC_CODE_INST_PHI;
629 Vals.push_back(VE.getTypeID(I.getType()));
630 Vals.push_back(I.getNumOperands());
631 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
632 Vals.push_back(VE.getValueID(I.getOperand(i)));
635 case Instruction::Malloc:
636 Code = bitc::FUNC_CODE_INST_MALLOC;
637 Vals.push_back(VE.getTypeID(I.getType()));
638 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
639 Vals.push_back(Log2_32(cast<MallocInst>(I).getAlignment())+1);
642 case Instruction::Free:
643 Code = bitc::FUNC_CODE_INST_FREE;
644 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
645 Vals.push_back(VE.getValueID(I.getOperand(0)));
648 case Instruction::Alloca:
649 Code = bitc::FUNC_CODE_INST_ALLOCA;
650 Vals.push_back(VE.getTypeID(I.getType()));
651 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
652 Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1);
655 case Instruction::Load:
656 Code = bitc::FUNC_CODE_INST_LOAD;
657 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
658 Vals.push_back(VE.getValueID(I.getOperand(0))); // ptr.
659 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
660 Vals.push_back(cast<LoadInst>(I).isVolatile());
662 case Instruction::Store:
663 Code = bitc::FUNC_CODE_INST_STORE;
664 Vals.push_back(VE.getTypeID(I.getOperand(1)->getType())); // Pointer
665 Vals.push_back(VE.getValueID(I.getOperand(0))); // val.
666 Vals.push_back(VE.getValueID(I.getOperand(1))); // ptr.
667 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
668 Vals.push_back(cast<StoreInst>(I).isVolatile());
670 case Instruction::Call: {
671 Code = bitc::FUNC_CODE_INST_CALL;
672 Vals.push_back((cast<CallInst>(I).getCallingConv() << 1) |
673 cast<CallInst>(I).isTailCall());
674 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
675 Vals.push_back(VE.getValueID(I.getOperand(0))); // callee
677 // Emit value #'s for the fixed parameters.
678 const PointerType *PTy = cast<PointerType>(I.getOperand(0)->getType());
679 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
680 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
681 Vals.push_back(VE.getValueID(I.getOperand(i+1))); // fixed param.
683 // Emit type/value pairs for varargs params.
684 if (FTy->isVarArg()) {
685 unsigned NumVarargs = I.getNumOperands()-1-FTy->getNumParams();
686 for (unsigned i = I.getNumOperands()-NumVarargs, e = I.getNumOperands();
688 Vals.push_back(VE.getTypeID(I.getOperand(i)->getType()));
689 Vals.push_back(VE.getValueID(I.getOperand(i)));
694 case Instruction::VAArg:
695 Code = bitc::FUNC_CODE_INST_VAARG;
696 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
697 Vals.push_back(VE.getValueID(I.getOperand(0))); // valist.
698 Vals.push_back(VE.getTypeID(I.getType())); // restype.
702 Stream.EmitRecord(Code, Vals, AbbrevToUse);
706 // Emit names for globals/functions etc.
707 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
708 const ValueEnumerator &VE,
709 BitstreamWriter &Stream) {
710 if (VST.empty()) return;
711 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 3);
713 // FIXME: Set up the abbrev, we know how many values there are!
714 // FIXME: We know if the type names can use 7-bit ascii.
715 SmallVector<unsigned, 64> NameVals;
717 for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
719 unsigned AbbrevToUse = 0;
721 // VST_ENTRY: [valueid, namelen, namechar x N]
722 // VST_BBENTRY: [bbid, namelen, namechar x N]
724 if (isa<BasicBlock>(SI->getValue())) {
725 Code = bitc::VST_CODE_BBENTRY;
727 Code = bitc::VST_CODE_ENTRY;
730 NameVals.push_back(VE.getValueID(SI->getValue()));
731 NameVals.push_back(SI->getKeyLength());
732 for (const char *P = SI->getKeyData(),
733 *E = SI->getKeyData()+SI->getKeyLength(); P != E; ++P)
734 NameVals.push_back((unsigned char)*P);
736 // Emit the finished record.
737 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
743 /// WriteFunction - Emit a function body to the module stream.
744 static void WriteFunction(const Function &F, ValueEnumerator &VE,
745 BitstreamWriter &Stream) {
746 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 3);
747 VE.incorporateFunction(F);
749 SmallVector<unsigned, 64> Vals;
751 // Emit the number of basic blocks, so the reader can create them ahead of
753 Vals.push_back(VE.getBasicBlocks().size());
754 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
757 // FIXME: Function attributes?
759 // If there are function-local constants, emit them now.
760 unsigned CstStart, CstEnd;
761 VE.getFunctionConstantRange(CstStart, CstEnd);
762 WriteConstants(CstStart, CstEnd, VE, Stream);
764 // Finally, emit all the instructions, in order.
765 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
766 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
767 WriteInstruction(*I, VE, Stream, Vals);
769 // Emit names for all the instructions etc.
770 WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
776 /// WriteTypeSymbolTable - Emit a block for the specified type symtab.
777 static void WriteTypeSymbolTable(const TypeSymbolTable &TST,
778 const ValueEnumerator &VE,
779 BitstreamWriter &Stream) {
780 if (TST.empty()) return;
782 Stream.EnterSubblock(bitc::TYPE_SYMTAB_BLOCK_ID, 3);
784 // FIXME: Set up the abbrev, we know how many types there are!
785 // FIXME: We know if the type names can use 7-bit ascii.
787 SmallVector<unsigned, 64> NameVals;
789 for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end();
791 unsigned AbbrevToUse = 0;
793 // TST_ENTRY: [typeid, namelen, namechar x N]
794 NameVals.push_back(VE.getTypeID(TI->second));
796 const std::string &Str = TI->first;
797 NameVals.push_back(Str.size());
798 for (unsigned i = 0, e = Str.size(); i != e; ++i)
799 NameVals.push_back(Str[i]);
801 // Emit the finished record.
802 Stream.EmitRecord(bitc::VST_CODE_ENTRY, NameVals, AbbrevToUse);
810 /// WriteModule - Emit the specified module to the bitstream.
811 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
812 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
814 // Emit the version number if it is non-zero.
816 SmallVector<unsigned, 1> Vals;
817 Vals.push_back(CurVersion);
818 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
821 // Analyze the module, enumerating globals, functions, etc.
822 ValueEnumerator VE(M);
824 // Emit information about parameter attributes.
825 WriteParamAttrTable(VE, Stream);
827 // Emit information describing all of the types in the module.
828 WriteTypeTable(VE, Stream);
830 // Emit top-level description of module, including target triple, inline asm,
831 // descriptors for global variables, and function prototype info.
832 WriteModuleInfo(M, VE, Stream);
835 WriteModuleConstants(VE, Stream);
837 // If we have any aggregate values in the value table, purge them - these can
838 // only be used to initialize global variables. Doing so makes the value
839 // namespace smaller for code in functions.
840 int NumNonAggregates = VE.PurgeAggregateValues();
841 if (NumNonAggregates != -1) {
842 SmallVector<unsigned, 1> Vals;
843 Vals.push_back(NumNonAggregates);
844 Stream.EmitRecord(bitc::MODULE_CODE_PURGEVALS, Vals);
847 // Emit function bodies.
848 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
849 if (!I->isDeclaration())
850 WriteFunction(*I, VE, Stream);
852 // Emit the type symbol table information.
853 WriteTypeSymbolTable(M->getTypeSymbolTable(), VE, Stream);
855 // Emit names for globals/functions etc.
856 WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
861 // Emit blockinfo, which defines the standard abbreviations etc.
862 static void WriteBlockInfo(BitstreamWriter &Stream) {
863 // We only want to emit block info records for blocks that have multiple
864 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK. Other
865 // blocks can defined their abbrevs inline.
866 Stream.EnterSubblock(bitc::BLOCKINFO_BLOCK_ID, 2);
869 // Configure TYPE_SYMTAB_BLOCK's.
871 // Add an abbrev for VST_ENTRY where the characters each fit in 7 bits.
872 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
873 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
874 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8); // Value ID
875 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth, 3)); // Linkage.
877 xxx = Stream.EmitAbbrev(Abbv);
883 /// WriteBitcodeToFile - Write the specified module to the specified output
885 void llvm::WriteBitcodeToFile(const Module *M, std::ostream &Out) {
886 std::vector<unsigned char> Buffer;
887 BitstreamWriter Stream(Buffer);
889 Buffer.reserve(256*1024);
891 // Emit the file header.
892 Stream.Emit((unsigned)'B', 8);
893 Stream.Emit((unsigned)'C', 8);
899 // Emit blockinfo, which defines the standard abbreviations etc.
900 WriteBlockInfo(Stream);
903 WriteModule(M, Stream);
905 // Write the generated bitstream to "Out".
906 Out.write((char*)&Buffer.front(), Buffer.size());