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.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "ReaderWriter_2_9.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/Operator.h"
24 #include "llvm/ValueSymbolTable.h"
25 #include "llvm/ADT/Triple.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/MathExtras.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/Support/Program.h"
30 #include <cctype>
31 #include <map>
32 using namespace llvm;
33
34 // Redefine older bitcode opcodes for use here. Note that these come from
35 // LLVM 2.7 (which is what HC shipped with).
36 #define METADATA_NODE_2_7 2
37 #define METADATA_FN_NODE_2_7 3
38 #define METADATA_NAMED_NODE_2_7 5
39 #define METADATA_ATTACHMENT_2_7 7
40 #define FUNC_CODE_INST_CALL_2_7 22
41 #define FUNC_CODE_DEBUG_LOC_2_7 32
42
43 /// These are manifest constants used by the bitcode writer. They do not need to
44 /// be kept in sync with the reader, but need to be consistent within this file.
45 enum {
46 CurVersion = 0,
47
48 // VALUE_SYMTAB_BLOCK abbrev id's.
49 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
50 VST_ENTRY_7_ABBREV,
51 VST_ENTRY_6_ABBREV,
52 VST_BBENTRY_6_ABBREV,
53
54 // CONSTANTS_BLOCK abbrev id's.
55 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
56 CONSTANTS_INTEGER_ABBREV,
57 CONSTANTS_CE_CAST_Abbrev,
58 CONSTANTS_NULL_Abbrev,
59
60 // FUNCTION_BLOCK abbrev id's.
61 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
62 FUNCTION_INST_BINOP_ABBREV,
63 FUNCTION_INST_BINOP_FLAGS_ABBREV,
64 FUNCTION_INST_CAST_ABBREV,
65 FUNCTION_INST_RET_VOID_ABBREV,
66 FUNCTION_INST_RET_VAL_ABBREV,
67 FUNCTION_INST_UNREACHABLE_ABBREV
68 };
69
70
GetEncodedCastOpcode(unsigned Opcode)71 static unsigned GetEncodedCastOpcode(unsigned Opcode) {
72 switch (Opcode) {
73 default: llvm_unreachable("Unknown cast instruction!");
74 case Instruction::Trunc : return bitc::CAST_TRUNC;
75 case Instruction::ZExt : return bitc::CAST_ZEXT;
76 case Instruction::SExt : return bitc::CAST_SEXT;
77 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
78 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
79 case Instruction::UIToFP : return bitc::CAST_UITOFP;
80 case Instruction::SIToFP : return bitc::CAST_SITOFP;
81 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
82 case Instruction::FPExt : return bitc::CAST_FPEXT;
83 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
84 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
85 case Instruction::BitCast : return bitc::CAST_BITCAST;
86 }
87 }
88
GetEncodedBinaryOpcode(unsigned Opcode)89 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
90 switch (Opcode) {
91 default: llvm_unreachable("Unknown binary instruction!");
92 case Instruction::Add:
93 case Instruction::FAdd: return bitc::BINOP_ADD;
94 case Instruction::Sub:
95 case Instruction::FSub: return bitc::BINOP_SUB;
96 case Instruction::Mul:
97 case Instruction::FMul: return bitc::BINOP_MUL;
98 case Instruction::UDiv: return bitc::BINOP_UDIV;
99 case Instruction::FDiv:
100 case Instruction::SDiv: return bitc::BINOP_SDIV;
101 case Instruction::URem: return bitc::BINOP_UREM;
102 case Instruction::FRem:
103 case Instruction::SRem: return bitc::BINOP_SREM;
104 case Instruction::Shl: return bitc::BINOP_SHL;
105 case Instruction::LShr: return bitc::BINOP_LSHR;
106 case Instruction::AShr: return bitc::BINOP_ASHR;
107 case Instruction::And: return bitc::BINOP_AND;
108 case Instruction::Or: return bitc::BINOP_OR;
109 case Instruction::Xor: return bitc::BINOP_XOR;
110 }
111 }
112
WriteStringRecord(unsigned Code,StringRef Str,unsigned AbbrevToUse,BitstreamWriter & Stream)113 static void WriteStringRecord(unsigned Code, StringRef Str,
114 unsigned AbbrevToUse, BitstreamWriter &Stream) {
115 SmallVector<unsigned, 64> Vals;
116
117 // Code: [strchar x N]
118 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
119 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
120 AbbrevToUse = 0;
121 Vals.push_back(Str[i]);
122 }
123
124 // Emit the finished record.
125 Stream.EmitRecord(Code, Vals, AbbrevToUse);
126 }
127
128 // Emit information about parameter attributes.
WriteAttributeTable(const ValueEnumerator & VE,BitstreamWriter & Stream)129 static void WriteAttributeTable(const ValueEnumerator &VE,
130 BitstreamWriter &Stream) {
131 const std::vector<AttrListPtr> &Attrs = VE.getAttributes();
132 if (Attrs.empty()) return;
133
134 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
135
136 SmallVector<uint64_t, 64> Record;
137 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
138 const AttrListPtr &A = Attrs[i];
139 for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i) {
140 const AttributeWithIndex &PAWI = A.getSlot(i);
141 Record.push_back(PAWI.Index);
142
143 // FIXME: remove in LLVM 3.0
144 // Store the alignment in the bitcode as a 16-bit raw value instead of a
145 // 5-bit log2 encoded value. Shift the bits above the alignment up by
146 // 11 bits.
147 uint64_t FauxAttr = PAWI.Attrs & 0xffff;
148 if (PAWI.Attrs & Attribute::Alignment)
149 FauxAttr |= (1ull<<16)<<(((PAWI.Attrs & Attribute::Alignment)-1) >> 16);
150 FauxAttr |= (PAWI.Attrs & (0x3FFull << 21)) << 11;
151
152 Record.push_back(FauxAttr);
153 }
154
155 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
156 Record.clear();
157 }
158
159 Stream.ExitBlock();
160 }
161
WriteTypeSymbolTable(const ValueEnumerator & VE,BitstreamWriter & Stream)162 static void WriteTypeSymbolTable(const ValueEnumerator &VE,
163 BitstreamWriter &Stream) {
164 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
165 Stream.EnterSubblock(bitc::TYPE_SYMTAB_BLOCK_ID_OLD, 3);
166
167 // 7-bit fixed width VST_CODE_ENTRY strings.
168 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
169 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
170 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
171 Log2_32_Ceil(VE.getTypes().size()+1)));
172 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
173 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
174 unsigned V7Abbrev = Stream.EmitAbbrev(Abbv);
175
176 SmallVector<unsigned, 64> NameVals;
177
178 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
179 Type *T = TypeList[i];
180
181 switch (T->getTypeID()) {
182 case Type::StructTyID: {
183 StructType *ST = cast<StructType>(T);
184 if (ST->isAnonymous()) {
185 // Skip anonymous struct definitions in type symbol table
186 // FIXME(srhines)
187 break;
188 }
189
190 // TST_ENTRY: [typeid, namechar x N]
191 NameVals.push_back(i);
192
193 const std::string &Str = ST->getName();
194 bool is7Bit = true;
195 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
196 NameVals.push_back((unsigned char)Str[i]);
197 if (Str[i] & 128)
198 is7Bit = false;
199 }
200
201 // Emit the finished record.
202 Stream.EmitRecord(bitc::VST_CODE_ENTRY, NameVals, is7Bit ? V7Abbrev : 0);
203 NameVals.clear();
204
205 break;
206 }
207 default: break;
208 }
209 }
210
211 #if 0
212 for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end();
213 TI != TE; ++TI) {
214 // TST_ENTRY: [typeid, namechar x N]
215 NameVals.push_back(VE.getTypeID(TI->second));
216
217 const std::string &Str = TI->first;
218 bool is7Bit = true;
219 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
220 NameVals.push_back((unsigned char)Str[i]);
221 if (Str[i] & 128)
222 is7Bit = false;
223 }
224
225 // Emit the finished record.
226 Stream.EmitRecord(bitc::VST_CODE_ENTRY, NameVals, is7Bit ? V7Abbrev : 0);
227 NameVals.clear();
228 }
229 #endif
230
231 Stream.ExitBlock();
232 }
233
234 /// WriteTypeTable - Write out the type table for a module.
WriteTypeTable(const ValueEnumerator & VE,BitstreamWriter & Stream)235 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
236 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
237
238 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_OLD, 4 /*count from # abbrevs */);
239 SmallVector<uint64_t, 64> TypeVals;
240
241 // Abbrev for TYPE_CODE_POINTER.
242 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
243 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
244 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
245 Log2_32_Ceil(VE.getTypes().size()+1)));
246 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
247 unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
248
249 // Abbrev for TYPE_CODE_FUNCTION.
250 Abbv = new BitCodeAbbrev();
251 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
252 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
253 Abbv->Add(BitCodeAbbrevOp(0)); // FIXME: DEAD value, remove in LLVM 3.0
254 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
255 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
256 Log2_32_Ceil(VE.getTypes().size()+1)));
257 unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
258
259 #if 0
260 // Abbrev for TYPE_CODE_STRUCT_ANON.
261 Abbv = new BitCodeAbbrev();
262 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
263 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
264 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
265 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
266 Log2_32_Ceil(VE.getTypes().size()+1)));
267 unsigned StructAnonAbbrev = Stream.EmitAbbrev(Abbv);
268
269 // Abbrev for TYPE_CODE_STRUCT_NAME.
270 Abbv = new BitCodeAbbrev();
271 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
272 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
273 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
274 unsigned StructNameAbbrev = Stream.EmitAbbrev(Abbv);
275
276 // Abbrev for TYPE_CODE_STRUCT_NAMED.
277 Abbv = new BitCodeAbbrev();
278 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
279 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
280 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
281 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
282 Log2_32_Ceil(VE.getTypes().size()+1)));
283 unsigned StructNamedAbbrev = Stream.EmitAbbrev(Abbv);
284 #endif
285
286 // Abbrev for TYPE_CODE_STRUCT.
287 Abbv = new BitCodeAbbrev();
288 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_OLD));
289 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
290 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
291 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
292 Log2_32_Ceil(VE.getTypes().size()+1)));
293 unsigned StructAbbrev = Stream.EmitAbbrev(Abbv);
294
295 // Abbrev for TYPE_CODE_ARRAY.
296 Abbv = new BitCodeAbbrev();
297 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
298 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
299 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
300 Log2_32_Ceil(VE.getTypes().size()+1)));
301 unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
302
303 // Emit an entry count so the reader can reserve space.
304 TypeVals.push_back(TypeList.size());
305 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
306 TypeVals.clear();
307
308 // Loop over all of the types, emitting each in turn.
309 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
310 Type *T = TypeList[i];
311 int AbbrevToUse = 0;
312 unsigned Code = 0;
313
314 switch (T->getTypeID()) {
315 default: llvm_unreachable("Unknown type!");
316 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
317 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
318 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
319 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
320 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
321 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
322 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
323 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
324 case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break;
325 case Type::IntegerTyID:
326 // INTEGER: [width]
327 Code = bitc::TYPE_CODE_INTEGER;
328 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
329 break;
330 case Type::PointerTyID: {
331 PointerType *PTy = cast<PointerType>(T);
332 // POINTER: [pointee type, address space]
333 Code = bitc::TYPE_CODE_POINTER;
334 TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
335 unsigned AddressSpace = PTy->getAddressSpace();
336 TypeVals.push_back(AddressSpace);
337 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
338 break;
339 }
340 case Type::FunctionTyID: {
341 FunctionType *FT = cast<FunctionType>(T);
342 // FUNCTION: [isvararg, attrid, retty, paramty x N]
343 Code = bitc::TYPE_CODE_FUNCTION;
344 TypeVals.push_back(FT->isVarArg());
345 TypeVals.push_back(0); // FIXME: DEAD: remove in llvm 3.0
346 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
347 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
348 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
349 AbbrevToUse = FunctionAbbrev;
350 break;
351 }
352 case Type::StructTyID: {
353 StructType *ST = cast<StructType>(T);
354 // STRUCT: [ispacked, eltty x N]
355 TypeVals.push_back(ST->isPacked());
356 // Output all of the element types.
357 for (StructType::element_iterator I = ST->element_begin(),
358 E = ST->element_end(); I != E; ++I)
359 TypeVals.push_back(VE.getTypeID(*I));
360 AbbrevToUse = StructAbbrev;
361 break;
362 }
363 case Type::ArrayTyID: {
364 ArrayType *AT = cast<ArrayType>(T);
365 // ARRAY: [numelts, eltty]
366 Code = bitc::TYPE_CODE_ARRAY;
367 TypeVals.push_back(AT->getNumElements());
368 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
369 AbbrevToUse = ArrayAbbrev;
370 break;
371 }
372 case Type::VectorTyID: {
373 VectorType *VT = cast<VectorType>(T);
374 // VECTOR [numelts, eltty]
375 Code = bitc::TYPE_CODE_VECTOR;
376 TypeVals.push_back(VT->getNumElements());
377 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
378 break;
379 }
380 }
381
382 // Emit the finished record.
383 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
384 TypeVals.clear();
385 }
386
387 Stream.ExitBlock();
388
389 WriteTypeSymbolTable(VE, Stream);
390 }
391
getEncodedLinkage(const GlobalValue * GV)392 static unsigned getEncodedLinkage(const GlobalValue *GV) {
393 switch (GV->getLinkage()) {
394 default: llvm_unreachable("Invalid linkage!");
395 case GlobalValue::ExternalLinkage: return 0;
396 case GlobalValue::WeakAnyLinkage: return 1;
397 case GlobalValue::AppendingLinkage: return 2;
398 case GlobalValue::InternalLinkage: return 3;
399 case GlobalValue::LinkOnceAnyLinkage: return 4;
400 case GlobalValue::DLLImportLinkage: return 5;
401 case GlobalValue::DLLExportLinkage: return 6;
402 case GlobalValue::ExternalWeakLinkage: return 7;
403 case GlobalValue::CommonLinkage: return 8;
404 case GlobalValue::PrivateLinkage: return 9;
405 case GlobalValue::WeakODRLinkage: return 10;
406 case GlobalValue::LinkOnceODRLinkage: return 11;
407 case GlobalValue::AvailableExternallyLinkage: return 12;
408 case GlobalValue::LinkerPrivateLinkage: return 13;
409 case GlobalValue::LinkerPrivateWeakLinkage: return 14;
410 case GlobalValue::LinkerPrivateWeakDefAutoLinkage: return 15;
411 }
412 }
413
getEncodedVisibility(const GlobalValue * GV)414 static unsigned getEncodedVisibility(const GlobalValue *GV) {
415 switch (GV->getVisibility()) {
416 default: llvm_unreachable("Invalid visibility!");
417 case GlobalValue::DefaultVisibility: return 0;
418 case GlobalValue::HiddenVisibility: return 1;
419 case GlobalValue::ProtectedVisibility: return 2;
420 }
421 }
422
423 // Emit top-level description of module, including target triple, inline asm,
424 // descriptors for global variables, and function prototype info.
WriteModuleInfo(const Module * M,const ValueEnumerator & VE,BitstreamWriter & Stream)425 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
426 BitstreamWriter &Stream) {
427 // Emit the list of dependent libraries for the Module.
428 for (Module::lib_iterator I = M->lib_begin(), E = M->lib_end(); I != E; ++I)
429 WriteStringRecord(bitc::MODULE_CODE_DEPLIB, *I, 0/*TODO*/, Stream);
430
431 // Emit various pieces of data attached to a module.
432 if (!M->getTargetTriple().empty())
433 WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
434 0/*TODO*/, Stream);
435 if (!M->getDataLayout().empty())
436 WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(),
437 0/*TODO*/, Stream);
438 if (!M->getModuleInlineAsm().empty())
439 WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
440 0/*TODO*/, Stream);
441
442 // Emit information about sections and GC, computing how many there are. Also
443 // compute the maximum alignment value.
444 std::map<std::string, unsigned> SectionMap;
445 std::map<std::string, unsigned> GCMap;
446 unsigned MaxAlignment = 0;
447 unsigned MaxGlobalType = 0;
448 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
449 GV != E; ++GV) {
450 MaxAlignment = std::max(MaxAlignment, GV->getAlignment());
451 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType()));
452
453 if (!GV->hasSection()) continue;
454 // Give section names unique ID's.
455 unsigned &Entry = SectionMap[GV->getSection()];
456 if (Entry != 0) continue;
457 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(),
458 0/*TODO*/, Stream);
459 Entry = SectionMap.size();
460 }
461 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
462 MaxAlignment = std::max(MaxAlignment, F->getAlignment());
463 if (F->hasSection()) {
464 // Give section names unique ID's.
465 unsigned &Entry = SectionMap[F->getSection()];
466 if (!Entry) {
467 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(),
468 0/*TODO*/, Stream);
469 Entry = SectionMap.size();
470 }
471 }
472 if (F->hasGC()) {
473 // Same for GC names.
474 unsigned &Entry = GCMap[F->getGC()];
475 if (!Entry) {
476 WriteStringRecord(bitc::MODULE_CODE_GCNAME, F->getGC(),
477 0/*TODO*/, Stream);
478 Entry = GCMap.size();
479 }
480 }
481 }
482
483 // Emit abbrev for globals, now that we know # sections and max alignment.
484 unsigned SimpleGVarAbbrev = 0;
485 if (!M->global_empty()) {
486 // Add an abbrev for common globals with no visibility or thread localness.
487 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
488 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
489 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
490 Log2_32_Ceil(MaxGlobalType+1)));
491 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Constant.
492 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
493 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // Linkage.
494 if (MaxAlignment == 0) // Alignment.
495 Abbv->Add(BitCodeAbbrevOp(0));
496 else {
497 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
498 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
499 Log2_32_Ceil(MaxEncAlignment+1)));
500 }
501 if (SectionMap.empty()) // Section.
502 Abbv->Add(BitCodeAbbrevOp(0));
503 else
504 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
505 Log2_32_Ceil(SectionMap.size()+1)));
506 // Don't bother emitting vis + thread local.
507 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
508 }
509
510 // Emit the global variable information.
511 SmallVector<unsigned, 64> Vals;
512 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
513 GV != E; ++GV) {
514 unsigned AbbrevToUse = 0;
515
516 // GLOBALVAR: [type, isconst, initid,
517 // linkage, alignment, section, visibility, threadlocal,
518 // unnamed_addr]
519 Vals.push_back(VE.getTypeID(GV->getType()));
520 Vals.push_back(GV->isConstant());
521 Vals.push_back(GV->isDeclaration() ? 0 :
522 (VE.getValueID(GV->getInitializer()) + 1));
523 Vals.push_back(getEncodedLinkage(GV));
524 Vals.push_back(Log2_32(GV->getAlignment())+1);
525 Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0);
526 if (GV->isThreadLocal() ||
527 GV->getVisibility() != GlobalValue::DefaultVisibility ||
528 GV->hasUnnamedAddr()) {
529 Vals.push_back(getEncodedVisibility(GV));
530 Vals.push_back(GV->isThreadLocal());
531 Vals.push_back(GV->hasUnnamedAddr());
532 } else {
533 AbbrevToUse = SimpleGVarAbbrev;
534 }
535
536 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
537 Vals.clear();
538 }
539
540 // Emit the function proto information.
541 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
542 // FUNCTION: [type, callingconv, isproto, paramattr,
543 // linkage, alignment, section, visibility, gc, unnamed_addr]
544 Vals.push_back(VE.getTypeID(F->getType()));
545 Vals.push_back(F->getCallingConv());
546 Vals.push_back(F->isDeclaration());
547 Vals.push_back(getEncodedLinkage(F));
548 Vals.push_back(VE.getAttributeID(F->getAttributes()));
549 Vals.push_back(Log2_32(F->getAlignment())+1);
550 Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
551 Vals.push_back(getEncodedVisibility(F));
552 Vals.push_back(F->hasGC() ? GCMap[F->getGC()] : 0);
553 Vals.push_back(F->hasUnnamedAddr());
554
555 unsigned AbbrevToUse = 0;
556 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
557 Vals.clear();
558 }
559
560 // Emit the alias information.
561 for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end();
562 AI != E; ++AI) {
563 Vals.push_back(VE.getTypeID(AI->getType()));
564 Vals.push_back(VE.getValueID(AI->getAliasee()));
565 Vals.push_back(getEncodedLinkage(AI));
566 Vals.push_back(getEncodedVisibility(AI));
567 unsigned AbbrevToUse = 0;
568 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
569 Vals.clear();
570 }
571 }
572
GetOptimizationFlags(const Value * V)573 static uint64_t GetOptimizationFlags(const Value *V) {
574 uint64_t Flags = 0;
575
576 if (const OverflowingBinaryOperator *OBO =
577 dyn_cast<OverflowingBinaryOperator>(V)) {
578 if (OBO->hasNoSignedWrap())
579 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
580 if (OBO->hasNoUnsignedWrap())
581 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
582 } else if (const PossiblyExactOperator *PEO =
583 dyn_cast<PossiblyExactOperator>(V)) {
584 if (PEO->isExact())
585 Flags |= 1 << bitc::PEO_EXACT;
586 }
587
588 return Flags;
589 }
590
WriteMDNode(const MDNode * N,const ValueEnumerator & VE,BitstreamWriter & Stream,SmallVector<uint64_t,64> & Record)591 static void WriteMDNode(const MDNode *N,
592 const ValueEnumerator &VE,
593 BitstreamWriter &Stream,
594 SmallVector<uint64_t, 64> &Record) {
595 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
596 if (N->getOperand(i)) {
597 Record.push_back(VE.getTypeID(N->getOperand(i)->getType()));
598 Record.push_back(VE.getValueID(N->getOperand(i)));
599 } else {
600 Record.push_back(VE.getTypeID(Type::getVoidTy(N->getContext())));
601 Record.push_back(0);
602 }
603 }
604 unsigned MDCode = N->isFunctionLocal() ? METADATA_FN_NODE_2_7 :
605 METADATA_NODE_2_7;
606 Stream.EmitRecord(MDCode, Record, 0);
607 Record.clear();
608 }
609
WriteModuleMetadata(const Module * M,const ValueEnumerator & VE,BitstreamWriter & Stream)610 static void WriteModuleMetadata(const Module *M,
611 const ValueEnumerator &VE,
612 BitstreamWriter &Stream) {
613 const ValueEnumerator::ValueList &Vals = VE.getMDValues();
614 bool StartedMetadataBlock = false;
615 unsigned MDSAbbrev = 0;
616 SmallVector<uint64_t, 64> Record;
617 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
618
619 if (const MDNode *N = dyn_cast<MDNode>(Vals[i].first)) {
620 if (!N->isFunctionLocal() || !N->getFunction()) {
621 if (!StartedMetadataBlock) {
622 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
623 StartedMetadataBlock = true;
624 }
625 WriteMDNode(N, VE, Stream, Record);
626 }
627 } else if (const MDString *MDS = dyn_cast<MDString>(Vals[i].first)) {
628 if (!StartedMetadataBlock) {
629 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
630
631 // Abbrev for METADATA_STRING.
632 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
633 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING));
634 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
635 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
636 MDSAbbrev = Stream.EmitAbbrev(Abbv);
637 StartedMetadataBlock = true;
638 }
639
640 // Code: [strchar x N]
641 Record.append(MDS->begin(), MDS->end());
642
643 // Emit the finished record.
644 Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev);
645 Record.clear();
646 }
647 }
648
649 // Write named metadata.
650 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
651 E = M->named_metadata_end(); I != E; ++I) {
652 const NamedMDNode *NMD = I;
653 if (!StartedMetadataBlock) {
654 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
655 StartedMetadataBlock = true;
656 }
657
658 // Write name.
659 StringRef Str = NMD->getName();
660 for (unsigned i = 0, e = Str.size(); i != e; ++i)
661 Record.push_back(Str[i]);
662 Stream.EmitRecord(bitc::METADATA_NAME, Record, 0/*TODO*/);
663 Record.clear();
664
665 // Write named metadata operands.
666 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
667 Record.push_back(VE.getValueID(NMD->getOperand(i)));
668 Stream.EmitRecord(METADATA_NAMED_NODE_2_7, Record, 0);
669 Record.clear();
670 }
671
672 if (StartedMetadataBlock)
673 Stream.ExitBlock();
674 }
675
WriteFunctionLocalMetadata(const Function & F,const ValueEnumerator & VE,BitstreamWriter & Stream)676 static void WriteFunctionLocalMetadata(const Function &F,
677 const ValueEnumerator &VE,
678 BitstreamWriter &Stream) {
679 bool StartedMetadataBlock = false;
680 SmallVector<uint64_t, 64> Record;
681 const SmallVector<const MDNode *, 8> &Vals = VE.getFunctionLocalMDValues();
682 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
683 if (const MDNode *N = Vals[i])
684 if (N->isFunctionLocal() && N->getFunction() == &F) {
685 if (!StartedMetadataBlock) {
686 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
687 StartedMetadataBlock = true;
688 }
689 WriteMDNode(N, VE, Stream, Record);
690 }
691
692 if (StartedMetadataBlock)
693 Stream.ExitBlock();
694 }
695
WriteMetadataAttachment(const Function & F,const ValueEnumerator & VE,BitstreamWriter & Stream)696 static void WriteMetadataAttachment(const Function &F,
697 const ValueEnumerator &VE,
698 BitstreamWriter &Stream) {
699 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
700
701 SmallVector<uint64_t, 64> Record;
702
703 // Write metadata attachments
704 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
705 SmallVector<std::pair<unsigned, MDNode*>, 4> MDs;
706
707 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
708 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
709 I != E; ++I) {
710 MDs.clear();
711 I->getAllMetadataOtherThanDebugLoc(MDs);
712
713 // If no metadata, ignore instruction.
714 if (MDs.empty()) continue;
715
716 Record.push_back(VE.getInstructionID(I));
717
718 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
719 Record.push_back(MDs[i].first);
720 Record.push_back(VE.getValueID(MDs[i].second));
721 }
722 Stream.EmitRecord(METADATA_ATTACHMENT_2_7, Record, 0);
723 Record.clear();
724 }
725
726 Stream.ExitBlock();
727 }
728
WriteModuleMetadataStore(const Module * M,BitstreamWriter & Stream)729 static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) {
730 SmallVector<uint64_t, 64> Record;
731
732 // Write metadata kinds
733 // METADATA_KIND - [n x [id, name]]
734 SmallVector<StringRef, 4> Names;
735 M->getMDKindNames(Names);
736
737 if (Names.empty()) return;
738
739 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
740
741 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
742 Record.push_back(MDKindID);
743 StringRef KName = Names[MDKindID];
744 Record.append(KName.begin(), KName.end());
745
746 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
747 Record.clear();
748 }
749
750 Stream.ExitBlock();
751 }
752
WriteConstants(unsigned FirstVal,unsigned LastVal,const ValueEnumerator & VE,BitstreamWriter & Stream,bool isGlobal)753 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
754 const ValueEnumerator &VE,
755 BitstreamWriter &Stream, bool isGlobal) {
756 if (FirstVal == LastVal) return;
757
758 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
759
760 unsigned AggregateAbbrev = 0;
761 unsigned String8Abbrev = 0;
762 unsigned CString7Abbrev = 0;
763 unsigned CString6Abbrev = 0;
764 // If this is a constant pool for the module, emit module-specific abbrevs.
765 if (isGlobal) {
766 // Abbrev for CST_CODE_AGGREGATE.
767 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
768 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
769 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
770 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
771 AggregateAbbrev = Stream.EmitAbbrev(Abbv);
772
773 // Abbrev for CST_CODE_STRING.
774 Abbv = new BitCodeAbbrev();
775 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
776 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
777 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
778 String8Abbrev = Stream.EmitAbbrev(Abbv);
779 // Abbrev for CST_CODE_CSTRING.
780 Abbv = new BitCodeAbbrev();
781 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
782 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
783 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
784 CString7Abbrev = Stream.EmitAbbrev(Abbv);
785 // Abbrev for CST_CODE_CSTRING.
786 Abbv = new BitCodeAbbrev();
787 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
788 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
789 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
790 CString6Abbrev = Stream.EmitAbbrev(Abbv);
791 }
792
793 SmallVector<uint64_t, 64> Record;
794
795 const ValueEnumerator::ValueList &Vals = VE.getValues();
796 Type *LastTy = 0;
797 for (unsigned i = FirstVal; i != LastVal; ++i) {
798 const Value *V = Vals[i].first;
799 // If we need to switch types, do so now.
800 if (V->getType() != LastTy) {
801 LastTy = V->getType();
802 Record.push_back(VE.getTypeID(LastTy));
803 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
804 CONSTANTS_SETTYPE_ABBREV);
805 Record.clear();
806 }
807
808 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
809 Record.push_back(unsigned(IA->hasSideEffects()) |
810 unsigned(IA->isAlignStack()) << 1);
811
812 // Add the asm string.
813 const std::string &AsmStr = IA->getAsmString();
814 Record.push_back(AsmStr.size());
815 for (unsigned i = 0, e = AsmStr.size(); i != e; ++i)
816 Record.push_back(AsmStr[i]);
817
818 // Add the constraint string.
819 const std::string &ConstraintStr = IA->getConstraintString();
820 Record.push_back(ConstraintStr.size());
821 for (unsigned i = 0, e = ConstraintStr.size(); i != e; ++i)
822 Record.push_back(ConstraintStr[i]);
823 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
824 Record.clear();
825 continue;
826 }
827 const Constant *C = cast<Constant>(V);
828 unsigned Code = -1U;
829 unsigned AbbrevToUse = 0;
830 if (C->isNullValue()) {
831 Code = bitc::CST_CODE_NULL;
832 } else if (isa<UndefValue>(C)) {
833 Code = bitc::CST_CODE_UNDEF;
834 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
835 if (IV->getBitWidth() <= 64) {
836 uint64_t V = IV->getSExtValue();
837 if ((int64_t)V >= 0)
838 Record.push_back(V << 1);
839 else
840 Record.push_back((-V << 1) | 1);
841 Code = bitc::CST_CODE_INTEGER;
842 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
843 } else { // Wide integers, > 64 bits in size.
844 // We have an arbitrary precision integer value to write whose
845 // bit width is > 64. However, in canonical unsigned integer
846 // format it is likely that the high bits are going to be zero.
847 // So, we only write the number of active words.
848 unsigned NWords = IV->getValue().getActiveWords();
849 const uint64_t *RawWords = IV->getValue().getRawData();
850 for (unsigned i = 0; i != NWords; ++i) {
851 int64_t V = RawWords[i];
852 if (V >= 0)
853 Record.push_back(V << 1);
854 else
855 Record.push_back((-V << 1) | 1);
856 }
857 Code = bitc::CST_CODE_WIDE_INTEGER;
858 }
859 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
860 Code = bitc::CST_CODE_FLOAT;
861 Type *Ty = CFP->getType();
862 if (Ty->isFloatTy() || Ty->isDoubleTy()) {
863 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
864 } else if (Ty->isX86_FP80Ty()) {
865 // api needed to prevent premature destruction
866 // bits are not in the same order as a normal i80 APInt, compensate.
867 APInt api = CFP->getValueAPF().bitcastToAPInt();
868 const uint64_t *p = api.getRawData();
869 Record.push_back((p[1] << 48) | (p[0] >> 16));
870 Record.push_back(p[0] & 0xffffLL);
871 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
872 APInt api = CFP->getValueAPF().bitcastToAPInt();
873 const uint64_t *p = api.getRawData();
874 Record.push_back(p[0]);
875 Record.push_back(p[1]);
876 } else {
877 assert (0 && "Unknown FP type!");
878 }
879 } else if (isa<ConstantArray>(C) && cast<ConstantArray>(C)->isString()) {
880 const ConstantArray *CA = cast<ConstantArray>(C);
881 // Emit constant strings specially.
882 unsigned NumOps = CA->getNumOperands();
883 // If this is a null-terminated string, use the denser CSTRING encoding.
884 if (CA->getOperand(NumOps-1)->isNullValue()) {
885 Code = bitc::CST_CODE_CSTRING;
886 --NumOps; // Don't encode the null, which isn't allowed by char6.
887 } else {
888 Code = bitc::CST_CODE_STRING;
889 AbbrevToUse = String8Abbrev;
890 }
891 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
892 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
893 for (unsigned i = 0; i != NumOps; ++i) {
894 unsigned char V = cast<ConstantInt>(CA->getOperand(i))->getZExtValue();
895 Record.push_back(V);
896 isCStr7 &= (V & 128) == 0;
897 if (isCStrChar6)
898 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
899 }
900
901 if (isCStrChar6)
902 AbbrevToUse = CString6Abbrev;
903 else if (isCStr7)
904 AbbrevToUse = CString7Abbrev;
905 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(V) ||
906 isa<ConstantVector>(V)) {
907 Code = bitc::CST_CODE_AGGREGATE;
908 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
909 Record.push_back(VE.getValueID(C->getOperand(i)));
910 AbbrevToUse = AggregateAbbrev;
911 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
912 switch (CE->getOpcode()) {
913 default:
914 if (Instruction::isCast(CE->getOpcode())) {
915 Code = bitc::CST_CODE_CE_CAST;
916 Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
917 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
918 Record.push_back(VE.getValueID(C->getOperand(0)));
919 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
920 } else {
921 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
922 Code = bitc::CST_CODE_CE_BINOP;
923 Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
924 Record.push_back(VE.getValueID(C->getOperand(0)));
925 Record.push_back(VE.getValueID(C->getOperand(1)));
926 uint64_t Flags = GetOptimizationFlags(CE);
927 if (Flags != 0)
928 Record.push_back(Flags);
929 }
930 break;
931 case Instruction::GetElementPtr:
932 Code = bitc::CST_CODE_CE_GEP;
933 if (cast<GEPOperator>(C)->isInBounds())
934 Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
935 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
936 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
937 Record.push_back(VE.getValueID(C->getOperand(i)));
938 }
939 break;
940 case Instruction::Select:
941 Code = bitc::CST_CODE_CE_SELECT;
942 Record.push_back(VE.getValueID(C->getOperand(0)));
943 Record.push_back(VE.getValueID(C->getOperand(1)));
944 Record.push_back(VE.getValueID(C->getOperand(2)));
945 break;
946 case Instruction::ExtractElement:
947 Code = bitc::CST_CODE_CE_EXTRACTELT;
948 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
949 Record.push_back(VE.getValueID(C->getOperand(0)));
950 Record.push_back(VE.getValueID(C->getOperand(1)));
951 break;
952 case Instruction::InsertElement:
953 Code = bitc::CST_CODE_CE_INSERTELT;
954 Record.push_back(VE.getValueID(C->getOperand(0)));
955 Record.push_back(VE.getValueID(C->getOperand(1)));
956 Record.push_back(VE.getValueID(C->getOperand(2)));
957 break;
958 case Instruction::ShuffleVector:
959 // If the return type and argument types are the same, this is a
960 // standard shufflevector instruction. If the types are different,
961 // then the shuffle is widening or truncating the input vectors, and
962 // the argument type must also be encoded.
963 if (C->getType() == C->getOperand(0)->getType()) {
964 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
965 } else {
966 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
967 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
968 }
969 Record.push_back(VE.getValueID(C->getOperand(0)));
970 Record.push_back(VE.getValueID(C->getOperand(1)));
971 Record.push_back(VE.getValueID(C->getOperand(2)));
972 break;
973 case Instruction::ICmp:
974 case Instruction::FCmp:
975 Code = bitc::CST_CODE_CE_CMP;
976 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
977 Record.push_back(VE.getValueID(C->getOperand(0)));
978 Record.push_back(VE.getValueID(C->getOperand(1)));
979 Record.push_back(CE->getPredicate());
980 break;
981 }
982 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
983 Code = bitc::CST_CODE_BLOCKADDRESS;
984 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
985 Record.push_back(VE.getValueID(BA->getFunction()));
986 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
987 } else {
988 #ifndef NDEBUG
989 C->dump();
990 #endif
991 llvm_unreachable("Unknown constant!");
992 }
993 Stream.EmitRecord(Code, Record, AbbrevToUse);
994 Record.clear();
995 }
996
997 Stream.ExitBlock();
998 }
999
WriteModuleConstants(const ValueEnumerator & VE,BitstreamWriter & Stream)1000 static void WriteModuleConstants(const ValueEnumerator &VE,
1001 BitstreamWriter &Stream) {
1002 const ValueEnumerator::ValueList &Vals = VE.getValues();
1003
1004 // Find the first constant to emit, which is the first non-globalvalue value.
1005 // We know globalvalues have been emitted by WriteModuleInfo.
1006 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1007 if (!isa<GlobalValue>(Vals[i].first)) {
1008 WriteConstants(i, Vals.size(), VE, Stream, true);
1009 return;
1010 }
1011 }
1012 }
1013
1014 /// PushValueAndType - The file has to encode both the value and type id for
1015 /// many values, because we need to know what type to create for forward
1016 /// references. However, most operands are not forward references, so this type
1017 /// field is not needed.
1018 ///
1019 /// This function adds V's value ID to Vals. If the value ID is higher than the
1020 /// instruction ID, then it is a forward reference, and it also includes the
1021 /// type ID.
PushValueAndType(const Value * V,unsigned InstID,SmallVector<unsigned,64> & Vals,ValueEnumerator & VE)1022 static bool PushValueAndType(const Value *V, unsigned InstID,
1023 SmallVector<unsigned, 64> &Vals,
1024 ValueEnumerator &VE) {
1025 unsigned ValID = VE.getValueID(V);
1026 Vals.push_back(ValID);
1027 if (ValID >= InstID) {
1028 Vals.push_back(VE.getTypeID(V->getType()));
1029 return true;
1030 }
1031 return false;
1032 }
1033
1034 /// WriteInstruction - Emit an instruction to the specified stream.
WriteInstruction(const Instruction & I,unsigned InstID,ValueEnumerator & VE,BitstreamWriter & Stream,SmallVector<unsigned,64> & Vals)1035 static void WriteInstruction(const Instruction &I, unsigned InstID,
1036 ValueEnumerator &VE, BitstreamWriter &Stream,
1037 SmallVector<unsigned, 64> &Vals) {
1038 unsigned Code = 0;
1039 unsigned AbbrevToUse = 0;
1040 VE.setInstructionID(&I);
1041 switch (I.getOpcode()) {
1042 default:
1043 if (Instruction::isCast(I.getOpcode())) {
1044 Code = bitc::FUNC_CODE_INST_CAST;
1045 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1046 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
1047 Vals.push_back(VE.getTypeID(I.getType()));
1048 Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
1049 } else {
1050 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
1051 Code = bitc::FUNC_CODE_INST_BINOP;
1052 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1053 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
1054 Vals.push_back(VE.getValueID(I.getOperand(1)));
1055 Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
1056 uint64_t Flags = GetOptimizationFlags(&I);
1057 if (Flags != 0) {
1058 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
1059 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
1060 Vals.push_back(Flags);
1061 }
1062 }
1063 break;
1064
1065 case Instruction::GetElementPtr:
1066 Code = bitc::FUNC_CODE_INST_GEP;
1067 if (cast<GEPOperator>(&I)->isInBounds())
1068 Code = bitc::FUNC_CODE_INST_INBOUNDS_GEP;
1069 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1070 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1071 break;
1072 case Instruction::ExtractValue: {
1073 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
1074 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1075 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
1076 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1077 Vals.push_back(*i);
1078 break;
1079 }
1080 case Instruction::InsertValue: {
1081 Code = bitc::FUNC_CODE_INST_INSERTVAL;
1082 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1083 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1084 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
1085 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1086 Vals.push_back(*i);
1087 break;
1088 }
1089 case Instruction::Select:
1090 Code = bitc::FUNC_CODE_INST_VSELECT;
1091 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1092 Vals.push_back(VE.getValueID(I.getOperand(2)));
1093 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1094 break;
1095 case Instruction::ExtractElement:
1096 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
1097 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1098 Vals.push_back(VE.getValueID(I.getOperand(1)));
1099 break;
1100 case Instruction::InsertElement:
1101 Code = bitc::FUNC_CODE_INST_INSERTELT;
1102 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1103 Vals.push_back(VE.getValueID(I.getOperand(1)));
1104 Vals.push_back(VE.getValueID(I.getOperand(2)));
1105 break;
1106 case Instruction::ShuffleVector:
1107 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
1108 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1109 Vals.push_back(VE.getValueID(I.getOperand(1)));
1110 Vals.push_back(VE.getValueID(I.getOperand(2)));
1111 break;
1112 case Instruction::ICmp:
1113 case Instruction::FCmp:
1114 // compare returning Int1Ty or vector of Int1Ty
1115 Code = bitc::FUNC_CODE_INST_CMP2;
1116 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1117 Vals.push_back(VE.getValueID(I.getOperand(1)));
1118 Vals.push_back(cast<CmpInst>(I).getPredicate());
1119 break;
1120
1121 case Instruction::Ret:
1122 {
1123 Code = bitc::FUNC_CODE_INST_RET;
1124 unsigned NumOperands = I.getNumOperands();
1125 if (NumOperands == 0)
1126 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
1127 else if (NumOperands == 1) {
1128 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1129 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
1130 } else {
1131 for (unsigned i = 0, e = NumOperands; i != e; ++i)
1132 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1133 }
1134 }
1135 break;
1136 case Instruction::Br:
1137 {
1138 Code = bitc::FUNC_CODE_INST_BR;
1139 BranchInst &II = cast<BranchInst>(I);
1140 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
1141 if (II.isConditional()) {
1142 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
1143 Vals.push_back(VE.getValueID(II.getCondition()));
1144 }
1145 }
1146 break;
1147 case Instruction::Switch:
1148 Code = bitc::FUNC_CODE_INST_SWITCH;
1149 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1150 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1151 Vals.push_back(VE.getValueID(I.getOperand(i)));
1152 break;
1153 case Instruction::IndirectBr:
1154 Code = bitc::FUNC_CODE_INST_INDIRECTBR;
1155 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1156 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1157 Vals.push_back(VE.getValueID(I.getOperand(i)));
1158 break;
1159
1160 case Instruction::Invoke: {
1161 const InvokeInst *II = cast<InvokeInst>(&I);
1162 const Value *Callee(II->getCalledValue());
1163 PointerType *PTy = cast<PointerType>(Callee->getType());
1164 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1165 Code = bitc::FUNC_CODE_INST_INVOKE;
1166
1167 Vals.push_back(VE.getAttributeID(II->getAttributes()));
1168 Vals.push_back(II->getCallingConv());
1169 Vals.push_back(VE.getValueID(II->getNormalDest()));
1170 Vals.push_back(VE.getValueID(II->getUnwindDest()));
1171 PushValueAndType(Callee, InstID, Vals, VE);
1172
1173 // Emit value #'s for the fixed parameters.
1174 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1175 Vals.push_back(VE.getValueID(I.getOperand(i))); // fixed param.
1176
1177 // Emit type/value pairs for varargs params.
1178 if (FTy->isVarArg()) {
1179 for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
1180 i != e; ++i)
1181 PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
1182 }
1183 break;
1184 }
1185 case Instruction::Unwind:
1186 Code = bitc::FUNC_CODE_INST_UNWIND;
1187 break;
1188 case Instruction::Unreachable:
1189 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
1190 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
1191 break;
1192
1193 case Instruction::PHI: {
1194 const PHINode &PN = cast<PHINode>(I);
1195 Code = bitc::FUNC_CODE_INST_PHI;
1196 Vals.push_back(VE.getTypeID(PN.getType()));
1197 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1198 Vals.push_back(VE.getValueID(PN.getIncomingValue(i)));
1199 Vals.push_back(VE.getValueID(PN.getIncomingBlock(i)));
1200 }
1201 break;
1202 }
1203
1204 case Instruction::Alloca:
1205 Code = bitc::FUNC_CODE_INST_ALLOCA;
1206 Vals.push_back(VE.getTypeID(I.getType()));
1207 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1208 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
1209 Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1);
1210 break;
1211
1212 case Instruction::Load:
1213 Code = bitc::FUNC_CODE_INST_LOAD;
1214 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) // ptr
1215 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
1216
1217 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
1218 Vals.push_back(cast<LoadInst>(I).isVolatile());
1219 break;
1220 case Instruction::Store:
1221 Code = bitc::FUNC_CODE_INST_STORE;
1222 PushValueAndType(I.getOperand(1), InstID, Vals, VE); // ptrty + ptr
1223 Vals.push_back(VE.getValueID(I.getOperand(0))); // val.
1224 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
1225 Vals.push_back(cast<StoreInst>(I).isVolatile());
1226 break;
1227 case Instruction::Call: {
1228 const CallInst &CI = cast<CallInst>(I);
1229 PointerType *PTy = cast<PointerType>(CI.getCalledValue()->getType());
1230 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1231
1232 Code = FUNC_CODE_INST_CALL_2_7;
1233
1234 Vals.push_back(VE.getAttributeID(CI.getAttributes()));
1235 Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall()));
1236 PushValueAndType(CI.getCalledValue(), InstID, Vals, VE); // Callee
1237
1238 // Emit value #'s for the fixed parameters.
1239 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1240 Vals.push_back(VE.getValueID(CI.getArgOperand(i))); // fixed param.
1241
1242 // Emit type/value pairs for varargs params.
1243 if (FTy->isVarArg()) {
1244 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
1245 i != e; ++i)
1246 PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE); // varargs
1247 }
1248 break;
1249 }
1250 case Instruction::VAArg:
1251 Code = bitc::FUNC_CODE_INST_VAARG;
1252 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
1253 Vals.push_back(VE.getValueID(I.getOperand(0))); // valist.
1254 Vals.push_back(VE.getTypeID(I.getType())); // restype.
1255 break;
1256 }
1257
1258 Stream.EmitRecord(Code, Vals, AbbrevToUse);
1259 Vals.clear();
1260 }
1261
1262 // Emit names for globals/functions etc.
WriteValueSymbolTable(const ValueSymbolTable & VST,const ValueEnumerator & VE,BitstreamWriter & Stream)1263 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
1264 const ValueEnumerator &VE,
1265 BitstreamWriter &Stream) {
1266 if (VST.empty()) return;
1267 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
1268
1269 // FIXME: Set up the abbrev, we know how many values there are!
1270 // FIXME: We know if the type names can use 7-bit ascii.
1271 SmallVector<unsigned, 64> NameVals;
1272
1273 for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
1274 SI != SE; ++SI) {
1275
1276 const ValueName &Name = *SI;
1277
1278 // Figure out the encoding to use for the name.
1279 bool is7Bit = true;
1280 bool isChar6 = true;
1281 for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
1282 C != E; ++C) {
1283 if (isChar6)
1284 isChar6 = BitCodeAbbrevOp::isChar6(*C);
1285 if ((unsigned char)*C & 128) {
1286 is7Bit = false;
1287 break; // don't bother scanning the rest.
1288 }
1289 }
1290
1291 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
1292
1293 // VST_ENTRY: [valueid, namechar x N]
1294 // VST_BBENTRY: [bbid, namechar x N]
1295 unsigned Code;
1296 if (isa<BasicBlock>(SI->getValue())) {
1297 Code = bitc::VST_CODE_BBENTRY;
1298 if (isChar6)
1299 AbbrevToUse = VST_BBENTRY_6_ABBREV;
1300 } else {
1301 Code = bitc::VST_CODE_ENTRY;
1302 if (isChar6)
1303 AbbrevToUse = VST_ENTRY_6_ABBREV;
1304 else if (is7Bit)
1305 AbbrevToUse = VST_ENTRY_7_ABBREV;
1306 }
1307
1308 NameVals.push_back(VE.getValueID(SI->getValue()));
1309 for (const char *P = Name.getKeyData(),
1310 *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
1311 NameVals.push_back((unsigned char)*P);
1312
1313 // Emit the finished record.
1314 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
1315 NameVals.clear();
1316 }
1317 Stream.ExitBlock();
1318 }
1319
1320 /// WriteFunction - Emit a function body to the module stream.
WriteFunction(const Function & F,ValueEnumerator & VE,BitstreamWriter & Stream)1321 static void WriteFunction(const Function &F, ValueEnumerator &VE,
1322 BitstreamWriter &Stream) {
1323 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
1324 VE.incorporateFunction(F);
1325
1326 SmallVector<unsigned, 64> Vals;
1327
1328 // Emit the number of basic blocks, so the reader can create them ahead of
1329 // time.
1330 Vals.push_back(VE.getBasicBlocks().size());
1331 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
1332 Vals.clear();
1333
1334 // If there are function-local constants, emit them now.
1335 unsigned CstStart, CstEnd;
1336 VE.getFunctionConstantRange(CstStart, CstEnd);
1337 WriteConstants(CstStart, CstEnd, VE, Stream, false);
1338
1339 // If there is function-local metadata, emit it now.
1340 WriteFunctionLocalMetadata(F, VE, Stream);
1341
1342 // Keep a running idea of what the instruction ID is.
1343 unsigned InstID = CstEnd;
1344
1345 bool NeedsMetadataAttachment = false;
1346
1347 DebugLoc LastDL;
1348
1349 // Finally, emit all the instructions, in order.
1350 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1351 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1352 I != E; ++I) {
1353 WriteInstruction(*I, InstID, VE, Stream, Vals);
1354
1355 if (!I->getType()->isVoidTy())
1356 ++InstID;
1357
1358 // If the instruction has metadata, write a metadata attachment later.
1359 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
1360
1361 // If the instruction has a debug location, emit it.
1362 DebugLoc DL = I->getDebugLoc();
1363 if (DL.isUnknown()) {
1364 // nothing todo.
1365 } else if (DL == LastDL) {
1366 // Just repeat the same debug loc as last time.
1367 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
1368 } else {
1369 MDNode *Scope, *IA;
1370 DL.getScopeAndInlinedAt(Scope, IA, I->getContext());
1371
1372 Vals.push_back(DL.getLine());
1373 Vals.push_back(DL.getCol());
1374 Vals.push_back(Scope ? VE.getValueID(Scope)+1 : 0);
1375 Vals.push_back(IA ? VE.getValueID(IA)+1 : 0);
1376 Stream.EmitRecord(FUNC_CODE_DEBUG_LOC_2_7, Vals);
1377 Vals.clear();
1378
1379 LastDL = DL;
1380 }
1381 }
1382
1383 // Emit names for all the instructions etc.
1384 WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
1385
1386 if (NeedsMetadataAttachment)
1387 WriteMetadataAttachment(F, VE, Stream);
1388 VE.purgeFunction();
1389 Stream.ExitBlock();
1390 }
1391
1392 // Emit blockinfo, which defines the standard abbreviations etc.
WriteBlockInfo(const ValueEnumerator & VE,BitstreamWriter & Stream)1393 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
1394 // We only want to emit block info records for blocks that have multiple
1395 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK. Other
1396 // blocks can defined their abbrevs inline.
1397 Stream.EnterBlockInfoBlock(2);
1398
1399 { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
1400 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1401 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
1402 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1403 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1404 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1405 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1406 Abbv) != VST_ENTRY_8_ABBREV)
1407 llvm_unreachable("Unexpected abbrev ordering!");
1408 }
1409
1410 { // 7-bit fixed width VST_ENTRY strings.
1411 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1412 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1413 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1414 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1415 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1416 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1417 Abbv) != VST_ENTRY_7_ABBREV)
1418 llvm_unreachable("Unexpected abbrev ordering!");
1419 }
1420 { // 6-bit char6 VST_ENTRY strings.
1421 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1422 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1423 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1424 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1425 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1426 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1427 Abbv) != VST_ENTRY_6_ABBREV)
1428 llvm_unreachable("Unexpected abbrev ordering!");
1429 }
1430 { // 6-bit char6 VST_BBENTRY strings.
1431 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1432 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
1433 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1434 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1435 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1436 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1437 Abbv) != VST_BBENTRY_6_ABBREV)
1438 llvm_unreachable("Unexpected abbrev ordering!");
1439 }
1440
1441
1442
1443 { // SETTYPE abbrev for CONSTANTS_BLOCK.
1444 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1445 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
1446 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1447 Log2_32_Ceil(VE.getTypes().size()+1)));
1448 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1449 Abbv) != CONSTANTS_SETTYPE_ABBREV)
1450 llvm_unreachable("Unexpected abbrev ordering!");
1451 }
1452
1453 { // INTEGER abbrev for CONSTANTS_BLOCK.
1454 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1455 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
1456 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1457 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1458 Abbv) != CONSTANTS_INTEGER_ABBREV)
1459 llvm_unreachable("Unexpected abbrev ordering!");
1460 }
1461
1462 { // CE_CAST abbrev for CONSTANTS_BLOCK.
1463 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1464 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
1465 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
1466 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
1467 Log2_32_Ceil(VE.getTypes().size()+1)));
1468 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
1469
1470 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1471 Abbv) != CONSTANTS_CE_CAST_Abbrev)
1472 llvm_unreachable("Unexpected abbrev ordering!");
1473 }
1474 { // NULL abbrev for CONSTANTS_BLOCK.
1475 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1476 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
1477 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1478 Abbv) != CONSTANTS_NULL_Abbrev)
1479 llvm_unreachable("Unexpected abbrev ordering!");
1480 }
1481
1482 // FIXME: This should only use space for first class types!
1483
1484 { // INST_LOAD abbrev for FUNCTION_BLOCK.
1485 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1486 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
1487 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
1488 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
1489 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
1490 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1491 Abbv) != FUNCTION_INST_LOAD_ABBREV)
1492 llvm_unreachable("Unexpected abbrev ordering!");
1493 }
1494 { // INST_BINOP abbrev for FUNCTION_BLOCK.
1495 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1496 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1497 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1498 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1499 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1500 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1501 Abbv) != FUNCTION_INST_BINOP_ABBREV)
1502 llvm_unreachable("Unexpected abbrev ordering!");
1503 }
1504 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
1505 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1506 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1507 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1508 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1509 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1510 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
1511 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1512 Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV)
1513 llvm_unreachable("Unexpected abbrev ordering!");
1514 }
1515 { // INST_CAST abbrev for FUNCTION_BLOCK.
1516 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1517 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
1518 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
1519 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
1520 Log2_32_Ceil(VE.getTypes().size()+1)));
1521 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1522 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1523 Abbv) != FUNCTION_INST_CAST_ABBREV)
1524 llvm_unreachable("Unexpected abbrev ordering!");
1525 }
1526
1527 { // INST_RET abbrev for FUNCTION_BLOCK.
1528 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1529 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1530 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1531 Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
1532 llvm_unreachable("Unexpected abbrev ordering!");
1533 }
1534 { // INST_RET abbrev for FUNCTION_BLOCK.
1535 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1536 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1537 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
1538 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1539 Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
1540 llvm_unreachable("Unexpected abbrev ordering!");
1541 }
1542 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
1543 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1544 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
1545 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1546 Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
1547 llvm_unreachable("Unexpected abbrev ordering!");
1548 }
1549
1550 Stream.ExitBlock();
1551 }
1552
1553
1554 /// WriteModule - Emit the specified module to the bitstream.
WriteModule(const Module * M,BitstreamWriter & Stream)1555 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
1556 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
1557
1558 // Emit the version number if it is non-zero.
1559 if (CurVersion) {
1560 SmallVector<unsigned, 1> Vals;
1561 Vals.push_back(CurVersion);
1562 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
1563 }
1564
1565 // Analyze the module, enumerating globals, functions, etc.
1566 ValueEnumerator VE(M);
1567
1568 // Emit blockinfo, which defines the standard abbreviations etc.
1569 WriteBlockInfo(VE, Stream);
1570
1571 // Emit information about parameter attributes.
1572 WriteAttributeTable(VE, Stream);
1573
1574 // Emit information describing all of the types in the module.
1575 WriteTypeTable(VE, Stream);
1576
1577 // Emit top-level description of module, including target triple, inline asm,
1578 // descriptors for global variables, and function prototype info.
1579 WriteModuleInfo(M, VE, Stream);
1580
1581 // Emit constants.
1582 WriteModuleConstants(VE, Stream);
1583
1584 // Emit metadata.
1585 WriteModuleMetadata(M, VE, Stream);
1586
1587 // Emit function bodies.
1588 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F)
1589 if (!F->isDeclaration())
1590 WriteFunction(*F, VE, Stream);
1591
1592 // Emit metadata.
1593 WriteModuleMetadataStore(M, Stream);
1594
1595 // Emit names for globals/functions etc.
1596 WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
1597
1598 Stream.ExitBlock();
1599 }
1600
1601 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
1602 /// header and trailer to make it compatible with the system archiver. To do
1603 /// this we emit the following header, and then emit a trailer that pads the
1604 /// file out to be a multiple of 16 bytes.
1605 ///
1606 /// struct bc_header {
1607 /// uint32_t Magic; // 0x0B17C0DE
1608 /// uint32_t Version; // Version, currently always 0.
1609 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
1610 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
1611 /// uint32_t CPUType; // CPU specifier.
1612 /// ... potentially more later ...
1613 /// };
1614 enum {
1615 DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
1616 DarwinBCHeaderSize = 5*4
1617 };
1618
EmitDarwinBCHeader(BitstreamWriter & Stream,const Triple & TT)1619 static void EmitDarwinBCHeader(BitstreamWriter &Stream, const Triple &TT) {
1620 unsigned CPUType = ~0U;
1621
1622 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
1623 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
1624 // number from /usr/include/mach/machine.h. It is ok to reproduce the
1625 // specific constants here because they are implicitly part of the Darwin ABI.
1626 enum {
1627 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
1628 DARWIN_CPU_TYPE_X86 = 7,
1629 DARWIN_CPU_TYPE_ARM = 12,
1630 DARWIN_CPU_TYPE_POWERPC = 18
1631 };
1632
1633 Triple::ArchType Arch = TT.getArch();
1634 if (Arch == Triple::x86_64)
1635 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
1636 else if (Arch == Triple::x86)
1637 CPUType = DARWIN_CPU_TYPE_X86;
1638 else if (Arch == Triple::ppc)
1639 CPUType = DARWIN_CPU_TYPE_POWERPC;
1640 else if (Arch == Triple::ppc64)
1641 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
1642 else if (Arch == Triple::arm || Arch == Triple::thumb)
1643 CPUType = DARWIN_CPU_TYPE_ARM;
1644
1645 // Traditional Bitcode starts after header.
1646 unsigned BCOffset = DarwinBCHeaderSize;
1647
1648 Stream.Emit(0x0B17C0DE, 32);
1649 Stream.Emit(0 , 32); // Version.
1650 Stream.Emit(BCOffset , 32);
1651 Stream.Emit(0 , 32); // Filled in later.
1652 Stream.Emit(CPUType , 32);
1653 }
1654
1655 /// EmitDarwinBCTrailer - Emit the darwin epilog after the bitcode file and
1656 /// finalize the header.
EmitDarwinBCTrailer(BitstreamWriter & Stream,unsigned BufferSize)1657 static void EmitDarwinBCTrailer(BitstreamWriter &Stream, unsigned BufferSize) {
1658 // Update the size field in the header.
1659 Stream.BackpatchWord(DarwinBCSizeFieldOffset, BufferSize-DarwinBCHeaderSize);
1660
1661 // If the file is not a multiple of 16 bytes, insert dummy padding.
1662 while (BufferSize & 15) {
1663 Stream.Emit(0, 8);
1664 ++BufferSize;
1665 }
1666 }
1667
1668
1669 /// WriteBitcodeToFile - Write the specified module to the specified output
1670 /// stream.
WriteBitcodeToFile(const Module * M,raw_ostream & Out)1671 void llvm_2_9::WriteBitcodeToFile(const Module *M, raw_ostream &Out) {
1672 std::vector<unsigned char> Buffer;
1673 BitstreamWriter Stream(Buffer);
1674
1675 Buffer.reserve(256*1024);
1676
1677 WriteBitcodeToStream( M, Stream );
1678
1679 // Write the generated bitstream to "Out".
1680 Out.write((char*)&Buffer.front(), Buffer.size());
1681 }
1682
1683 /// WriteBitcodeToStream - Write the specified module to the specified output
1684 /// stream.
WriteBitcodeToStream(const Module * M,BitstreamWriter & Stream)1685 void llvm_2_9::WriteBitcodeToStream(const Module *M, BitstreamWriter &Stream) {
1686 // If this is darwin or another generic macho target, emit a file header and
1687 // trailer if needed.
1688 Triple TT(M->getTargetTriple());
1689 if (TT.isOSDarwin())
1690 EmitDarwinBCHeader(Stream, TT);
1691
1692 // Emit the file header.
1693 Stream.Emit((unsigned)'B', 8);
1694 Stream.Emit((unsigned)'C', 8);
1695 Stream.Emit(0x0, 4);
1696 Stream.Emit(0xC, 4);
1697 Stream.Emit(0xE, 4);
1698 Stream.Emit(0xD, 4);
1699
1700 // Emit the module.
1701 WriteModule(M, Stream);
1702
1703 if (TT.isOSDarwin())
1704 EmitDarwinBCTrailer(Stream, Stream.getBuffer().size());
1705 }
1706