blob: fdaa9be5bb615b5b586c463387a32d4759e0502c [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===--- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Bitcode writer implementation.
11//
12//===----------------------------------------------------------------------===//
13
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/ParameterAttributes.h"
24#include "llvm/TypeSymbolTable.h"
25#include "llvm/ValueSymbolTable.h"
26#include "llvm/Support/MathExtras.h"
27using namespace llvm;
28
29/// These are manifest constants used by the bitcode writer. They do not need to
30/// be kept in sync with the reader, but need to be consistent within this file.
31enum {
32 CurVersion = 0,
33
34 // VALUE_SYMTAB_BLOCK abbrev id's.
35 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
36 VST_ENTRY_7_ABBREV,
37 VST_ENTRY_6_ABBREV,
38 VST_BBENTRY_6_ABBREV,
39
40 // CONSTANTS_BLOCK abbrev id's.
41 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
42 CONSTANTS_INTEGER_ABBREV,
43 CONSTANTS_CE_CAST_Abbrev,
44 CONSTANTS_NULL_Abbrev,
45
46 // FUNCTION_BLOCK abbrev id's.
47 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
48 FUNCTION_INST_BINOP_ABBREV,
49 FUNCTION_INST_CAST_ABBREV,
50 FUNCTION_INST_RET_VOID_ABBREV,
51 FUNCTION_INST_RET_VAL_ABBREV,
52 FUNCTION_INST_UNREACHABLE_ABBREV
53};
54
55
56static unsigned GetEncodedCastOpcode(unsigned Opcode) {
57 switch (Opcode) {
58 default: assert(0 && "Unknown cast instruction!");
59 case Instruction::Trunc : return bitc::CAST_TRUNC;
60 case Instruction::ZExt : return bitc::CAST_ZEXT;
61 case Instruction::SExt : return bitc::CAST_SEXT;
62 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
63 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
64 case Instruction::UIToFP : return bitc::CAST_UITOFP;
65 case Instruction::SIToFP : return bitc::CAST_SITOFP;
66 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
67 case Instruction::FPExt : return bitc::CAST_FPEXT;
68 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
69 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
70 case Instruction::BitCast : return bitc::CAST_BITCAST;
71 }
72}
73
74static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
75 switch (Opcode) {
76 default: assert(0 && "Unknown binary instruction!");
77 case Instruction::Add: return bitc::BINOP_ADD;
78 case Instruction::Sub: return bitc::BINOP_SUB;
79 case Instruction::Mul: return bitc::BINOP_MUL;
80 case Instruction::UDiv: return bitc::BINOP_UDIV;
81 case Instruction::FDiv:
82 case Instruction::SDiv: return bitc::BINOP_SDIV;
83 case Instruction::URem: return bitc::BINOP_UREM;
84 case Instruction::FRem:
85 case Instruction::SRem: return bitc::BINOP_SREM;
86 case Instruction::Shl: return bitc::BINOP_SHL;
87 case Instruction::LShr: return bitc::BINOP_LSHR;
88 case Instruction::AShr: return bitc::BINOP_ASHR;
89 case Instruction::And: return bitc::BINOP_AND;
90 case Instruction::Or: return bitc::BINOP_OR;
91 case Instruction::Xor: return bitc::BINOP_XOR;
92 }
93}
94
95
96
97static void WriteStringRecord(unsigned Code, const std::string &Str,
98 unsigned AbbrevToUse, BitstreamWriter &Stream) {
99 SmallVector<unsigned, 64> Vals;
100
101 // Code: [strchar x N]
102 for (unsigned i = 0, e = Str.size(); i != e; ++i)
103 Vals.push_back(Str[i]);
104
105 // Emit the finished record.
106 Stream.EmitRecord(Code, Vals, AbbrevToUse);
107}
108
109// Emit information about parameter attributes.
110static void WriteParamAttrTable(const ValueEnumerator &VE,
111 BitstreamWriter &Stream) {
112 const std::vector<const ParamAttrsList*> &Attrs = VE.getParamAttrs();
113 if (Attrs.empty()) return;
114
115 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
116
117 SmallVector<uint64_t, 64> Record;
118 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
119 const ParamAttrsList *A = Attrs[i];
120 for (unsigned op = 0, e = A->size(); op != e; ++op) {
121 Record.push_back(A->getParamIndex(op));
122 Record.push_back(A->getParamAttrsAtIndex(op));
123 }
124
125 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
126 Record.clear();
127 }
128
129 Stream.ExitBlock();
130}
131
132/// WriteTypeTable - Write out the type table for a module.
133static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
134 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
135
136 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID, 4 /*count from # abbrevs */);
137 SmallVector<uint64_t, 64> TypeVals;
138
139 // Abbrev for TYPE_CODE_POINTER.
140 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
141 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
142 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
143 Log2_32_Ceil(VE.getTypes().size()+1)));
144 unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
145
146 // Abbrev for TYPE_CODE_FUNCTION.
147 Abbv = new BitCodeAbbrev();
148 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
149 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
150 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
151 Log2_32_Ceil(VE.getParamAttrs().size()+1)));
152 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
153 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
154 Log2_32_Ceil(VE.getTypes().size()+1)));
155 unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
156
157 // Abbrev for TYPE_CODE_STRUCT.
158 Abbv = new BitCodeAbbrev();
159 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT));
160 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
161 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
162 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
163 Log2_32_Ceil(VE.getTypes().size()+1)));
164 unsigned StructAbbrev = Stream.EmitAbbrev(Abbv);
165
166 // Abbrev for TYPE_CODE_ARRAY.
167 Abbv = new BitCodeAbbrev();
168 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
169 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
170 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
171 Log2_32_Ceil(VE.getTypes().size()+1)));
172 unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
173
174 // Emit an entry count so the reader can reserve space.
175 TypeVals.push_back(TypeList.size());
176 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
177 TypeVals.clear();
178
179 // Loop over all of the types, emitting each in turn.
180 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
181 const Type *T = TypeList[i].first;
182 int AbbrevToUse = 0;
183 unsigned Code = 0;
184
185 switch (T->getTypeID()) {
186 default: assert(0 && "Unknown type!");
187 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
188 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
189 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
Dale Johannesenf325d9f2007-08-03 01:03:46 +0000190 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
191 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
192 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000193 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
194 case Type::OpaqueTyID: Code = bitc::TYPE_CODE_OPAQUE; break;
195 case Type::IntegerTyID:
196 // INTEGER: [width]
197 Code = bitc::TYPE_CODE_INTEGER;
198 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
199 break;
200 case Type::PointerTyID:
201 // POINTER: [pointee type]
202 Code = bitc::TYPE_CODE_POINTER;
203 TypeVals.push_back(VE.getTypeID(cast<PointerType>(T)->getElementType()));
204 AbbrevToUse = PtrAbbrev;
205 break;
206
207 case Type::FunctionTyID: {
208 const FunctionType *FT = cast<FunctionType>(T);
209 // FUNCTION: [isvararg, attrid, retty, paramty x N]
210 Code = bitc::TYPE_CODE_FUNCTION;
211 TypeVals.push_back(FT->isVarArg());
212 TypeVals.push_back(VE.getParamAttrID(FT->getParamAttrs()));
213 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
214 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
215 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
216 AbbrevToUse = FunctionAbbrev;
217 break;
218 }
219 case Type::StructTyID: {
220 const StructType *ST = cast<StructType>(T);
221 // STRUCT: [ispacked, eltty x N]
222 Code = bitc::TYPE_CODE_STRUCT;
223 TypeVals.push_back(ST->isPacked());
224 // Output all of the element types.
225 for (StructType::element_iterator I = ST->element_begin(),
226 E = ST->element_end(); I != E; ++I)
227 TypeVals.push_back(VE.getTypeID(*I));
228 AbbrevToUse = StructAbbrev;
229 break;
230 }
231 case Type::ArrayTyID: {
232 const ArrayType *AT = cast<ArrayType>(T);
233 // ARRAY: [numelts, eltty]
234 Code = bitc::TYPE_CODE_ARRAY;
235 TypeVals.push_back(AT->getNumElements());
236 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
237 AbbrevToUse = ArrayAbbrev;
238 break;
239 }
240 case Type::VectorTyID: {
241 const VectorType *VT = cast<VectorType>(T);
242 // VECTOR [numelts, eltty]
243 Code = bitc::TYPE_CODE_VECTOR;
244 TypeVals.push_back(VT->getNumElements());
245 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
246 break;
247 }
248 }
249
250 // Emit the finished record.
251 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
252 TypeVals.clear();
253 }
254
255 Stream.ExitBlock();
256}
257
258static unsigned getEncodedLinkage(const GlobalValue *GV) {
259 switch (GV->getLinkage()) {
260 default: assert(0 && "Invalid linkage!");
261 case GlobalValue::GhostLinkage: // Map ghost linkage onto external.
262 case GlobalValue::ExternalLinkage: return 0;
263 case GlobalValue::WeakLinkage: return 1;
264 case GlobalValue::AppendingLinkage: return 2;
265 case GlobalValue::InternalLinkage: return 3;
266 case GlobalValue::LinkOnceLinkage: return 4;
267 case GlobalValue::DLLImportLinkage: return 5;
268 case GlobalValue::DLLExportLinkage: return 6;
269 case GlobalValue::ExternalWeakLinkage: return 7;
270 }
271}
272
273static unsigned getEncodedVisibility(const GlobalValue *GV) {
274 switch (GV->getVisibility()) {
275 default: assert(0 && "Invalid visibility!");
276 case GlobalValue::DefaultVisibility: return 0;
277 case GlobalValue::HiddenVisibility: return 1;
278 case GlobalValue::ProtectedVisibility: return 2;
279 }
280}
281
282// Emit top-level description of module, including target triple, inline asm,
283// descriptors for global variables, and function prototype info.
284static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
285 BitstreamWriter &Stream) {
286 // Emit the list of dependent libraries for the Module.
287 for (Module::lib_iterator I = M->lib_begin(), E = M->lib_end(); I != E; ++I)
288 WriteStringRecord(bitc::MODULE_CODE_DEPLIB, *I, 0/*TODO*/, Stream);
289
290 // Emit various pieces of data attached to a module.
291 if (!M->getTargetTriple().empty())
292 WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
293 0/*TODO*/, Stream);
294 if (!M->getDataLayout().empty())
295 WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(),
296 0/*TODO*/, Stream);
297 if (!M->getModuleInlineAsm().empty())
298 WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
299 0/*TODO*/, Stream);
300
301 // Emit information about sections, computing how many there are. Also
302 // compute the maximum alignment value.
303 std::map<std::string, unsigned> SectionMap;
304 unsigned MaxAlignment = 0;
305 unsigned MaxGlobalType = 0;
306 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
307 GV != E; ++GV) {
308 MaxAlignment = std::max(MaxAlignment, GV->getAlignment());
309 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType()));
310
311 if (!GV->hasSection()) continue;
312 // Give section names unique ID's.
313 unsigned &Entry = SectionMap[GV->getSection()];
314 if (Entry != 0) continue;
315 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(),
316 0/*TODO*/, Stream);
317 Entry = SectionMap.size();
318 }
319 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
320 MaxAlignment = std::max(MaxAlignment, F->getAlignment());
321 if (!F->hasSection()) continue;
322 // Give section names unique ID's.
323 unsigned &Entry = SectionMap[F->getSection()];
324 if (Entry != 0) continue;
325 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(),
326 0/*TODO*/, Stream);
327 Entry = SectionMap.size();
328 }
329
330 // Emit abbrev for globals, now that we know # sections and max alignment.
331 unsigned SimpleGVarAbbrev = 0;
332 if (!M->global_empty()) {
333 // Add an abbrev for common globals with no visibility or thread localness.
334 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
335 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
336 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
337 Log2_32_Ceil(MaxGlobalType+1)));
338 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Constant.
339 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
340 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Linkage.
341 if (MaxAlignment == 0) // Alignment.
342 Abbv->Add(BitCodeAbbrevOp(0));
343 else {
344 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
345 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
346 Log2_32_Ceil(MaxEncAlignment+1)));
347 }
348 if (SectionMap.empty()) // Section.
349 Abbv->Add(BitCodeAbbrevOp(0));
350 else
351 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
352 Log2_32_Ceil(SectionMap.size()+1)));
353 // Don't bother emitting vis + thread local.
354 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
355 }
356
357 // Emit the global variable information.
358 SmallVector<unsigned, 64> Vals;
359 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
360 GV != E; ++GV) {
361 unsigned AbbrevToUse = 0;
362
363 // GLOBALVAR: [type, isconst, initid,
364 // linkage, alignment, section, visibility, threadlocal]
365 Vals.push_back(VE.getTypeID(GV->getType()));
366 Vals.push_back(GV->isConstant());
367 Vals.push_back(GV->isDeclaration() ? 0 :
368 (VE.getValueID(GV->getInitializer()) + 1));
369 Vals.push_back(getEncodedLinkage(GV));
370 Vals.push_back(Log2_32(GV->getAlignment())+1);
371 Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0);
372 if (GV->isThreadLocal() ||
373 GV->getVisibility() != GlobalValue::DefaultVisibility) {
374 Vals.push_back(getEncodedVisibility(GV));
375 Vals.push_back(GV->isThreadLocal());
376 } else {
377 AbbrevToUse = SimpleGVarAbbrev;
378 }
379
380 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
381 Vals.clear();
382 }
383
384 // Emit the function proto information.
385 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
386 // FUNCTION: [type, callingconv, isproto, linkage, alignment, section,
387 // visibility]
388 Vals.push_back(VE.getTypeID(F->getType()));
389 Vals.push_back(F->getCallingConv());
390 Vals.push_back(F->isDeclaration());
391 Vals.push_back(getEncodedLinkage(F));
392
393 // Note: we emit the param attr ID number for the function type of this
394 // function. In the future, we intend for attrs to be properties of
395 // functions, instead of on the type. This is to support this future work.
396 Vals.push_back(VE.getParamAttrID(F->getFunctionType()->getParamAttrs()));
397
398 Vals.push_back(Log2_32(F->getAlignment())+1);
399 Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
400 Vals.push_back(getEncodedVisibility(F));
401
402 unsigned AbbrevToUse = 0;
403 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
404 Vals.clear();
405 }
406
407
408 // Emit the alias information.
409 for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end();
410 AI != E; ++AI) {
411 Vals.push_back(VE.getTypeID(AI->getType()));
412 Vals.push_back(VE.getValueID(AI->getAliasee()));
413 Vals.push_back(getEncodedLinkage(AI));
414 unsigned AbbrevToUse = 0;
415 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
416 Vals.clear();
417 }
418}
419
420
421static void WriteConstants(unsigned FirstVal, unsigned LastVal,
422 const ValueEnumerator &VE,
423 BitstreamWriter &Stream, bool isGlobal) {
424 if (FirstVal == LastVal) return;
425
426 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
427
428 unsigned AggregateAbbrev = 0;
429 unsigned String8Abbrev = 0;
430 unsigned CString7Abbrev = 0;
431 unsigned CString6Abbrev = 0;
432 // If this is a constant pool for the module, emit module-specific abbrevs.
433 if (isGlobal) {
434 // Abbrev for CST_CODE_AGGREGATE.
435 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
436 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
437 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
438 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
439 AggregateAbbrev = Stream.EmitAbbrev(Abbv);
440
441 // Abbrev for CST_CODE_STRING.
442 Abbv = new BitCodeAbbrev();
443 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
444 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
445 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
446 String8Abbrev = Stream.EmitAbbrev(Abbv);
447 // Abbrev for CST_CODE_CSTRING.
448 Abbv = new BitCodeAbbrev();
449 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
450 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
451 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
452 CString7Abbrev = Stream.EmitAbbrev(Abbv);
453 // Abbrev for CST_CODE_CSTRING.
454 Abbv = new BitCodeAbbrev();
455 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
456 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
457 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
458 CString6Abbrev = Stream.EmitAbbrev(Abbv);
459 }
460
461 SmallVector<uint64_t, 64> Record;
462
463 const ValueEnumerator::ValueList &Vals = VE.getValues();
464 const Type *LastTy = 0;
465 for (unsigned i = FirstVal; i != LastVal; ++i) {
466 const Value *V = Vals[i].first;
467 // If we need to switch types, do so now.
468 if (V->getType() != LastTy) {
469 LastTy = V->getType();
470 Record.push_back(VE.getTypeID(LastTy));
471 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
472 CONSTANTS_SETTYPE_ABBREV);
473 Record.clear();
474 }
475
476 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
477 Record.push_back(unsigned(IA->hasSideEffects()));
478
479 // Add the asm string.
480 const std::string &AsmStr = IA->getAsmString();
481 Record.push_back(AsmStr.size());
482 for (unsigned i = 0, e = AsmStr.size(); i != e; ++i)
483 Record.push_back(AsmStr[i]);
484
485 // Add the constraint string.
486 const std::string &ConstraintStr = IA->getConstraintString();
487 Record.push_back(ConstraintStr.size());
488 for (unsigned i = 0, e = ConstraintStr.size(); i != e; ++i)
489 Record.push_back(ConstraintStr[i]);
490 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
491 Record.clear();
492 continue;
493 }
494 const Constant *C = cast<Constant>(V);
495 unsigned Code = -1U;
496 unsigned AbbrevToUse = 0;
497 if (C->isNullValue()) {
498 Code = bitc::CST_CODE_NULL;
499 } else if (isa<UndefValue>(C)) {
500 Code = bitc::CST_CODE_UNDEF;
501 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
502 if (IV->getBitWidth() <= 64) {
503 int64_t V = IV->getSExtValue();
504 if (V >= 0)
505 Record.push_back(V << 1);
506 else
507 Record.push_back((-V << 1) | 1);
508 Code = bitc::CST_CODE_INTEGER;
509 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
510 } else { // Wide integers, > 64 bits in size.
511 // We have an arbitrary precision integer value to write whose
512 // bit width is > 64. However, in canonical unsigned integer
513 // format it is likely that the high bits are going to be zero.
514 // So, we only write the number of active words.
515 unsigned NWords = IV->getValue().getActiveWords();
516 const uint64_t *RawWords = IV->getValue().getRawData();
517 for (unsigned i = 0; i != NWords; ++i) {
518 int64_t V = RawWords[i];
519 if (V >= 0)
520 Record.push_back(V << 1);
521 else
522 Record.push_back((-V << 1) | 1);
523 }
524 Code = bitc::CST_CODE_WIDE_INTEGER;
525 }
526 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
527 Code = bitc::CST_CODE_FLOAT;
Dale Johannesene617f912007-08-09 22:51:36 +0000528 const Type *Ty = CFP->getType();
Dale Johannesenfbd9cda2007-09-12 03:30:33 +0000529 if (Ty == Type::FloatTy || Ty == Type::DoubleTy) {
530 Record.push_back(CFP->getValueAPF().convertToAPInt().getZExtValue());
Dale Johannesen1616e902007-09-11 18:32:33 +0000531 } else if (Ty == Type::X86_FP80Ty) {
532 const uint64_t *p = CFP->getValueAPF().convertToAPInt().getRawData();
533 Record.push_back(p[0]);
534 Record.push_back((uint16_t)p[1]);
535 } else if (Ty == Type::FP128Ty) {
536 const uint64_t *p = CFP->getValueAPF().convertToAPInt().getRawData();
537 Record.push_back(p[0]);
538 Record.push_back(p[1]);
539 } else if (Ty == Type::PPC_FP128Ty) {
540 assert(0 && "PowerPC long double constants not handled yet.");
Dale Johannesene617f912007-08-09 22:51:36 +0000541 } else {
542 assert (0 && "Unknown FP type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000543 }
544 } else if (isa<ConstantArray>(C) && cast<ConstantArray>(C)->isString()) {
545 // Emit constant strings specially.
546 unsigned NumOps = C->getNumOperands();
547 // If this is a null-terminated string, use the denser CSTRING encoding.
548 if (C->getOperand(NumOps-1)->isNullValue()) {
549 Code = bitc::CST_CODE_CSTRING;
550 --NumOps; // Don't encode the null, which isn't allowed by char6.
551 } else {
552 Code = bitc::CST_CODE_STRING;
553 AbbrevToUse = String8Abbrev;
554 }
555 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
556 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
557 for (unsigned i = 0; i != NumOps; ++i) {
558 unsigned char V = cast<ConstantInt>(C->getOperand(i))->getZExtValue();
559 Record.push_back(V);
560 isCStr7 &= (V & 128) == 0;
561 if (isCStrChar6)
562 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
563 }
564
565 if (isCStrChar6)
566 AbbrevToUse = CString6Abbrev;
567 else if (isCStr7)
568 AbbrevToUse = CString7Abbrev;
569 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(V) ||
570 isa<ConstantVector>(V)) {
571 Code = bitc::CST_CODE_AGGREGATE;
572 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
573 Record.push_back(VE.getValueID(C->getOperand(i)));
574 AbbrevToUse = AggregateAbbrev;
575 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
576 switch (CE->getOpcode()) {
577 default:
578 if (Instruction::isCast(CE->getOpcode())) {
579 Code = bitc::CST_CODE_CE_CAST;
580 Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
581 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
582 Record.push_back(VE.getValueID(C->getOperand(0)));
583 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
584 } else {
585 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
586 Code = bitc::CST_CODE_CE_BINOP;
587 Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
588 Record.push_back(VE.getValueID(C->getOperand(0)));
589 Record.push_back(VE.getValueID(C->getOperand(1)));
590 }
591 break;
592 case Instruction::GetElementPtr:
593 Code = bitc::CST_CODE_CE_GEP;
594 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
595 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
596 Record.push_back(VE.getValueID(C->getOperand(i)));
597 }
598 break;
599 case Instruction::Select:
600 Code = bitc::CST_CODE_CE_SELECT;
601 Record.push_back(VE.getValueID(C->getOperand(0)));
602 Record.push_back(VE.getValueID(C->getOperand(1)));
603 Record.push_back(VE.getValueID(C->getOperand(2)));
604 break;
605 case Instruction::ExtractElement:
606 Code = bitc::CST_CODE_CE_EXTRACTELT;
607 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
608 Record.push_back(VE.getValueID(C->getOperand(0)));
609 Record.push_back(VE.getValueID(C->getOperand(1)));
610 break;
611 case Instruction::InsertElement:
612 Code = bitc::CST_CODE_CE_INSERTELT;
613 Record.push_back(VE.getValueID(C->getOperand(0)));
614 Record.push_back(VE.getValueID(C->getOperand(1)));
615 Record.push_back(VE.getValueID(C->getOperand(2)));
616 break;
617 case Instruction::ShuffleVector:
618 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
619 Record.push_back(VE.getValueID(C->getOperand(0)));
620 Record.push_back(VE.getValueID(C->getOperand(1)));
621 Record.push_back(VE.getValueID(C->getOperand(2)));
622 break;
623 case Instruction::ICmp:
624 case Instruction::FCmp:
625 Code = bitc::CST_CODE_CE_CMP;
626 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
627 Record.push_back(VE.getValueID(C->getOperand(0)));
628 Record.push_back(VE.getValueID(C->getOperand(1)));
629 Record.push_back(CE->getPredicate());
630 break;
631 }
632 } else {
633 assert(0 && "Unknown constant!");
634 }
635 Stream.EmitRecord(Code, Record, AbbrevToUse);
636 Record.clear();
637 }
638
639 Stream.ExitBlock();
640}
641
642static void WriteModuleConstants(const ValueEnumerator &VE,
643 BitstreamWriter &Stream) {
644 const ValueEnumerator::ValueList &Vals = VE.getValues();
645
646 // Find the first constant to emit, which is the first non-globalvalue value.
647 // We know globalvalues have been emitted by WriteModuleInfo.
648 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
649 if (!isa<GlobalValue>(Vals[i].first)) {
650 WriteConstants(i, Vals.size(), VE, Stream, true);
651 return;
652 }
653 }
654}
655
656/// PushValueAndType - The file has to encode both the value and type id for
657/// many values, because we need to know what type to create for forward
658/// references. However, most operands are not forward references, so this type
659/// field is not needed.
660///
661/// This function adds V's value ID to Vals. If the value ID is higher than the
662/// instruction ID, then it is a forward reference, and it also includes the
663/// type ID.
664static bool PushValueAndType(Value *V, unsigned InstID,
665 SmallVector<unsigned, 64> &Vals,
666 ValueEnumerator &VE) {
667 unsigned ValID = VE.getValueID(V);
668 Vals.push_back(ValID);
669 if (ValID >= InstID) {
670 Vals.push_back(VE.getTypeID(V->getType()));
671 return true;
672 }
673 return false;
674}
675
676/// WriteInstruction - Emit an instruction to the specified stream.
677static void WriteInstruction(const Instruction &I, unsigned InstID,
678 ValueEnumerator &VE, BitstreamWriter &Stream,
679 SmallVector<unsigned, 64> &Vals) {
680 unsigned Code = 0;
681 unsigned AbbrevToUse = 0;
682 switch (I.getOpcode()) {
683 default:
684 if (Instruction::isCast(I.getOpcode())) {
685 Code = bitc::FUNC_CODE_INST_CAST;
686 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
687 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
688 Vals.push_back(VE.getTypeID(I.getType()));
689 Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
690 } else {
691 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
692 Code = bitc::FUNC_CODE_INST_BINOP;
693 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
694 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
695 Vals.push_back(VE.getValueID(I.getOperand(1)));
696 Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
697 }
698 break;
699
700 case Instruction::GetElementPtr:
701 Code = bitc::FUNC_CODE_INST_GEP;
702 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
703 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
704 break;
705 case Instruction::Select:
706 Code = bitc::FUNC_CODE_INST_SELECT;
707 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
708 Vals.push_back(VE.getValueID(I.getOperand(2)));
709 Vals.push_back(VE.getValueID(I.getOperand(0)));
710 break;
711 case Instruction::ExtractElement:
712 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
713 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
714 Vals.push_back(VE.getValueID(I.getOperand(1)));
715 break;
716 case Instruction::InsertElement:
717 Code = bitc::FUNC_CODE_INST_INSERTELT;
718 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
719 Vals.push_back(VE.getValueID(I.getOperand(1)));
720 Vals.push_back(VE.getValueID(I.getOperand(2)));
721 break;
722 case Instruction::ShuffleVector:
723 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
724 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
725 Vals.push_back(VE.getValueID(I.getOperand(1)));
726 Vals.push_back(VE.getValueID(I.getOperand(2)));
727 break;
728 case Instruction::ICmp:
729 case Instruction::FCmp:
730 Code = bitc::FUNC_CODE_INST_CMP;
731 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
732 Vals.push_back(VE.getValueID(I.getOperand(1)));
733 Vals.push_back(cast<CmpInst>(I).getPredicate());
734 break;
735
736 case Instruction::Ret:
737 Code = bitc::FUNC_CODE_INST_RET;
738 if (!I.getNumOperands())
739 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
740 else if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
741 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
742 break;
743 case Instruction::Br:
744 Code = bitc::FUNC_CODE_INST_BR;
745 Vals.push_back(VE.getValueID(I.getOperand(0)));
746 if (cast<BranchInst>(I).isConditional()) {
747 Vals.push_back(VE.getValueID(I.getOperand(1)));
748 Vals.push_back(VE.getValueID(I.getOperand(2)));
749 }
750 break;
751 case Instruction::Switch:
752 Code = bitc::FUNC_CODE_INST_SWITCH;
753 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
754 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
755 Vals.push_back(VE.getValueID(I.getOperand(i)));
756 break;
757 case Instruction::Invoke: {
758 const PointerType *PTy = cast<PointerType>(I.getOperand(0)->getType());
759 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
760 Code = bitc::FUNC_CODE_INST_INVOKE;
761
762 // Note: we emit the param attr ID number for the function type of this
763 // function. In the future, we intend for attrs to be properties of
764 // functions, instead of on the type. This is to support this future work.
765 Vals.push_back(VE.getParamAttrID(FTy->getParamAttrs()));
766
767 Vals.push_back(cast<InvokeInst>(I).getCallingConv());
768 Vals.push_back(VE.getValueID(I.getOperand(1))); // normal dest
769 Vals.push_back(VE.getValueID(I.getOperand(2))); // unwind dest
770 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // callee
771
772 // Emit value #'s for the fixed parameters.
773 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
774 Vals.push_back(VE.getValueID(I.getOperand(i+3))); // fixed param.
775
776 // Emit type/value pairs for varargs params.
777 if (FTy->isVarArg()) {
778 for (unsigned i = 3+FTy->getNumParams(), e = I.getNumOperands();
779 i != e; ++i)
780 PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
781 }
782 break;
783 }
784 case Instruction::Unwind:
785 Code = bitc::FUNC_CODE_INST_UNWIND;
786 break;
787 case Instruction::Unreachable:
788 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
789 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
790 break;
791
792 case Instruction::PHI:
793 Code = bitc::FUNC_CODE_INST_PHI;
794 Vals.push_back(VE.getTypeID(I.getType()));
795 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
796 Vals.push_back(VE.getValueID(I.getOperand(i)));
797 break;
798
799 case Instruction::Malloc:
800 Code = bitc::FUNC_CODE_INST_MALLOC;
801 Vals.push_back(VE.getTypeID(I.getType()));
802 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
803 Vals.push_back(Log2_32(cast<MallocInst>(I).getAlignment())+1);
804 break;
805
806 case Instruction::Free:
807 Code = bitc::FUNC_CODE_INST_FREE;
808 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
809 break;
810
811 case Instruction::Alloca:
812 Code = bitc::FUNC_CODE_INST_ALLOCA;
813 Vals.push_back(VE.getTypeID(I.getType()));
814 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
815 Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1);
816 break;
817
818 case Instruction::Load:
819 Code = bitc::FUNC_CODE_INST_LOAD;
820 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) // ptr
821 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
822
823 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
824 Vals.push_back(cast<LoadInst>(I).isVolatile());
825 break;
826 case Instruction::Store:
827 Code = bitc::FUNC_CODE_INST_STORE;
828 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // val.
829 Vals.push_back(VE.getValueID(I.getOperand(1))); // ptr.
830 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
831 Vals.push_back(cast<StoreInst>(I).isVolatile());
832 break;
833 case Instruction::Call: {
834 const PointerType *PTy = cast<PointerType>(I.getOperand(0)->getType());
835 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
836
837 Code = bitc::FUNC_CODE_INST_CALL;
838
839 // Note: we emit the param attr ID number for the function type of this
840 // function. In the future, we intend for attrs to be properties of
841 // functions, instead of on the type. This is to support this future work.
842 Vals.push_back(VE.getParamAttrID(FTy->getParamAttrs()));
843
844 Vals.push_back((cast<CallInst>(I).getCallingConv() << 1) |
845 unsigned(cast<CallInst>(I).isTailCall()));
846 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // Callee
847
848 // Emit value #'s for the fixed parameters.
849 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
850 Vals.push_back(VE.getValueID(I.getOperand(i+1))); // fixed param.
851
852 // Emit type/value pairs for varargs params.
853 if (FTy->isVarArg()) {
854 unsigned NumVarargs = I.getNumOperands()-1-FTy->getNumParams();
855 for (unsigned i = I.getNumOperands()-NumVarargs, e = I.getNumOperands();
856 i != e; ++i)
857 PushValueAndType(I.getOperand(i), InstID, Vals, VE); // varargs
858 }
859 break;
860 }
861 case Instruction::VAArg:
862 Code = bitc::FUNC_CODE_INST_VAARG;
863 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
864 Vals.push_back(VE.getValueID(I.getOperand(0))); // valist.
865 Vals.push_back(VE.getTypeID(I.getType())); // restype.
866 break;
867 }
868
869 Stream.EmitRecord(Code, Vals, AbbrevToUse);
870 Vals.clear();
871}
872
873// Emit names for globals/functions etc.
874static void WriteValueSymbolTable(const ValueSymbolTable &VST,
875 const ValueEnumerator &VE,
876 BitstreamWriter &Stream) {
877 if (VST.empty()) return;
878 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
879
880 // FIXME: Set up the abbrev, we know how many values there are!
881 // FIXME: We know if the type names can use 7-bit ascii.
882 SmallVector<unsigned, 64> NameVals;
883
884 for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
885 SI != SE; ++SI) {
886
887 const ValueName &Name = *SI;
888
889 // Figure out the encoding to use for the name.
890 bool is7Bit = true;
891 bool isChar6 = true;
892 for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
893 C != E; ++C) {
894 if (isChar6)
895 isChar6 = BitCodeAbbrevOp::isChar6(*C);
896 if ((unsigned char)*C & 128) {
897 is7Bit = false;
898 break; // don't bother scanning the rest.
899 }
900 }
901
902 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
903
904 // VST_ENTRY: [valueid, namechar x N]
905 // VST_BBENTRY: [bbid, namechar x N]
906 unsigned Code;
907 if (isa<BasicBlock>(SI->getValue())) {
908 Code = bitc::VST_CODE_BBENTRY;
909 if (isChar6)
910 AbbrevToUse = VST_BBENTRY_6_ABBREV;
911 } else {
912 Code = bitc::VST_CODE_ENTRY;
913 if (isChar6)
914 AbbrevToUse = VST_ENTRY_6_ABBREV;
915 else if (is7Bit)
916 AbbrevToUse = VST_ENTRY_7_ABBREV;
917 }
918
919 NameVals.push_back(VE.getValueID(SI->getValue()));
920 for (const char *P = Name.getKeyData(),
921 *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
922 NameVals.push_back((unsigned char)*P);
923
924 // Emit the finished record.
925 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
926 NameVals.clear();
927 }
928 Stream.ExitBlock();
929}
930
931/// WriteFunction - Emit a function body to the module stream.
932static void WriteFunction(const Function &F, ValueEnumerator &VE,
933 BitstreamWriter &Stream) {
934 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
935 VE.incorporateFunction(F);
936
937 SmallVector<unsigned, 64> Vals;
938
939 // Emit the number of basic blocks, so the reader can create them ahead of
940 // time.
941 Vals.push_back(VE.getBasicBlocks().size());
942 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
943 Vals.clear();
944
945 // If there are function-local constants, emit them now.
946 unsigned CstStart, CstEnd;
947 VE.getFunctionConstantRange(CstStart, CstEnd);
948 WriteConstants(CstStart, CstEnd, VE, Stream, false);
949
950 // Keep a running idea of what the instruction ID is.
951 unsigned InstID = CstEnd;
952
953 // Finally, emit all the instructions, in order.
954 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
955 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
956 I != E; ++I) {
957 WriteInstruction(*I, InstID, VE, Stream, Vals);
958 if (I->getType() != Type::VoidTy)
959 ++InstID;
960 }
961
962 // Emit names for all the instructions etc.
963 WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
964
965 VE.purgeFunction();
966 Stream.ExitBlock();
967}
968
969/// WriteTypeSymbolTable - Emit a block for the specified type symtab.
970static void WriteTypeSymbolTable(const TypeSymbolTable &TST,
971 const ValueEnumerator &VE,
972 BitstreamWriter &Stream) {
973 if (TST.empty()) return;
974
975 Stream.EnterSubblock(bitc::TYPE_SYMTAB_BLOCK_ID, 3);
976
977 // 7-bit fixed width VST_CODE_ENTRY strings.
978 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
979 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
980 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
981 Log2_32_Ceil(VE.getTypes().size()+1)));
982 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
983 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
984 unsigned V7Abbrev = Stream.EmitAbbrev(Abbv);
985
986 SmallVector<unsigned, 64> NameVals;
987
988 for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end();
989 TI != TE; ++TI) {
990 // TST_ENTRY: [typeid, namechar x N]
991 NameVals.push_back(VE.getTypeID(TI->second));
992
993 const std::string &Str = TI->first;
994 bool is7Bit = true;
995 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
996 NameVals.push_back((unsigned char)Str[i]);
997 if (Str[i] & 128)
998 is7Bit = false;
999 }
1000
1001 // Emit the finished record.
1002 Stream.EmitRecord(bitc::VST_CODE_ENTRY, NameVals, is7Bit ? V7Abbrev : 0);
1003 NameVals.clear();
1004 }
1005
1006 Stream.ExitBlock();
1007}
1008
1009// Emit blockinfo, which defines the standard abbreviations etc.
1010static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
1011 // We only want to emit block info records for blocks that have multiple
1012 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK. Other
1013 // blocks can defined their abbrevs inline.
1014 Stream.EnterBlockInfoBlock(2);
1015
1016 { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
1017 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1018 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
1019 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1020 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1021 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1022 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1023 Abbv) != VST_ENTRY_8_ABBREV)
1024 assert(0 && "Unexpected abbrev ordering!");
1025 }
1026
1027 { // 7-bit fixed width VST_ENTRY strings.
1028 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1029 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1030 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1031 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1032 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1033 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1034 Abbv) != VST_ENTRY_7_ABBREV)
1035 assert(0 && "Unexpected abbrev ordering!");
1036 }
1037 { // 6-bit char6 VST_ENTRY strings.
1038 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1039 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1040 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1041 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1042 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1043 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1044 Abbv) != VST_ENTRY_6_ABBREV)
1045 assert(0 && "Unexpected abbrev ordering!");
1046 }
1047 { // 6-bit char6 VST_BBENTRY strings.
1048 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1049 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
1050 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1051 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1052 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1053 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1054 Abbv) != VST_BBENTRY_6_ABBREV)
1055 assert(0 && "Unexpected abbrev ordering!");
1056 }
1057
1058
1059
1060 { // SETTYPE abbrev for CONSTANTS_BLOCK.
1061 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1062 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
1063 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1064 Log2_32_Ceil(VE.getTypes().size()+1)));
1065 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1066 Abbv) != CONSTANTS_SETTYPE_ABBREV)
1067 assert(0 && "Unexpected abbrev ordering!");
1068 }
1069
1070 { // INTEGER abbrev for CONSTANTS_BLOCK.
1071 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1072 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
1073 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1074 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1075 Abbv) != CONSTANTS_INTEGER_ABBREV)
1076 assert(0 && "Unexpected abbrev ordering!");
1077 }
1078
1079 { // CE_CAST abbrev for CONSTANTS_BLOCK.
1080 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1081 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
1082 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
1083 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
1084 Log2_32_Ceil(VE.getTypes().size()+1)));
1085 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
1086
1087 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1088 Abbv) != CONSTANTS_CE_CAST_Abbrev)
1089 assert(0 && "Unexpected abbrev ordering!");
1090 }
1091 { // NULL abbrev for CONSTANTS_BLOCK.
1092 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1093 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
1094 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1095 Abbv) != CONSTANTS_NULL_Abbrev)
1096 assert(0 && "Unexpected abbrev ordering!");
1097 }
1098
1099 // FIXME: This should only use space for first class types!
1100
1101 { // INST_LOAD abbrev for FUNCTION_BLOCK.
1102 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1103 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
1104 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
1105 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
1106 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
1107 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1108 Abbv) != FUNCTION_INST_LOAD_ABBREV)
1109 assert(0 && "Unexpected abbrev ordering!");
1110 }
1111 { // INST_BINOP abbrev for FUNCTION_BLOCK.
1112 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1113 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1114 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1115 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1116 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1117 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1118 Abbv) != FUNCTION_INST_BINOP_ABBREV)
1119 assert(0 && "Unexpected abbrev ordering!");
1120 }
1121 { // INST_CAST abbrev for FUNCTION_BLOCK.
1122 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1123 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
1124 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
1125 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
1126 Log2_32_Ceil(VE.getTypes().size()+1)));
1127 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1128 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1129 Abbv) != FUNCTION_INST_CAST_ABBREV)
1130 assert(0 && "Unexpected abbrev ordering!");
1131 }
1132
1133 { // INST_RET abbrev for FUNCTION_BLOCK.
1134 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1135 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1136 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1137 Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
1138 assert(0 && "Unexpected abbrev ordering!");
1139 }
1140 { // INST_RET abbrev for FUNCTION_BLOCK.
1141 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1142 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1143 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
1144 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1145 Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
1146 assert(0 && "Unexpected abbrev ordering!");
1147 }
1148 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
1149 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1150 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
1151 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1152 Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
1153 assert(0 && "Unexpected abbrev ordering!");
1154 }
1155
1156 Stream.ExitBlock();
1157}
1158
1159
1160/// WriteModule - Emit the specified module to the bitstream.
1161static void WriteModule(const Module *M, BitstreamWriter &Stream) {
1162 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
1163
1164 // Emit the version number if it is non-zero.
1165 if (CurVersion) {
1166 SmallVector<unsigned, 1> Vals;
1167 Vals.push_back(CurVersion);
1168 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
1169 }
1170
1171 // Analyze the module, enumerating globals, functions, etc.
1172 ValueEnumerator VE(M);
1173
1174 // Emit blockinfo, which defines the standard abbreviations etc.
1175 WriteBlockInfo(VE, Stream);
1176
1177 // Emit information about parameter attributes.
1178 WriteParamAttrTable(VE, Stream);
1179
1180 // Emit information describing all of the types in the module.
1181 WriteTypeTable(VE, Stream);
1182
1183 // Emit top-level description of module, including target triple, inline asm,
1184 // descriptors for global variables, and function prototype info.
1185 WriteModuleInfo(M, VE, Stream);
1186
1187 // Emit constants.
1188 WriteModuleConstants(VE, Stream);
1189
1190 // If we have any aggregate values in the value table, purge them - these can
1191 // only be used to initialize global variables. Doing so makes the value
1192 // namespace smaller for code in functions.
1193 int NumNonAggregates = VE.PurgeAggregateValues();
1194 if (NumNonAggregates != -1) {
1195 SmallVector<unsigned, 1> Vals;
1196 Vals.push_back(NumNonAggregates);
1197 Stream.EmitRecord(bitc::MODULE_CODE_PURGEVALS, Vals);
1198 }
1199
1200 // Emit function bodies.
1201 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1202 if (!I->isDeclaration())
1203 WriteFunction(*I, VE, Stream);
1204
1205 // Emit the type symbol table information.
1206 WriteTypeSymbolTable(M->getTypeSymbolTable(), VE, Stream);
1207
1208 // Emit names for globals/functions etc.
1209 WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
1210
1211 Stream.ExitBlock();
1212}
1213
1214
1215/// WriteBitcodeToFile - Write the specified module to the specified output
1216/// stream.
1217void llvm::WriteBitcodeToFile(const Module *M, std::ostream &Out) {
1218 std::vector<unsigned char> Buffer;
1219 BitstreamWriter Stream(Buffer);
1220
1221 Buffer.reserve(256*1024);
1222
1223 // Emit the file header.
1224 Stream.Emit((unsigned)'B', 8);
1225 Stream.Emit((unsigned)'C', 8);
1226 Stream.Emit(0x0, 4);
1227 Stream.Emit(0xC, 4);
1228 Stream.Emit(0xE, 4);
1229 Stream.Emit(0xD, 4);
1230
1231 // Emit the module.
1232 WriteModule(M, Stream);
1233
1234 // Write the generated bitstream to "Out".
1235 Out.write((char*)&Buffer.front(), Buffer.size());
1236
1237 // Make sure it hits disk now.
1238 Out.flush();
1239}