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/Support/Streams.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/System/Program.h"
31 /// These are manifest constants used by the bitcode writer. They do not need to
32 /// be kept in sync with the reader, but need to be consistent within this file.
36 // VALUE_SYMTAB_BLOCK abbrev id's.
37 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
42 // CONSTANTS_BLOCK abbrev id's.
43 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
44 CONSTANTS_INTEGER_ABBREV,
45 CONSTANTS_CE_CAST_Abbrev,
46 CONSTANTS_NULL_Abbrev,
48 // FUNCTION_BLOCK abbrev id's.
49 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
50 FUNCTION_INST_BINOP_ABBREV,
51 FUNCTION_INST_CAST_ABBREV,
52 FUNCTION_INST_RET_VOID_ABBREV,
53 FUNCTION_INST_RET_VAL_ABBREV,
54 FUNCTION_INST_UNREACHABLE_ABBREV
58 static unsigned GetEncodedCastOpcode(unsigned Opcode) {
60 default: assert(0 && "Unknown cast instruction!");
61 case Instruction::Trunc : return bitc::CAST_TRUNC;
62 case Instruction::ZExt : return bitc::CAST_ZEXT;
63 case Instruction::SExt : return bitc::CAST_SEXT;
64 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
65 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
66 case Instruction::UIToFP : return bitc::CAST_UITOFP;
67 case Instruction::SIToFP : return bitc::CAST_SITOFP;
68 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
69 case Instruction::FPExt : return bitc::CAST_FPEXT;
70 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
71 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
72 case Instruction::BitCast : return bitc::CAST_BITCAST;
76 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
78 default: assert(0 && "Unknown binary instruction!");
79 case Instruction::Add: return bitc::BINOP_ADD;
80 case Instruction::Sub: return bitc::BINOP_SUB;
81 case Instruction::Mul: return bitc::BINOP_MUL;
82 case Instruction::UDiv: return bitc::BINOP_UDIV;
83 case Instruction::FDiv:
84 case Instruction::SDiv: return bitc::BINOP_SDIV;
85 case Instruction::URem: return bitc::BINOP_UREM;
86 case Instruction::FRem:
87 case Instruction::SRem: return bitc::BINOP_SREM;
88 case Instruction::Shl: return bitc::BINOP_SHL;
89 case Instruction::LShr: return bitc::BINOP_LSHR;
90 case Instruction::AShr: return bitc::BINOP_ASHR;
91 case Instruction::And: return bitc::BINOP_AND;
92 case Instruction::Or: return bitc::BINOP_OR;
93 case Instruction::Xor: return bitc::BINOP_XOR;
99 static void WriteStringRecord(unsigned Code, const std::string &Str,
100 unsigned AbbrevToUse, BitstreamWriter &Stream) {
101 SmallVector<unsigned, 64> Vals;
103 // Code: [strchar x N]
104 for (unsigned i = 0, e = Str.size(); i != e; ++i)
105 Vals.push_back(Str[i]);
107 // Emit the finished record.
108 Stream.EmitRecord(Code, Vals, AbbrevToUse);
111 // Emit information about parameter attributes.
112 static void WriteAttributeTable(const ValueEnumerator &VE,
113 BitstreamWriter &Stream) {
114 const std::vector<AttrListPtr> &Attrs = VE.getAttributes();
115 if (Attrs.empty()) return;
117 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
119 SmallVector<uint64_t, 64> Record;
120 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
121 const AttrListPtr &A = Attrs[i];
122 for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i) {
123 const AttributeWithIndex &PAWI = A.getSlot(i);
124 Record.push_back(PAWI.Index);
126 // FIXME: remove in LLVM 3.0
127 // Store the alignment in the bitcode as a 16-bit raw value instead of a
128 // 5-bit log2 encoded value. Shift the bits above the alignment up by
130 uint64_t FauxAttr = PAWI.Attrs & 0xffff;
131 if (PAWI.Attrs & Attribute::Alignment)
132 FauxAttr |= (1ull<<16)<<(((PAWI.Attrs & Attribute::Alignment)-1) >> 16);
133 FauxAttr |= (PAWI.Attrs & (0x3FFull << 21)) << 11;
135 Record.push_back(FauxAttr);
138 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
145 /// WriteTypeTable - Write out the type table for a module.
146 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
147 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
149 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID, 4 /*count from # abbrevs */);
150 SmallVector<uint64_t, 64> TypeVals;
152 // Abbrev for TYPE_CODE_POINTER.
153 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
154 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
155 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
156 Log2_32_Ceil(VE.getTypes().size()+1)));
157 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
158 unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
160 // Abbrev for TYPE_CODE_FUNCTION.
161 Abbv = new BitCodeAbbrev();
162 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
163 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
164 Abbv->Add(BitCodeAbbrevOp(0)); // FIXME: DEAD value, remove in LLVM 3.0
165 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
166 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
167 Log2_32_Ceil(VE.getTypes().size()+1)));
168 unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
170 // Abbrev for TYPE_CODE_STRUCT.
171 Abbv = new BitCodeAbbrev();
172 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT));
173 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
174 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
175 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
176 Log2_32_Ceil(VE.getTypes().size()+1)));
177 unsigned StructAbbrev = Stream.EmitAbbrev(Abbv);
179 // Abbrev for TYPE_CODE_ARRAY.
180 Abbv = new BitCodeAbbrev();
181 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
182 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
183 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
184 Log2_32_Ceil(VE.getTypes().size()+1)));
185 unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
187 // Emit an entry count so the reader can reserve space.
188 TypeVals.push_back(TypeList.size());
189 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
192 // Loop over all of the types, emitting each in turn.
193 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
194 const Type *T = TypeList[i].first;
198 switch (T->getTypeID()) {
199 default: assert(0 && "Unknown type!");
200 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
201 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
202 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
203 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
204 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
205 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
206 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
207 case Type::OpaqueTyID: Code = bitc::TYPE_CODE_OPAQUE; break;
208 case Type::IntegerTyID:
210 Code = bitc::TYPE_CODE_INTEGER;
211 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
213 case Type::PointerTyID: {
214 const PointerType *PTy = cast<PointerType>(T);
215 // POINTER: [pointee type, address space]
216 Code = bitc::TYPE_CODE_POINTER;
217 TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
218 unsigned AddressSpace = PTy->getAddressSpace();
219 TypeVals.push_back(AddressSpace);
220 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
223 case Type::FunctionTyID: {
224 const FunctionType *FT = cast<FunctionType>(T);
225 // FUNCTION: [isvararg, attrid, retty, paramty x N]
226 Code = bitc::TYPE_CODE_FUNCTION;
227 TypeVals.push_back(FT->isVarArg());
228 TypeVals.push_back(0); // FIXME: DEAD: remove in llvm 3.0
229 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
230 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
231 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
232 AbbrevToUse = FunctionAbbrev;
235 case Type::StructTyID: {
236 const StructType *ST = cast<StructType>(T);
237 // STRUCT: [ispacked, eltty x N]
238 Code = bitc::TYPE_CODE_STRUCT;
239 TypeVals.push_back(ST->isPacked());
240 // Output all of the element types.
241 for (StructType::element_iterator I = ST->element_begin(),
242 E = ST->element_end(); I != E; ++I)
243 TypeVals.push_back(VE.getTypeID(*I));
244 AbbrevToUse = StructAbbrev;
247 case Type::ArrayTyID: {
248 const ArrayType *AT = cast<ArrayType>(T);
249 // ARRAY: [numelts, eltty]
250 Code = bitc::TYPE_CODE_ARRAY;
251 TypeVals.push_back(AT->getNumElements());
252 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
253 AbbrevToUse = ArrayAbbrev;
256 case Type::VectorTyID: {
257 const VectorType *VT = cast<VectorType>(T);
258 // VECTOR [numelts, eltty]
259 Code = bitc::TYPE_CODE_VECTOR;
260 TypeVals.push_back(VT->getNumElements());
261 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
266 // Emit the finished record.
267 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
274 static unsigned getEncodedLinkage(const GlobalValue *GV) {
275 switch (GV->getLinkage()) {
276 default: assert(0 && "Invalid linkage!");
277 case GlobalValue::GhostLinkage: // Map ghost linkage onto external.
278 case GlobalValue::ExternalLinkage: return 0;
279 case GlobalValue::WeakAnyLinkage: return 1;
280 case GlobalValue::AppendingLinkage: return 2;
281 case GlobalValue::InternalLinkage: return 3;
282 case GlobalValue::LinkOnceAnyLinkage: return 4;
283 case GlobalValue::DLLImportLinkage: return 5;
284 case GlobalValue::DLLExportLinkage: return 6;
285 case GlobalValue::ExternalWeakLinkage: return 7;
286 case GlobalValue::CommonLinkage: return 8;
287 case GlobalValue::PrivateLinkage: return 9;
288 case GlobalValue::WeakODRLinkage: return 10;
289 case GlobalValue::LinkOnceODRLinkage: return 11;
293 static unsigned getEncodedVisibility(const GlobalValue *GV) {
294 switch (GV->getVisibility()) {
295 default: assert(0 && "Invalid visibility!");
296 case GlobalValue::DefaultVisibility: return 0;
297 case GlobalValue::HiddenVisibility: return 1;
298 case GlobalValue::ProtectedVisibility: return 2;
302 // Emit top-level description of module, including target triple, inline asm,
303 // descriptors for global variables, and function prototype info.
304 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
305 BitstreamWriter &Stream) {
306 // Emit the list of dependent libraries for the Module.
307 for (Module::lib_iterator I = M->lib_begin(), E = M->lib_end(); I != E; ++I)
308 WriteStringRecord(bitc::MODULE_CODE_DEPLIB, *I, 0/*TODO*/, Stream);
310 // Emit various pieces of data attached to a module.
311 if (!M->getTargetTriple().empty())
312 WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
314 if (!M->getDataLayout().empty())
315 WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(),
317 if (!M->getModuleInlineAsm().empty())
318 WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
321 // Emit information about sections and GC, computing how many there are. Also
322 // compute the maximum alignment value.
323 std::map<std::string, unsigned> SectionMap;
324 std::map<std::string, unsigned> GCMap;
325 unsigned MaxAlignment = 0;
326 unsigned MaxGlobalType = 0;
327 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
329 MaxAlignment = std::max(MaxAlignment, GV->getAlignment());
330 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType()));
332 if (!GV->hasSection()) continue;
333 // Give section names unique ID's.
334 unsigned &Entry = SectionMap[GV->getSection()];
335 if (Entry != 0) continue;
336 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(),
338 Entry = SectionMap.size();
340 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
341 MaxAlignment = std::max(MaxAlignment, F->getAlignment());
342 if (F->hasSection()) {
343 // Give section names unique ID's.
344 unsigned &Entry = SectionMap[F->getSection()];
346 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(),
348 Entry = SectionMap.size();
352 // Same for GC names.
353 unsigned &Entry = GCMap[F->getGC()];
355 WriteStringRecord(bitc::MODULE_CODE_GCNAME, F->getGC(),
357 Entry = GCMap.size();
362 // Emit abbrev for globals, now that we know # sections and max alignment.
363 unsigned SimpleGVarAbbrev = 0;
364 if (!M->global_empty()) {
365 // Add an abbrev for common globals with no visibility or thread localness.
366 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
367 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
368 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
369 Log2_32_Ceil(MaxGlobalType+1)));
370 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Constant.
371 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
372 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // Linkage.
373 if (MaxAlignment == 0) // Alignment.
374 Abbv->Add(BitCodeAbbrevOp(0));
376 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
377 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
378 Log2_32_Ceil(MaxEncAlignment+1)));
380 if (SectionMap.empty()) // Section.
381 Abbv->Add(BitCodeAbbrevOp(0));
383 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
384 Log2_32_Ceil(SectionMap.size()+1)));
385 // Don't bother emitting vis + thread local.
386 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
389 // Emit the global variable information.
390 SmallVector<unsigned, 64> Vals;
391 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
393 unsigned AbbrevToUse = 0;
395 // GLOBALVAR: [type, isconst, initid,
396 // linkage, alignment, section, visibility, threadlocal]
397 Vals.push_back(VE.getTypeID(GV->getType()));
398 Vals.push_back(GV->isConstant());
399 Vals.push_back(GV->isDeclaration() ? 0 :
400 (VE.getValueID(GV->getInitializer()) + 1));
401 Vals.push_back(getEncodedLinkage(GV));
402 Vals.push_back(Log2_32(GV->getAlignment())+1);
403 Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0);
404 if (GV->isThreadLocal() ||
405 GV->getVisibility() != GlobalValue::DefaultVisibility) {
406 Vals.push_back(getEncodedVisibility(GV));
407 Vals.push_back(GV->isThreadLocal());
409 AbbrevToUse = SimpleGVarAbbrev;
412 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
416 // Emit the function proto information.
417 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
418 // FUNCTION: [type, callingconv, isproto, paramattr,
419 // linkage, alignment, section, visibility, gc]
420 Vals.push_back(VE.getTypeID(F->getType()));
421 Vals.push_back(F->getCallingConv());
422 Vals.push_back(F->isDeclaration());
423 Vals.push_back(getEncodedLinkage(F));
424 Vals.push_back(VE.getAttributeID(F->getAttributes()));
425 Vals.push_back(Log2_32(F->getAlignment())+1);
426 Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
427 Vals.push_back(getEncodedVisibility(F));
428 Vals.push_back(F->hasGC() ? GCMap[F->getGC()] : 0);
430 unsigned AbbrevToUse = 0;
431 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
436 // Emit the alias information.
437 for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end();
439 Vals.push_back(VE.getTypeID(AI->getType()));
440 Vals.push_back(VE.getValueID(AI->getAliasee()));
441 Vals.push_back(getEncodedLinkage(AI));
442 Vals.push_back(getEncodedVisibility(AI));
443 unsigned AbbrevToUse = 0;
444 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
450 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
451 const ValueEnumerator &VE,
452 BitstreamWriter &Stream, bool isGlobal) {
453 if (FirstVal == LastVal) return;
455 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
457 unsigned AggregateAbbrev = 0;
458 unsigned String8Abbrev = 0;
459 unsigned CString7Abbrev = 0;
460 unsigned CString6Abbrev = 0;
461 unsigned MDString8Abbrev = 0;
462 unsigned MDString6Abbrev = 0;
463 // If this is a constant pool for the module, emit module-specific abbrevs.
465 // Abbrev for CST_CODE_AGGREGATE.
466 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
467 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
468 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
469 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
470 AggregateAbbrev = Stream.EmitAbbrev(Abbv);
472 // Abbrev for CST_CODE_STRING.
473 Abbv = new BitCodeAbbrev();
474 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
475 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
476 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
477 String8Abbrev = Stream.EmitAbbrev(Abbv);
478 // Abbrev for CST_CODE_CSTRING.
479 Abbv = new BitCodeAbbrev();
480 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
481 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
482 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
483 CString7Abbrev = Stream.EmitAbbrev(Abbv);
484 // Abbrev for CST_CODE_CSTRING.
485 Abbv = new BitCodeAbbrev();
486 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
487 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
488 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
489 CString6Abbrev = Stream.EmitAbbrev(Abbv);
491 // Abbrev for CST_CODE_MDSTRING.
492 Abbv = new BitCodeAbbrev();
493 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_MDSTRING));
494 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
495 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
496 MDString8Abbrev = Stream.EmitAbbrev(Abbv);
497 // Abbrev for CST_CODE_MDSTRING.
498 Abbv = new BitCodeAbbrev();
499 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_MDSTRING));
500 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
501 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
502 MDString6Abbrev = Stream.EmitAbbrev(Abbv);
505 SmallVector<uint64_t, 64> Record;
507 const ValueEnumerator::ValueList &Vals = VE.getValues();
508 const Type *LastTy = 0;
509 for (unsigned i = FirstVal; i != LastVal; ++i) {
510 const Value *V = Vals[i].first;
511 // If we need to switch types, do so now.
512 if (V->getType() != LastTy) {
513 LastTy = V->getType();
514 Record.push_back(VE.getTypeID(LastTy));
515 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
516 CONSTANTS_SETTYPE_ABBREV);
520 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
521 Record.push_back(unsigned(IA->hasSideEffects()));
523 // Add the asm string.
524 const std::string &AsmStr = IA->getAsmString();
525 Record.push_back(AsmStr.size());
526 for (unsigned i = 0, e = AsmStr.size(); i != e; ++i)
527 Record.push_back(AsmStr[i]);
529 // Add the constraint string.
530 const std::string &ConstraintStr = IA->getConstraintString();
531 Record.push_back(ConstraintStr.size());
532 for (unsigned i = 0, e = ConstraintStr.size(); i != e; ++i)
533 Record.push_back(ConstraintStr[i]);
534 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
538 const Constant *C = cast<Constant>(V);
540 unsigned AbbrevToUse = 0;
541 if (C->isNullValue()) {
542 Code = bitc::CST_CODE_NULL;
543 } else if (isa<UndefValue>(C)) {
544 Code = bitc::CST_CODE_UNDEF;
545 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
546 if (IV->getBitWidth() <= 64) {
547 int64_t V = IV->getSExtValue();
549 Record.push_back(V << 1);
551 Record.push_back((-V << 1) | 1);
552 Code = bitc::CST_CODE_INTEGER;
553 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
554 } else { // Wide integers, > 64 bits in size.
555 // We have an arbitrary precision integer value to write whose
556 // bit width is > 64. However, in canonical unsigned integer
557 // format it is likely that the high bits are going to be zero.
558 // So, we only write the number of active words.
559 unsigned NWords = IV->getValue().getActiveWords();
560 const uint64_t *RawWords = IV->getValue().getRawData();
561 for (unsigned i = 0; i != NWords; ++i) {
562 int64_t V = RawWords[i];
564 Record.push_back(V << 1);
566 Record.push_back((-V << 1) | 1);
568 Code = bitc::CST_CODE_WIDE_INTEGER;
570 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
571 Code = bitc::CST_CODE_FLOAT;
572 const Type *Ty = CFP->getType();
573 if (Ty == Type::FloatTy || Ty == Type::DoubleTy) {
574 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
575 } else if (Ty == Type::X86_FP80Ty) {
576 // api needed to prevent premature destruction
577 // bits are not in the same order as a normal i80 APInt, compensate.
578 APInt api = CFP->getValueAPF().bitcastToAPInt();
579 const uint64_t *p = api.getRawData();
580 Record.push_back((p[1] << 48) | (p[0] >> 16));
581 Record.push_back(p[0] & 0xffffLL);
582 } else if (Ty == Type::FP128Ty || Ty == Type::PPC_FP128Ty) {
583 APInt api = CFP->getValueAPF().bitcastToAPInt();
584 const uint64_t *p = api.getRawData();
585 Record.push_back(p[0]);
586 Record.push_back(p[1]);
588 assert (0 && "Unknown FP type!");
590 } else if (isa<ConstantArray>(C) && cast<ConstantArray>(C)->isString()) {
591 // Emit constant strings specially.
592 unsigned NumOps = C->getNumOperands();
593 // If this is a null-terminated string, use the denser CSTRING encoding.
594 if (C->getOperand(NumOps-1)->isNullValue()) {
595 Code = bitc::CST_CODE_CSTRING;
596 --NumOps; // Don't encode the null, which isn't allowed by char6.
598 Code = bitc::CST_CODE_STRING;
599 AbbrevToUse = String8Abbrev;
601 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
602 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
603 for (unsigned i = 0; i != NumOps; ++i) {
604 unsigned char V = cast<ConstantInt>(C->getOperand(i))->getZExtValue();
606 isCStr7 &= (V & 128) == 0;
608 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
612 AbbrevToUse = CString6Abbrev;
614 AbbrevToUse = CString7Abbrev;
615 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(V) ||
616 isa<ConstantVector>(V)) {
617 Code = bitc::CST_CODE_AGGREGATE;
618 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
619 Record.push_back(VE.getValueID(C->getOperand(i)));
620 AbbrevToUse = AggregateAbbrev;
621 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
622 switch (CE->getOpcode()) {
624 if (Instruction::isCast(CE->getOpcode())) {
625 Code = bitc::CST_CODE_CE_CAST;
626 Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
627 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
628 Record.push_back(VE.getValueID(C->getOperand(0)));
629 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
631 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
632 Code = bitc::CST_CODE_CE_BINOP;
633 Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
634 Record.push_back(VE.getValueID(C->getOperand(0)));
635 Record.push_back(VE.getValueID(C->getOperand(1)));
638 case Instruction::GetElementPtr:
639 Code = bitc::CST_CODE_CE_GEP;
640 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
641 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
642 Record.push_back(VE.getValueID(C->getOperand(i)));
645 case Instruction::Select:
646 Code = bitc::CST_CODE_CE_SELECT;
647 Record.push_back(VE.getValueID(C->getOperand(0)));
648 Record.push_back(VE.getValueID(C->getOperand(1)));
649 Record.push_back(VE.getValueID(C->getOperand(2)));
651 case Instruction::ExtractElement:
652 Code = bitc::CST_CODE_CE_EXTRACTELT;
653 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
654 Record.push_back(VE.getValueID(C->getOperand(0)));
655 Record.push_back(VE.getValueID(C->getOperand(1)));
657 case Instruction::InsertElement:
658 Code = bitc::CST_CODE_CE_INSERTELT;
659 Record.push_back(VE.getValueID(C->getOperand(0)));
660 Record.push_back(VE.getValueID(C->getOperand(1)));
661 Record.push_back(VE.getValueID(C->getOperand(2)));
663 case Instruction::ShuffleVector:
664 // If the return type and argument types are the same, this is a
665 // standard shufflevector instruction. If the types are different,
666 // then the shuffle is widening or truncating the input vectors, and
667 // the argument type must also be encoded.
668 if (C->getType() == C->getOperand(0)->getType()) {
669 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
671 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
672 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
674 Record.push_back(VE.getValueID(C->getOperand(0)));
675 Record.push_back(VE.getValueID(C->getOperand(1)));
676 Record.push_back(VE.getValueID(C->getOperand(2)));
678 case Instruction::ICmp:
679 case Instruction::FCmp:
680 case Instruction::VICmp:
681 case Instruction::VFCmp:
682 if (isa<VectorType>(C->getOperand(0)->getType())
683 && (CE->getOpcode() == Instruction::ICmp
684 || CE->getOpcode() == Instruction::FCmp)) {
685 // compare returning vector of Int1Ty
686 assert(0 && "Unsupported constant!");
688 Code = bitc::CST_CODE_CE_CMP;
690 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
691 Record.push_back(VE.getValueID(C->getOperand(0)));
692 Record.push_back(VE.getValueID(C->getOperand(1)));
693 Record.push_back(CE->getPredicate());
696 } else if (const MDString *S = dyn_cast<MDString>(C)) {
697 Code = bitc::CST_CODE_MDSTRING;
698 AbbrevToUse = MDString6Abbrev;
699 for (unsigned i = 0, e = S->size(); i != e; ++i) {
700 char V = S->begin()[i];
703 if (!BitCodeAbbrevOp::isChar6(V))
704 AbbrevToUse = MDString8Abbrev;
706 } else if (const MDNode *N = dyn_cast<MDNode>(C)) {
707 Code = bitc::CST_CODE_MDNODE;
708 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
709 Record.push_back(VE.getTypeID(N->getOperand(i)->getType()));
710 Record.push_back(VE.getValueID(N->getOperand(i)));
713 assert(0 && "Unknown constant!");
715 Stream.EmitRecord(Code, Record, AbbrevToUse);
722 static void WriteModuleConstants(const ValueEnumerator &VE,
723 BitstreamWriter &Stream) {
724 const ValueEnumerator::ValueList &Vals = VE.getValues();
726 // Find the first constant to emit, which is the first non-globalvalue value.
727 // We know globalvalues have been emitted by WriteModuleInfo.
728 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
729 if (!isa<GlobalValue>(Vals[i].first)) {
730 WriteConstants(i, Vals.size(), VE, Stream, true);
736 /// PushValueAndType - The file has to encode both the value and type id for
737 /// many values, because we need to know what type to create for forward
738 /// references. However, most operands are not forward references, so this type
739 /// field is not needed.
741 /// This function adds V's value ID to Vals. If the value ID is higher than the
742 /// instruction ID, then it is a forward reference, and it also includes the
744 static bool PushValueAndType(const Value *V, unsigned InstID,
745 SmallVector<unsigned, 64> &Vals,
746 ValueEnumerator &VE) {
747 unsigned ValID = VE.getValueID(V);
748 Vals.push_back(ValID);
749 if (ValID >= InstID) {
750 Vals.push_back(VE.getTypeID(V->getType()));
756 /// WriteInstruction - Emit an instruction to the specified stream.
757 static void WriteInstruction(const Instruction &I, unsigned InstID,
758 ValueEnumerator &VE, BitstreamWriter &Stream,
759 SmallVector<unsigned, 64> &Vals) {
761 unsigned AbbrevToUse = 0;
762 switch (I.getOpcode()) {
764 if (Instruction::isCast(I.getOpcode())) {
765 Code = bitc::FUNC_CODE_INST_CAST;
766 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
767 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
768 Vals.push_back(VE.getTypeID(I.getType()));
769 Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
771 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
772 Code = bitc::FUNC_CODE_INST_BINOP;
773 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
774 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
775 Vals.push_back(VE.getValueID(I.getOperand(1)));
776 Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
780 case Instruction::GetElementPtr:
781 Code = bitc::FUNC_CODE_INST_GEP;
782 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
783 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
785 case Instruction::ExtractValue: {
786 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
787 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
788 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
789 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
793 case Instruction::InsertValue: {
794 Code = bitc::FUNC_CODE_INST_INSERTVAL;
795 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
796 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
797 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
798 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
802 case Instruction::Select:
803 Code = bitc::FUNC_CODE_INST_VSELECT;
804 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
805 Vals.push_back(VE.getValueID(I.getOperand(2)));
806 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
808 case Instruction::ExtractElement:
809 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
810 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
811 Vals.push_back(VE.getValueID(I.getOperand(1)));
813 case Instruction::InsertElement:
814 Code = bitc::FUNC_CODE_INST_INSERTELT;
815 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
816 Vals.push_back(VE.getValueID(I.getOperand(1)));
817 Vals.push_back(VE.getValueID(I.getOperand(2)));
819 case Instruction::ShuffleVector:
820 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
821 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
822 Vals.push_back(VE.getValueID(I.getOperand(1)));
823 Vals.push_back(VE.getValueID(I.getOperand(2)));
825 case Instruction::ICmp:
826 case Instruction::FCmp:
827 case Instruction::VICmp:
828 case Instruction::VFCmp:
829 if (I.getOpcode() == Instruction::ICmp
830 || I.getOpcode() == Instruction::FCmp) {
831 // compare returning Int1Ty or vector of Int1Ty
832 Code = bitc::FUNC_CODE_INST_CMP2;
834 Code = bitc::FUNC_CODE_INST_CMP;
836 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
837 Vals.push_back(VE.getValueID(I.getOperand(1)));
838 Vals.push_back(cast<CmpInst>(I).getPredicate());
841 case Instruction::Ret:
843 Code = bitc::FUNC_CODE_INST_RET;
844 unsigned NumOperands = I.getNumOperands();
845 if (NumOperands == 0)
846 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
847 else if (NumOperands == 1) {
848 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
849 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
851 for (unsigned i = 0, e = NumOperands; i != e; ++i)
852 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
856 case Instruction::Br:
858 Code = bitc::FUNC_CODE_INST_BR;
859 BranchInst &II(cast<BranchInst>(I));
860 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
861 if (II.isConditional()) {
862 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
863 Vals.push_back(VE.getValueID(II.getCondition()));
867 case Instruction::Switch:
868 Code = bitc::FUNC_CODE_INST_SWITCH;
869 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
870 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
871 Vals.push_back(VE.getValueID(I.getOperand(i)));
873 case Instruction::Invoke: {
874 const InvokeInst *II = cast<InvokeInst>(&I);
875 const Value *Callee(II->getCalledValue());
876 const PointerType *PTy = cast<PointerType>(Callee->getType());
877 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
878 Code = bitc::FUNC_CODE_INST_INVOKE;
880 Vals.push_back(VE.getAttributeID(II->getAttributes()));
881 Vals.push_back(II->getCallingConv());
882 Vals.push_back(VE.getValueID(II->getNormalDest()));
883 Vals.push_back(VE.getValueID(II->getUnwindDest()));
884 PushValueAndType(Callee, InstID, Vals, VE);
886 // Emit value #'s for the fixed parameters.
887 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
888 Vals.push_back(VE.getValueID(I.getOperand(i+3))); // fixed param.
890 // Emit type/value pairs for varargs params.
891 if (FTy->isVarArg()) {
892 for (unsigned i = 3+FTy->getNumParams(), e = I.getNumOperands();
894 PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
898 case Instruction::Unwind:
899 Code = bitc::FUNC_CODE_INST_UNWIND;
901 case Instruction::Unreachable:
902 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
903 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
906 case Instruction::PHI:
907 Code = bitc::FUNC_CODE_INST_PHI;
908 Vals.push_back(VE.getTypeID(I.getType()));
909 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
910 Vals.push_back(VE.getValueID(I.getOperand(i)));
913 case Instruction::Malloc:
914 Code = bitc::FUNC_CODE_INST_MALLOC;
915 Vals.push_back(VE.getTypeID(I.getType()));
916 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
917 Vals.push_back(Log2_32(cast<MallocInst>(I).getAlignment())+1);
920 case Instruction::Free:
921 Code = bitc::FUNC_CODE_INST_FREE;
922 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
925 case Instruction::Alloca:
926 Code = bitc::FUNC_CODE_INST_ALLOCA;
927 Vals.push_back(VE.getTypeID(I.getType()));
928 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
929 Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1);
932 case Instruction::Load:
933 Code = bitc::FUNC_CODE_INST_LOAD;
934 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) // ptr
935 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
937 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
938 Vals.push_back(cast<LoadInst>(I).isVolatile());
940 case Instruction::Store:
941 Code = bitc::FUNC_CODE_INST_STORE2;
942 PushValueAndType(I.getOperand(1), InstID, Vals, VE); // ptrty + ptr
943 Vals.push_back(VE.getValueID(I.getOperand(0))); // val.
944 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
945 Vals.push_back(cast<StoreInst>(I).isVolatile());
947 case Instruction::Call: {
948 const PointerType *PTy = cast<PointerType>(I.getOperand(0)->getType());
949 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
951 Code = bitc::FUNC_CODE_INST_CALL;
953 const CallInst *CI = cast<CallInst>(&I);
954 Vals.push_back(VE.getAttributeID(CI->getAttributes()));
955 Vals.push_back((CI->getCallingConv() << 1) | unsigned(CI->isTailCall()));
956 PushValueAndType(CI->getOperand(0), InstID, Vals, VE); // Callee
958 // Emit value #'s for the fixed parameters.
959 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
960 Vals.push_back(VE.getValueID(I.getOperand(i+1))); // fixed param.
962 // Emit type/value pairs for varargs params.
963 if (FTy->isVarArg()) {
964 unsigned NumVarargs = I.getNumOperands()-1-FTy->getNumParams();
965 for (unsigned i = I.getNumOperands()-NumVarargs, e = I.getNumOperands();
967 PushValueAndType(I.getOperand(i), InstID, Vals, VE); // varargs
971 case Instruction::VAArg:
972 Code = bitc::FUNC_CODE_INST_VAARG;
973 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
974 Vals.push_back(VE.getValueID(I.getOperand(0))); // valist.
975 Vals.push_back(VE.getTypeID(I.getType())); // restype.
979 Stream.EmitRecord(Code, Vals, AbbrevToUse);
983 // Emit names for globals/functions etc.
984 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
985 const ValueEnumerator &VE,
986 BitstreamWriter &Stream) {
987 if (VST.empty()) return;
988 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
990 // FIXME: Set up the abbrev, we know how many values there are!
991 // FIXME: We know if the type names can use 7-bit ascii.
992 SmallVector<unsigned, 64> NameVals;
994 for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
997 const ValueName &Name = *SI;
999 // Figure out the encoding to use for the name.
1001 bool isChar6 = true;
1002 for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
1005 isChar6 = BitCodeAbbrevOp::isChar6(*C);
1006 if ((unsigned char)*C & 128) {
1008 break; // don't bother scanning the rest.
1012 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
1014 // VST_ENTRY: [valueid, namechar x N]
1015 // VST_BBENTRY: [bbid, namechar x N]
1017 if (isa<BasicBlock>(SI->getValue())) {
1018 Code = bitc::VST_CODE_BBENTRY;
1020 AbbrevToUse = VST_BBENTRY_6_ABBREV;
1022 Code = bitc::VST_CODE_ENTRY;
1024 AbbrevToUse = VST_ENTRY_6_ABBREV;
1026 AbbrevToUse = VST_ENTRY_7_ABBREV;
1029 NameVals.push_back(VE.getValueID(SI->getValue()));
1030 for (const char *P = Name.getKeyData(),
1031 *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
1032 NameVals.push_back((unsigned char)*P);
1034 // Emit the finished record.
1035 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
1041 /// WriteFunction - Emit a function body to the module stream.
1042 static void WriteFunction(const Function &F, ValueEnumerator &VE,
1043 BitstreamWriter &Stream) {
1044 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
1045 VE.incorporateFunction(F);
1047 SmallVector<unsigned, 64> Vals;
1049 // Emit the number of basic blocks, so the reader can create them ahead of
1051 Vals.push_back(VE.getBasicBlocks().size());
1052 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
1055 // If there are function-local constants, emit them now.
1056 unsigned CstStart, CstEnd;
1057 VE.getFunctionConstantRange(CstStart, CstEnd);
1058 WriteConstants(CstStart, CstEnd, VE, Stream, false);
1060 // Keep a running idea of what the instruction ID is.
1061 unsigned InstID = CstEnd;
1063 // Finally, emit all the instructions, in order.
1064 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1065 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1067 WriteInstruction(*I, InstID, VE, Stream, Vals);
1068 if (I->getType() != Type::VoidTy)
1072 // Emit names for all the instructions etc.
1073 WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
1079 /// WriteTypeSymbolTable - Emit a block for the specified type symtab.
1080 static void WriteTypeSymbolTable(const TypeSymbolTable &TST,
1081 const ValueEnumerator &VE,
1082 BitstreamWriter &Stream) {
1083 if (TST.empty()) return;
1085 Stream.EnterSubblock(bitc::TYPE_SYMTAB_BLOCK_ID, 3);
1087 // 7-bit fixed width VST_CODE_ENTRY strings.
1088 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1089 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1090 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1091 Log2_32_Ceil(VE.getTypes().size()+1)));
1092 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1093 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1094 unsigned V7Abbrev = Stream.EmitAbbrev(Abbv);
1096 SmallVector<unsigned, 64> NameVals;
1098 for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end();
1100 // TST_ENTRY: [typeid, namechar x N]
1101 NameVals.push_back(VE.getTypeID(TI->second));
1103 const std::string &Str = TI->first;
1105 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1106 NameVals.push_back((unsigned char)Str[i]);
1111 // Emit the finished record.
1112 Stream.EmitRecord(bitc::VST_CODE_ENTRY, NameVals, is7Bit ? V7Abbrev : 0);
1119 // Emit blockinfo, which defines the standard abbreviations etc.
1120 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
1121 // We only want to emit block info records for blocks that have multiple
1122 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK. Other
1123 // blocks can defined their abbrevs inline.
1124 Stream.EnterBlockInfoBlock(2);
1126 { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
1127 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1128 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
1129 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1130 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1131 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1132 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1133 Abbv) != VST_ENTRY_8_ABBREV)
1134 assert(0 && "Unexpected abbrev ordering!");
1137 { // 7-bit fixed width VST_ENTRY strings.
1138 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1139 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1140 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1141 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1142 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1143 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1144 Abbv) != VST_ENTRY_7_ABBREV)
1145 assert(0 && "Unexpected abbrev ordering!");
1147 { // 6-bit char6 VST_ENTRY strings.
1148 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1149 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1150 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1151 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1152 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1153 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1154 Abbv) != VST_ENTRY_6_ABBREV)
1155 assert(0 && "Unexpected abbrev ordering!");
1157 { // 6-bit char6 VST_BBENTRY strings.
1158 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1159 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
1160 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1161 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1162 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1163 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1164 Abbv) != VST_BBENTRY_6_ABBREV)
1165 assert(0 && "Unexpected abbrev ordering!");
1170 { // SETTYPE abbrev for CONSTANTS_BLOCK.
1171 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1172 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
1173 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1174 Log2_32_Ceil(VE.getTypes().size()+1)));
1175 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1176 Abbv) != CONSTANTS_SETTYPE_ABBREV)
1177 assert(0 && "Unexpected abbrev ordering!");
1180 { // INTEGER abbrev for CONSTANTS_BLOCK.
1181 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1182 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
1183 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1184 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1185 Abbv) != CONSTANTS_INTEGER_ABBREV)
1186 assert(0 && "Unexpected abbrev ordering!");
1189 { // CE_CAST abbrev for CONSTANTS_BLOCK.
1190 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1191 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
1192 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
1193 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
1194 Log2_32_Ceil(VE.getTypes().size()+1)));
1195 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
1197 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1198 Abbv) != CONSTANTS_CE_CAST_Abbrev)
1199 assert(0 && "Unexpected abbrev ordering!");
1201 { // NULL abbrev for CONSTANTS_BLOCK.
1202 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1203 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
1204 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1205 Abbv) != CONSTANTS_NULL_Abbrev)
1206 assert(0 && "Unexpected abbrev ordering!");
1209 // FIXME: This should only use space for first class types!
1211 { // INST_LOAD abbrev for FUNCTION_BLOCK.
1212 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1213 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
1214 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
1215 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
1216 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
1217 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1218 Abbv) != FUNCTION_INST_LOAD_ABBREV)
1219 assert(0 && "Unexpected abbrev ordering!");
1221 { // INST_BINOP abbrev for FUNCTION_BLOCK.
1222 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1223 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1224 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1225 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1226 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1227 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1228 Abbv) != FUNCTION_INST_BINOP_ABBREV)
1229 assert(0 && "Unexpected abbrev ordering!");
1231 { // INST_CAST abbrev for FUNCTION_BLOCK.
1232 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1233 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
1234 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
1235 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
1236 Log2_32_Ceil(VE.getTypes().size()+1)));
1237 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1238 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1239 Abbv) != FUNCTION_INST_CAST_ABBREV)
1240 assert(0 && "Unexpected abbrev ordering!");
1243 { // INST_RET abbrev for FUNCTION_BLOCK.
1244 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1245 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1246 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1247 Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
1248 assert(0 && "Unexpected abbrev ordering!");
1250 { // INST_RET abbrev for FUNCTION_BLOCK.
1251 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1252 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1253 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
1254 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1255 Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
1256 assert(0 && "Unexpected abbrev ordering!");
1258 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
1259 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1260 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
1261 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1262 Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
1263 assert(0 && "Unexpected abbrev ordering!");
1270 /// WriteModule - Emit the specified module to the bitstream.
1271 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
1272 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
1274 // Emit the version number if it is non-zero.
1276 SmallVector<unsigned, 1> Vals;
1277 Vals.push_back(CurVersion);
1278 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
1281 // Analyze the module, enumerating globals, functions, etc.
1282 ValueEnumerator VE(M);
1284 // Emit blockinfo, which defines the standard abbreviations etc.
1285 WriteBlockInfo(VE, Stream);
1287 // Emit information about parameter attributes.
1288 WriteAttributeTable(VE, Stream);
1290 // Emit information describing all of the types in the module.
1291 WriteTypeTable(VE, Stream);
1293 // Emit top-level description of module, including target triple, inline asm,
1294 // descriptors for global variables, and function prototype info.
1295 WriteModuleInfo(M, VE, Stream);
1298 WriteModuleConstants(VE, Stream);
1300 // If we have any aggregate values in the value table, purge them - these can
1301 // only be used to initialize global variables. Doing so makes the value
1302 // namespace smaller for code in functions.
1303 int NumNonAggregates = VE.PurgeAggregateValues();
1304 if (NumNonAggregates != -1) {
1305 SmallVector<unsigned, 1> Vals;
1306 Vals.push_back(NumNonAggregates);
1307 Stream.EmitRecord(bitc::MODULE_CODE_PURGEVALS, Vals);
1310 // Emit function bodies.
1311 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1312 if (!I->isDeclaration())
1313 WriteFunction(*I, VE, Stream);
1315 // Emit the type symbol table information.
1316 WriteTypeSymbolTable(M->getTypeSymbolTable(), VE, Stream);
1318 // Emit names for globals/functions etc.
1319 WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
1324 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
1325 /// header and trailer to make it compatible with the system archiver. To do
1326 /// this we emit the following header, and then emit a trailer that pads the
1327 /// file out to be a multiple of 16 bytes.
1329 /// struct bc_header {
1330 /// uint32_t Magic; // 0x0B17C0DE
1331 /// uint32_t Version; // Version, currently always 0.
1332 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
1333 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
1334 /// uint32_t CPUType; // CPU specifier.
1335 /// ... potentially more later ...
1338 DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
1339 DarwinBCHeaderSize = 5*4
1342 static void EmitDarwinBCHeader(BitstreamWriter &Stream,
1343 const std::string &TT) {
1344 unsigned CPUType = ~0U;
1346 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*. The CPUType is a
1347 // magic number from /usr/include/mach/machine.h. It is ok to reproduce the
1348 // specific constants here because they are implicitly part of the Darwin ABI.
1350 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
1351 DARWIN_CPU_TYPE_X86 = 7,
1352 DARWIN_CPU_TYPE_POWERPC = 18
1355 if (TT.find("x86_64-") == 0)
1356 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
1357 else if (TT.size() >= 5 && TT[0] == 'i' && TT[2] == '8' && TT[3] == '6' &&
1358 TT[4] == '-' && TT[1] - '3' < 6)
1359 CPUType = DARWIN_CPU_TYPE_X86;
1360 else if (TT.find("powerpc-") == 0)
1361 CPUType = DARWIN_CPU_TYPE_POWERPC;
1362 else if (TT.find("powerpc64-") == 0)
1363 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
1365 // Traditional Bitcode starts after header.
1366 unsigned BCOffset = DarwinBCHeaderSize;
1368 Stream.Emit(0x0B17C0DE, 32);
1369 Stream.Emit(0 , 32); // Version.
1370 Stream.Emit(BCOffset , 32);
1371 Stream.Emit(0 , 32); // Filled in later.
1372 Stream.Emit(CPUType , 32);
1375 /// EmitDarwinBCTrailer - Emit the darwin epilog after the bitcode file and
1376 /// finalize the header.
1377 static void EmitDarwinBCTrailer(BitstreamWriter &Stream, unsigned BufferSize) {
1378 // Update the size field in the header.
1379 Stream.BackpatchWord(DarwinBCSizeFieldOffset, BufferSize-DarwinBCHeaderSize);
1381 // If the file is not a multiple of 16 bytes, insert dummy padding.
1382 while (BufferSize & 15) {
1389 /// WriteBitcodeToFile - Write the specified module to the specified output
1391 void llvm::WriteBitcodeToFile(const Module *M, std::ostream &Out) {
1392 raw_os_ostream RawOut(Out);
1393 // If writing to stdout, set binary mode.
1394 if (llvm::cout == Out)
1395 sys::Program::ChangeStdoutToBinary();
1396 WriteBitcodeToFile(M, RawOut);
1399 /// WriteBitcodeToFile - Write the specified module to the specified output
1401 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out) {
1402 std::vector<unsigned char> Buffer;
1403 BitstreamWriter Stream(Buffer);
1405 Buffer.reserve(256*1024);
1407 WriteBitcodeToStream( M, Stream );
1409 // If writing to stdout, set binary mode.
1410 if (&llvm::outs() == &Out)
1411 sys::Program::ChangeStdoutToBinary();
1413 // Write the generated bitstream to "Out".
1414 Out.write((char*)&Buffer.front(), Buffer.size());
1416 // Make sure it hits disk now.
1420 /// WriteBitcodeToStream - Write the specified module to the specified output
1422 void llvm::WriteBitcodeToStream(const Module *M, BitstreamWriter &Stream) {
1423 // If this is darwin, emit a file header and trailer if needed.
1424 bool isDarwin = M->getTargetTriple().find("-darwin") != std::string::npos;
1426 EmitDarwinBCHeader(Stream, M->getTargetTriple());
1428 // Emit the file header.
1429 Stream.Emit((unsigned)'B', 8);
1430 Stream.Emit((unsigned)'C', 8);
1431 Stream.Emit(0x0, 4);
1432 Stream.Emit(0xC, 4);
1433 Stream.Emit(0xE, 4);
1434 Stream.Emit(0xD, 4);
1437 WriteModule(M, Stream);
1440 EmitDarwinBCTrailer(Stream, Stream.getBuffer().size());