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