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: [strchar x N]
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);
83 // Emit information about parameter attributes.
84 static void WriteParamAttrTable(const ValueEnumerator &VE,
85 BitstreamWriter &Stream) {
86 const std::vector<const ParamAttrsList*> &Attrs = VE.getParamAttrs();
87 if (Attrs.empty()) return;
89 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
91 SmallVector<uint64_t, 64> Record;
92 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
93 const ParamAttrsList *A = Attrs[i];
94 for (unsigned op = 0, e = A->size(); op != e; ++op) {
95 Record.push_back(A->getParamIndex(op));
96 Record.push_back(A->getParamAttrsAtIndex(op));
99 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
106 /// WriteTypeTable - Write out the type table for a module.
107 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
108 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
110 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID, 4 /*count from # abbrevs */);
111 SmallVector<uint64_t, 64> TypeVals;
113 // FIXME: Set up abbrevs now that we know the width of the type fields, etc.
115 // Emit an entry count so the reader can reserve space.
116 TypeVals.push_back(TypeList.size());
117 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
120 // Loop over all of the types, emitting each in turn.
121 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
122 const Type *T = TypeList[i].first;
126 switch (T->getTypeID()) {
127 case Type::PackedStructTyID: // FIXME: Delete Type::PackedStructTyID.
128 default: assert(0 && "Unknown type!");
129 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
130 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
131 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
132 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
133 case Type::OpaqueTyID: Code = bitc::TYPE_CODE_OPAQUE; break;
134 case Type::IntegerTyID:
136 Code = bitc::TYPE_CODE_INTEGER;
137 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
139 case Type::PointerTyID:
140 // POINTER: [pointee type]
141 Code = bitc::TYPE_CODE_POINTER;
142 TypeVals.push_back(VE.getTypeID(cast<PointerType>(T)->getElementType()));
145 case Type::FunctionTyID: {
146 const FunctionType *FT = cast<FunctionType>(T);
147 // FUNCTION: [isvararg, attrid, #pararms, paramty x N]
148 Code = bitc::TYPE_CODE_FUNCTION;
149 TypeVals.push_back(FT->isVarArg());
150 TypeVals.push_back(VE.getParamAttrID(FT->getParamAttrs()));
151 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
152 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
153 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
156 case Type::StructTyID: {
157 const StructType *ST = cast<StructType>(T);
158 // STRUCT: [ispacked, #elts, eltty x N]
159 Code = bitc::TYPE_CODE_STRUCT;
160 TypeVals.push_back(ST->isPacked());
161 // Output all of the element types.
162 for (StructType::element_iterator I = ST->element_begin(),
163 E = ST->element_end(); I != E; ++I)
164 TypeVals.push_back(VE.getTypeID(*I));
167 case Type::ArrayTyID: {
168 const ArrayType *AT = cast<ArrayType>(T);
169 // ARRAY: [numelts, eltty]
170 Code = bitc::TYPE_CODE_ARRAY;
171 TypeVals.push_back(AT->getNumElements());
172 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
175 case Type::VectorTyID: {
176 const VectorType *VT = cast<VectorType>(T);
177 // VECTOR [numelts, eltty]
178 Code = bitc::TYPE_CODE_VECTOR;
179 TypeVals.push_back(VT->getNumElements());
180 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
185 // Emit the finished record.
186 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
193 static unsigned getEncodedLinkage(const GlobalValue *GV) {
194 switch (GV->getLinkage()) {
195 default: assert(0 && "Invalid linkage!");
196 case GlobalValue::ExternalLinkage: return 0;
197 case GlobalValue::WeakLinkage: return 1;
198 case GlobalValue::AppendingLinkage: return 2;
199 case GlobalValue::InternalLinkage: return 3;
200 case GlobalValue::LinkOnceLinkage: return 4;
201 case GlobalValue::DLLImportLinkage: return 5;
202 case GlobalValue::DLLExportLinkage: return 6;
203 case GlobalValue::ExternalWeakLinkage: return 7;
207 static unsigned getEncodedVisibility(const GlobalValue *GV) {
208 switch (GV->getVisibility()) {
209 default: assert(0 && "Invalid visibility!");
210 case GlobalValue::DefaultVisibility: return 0;
211 case GlobalValue::HiddenVisibility: return 1;
212 case GlobalValue::ProtectedVisibility: return 2;
216 // Emit top-level description of module, including target triple, inline asm,
217 // descriptors for global variables, and function prototype info.
218 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
219 BitstreamWriter &Stream) {
220 // Emit the list of dependent libraries for the Module.
221 for (Module::lib_iterator I = M->lib_begin(), E = M->lib_end(); I != E; ++I)
222 WriteStringRecord(bitc::MODULE_CODE_DEPLIB, *I, 0/*TODO*/, Stream);
224 // Emit various pieces of data attached to a module.
225 if (!M->getTargetTriple().empty())
226 WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
228 if (!M->getDataLayout().empty())
229 WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(),
231 if (!M->getModuleInlineAsm().empty())
232 WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
235 // Emit information about sections, computing how many there are. Also
236 // compute the maximum alignment value.
237 std::map<std::string, unsigned> SectionMap;
238 unsigned MaxAlignment = 0;
239 unsigned MaxGlobalType = 0;
240 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
242 MaxAlignment = std::max(MaxAlignment, GV->getAlignment());
243 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType()));
245 if (!GV->hasSection()) continue;
246 // Give section names unique ID's.
247 unsigned &Entry = SectionMap[GV->getSection()];
248 if (Entry != 0) continue;
249 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(),
251 Entry = SectionMap.size();
253 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
254 MaxAlignment = std::max(MaxAlignment, F->getAlignment());
255 if (!F->hasSection()) continue;
256 // Give section names unique ID's.
257 unsigned &Entry = SectionMap[F->getSection()];
258 if (Entry != 0) continue;
259 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(),
261 Entry = SectionMap.size();
264 // Emit abbrev for globals, now that we know # sections and max alignment.
265 unsigned SimpleGVarAbbrev = 0;
266 if (!M->global_empty()) {
267 // Add an abbrev for common globals with no visibility or thread localness.
268 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
269 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
270 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
271 Log2_32_Ceil(MaxGlobalType+1)));
272 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Constant.
273 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
274 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Linkage.
275 if (MaxAlignment == 0) // Alignment.
276 Abbv->Add(BitCodeAbbrevOp(0));
278 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
279 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
280 Log2_32_Ceil(MaxEncAlignment+1)));
282 if (SectionMap.empty()) // Section.
283 Abbv->Add(BitCodeAbbrevOp(0));
285 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
286 Log2_32_Ceil(SectionMap.size()+1)));
287 // Don't bother emitting vis + thread local.
288 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
291 // Emit the global variable information.
292 SmallVector<unsigned, 64> Vals;
293 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
295 unsigned AbbrevToUse = 0;
297 // GLOBALVAR: [type, isconst, initid,
298 // linkage, alignment, section, visibility, threadlocal]
299 Vals.push_back(VE.getTypeID(GV->getType()));
300 Vals.push_back(GV->isConstant());
301 Vals.push_back(GV->isDeclaration() ? 0 :
302 (VE.getValueID(GV->getInitializer()) + 1));
303 Vals.push_back(getEncodedLinkage(GV));
304 Vals.push_back(Log2_32(GV->getAlignment())+1);
305 Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0);
306 if (GV->isThreadLocal() ||
307 GV->getVisibility() != GlobalValue::DefaultVisibility) {
308 Vals.push_back(getEncodedVisibility(GV));
309 Vals.push_back(GV->isThreadLocal());
311 AbbrevToUse = SimpleGVarAbbrev;
314 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
318 // Emit the function proto information.
319 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
320 // FUNCTION: [type, callingconv, isproto, linkage, alignment, section,
322 Vals.push_back(VE.getTypeID(F->getType()));
323 Vals.push_back(F->getCallingConv());
324 Vals.push_back(F->isDeclaration());
325 Vals.push_back(getEncodedLinkage(F));
326 Vals.push_back(Log2_32(F->getAlignment())+1);
327 Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
328 Vals.push_back(getEncodedVisibility(F));
330 unsigned AbbrevToUse = 0;
331 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
336 // Emit the alias information.
337 for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end();
339 Vals.push_back(VE.getTypeID(AI->getType()));
340 Vals.push_back(VE.getValueID(AI->getAliasee()));
341 Vals.push_back(getEncodedLinkage(AI));
342 unsigned AbbrevToUse = 0;
343 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
349 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
350 const ValueEnumerator &VE,
351 BitstreamWriter &Stream) {
352 if (FirstVal == LastVal) return;
354 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 2);
356 // FIXME: Install and use abbrevs to reduce size. Install them globally so
357 // they don't need to be reemitted for each function body.
359 SmallVector<uint64_t, 64> Record;
361 const ValueEnumerator::ValueList &Vals = VE.getValues();
362 const Type *LastTy = 0;
363 for (unsigned i = FirstVal; i != LastVal; ++i) {
364 const Value *V = Vals[i].first;
365 // If we need to switch types, do so now.
366 if (V->getType() != LastTy) {
367 LastTy = V->getType();
368 Record.push_back(VE.getTypeID(LastTy));
369 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record);
373 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
374 assert(0 && IA && "FIXME: Inline asm writing unimp!");
377 const Constant *C = cast<Constant>(V);
379 unsigned AbbrevToUse = 0;
380 if (C->isNullValue()) {
381 Code = bitc::CST_CODE_NULL;
382 } else if (isa<UndefValue>(C)) {
383 Code = bitc::CST_CODE_UNDEF;
384 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
385 if (IV->getBitWidth() <= 64) {
386 int64_t V = IV->getSExtValue();
388 Record.push_back(V << 1);
390 Record.push_back((-V << 1) | 1);
391 Code = bitc::CST_CODE_INTEGER;
392 } else { // Wide integers, > 64 bits in size.
393 // We have an arbitrary precision integer value to write whose
394 // bit width is > 64. However, in canonical unsigned integer
395 // format it is likely that the high bits are going to be zero.
396 // So, we only write the number of active words.
397 unsigned NWords = IV->getValue().getActiveWords();
398 const uint64_t *RawWords = IV->getValue().getRawData();
399 for (unsigned i = 0; i != NWords; ++i) {
400 int64_t V = RawWords[i];
402 Record.push_back(V << 1);
404 Record.push_back((-V << 1) | 1);
406 Code = bitc::CST_CODE_WIDE_INTEGER;
408 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
409 Code = bitc::CST_CODE_FLOAT;
410 if (CFP->getType() == Type::FloatTy) {
411 Record.push_back(FloatToBits((float)CFP->getValue()));
413 assert (CFP->getType() == Type::DoubleTy && "Unknown FP type!");
414 Record.push_back(DoubleToBits((double)CFP->getValue()));
416 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(V) ||
417 isa<ConstantVector>(V)) {
418 Code = bitc::CST_CODE_AGGREGATE;
419 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
420 Record.push_back(VE.getValueID(C->getOperand(i)));
421 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
422 switch (CE->getOpcode()) {
424 if (Instruction::isCast(CE->getOpcode())) {
425 Code = bitc::CST_CODE_CE_CAST;
426 Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
427 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
428 Record.push_back(VE.getValueID(C->getOperand(0)));
430 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
431 Code = bitc::CST_CODE_CE_BINOP;
432 Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
433 Record.push_back(VE.getValueID(C->getOperand(0)));
434 Record.push_back(VE.getValueID(C->getOperand(1)));
437 case Instruction::GetElementPtr:
438 Code = bitc::CST_CODE_CE_GEP;
439 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
440 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
441 Record.push_back(VE.getValueID(C->getOperand(i)));
444 case Instruction::Select:
445 Code = bitc::CST_CODE_CE_SELECT;
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::ExtractElement:
451 Code = bitc::CST_CODE_CE_EXTRACTELT;
452 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
453 Record.push_back(VE.getValueID(C->getOperand(0)));
454 Record.push_back(VE.getValueID(C->getOperand(1)));
456 case Instruction::InsertElement:
457 Code = bitc::CST_CODE_CE_INSERTELT;
458 Record.push_back(VE.getValueID(C->getOperand(0)));
459 Record.push_back(VE.getValueID(C->getOperand(1)));
460 Record.push_back(VE.getValueID(C->getOperand(2)));
462 case Instruction::ShuffleVector:
463 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
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::ICmp:
469 case Instruction::FCmp:
470 Code = bitc::CST_CODE_CE_CMP;
471 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
472 Record.push_back(VE.getValueID(C->getOperand(0)));
473 Record.push_back(VE.getValueID(C->getOperand(1)));
474 Record.push_back(CE->getPredicate());
478 assert(0 && "Unknown constant!");
480 Stream.EmitRecord(Code, Record, AbbrevToUse);
487 static void WriteModuleConstants(const ValueEnumerator &VE,
488 BitstreamWriter &Stream) {
489 const ValueEnumerator::ValueList &Vals = VE.getValues();
491 // Find the first constant to emit, which is the first non-globalvalue value.
492 // We know globalvalues have been emitted by WriteModuleInfo.
493 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
494 if (!isa<GlobalValue>(Vals[i].first)) {
495 WriteConstants(i, Vals.size(), VE, Stream);
501 /// WriteInstruction - Emit an instruction to the specified stream.
502 static void WriteInstruction(const Instruction &I, ValueEnumerator &VE,
503 BitstreamWriter &Stream,
504 SmallVector<unsigned, 64> &Vals) {
506 unsigned AbbrevToUse = 0;
507 switch (I.getOpcode()) {
509 if (Instruction::isCast(I.getOpcode())) {
510 Code = bitc::FUNC_CODE_INST_CAST;
511 Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
512 Vals.push_back(VE.getTypeID(I.getType()));
513 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
514 Vals.push_back(VE.getValueID(I.getOperand(0)));
516 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
517 Code = bitc::FUNC_CODE_INST_BINOP;
518 Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
519 Vals.push_back(VE.getTypeID(I.getType()));
520 Vals.push_back(VE.getValueID(I.getOperand(0)));
521 Vals.push_back(VE.getValueID(I.getOperand(1)));
525 case Instruction::GetElementPtr:
526 Code = bitc::FUNC_CODE_INST_GEP;
527 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
528 Vals.push_back(VE.getTypeID(I.getOperand(i)->getType()));
529 Vals.push_back(VE.getValueID(I.getOperand(i)));
532 case Instruction::Select:
533 Code = bitc::FUNC_CODE_INST_SELECT;
534 Vals.push_back(VE.getTypeID(I.getType()));
535 Vals.push_back(VE.getValueID(I.getOperand(0)));
536 Vals.push_back(VE.getValueID(I.getOperand(1)));
537 Vals.push_back(VE.getValueID(I.getOperand(2)));
539 case Instruction::ExtractElement:
540 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
541 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
542 Vals.push_back(VE.getValueID(I.getOperand(0)));
543 Vals.push_back(VE.getValueID(I.getOperand(1)));
545 case Instruction::InsertElement:
546 Code = bitc::FUNC_CODE_INST_INSERTELT;
547 Vals.push_back(VE.getTypeID(I.getType()));
548 Vals.push_back(VE.getValueID(I.getOperand(0)));
549 Vals.push_back(VE.getValueID(I.getOperand(1)));
550 Vals.push_back(VE.getValueID(I.getOperand(2)));
552 case Instruction::ShuffleVector:
553 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
554 Vals.push_back(VE.getTypeID(I.getType()));
555 Vals.push_back(VE.getValueID(I.getOperand(0)));
556 Vals.push_back(VE.getValueID(I.getOperand(1)));
557 Vals.push_back(VE.getValueID(I.getOperand(2)));
559 case Instruction::ICmp:
560 case Instruction::FCmp:
561 Code = bitc::FUNC_CODE_INST_CMP;
562 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
563 Vals.push_back(VE.getValueID(I.getOperand(0)));
564 Vals.push_back(VE.getValueID(I.getOperand(1)));
565 Vals.push_back(cast<CmpInst>(I).getPredicate());
568 case Instruction::Ret:
569 Code = bitc::FUNC_CODE_INST_RET;
570 if (I.getNumOperands()) {
571 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
572 Vals.push_back(VE.getValueID(I.getOperand(0)));
575 case Instruction::Br:
576 Code = bitc::FUNC_CODE_INST_BR;
577 Vals.push_back(VE.getValueID(I.getOperand(0)));
578 if (cast<BranchInst>(I).isConditional()) {
579 Vals.push_back(VE.getValueID(I.getOperand(1)));
580 Vals.push_back(VE.getValueID(I.getOperand(2)));
583 case Instruction::Switch:
584 Code = bitc::FUNC_CODE_INST_SWITCH;
585 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
586 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
587 Vals.push_back(VE.getValueID(I.getOperand(i)));
589 case Instruction::Invoke: {
590 Code = bitc::FUNC_CODE_INST_INVOKE;
591 Vals.push_back(cast<InvokeInst>(I).getCallingConv());
592 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
593 Vals.push_back(VE.getValueID(I.getOperand(0))); // callee
594 Vals.push_back(VE.getValueID(I.getOperand(1))); // normal
595 Vals.push_back(VE.getValueID(I.getOperand(2))); // unwind
597 // Emit value #'s for the fixed parameters.
598 const PointerType *PTy = cast<PointerType>(I.getOperand(0)->getType());
599 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
600 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
601 Vals.push_back(VE.getValueID(I.getOperand(i+3))); // fixed param.
603 // Emit type/value pairs for varargs params.
604 if (FTy->isVarArg()) {
605 unsigned NumVarargs = I.getNumOperands()-3-FTy->getNumParams();
606 for (unsigned i = I.getNumOperands()-NumVarargs, e = I.getNumOperands();
608 Vals.push_back(VE.getTypeID(I.getOperand(i)->getType()));
609 Vals.push_back(VE.getValueID(I.getOperand(i)));
614 case Instruction::Unwind:
615 Code = bitc::FUNC_CODE_INST_UNWIND;
617 case Instruction::Unreachable:
618 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
621 case Instruction::PHI:
622 Code = bitc::FUNC_CODE_INST_PHI;
623 Vals.push_back(VE.getTypeID(I.getType()));
624 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
625 Vals.push_back(VE.getValueID(I.getOperand(i)));
628 case Instruction::Malloc:
629 Code = bitc::FUNC_CODE_INST_MALLOC;
630 Vals.push_back(VE.getTypeID(I.getType()));
631 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
632 Vals.push_back(Log2_32(cast<MallocInst>(I).getAlignment())+1);
635 case Instruction::Free:
636 Code = bitc::FUNC_CODE_INST_FREE;
637 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
638 Vals.push_back(VE.getValueID(I.getOperand(0)));
641 case Instruction::Alloca:
642 Code = bitc::FUNC_CODE_INST_ALLOCA;
643 Vals.push_back(VE.getTypeID(I.getType()));
644 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
645 Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1);
648 case Instruction::Load:
649 Code = bitc::FUNC_CODE_INST_LOAD;
650 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
651 Vals.push_back(VE.getValueID(I.getOperand(0))); // ptr.
652 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
653 Vals.push_back(cast<LoadInst>(I).isVolatile());
655 case Instruction::Store:
656 Code = bitc::FUNC_CODE_INST_STORE;
657 Vals.push_back(VE.getTypeID(I.getOperand(1)->getType())); // Pointer
658 Vals.push_back(VE.getValueID(I.getOperand(0))); // val.
659 Vals.push_back(VE.getValueID(I.getOperand(1))); // ptr.
660 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
661 Vals.push_back(cast<StoreInst>(I).isVolatile());
663 case Instruction::Call: {
664 Code = bitc::FUNC_CODE_INST_CALL;
665 Vals.push_back((cast<CallInst>(I).getCallingConv() << 1) |
666 cast<CallInst>(I).isTailCall());
667 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
668 Vals.push_back(VE.getValueID(I.getOperand(0))); // callee
670 // Emit value #'s for the fixed parameters.
671 const PointerType *PTy = cast<PointerType>(I.getOperand(0)->getType());
672 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
673 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
674 Vals.push_back(VE.getValueID(I.getOperand(i+1))); // fixed param.
676 // Emit type/value pairs for varargs params.
677 if (FTy->isVarArg()) {
678 unsigned NumVarargs = I.getNumOperands()-1-FTy->getNumParams();
679 for (unsigned i = I.getNumOperands()-NumVarargs, e = I.getNumOperands();
681 Vals.push_back(VE.getTypeID(I.getOperand(i)->getType()));
682 Vals.push_back(VE.getValueID(I.getOperand(i)));
687 case Instruction::VAArg:
688 Code = bitc::FUNC_CODE_INST_VAARG;
689 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
690 Vals.push_back(VE.getValueID(I.getOperand(0))); // valist.
691 Vals.push_back(VE.getTypeID(I.getType())); // restype.
695 Stream.EmitRecord(Code, Vals, AbbrevToUse);
699 // Emit names for globals/functions etc.
700 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
701 const ValueEnumerator &VE,
702 BitstreamWriter &Stream) {
703 if (VST.empty()) return;
704 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 3);
706 // 8-bit fixed width VST_ENTRY strings.
707 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
708 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
709 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
710 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
711 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
712 unsigned AbbrevID = Stream.EmitAbbrev(Abbv);
715 // FIXME: Set up the abbrev, we know how many values there are!
716 // FIXME: We know if the type names can use 7-bit ascii.
717 SmallVector<unsigned, 64> NameVals;
719 for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
721 unsigned AbbrevToUse = 0;
723 // VST_ENTRY: [valueid, namelen, namechar x N]
724 // VST_BBENTRY: [bbid, namelen, namechar x N]
726 if (isa<BasicBlock>(SI->getValue())) {
727 Code = bitc::VST_CODE_BBENTRY;
729 Code = bitc::VST_CODE_ENTRY;
730 AbbrevToUse = AbbrevID;
733 NameVals.push_back(VE.getValueID(SI->getValue()));
734 for (const char *P = SI->getKeyData(),
735 *E = SI->getKeyData()+SI->getKeyLength(); P != E; ++P)
736 NameVals.push_back((unsigned char)*P);
738 // Emit the finished record.
739 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
745 /// WriteFunction - Emit a function body to the module stream.
746 static void WriteFunction(const Function &F, ValueEnumerator &VE,
747 BitstreamWriter &Stream) {
748 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 3);
749 VE.incorporateFunction(F);
751 SmallVector<unsigned, 64> Vals;
753 // Emit the number of basic blocks, so the reader can create them ahead of
755 Vals.push_back(VE.getBasicBlocks().size());
756 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
759 // FIXME: Function attributes?
761 // If there are function-local constants, emit them now.
762 unsigned CstStart, CstEnd;
763 VE.getFunctionConstantRange(CstStart, CstEnd);
764 WriteConstants(CstStart, CstEnd, VE, Stream);
766 // Finally, emit all the instructions, in order.
767 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
768 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
769 WriteInstruction(*I, VE, Stream, Vals);
771 // Emit names for all the instructions etc.
772 WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
778 /// WriteTypeSymbolTable - Emit a block for the specified type symtab.
779 static void WriteTypeSymbolTable(const TypeSymbolTable &TST,
780 const ValueEnumerator &VE,
781 BitstreamWriter &Stream) {
782 if (TST.empty()) return;
784 Stream.EnterSubblock(bitc::TYPE_SYMTAB_BLOCK_ID, 3);
786 // FIXME: Set up the abbrev, we know how many types there are!
787 // FIXME: We know if the type names can use 7-bit ascii.
789 SmallVector<unsigned, 64> NameVals;
791 for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end();
793 unsigned AbbrevToUse = 0;
795 // TST_ENTRY: [typeid, namelen, namechar x N]
796 NameVals.push_back(VE.getTypeID(TI->second));
798 const std::string &Str = TI->first;
799 for (unsigned i = 0, e = Str.size(); i != e; ++i)
800 NameVals.push_back(Str[i]);
802 // Emit the finished record.
803 Stream.EmitRecord(bitc::VST_CODE_ENTRY, NameVals, AbbrevToUse);
811 /// WriteModule - Emit the specified module to the bitstream.
812 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
813 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
815 // Emit the version number if it is non-zero.
817 SmallVector<unsigned, 1> Vals;
818 Vals.push_back(CurVersion);
819 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
822 // Analyze the module, enumerating globals, functions, etc.
823 ValueEnumerator VE(M);
825 // Emit information about parameter attributes.
826 WriteParamAttrTable(VE, Stream);
828 // Emit information describing all of the types in the module.
829 WriteTypeTable(VE, Stream);
831 // Emit top-level description of module, including target triple, inline asm,
832 // descriptors for global variables, and function prototype info.
833 WriteModuleInfo(M, VE, Stream);
836 WriteModuleConstants(VE, Stream);
838 // If we have any aggregate values in the value table, purge them - these can
839 // only be used to initialize global variables. Doing so makes the value
840 // namespace smaller for code in functions.
841 int NumNonAggregates = VE.PurgeAggregateValues();
842 if (NumNonAggregates != -1) {
843 SmallVector<unsigned, 1> Vals;
844 Vals.push_back(NumNonAggregates);
845 Stream.EmitRecord(bitc::MODULE_CODE_PURGEVALS, Vals);
848 // Emit function bodies.
849 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
850 if (!I->isDeclaration())
851 WriteFunction(*I, VE, Stream);
853 // Emit the type symbol table information.
854 WriteTypeSymbolTable(M->getTypeSymbolTable(), VE, Stream);
856 // Emit names for globals/functions etc.
857 WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
862 // Emit blockinfo, which defines the standard abbreviations etc.
863 static void WriteBlockInfo(BitstreamWriter &Stream) {
864 // We only want to emit block info records for blocks that have multiple
865 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK. Other
866 // blocks can defined their abbrevs inline.
867 Stream.EnterSubblock(bitc::BLOCKINFO_BLOCK_ID, 2);
870 // Configure TYPE_SYMTAB_BLOCK's.
872 // Add an abbrev for VST_ENTRY where the characters each fit in 7 bits.
873 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
874 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
875 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8); // Value ID
876 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Linkage.
878 xxx = Stream.EmitAbbrev(Abbv);
884 /// WriteBitcodeToFile - Write the specified module to the specified output
886 void llvm::WriteBitcodeToFile(const Module *M, std::ostream &Out) {
887 std::vector<unsigned char> Buffer;
888 BitstreamWriter Stream(Buffer);
890 Buffer.reserve(256*1024);
892 // Emit the file header.
893 Stream.Emit((unsigned)'B', 8);
894 Stream.Emit((unsigned)'C', 8);
900 // Emit blockinfo, which defines the standard abbreviations etc.
901 WriteBlockInfo(Stream);
904 WriteModule(M, Stream);
906 // Write the generated bitstream to "Out".
907 Out.write((char*)&Buffer.front(), Buffer.size());