1 //===--- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Bitcode writer implementation.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Bitcode/ReaderWriter.h"
15 #include "llvm/Bitcode/BitstreamWriter.h"
16 #include "llvm/Bitcode/LLVMBitCodes.h"
17 #include "ValueEnumerator.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/InlineAsm.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/Module.h"
23 #include "llvm/TypeSymbolTable.h"
24 #include "llvm/ValueSymbolTable.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/System/Program.h"
29 /// These are manifest constants used by the bitcode writer. They do not need to
30 /// be kept in sync with the reader, but need to be consistent within this file.
34 // VALUE_SYMTAB_BLOCK abbrev id's.
35 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
40 // CONSTANTS_BLOCK abbrev id's.
41 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
42 CONSTANTS_INTEGER_ABBREV,
43 CONSTANTS_CE_CAST_Abbrev,
44 CONSTANTS_NULL_Abbrev,
46 // FUNCTION_BLOCK abbrev id's.
47 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
48 FUNCTION_INST_BINOP_ABBREV,
49 FUNCTION_INST_CAST_ABBREV,
50 FUNCTION_INST_RET_VOID_ABBREV,
51 FUNCTION_INST_RET_VAL_ABBREV,
52 FUNCTION_INST_UNREACHABLE_ABBREV
56 static unsigned GetEncodedCastOpcode(unsigned Opcode) {
58 default: assert(0 && "Unknown cast instruction!");
59 case Instruction::Trunc : return bitc::CAST_TRUNC;
60 case Instruction::ZExt : return bitc::CAST_ZEXT;
61 case Instruction::SExt : return bitc::CAST_SEXT;
62 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
63 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
64 case Instruction::UIToFP : return bitc::CAST_UITOFP;
65 case Instruction::SIToFP : return bitc::CAST_SITOFP;
66 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
67 case Instruction::FPExt : return bitc::CAST_FPEXT;
68 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
69 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
70 case Instruction::BitCast : return bitc::CAST_BITCAST;
74 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
76 default: assert(0 && "Unknown binary instruction!");
77 case Instruction::Add: return bitc::BINOP_ADD;
78 case Instruction::Sub: return bitc::BINOP_SUB;
79 case Instruction::Mul: return bitc::BINOP_MUL;
80 case Instruction::UDiv: return bitc::BINOP_UDIV;
81 case Instruction::FDiv:
82 case Instruction::SDiv: return bitc::BINOP_SDIV;
83 case Instruction::URem: return bitc::BINOP_UREM;
84 case Instruction::FRem:
85 case Instruction::SRem: return bitc::BINOP_SREM;
86 case Instruction::Shl: return bitc::BINOP_SHL;
87 case Instruction::LShr: return bitc::BINOP_LSHR;
88 case Instruction::AShr: return bitc::BINOP_ASHR;
89 case Instruction::And: return bitc::BINOP_AND;
90 case Instruction::Or: return bitc::BINOP_OR;
91 case Instruction::Xor: return bitc::BINOP_XOR;
97 static void WriteStringRecord(unsigned Code, const std::string &Str,
98 unsigned AbbrevToUse, BitstreamWriter &Stream) {
99 SmallVector<unsigned, 64> Vals;
101 // Code: [strchar x N]
102 for (unsigned i = 0, e = Str.size(); i != e; ++i)
103 Vals.push_back(Str[i]);
105 // Emit the finished record.
106 Stream.EmitRecord(Code, Vals, AbbrevToUse);
109 // Emit information about parameter attributes.
110 static void WriteParamAttrTable(const ValueEnumerator &VE,
111 BitstreamWriter &Stream) {
112 const std::vector<PAListPtr> &Attrs = VE.getParamAttrs();
113 if (Attrs.empty()) return;
115 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
117 SmallVector<uint64_t, 64> Record;
118 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
119 const PAListPtr &A = Attrs[i];
120 for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i) {
121 const ParamAttrsWithIndex &PAWI = A.getSlot(i);
122 Record.push_back(PAWI.Index);
123 Record.push_back(PAWI.Attrs);
126 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
133 /// WriteTypeTable - Write out the type table for a module.
134 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
135 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
137 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID, 4 /*count from # abbrevs */);
138 SmallVector<uint64_t, 64> TypeVals;
140 // Abbrev for TYPE_CODE_POINTER.
141 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
142 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
143 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
144 Log2_32_Ceil(VE.getTypes().size()+1)));
145 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
146 unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
148 // Abbrev for TYPE_CODE_FUNCTION.
149 Abbv = new BitCodeAbbrev();
150 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
151 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
152 Abbv->Add(BitCodeAbbrevOp(0)); // FIXME: DEAD value, remove in LLVM 3.0
153 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
154 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
155 Log2_32_Ceil(VE.getTypes().size()+1)));
156 unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
158 // Abbrev for TYPE_CODE_STRUCT.
159 Abbv = new BitCodeAbbrev();
160 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT));
161 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
162 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
163 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
164 Log2_32_Ceil(VE.getTypes().size()+1)));
165 unsigned StructAbbrev = Stream.EmitAbbrev(Abbv);
167 // Abbrev for TYPE_CODE_ARRAY.
168 Abbv = new BitCodeAbbrev();
169 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
170 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
171 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
172 Log2_32_Ceil(VE.getTypes().size()+1)));
173 unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
175 // Emit an entry count so the reader can reserve space.
176 TypeVals.push_back(TypeList.size());
177 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
180 // Loop over all of the types, emitting each in turn.
181 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
182 const Type *T = TypeList[i].first;
186 switch (T->getTypeID()) {
187 default: assert(0 && "Unknown type!");
188 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
189 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
190 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
191 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
192 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
193 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
194 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
195 case Type::OpaqueTyID: Code = bitc::TYPE_CODE_OPAQUE; break;
196 case Type::IntegerTyID:
198 Code = bitc::TYPE_CODE_INTEGER;
199 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
201 case Type::PointerTyID: {
202 const PointerType *PTy = cast<PointerType>(T);
203 // POINTER: [pointee type, address space]
204 Code = bitc::TYPE_CODE_POINTER;
205 TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
206 unsigned AddressSpace = PTy->getAddressSpace();
207 TypeVals.push_back(AddressSpace);
208 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
211 case Type::FunctionTyID: {
212 const FunctionType *FT = cast<FunctionType>(T);
213 // FUNCTION: [isvararg, attrid, retty, paramty x N]
214 Code = bitc::TYPE_CODE_FUNCTION;
215 TypeVals.push_back(FT->isVarArg());
216 TypeVals.push_back(0); // FIXME: DEAD: remove in llvm 3.0
217 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
218 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
219 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
220 AbbrevToUse = FunctionAbbrev;
223 case Type::StructTyID: {
224 const StructType *ST = cast<StructType>(T);
225 // STRUCT: [ispacked, eltty x N]
226 Code = bitc::TYPE_CODE_STRUCT;
227 TypeVals.push_back(ST->isPacked());
228 // Output all of the element types.
229 for (StructType::element_iterator I = ST->element_begin(),
230 E = ST->element_end(); I != E; ++I)
231 TypeVals.push_back(VE.getTypeID(*I));
232 AbbrevToUse = StructAbbrev;
235 case Type::ArrayTyID: {
236 const ArrayType *AT = cast<ArrayType>(T);
237 // ARRAY: [numelts, eltty]
238 Code = bitc::TYPE_CODE_ARRAY;
239 TypeVals.push_back(AT->getNumElements());
240 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
241 AbbrevToUse = ArrayAbbrev;
244 case Type::VectorTyID: {
245 const VectorType *VT = cast<VectorType>(T);
246 // VECTOR [numelts, eltty]
247 Code = bitc::TYPE_CODE_VECTOR;
248 TypeVals.push_back(VT->getNumElements());
249 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
254 // Emit the finished record.
255 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
262 static unsigned getEncodedLinkage(const GlobalValue *GV) {
263 switch (GV->getLinkage()) {
264 default: assert(0 && "Invalid linkage!");
265 case GlobalValue::GhostLinkage: // Map ghost linkage onto external.
266 case GlobalValue::ExternalLinkage: return 0;
267 case GlobalValue::WeakLinkage: return 1;
268 case GlobalValue::AppendingLinkage: return 2;
269 case GlobalValue::InternalLinkage: return 3;
270 case GlobalValue::LinkOnceLinkage: return 4;
271 case GlobalValue::DLLImportLinkage: return 5;
272 case GlobalValue::DLLExportLinkage: return 6;
273 case GlobalValue::ExternalWeakLinkage: return 7;
274 case GlobalValue::CommonLinkage: return 8;
278 static unsigned getEncodedVisibility(const GlobalValue *GV) {
279 switch (GV->getVisibility()) {
280 default: assert(0 && "Invalid visibility!");
281 case GlobalValue::DefaultVisibility: return 0;
282 case GlobalValue::HiddenVisibility: return 1;
283 case GlobalValue::ProtectedVisibility: return 2;
287 // Emit top-level description of module, including target triple, inline asm,
288 // descriptors for global variables, and function prototype info.
289 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
290 BitstreamWriter &Stream) {
291 // Emit the list of dependent libraries for the Module.
292 for (Module::lib_iterator I = M->lib_begin(), E = M->lib_end(); I != E; ++I)
293 WriteStringRecord(bitc::MODULE_CODE_DEPLIB, *I, 0/*TODO*/, Stream);
295 // Emit various pieces of data attached to a module.
296 if (!M->getTargetTriple().empty())
297 WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
299 if (!M->getDataLayout().empty())
300 WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(),
302 if (!M->getModuleInlineAsm().empty())
303 WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
306 // Emit information about sections and GC, computing how many there are. Also
307 // compute the maximum alignment value.
308 std::map<std::string, unsigned> SectionMap;
309 std::map<std::string, unsigned> GCMap;
310 unsigned MaxAlignment = 0;
311 unsigned MaxGlobalType = 0;
312 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
314 MaxAlignment = std::max(MaxAlignment, GV->getAlignment());
315 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType()));
317 if (!GV->hasSection()) continue;
318 // Give section names unique ID's.
319 unsigned &Entry = SectionMap[GV->getSection()];
320 if (Entry != 0) continue;
321 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(),
323 Entry = SectionMap.size();
325 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
326 MaxAlignment = std::max(MaxAlignment, F->getAlignment());
327 if (F->hasSection()) {
328 // Give section names unique ID's.
329 unsigned &Entry = SectionMap[F->getSection()];
331 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(),
333 Entry = SectionMap.size();
337 // Same for GC names.
338 unsigned &Entry = GCMap[F->getGC()];
340 WriteStringRecord(bitc::MODULE_CODE_GCNAME, F->getGC(),
342 Entry = GCMap.size();
347 // Emit abbrev for globals, now that we know # sections and max alignment.
348 unsigned SimpleGVarAbbrev = 0;
349 if (!M->global_empty()) {
350 // Add an abbrev for common globals with no visibility or thread localness.
351 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
352 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
353 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
354 Log2_32_Ceil(MaxGlobalType+1)));
355 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Constant.
356 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
357 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // Linkage.
358 if (MaxAlignment == 0) // Alignment.
359 Abbv->Add(BitCodeAbbrevOp(0));
361 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
362 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
363 Log2_32_Ceil(MaxEncAlignment+1)));
365 if (SectionMap.empty()) // Section.
366 Abbv->Add(BitCodeAbbrevOp(0));
368 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
369 Log2_32_Ceil(SectionMap.size()+1)));
370 // Don't bother emitting vis + thread local.
371 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
374 // Emit the global variable information.
375 SmallVector<unsigned, 64> Vals;
376 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
378 unsigned AbbrevToUse = 0;
380 // GLOBALVAR: [type, isconst, initid,
381 // linkage, alignment, section, visibility, threadlocal]
382 Vals.push_back(VE.getTypeID(GV->getType()));
383 Vals.push_back(GV->isConstant());
384 Vals.push_back(GV->isDeclaration() ? 0 :
385 (VE.getValueID(GV->getInitializer()) + 1));
386 Vals.push_back(getEncodedLinkage(GV));
387 Vals.push_back(Log2_32(GV->getAlignment())+1);
388 Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0);
389 if (GV->isThreadLocal() ||
390 GV->getVisibility() != GlobalValue::DefaultVisibility) {
391 Vals.push_back(getEncodedVisibility(GV));
392 Vals.push_back(GV->isThreadLocal());
394 AbbrevToUse = SimpleGVarAbbrev;
397 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
401 // Emit the function proto information.
402 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
403 // FUNCTION: [type, callingconv, isproto, paramattr,
404 // linkage, alignment, section, visibility, gc]
405 Vals.push_back(VE.getTypeID(F->getType()));
406 Vals.push_back(F->getCallingConv());
407 Vals.push_back(F->isDeclaration());
408 Vals.push_back(getEncodedLinkage(F));
409 Vals.push_back(VE.getParamAttrID(F->getParamAttrs()));
410 Vals.push_back(Log2_32(F->getAlignment())+1);
411 Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
412 Vals.push_back(getEncodedVisibility(F));
413 Vals.push_back(F->hasGC() ? GCMap[F->getGC()] : 0);
415 unsigned AbbrevToUse = 0;
416 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
421 // Emit the alias information.
422 for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end();
424 Vals.push_back(VE.getTypeID(AI->getType()));
425 Vals.push_back(VE.getValueID(AI->getAliasee()));
426 Vals.push_back(getEncodedLinkage(AI));
427 Vals.push_back(getEncodedVisibility(AI));
428 unsigned AbbrevToUse = 0;
429 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
435 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
436 const ValueEnumerator &VE,
437 BitstreamWriter &Stream, bool isGlobal) {
438 if (FirstVal == LastVal) return;
440 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
442 unsigned AggregateAbbrev = 0;
443 unsigned String8Abbrev = 0;
444 unsigned CString7Abbrev = 0;
445 unsigned CString6Abbrev = 0;
446 // If this is a constant pool for the module, emit module-specific abbrevs.
448 // Abbrev for CST_CODE_AGGREGATE.
449 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
450 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
451 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
452 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
453 AggregateAbbrev = Stream.EmitAbbrev(Abbv);
455 // Abbrev for CST_CODE_STRING.
456 Abbv = new BitCodeAbbrev();
457 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
458 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
459 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
460 String8Abbrev = Stream.EmitAbbrev(Abbv);
461 // Abbrev for CST_CODE_CSTRING.
462 Abbv = new BitCodeAbbrev();
463 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
464 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
465 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
466 CString7Abbrev = Stream.EmitAbbrev(Abbv);
467 // Abbrev for CST_CODE_CSTRING.
468 Abbv = new BitCodeAbbrev();
469 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
470 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
471 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
472 CString6Abbrev = Stream.EmitAbbrev(Abbv);
475 SmallVector<uint64_t, 64> Record;
477 const ValueEnumerator::ValueList &Vals = VE.getValues();
478 const Type *LastTy = 0;
479 for (unsigned i = FirstVal; i != LastVal; ++i) {
480 const Value *V = Vals[i].first;
481 // If we need to switch types, do so now.
482 if (V->getType() != LastTy) {
483 LastTy = V->getType();
484 Record.push_back(VE.getTypeID(LastTy));
485 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
486 CONSTANTS_SETTYPE_ABBREV);
490 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
491 Record.push_back(unsigned(IA->hasSideEffects()));
493 // Add the asm string.
494 const std::string &AsmStr = IA->getAsmString();
495 Record.push_back(AsmStr.size());
496 for (unsigned i = 0, e = AsmStr.size(); i != e; ++i)
497 Record.push_back(AsmStr[i]);
499 // Add the constraint string.
500 const std::string &ConstraintStr = IA->getConstraintString();
501 Record.push_back(ConstraintStr.size());
502 for (unsigned i = 0, e = ConstraintStr.size(); i != e; ++i)
503 Record.push_back(ConstraintStr[i]);
504 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
508 const Constant *C = cast<Constant>(V);
510 unsigned AbbrevToUse = 0;
511 if (C->isNullValue()) {
512 Code = bitc::CST_CODE_NULL;
513 } else if (isa<UndefValue>(C)) {
514 Code = bitc::CST_CODE_UNDEF;
515 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
516 if (IV->getBitWidth() <= 64) {
517 int64_t V = IV->getSExtValue();
519 Record.push_back(V << 1);
521 Record.push_back((-V << 1) | 1);
522 Code = bitc::CST_CODE_INTEGER;
523 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
524 } else { // Wide integers, > 64 bits in size.
525 // We have an arbitrary precision integer value to write whose
526 // bit width is > 64. However, in canonical unsigned integer
527 // format it is likely that the high bits are going to be zero.
528 // So, we only write the number of active words.
529 unsigned NWords = IV->getValue().getActiveWords();
530 const uint64_t *RawWords = IV->getValue().getRawData();
531 for (unsigned i = 0; i != NWords; ++i) {
532 int64_t V = RawWords[i];
534 Record.push_back(V << 1);
536 Record.push_back((-V << 1) | 1);
538 Code = bitc::CST_CODE_WIDE_INTEGER;
540 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
541 Code = bitc::CST_CODE_FLOAT;
542 const Type *Ty = CFP->getType();
543 if (Ty == Type::FloatTy || Ty == Type::DoubleTy) {
544 Record.push_back(CFP->getValueAPF().convertToAPInt().getZExtValue());
545 } else if (Ty == Type::X86_FP80Ty) {
546 // api needed to prevent premature destruction
547 APInt api = CFP->getValueAPF().convertToAPInt();
548 const uint64_t *p = api.getRawData();
549 Record.push_back(p[0]);
550 Record.push_back((uint16_t)p[1]);
551 } else if (Ty == Type::FP128Ty || Ty == Type::PPC_FP128Ty) {
552 APInt api = CFP->getValueAPF().convertToAPInt();
553 const uint64_t *p = api.getRawData();
554 Record.push_back(p[0]);
555 Record.push_back(p[1]);
557 assert (0 && "Unknown FP type!");
559 } else if (isa<ConstantArray>(C) && cast<ConstantArray>(C)->isString()) {
560 // Emit constant strings specially.
561 unsigned NumOps = C->getNumOperands();
562 // If this is a null-terminated string, use the denser CSTRING encoding.
563 if (C->getOperand(NumOps-1)->isNullValue()) {
564 Code = bitc::CST_CODE_CSTRING;
565 --NumOps; // Don't encode the null, which isn't allowed by char6.
567 Code = bitc::CST_CODE_STRING;
568 AbbrevToUse = String8Abbrev;
570 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
571 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
572 for (unsigned i = 0; i != NumOps; ++i) {
573 unsigned char V = cast<ConstantInt>(C->getOperand(i))->getZExtValue();
575 isCStr7 &= (V & 128) == 0;
577 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
581 AbbrevToUse = CString6Abbrev;
583 AbbrevToUse = CString7Abbrev;
584 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(V) ||
585 isa<ConstantVector>(V)) {
586 Code = bitc::CST_CODE_AGGREGATE;
587 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
588 Record.push_back(VE.getValueID(C->getOperand(i)));
589 AbbrevToUse = AggregateAbbrev;
590 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
591 switch (CE->getOpcode()) {
593 if (Instruction::isCast(CE->getOpcode())) {
594 Code = bitc::CST_CODE_CE_CAST;
595 Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
596 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
597 Record.push_back(VE.getValueID(C->getOperand(0)));
598 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
600 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
601 Code = bitc::CST_CODE_CE_BINOP;
602 Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
603 Record.push_back(VE.getValueID(C->getOperand(0)));
604 Record.push_back(VE.getValueID(C->getOperand(1)));
607 case Instruction::GetElementPtr:
608 Code = bitc::CST_CODE_CE_GEP;
609 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
610 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
611 Record.push_back(VE.getValueID(C->getOperand(i)));
614 case Instruction::Select:
615 Code = bitc::CST_CODE_CE_SELECT;
616 Record.push_back(VE.getValueID(C->getOperand(0)));
617 Record.push_back(VE.getValueID(C->getOperand(1)));
618 Record.push_back(VE.getValueID(C->getOperand(2)));
620 case Instruction::ExtractElement:
621 Code = bitc::CST_CODE_CE_EXTRACTELT;
622 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
623 Record.push_back(VE.getValueID(C->getOperand(0)));
624 Record.push_back(VE.getValueID(C->getOperand(1)));
626 case Instruction::InsertElement:
627 Code = bitc::CST_CODE_CE_INSERTELT;
628 Record.push_back(VE.getValueID(C->getOperand(0)));
629 Record.push_back(VE.getValueID(C->getOperand(1)));
630 Record.push_back(VE.getValueID(C->getOperand(2)));
632 case Instruction::ShuffleVector:
633 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
634 Record.push_back(VE.getValueID(C->getOperand(0)));
635 Record.push_back(VE.getValueID(C->getOperand(1)));
636 Record.push_back(VE.getValueID(C->getOperand(2)));
638 case Instruction::ICmp:
639 case Instruction::FCmp:
640 case Instruction::VICmp:
641 case Instruction::VFCmp:
642 Code = bitc::CST_CODE_CE_CMP;
643 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
644 Record.push_back(VE.getValueID(C->getOperand(0)));
645 Record.push_back(VE.getValueID(C->getOperand(1)));
646 Record.push_back(CE->getPredicate());
650 assert(0 && "Unknown constant!");
652 Stream.EmitRecord(Code, Record, AbbrevToUse);
659 static void WriteModuleConstants(const ValueEnumerator &VE,
660 BitstreamWriter &Stream) {
661 const ValueEnumerator::ValueList &Vals = VE.getValues();
663 // Find the first constant to emit, which is the first non-globalvalue value.
664 // We know globalvalues have been emitted by WriteModuleInfo.
665 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
666 if (!isa<GlobalValue>(Vals[i].first)) {
667 WriteConstants(i, Vals.size(), VE, Stream, true);
673 /// PushValueAndType - The file has to encode both the value and type id for
674 /// many values, because we need to know what type to create for forward
675 /// references. However, most operands are not forward references, so this type
676 /// field is not needed.
678 /// This function adds V's value ID to Vals. If the value ID is higher than the
679 /// instruction ID, then it is a forward reference, and it also includes the
681 static bool PushValueAndType(Value *V, unsigned InstID,
682 SmallVector<unsigned, 64> &Vals,
683 ValueEnumerator &VE) {
684 unsigned ValID = VE.getValueID(V);
685 Vals.push_back(ValID);
686 if (ValID >= InstID) {
687 Vals.push_back(VE.getTypeID(V->getType()));
693 /// WriteInstruction - Emit an instruction to the specified stream.
694 static void WriteInstruction(const Instruction &I, unsigned InstID,
695 ValueEnumerator &VE, BitstreamWriter &Stream,
696 SmallVector<unsigned, 64> &Vals) {
698 unsigned AbbrevToUse = 0;
699 switch (I.getOpcode()) {
701 if (Instruction::isCast(I.getOpcode())) {
702 Code = bitc::FUNC_CODE_INST_CAST;
703 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
704 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
705 Vals.push_back(VE.getTypeID(I.getType()));
706 Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
708 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
709 Code = bitc::FUNC_CODE_INST_BINOP;
710 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
711 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
712 Vals.push_back(VE.getValueID(I.getOperand(1)));
713 Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
717 case Instruction::GetElementPtr:
718 Code = bitc::FUNC_CODE_INST_GEP;
719 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
720 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
722 case Instruction::ExtractValue: {
723 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
724 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
725 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
726 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
730 case Instruction::InsertValue: {
731 Code = bitc::FUNC_CODE_INST_INSERTVAL;
732 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
733 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
734 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
735 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
739 case Instruction::Select:
740 Code = bitc::FUNC_CODE_INST_SELECT;
741 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
742 Vals.push_back(VE.getValueID(I.getOperand(2)));
743 Vals.push_back(VE.getValueID(I.getOperand(0)));
745 case Instruction::ExtractElement:
746 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
747 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
748 Vals.push_back(VE.getValueID(I.getOperand(1)));
750 case Instruction::InsertElement:
751 Code = bitc::FUNC_CODE_INST_INSERTELT;
752 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
753 Vals.push_back(VE.getValueID(I.getOperand(1)));
754 Vals.push_back(VE.getValueID(I.getOperand(2)));
756 case Instruction::ShuffleVector:
757 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
758 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
759 Vals.push_back(VE.getValueID(I.getOperand(1)));
760 Vals.push_back(VE.getValueID(I.getOperand(2)));
762 case Instruction::ICmp:
763 case Instruction::FCmp:
764 case Instruction::VICmp:
765 case Instruction::VFCmp:
766 Code = bitc::FUNC_CODE_INST_CMP;
767 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
768 Vals.push_back(VE.getValueID(I.getOperand(1)));
769 Vals.push_back(cast<CmpInst>(I).getPredicate());
772 case Instruction::Ret:
774 Code = bitc::FUNC_CODE_INST_RET;
775 unsigned NumOperands = I.getNumOperands();
776 if (NumOperands == 0)
777 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
778 else if (NumOperands == 1) {
779 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
780 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
782 for (unsigned i = 0, e = NumOperands; i != e; ++i)
783 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
787 case Instruction::Br:
788 Code = bitc::FUNC_CODE_INST_BR;
789 Vals.push_back(VE.getValueID(I.getOperand(0)));
790 if (cast<BranchInst>(I).isConditional()) {
791 Vals.push_back(VE.getValueID(I.getOperand(1)));
792 Vals.push_back(VE.getValueID(I.getOperand(2)));
795 case Instruction::Switch:
796 Code = bitc::FUNC_CODE_INST_SWITCH;
797 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
798 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
799 Vals.push_back(VE.getValueID(I.getOperand(i)));
801 case Instruction::Invoke: {
802 const PointerType *PTy = cast<PointerType>(I.getOperand(0)->getType());
803 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
804 Code = bitc::FUNC_CODE_INST_INVOKE;
806 const InvokeInst *II = cast<InvokeInst>(&I);
807 Vals.push_back(VE.getParamAttrID(II->getParamAttrs()));
808 Vals.push_back(II->getCallingConv());
809 Vals.push_back(VE.getValueID(I.getOperand(1))); // normal dest
810 Vals.push_back(VE.getValueID(I.getOperand(2))); // unwind dest
811 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // callee
813 // Emit value #'s for the fixed parameters.
814 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
815 Vals.push_back(VE.getValueID(I.getOperand(i+3))); // fixed param.
817 // Emit type/value pairs for varargs params.
818 if (FTy->isVarArg()) {
819 for (unsigned i = 3+FTy->getNumParams(), e = I.getNumOperands();
821 PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
825 case Instruction::Unwind:
826 Code = bitc::FUNC_CODE_INST_UNWIND;
828 case Instruction::Unreachable:
829 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
830 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
833 case Instruction::PHI:
834 Code = bitc::FUNC_CODE_INST_PHI;
835 Vals.push_back(VE.getTypeID(I.getType()));
836 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
837 Vals.push_back(VE.getValueID(I.getOperand(i)));
840 case Instruction::Malloc:
841 Code = bitc::FUNC_CODE_INST_MALLOC;
842 Vals.push_back(VE.getTypeID(I.getType()));
843 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
844 Vals.push_back(Log2_32(cast<MallocInst>(I).getAlignment())+1);
847 case Instruction::Free:
848 Code = bitc::FUNC_CODE_INST_FREE;
849 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
852 case Instruction::Alloca:
853 Code = bitc::FUNC_CODE_INST_ALLOCA;
854 Vals.push_back(VE.getTypeID(I.getType()));
855 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
856 Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1);
859 case Instruction::Load:
860 Code = bitc::FUNC_CODE_INST_LOAD;
861 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) // ptr
862 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
864 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
865 Vals.push_back(cast<LoadInst>(I).isVolatile());
867 case Instruction::Store:
868 Code = bitc::FUNC_CODE_INST_STORE2;
869 PushValueAndType(I.getOperand(1), InstID, Vals, VE); // ptrty + ptr
870 Vals.push_back(VE.getValueID(I.getOperand(0))); // val.
871 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
872 Vals.push_back(cast<StoreInst>(I).isVolatile());
874 case Instruction::Call: {
875 const PointerType *PTy = cast<PointerType>(I.getOperand(0)->getType());
876 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
878 Code = bitc::FUNC_CODE_INST_CALL;
880 const CallInst *CI = cast<CallInst>(&I);
881 Vals.push_back(VE.getParamAttrID(CI->getParamAttrs()));
882 Vals.push_back((CI->getCallingConv() << 1) | unsigned(CI->isTailCall()));
883 PushValueAndType(CI->getOperand(0), InstID, Vals, VE); // Callee
885 // Emit value #'s for the fixed parameters.
886 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
887 Vals.push_back(VE.getValueID(I.getOperand(i+1))); // fixed param.
889 // Emit type/value pairs for varargs params.
890 if (FTy->isVarArg()) {
891 unsigned NumVarargs = I.getNumOperands()-1-FTy->getNumParams();
892 for (unsigned i = I.getNumOperands()-NumVarargs, e = I.getNumOperands();
894 PushValueAndType(I.getOperand(i), InstID, Vals, VE); // varargs
898 case Instruction::VAArg:
899 Code = bitc::FUNC_CODE_INST_VAARG;
900 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
901 Vals.push_back(VE.getValueID(I.getOperand(0))); // valist.
902 Vals.push_back(VE.getTypeID(I.getType())); // restype.
906 Stream.EmitRecord(Code, Vals, AbbrevToUse);
910 // Emit names for globals/functions etc.
911 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
912 const ValueEnumerator &VE,
913 BitstreamWriter &Stream) {
914 if (VST.empty()) return;
915 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
917 // FIXME: Set up the abbrev, we know how many values there are!
918 // FIXME: We know if the type names can use 7-bit ascii.
919 SmallVector<unsigned, 64> NameVals;
921 for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
924 const ValueName &Name = *SI;
926 // Figure out the encoding to use for the name.
929 for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
932 isChar6 = BitCodeAbbrevOp::isChar6(*C);
933 if ((unsigned char)*C & 128) {
935 break; // don't bother scanning the rest.
939 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
941 // VST_ENTRY: [valueid, namechar x N]
942 // VST_BBENTRY: [bbid, namechar x N]
944 if (isa<BasicBlock>(SI->getValue())) {
945 Code = bitc::VST_CODE_BBENTRY;
947 AbbrevToUse = VST_BBENTRY_6_ABBREV;
949 Code = bitc::VST_CODE_ENTRY;
951 AbbrevToUse = VST_ENTRY_6_ABBREV;
953 AbbrevToUse = VST_ENTRY_7_ABBREV;
956 NameVals.push_back(VE.getValueID(SI->getValue()));
957 for (const char *P = Name.getKeyData(),
958 *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
959 NameVals.push_back((unsigned char)*P);
961 // Emit the finished record.
962 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
968 /// WriteFunction - Emit a function body to the module stream.
969 static void WriteFunction(const Function &F, ValueEnumerator &VE,
970 BitstreamWriter &Stream) {
971 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
972 VE.incorporateFunction(F);
974 SmallVector<unsigned, 64> Vals;
976 // Emit the number of basic blocks, so the reader can create them ahead of
978 Vals.push_back(VE.getBasicBlocks().size());
979 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
982 // If there are function-local constants, emit them now.
983 unsigned CstStart, CstEnd;
984 VE.getFunctionConstantRange(CstStart, CstEnd);
985 WriteConstants(CstStart, CstEnd, VE, Stream, false);
987 // Keep a running idea of what the instruction ID is.
988 unsigned InstID = CstEnd;
990 // Finally, emit all the instructions, in order.
991 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
992 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
994 WriteInstruction(*I, InstID, VE, Stream, Vals);
995 if (I->getType() != Type::VoidTy)
999 // Emit names for all the instructions etc.
1000 WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
1006 /// WriteTypeSymbolTable - Emit a block for the specified type symtab.
1007 static void WriteTypeSymbolTable(const TypeSymbolTable &TST,
1008 const ValueEnumerator &VE,
1009 BitstreamWriter &Stream) {
1010 if (TST.empty()) return;
1012 Stream.EnterSubblock(bitc::TYPE_SYMTAB_BLOCK_ID, 3);
1014 // 7-bit fixed width VST_CODE_ENTRY strings.
1015 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1016 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1017 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1018 Log2_32_Ceil(VE.getTypes().size()+1)));
1019 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1020 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1021 unsigned V7Abbrev = Stream.EmitAbbrev(Abbv);
1023 SmallVector<unsigned, 64> NameVals;
1025 for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end();
1027 // TST_ENTRY: [typeid, namechar x N]
1028 NameVals.push_back(VE.getTypeID(TI->second));
1030 const std::string &Str = TI->first;
1032 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1033 NameVals.push_back((unsigned char)Str[i]);
1038 // Emit the finished record.
1039 Stream.EmitRecord(bitc::VST_CODE_ENTRY, NameVals, is7Bit ? V7Abbrev : 0);
1046 // Emit blockinfo, which defines the standard abbreviations etc.
1047 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
1048 // We only want to emit block info records for blocks that have multiple
1049 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK. Other
1050 // blocks can defined their abbrevs inline.
1051 Stream.EnterBlockInfoBlock(2);
1053 { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
1054 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1055 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
1056 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1057 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1058 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1059 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1060 Abbv) != VST_ENTRY_8_ABBREV)
1061 assert(0 && "Unexpected abbrev ordering!");
1064 { // 7-bit fixed width VST_ENTRY strings.
1065 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1066 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1067 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1068 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1069 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1070 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1071 Abbv) != VST_ENTRY_7_ABBREV)
1072 assert(0 && "Unexpected abbrev ordering!");
1074 { // 6-bit char6 VST_ENTRY strings.
1075 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1076 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1077 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1078 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1079 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1080 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1081 Abbv) != VST_ENTRY_6_ABBREV)
1082 assert(0 && "Unexpected abbrev ordering!");
1084 { // 6-bit char6 VST_BBENTRY strings.
1085 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1086 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
1087 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1088 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1089 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1090 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1091 Abbv) != VST_BBENTRY_6_ABBREV)
1092 assert(0 && "Unexpected abbrev ordering!");
1097 { // SETTYPE abbrev for CONSTANTS_BLOCK.
1098 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1099 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
1100 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1101 Log2_32_Ceil(VE.getTypes().size()+1)));
1102 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1103 Abbv) != CONSTANTS_SETTYPE_ABBREV)
1104 assert(0 && "Unexpected abbrev ordering!");
1107 { // INTEGER abbrev for CONSTANTS_BLOCK.
1108 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1109 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
1110 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1111 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1112 Abbv) != CONSTANTS_INTEGER_ABBREV)
1113 assert(0 && "Unexpected abbrev ordering!");
1116 { // CE_CAST abbrev for CONSTANTS_BLOCK.
1117 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1118 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
1119 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
1120 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
1121 Log2_32_Ceil(VE.getTypes().size()+1)));
1122 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
1124 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1125 Abbv) != CONSTANTS_CE_CAST_Abbrev)
1126 assert(0 && "Unexpected abbrev ordering!");
1128 { // NULL abbrev for CONSTANTS_BLOCK.
1129 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1130 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
1131 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1132 Abbv) != CONSTANTS_NULL_Abbrev)
1133 assert(0 && "Unexpected abbrev ordering!");
1136 // FIXME: This should only use space for first class types!
1138 { // INST_LOAD abbrev for FUNCTION_BLOCK.
1139 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1140 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
1141 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
1142 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
1143 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
1144 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1145 Abbv) != FUNCTION_INST_LOAD_ABBREV)
1146 assert(0 && "Unexpected abbrev ordering!");
1148 { // INST_BINOP abbrev for FUNCTION_BLOCK.
1149 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1150 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1151 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1152 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1153 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1154 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1155 Abbv) != FUNCTION_INST_BINOP_ABBREV)
1156 assert(0 && "Unexpected abbrev ordering!");
1158 { // INST_CAST abbrev for FUNCTION_BLOCK.
1159 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1160 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
1161 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
1162 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
1163 Log2_32_Ceil(VE.getTypes().size()+1)));
1164 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1165 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1166 Abbv) != FUNCTION_INST_CAST_ABBREV)
1167 assert(0 && "Unexpected abbrev ordering!");
1170 { // INST_RET abbrev for FUNCTION_BLOCK.
1171 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1172 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1173 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1174 Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
1175 assert(0 && "Unexpected abbrev ordering!");
1177 { // INST_RET abbrev for FUNCTION_BLOCK.
1178 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1179 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1180 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
1181 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1182 Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
1183 assert(0 && "Unexpected abbrev ordering!");
1185 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
1186 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1187 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
1188 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1189 Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
1190 assert(0 && "Unexpected abbrev ordering!");
1197 /// WriteModule - Emit the specified module to the bitstream.
1198 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
1199 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
1201 // Emit the version number if it is non-zero.
1203 SmallVector<unsigned, 1> Vals;
1204 Vals.push_back(CurVersion);
1205 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
1208 // Analyze the module, enumerating globals, functions, etc.
1209 ValueEnumerator VE(M);
1211 // Emit blockinfo, which defines the standard abbreviations etc.
1212 WriteBlockInfo(VE, Stream);
1214 // Emit information about parameter attributes.
1215 WriteParamAttrTable(VE, Stream);
1217 // Emit information describing all of the types in the module.
1218 WriteTypeTable(VE, Stream);
1220 // Emit top-level description of module, including target triple, inline asm,
1221 // descriptors for global variables, and function prototype info.
1222 WriteModuleInfo(M, VE, Stream);
1225 WriteModuleConstants(VE, Stream);
1227 // If we have any aggregate values in the value table, purge them - these can
1228 // only be used to initialize global variables. Doing so makes the value
1229 // namespace smaller for code in functions.
1230 int NumNonAggregates = VE.PurgeAggregateValues();
1231 if (NumNonAggregates != -1) {
1232 SmallVector<unsigned, 1> Vals;
1233 Vals.push_back(NumNonAggregates);
1234 Stream.EmitRecord(bitc::MODULE_CODE_PURGEVALS, Vals);
1237 // Emit function bodies.
1238 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1239 if (!I->isDeclaration())
1240 WriteFunction(*I, VE, Stream);
1242 // Emit the type symbol table information.
1243 WriteTypeSymbolTable(M->getTypeSymbolTable(), VE, Stream);
1245 // Emit names for globals/functions etc.
1246 WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
1251 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
1252 /// header and trailer to make it compatible with the system archiver. To do
1253 /// this we emit the following header, and then emit a trailer that pads the
1254 /// file out to be a multiple of 16 bytes.
1256 /// struct bc_header {
1257 /// uint32_t Magic; // 0x0B17C0DE
1258 /// uint32_t Version; // Version, currently always 0.
1259 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
1260 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
1261 /// uint32_t CPUType; // CPU specifier.
1262 /// ... potentially more later ...
1265 DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
1266 DarwinBCHeaderSize = 5*4
1269 static void EmitDarwinBCHeader(BitstreamWriter &Stream,
1270 const std::string &TT) {
1271 unsigned CPUType = ~0U;
1273 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*. The CPUType is a
1274 // magic number from /usr/include/mach/machine.h. It is ok to reproduce the
1275 // specific constants here because they are implicitly part of the Darwin ABI.
1277 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
1278 DARWIN_CPU_TYPE_X86 = 7,
1279 DARWIN_CPU_TYPE_POWERPC = 18
1282 if (TT.find("x86_64-") == 0)
1283 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
1284 else if (TT.size() >= 5 && TT[0] == 'i' && TT[2] == '8' && TT[3] == '6' &&
1285 TT[4] == '-' && TT[1] - '3' < 6)
1286 CPUType = DARWIN_CPU_TYPE_X86;
1287 else if (TT.find("powerpc-") == 0)
1288 CPUType = DARWIN_CPU_TYPE_POWERPC;
1289 else if (TT.find("powerpc64-") == 0)
1290 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
1292 // Traditional Bitcode starts after header.
1293 unsigned BCOffset = DarwinBCHeaderSize;
1295 Stream.Emit(0x0B17C0DE, 32);
1296 Stream.Emit(0 , 32); // Version.
1297 Stream.Emit(BCOffset , 32);
1298 Stream.Emit(0 , 32); // Filled in later.
1299 Stream.Emit(CPUType , 32);
1302 /// EmitDarwinBCTrailer - Emit the darwin epilog after the bitcode file and
1303 /// finalize the header.
1304 static void EmitDarwinBCTrailer(BitstreamWriter &Stream, unsigned BufferSize) {
1305 // Update the size field in the header.
1306 Stream.BackpatchWord(DarwinBCSizeFieldOffset, BufferSize-DarwinBCHeaderSize);
1308 // If the file is not a multiple of 16 bytes, insert dummy padding.
1309 while (BufferSize & 15) {
1316 /// WriteBitcodeToFile - Write the specified module to the specified output
1318 void llvm::WriteBitcodeToFile(const Module *M, std::ostream &Out) {
1319 std::vector<unsigned char> Buffer;
1320 BitstreamWriter Stream(Buffer);
1322 Buffer.reserve(256*1024);
1324 // If this is darwin, emit a file header and trailer if needed.
1325 bool isDarwin = M->getTargetTriple().find("-darwin") != std::string::npos;
1327 EmitDarwinBCHeader(Stream, M->getTargetTriple());
1329 // Emit the file header.
1330 Stream.Emit((unsigned)'B', 8);
1331 Stream.Emit((unsigned)'C', 8);
1332 Stream.Emit(0x0, 4);
1333 Stream.Emit(0xC, 4);
1334 Stream.Emit(0xE, 4);
1335 Stream.Emit(0xD, 4);
1338 WriteModule(M, Stream);
1341 EmitDarwinBCTrailer(Stream, Buffer.size());
1344 // If writing to stdout, set binary mode.
1345 if (llvm::cout == Out)
1346 sys::Program::ChangeStdoutToBinary();
1348 // Write the generated bitstream to "Out".
1349 Out.write((char*)&Buffer.front(), Buffer.size());
1351 // Make sure it hits disk now.