Merge branch 'master' into msp430
[llvm/msp430.git] / lib / Bitcode / Writer / BitcodeWriter.cpp
blob1ad70df0540cf6cbe2f2ae3a95e3b676e4bfd4bb
1 //===--- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ----------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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/MDNode.h"
23 #include "llvm/Module.h"
24 #include "llvm/TypeSymbolTable.h"
25 #include "llvm/ValueSymbolTable.h"
26 #include "llvm/Support/MathExtras.h"
27 #include "llvm/Support/Streams.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/System/Program.h"
30 using namespace llvm;
32 /// These are manifest constants used by the bitcode writer. They do not need to
33 /// be kept in sync with the reader, but need to be consistent within this file.
34 enum {
35 CurVersion = 0,
37 // VALUE_SYMTAB_BLOCK abbrev id's.
38 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
39 VST_ENTRY_7_ABBREV,
40 VST_ENTRY_6_ABBREV,
41 VST_BBENTRY_6_ABBREV,
43 // CONSTANTS_BLOCK abbrev id's.
44 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
45 CONSTANTS_INTEGER_ABBREV,
46 CONSTANTS_CE_CAST_Abbrev,
47 CONSTANTS_NULL_Abbrev,
49 // FUNCTION_BLOCK abbrev id's.
50 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
51 FUNCTION_INST_BINOP_ABBREV,
52 FUNCTION_INST_CAST_ABBREV,
53 FUNCTION_INST_RET_VOID_ABBREV,
54 FUNCTION_INST_RET_VAL_ABBREV,
55 FUNCTION_INST_UNREACHABLE_ABBREV
59 static unsigned GetEncodedCastOpcode(unsigned Opcode) {
60 switch (Opcode) {
61 default: assert(0 && "Unknown cast instruction!");
62 case Instruction::Trunc : return bitc::CAST_TRUNC;
63 case Instruction::ZExt : return bitc::CAST_ZEXT;
64 case Instruction::SExt : return bitc::CAST_SEXT;
65 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
66 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
67 case Instruction::UIToFP : return bitc::CAST_UITOFP;
68 case Instruction::SIToFP : return bitc::CAST_SITOFP;
69 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
70 case Instruction::FPExt : return bitc::CAST_FPEXT;
71 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
72 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
73 case Instruction::BitCast : return bitc::CAST_BITCAST;
77 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
78 switch (Opcode) {
79 default: assert(0 && "Unknown binary instruction!");
80 case Instruction::Add: return bitc::BINOP_ADD;
81 case Instruction::Sub: return bitc::BINOP_SUB;
82 case Instruction::Mul: return bitc::BINOP_MUL;
83 case Instruction::UDiv: return bitc::BINOP_UDIV;
84 case Instruction::FDiv:
85 case Instruction::SDiv: return bitc::BINOP_SDIV;
86 case Instruction::URem: return bitc::BINOP_UREM;
87 case Instruction::FRem:
88 case Instruction::SRem: return bitc::BINOP_SREM;
89 case Instruction::Shl: return bitc::BINOP_SHL;
90 case Instruction::LShr: return bitc::BINOP_LSHR;
91 case Instruction::AShr: return bitc::BINOP_ASHR;
92 case Instruction::And: return bitc::BINOP_AND;
93 case Instruction::Or: return bitc::BINOP_OR;
94 case Instruction::Xor: return bitc::BINOP_XOR;
100 static void WriteStringRecord(unsigned Code, const std::string &Str,
101 unsigned AbbrevToUse, BitstreamWriter &Stream) {
102 SmallVector<unsigned, 64> Vals;
104 // Code: [strchar x N]
105 for (unsigned i = 0, e = Str.size(); i != e; ++i)
106 Vals.push_back(Str[i]);
108 // Emit the finished record.
109 Stream.EmitRecord(Code, Vals, AbbrevToUse);
112 // Emit information about parameter attributes.
113 static void WriteAttributeTable(const ValueEnumerator &VE,
114 BitstreamWriter &Stream) {
115 const std::vector<AttrListPtr> &Attrs = VE.getAttributes();
116 if (Attrs.empty()) return;
118 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
120 SmallVector<uint64_t, 64> Record;
121 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
122 const AttrListPtr &A = Attrs[i];
123 for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i) {
124 const AttributeWithIndex &PAWI = A.getSlot(i);
125 Record.push_back(PAWI.Index);
127 // FIXME: remove in LLVM 3.0
128 // Store the alignment in the bitcode as a 16-bit raw value instead of a
129 // 5-bit log2 encoded value. Shift the bits above the alignment up by
130 // 11 bits.
131 uint64_t FauxAttr = PAWI.Attrs & 0xffff;
132 if (PAWI.Attrs & Attribute::Alignment)
133 FauxAttr |= (1ull<<16)<<(((PAWI.Attrs & Attribute::Alignment)-1) >> 16);
134 FauxAttr |= (PAWI.Attrs & (0x3FFull << 21)) << 11;
136 Record.push_back(FauxAttr);
139 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
140 Record.clear();
143 Stream.ExitBlock();
146 /// WriteTypeTable - Write out the type table for a module.
147 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
148 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
150 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID, 4 /*count from # abbrevs */);
151 SmallVector<uint64_t, 64> TypeVals;
153 // Abbrev for TYPE_CODE_POINTER.
154 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
155 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
156 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
157 Log2_32_Ceil(VE.getTypes().size()+1)));
158 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
159 unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
161 // Abbrev for TYPE_CODE_FUNCTION.
162 Abbv = new BitCodeAbbrev();
163 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
164 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
165 Abbv->Add(BitCodeAbbrevOp(0)); // FIXME: DEAD value, remove in LLVM 3.0
166 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
167 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
168 Log2_32_Ceil(VE.getTypes().size()+1)));
169 unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
171 // Abbrev for TYPE_CODE_STRUCT.
172 Abbv = new BitCodeAbbrev();
173 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT));
174 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
175 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
176 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
177 Log2_32_Ceil(VE.getTypes().size()+1)));
178 unsigned StructAbbrev = Stream.EmitAbbrev(Abbv);
180 // Abbrev for TYPE_CODE_ARRAY.
181 Abbv = new BitCodeAbbrev();
182 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
183 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
184 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
185 Log2_32_Ceil(VE.getTypes().size()+1)));
186 unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
188 // Emit an entry count so the reader can reserve space.
189 TypeVals.push_back(TypeList.size());
190 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
191 TypeVals.clear();
193 // Loop over all of the types, emitting each in turn.
194 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
195 const Type *T = TypeList[i].first;
196 int AbbrevToUse = 0;
197 unsigned Code = 0;
199 switch (T->getTypeID()) {
200 default: assert(0 && "Unknown type!");
201 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
202 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
203 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
204 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
205 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
206 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
207 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
208 case Type::OpaqueTyID: Code = bitc::TYPE_CODE_OPAQUE; break;
209 case Type::IntegerTyID:
210 // INTEGER: [width]
211 Code = bitc::TYPE_CODE_INTEGER;
212 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
213 break;
214 case Type::PointerTyID: {
215 const PointerType *PTy = cast<PointerType>(T);
216 // POINTER: [pointee type, address space]
217 Code = bitc::TYPE_CODE_POINTER;
218 TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
219 unsigned AddressSpace = PTy->getAddressSpace();
220 TypeVals.push_back(AddressSpace);
221 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
222 break;
224 case Type::FunctionTyID: {
225 const FunctionType *FT = cast<FunctionType>(T);
226 // FUNCTION: [isvararg, attrid, retty, paramty x N]
227 Code = bitc::TYPE_CODE_FUNCTION;
228 TypeVals.push_back(FT->isVarArg());
229 TypeVals.push_back(0); // FIXME: DEAD: remove in llvm 3.0
230 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
231 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
232 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
233 AbbrevToUse = FunctionAbbrev;
234 break;
236 case Type::StructTyID: {
237 const StructType *ST = cast<StructType>(T);
238 // STRUCT: [ispacked, eltty x N]
239 Code = bitc::TYPE_CODE_STRUCT;
240 TypeVals.push_back(ST->isPacked());
241 // Output all of the element types.
242 for (StructType::element_iterator I = ST->element_begin(),
243 E = ST->element_end(); I != E; ++I)
244 TypeVals.push_back(VE.getTypeID(*I));
245 AbbrevToUse = StructAbbrev;
246 break;
248 case Type::ArrayTyID: {
249 const ArrayType *AT = cast<ArrayType>(T);
250 // ARRAY: [numelts, eltty]
251 Code = bitc::TYPE_CODE_ARRAY;
252 TypeVals.push_back(AT->getNumElements());
253 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
254 AbbrevToUse = ArrayAbbrev;
255 break;
257 case Type::VectorTyID: {
258 const VectorType *VT = cast<VectorType>(T);
259 // VECTOR [numelts, eltty]
260 Code = bitc::TYPE_CODE_VECTOR;
261 TypeVals.push_back(VT->getNumElements());
262 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
263 break;
267 // Emit the finished record.
268 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
269 TypeVals.clear();
272 Stream.ExitBlock();
275 static unsigned getEncodedLinkage(const GlobalValue *GV) {
276 switch (GV->getLinkage()) {
277 default: assert(0 && "Invalid linkage!");
278 case GlobalValue::GhostLinkage: // Map ghost linkage onto external.
279 case GlobalValue::ExternalLinkage: return 0;
280 case GlobalValue::WeakAnyLinkage: return 1;
281 case GlobalValue::AppendingLinkage: return 2;
282 case GlobalValue::InternalLinkage: return 3;
283 case GlobalValue::LinkOnceAnyLinkage: return 4;
284 case GlobalValue::DLLImportLinkage: return 5;
285 case GlobalValue::DLLExportLinkage: return 6;
286 case GlobalValue::ExternalWeakLinkage: return 7;
287 case GlobalValue::CommonLinkage: return 8;
288 case GlobalValue::PrivateLinkage: return 9;
289 case GlobalValue::WeakODRLinkage: return 10;
290 case GlobalValue::LinkOnceODRLinkage: return 11;
291 case GlobalValue::AvailableExternallyLinkage: return 12;
295 static unsigned getEncodedVisibility(const GlobalValue *GV) {
296 switch (GV->getVisibility()) {
297 default: assert(0 && "Invalid visibility!");
298 case GlobalValue::DefaultVisibility: return 0;
299 case GlobalValue::HiddenVisibility: return 1;
300 case GlobalValue::ProtectedVisibility: return 2;
304 // Emit top-level description of module, including target triple, inline asm,
305 // descriptors for global variables, and function prototype info.
306 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
307 BitstreamWriter &Stream) {
308 // Emit the list of dependent libraries for the Module.
309 for (Module::lib_iterator I = M->lib_begin(), E = M->lib_end(); I != E; ++I)
310 WriteStringRecord(bitc::MODULE_CODE_DEPLIB, *I, 0/*TODO*/, Stream);
312 // Emit various pieces of data attached to a module.
313 if (!M->getTargetTriple().empty())
314 WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
315 0/*TODO*/, Stream);
316 if (!M->getDataLayout().empty())
317 WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(),
318 0/*TODO*/, Stream);
319 if (!M->getModuleInlineAsm().empty())
320 WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
321 0/*TODO*/, Stream);
323 // Emit information about sections and GC, computing how many there are. Also
324 // compute the maximum alignment value.
325 std::map<std::string, unsigned> SectionMap;
326 std::map<std::string, unsigned> GCMap;
327 unsigned MaxAlignment = 0;
328 unsigned MaxGlobalType = 0;
329 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
330 GV != E; ++GV) {
331 MaxAlignment = std::max(MaxAlignment, GV->getAlignment());
332 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType()));
334 if (!GV->hasSection()) continue;
335 // Give section names unique ID's.
336 unsigned &Entry = SectionMap[GV->getSection()];
337 if (Entry != 0) continue;
338 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(),
339 0/*TODO*/, Stream);
340 Entry = SectionMap.size();
342 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
343 MaxAlignment = std::max(MaxAlignment, F->getAlignment());
344 if (F->hasSection()) {
345 // Give section names unique ID's.
346 unsigned &Entry = SectionMap[F->getSection()];
347 if (!Entry) {
348 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(),
349 0/*TODO*/, Stream);
350 Entry = SectionMap.size();
353 if (F->hasGC()) {
354 // Same for GC names.
355 unsigned &Entry = GCMap[F->getGC()];
356 if (!Entry) {
357 WriteStringRecord(bitc::MODULE_CODE_GCNAME, F->getGC(),
358 0/*TODO*/, Stream);
359 Entry = GCMap.size();
364 // Emit abbrev for globals, now that we know # sections and max alignment.
365 unsigned SimpleGVarAbbrev = 0;
366 if (!M->global_empty()) {
367 // Add an abbrev for common globals with no visibility or thread localness.
368 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
369 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
370 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
371 Log2_32_Ceil(MaxGlobalType+1)));
372 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Constant.
373 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
374 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // Linkage.
375 if (MaxAlignment == 0) // Alignment.
376 Abbv->Add(BitCodeAbbrevOp(0));
377 else {
378 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
379 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
380 Log2_32_Ceil(MaxEncAlignment+1)));
382 if (SectionMap.empty()) // Section.
383 Abbv->Add(BitCodeAbbrevOp(0));
384 else
385 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
386 Log2_32_Ceil(SectionMap.size()+1)));
387 // Don't bother emitting vis + thread local.
388 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
391 // Emit the global variable information.
392 SmallVector<unsigned, 64> Vals;
393 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
394 GV != E; ++GV) {
395 unsigned AbbrevToUse = 0;
397 // GLOBALVAR: [type, isconst, initid,
398 // linkage, alignment, section, visibility, threadlocal]
399 Vals.push_back(VE.getTypeID(GV->getType()));
400 Vals.push_back(GV->isConstant());
401 Vals.push_back(GV->isDeclaration() ? 0 :
402 (VE.getValueID(GV->getInitializer()) + 1));
403 Vals.push_back(getEncodedLinkage(GV));
404 Vals.push_back(Log2_32(GV->getAlignment())+1);
405 Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0);
406 if (GV->isThreadLocal() ||
407 GV->getVisibility() != GlobalValue::DefaultVisibility) {
408 Vals.push_back(getEncodedVisibility(GV));
409 Vals.push_back(GV->isThreadLocal());
410 } else {
411 AbbrevToUse = SimpleGVarAbbrev;
414 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
415 Vals.clear();
418 // Emit the function proto information.
419 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
420 // FUNCTION: [type, callingconv, isproto, paramattr,
421 // linkage, alignment, section, visibility, gc]
422 Vals.push_back(VE.getTypeID(F->getType()));
423 Vals.push_back(F->getCallingConv());
424 Vals.push_back(F->isDeclaration());
425 Vals.push_back(getEncodedLinkage(F));
426 Vals.push_back(VE.getAttributeID(F->getAttributes()));
427 Vals.push_back(Log2_32(F->getAlignment())+1);
428 Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
429 Vals.push_back(getEncodedVisibility(F));
430 Vals.push_back(F->hasGC() ? GCMap[F->getGC()] : 0);
432 unsigned AbbrevToUse = 0;
433 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
434 Vals.clear();
438 // Emit the alias information.
439 for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end();
440 AI != E; ++AI) {
441 Vals.push_back(VE.getTypeID(AI->getType()));
442 Vals.push_back(VE.getValueID(AI->getAliasee()));
443 Vals.push_back(getEncodedLinkage(AI));
444 Vals.push_back(getEncodedVisibility(AI));
445 unsigned AbbrevToUse = 0;
446 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
447 Vals.clear();
452 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
453 const ValueEnumerator &VE,
454 BitstreamWriter &Stream, bool isGlobal) {
455 if (FirstVal == LastVal) return;
457 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
459 unsigned AggregateAbbrev = 0;
460 unsigned String8Abbrev = 0;
461 unsigned CString7Abbrev = 0;
462 unsigned CString6Abbrev = 0;
463 unsigned MDString8Abbrev = 0;
464 unsigned MDString6Abbrev = 0;
465 // If this is a constant pool for the module, emit module-specific abbrevs.
466 if (isGlobal) {
467 // Abbrev for CST_CODE_AGGREGATE.
468 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
469 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
470 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
471 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
472 AggregateAbbrev = Stream.EmitAbbrev(Abbv);
474 // Abbrev for CST_CODE_STRING.
475 Abbv = new BitCodeAbbrev();
476 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
477 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
478 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
479 String8Abbrev = Stream.EmitAbbrev(Abbv);
480 // Abbrev for CST_CODE_CSTRING.
481 Abbv = new BitCodeAbbrev();
482 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
483 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
484 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
485 CString7Abbrev = Stream.EmitAbbrev(Abbv);
486 // Abbrev for CST_CODE_CSTRING.
487 Abbv = new BitCodeAbbrev();
488 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
489 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
490 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
491 CString6Abbrev = Stream.EmitAbbrev(Abbv);
493 // Abbrev for CST_CODE_MDSTRING.
494 Abbv = new BitCodeAbbrev();
495 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_MDSTRING));
496 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
497 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
498 MDString8Abbrev = Stream.EmitAbbrev(Abbv);
499 // Abbrev for CST_CODE_MDSTRING.
500 Abbv = new BitCodeAbbrev();
501 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_MDSTRING));
502 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
503 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
504 MDString6Abbrev = Stream.EmitAbbrev(Abbv);
507 SmallVector<uint64_t, 64> Record;
509 const ValueEnumerator::ValueList &Vals = VE.getValues();
510 const Type *LastTy = 0;
511 for (unsigned i = FirstVal; i != LastVal; ++i) {
512 const Value *V = Vals[i].first;
513 // If we need to switch types, do so now.
514 if (V->getType() != LastTy) {
515 LastTy = V->getType();
516 Record.push_back(VE.getTypeID(LastTy));
517 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
518 CONSTANTS_SETTYPE_ABBREV);
519 Record.clear();
522 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
523 Record.push_back(unsigned(IA->hasSideEffects()));
525 // Add the asm string.
526 const std::string &AsmStr = IA->getAsmString();
527 Record.push_back(AsmStr.size());
528 for (unsigned i = 0, e = AsmStr.size(); i != e; ++i)
529 Record.push_back(AsmStr[i]);
531 // Add the constraint string.
532 const std::string &ConstraintStr = IA->getConstraintString();
533 Record.push_back(ConstraintStr.size());
534 for (unsigned i = 0, e = ConstraintStr.size(); i != e; ++i)
535 Record.push_back(ConstraintStr[i]);
536 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
537 Record.clear();
538 continue;
540 const Constant *C = cast<Constant>(V);
541 unsigned Code = -1U;
542 unsigned AbbrevToUse = 0;
543 if (C->isNullValue()) {
544 Code = bitc::CST_CODE_NULL;
545 } else if (isa<UndefValue>(C)) {
546 Code = bitc::CST_CODE_UNDEF;
547 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
548 if (IV->getBitWidth() <= 64) {
549 int64_t V = IV->getSExtValue();
550 if (V >= 0)
551 Record.push_back(V << 1);
552 else
553 Record.push_back((-V << 1) | 1);
554 Code = bitc::CST_CODE_INTEGER;
555 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
556 } else { // Wide integers, > 64 bits in size.
557 // We have an arbitrary precision integer value to write whose
558 // bit width is > 64. However, in canonical unsigned integer
559 // format it is likely that the high bits are going to be zero.
560 // So, we only write the number of active words.
561 unsigned NWords = IV->getValue().getActiveWords();
562 const uint64_t *RawWords = IV->getValue().getRawData();
563 for (unsigned i = 0; i != NWords; ++i) {
564 int64_t V = RawWords[i];
565 if (V >= 0)
566 Record.push_back(V << 1);
567 else
568 Record.push_back((-V << 1) | 1);
570 Code = bitc::CST_CODE_WIDE_INTEGER;
572 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
573 Code = bitc::CST_CODE_FLOAT;
574 const Type *Ty = CFP->getType();
575 if (Ty == Type::FloatTy || Ty == Type::DoubleTy) {
576 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
577 } else if (Ty == Type::X86_FP80Ty) {
578 // api needed to prevent premature destruction
579 // bits are not in the same order as a normal i80 APInt, compensate.
580 APInt api = CFP->getValueAPF().bitcastToAPInt();
581 const uint64_t *p = api.getRawData();
582 Record.push_back((p[1] << 48) | (p[0] >> 16));
583 Record.push_back(p[0] & 0xffffLL);
584 } else if (Ty == Type::FP128Ty || Ty == Type::PPC_FP128Ty) {
585 APInt api = CFP->getValueAPF().bitcastToAPInt();
586 const uint64_t *p = api.getRawData();
587 Record.push_back(p[0]);
588 Record.push_back(p[1]);
589 } else {
590 assert (0 && "Unknown FP type!");
592 } else if (isa<ConstantArray>(C) && cast<ConstantArray>(C)->isString()) {
593 // Emit constant strings specially.
594 unsigned NumOps = C->getNumOperands();
595 // If this is a null-terminated string, use the denser CSTRING encoding.
596 if (C->getOperand(NumOps-1)->isNullValue()) {
597 Code = bitc::CST_CODE_CSTRING;
598 --NumOps; // Don't encode the null, which isn't allowed by char6.
599 } else {
600 Code = bitc::CST_CODE_STRING;
601 AbbrevToUse = String8Abbrev;
603 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
604 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
605 for (unsigned i = 0; i != NumOps; ++i) {
606 unsigned char V = cast<ConstantInt>(C->getOperand(i))->getZExtValue();
607 Record.push_back(V);
608 isCStr7 &= (V & 128) == 0;
609 if (isCStrChar6)
610 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
613 if (isCStrChar6)
614 AbbrevToUse = CString6Abbrev;
615 else if (isCStr7)
616 AbbrevToUse = CString7Abbrev;
617 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(V) ||
618 isa<ConstantVector>(V)) {
619 Code = bitc::CST_CODE_AGGREGATE;
620 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
621 Record.push_back(VE.getValueID(C->getOperand(i)));
622 AbbrevToUse = AggregateAbbrev;
623 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
624 switch (CE->getOpcode()) {
625 default:
626 if (Instruction::isCast(CE->getOpcode())) {
627 Code = bitc::CST_CODE_CE_CAST;
628 Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
629 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
630 Record.push_back(VE.getValueID(C->getOperand(0)));
631 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
632 } else {
633 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
634 Code = bitc::CST_CODE_CE_BINOP;
635 Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
636 Record.push_back(VE.getValueID(C->getOperand(0)));
637 Record.push_back(VE.getValueID(C->getOperand(1)));
639 break;
640 case Instruction::GetElementPtr:
641 Code = bitc::CST_CODE_CE_GEP;
642 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
643 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
644 Record.push_back(VE.getValueID(C->getOperand(i)));
646 break;
647 case Instruction::Select:
648 Code = bitc::CST_CODE_CE_SELECT;
649 Record.push_back(VE.getValueID(C->getOperand(0)));
650 Record.push_back(VE.getValueID(C->getOperand(1)));
651 Record.push_back(VE.getValueID(C->getOperand(2)));
652 break;
653 case Instruction::ExtractElement:
654 Code = bitc::CST_CODE_CE_EXTRACTELT;
655 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
656 Record.push_back(VE.getValueID(C->getOperand(0)));
657 Record.push_back(VE.getValueID(C->getOperand(1)));
658 break;
659 case Instruction::InsertElement:
660 Code = bitc::CST_CODE_CE_INSERTELT;
661 Record.push_back(VE.getValueID(C->getOperand(0)));
662 Record.push_back(VE.getValueID(C->getOperand(1)));
663 Record.push_back(VE.getValueID(C->getOperand(2)));
664 break;
665 case Instruction::ShuffleVector:
666 // If the return type and argument types are the same, this is a
667 // standard shufflevector instruction. If the types are different,
668 // then the shuffle is widening or truncating the input vectors, and
669 // the argument type must also be encoded.
670 if (C->getType() == C->getOperand(0)->getType()) {
671 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
672 } else {
673 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
674 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
676 Record.push_back(VE.getValueID(C->getOperand(0)));
677 Record.push_back(VE.getValueID(C->getOperand(1)));
678 Record.push_back(VE.getValueID(C->getOperand(2)));
679 break;
680 case Instruction::ICmp:
681 case Instruction::FCmp:
682 case Instruction::VICmp:
683 case Instruction::VFCmp:
684 if (isa<VectorType>(C->getOperand(0)->getType())
685 && (CE->getOpcode() == Instruction::ICmp
686 || CE->getOpcode() == Instruction::FCmp)) {
687 // compare returning vector of Int1Ty
688 assert(0 && "Unsupported constant!");
689 } else {
690 Code = bitc::CST_CODE_CE_CMP;
692 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
693 Record.push_back(VE.getValueID(C->getOperand(0)));
694 Record.push_back(VE.getValueID(C->getOperand(1)));
695 Record.push_back(CE->getPredicate());
696 break;
698 } else if (const MDString *S = dyn_cast<MDString>(C)) {
699 Code = bitc::CST_CODE_MDSTRING;
700 AbbrevToUse = MDString6Abbrev;
701 for (unsigned i = 0, e = S->size(); i != e; ++i) {
702 char V = S->begin()[i];
703 Record.push_back(V);
705 if (!BitCodeAbbrevOp::isChar6(V))
706 AbbrevToUse = MDString8Abbrev;
708 } else if (const MDNode *N = dyn_cast<MDNode>(C)) {
709 Code = bitc::CST_CODE_MDNODE;
710 for (unsigned i = 0, e = N->getNumElements(); i != e; ++i) {
711 if (N->getElement(i)) {
712 Record.push_back(VE.getTypeID(N->getElement(i)->getType()));
713 Record.push_back(VE.getValueID(N->getElement(i)));
714 } else {
715 Record.push_back(VE.getTypeID(Type::VoidTy));
716 Record.push_back(0);
719 } else {
720 assert(0 && "Unknown constant!");
722 Stream.EmitRecord(Code, Record, AbbrevToUse);
723 Record.clear();
726 Stream.ExitBlock();
729 static void WriteModuleConstants(const ValueEnumerator &VE,
730 BitstreamWriter &Stream) {
731 const ValueEnumerator::ValueList &Vals = VE.getValues();
733 // Find the first constant to emit, which is the first non-globalvalue value.
734 // We know globalvalues have been emitted by WriteModuleInfo.
735 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
736 if (!isa<GlobalValue>(Vals[i].first)) {
737 WriteConstants(i, Vals.size(), VE, Stream, true);
738 return;
743 /// PushValueAndType - The file has to encode both the value and type id for
744 /// many values, because we need to know what type to create for forward
745 /// references. However, most operands are not forward references, so this type
746 /// field is not needed.
748 /// This function adds V's value ID to Vals. If the value ID is higher than the
749 /// instruction ID, then it is a forward reference, and it also includes the
750 /// type ID.
751 static bool PushValueAndType(const Value *V, unsigned InstID,
752 SmallVector<unsigned, 64> &Vals,
753 ValueEnumerator &VE) {
754 unsigned ValID = VE.getValueID(V);
755 Vals.push_back(ValID);
756 if (ValID >= InstID) {
757 Vals.push_back(VE.getTypeID(V->getType()));
758 return true;
760 return false;
763 /// WriteInstruction - Emit an instruction to the specified stream.
764 static void WriteInstruction(const Instruction &I, unsigned InstID,
765 ValueEnumerator &VE, BitstreamWriter &Stream,
766 SmallVector<unsigned, 64> &Vals) {
767 unsigned Code = 0;
768 unsigned AbbrevToUse = 0;
769 switch (I.getOpcode()) {
770 default:
771 if (Instruction::isCast(I.getOpcode())) {
772 Code = bitc::FUNC_CODE_INST_CAST;
773 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
774 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
775 Vals.push_back(VE.getTypeID(I.getType()));
776 Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
777 } else {
778 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
779 Code = bitc::FUNC_CODE_INST_BINOP;
780 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
781 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
782 Vals.push_back(VE.getValueID(I.getOperand(1)));
783 Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
785 break;
787 case Instruction::GetElementPtr:
788 Code = bitc::FUNC_CODE_INST_GEP;
789 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
790 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
791 break;
792 case Instruction::ExtractValue: {
793 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
794 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
795 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
796 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
797 Vals.push_back(*i);
798 break;
800 case Instruction::InsertValue: {
801 Code = bitc::FUNC_CODE_INST_INSERTVAL;
802 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
803 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
804 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
805 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
806 Vals.push_back(*i);
807 break;
809 case Instruction::Select:
810 Code = bitc::FUNC_CODE_INST_VSELECT;
811 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
812 Vals.push_back(VE.getValueID(I.getOperand(2)));
813 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
814 break;
815 case Instruction::ExtractElement:
816 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
817 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
818 Vals.push_back(VE.getValueID(I.getOperand(1)));
819 break;
820 case Instruction::InsertElement:
821 Code = bitc::FUNC_CODE_INST_INSERTELT;
822 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
823 Vals.push_back(VE.getValueID(I.getOperand(1)));
824 Vals.push_back(VE.getValueID(I.getOperand(2)));
825 break;
826 case Instruction::ShuffleVector:
827 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
828 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
829 Vals.push_back(VE.getValueID(I.getOperand(1)));
830 Vals.push_back(VE.getValueID(I.getOperand(2)));
831 break;
832 case Instruction::ICmp:
833 case Instruction::FCmp:
834 case Instruction::VICmp:
835 case Instruction::VFCmp:
836 if (I.getOpcode() == Instruction::ICmp
837 || I.getOpcode() == Instruction::FCmp) {
838 // compare returning Int1Ty or vector of Int1Ty
839 Code = bitc::FUNC_CODE_INST_CMP2;
840 } else {
841 Code = bitc::FUNC_CODE_INST_CMP;
843 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
844 Vals.push_back(VE.getValueID(I.getOperand(1)));
845 Vals.push_back(cast<CmpInst>(I).getPredicate());
846 break;
848 case Instruction::Ret:
850 Code = bitc::FUNC_CODE_INST_RET;
851 unsigned NumOperands = I.getNumOperands();
852 if (NumOperands == 0)
853 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
854 else if (NumOperands == 1) {
855 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
856 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
857 } else {
858 for (unsigned i = 0, e = NumOperands; i != e; ++i)
859 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
862 break;
863 case Instruction::Br:
865 Code = bitc::FUNC_CODE_INST_BR;
866 BranchInst &II(cast<BranchInst>(I));
867 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
868 if (II.isConditional()) {
869 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
870 Vals.push_back(VE.getValueID(II.getCondition()));
873 break;
874 case Instruction::Switch:
875 Code = bitc::FUNC_CODE_INST_SWITCH;
876 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
877 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
878 Vals.push_back(VE.getValueID(I.getOperand(i)));
879 break;
880 case Instruction::Invoke: {
881 const InvokeInst *II = cast<InvokeInst>(&I);
882 const Value *Callee(II->getCalledValue());
883 const PointerType *PTy = cast<PointerType>(Callee->getType());
884 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
885 Code = bitc::FUNC_CODE_INST_INVOKE;
887 Vals.push_back(VE.getAttributeID(II->getAttributes()));
888 Vals.push_back(II->getCallingConv());
889 Vals.push_back(VE.getValueID(II->getNormalDest()));
890 Vals.push_back(VE.getValueID(II->getUnwindDest()));
891 PushValueAndType(Callee, InstID, Vals, VE);
893 // Emit value #'s for the fixed parameters.
894 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
895 Vals.push_back(VE.getValueID(I.getOperand(i+3))); // fixed param.
897 // Emit type/value pairs for varargs params.
898 if (FTy->isVarArg()) {
899 for (unsigned i = 3+FTy->getNumParams(), e = I.getNumOperands();
900 i != e; ++i)
901 PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
903 break;
905 case Instruction::Unwind:
906 Code = bitc::FUNC_CODE_INST_UNWIND;
907 break;
908 case Instruction::Unreachable:
909 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
910 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
911 break;
913 case Instruction::PHI:
914 Code = bitc::FUNC_CODE_INST_PHI;
915 Vals.push_back(VE.getTypeID(I.getType()));
916 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
917 Vals.push_back(VE.getValueID(I.getOperand(i)));
918 break;
920 case Instruction::Malloc:
921 Code = bitc::FUNC_CODE_INST_MALLOC;
922 Vals.push_back(VE.getTypeID(I.getType()));
923 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
924 Vals.push_back(Log2_32(cast<MallocInst>(I).getAlignment())+1);
925 break;
927 case Instruction::Free:
928 Code = bitc::FUNC_CODE_INST_FREE;
929 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
930 break;
932 case Instruction::Alloca:
933 Code = bitc::FUNC_CODE_INST_ALLOCA;
934 Vals.push_back(VE.getTypeID(I.getType()));
935 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
936 Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1);
937 break;
939 case Instruction::Load:
940 Code = bitc::FUNC_CODE_INST_LOAD;
941 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) // ptr
942 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
944 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
945 Vals.push_back(cast<LoadInst>(I).isVolatile());
946 break;
947 case Instruction::Store:
948 Code = bitc::FUNC_CODE_INST_STORE2;
949 PushValueAndType(I.getOperand(1), InstID, Vals, VE); // ptrty + ptr
950 Vals.push_back(VE.getValueID(I.getOperand(0))); // val.
951 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
952 Vals.push_back(cast<StoreInst>(I).isVolatile());
953 break;
954 case Instruction::Call: {
955 const PointerType *PTy = cast<PointerType>(I.getOperand(0)->getType());
956 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
958 Code = bitc::FUNC_CODE_INST_CALL;
960 const CallInst *CI = cast<CallInst>(&I);
961 Vals.push_back(VE.getAttributeID(CI->getAttributes()));
962 Vals.push_back((CI->getCallingConv() << 1) | unsigned(CI->isTailCall()));
963 PushValueAndType(CI->getOperand(0), InstID, Vals, VE); // Callee
965 // Emit value #'s for the fixed parameters.
966 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
967 Vals.push_back(VE.getValueID(I.getOperand(i+1))); // fixed param.
969 // Emit type/value pairs for varargs params.
970 if (FTy->isVarArg()) {
971 unsigned NumVarargs = I.getNumOperands()-1-FTy->getNumParams();
972 for (unsigned i = I.getNumOperands()-NumVarargs, e = I.getNumOperands();
973 i != e; ++i)
974 PushValueAndType(I.getOperand(i), InstID, Vals, VE); // varargs
976 break;
978 case Instruction::VAArg:
979 Code = bitc::FUNC_CODE_INST_VAARG;
980 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
981 Vals.push_back(VE.getValueID(I.getOperand(0))); // valist.
982 Vals.push_back(VE.getTypeID(I.getType())); // restype.
983 break;
986 Stream.EmitRecord(Code, Vals, AbbrevToUse);
987 Vals.clear();
990 // Emit names for globals/functions etc.
991 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
992 const ValueEnumerator &VE,
993 BitstreamWriter &Stream) {
994 if (VST.empty()) return;
995 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
997 // FIXME: Set up the abbrev, we know how many values there are!
998 // FIXME: We know if the type names can use 7-bit ascii.
999 SmallVector<unsigned, 64> NameVals;
1001 for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
1002 SI != SE; ++SI) {
1004 const ValueName &Name = *SI;
1006 // Figure out the encoding to use for the name.
1007 bool is7Bit = true;
1008 bool isChar6 = true;
1009 for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
1010 C != E; ++C) {
1011 if (isChar6)
1012 isChar6 = BitCodeAbbrevOp::isChar6(*C);
1013 if ((unsigned char)*C & 128) {
1014 is7Bit = false;
1015 break; // don't bother scanning the rest.
1019 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
1021 // VST_ENTRY: [valueid, namechar x N]
1022 // VST_BBENTRY: [bbid, namechar x N]
1023 unsigned Code;
1024 if (isa<BasicBlock>(SI->getValue())) {
1025 Code = bitc::VST_CODE_BBENTRY;
1026 if (isChar6)
1027 AbbrevToUse = VST_BBENTRY_6_ABBREV;
1028 } else {
1029 Code = bitc::VST_CODE_ENTRY;
1030 if (isChar6)
1031 AbbrevToUse = VST_ENTRY_6_ABBREV;
1032 else if (is7Bit)
1033 AbbrevToUse = VST_ENTRY_7_ABBREV;
1036 NameVals.push_back(VE.getValueID(SI->getValue()));
1037 for (const char *P = Name.getKeyData(),
1038 *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
1039 NameVals.push_back((unsigned char)*P);
1041 // Emit the finished record.
1042 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
1043 NameVals.clear();
1045 Stream.ExitBlock();
1048 /// WriteFunction - Emit a function body to the module stream.
1049 static void WriteFunction(const Function &F, ValueEnumerator &VE,
1050 BitstreamWriter &Stream) {
1051 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
1052 VE.incorporateFunction(F);
1054 SmallVector<unsigned, 64> Vals;
1056 // Emit the number of basic blocks, so the reader can create them ahead of
1057 // time.
1058 Vals.push_back(VE.getBasicBlocks().size());
1059 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
1060 Vals.clear();
1062 // If there are function-local constants, emit them now.
1063 unsigned CstStart, CstEnd;
1064 VE.getFunctionConstantRange(CstStart, CstEnd);
1065 WriteConstants(CstStart, CstEnd, VE, Stream, false);
1067 // Keep a running idea of what the instruction ID is.
1068 unsigned InstID = CstEnd;
1070 // Finally, emit all the instructions, in order.
1071 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1072 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1073 I != E; ++I) {
1074 WriteInstruction(*I, InstID, VE, Stream, Vals);
1075 if (I->getType() != Type::VoidTy)
1076 ++InstID;
1079 // Emit names for all the instructions etc.
1080 WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
1082 VE.purgeFunction();
1083 Stream.ExitBlock();
1086 /// WriteTypeSymbolTable - Emit a block for the specified type symtab.
1087 static void WriteTypeSymbolTable(const TypeSymbolTable &TST,
1088 const ValueEnumerator &VE,
1089 BitstreamWriter &Stream) {
1090 if (TST.empty()) return;
1092 Stream.EnterSubblock(bitc::TYPE_SYMTAB_BLOCK_ID, 3);
1094 // 7-bit fixed width VST_CODE_ENTRY strings.
1095 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1096 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1097 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1098 Log2_32_Ceil(VE.getTypes().size()+1)));
1099 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1100 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1101 unsigned V7Abbrev = Stream.EmitAbbrev(Abbv);
1103 SmallVector<unsigned, 64> NameVals;
1105 for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end();
1106 TI != TE; ++TI) {
1107 // TST_ENTRY: [typeid, namechar x N]
1108 NameVals.push_back(VE.getTypeID(TI->second));
1110 const std::string &Str = TI->first;
1111 bool is7Bit = true;
1112 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1113 NameVals.push_back((unsigned char)Str[i]);
1114 if (Str[i] & 128)
1115 is7Bit = false;
1118 // Emit the finished record.
1119 Stream.EmitRecord(bitc::VST_CODE_ENTRY, NameVals, is7Bit ? V7Abbrev : 0);
1120 NameVals.clear();
1123 Stream.ExitBlock();
1126 // Emit blockinfo, which defines the standard abbreviations etc.
1127 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
1128 // We only want to emit block info records for blocks that have multiple
1129 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK. Other
1130 // blocks can defined their abbrevs inline.
1131 Stream.EnterBlockInfoBlock(2);
1133 { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
1134 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1135 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
1136 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1137 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1138 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1139 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1140 Abbv) != VST_ENTRY_8_ABBREV)
1141 assert(0 && "Unexpected abbrev ordering!");
1144 { // 7-bit fixed width VST_ENTRY strings.
1145 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1146 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1147 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1148 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1149 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1150 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1151 Abbv) != VST_ENTRY_7_ABBREV)
1152 assert(0 && "Unexpected abbrev ordering!");
1154 { // 6-bit char6 VST_ENTRY strings.
1155 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1156 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1157 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1158 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1159 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1160 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1161 Abbv) != VST_ENTRY_6_ABBREV)
1162 assert(0 && "Unexpected abbrev ordering!");
1164 { // 6-bit char6 VST_BBENTRY strings.
1165 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1166 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
1167 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1168 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1169 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1170 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1171 Abbv) != VST_BBENTRY_6_ABBREV)
1172 assert(0 && "Unexpected abbrev ordering!");
1177 { // SETTYPE abbrev for CONSTANTS_BLOCK.
1178 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1179 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
1180 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1181 Log2_32_Ceil(VE.getTypes().size()+1)));
1182 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1183 Abbv) != CONSTANTS_SETTYPE_ABBREV)
1184 assert(0 && "Unexpected abbrev ordering!");
1187 { // INTEGER abbrev for CONSTANTS_BLOCK.
1188 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1189 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
1190 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1191 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1192 Abbv) != CONSTANTS_INTEGER_ABBREV)
1193 assert(0 && "Unexpected abbrev ordering!");
1196 { // CE_CAST abbrev for CONSTANTS_BLOCK.
1197 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1198 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
1199 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
1200 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
1201 Log2_32_Ceil(VE.getTypes().size()+1)));
1202 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
1204 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1205 Abbv) != CONSTANTS_CE_CAST_Abbrev)
1206 assert(0 && "Unexpected abbrev ordering!");
1208 { // NULL abbrev for CONSTANTS_BLOCK.
1209 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1210 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
1211 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1212 Abbv) != CONSTANTS_NULL_Abbrev)
1213 assert(0 && "Unexpected abbrev ordering!");
1216 // FIXME: This should only use space for first class types!
1218 { // INST_LOAD abbrev for FUNCTION_BLOCK.
1219 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1220 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
1221 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
1222 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
1223 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
1224 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1225 Abbv) != FUNCTION_INST_LOAD_ABBREV)
1226 assert(0 && "Unexpected abbrev ordering!");
1228 { // INST_BINOP abbrev for FUNCTION_BLOCK.
1229 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1230 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1231 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1232 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1233 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1234 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1235 Abbv) != FUNCTION_INST_BINOP_ABBREV)
1236 assert(0 && "Unexpected abbrev ordering!");
1238 { // INST_CAST abbrev for FUNCTION_BLOCK.
1239 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1240 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
1241 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
1242 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
1243 Log2_32_Ceil(VE.getTypes().size()+1)));
1244 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1245 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1246 Abbv) != FUNCTION_INST_CAST_ABBREV)
1247 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 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1254 Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
1255 assert(0 && "Unexpected abbrev ordering!");
1257 { // INST_RET abbrev for FUNCTION_BLOCK.
1258 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1259 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1260 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
1261 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1262 Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
1263 assert(0 && "Unexpected abbrev ordering!");
1265 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
1266 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1267 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
1268 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1269 Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
1270 assert(0 && "Unexpected abbrev ordering!");
1273 Stream.ExitBlock();
1277 /// WriteModule - Emit the specified module to the bitstream.
1278 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
1279 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
1281 // Emit the version number if it is non-zero.
1282 if (CurVersion) {
1283 SmallVector<unsigned, 1> Vals;
1284 Vals.push_back(CurVersion);
1285 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
1288 // Analyze the module, enumerating globals, functions, etc.
1289 ValueEnumerator VE(M);
1291 // Emit blockinfo, which defines the standard abbreviations etc.
1292 WriteBlockInfo(VE, Stream);
1294 // Emit information about parameter attributes.
1295 WriteAttributeTable(VE, Stream);
1297 // Emit information describing all of the types in the module.
1298 WriteTypeTable(VE, Stream);
1300 // Emit top-level description of module, including target triple, inline asm,
1301 // descriptors for global variables, and function prototype info.
1302 WriteModuleInfo(M, VE, Stream);
1304 // Emit constants.
1305 WriteModuleConstants(VE, Stream);
1307 // If we have any aggregate values in the value table, purge them - these can
1308 // only be used to initialize global variables. Doing so makes the value
1309 // namespace smaller for code in functions.
1310 int NumNonAggregates = VE.PurgeAggregateValues();
1311 if (NumNonAggregates != -1) {
1312 SmallVector<unsigned, 1> Vals;
1313 Vals.push_back(NumNonAggregates);
1314 Stream.EmitRecord(bitc::MODULE_CODE_PURGEVALS, Vals);
1317 // Emit function bodies.
1318 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1319 if (!I->isDeclaration())
1320 WriteFunction(*I, VE, Stream);
1322 // Emit the type symbol table information.
1323 WriteTypeSymbolTable(M->getTypeSymbolTable(), VE, Stream);
1325 // Emit names for globals/functions etc.
1326 WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
1328 Stream.ExitBlock();
1331 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
1332 /// header and trailer to make it compatible with the system archiver. To do
1333 /// this we emit the following header, and then emit a trailer that pads the
1334 /// file out to be a multiple of 16 bytes.
1335 ///
1336 /// struct bc_header {
1337 /// uint32_t Magic; // 0x0B17C0DE
1338 /// uint32_t Version; // Version, currently always 0.
1339 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
1340 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
1341 /// uint32_t CPUType; // CPU specifier.
1342 /// ... potentially more later ...
1343 /// };
1344 enum {
1345 DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
1346 DarwinBCHeaderSize = 5*4
1349 static void EmitDarwinBCHeader(BitstreamWriter &Stream,
1350 const std::string &TT) {
1351 unsigned CPUType = ~0U;
1353 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*. The CPUType is a
1354 // magic number from /usr/include/mach/machine.h. It is ok to reproduce the
1355 // specific constants here because they are implicitly part of the Darwin ABI.
1356 enum {
1357 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
1358 DARWIN_CPU_TYPE_X86 = 7,
1359 DARWIN_CPU_TYPE_POWERPC = 18
1362 if (TT.find("x86_64-") == 0)
1363 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
1364 else if (TT.size() >= 5 && TT[0] == 'i' && TT[2] == '8' && TT[3] == '6' &&
1365 TT[4] == '-' && TT[1] - '3' < 6)
1366 CPUType = DARWIN_CPU_TYPE_X86;
1367 else if (TT.find("powerpc-") == 0)
1368 CPUType = DARWIN_CPU_TYPE_POWERPC;
1369 else if (TT.find("powerpc64-") == 0)
1370 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
1372 // Traditional Bitcode starts after header.
1373 unsigned BCOffset = DarwinBCHeaderSize;
1375 Stream.Emit(0x0B17C0DE, 32);
1376 Stream.Emit(0 , 32); // Version.
1377 Stream.Emit(BCOffset , 32);
1378 Stream.Emit(0 , 32); // Filled in later.
1379 Stream.Emit(CPUType , 32);
1382 /// EmitDarwinBCTrailer - Emit the darwin epilog after the bitcode file and
1383 /// finalize the header.
1384 static void EmitDarwinBCTrailer(BitstreamWriter &Stream, unsigned BufferSize) {
1385 // Update the size field in the header.
1386 Stream.BackpatchWord(DarwinBCSizeFieldOffset, BufferSize-DarwinBCHeaderSize);
1388 // If the file is not a multiple of 16 bytes, insert dummy padding.
1389 while (BufferSize & 15) {
1390 Stream.Emit(0, 8);
1391 ++BufferSize;
1396 /// WriteBitcodeToFile - Write the specified module to the specified output
1397 /// stream.
1398 void llvm::WriteBitcodeToFile(const Module *M, std::ostream &Out) {
1399 raw_os_ostream RawOut(Out);
1400 // If writing to stdout, set binary mode.
1401 if (llvm::cout == Out)
1402 sys::Program::ChangeStdoutToBinary();
1403 WriteBitcodeToFile(M, RawOut);
1406 /// WriteBitcodeToFile - Write the specified module to the specified output
1407 /// stream.
1408 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out) {
1409 std::vector<unsigned char> Buffer;
1410 BitstreamWriter Stream(Buffer);
1412 Buffer.reserve(256*1024);
1414 WriteBitcodeToStream( M, Stream );
1416 // If writing to stdout, set binary mode.
1417 if (&llvm::outs() == &Out)
1418 sys::Program::ChangeStdoutToBinary();
1420 // Write the generated bitstream to "Out".
1421 Out.write((char*)&Buffer.front(), Buffer.size());
1423 // Make sure it hits disk now.
1424 Out.flush();
1427 /// WriteBitcodeToStream - Write the specified module to the specified output
1428 /// stream.
1429 void llvm::WriteBitcodeToStream(const Module *M, BitstreamWriter &Stream) {
1430 // If this is darwin, emit a file header and trailer if needed.
1431 bool isDarwin = M->getTargetTriple().find("-darwin") != std::string::npos;
1432 if (isDarwin)
1433 EmitDarwinBCHeader(Stream, M->getTargetTriple());
1435 // Emit the file header.
1436 Stream.Emit((unsigned)'B', 8);
1437 Stream.Emit((unsigned)'C', 8);
1438 Stream.Emit(0x0, 4);
1439 Stream.Emit(0xC, 4);
1440 Stream.Emit(0xE, 4);
1441 Stream.Emit(0xD, 4);
1443 // Emit the module.
1444 WriteModule(M, Stream);
1446 if (isDarwin)
1447 EmitDarwinBCTrailer(Stream, Stream.getBuffer().size());