1 //===--- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Bitcode writer implementation.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Bitcode/ReaderWriter.h"
15 #include "ValueEnumerator.h"
16 #include "llvm/ADT/Triple.h"
17 #include "llvm/Bitcode/BitstreamWriter.h"
18 #include "llvm/Bitcode/LLVMBitCodes.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/DerivedTypes.h"
21 #include "llvm/IR/InlineAsm.h"
22 #include "llvm/IR/Instructions.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/Operator.h"
25 #include "llvm/IR/ValueSymbolTable.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/MathExtras.h"
29 #include "llvm/Support/Program.h"
30 #include "llvm/Support/raw_ostream.h"
36 EnablePreserveUseListOrdering("enable-bc-uselist-preserve",
37 cl::desc("Turn on experimental support for "
38 "use-list order preservation."),
39 cl::init(false), cl::Hidden);
41 /// These are manifest constants used by the bitcode writer. They do not need to
42 /// be kept in sync with the reader, but need to be consistent within this file.
44 // VALUE_SYMTAB_BLOCK abbrev id's.
45 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
50 // CONSTANTS_BLOCK abbrev id's.
51 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
52 CONSTANTS_INTEGER_ABBREV,
53 CONSTANTS_CE_CAST_Abbrev,
54 CONSTANTS_NULL_Abbrev,
56 // FUNCTION_BLOCK abbrev id's.
57 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
58 FUNCTION_INST_BINOP_ABBREV,
59 FUNCTION_INST_BINOP_FLAGS_ABBREV,
60 FUNCTION_INST_CAST_ABBREV,
61 FUNCTION_INST_RET_VOID_ABBREV,
62 FUNCTION_INST_RET_VAL_ABBREV,
63 FUNCTION_INST_UNREACHABLE_ABBREV
66 static unsigned GetEncodedCastOpcode(unsigned Opcode) {
68 default: llvm_unreachable("Unknown cast instruction!");
69 case Instruction::Trunc : return bitc::CAST_TRUNC;
70 case Instruction::ZExt : return bitc::CAST_ZEXT;
71 case Instruction::SExt : return bitc::CAST_SEXT;
72 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
73 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
74 case Instruction::UIToFP : return bitc::CAST_UITOFP;
75 case Instruction::SIToFP : return bitc::CAST_SITOFP;
76 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
77 case Instruction::FPExt : return bitc::CAST_FPEXT;
78 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
79 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
80 case Instruction::BitCast : return bitc::CAST_BITCAST;
84 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
86 default: llvm_unreachable("Unknown binary instruction!");
87 case Instruction::Add:
88 case Instruction::FAdd: return bitc::BINOP_ADD;
89 case Instruction::Sub:
90 case Instruction::FSub: return bitc::BINOP_SUB;
91 case Instruction::Mul:
92 case Instruction::FMul: return bitc::BINOP_MUL;
93 case Instruction::UDiv: return bitc::BINOP_UDIV;
94 case Instruction::FDiv:
95 case Instruction::SDiv: return bitc::BINOP_SDIV;
96 case Instruction::URem: return bitc::BINOP_UREM;
97 case Instruction::FRem:
98 case Instruction::SRem: return bitc::BINOP_SREM;
99 case Instruction::Shl: return bitc::BINOP_SHL;
100 case Instruction::LShr: return bitc::BINOP_LSHR;
101 case Instruction::AShr: return bitc::BINOP_ASHR;
102 case Instruction::And: return bitc::BINOP_AND;
103 case Instruction::Or: return bitc::BINOP_OR;
104 case Instruction::Xor: return bitc::BINOP_XOR;
108 static unsigned GetEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
110 default: llvm_unreachable("Unknown RMW operation!");
111 case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
112 case AtomicRMWInst::Add: return bitc::RMW_ADD;
113 case AtomicRMWInst::Sub: return bitc::RMW_SUB;
114 case AtomicRMWInst::And: return bitc::RMW_AND;
115 case AtomicRMWInst::Nand: return bitc::RMW_NAND;
116 case AtomicRMWInst::Or: return bitc::RMW_OR;
117 case AtomicRMWInst::Xor: return bitc::RMW_XOR;
118 case AtomicRMWInst::Max: return bitc::RMW_MAX;
119 case AtomicRMWInst::Min: return bitc::RMW_MIN;
120 case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
121 case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
125 static unsigned GetEncodedOrdering(AtomicOrdering Ordering) {
127 case NotAtomic: return bitc::ORDERING_NOTATOMIC;
128 case Unordered: return bitc::ORDERING_UNORDERED;
129 case Monotonic: return bitc::ORDERING_MONOTONIC;
130 case Acquire: return bitc::ORDERING_ACQUIRE;
131 case Release: return bitc::ORDERING_RELEASE;
132 case AcquireRelease: return bitc::ORDERING_ACQREL;
133 case SequentiallyConsistent: return bitc::ORDERING_SEQCST;
135 llvm_unreachable("Invalid ordering");
138 static unsigned GetEncodedSynchScope(SynchronizationScope SynchScope) {
139 switch (SynchScope) {
140 case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD;
141 case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD;
143 llvm_unreachable("Invalid synch scope");
146 static void WriteStringRecord(unsigned Code, StringRef Str,
147 unsigned AbbrevToUse, BitstreamWriter &Stream) {
148 SmallVector<unsigned, 64> Vals;
150 // Code: [strchar x N]
151 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
152 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
154 Vals.push_back(Str[i]);
157 // Emit the finished record.
158 Stream.EmitRecord(Code, Vals, AbbrevToUse);
161 static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
163 case Attribute::Alignment:
164 return bitc::ATTR_KIND_ALIGNMENT;
165 case Attribute::AlwaysInline:
166 return bitc::ATTR_KIND_ALWAYS_INLINE;
167 case Attribute::Builtin:
168 return bitc::ATTR_KIND_BUILTIN;
169 case Attribute::ByVal:
170 return bitc::ATTR_KIND_BY_VAL;
171 case Attribute::Cold:
172 return bitc::ATTR_KIND_COLD;
173 case Attribute::InlineHint:
174 return bitc::ATTR_KIND_INLINE_HINT;
175 case Attribute::InReg:
176 return bitc::ATTR_KIND_IN_REG;
177 case Attribute::MinSize:
178 return bitc::ATTR_KIND_MIN_SIZE;
179 case Attribute::Naked:
180 return bitc::ATTR_KIND_NAKED;
181 case Attribute::Nest:
182 return bitc::ATTR_KIND_NEST;
183 case Attribute::NoAlias:
184 return bitc::ATTR_KIND_NO_ALIAS;
185 case Attribute::NoBuiltin:
186 return bitc::ATTR_KIND_NO_BUILTIN;
187 case Attribute::NoCapture:
188 return bitc::ATTR_KIND_NO_CAPTURE;
189 case Attribute::NoDuplicate:
190 return bitc::ATTR_KIND_NO_DUPLICATE;
191 case Attribute::NoImplicitFloat:
192 return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
193 case Attribute::NoInline:
194 return bitc::ATTR_KIND_NO_INLINE;
195 case Attribute::NonLazyBind:
196 return bitc::ATTR_KIND_NON_LAZY_BIND;
197 case Attribute::NoRedZone:
198 return bitc::ATTR_KIND_NO_RED_ZONE;
199 case Attribute::NoReturn:
200 return bitc::ATTR_KIND_NO_RETURN;
201 case Attribute::NoUnwind:
202 return bitc::ATTR_KIND_NO_UNWIND;
203 case Attribute::OptimizeForSize:
204 return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
205 case Attribute::OptimizeNone:
206 return bitc::ATTR_KIND_OPTIMIZE_NONE;
207 case Attribute::ReadNone:
208 return bitc::ATTR_KIND_READ_NONE;
209 case Attribute::ReadOnly:
210 return bitc::ATTR_KIND_READ_ONLY;
211 case Attribute::Returned:
212 return bitc::ATTR_KIND_RETURNED;
213 case Attribute::ReturnsTwice:
214 return bitc::ATTR_KIND_RETURNS_TWICE;
215 case Attribute::SExt:
216 return bitc::ATTR_KIND_S_EXT;
217 case Attribute::StackAlignment:
218 return bitc::ATTR_KIND_STACK_ALIGNMENT;
219 case Attribute::StackProtect:
220 return bitc::ATTR_KIND_STACK_PROTECT;
221 case Attribute::StackProtectReq:
222 return bitc::ATTR_KIND_STACK_PROTECT_REQ;
223 case Attribute::StackProtectStrong:
224 return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
225 case Attribute::StructRet:
226 return bitc::ATTR_KIND_STRUCT_RET;
227 case Attribute::SanitizeAddress:
228 return bitc::ATTR_KIND_SANITIZE_ADDRESS;
229 case Attribute::SanitizeThread:
230 return bitc::ATTR_KIND_SANITIZE_THREAD;
231 case Attribute::SanitizeMemory:
232 return bitc::ATTR_KIND_SANITIZE_MEMORY;
233 case Attribute::UWTable:
234 return bitc::ATTR_KIND_UW_TABLE;
235 case Attribute::ZExt:
236 return bitc::ATTR_KIND_Z_EXT;
237 case Attribute::EndAttrKinds:
238 llvm_unreachable("Can not encode end-attribute kinds marker.");
239 case Attribute::None:
240 llvm_unreachable("Can not encode none-attribute.");
243 llvm_unreachable("Trying to encode unknown attribute");
246 static void WriteAttributeGroupTable(const ValueEnumerator &VE,
247 BitstreamWriter &Stream) {
248 const std::vector<AttributeSet> &AttrGrps = VE.getAttributeGroups();
249 if (AttrGrps.empty()) return;
251 Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
253 SmallVector<uint64_t, 64> Record;
254 for (unsigned i = 0, e = AttrGrps.size(); i != e; ++i) {
255 AttributeSet AS = AttrGrps[i];
256 for (unsigned i = 0, e = AS.getNumSlots(); i != e; ++i) {
257 AttributeSet A = AS.getSlotAttributes(i);
259 Record.push_back(VE.getAttributeGroupID(A));
260 Record.push_back(AS.getSlotIndex(i));
262 for (AttributeSet::iterator I = AS.begin(0), E = AS.end(0);
265 if (Attr.isEnumAttribute()) {
267 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
268 } else if (Attr.isAlignAttribute()) {
270 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
271 Record.push_back(Attr.getValueAsInt());
273 StringRef Kind = Attr.getKindAsString();
274 StringRef Val = Attr.getValueAsString();
276 Record.push_back(Val.empty() ? 3 : 4);
277 Record.append(Kind.begin(), Kind.end());
280 Record.append(Val.begin(), Val.end());
286 Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
294 static void WriteAttributeTable(const ValueEnumerator &VE,
295 BitstreamWriter &Stream) {
296 const std::vector<AttributeSet> &Attrs = VE.getAttributes();
297 if (Attrs.empty()) return;
299 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
301 SmallVector<uint64_t, 64> Record;
302 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
303 const AttributeSet &A = Attrs[i];
304 for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i)
305 Record.push_back(VE.getAttributeGroupID(A.getSlotAttributes(i)));
307 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
314 /// WriteTypeTable - Write out the type table for a module.
315 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
316 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
318 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
319 SmallVector<uint64_t, 64> TypeVals;
321 uint64_t NumBits = Log2_32_Ceil(VE.getTypes().size()+1);
323 // Abbrev for TYPE_CODE_POINTER.
324 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
325 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
326 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
327 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
328 unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
330 // Abbrev for TYPE_CODE_FUNCTION.
331 Abbv = new BitCodeAbbrev();
332 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
333 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
334 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
335 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
337 unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
339 // Abbrev for TYPE_CODE_STRUCT_ANON.
340 Abbv = new BitCodeAbbrev();
341 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
342 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
343 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
344 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
346 unsigned StructAnonAbbrev = Stream.EmitAbbrev(Abbv);
348 // Abbrev for TYPE_CODE_STRUCT_NAME.
349 Abbv = new BitCodeAbbrev();
350 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
351 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
352 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
353 unsigned StructNameAbbrev = Stream.EmitAbbrev(Abbv);
355 // Abbrev for TYPE_CODE_STRUCT_NAMED.
356 Abbv = new BitCodeAbbrev();
357 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
358 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
359 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
360 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
362 unsigned StructNamedAbbrev = Stream.EmitAbbrev(Abbv);
364 // Abbrev for TYPE_CODE_ARRAY.
365 Abbv = new BitCodeAbbrev();
366 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
367 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
368 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
370 unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
372 // Emit an entry count so the reader can reserve space.
373 TypeVals.push_back(TypeList.size());
374 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
377 // Loop over all of the types, emitting each in turn.
378 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
379 Type *T = TypeList[i];
383 switch (T->getTypeID()) {
384 default: llvm_unreachable("Unknown type!");
385 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
386 case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break;
387 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
388 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
389 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
390 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
391 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
392 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
393 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
394 case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break;
395 case Type::IntegerTyID:
397 Code = bitc::TYPE_CODE_INTEGER;
398 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
400 case Type::PointerTyID: {
401 PointerType *PTy = cast<PointerType>(T);
402 // POINTER: [pointee type, address space]
403 Code = bitc::TYPE_CODE_POINTER;
404 TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
405 unsigned AddressSpace = PTy->getAddressSpace();
406 TypeVals.push_back(AddressSpace);
407 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
410 case Type::FunctionTyID: {
411 FunctionType *FT = cast<FunctionType>(T);
412 // FUNCTION: [isvararg, retty, paramty x N]
413 Code = bitc::TYPE_CODE_FUNCTION;
414 TypeVals.push_back(FT->isVarArg());
415 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
416 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
417 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
418 AbbrevToUse = FunctionAbbrev;
421 case Type::StructTyID: {
422 StructType *ST = cast<StructType>(T);
423 // STRUCT: [ispacked, eltty x N]
424 TypeVals.push_back(ST->isPacked());
425 // Output all of the element types.
426 for (StructType::element_iterator I = ST->element_begin(),
427 E = ST->element_end(); I != E; ++I)
428 TypeVals.push_back(VE.getTypeID(*I));
430 if (ST->isLiteral()) {
431 Code = bitc::TYPE_CODE_STRUCT_ANON;
432 AbbrevToUse = StructAnonAbbrev;
434 if (ST->isOpaque()) {
435 Code = bitc::TYPE_CODE_OPAQUE;
437 Code = bitc::TYPE_CODE_STRUCT_NAMED;
438 AbbrevToUse = StructNamedAbbrev;
441 // Emit the name if it is present.
442 if (!ST->getName().empty())
443 WriteStringRecord(bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
444 StructNameAbbrev, Stream);
448 case Type::ArrayTyID: {
449 ArrayType *AT = cast<ArrayType>(T);
450 // ARRAY: [numelts, eltty]
451 Code = bitc::TYPE_CODE_ARRAY;
452 TypeVals.push_back(AT->getNumElements());
453 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
454 AbbrevToUse = ArrayAbbrev;
457 case Type::VectorTyID: {
458 VectorType *VT = cast<VectorType>(T);
459 // VECTOR [numelts, eltty]
460 Code = bitc::TYPE_CODE_VECTOR;
461 TypeVals.push_back(VT->getNumElements());
462 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
467 // Emit the finished record.
468 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
475 static unsigned getEncodedLinkage(const GlobalValue *GV) {
476 switch (GV->getLinkage()) {
477 case GlobalValue::ExternalLinkage: return 0;
478 case GlobalValue::WeakAnyLinkage: return 1;
479 case GlobalValue::AppendingLinkage: return 2;
480 case GlobalValue::InternalLinkage: return 3;
481 case GlobalValue::LinkOnceAnyLinkage: return 4;
482 case GlobalValue::DLLImportLinkage: return 5;
483 case GlobalValue::DLLExportLinkage: return 6;
484 case GlobalValue::ExternalWeakLinkage: return 7;
485 case GlobalValue::CommonLinkage: return 8;
486 case GlobalValue::PrivateLinkage: return 9;
487 case GlobalValue::WeakODRLinkage: return 10;
488 case GlobalValue::LinkOnceODRLinkage: return 11;
489 case GlobalValue::AvailableExternallyLinkage: return 12;
490 case GlobalValue::LinkerPrivateLinkage: return 13;
491 case GlobalValue::LinkerPrivateWeakLinkage: return 14;
492 case GlobalValue::LinkOnceODRAutoHideLinkage: return 15;
494 llvm_unreachable("Invalid linkage");
497 static unsigned getEncodedVisibility(const GlobalValue *GV) {
498 switch (GV->getVisibility()) {
499 case GlobalValue::DefaultVisibility: return 0;
500 case GlobalValue::HiddenVisibility: return 1;
501 case GlobalValue::ProtectedVisibility: return 2;
503 llvm_unreachable("Invalid visibility");
506 static unsigned getEncodedThreadLocalMode(const GlobalVariable *GV) {
507 switch (GV->getThreadLocalMode()) {
508 case GlobalVariable::NotThreadLocal: return 0;
509 case GlobalVariable::GeneralDynamicTLSModel: return 1;
510 case GlobalVariable::LocalDynamicTLSModel: return 2;
511 case GlobalVariable::InitialExecTLSModel: return 3;
512 case GlobalVariable::LocalExecTLSModel: return 4;
514 llvm_unreachable("Invalid TLS model");
517 // Emit top-level description of module, including target triple, inline asm,
518 // descriptors for global variables, and function prototype info.
519 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
520 BitstreamWriter &Stream) {
521 // Emit various pieces of data attached to a module.
522 if (!M->getTargetTriple().empty())
523 WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
525 if (!M->getDataLayout().empty())
526 WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(),
528 if (!M->getModuleInlineAsm().empty())
529 WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
532 // Emit information about sections and GC, computing how many there are. Also
533 // compute the maximum alignment value.
534 std::map<std::string, unsigned> SectionMap;
535 std::map<std::string, unsigned> GCMap;
536 unsigned MaxAlignment = 0;
537 unsigned MaxGlobalType = 0;
538 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
540 MaxAlignment = std::max(MaxAlignment, GV->getAlignment());
541 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType()));
542 if (GV->hasSection()) {
543 // Give section names unique ID's.
544 unsigned &Entry = SectionMap[GV->getSection()];
546 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(),
548 Entry = SectionMap.size();
552 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
553 MaxAlignment = std::max(MaxAlignment, F->getAlignment());
554 if (F->hasSection()) {
555 // Give section names unique ID's.
556 unsigned &Entry = SectionMap[F->getSection()];
558 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(),
560 Entry = SectionMap.size();
564 // Same for GC names.
565 unsigned &Entry = GCMap[F->getGC()];
567 WriteStringRecord(bitc::MODULE_CODE_GCNAME, F->getGC(),
569 Entry = GCMap.size();
574 // Emit abbrev for globals, now that we know # sections and max alignment.
575 unsigned SimpleGVarAbbrev = 0;
576 if (!M->global_empty()) {
577 // Add an abbrev for common globals with no visibility or thread localness.
578 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
579 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
580 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
581 Log2_32_Ceil(MaxGlobalType+1)));
582 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Constant.
583 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
584 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // Linkage.
585 if (MaxAlignment == 0) // Alignment.
586 Abbv->Add(BitCodeAbbrevOp(0));
588 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
589 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
590 Log2_32_Ceil(MaxEncAlignment+1)));
592 if (SectionMap.empty()) // Section.
593 Abbv->Add(BitCodeAbbrevOp(0));
595 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
596 Log2_32_Ceil(SectionMap.size()+1)));
597 // Don't bother emitting vis + thread local.
598 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
601 // Emit the global variable information.
602 SmallVector<unsigned, 64> Vals;
603 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
605 unsigned AbbrevToUse = 0;
607 // GLOBALVAR: [type, isconst, initid,
608 // linkage, alignment, section, visibility, threadlocal,
609 // unnamed_addr, externally_initialized]
610 Vals.push_back(VE.getTypeID(GV->getType()));
611 Vals.push_back(GV->isConstant());
612 Vals.push_back(GV->isDeclaration() ? 0 :
613 (VE.getValueID(GV->getInitializer()) + 1));
614 Vals.push_back(getEncodedLinkage(GV));
615 Vals.push_back(Log2_32(GV->getAlignment())+1);
616 Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0);
617 if (GV->isThreadLocal() ||
618 GV->getVisibility() != GlobalValue::DefaultVisibility ||
619 GV->hasUnnamedAddr() || GV->isExternallyInitialized()) {
620 Vals.push_back(getEncodedVisibility(GV));
621 Vals.push_back(getEncodedThreadLocalMode(GV));
622 Vals.push_back(GV->hasUnnamedAddr());
623 Vals.push_back(GV->isExternallyInitialized());
625 AbbrevToUse = SimpleGVarAbbrev;
628 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
632 // Emit the function proto information.
633 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
634 // FUNCTION: [type, callingconv, isproto, linkage, paramattrs, alignment,
635 // section, visibility, gc, unnamed_addr, prefix]
636 Vals.push_back(VE.getTypeID(F->getType()));
637 Vals.push_back(F->getCallingConv());
638 Vals.push_back(F->isDeclaration());
639 Vals.push_back(getEncodedLinkage(F));
640 Vals.push_back(VE.getAttributeID(F->getAttributes()));
641 Vals.push_back(Log2_32(F->getAlignment())+1);
642 Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
643 Vals.push_back(getEncodedVisibility(F));
644 Vals.push_back(F->hasGC() ? GCMap[F->getGC()] : 0);
645 Vals.push_back(F->hasUnnamedAddr());
646 Vals.push_back(F->hasPrefixData() ? (VE.getValueID(F->getPrefixData()) + 1)
649 unsigned AbbrevToUse = 0;
650 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
654 // Emit the alias information.
655 for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end();
657 // ALIAS: [alias type, aliasee val#, linkage, visibility]
658 Vals.push_back(VE.getTypeID(AI->getType()));
659 Vals.push_back(VE.getValueID(AI->getAliasee()));
660 Vals.push_back(getEncodedLinkage(AI));
661 Vals.push_back(getEncodedVisibility(AI));
662 unsigned AbbrevToUse = 0;
663 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
668 static uint64_t GetOptimizationFlags(const Value *V) {
671 if (const OverflowingBinaryOperator *OBO =
672 dyn_cast<OverflowingBinaryOperator>(V)) {
673 if (OBO->hasNoSignedWrap())
674 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
675 if (OBO->hasNoUnsignedWrap())
676 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
677 } else if (const PossiblyExactOperator *PEO =
678 dyn_cast<PossiblyExactOperator>(V)) {
680 Flags |= 1 << bitc::PEO_EXACT;
681 } else if (const FPMathOperator *FPMO =
682 dyn_cast<const FPMathOperator>(V)) {
683 if (FPMO->hasUnsafeAlgebra())
684 Flags |= FastMathFlags::UnsafeAlgebra;
685 if (FPMO->hasNoNaNs())
686 Flags |= FastMathFlags::NoNaNs;
687 if (FPMO->hasNoInfs())
688 Flags |= FastMathFlags::NoInfs;
689 if (FPMO->hasNoSignedZeros())
690 Flags |= FastMathFlags::NoSignedZeros;
691 if (FPMO->hasAllowReciprocal())
692 Flags |= FastMathFlags::AllowReciprocal;
698 static void WriteMDNode(const MDNode *N,
699 const ValueEnumerator &VE,
700 BitstreamWriter &Stream,
701 SmallVectorImpl<uint64_t> &Record) {
702 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
703 if (N->getOperand(i)) {
704 Record.push_back(VE.getTypeID(N->getOperand(i)->getType()));
705 Record.push_back(VE.getValueID(N->getOperand(i)));
707 Record.push_back(VE.getTypeID(Type::getVoidTy(N->getContext())));
711 unsigned MDCode = N->isFunctionLocal() ? bitc::METADATA_FN_NODE :
713 Stream.EmitRecord(MDCode, Record, 0);
717 static void WriteModuleMetadata(const Module *M,
718 const ValueEnumerator &VE,
719 BitstreamWriter &Stream) {
720 const ValueEnumerator::ValueList &Vals = VE.getMDValues();
721 bool StartedMetadataBlock = false;
722 unsigned MDSAbbrev = 0;
723 SmallVector<uint64_t, 64> Record;
724 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
726 if (const MDNode *N = dyn_cast<MDNode>(Vals[i].first)) {
727 if (!N->isFunctionLocal() || !N->getFunction()) {
728 if (!StartedMetadataBlock) {
729 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
730 StartedMetadataBlock = true;
732 WriteMDNode(N, VE, Stream, Record);
734 } else if (const MDString *MDS = dyn_cast<MDString>(Vals[i].first)) {
735 if (!StartedMetadataBlock) {
736 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
738 // Abbrev for METADATA_STRING.
739 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
740 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING));
741 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
742 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
743 MDSAbbrev = Stream.EmitAbbrev(Abbv);
744 StartedMetadataBlock = true;
747 // Code: [strchar x N]
748 Record.append(MDS->begin(), MDS->end());
750 // Emit the finished record.
751 Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev);
756 // Write named metadata.
757 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
758 E = M->named_metadata_end(); I != E; ++I) {
759 const NamedMDNode *NMD = I;
760 if (!StartedMetadataBlock) {
761 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
762 StartedMetadataBlock = true;
766 StringRef Str = NMD->getName();
767 for (unsigned i = 0, e = Str.size(); i != e; ++i)
768 Record.push_back(Str[i]);
769 Stream.EmitRecord(bitc::METADATA_NAME, Record, 0/*TODO*/);
772 // Write named metadata operands.
773 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
774 Record.push_back(VE.getValueID(NMD->getOperand(i)));
775 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
779 if (StartedMetadataBlock)
783 static void WriteFunctionLocalMetadata(const Function &F,
784 const ValueEnumerator &VE,
785 BitstreamWriter &Stream) {
786 bool StartedMetadataBlock = false;
787 SmallVector<uint64_t, 64> Record;
788 const SmallVectorImpl<const MDNode *> &Vals = VE.getFunctionLocalMDValues();
789 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
790 if (const MDNode *N = Vals[i])
791 if (N->isFunctionLocal() && N->getFunction() == &F) {
792 if (!StartedMetadataBlock) {
793 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
794 StartedMetadataBlock = true;
796 WriteMDNode(N, VE, Stream, Record);
799 if (StartedMetadataBlock)
803 static void WriteMetadataAttachment(const Function &F,
804 const ValueEnumerator &VE,
805 BitstreamWriter &Stream) {
806 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
808 SmallVector<uint64_t, 64> Record;
810 // Write metadata attachments
811 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
812 SmallVector<std::pair<unsigned, MDNode*>, 4> MDs;
814 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
815 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
818 I->getAllMetadataOtherThanDebugLoc(MDs);
820 // If no metadata, ignore instruction.
821 if (MDs.empty()) continue;
823 Record.push_back(VE.getInstructionID(I));
825 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
826 Record.push_back(MDs[i].first);
827 Record.push_back(VE.getValueID(MDs[i].second));
829 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
836 static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) {
837 SmallVector<uint64_t, 64> Record;
839 // Write metadata kinds
840 // METADATA_KIND - [n x [id, name]]
841 SmallVector<StringRef, 8> Names;
842 M->getMDKindNames(Names);
844 if (Names.empty()) return;
846 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
848 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
849 Record.push_back(MDKindID);
850 StringRef KName = Names[MDKindID];
851 Record.append(KName.begin(), KName.end());
853 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
860 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
862 Vals.push_back(V << 1);
864 Vals.push_back((-V << 1) | 1);
867 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
868 const ValueEnumerator &VE,
869 BitstreamWriter &Stream, bool isGlobal) {
870 if (FirstVal == LastVal) return;
872 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
874 unsigned AggregateAbbrev = 0;
875 unsigned String8Abbrev = 0;
876 unsigned CString7Abbrev = 0;
877 unsigned CString6Abbrev = 0;
878 // If this is a constant pool for the module, emit module-specific abbrevs.
880 // Abbrev for CST_CODE_AGGREGATE.
881 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
882 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
883 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
884 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
885 AggregateAbbrev = Stream.EmitAbbrev(Abbv);
887 // Abbrev for CST_CODE_STRING.
888 Abbv = new BitCodeAbbrev();
889 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
890 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
891 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
892 String8Abbrev = Stream.EmitAbbrev(Abbv);
893 // Abbrev for CST_CODE_CSTRING.
894 Abbv = new BitCodeAbbrev();
895 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
896 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
897 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
898 CString7Abbrev = Stream.EmitAbbrev(Abbv);
899 // Abbrev for CST_CODE_CSTRING.
900 Abbv = new BitCodeAbbrev();
901 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
902 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
903 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
904 CString6Abbrev = Stream.EmitAbbrev(Abbv);
907 SmallVector<uint64_t, 64> Record;
909 const ValueEnumerator::ValueList &Vals = VE.getValues();
911 for (unsigned i = FirstVal; i != LastVal; ++i) {
912 const Value *V = Vals[i].first;
913 // If we need to switch types, do so now.
914 if (V->getType() != LastTy) {
915 LastTy = V->getType();
916 Record.push_back(VE.getTypeID(LastTy));
917 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
918 CONSTANTS_SETTYPE_ABBREV);
922 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
923 Record.push_back(unsigned(IA->hasSideEffects()) |
924 unsigned(IA->isAlignStack()) << 1 |
925 unsigned(IA->getDialect()&1) << 2);
927 // Add the asm string.
928 const std::string &AsmStr = IA->getAsmString();
929 Record.push_back(AsmStr.size());
930 for (unsigned i = 0, e = AsmStr.size(); i != e; ++i)
931 Record.push_back(AsmStr[i]);
933 // Add the constraint string.
934 const std::string &ConstraintStr = IA->getConstraintString();
935 Record.push_back(ConstraintStr.size());
936 for (unsigned i = 0, e = ConstraintStr.size(); i != e; ++i)
937 Record.push_back(ConstraintStr[i]);
938 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
942 const Constant *C = cast<Constant>(V);
944 unsigned AbbrevToUse = 0;
945 if (C->isNullValue()) {
946 Code = bitc::CST_CODE_NULL;
947 } else if (isa<UndefValue>(C)) {
948 Code = bitc::CST_CODE_UNDEF;
949 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
950 if (IV->getBitWidth() <= 64) {
951 uint64_t V = IV->getSExtValue();
952 emitSignedInt64(Record, V);
953 Code = bitc::CST_CODE_INTEGER;
954 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
955 } else { // Wide integers, > 64 bits in size.
956 // We have an arbitrary precision integer value to write whose
957 // bit width is > 64. However, in canonical unsigned integer
958 // format it is likely that the high bits are going to be zero.
959 // So, we only write the number of active words.
960 unsigned NWords = IV->getValue().getActiveWords();
961 const uint64_t *RawWords = IV->getValue().getRawData();
962 for (unsigned i = 0; i != NWords; ++i) {
963 emitSignedInt64(Record, RawWords[i]);
965 Code = bitc::CST_CODE_WIDE_INTEGER;
967 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
968 Code = bitc::CST_CODE_FLOAT;
969 Type *Ty = CFP->getType();
970 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
971 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
972 } else if (Ty->isX86_FP80Ty()) {
973 // api needed to prevent premature destruction
974 // bits are not in the same order as a normal i80 APInt, compensate.
975 APInt api = CFP->getValueAPF().bitcastToAPInt();
976 const uint64_t *p = api.getRawData();
977 Record.push_back((p[1] << 48) | (p[0] >> 16));
978 Record.push_back(p[0] & 0xffffLL);
979 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
980 APInt api = CFP->getValueAPF().bitcastToAPInt();
981 const uint64_t *p = api.getRawData();
982 Record.push_back(p[0]);
983 Record.push_back(p[1]);
985 assert (0 && "Unknown FP type!");
987 } else if (isa<ConstantDataSequential>(C) &&
988 cast<ConstantDataSequential>(C)->isString()) {
989 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
990 // Emit constant strings specially.
991 unsigned NumElts = Str->getNumElements();
992 // If this is a null-terminated string, use the denser CSTRING encoding.
993 if (Str->isCString()) {
994 Code = bitc::CST_CODE_CSTRING;
995 --NumElts; // Don't encode the null, which isn't allowed by char6.
997 Code = bitc::CST_CODE_STRING;
998 AbbrevToUse = String8Abbrev;
1000 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
1001 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
1002 for (unsigned i = 0; i != NumElts; ++i) {
1003 unsigned char V = Str->getElementAsInteger(i);
1004 Record.push_back(V);
1005 isCStr7 &= (V & 128) == 0;
1007 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
1011 AbbrevToUse = CString6Abbrev;
1013 AbbrevToUse = CString7Abbrev;
1014 } else if (const ConstantDataSequential *CDS =
1015 dyn_cast<ConstantDataSequential>(C)) {
1016 Code = bitc::CST_CODE_DATA;
1017 Type *EltTy = CDS->getType()->getElementType();
1018 if (isa<IntegerType>(EltTy)) {
1019 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
1020 Record.push_back(CDS->getElementAsInteger(i));
1021 } else if (EltTy->isFloatTy()) {
1022 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1023 union { float F; uint32_t I; };
1024 F = CDS->getElementAsFloat(i);
1025 Record.push_back(I);
1028 assert(EltTy->isDoubleTy() && "Unknown ConstantData element type");
1029 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1030 union { double F; uint64_t I; };
1031 F = CDS->getElementAsDouble(i);
1032 Record.push_back(I);
1035 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
1036 isa<ConstantVector>(C)) {
1037 Code = bitc::CST_CODE_AGGREGATE;
1038 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
1039 Record.push_back(VE.getValueID(C->getOperand(i)));
1040 AbbrevToUse = AggregateAbbrev;
1041 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1042 switch (CE->getOpcode()) {
1044 if (Instruction::isCast(CE->getOpcode())) {
1045 Code = bitc::CST_CODE_CE_CAST;
1046 Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
1047 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1048 Record.push_back(VE.getValueID(C->getOperand(0)));
1049 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
1051 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
1052 Code = bitc::CST_CODE_CE_BINOP;
1053 Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
1054 Record.push_back(VE.getValueID(C->getOperand(0)));
1055 Record.push_back(VE.getValueID(C->getOperand(1)));
1056 uint64_t Flags = GetOptimizationFlags(CE);
1058 Record.push_back(Flags);
1061 case Instruction::GetElementPtr:
1062 Code = bitc::CST_CODE_CE_GEP;
1063 if (cast<GEPOperator>(C)->isInBounds())
1064 Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
1065 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
1066 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
1067 Record.push_back(VE.getValueID(C->getOperand(i)));
1070 case Instruction::Select:
1071 Code = bitc::CST_CODE_CE_SELECT;
1072 Record.push_back(VE.getValueID(C->getOperand(0)));
1073 Record.push_back(VE.getValueID(C->getOperand(1)));
1074 Record.push_back(VE.getValueID(C->getOperand(2)));
1076 case Instruction::ExtractElement:
1077 Code = bitc::CST_CODE_CE_EXTRACTELT;
1078 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1079 Record.push_back(VE.getValueID(C->getOperand(0)));
1080 Record.push_back(VE.getValueID(C->getOperand(1)));
1082 case Instruction::InsertElement:
1083 Code = bitc::CST_CODE_CE_INSERTELT;
1084 Record.push_back(VE.getValueID(C->getOperand(0)));
1085 Record.push_back(VE.getValueID(C->getOperand(1)));
1086 Record.push_back(VE.getValueID(C->getOperand(2)));
1088 case Instruction::ShuffleVector:
1089 // If the return type and argument types are the same, this is a
1090 // standard shufflevector instruction. If the types are different,
1091 // then the shuffle is widening or truncating the input vectors, and
1092 // the argument type must also be encoded.
1093 if (C->getType() == C->getOperand(0)->getType()) {
1094 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
1096 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
1097 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1099 Record.push_back(VE.getValueID(C->getOperand(0)));
1100 Record.push_back(VE.getValueID(C->getOperand(1)));
1101 Record.push_back(VE.getValueID(C->getOperand(2)));
1103 case Instruction::ICmp:
1104 case Instruction::FCmp:
1105 Code = bitc::CST_CODE_CE_CMP;
1106 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1107 Record.push_back(VE.getValueID(C->getOperand(0)));
1108 Record.push_back(VE.getValueID(C->getOperand(1)));
1109 Record.push_back(CE->getPredicate());
1112 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
1113 Code = bitc::CST_CODE_BLOCKADDRESS;
1114 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
1115 Record.push_back(VE.getValueID(BA->getFunction()));
1116 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
1121 llvm_unreachable("Unknown constant!");
1123 Stream.EmitRecord(Code, Record, AbbrevToUse);
1130 static void WriteModuleConstants(const ValueEnumerator &VE,
1131 BitstreamWriter &Stream) {
1132 const ValueEnumerator::ValueList &Vals = VE.getValues();
1134 // Find the first constant to emit, which is the first non-globalvalue value.
1135 // We know globalvalues have been emitted by WriteModuleInfo.
1136 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1137 if (!isa<GlobalValue>(Vals[i].first)) {
1138 WriteConstants(i, Vals.size(), VE, Stream, true);
1144 /// PushValueAndType - The file has to encode both the value and type id for
1145 /// many values, because we need to know what type to create for forward
1146 /// references. However, most operands are not forward references, so this type
1147 /// field is not needed.
1149 /// This function adds V's value ID to Vals. If the value ID is higher than the
1150 /// instruction ID, then it is a forward reference, and it also includes the
1151 /// type ID. The value ID that is written is encoded relative to the InstID.
1152 static bool PushValueAndType(const Value *V, unsigned InstID,
1153 SmallVectorImpl<unsigned> &Vals,
1154 ValueEnumerator &VE) {
1155 unsigned ValID = VE.getValueID(V);
1156 // Make encoding relative to the InstID.
1157 Vals.push_back(InstID - ValID);
1158 if (ValID >= InstID) {
1159 Vals.push_back(VE.getTypeID(V->getType()));
1165 /// pushValue - Like PushValueAndType, but where the type of the value is
1166 /// omitted (perhaps it was already encoded in an earlier operand).
1167 static void pushValue(const Value *V, unsigned InstID,
1168 SmallVectorImpl<unsigned> &Vals,
1169 ValueEnumerator &VE) {
1170 unsigned ValID = VE.getValueID(V);
1171 Vals.push_back(InstID - ValID);
1174 static void pushValueSigned(const Value *V, unsigned InstID,
1175 SmallVectorImpl<uint64_t> &Vals,
1176 ValueEnumerator &VE) {
1177 unsigned ValID = VE.getValueID(V);
1178 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
1179 emitSignedInt64(Vals, diff);
1182 /// WriteInstruction - Emit an instruction to the specified stream.
1183 static void WriteInstruction(const Instruction &I, unsigned InstID,
1184 ValueEnumerator &VE, BitstreamWriter &Stream,
1185 SmallVectorImpl<unsigned> &Vals) {
1187 unsigned AbbrevToUse = 0;
1188 VE.setInstructionID(&I);
1189 switch (I.getOpcode()) {
1191 if (Instruction::isCast(I.getOpcode())) {
1192 Code = bitc::FUNC_CODE_INST_CAST;
1193 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1194 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
1195 Vals.push_back(VE.getTypeID(I.getType()));
1196 Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
1198 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
1199 Code = bitc::FUNC_CODE_INST_BINOP;
1200 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1201 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
1202 pushValue(I.getOperand(1), InstID, Vals, VE);
1203 Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
1204 uint64_t Flags = GetOptimizationFlags(&I);
1206 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
1207 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
1208 Vals.push_back(Flags);
1213 case Instruction::GetElementPtr:
1214 Code = bitc::FUNC_CODE_INST_GEP;
1215 if (cast<GEPOperator>(&I)->isInBounds())
1216 Code = bitc::FUNC_CODE_INST_INBOUNDS_GEP;
1217 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1218 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1220 case Instruction::ExtractValue: {
1221 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
1222 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1223 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
1224 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1228 case Instruction::InsertValue: {
1229 Code = bitc::FUNC_CODE_INST_INSERTVAL;
1230 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1231 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1232 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
1233 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1237 case Instruction::Select:
1238 Code = bitc::FUNC_CODE_INST_VSELECT;
1239 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1240 pushValue(I.getOperand(2), InstID, Vals, VE);
1241 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1243 case Instruction::ExtractElement:
1244 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
1245 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1246 pushValue(I.getOperand(1), InstID, Vals, VE);
1248 case Instruction::InsertElement:
1249 Code = bitc::FUNC_CODE_INST_INSERTELT;
1250 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1251 pushValue(I.getOperand(1), InstID, Vals, VE);
1252 pushValue(I.getOperand(2), InstID, Vals, VE);
1254 case Instruction::ShuffleVector:
1255 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
1256 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1257 pushValue(I.getOperand(1), InstID, Vals, VE);
1258 pushValue(I.getOperand(2), InstID, Vals, VE);
1260 case Instruction::ICmp:
1261 case Instruction::FCmp:
1262 // compare returning Int1Ty or vector of Int1Ty
1263 Code = bitc::FUNC_CODE_INST_CMP2;
1264 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1265 pushValue(I.getOperand(1), InstID, Vals, VE);
1266 Vals.push_back(cast<CmpInst>(I).getPredicate());
1269 case Instruction::Ret:
1271 Code = bitc::FUNC_CODE_INST_RET;
1272 unsigned NumOperands = I.getNumOperands();
1273 if (NumOperands == 0)
1274 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
1275 else if (NumOperands == 1) {
1276 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1277 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
1279 for (unsigned i = 0, e = NumOperands; i != e; ++i)
1280 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1284 case Instruction::Br:
1286 Code = bitc::FUNC_CODE_INST_BR;
1287 const BranchInst &II = cast<BranchInst>(I);
1288 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
1289 if (II.isConditional()) {
1290 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
1291 pushValue(II.getCondition(), InstID, Vals, VE);
1295 case Instruction::Switch:
1297 Code = bitc::FUNC_CODE_INST_SWITCH;
1298 const SwitchInst &SI = cast<SwitchInst>(I);
1299 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
1300 pushValue(SI.getCondition(), InstID, Vals, VE);
1301 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
1302 for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
1304 Vals.push_back(VE.getValueID(i.getCaseValue()));
1305 Vals.push_back(VE.getValueID(i.getCaseSuccessor()));
1309 case Instruction::IndirectBr:
1310 Code = bitc::FUNC_CODE_INST_INDIRECTBR;
1311 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1312 // Encode the address operand as relative, but not the basic blocks.
1313 pushValue(I.getOperand(0), InstID, Vals, VE);
1314 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
1315 Vals.push_back(VE.getValueID(I.getOperand(i)));
1318 case Instruction::Invoke: {
1319 const InvokeInst *II = cast<InvokeInst>(&I);
1320 const Value *Callee(II->getCalledValue());
1321 PointerType *PTy = cast<PointerType>(Callee->getType());
1322 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1323 Code = bitc::FUNC_CODE_INST_INVOKE;
1325 Vals.push_back(VE.getAttributeID(II->getAttributes()));
1326 Vals.push_back(II->getCallingConv());
1327 Vals.push_back(VE.getValueID(II->getNormalDest()));
1328 Vals.push_back(VE.getValueID(II->getUnwindDest()));
1329 PushValueAndType(Callee, InstID, Vals, VE);
1331 // Emit value #'s for the fixed parameters.
1332 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1333 pushValue(I.getOperand(i), InstID, Vals, VE); // fixed param.
1335 // Emit type/value pairs for varargs params.
1336 if (FTy->isVarArg()) {
1337 for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
1339 PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
1343 case Instruction::Resume:
1344 Code = bitc::FUNC_CODE_INST_RESUME;
1345 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1347 case Instruction::Unreachable:
1348 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
1349 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
1352 case Instruction::PHI: {
1353 const PHINode &PN = cast<PHINode>(I);
1354 Code = bitc::FUNC_CODE_INST_PHI;
1355 // With the newer instruction encoding, forward references could give
1356 // negative valued IDs. This is most common for PHIs, so we use
1358 SmallVector<uint64_t, 128> Vals64;
1359 Vals64.push_back(VE.getTypeID(PN.getType()));
1360 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1361 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64, VE);
1362 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
1364 // Emit a Vals64 vector and exit.
1365 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
1370 case Instruction::LandingPad: {
1371 const LandingPadInst &LP = cast<LandingPadInst>(I);
1372 Code = bitc::FUNC_CODE_INST_LANDINGPAD;
1373 Vals.push_back(VE.getTypeID(LP.getType()));
1374 PushValueAndType(LP.getPersonalityFn(), InstID, Vals, VE);
1375 Vals.push_back(LP.isCleanup());
1376 Vals.push_back(LP.getNumClauses());
1377 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
1379 Vals.push_back(LandingPadInst::Catch);
1381 Vals.push_back(LandingPadInst::Filter);
1382 PushValueAndType(LP.getClause(I), InstID, Vals, VE);
1387 case Instruction::Alloca:
1388 Code = bitc::FUNC_CODE_INST_ALLOCA;
1389 Vals.push_back(VE.getTypeID(I.getType()));
1390 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1391 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
1392 Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1);
1395 case Instruction::Load:
1396 if (cast<LoadInst>(I).isAtomic()) {
1397 Code = bitc::FUNC_CODE_INST_LOADATOMIC;
1398 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1400 Code = bitc::FUNC_CODE_INST_LOAD;
1401 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) // ptr
1402 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
1404 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
1405 Vals.push_back(cast<LoadInst>(I).isVolatile());
1406 if (cast<LoadInst>(I).isAtomic()) {
1407 Vals.push_back(GetEncodedOrdering(cast<LoadInst>(I).getOrdering()));
1408 Vals.push_back(GetEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
1411 case Instruction::Store:
1412 if (cast<StoreInst>(I).isAtomic())
1413 Code = bitc::FUNC_CODE_INST_STOREATOMIC;
1415 Code = bitc::FUNC_CODE_INST_STORE;
1416 PushValueAndType(I.getOperand(1), InstID, Vals, VE); // ptrty + ptr
1417 pushValue(I.getOperand(0), InstID, Vals, VE); // val.
1418 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
1419 Vals.push_back(cast<StoreInst>(I).isVolatile());
1420 if (cast<StoreInst>(I).isAtomic()) {
1421 Vals.push_back(GetEncodedOrdering(cast<StoreInst>(I).getOrdering()));
1422 Vals.push_back(GetEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
1425 case Instruction::AtomicCmpXchg:
1426 Code = bitc::FUNC_CODE_INST_CMPXCHG;
1427 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr
1428 pushValue(I.getOperand(1), InstID, Vals, VE); // cmp.
1429 pushValue(I.getOperand(2), InstID, Vals, VE); // newval.
1430 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
1431 Vals.push_back(GetEncodedOrdering(
1432 cast<AtomicCmpXchgInst>(I).getOrdering()));
1433 Vals.push_back(GetEncodedSynchScope(
1434 cast<AtomicCmpXchgInst>(I).getSynchScope()));
1436 case Instruction::AtomicRMW:
1437 Code = bitc::FUNC_CODE_INST_ATOMICRMW;
1438 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr
1439 pushValue(I.getOperand(1), InstID, Vals, VE); // val.
1440 Vals.push_back(GetEncodedRMWOperation(
1441 cast<AtomicRMWInst>(I).getOperation()));
1442 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
1443 Vals.push_back(GetEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
1444 Vals.push_back(GetEncodedSynchScope(
1445 cast<AtomicRMWInst>(I).getSynchScope()));
1447 case Instruction::Fence:
1448 Code = bitc::FUNC_CODE_INST_FENCE;
1449 Vals.push_back(GetEncodedOrdering(cast<FenceInst>(I).getOrdering()));
1450 Vals.push_back(GetEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
1452 case Instruction::Call: {
1453 const CallInst &CI = cast<CallInst>(I);
1454 PointerType *PTy = cast<PointerType>(CI.getCalledValue()->getType());
1455 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1457 Code = bitc::FUNC_CODE_INST_CALL;
1459 Vals.push_back(VE.getAttributeID(CI.getAttributes()));
1460 Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall()));
1461 PushValueAndType(CI.getCalledValue(), InstID, Vals, VE); // Callee
1463 // Emit value #'s for the fixed parameters.
1464 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
1465 // Check for labels (can happen with asm labels).
1466 if (FTy->getParamType(i)->isLabelTy())
1467 Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
1469 pushValue(CI.getArgOperand(i), InstID, Vals, VE); // fixed param.
1472 // Emit type/value pairs for varargs params.
1473 if (FTy->isVarArg()) {
1474 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
1476 PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE); // varargs
1480 case Instruction::VAArg:
1481 Code = bitc::FUNC_CODE_INST_VAARG;
1482 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
1483 pushValue(I.getOperand(0), InstID, Vals, VE); // valist.
1484 Vals.push_back(VE.getTypeID(I.getType())); // restype.
1488 Stream.EmitRecord(Code, Vals, AbbrevToUse);
1492 // Emit names for globals/functions etc.
1493 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
1494 const ValueEnumerator &VE,
1495 BitstreamWriter &Stream) {
1496 if (VST.empty()) return;
1497 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
1499 // FIXME: Set up the abbrev, we know how many values there are!
1500 // FIXME: We know if the type names can use 7-bit ascii.
1501 SmallVector<unsigned, 64> NameVals;
1503 for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
1506 const ValueName &Name = *SI;
1508 // Figure out the encoding to use for the name.
1510 bool isChar6 = true;
1511 for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
1514 isChar6 = BitCodeAbbrevOp::isChar6(*C);
1515 if ((unsigned char)*C & 128) {
1517 break; // don't bother scanning the rest.
1521 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
1523 // VST_ENTRY: [valueid, namechar x N]
1524 // VST_BBENTRY: [bbid, namechar x N]
1526 if (isa<BasicBlock>(SI->getValue())) {
1527 Code = bitc::VST_CODE_BBENTRY;
1529 AbbrevToUse = VST_BBENTRY_6_ABBREV;
1531 Code = bitc::VST_CODE_ENTRY;
1533 AbbrevToUse = VST_ENTRY_6_ABBREV;
1535 AbbrevToUse = VST_ENTRY_7_ABBREV;
1538 NameVals.push_back(VE.getValueID(SI->getValue()));
1539 for (const char *P = Name.getKeyData(),
1540 *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
1541 NameVals.push_back((unsigned char)*P);
1543 // Emit the finished record.
1544 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
1550 /// WriteFunction - Emit a function body to the module stream.
1551 static void WriteFunction(const Function &F, ValueEnumerator &VE,
1552 BitstreamWriter &Stream) {
1553 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
1554 VE.incorporateFunction(F);
1556 SmallVector<unsigned, 64> Vals;
1558 // Emit the number of basic blocks, so the reader can create them ahead of
1560 Vals.push_back(VE.getBasicBlocks().size());
1561 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
1564 // If there are function-local constants, emit them now.
1565 unsigned CstStart, CstEnd;
1566 VE.getFunctionConstantRange(CstStart, CstEnd);
1567 WriteConstants(CstStart, CstEnd, VE, Stream, false);
1569 // If there is function-local metadata, emit it now.
1570 WriteFunctionLocalMetadata(F, VE, Stream);
1572 // Keep a running idea of what the instruction ID is.
1573 unsigned InstID = CstEnd;
1575 bool NeedsMetadataAttachment = false;
1579 // Finally, emit all the instructions, in order.
1580 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1581 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1583 WriteInstruction(*I, InstID, VE, Stream, Vals);
1585 if (!I->getType()->isVoidTy())
1588 // If the instruction has metadata, write a metadata attachment later.
1589 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
1591 // If the instruction has a debug location, emit it.
1592 DebugLoc DL = I->getDebugLoc();
1593 if (DL.isUnknown()) {
1595 } else if (DL == LastDL) {
1596 // Just repeat the same debug loc as last time.
1597 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
1600 DL.getScopeAndInlinedAt(Scope, IA, I->getContext());
1602 Vals.push_back(DL.getLine());
1603 Vals.push_back(DL.getCol());
1604 Vals.push_back(Scope ? VE.getValueID(Scope)+1 : 0);
1605 Vals.push_back(IA ? VE.getValueID(IA)+1 : 0);
1606 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
1613 // Emit names for all the instructions etc.
1614 WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
1616 if (NeedsMetadataAttachment)
1617 WriteMetadataAttachment(F, VE, Stream);
1622 // Emit blockinfo, which defines the standard abbreviations etc.
1623 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
1624 // We only want to emit block info records for blocks that have multiple
1625 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
1626 // Other blocks can define their abbrevs inline.
1627 Stream.EnterBlockInfoBlock(2);
1629 { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
1630 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1631 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
1632 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1633 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1634 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1635 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1636 Abbv) != VST_ENTRY_8_ABBREV)
1637 llvm_unreachable("Unexpected abbrev ordering!");
1640 { // 7-bit fixed width VST_ENTRY strings.
1641 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1642 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1643 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1644 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1645 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1646 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1647 Abbv) != VST_ENTRY_7_ABBREV)
1648 llvm_unreachable("Unexpected abbrev ordering!");
1650 { // 6-bit char6 VST_ENTRY strings.
1651 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1652 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1653 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1654 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1655 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1656 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1657 Abbv) != VST_ENTRY_6_ABBREV)
1658 llvm_unreachable("Unexpected abbrev ordering!");
1660 { // 6-bit char6 VST_BBENTRY strings.
1661 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1662 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
1663 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1664 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1665 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1666 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1667 Abbv) != VST_BBENTRY_6_ABBREV)
1668 llvm_unreachable("Unexpected abbrev ordering!");
1673 { // SETTYPE abbrev for CONSTANTS_BLOCK.
1674 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1675 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
1676 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1677 Log2_32_Ceil(VE.getTypes().size()+1)));
1678 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1679 Abbv) != CONSTANTS_SETTYPE_ABBREV)
1680 llvm_unreachable("Unexpected abbrev ordering!");
1683 { // INTEGER abbrev for CONSTANTS_BLOCK.
1684 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1685 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
1686 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1687 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1688 Abbv) != CONSTANTS_INTEGER_ABBREV)
1689 llvm_unreachable("Unexpected abbrev ordering!");
1692 { // CE_CAST abbrev for CONSTANTS_BLOCK.
1693 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1694 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
1695 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
1696 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
1697 Log2_32_Ceil(VE.getTypes().size()+1)));
1698 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
1700 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1701 Abbv) != CONSTANTS_CE_CAST_Abbrev)
1702 llvm_unreachable("Unexpected abbrev ordering!");
1704 { // NULL abbrev for CONSTANTS_BLOCK.
1705 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1706 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
1707 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1708 Abbv) != CONSTANTS_NULL_Abbrev)
1709 llvm_unreachable("Unexpected abbrev ordering!");
1712 // FIXME: This should only use space for first class types!
1714 { // INST_LOAD abbrev for FUNCTION_BLOCK.
1715 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1716 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
1717 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
1718 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
1719 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
1720 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1721 Abbv) != FUNCTION_INST_LOAD_ABBREV)
1722 llvm_unreachable("Unexpected abbrev ordering!");
1724 { // INST_BINOP abbrev for FUNCTION_BLOCK.
1725 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1726 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1727 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1728 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1729 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1730 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1731 Abbv) != FUNCTION_INST_BINOP_ABBREV)
1732 llvm_unreachable("Unexpected abbrev ordering!");
1734 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
1735 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1736 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1737 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1738 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1739 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1740 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
1741 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1742 Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV)
1743 llvm_unreachable("Unexpected abbrev ordering!");
1745 { // INST_CAST abbrev for FUNCTION_BLOCK.
1746 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1747 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
1748 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
1749 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
1750 Log2_32_Ceil(VE.getTypes().size()+1)));
1751 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1752 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1753 Abbv) != FUNCTION_INST_CAST_ABBREV)
1754 llvm_unreachable("Unexpected abbrev ordering!");
1757 { // INST_RET abbrev for FUNCTION_BLOCK.
1758 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1759 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1760 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1761 Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
1762 llvm_unreachable("Unexpected abbrev ordering!");
1764 { // INST_RET abbrev for FUNCTION_BLOCK.
1765 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1766 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1767 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
1768 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1769 Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
1770 llvm_unreachable("Unexpected abbrev ordering!");
1772 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
1773 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1774 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
1775 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1776 Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
1777 llvm_unreachable("Unexpected abbrev ordering!");
1783 // Sort the Users based on the order in which the reader parses the bitcode
1785 static bool bitcodereader_order(const User *lhs, const User *rhs) {
1790 static void WriteUseList(const Value *V, const ValueEnumerator &VE,
1791 BitstreamWriter &Stream) {
1793 // One or zero uses can't get out of order.
1794 if (V->use_empty() || V->hasNUses(1))
1797 // Make a copy of the in-memory use-list for sorting.
1798 unsigned UseListSize = std::distance(V->use_begin(), V->use_end());
1799 SmallVector<const User*, 8> UseList;
1800 UseList.reserve(UseListSize);
1801 for (Value::const_use_iterator I = V->use_begin(), E = V->use_end();
1804 UseList.push_back(U);
1807 // Sort the copy based on the order read by the BitcodeReader.
1808 std::sort(UseList.begin(), UseList.end(), bitcodereader_order);
1810 // TODO: Generate a diff between the BitcodeWriter in-memory use-list and the
1811 // sorted list (i.e., the expected BitcodeReader in-memory use-list).
1813 // TODO: Emit the USELIST_CODE_ENTRYs.
1816 static void WriteFunctionUseList(const Function *F, ValueEnumerator &VE,
1817 BitstreamWriter &Stream) {
1818 VE.incorporateFunction(*F);
1820 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1822 WriteUseList(AI, VE, Stream);
1823 for (Function::const_iterator BB = F->begin(), FE = F->end(); BB != FE;
1825 WriteUseList(BB, VE, Stream);
1826 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end(); II != IE;
1828 WriteUseList(II, VE, Stream);
1829 for (User::const_op_iterator OI = II->op_begin(), E = II->op_end();
1831 if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
1832 isa<InlineAsm>(*OI))
1833 WriteUseList(*OI, VE, Stream);
1841 static void WriteModuleUseLists(const Module *M, ValueEnumerator &VE,
1842 BitstreamWriter &Stream) {
1843 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
1845 // XXX: this modifies the module, but in a way that should never change the
1846 // behavior of any pass or codegen in LLVM. The problem is that GVs may
1847 // contain entries in the use_list that do not exist in the Module and are
1848 // not stored in the .bc file.
1849 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1851 I->removeDeadConstantUsers();
1853 // Write the global variables.
1854 for (Module::const_global_iterator GI = M->global_begin(),
1855 GE = M->global_end(); GI != GE; ++GI) {
1856 WriteUseList(GI, VE, Stream);
1858 // Write the global variable initializers.
1859 if (GI->hasInitializer())
1860 WriteUseList(GI->getInitializer(), VE, Stream);
1863 // Write the functions.
1864 for (Module::const_iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI) {
1865 WriteUseList(FI, VE, Stream);
1866 if (!FI->isDeclaration())
1867 WriteFunctionUseList(FI, VE, Stream);
1868 if (FI->hasPrefixData())
1869 WriteUseList(FI->getPrefixData(), VE, Stream);
1872 // Write the aliases.
1873 for (Module::const_alias_iterator AI = M->alias_begin(), AE = M->alias_end();
1875 WriteUseList(AI, VE, Stream);
1876 WriteUseList(AI->getAliasee(), VE, Stream);
1882 /// WriteModule - Emit the specified module to the bitstream.
1883 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
1884 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
1886 SmallVector<unsigned, 1> Vals;
1887 unsigned CurVersion = 1;
1888 Vals.push_back(CurVersion);
1889 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
1891 // Analyze the module, enumerating globals, functions, etc.
1892 ValueEnumerator VE(M);
1894 // Emit blockinfo, which defines the standard abbreviations etc.
1895 WriteBlockInfo(VE, Stream);
1897 // Emit information about attribute groups.
1898 WriteAttributeGroupTable(VE, Stream);
1900 // Emit information about parameter attributes.
1901 WriteAttributeTable(VE, Stream);
1903 // Emit information describing all of the types in the module.
1904 WriteTypeTable(VE, Stream);
1906 // Emit top-level description of module, including target triple, inline asm,
1907 // descriptors for global variables, and function prototype info.
1908 WriteModuleInfo(M, VE, Stream);
1911 WriteModuleConstants(VE, Stream);
1914 WriteModuleMetadata(M, VE, Stream);
1917 WriteModuleMetadataStore(M, Stream);
1919 // Emit names for globals/functions etc.
1920 WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
1923 if (EnablePreserveUseListOrdering)
1924 WriteModuleUseLists(M, VE, Stream);
1926 // Emit function bodies.
1927 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F)
1928 if (!F->isDeclaration())
1929 WriteFunction(*F, VE, Stream);
1934 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
1935 /// header and trailer to make it compatible with the system archiver. To do
1936 /// this we emit the following header, and then emit a trailer that pads the
1937 /// file out to be a multiple of 16 bytes.
1939 /// struct bc_header {
1940 /// uint32_t Magic; // 0x0B17C0DE
1941 /// uint32_t Version; // Version, currently always 0.
1942 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
1943 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
1944 /// uint32_t CPUType; // CPU specifier.
1945 /// ... potentially more later ...
1948 DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
1949 DarwinBCHeaderSize = 5*4
1952 static void WriteInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
1953 uint32_t &Position) {
1954 Buffer[Position + 0] = (unsigned char) (Value >> 0);
1955 Buffer[Position + 1] = (unsigned char) (Value >> 8);
1956 Buffer[Position + 2] = (unsigned char) (Value >> 16);
1957 Buffer[Position + 3] = (unsigned char) (Value >> 24);
1961 static void EmitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
1963 unsigned CPUType = ~0U;
1965 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
1966 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
1967 // number from /usr/include/mach/machine.h. It is ok to reproduce the
1968 // specific constants here because they are implicitly part of the Darwin ABI.
1970 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
1971 DARWIN_CPU_TYPE_X86 = 7,
1972 DARWIN_CPU_TYPE_ARM = 12,
1973 DARWIN_CPU_TYPE_POWERPC = 18
1976 Triple::ArchType Arch = TT.getArch();
1977 if (Arch == Triple::x86_64)
1978 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
1979 else if (Arch == Triple::x86)
1980 CPUType = DARWIN_CPU_TYPE_X86;
1981 else if (Arch == Triple::ppc)
1982 CPUType = DARWIN_CPU_TYPE_POWERPC;
1983 else if (Arch == Triple::ppc64)
1984 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
1985 else if (Arch == Triple::arm || Arch == Triple::thumb)
1986 CPUType = DARWIN_CPU_TYPE_ARM;
1988 // Traditional Bitcode starts after header.
1989 assert(Buffer.size() >= DarwinBCHeaderSize &&
1990 "Expected header size to be reserved");
1991 unsigned BCOffset = DarwinBCHeaderSize;
1992 unsigned BCSize = Buffer.size()-DarwinBCHeaderSize;
1994 // Write the magic and version.
1995 unsigned Position = 0;
1996 WriteInt32ToBuffer(0x0B17C0DE , Buffer, Position);
1997 WriteInt32ToBuffer(0 , Buffer, Position); // Version.
1998 WriteInt32ToBuffer(BCOffset , Buffer, Position);
1999 WriteInt32ToBuffer(BCSize , Buffer, Position);
2000 WriteInt32ToBuffer(CPUType , Buffer, Position);
2002 // If the file is not a multiple of 16 bytes, insert dummy padding.
2003 while (Buffer.size() & 15)
2004 Buffer.push_back(0);
2007 /// WriteBitcodeToFile - Write the specified module to the specified output
2009 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out) {
2010 SmallVector<char, 0> Buffer;
2011 Buffer.reserve(256*1024);
2013 // If this is darwin or another generic macho target, reserve space for the
2015 Triple TT(M->getTargetTriple());
2016 if (TT.isOSDarwin())
2017 Buffer.insert(Buffer.begin(), DarwinBCHeaderSize, 0);
2019 // Emit the module into the buffer.
2021 BitstreamWriter Stream(Buffer);
2023 // Emit the file header.
2024 Stream.Emit((unsigned)'B', 8);
2025 Stream.Emit((unsigned)'C', 8);
2026 Stream.Emit(0x0, 4);
2027 Stream.Emit(0xC, 4);
2028 Stream.Emit(0xE, 4);
2029 Stream.Emit(0xD, 4);
2032 WriteModule(M, Stream);
2035 if (TT.isOSDarwin())
2036 EmitDarwinBCHeaderAndTrailer(Buffer, TT);
2038 // Write the generated bitstream to "Out".
2039 Out.write((char*)&Buffer.front(), Buffer.size());