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;
493 llvm_unreachable("Invalid linkage");
496 static unsigned getEncodedVisibility(const GlobalValue *GV) {
497 switch (GV->getVisibility()) {
498 case GlobalValue::DefaultVisibility: return 0;
499 case GlobalValue::HiddenVisibility: return 1;
500 case GlobalValue::ProtectedVisibility: return 2;
502 llvm_unreachable("Invalid visibility");
505 static unsigned getEncodedThreadLocalMode(const GlobalVariable *GV) {
506 switch (GV->getThreadLocalMode()) {
507 case GlobalVariable::NotThreadLocal: return 0;
508 case GlobalVariable::GeneralDynamicTLSModel: return 1;
509 case GlobalVariable::LocalDynamicTLSModel: return 2;
510 case GlobalVariable::InitialExecTLSModel: return 3;
511 case GlobalVariable::LocalExecTLSModel: return 4;
513 llvm_unreachable("Invalid TLS model");
516 // Emit top-level description of module, including target triple, inline asm,
517 // descriptors for global variables, and function prototype info.
518 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
519 BitstreamWriter &Stream) {
520 // Emit various pieces of data attached to a module.
521 if (!M->getTargetTriple().empty())
522 WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
524 if (!M->getDataLayout().empty())
525 WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(),
527 if (!M->getModuleInlineAsm().empty())
528 WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
531 // Emit information about sections and GC, computing how many there are. Also
532 // compute the maximum alignment value.
533 std::map<std::string, unsigned> SectionMap;
534 std::map<std::string, unsigned> GCMap;
535 unsigned MaxAlignment = 0;
536 unsigned MaxGlobalType = 0;
537 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
539 MaxAlignment = std::max(MaxAlignment, GV->getAlignment());
540 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType()));
541 if (GV->hasSection()) {
542 // Give section names unique ID's.
543 unsigned &Entry = SectionMap[GV->getSection()];
545 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(),
547 Entry = SectionMap.size();
551 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
552 MaxAlignment = std::max(MaxAlignment, F->getAlignment());
553 if (F->hasSection()) {
554 // Give section names unique ID's.
555 unsigned &Entry = SectionMap[F->getSection()];
557 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(),
559 Entry = SectionMap.size();
563 // Same for GC names.
564 unsigned &Entry = GCMap[F->getGC()];
566 WriteStringRecord(bitc::MODULE_CODE_GCNAME, F->getGC(),
568 Entry = GCMap.size();
573 // Emit abbrev for globals, now that we know # sections and max alignment.
574 unsigned SimpleGVarAbbrev = 0;
575 if (!M->global_empty()) {
576 // Add an abbrev for common globals with no visibility or thread localness.
577 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
578 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
579 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
580 Log2_32_Ceil(MaxGlobalType+1)));
581 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Constant.
582 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
583 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // Linkage.
584 if (MaxAlignment == 0) // Alignment.
585 Abbv->Add(BitCodeAbbrevOp(0));
587 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
588 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
589 Log2_32_Ceil(MaxEncAlignment+1)));
591 if (SectionMap.empty()) // Section.
592 Abbv->Add(BitCodeAbbrevOp(0));
594 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
595 Log2_32_Ceil(SectionMap.size()+1)));
596 // Don't bother emitting vis + thread local.
597 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
600 // Emit the global variable information.
601 SmallVector<unsigned, 64> Vals;
602 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
604 unsigned AbbrevToUse = 0;
606 // GLOBALVAR: [type, isconst, initid,
607 // linkage, alignment, section, visibility, threadlocal,
608 // unnamed_addr, externally_initialized]
609 Vals.push_back(VE.getTypeID(GV->getType()));
610 Vals.push_back(GV->isConstant());
611 Vals.push_back(GV->isDeclaration() ? 0 :
612 (VE.getValueID(GV->getInitializer()) + 1));
613 Vals.push_back(getEncodedLinkage(GV));
614 Vals.push_back(Log2_32(GV->getAlignment())+1);
615 Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0);
616 if (GV->isThreadLocal() ||
617 GV->getVisibility() != GlobalValue::DefaultVisibility ||
618 GV->hasUnnamedAddr() || GV->isExternallyInitialized()) {
619 Vals.push_back(getEncodedVisibility(GV));
620 Vals.push_back(getEncodedThreadLocalMode(GV));
621 Vals.push_back(GV->hasUnnamedAddr());
622 Vals.push_back(GV->isExternallyInitialized());
624 AbbrevToUse = SimpleGVarAbbrev;
627 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
631 // Emit the function proto information.
632 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
633 // FUNCTION: [type, callingconv, isproto, linkage, paramattrs, alignment,
634 // section, visibility, gc, unnamed_addr, prefix]
635 Vals.push_back(VE.getTypeID(F->getType()));
636 Vals.push_back(F->getCallingConv());
637 Vals.push_back(F->isDeclaration());
638 Vals.push_back(getEncodedLinkage(F));
639 Vals.push_back(VE.getAttributeID(F->getAttributes()));
640 Vals.push_back(Log2_32(F->getAlignment())+1);
641 Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
642 Vals.push_back(getEncodedVisibility(F));
643 Vals.push_back(F->hasGC() ? GCMap[F->getGC()] : 0);
644 Vals.push_back(F->hasUnnamedAddr());
645 Vals.push_back(F->hasPrefixData() ? (VE.getValueID(F->getPrefixData()) + 1)
648 unsigned AbbrevToUse = 0;
649 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
653 // Emit the alias information.
654 for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end();
656 // ALIAS: [alias type, aliasee val#, linkage, visibility]
657 Vals.push_back(VE.getTypeID(AI->getType()));
658 Vals.push_back(VE.getValueID(AI->getAliasee()));
659 Vals.push_back(getEncodedLinkage(AI));
660 Vals.push_back(getEncodedVisibility(AI));
661 unsigned AbbrevToUse = 0;
662 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
667 static uint64_t GetOptimizationFlags(const Value *V) {
670 if (const OverflowingBinaryOperator *OBO =
671 dyn_cast<OverflowingBinaryOperator>(V)) {
672 if (OBO->hasNoSignedWrap())
673 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
674 if (OBO->hasNoUnsignedWrap())
675 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
676 } else if (const PossiblyExactOperator *PEO =
677 dyn_cast<PossiblyExactOperator>(V)) {
679 Flags |= 1 << bitc::PEO_EXACT;
680 } else if (const FPMathOperator *FPMO =
681 dyn_cast<const FPMathOperator>(V)) {
682 if (FPMO->hasUnsafeAlgebra())
683 Flags |= FastMathFlags::UnsafeAlgebra;
684 if (FPMO->hasNoNaNs())
685 Flags |= FastMathFlags::NoNaNs;
686 if (FPMO->hasNoInfs())
687 Flags |= FastMathFlags::NoInfs;
688 if (FPMO->hasNoSignedZeros())
689 Flags |= FastMathFlags::NoSignedZeros;
690 if (FPMO->hasAllowReciprocal())
691 Flags |= FastMathFlags::AllowReciprocal;
697 static void WriteMDNode(const MDNode *N,
698 const ValueEnumerator &VE,
699 BitstreamWriter &Stream,
700 SmallVectorImpl<uint64_t> &Record) {
701 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
702 if (N->getOperand(i)) {
703 Record.push_back(VE.getTypeID(N->getOperand(i)->getType()));
704 Record.push_back(VE.getValueID(N->getOperand(i)));
706 Record.push_back(VE.getTypeID(Type::getVoidTy(N->getContext())));
710 unsigned MDCode = N->isFunctionLocal() ? bitc::METADATA_FN_NODE :
712 Stream.EmitRecord(MDCode, Record, 0);
716 static void WriteModuleMetadata(const Module *M,
717 const ValueEnumerator &VE,
718 BitstreamWriter &Stream) {
719 const ValueEnumerator::ValueList &Vals = VE.getMDValues();
720 bool StartedMetadataBlock = false;
721 unsigned MDSAbbrev = 0;
722 SmallVector<uint64_t, 64> Record;
723 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
725 if (const MDNode *N = dyn_cast<MDNode>(Vals[i].first)) {
726 if (!N->isFunctionLocal() || !N->getFunction()) {
727 if (!StartedMetadataBlock) {
728 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
729 StartedMetadataBlock = true;
731 WriteMDNode(N, VE, Stream, Record);
733 } else if (const MDString *MDS = dyn_cast<MDString>(Vals[i].first)) {
734 if (!StartedMetadataBlock) {
735 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
737 // Abbrev for METADATA_STRING.
738 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
739 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING));
740 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
741 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
742 MDSAbbrev = Stream.EmitAbbrev(Abbv);
743 StartedMetadataBlock = true;
746 // Code: [strchar x N]
747 Record.append(MDS->begin(), MDS->end());
749 // Emit the finished record.
750 Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev);
755 // Write named metadata.
756 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
757 E = M->named_metadata_end(); I != E; ++I) {
758 const NamedMDNode *NMD = I;
759 if (!StartedMetadataBlock) {
760 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
761 StartedMetadataBlock = true;
765 StringRef Str = NMD->getName();
766 for (unsigned i = 0, e = Str.size(); i != e; ++i)
767 Record.push_back(Str[i]);
768 Stream.EmitRecord(bitc::METADATA_NAME, Record, 0/*TODO*/);
771 // Write named metadata operands.
772 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
773 Record.push_back(VE.getValueID(NMD->getOperand(i)));
774 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
778 if (StartedMetadataBlock)
782 static void WriteFunctionLocalMetadata(const Function &F,
783 const ValueEnumerator &VE,
784 BitstreamWriter &Stream) {
785 bool StartedMetadataBlock = false;
786 SmallVector<uint64_t, 64> Record;
787 const SmallVectorImpl<const MDNode *> &Vals = VE.getFunctionLocalMDValues();
788 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
789 if (const MDNode *N = Vals[i])
790 if (N->isFunctionLocal() && N->getFunction() == &F) {
791 if (!StartedMetadataBlock) {
792 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
793 StartedMetadataBlock = true;
795 WriteMDNode(N, VE, Stream, Record);
798 if (StartedMetadataBlock)
802 static void WriteMetadataAttachment(const Function &F,
803 const ValueEnumerator &VE,
804 BitstreamWriter &Stream) {
805 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
807 SmallVector<uint64_t, 64> Record;
809 // Write metadata attachments
810 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
811 SmallVector<std::pair<unsigned, MDNode*>, 4> MDs;
813 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
814 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
817 I->getAllMetadataOtherThanDebugLoc(MDs);
819 // If no metadata, ignore instruction.
820 if (MDs.empty()) continue;
822 Record.push_back(VE.getInstructionID(I));
824 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
825 Record.push_back(MDs[i].first);
826 Record.push_back(VE.getValueID(MDs[i].second));
828 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
835 static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) {
836 SmallVector<uint64_t, 64> Record;
838 // Write metadata kinds
839 // METADATA_KIND - [n x [id, name]]
840 SmallVector<StringRef, 8> Names;
841 M->getMDKindNames(Names);
843 if (Names.empty()) return;
845 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
847 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
848 Record.push_back(MDKindID);
849 StringRef KName = Names[MDKindID];
850 Record.append(KName.begin(), KName.end());
852 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
859 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
861 Vals.push_back(V << 1);
863 Vals.push_back((-V << 1) | 1);
866 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
867 const ValueEnumerator &VE,
868 BitstreamWriter &Stream, bool isGlobal) {
869 if (FirstVal == LastVal) return;
871 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
873 unsigned AggregateAbbrev = 0;
874 unsigned String8Abbrev = 0;
875 unsigned CString7Abbrev = 0;
876 unsigned CString6Abbrev = 0;
877 // If this is a constant pool for the module, emit module-specific abbrevs.
879 // Abbrev for CST_CODE_AGGREGATE.
880 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
881 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
882 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
883 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
884 AggregateAbbrev = Stream.EmitAbbrev(Abbv);
886 // Abbrev for CST_CODE_STRING.
887 Abbv = new BitCodeAbbrev();
888 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
889 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
890 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
891 String8Abbrev = Stream.EmitAbbrev(Abbv);
892 // Abbrev for CST_CODE_CSTRING.
893 Abbv = new BitCodeAbbrev();
894 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
895 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
896 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
897 CString7Abbrev = Stream.EmitAbbrev(Abbv);
898 // Abbrev for CST_CODE_CSTRING.
899 Abbv = new BitCodeAbbrev();
900 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
901 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
902 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
903 CString6Abbrev = Stream.EmitAbbrev(Abbv);
906 SmallVector<uint64_t, 64> Record;
908 const ValueEnumerator::ValueList &Vals = VE.getValues();
910 for (unsigned i = FirstVal; i != LastVal; ++i) {
911 const Value *V = Vals[i].first;
912 // If we need to switch types, do so now.
913 if (V->getType() != LastTy) {
914 LastTy = V->getType();
915 Record.push_back(VE.getTypeID(LastTy));
916 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
917 CONSTANTS_SETTYPE_ABBREV);
921 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
922 Record.push_back(unsigned(IA->hasSideEffects()) |
923 unsigned(IA->isAlignStack()) << 1 |
924 unsigned(IA->getDialect()&1) << 2);
926 // Add the asm string.
927 const std::string &AsmStr = IA->getAsmString();
928 Record.push_back(AsmStr.size());
929 for (unsigned i = 0, e = AsmStr.size(); i != e; ++i)
930 Record.push_back(AsmStr[i]);
932 // Add the constraint string.
933 const std::string &ConstraintStr = IA->getConstraintString();
934 Record.push_back(ConstraintStr.size());
935 for (unsigned i = 0, e = ConstraintStr.size(); i != e; ++i)
936 Record.push_back(ConstraintStr[i]);
937 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
941 const Constant *C = cast<Constant>(V);
943 unsigned AbbrevToUse = 0;
944 if (C->isNullValue()) {
945 Code = bitc::CST_CODE_NULL;
946 } else if (isa<UndefValue>(C)) {
947 Code = bitc::CST_CODE_UNDEF;
948 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
949 if (IV->getBitWidth() <= 64) {
950 uint64_t V = IV->getSExtValue();
951 emitSignedInt64(Record, V);
952 Code = bitc::CST_CODE_INTEGER;
953 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
954 } else { // Wide integers, > 64 bits in size.
955 // We have an arbitrary precision integer value to write whose
956 // bit width is > 64. However, in canonical unsigned integer
957 // format it is likely that the high bits are going to be zero.
958 // So, we only write the number of active words.
959 unsigned NWords = IV->getValue().getActiveWords();
960 const uint64_t *RawWords = IV->getValue().getRawData();
961 for (unsigned i = 0; i != NWords; ++i) {
962 emitSignedInt64(Record, RawWords[i]);
964 Code = bitc::CST_CODE_WIDE_INTEGER;
966 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
967 Code = bitc::CST_CODE_FLOAT;
968 Type *Ty = CFP->getType();
969 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
970 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
971 } else if (Ty->isX86_FP80Ty()) {
972 // api needed to prevent premature destruction
973 // bits are not in the same order as a normal i80 APInt, compensate.
974 APInt api = CFP->getValueAPF().bitcastToAPInt();
975 const uint64_t *p = api.getRawData();
976 Record.push_back((p[1] << 48) | (p[0] >> 16));
977 Record.push_back(p[0] & 0xffffLL);
978 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
979 APInt api = CFP->getValueAPF().bitcastToAPInt();
980 const uint64_t *p = api.getRawData();
981 Record.push_back(p[0]);
982 Record.push_back(p[1]);
984 assert (0 && "Unknown FP type!");
986 } else if (isa<ConstantDataSequential>(C) &&
987 cast<ConstantDataSequential>(C)->isString()) {
988 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
989 // Emit constant strings specially.
990 unsigned NumElts = Str->getNumElements();
991 // If this is a null-terminated string, use the denser CSTRING encoding.
992 if (Str->isCString()) {
993 Code = bitc::CST_CODE_CSTRING;
994 --NumElts; // Don't encode the null, which isn't allowed by char6.
996 Code = bitc::CST_CODE_STRING;
997 AbbrevToUse = String8Abbrev;
999 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
1000 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
1001 for (unsigned i = 0; i != NumElts; ++i) {
1002 unsigned char V = Str->getElementAsInteger(i);
1003 Record.push_back(V);
1004 isCStr7 &= (V & 128) == 0;
1006 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
1010 AbbrevToUse = CString6Abbrev;
1012 AbbrevToUse = CString7Abbrev;
1013 } else if (const ConstantDataSequential *CDS =
1014 dyn_cast<ConstantDataSequential>(C)) {
1015 Code = bitc::CST_CODE_DATA;
1016 Type *EltTy = CDS->getType()->getElementType();
1017 if (isa<IntegerType>(EltTy)) {
1018 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
1019 Record.push_back(CDS->getElementAsInteger(i));
1020 } else if (EltTy->isFloatTy()) {
1021 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1022 union { float F; uint32_t I; };
1023 F = CDS->getElementAsFloat(i);
1024 Record.push_back(I);
1027 assert(EltTy->isDoubleTy() && "Unknown ConstantData element type");
1028 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1029 union { double F; uint64_t I; };
1030 F = CDS->getElementAsDouble(i);
1031 Record.push_back(I);
1034 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
1035 isa<ConstantVector>(C)) {
1036 Code = bitc::CST_CODE_AGGREGATE;
1037 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
1038 Record.push_back(VE.getValueID(C->getOperand(i)));
1039 AbbrevToUse = AggregateAbbrev;
1040 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1041 switch (CE->getOpcode()) {
1043 if (Instruction::isCast(CE->getOpcode())) {
1044 Code = bitc::CST_CODE_CE_CAST;
1045 Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
1046 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1047 Record.push_back(VE.getValueID(C->getOperand(0)));
1048 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
1050 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
1051 Code = bitc::CST_CODE_CE_BINOP;
1052 Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
1053 Record.push_back(VE.getValueID(C->getOperand(0)));
1054 Record.push_back(VE.getValueID(C->getOperand(1)));
1055 uint64_t Flags = GetOptimizationFlags(CE);
1057 Record.push_back(Flags);
1060 case Instruction::GetElementPtr:
1061 Code = bitc::CST_CODE_CE_GEP;
1062 if (cast<GEPOperator>(C)->isInBounds())
1063 Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
1064 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
1065 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
1066 Record.push_back(VE.getValueID(C->getOperand(i)));
1069 case Instruction::Select:
1070 Code = bitc::CST_CODE_CE_SELECT;
1071 Record.push_back(VE.getValueID(C->getOperand(0)));
1072 Record.push_back(VE.getValueID(C->getOperand(1)));
1073 Record.push_back(VE.getValueID(C->getOperand(2)));
1075 case Instruction::ExtractElement:
1076 Code = bitc::CST_CODE_CE_EXTRACTELT;
1077 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1078 Record.push_back(VE.getValueID(C->getOperand(0)));
1079 Record.push_back(VE.getValueID(C->getOperand(1)));
1081 case Instruction::InsertElement:
1082 Code = bitc::CST_CODE_CE_INSERTELT;
1083 Record.push_back(VE.getValueID(C->getOperand(0)));
1084 Record.push_back(VE.getValueID(C->getOperand(1)));
1085 Record.push_back(VE.getValueID(C->getOperand(2)));
1087 case Instruction::ShuffleVector:
1088 // If the return type and argument types are the same, this is a
1089 // standard shufflevector instruction. If the types are different,
1090 // then the shuffle is widening or truncating the input vectors, and
1091 // the argument type must also be encoded.
1092 if (C->getType() == C->getOperand(0)->getType()) {
1093 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
1095 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
1096 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1098 Record.push_back(VE.getValueID(C->getOperand(0)));
1099 Record.push_back(VE.getValueID(C->getOperand(1)));
1100 Record.push_back(VE.getValueID(C->getOperand(2)));
1102 case Instruction::ICmp:
1103 case Instruction::FCmp:
1104 Code = bitc::CST_CODE_CE_CMP;
1105 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1106 Record.push_back(VE.getValueID(C->getOperand(0)));
1107 Record.push_back(VE.getValueID(C->getOperand(1)));
1108 Record.push_back(CE->getPredicate());
1111 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
1112 Code = bitc::CST_CODE_BLOCKADDRESS;
1113 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
1114 Record.push_back(VE.getValueID(BA->getFunction()));
1115 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
1120 llvm_unreachable("Unknown constant!");
1122 Stream.EmitRecord(Code, Record, AbbrevToUse);
1129 static void WriteModuleConstants(const ValueEnumerator &VE,
1130 BitstreamWriter &Stream) {
1131 const ValueEnumerator::ValueList &Vals = VE.getValues();
1133 // Find the first constant to emit, which is the first non-globalvalue value.
1134 // We know globalvalues have been emitted by WriteModuleInfo.
1135 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1136 if (!isa<GlobalValue>(Vals[i].first)) {
1137 WriteConstants(i, Vals.size(), VE, Stream, true);
1143 /// PushValueAndType - The file has to encode both the value and type id for
1144 /// many values, because we need to know what type to create for forward
1145 /// references. However, most operands are not forward references, so this type
1146 /// field is not needed.
1148 /// This function adds V's value ID to Vals. If the value ID is higher than the
1149 /// instruction ID, then it is a forward reference, and it also includes the
1150 /// type ID. The value ID that is written is encoded relative to the InstID.
1151 static bool PushValueAndType(const Value *V, unsigned InstID,
1152 SmallVectorImpl<unsigned> &Vals,
1153 ValueEnumerator &VE) {
1154 unsigned ValID = VE.getValueID(V);
1155 // Make encoding relative to the InstID.
1156 Vals.push_back(InstID - ValID);
1157 if (ValID >= InstID) {
1158 Vals.push_back(VE.getTypeID(V->getType()));
1164 /// pushValue - Like PushValueAndType, but where the type of the value is
1165 /// omitted (perhaps it was already encoded in an earlier operand).
1166 static void pushValue(const Value *V, unsigned InstID,
1167 SmallVectorImpl<unsigned> &Vals,
1168 ValueEnumerator &VE) {
1169 unsigned ValID = VE.getValueID(V);
1170 Vals.push_back(InstID - ValID);
1173 static void pushValueSigned(const Value *V, unsigned InstID,
1174 SmallVectorImpl<uint64_t> &Vals,
1175 ValueEnumerator &VE) {
1176 unsigned ValID = VE.getValueID(V);
1177 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
1178 emitSignedInt64(Vals, diff);
1181 /// WriteInstruction - Emit an instruction to the specified stream.
1182 static void WriteInstruction(const Instruction &I, unsigned InstID,
1183 ValueEnumerator &VE, BitstreamWriter &Stream,
1184 SmallVectorImpl<unsigned> &Vals) {
1186 unsigned AbbrevToUse = 0;
1187 VE.setInstructionID(&I);
1188 switch (I.getOpcode()) {
1190 if (Instruction::isCast(I.getOpcode())) {
1191 Code = bitc::FUNC_CODE_INST_CAST;
1192 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1193 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
1194 Vals.push_back(VE.getTypeID(I.getType()));
1195 Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
1197 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
1198 Code = bitc::FUNC_CODE_INST_BINOP;
1199 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1200 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
1201 pushValue(I.getOperand(1), InstID, Vals, VE);
1202 Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
1203 uint64_t Flags = GetOptimizationFlags(&I);
1205 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
1206 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
1207 Vals.push_back(Flags);
1212 case Instruction::GetElementPtr:
1213 Code = bitc::FUNC_CODE_INST_GEP;
1214 if (cast<GEPOperator>(&I)->isInBounds())
1215 Code = bitc::FUNC_CODE_INST_INBOUNDS_GEP;
1216 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1217 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1219 case Instruction::ExtractValue: {
1220 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
1221 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1222 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
1223 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1227 case Instruction::InsertValue: {
1228 Code = bitc::FUNC_CODE_INST_INSERTVAL;
1229 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1230 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1231 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
1232 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1236 case Instruction::Select:
1237 Code = bitc::FUNC_CODE_INST_VSELECT;
1238 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1239 pushValue(I.getOperand(2), InstID, Vals, VE);
1240 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1242 case Instruction::ExtractElement:
1243 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
1244 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1245 pushValue(I.getOperand(1), InstID, Vals, VE);
1247 case Instruction::InsertElement:
1248 Code = bitc::FUNC_CODE_INST_INSERTELT;
1249 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1250 pushValue(I.getOperand(1), InstID, Vals, VE);
1251 pushValue(I.getOperand(2), InstID, Vals, VE);
1253 case Instruction::ShuffleVector:
1254 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
1255 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1256 pushValue(I.getOperand(1), InstID, Vals, VE);
1257 pushValue(I.getOperand(2), InstID, Vals, VE);
1259 case Instruction::ICmp:
1260 case Instruction::FCmp:
1261 // compare returning Int1Ty or vector of Int1Ty
1262 Code = bitc::FUNC_CODE_INST_CMP2;
1263 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1264 pushValue(I.getOperand(1), InstID, Vals, VE);
1265 Vals.push_back(cast<CmpInst>(I).getPredicate());
1268 case Instruction::Ret:
1270 Code = bitc::FUNC_CODE_INST_RET;
1271 unsigned NumOperands = I.getNumOperands();
1272 if (NumOperands == 0)
1273 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
1274 else if (NumOperands == 1) {
1275 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1276 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
1278 for (unsigned i = 0, e = NumOperands; i != e; ++i)
1279 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1283 case Instruction::Br:
1285 Code = bitc::FUNC_CODE_INST_BR;
1286 const BranchInst &II = cast<BranchInst>(I);
1287 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
1288 if (II.isConditional()) {
1289 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
1290 pushValue(II.getCondition(), InstID, Vals, VE);
1294 case Instruction::Switch:
1296 Code = bitc::FUNC_CODE_INST_SWITCH;
1297 const SwitchInst &SI = cast<SwitchInst>(I);
1298 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
1299 pushValue(SI.getCondition(), InstID, Vals, VE);
1300 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
1301 for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
1303 Vals.push_back(VE.getValueID(i.getCaseValue()));
1304 Vals.push_back(VE.getValueID(i.getCaseSuccessor()));
1308 case Instruction::IndirectBr:
1309 Code = bitc::FUNC_CODE_INST_INDIRECTBR;
1310 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1311 // Encode the address operand as relative, but not the basic blocks.
1312 pushValue(I.getOperand(0), InstID, Vals, VE);
1313 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
1314 Vals.push_back(VE.getValueID(I.getOperand(i)));
1317 case Instruction::Invoke: {
1318 const InvokeInst *II = cast<InvokeInst>(&I);
1319 const Value *Callee(II->getCalledValue());
1320 PointerType *PTy = cast<PointerType>(Callee->getType());
1321 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1322 Code = bitc::FUNC_CODE_INST_INVOKE;
1324 Vals.push_back(VE.getAttributeID(II->getAttributes()));
1325 Vals.push_back(II->getCallingConv());
1326 Vals.push_back(VE.getValueID(II->getNormalDest()));
1327 Vals.push_back(VE.getValueID(II->getUnwindDest()));
1328 PushValueAndType(Callee, InstID, Vals, VE);
1330 // Emit value #'s for the fixed parameters.
1331 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1332 pushValue(I.getOperand(i), InstID, Vals, VE); // fixed param.
1334 // Emit type/value pairs for varargs params.
1335 if (FTy->isVarArg()) {
1336 for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
1338 PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
1342 case Instruction::Resume:
1343 Code = bitc::FUNC_CODE_INST_RESUME;
1344 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1346 case Instruction::Unreachable:
1347 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
1348 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
1351 case Instruction::PHI: {
1352 const PHINode &PN = cast<PHINode>(I);
1353 Code = bitc::FUNC_CODE_INST_PHI;
1354 // With the newer instruction encoding, forward references could give
1355 // negative valued IDs. This is most common for PHIs, so we use
1357 SmallVector<uint64_t, 128> Vals64;
1358 Vals64.push_back(VE.getTypeID(PN.getType()));
1359 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1360 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64, VE);
1361 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
1363 // Emit a Vals64 vector and exit.
1364 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
1369 case Instruction::LandingPad: {
1370 const LandingPadInst &LP = cast<LandingPadInst>(I);
1371 Code = bitc::FUNC_CODE_INST_LANDINGPAD;
1372 Vals.push_back(VE.getTypeID(LP.getType()));
1373 PushValueAndType(LP.getPersonalityFn(), InstID, Vals, VE);
1374 Vals.push_back(LP.isCleanup());
1375 Vals.push_back(LP.getNumClauses());
1376 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
1378 Vals.push_back(LandingPadInst::Catch);
1380 Vals.push_back(LandingPadInst::Filter);
1381 PushValueAndType(LP.getClause(I), InstID, Vals, VE);
1386 case Instruction::Alloca:
1387 Code = bitc::FUNC_CODE_INST_ALLOCA;
1388 Vals.push_back(VE.getTypeID(I.getType()));
1389 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1390 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
1391 Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1);
1394 case Instruction::Load:
1395 if (cast<LoadInst>(I).isAtomic()) {
1396 Code = bitc::FUNC_CODE_INST_LOADATOMIC;
1397 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1399 Code = bitc::FUNC_CODE_INST_LOAD;
1400 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) // ptr
1401 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
1403 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
1404 Vals.push_back(cast<LoadInst>(I).isVolatile());
1405 if (cast<LoadInst>(I).isAtomic()) {
1406 Vals.push_back(GetEncodedOrdering(cast<LoadInst>(I).getOrdering()));
1407 Vals.push_back(GetEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
1410 case Instruction::Store:
1411 if (cast<StoreInst>(I).isAtomic())
1412 Code = bitc::FUNC_CODE_INST_STOREATOMIC;
1414 Code = bitc::FUNC_CODE_INST_STORE;
1415 PushValueAndType(I.getOperand(1), InstID, Vals, VE); // ptrty + ptr
1416 pushValue(I.getOperand(0), InstID, Vals, VE); // val.
1417 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
1418 Vals.push_back(cast<StoreInst>(I).isVolatile());
1419 if (cast<StoreInst>(I).isAtomic()) {
1420 Vals.push_back(GetEncodedOrdering(cast<StoreInst>(I).getOrdering()));
1421 Vals.push_back(GetEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
1424 case Instruction::AtomicCmpXchg:
1425 Code = bitc::FUNC_CODE_INST_CMPXCHG;
1426 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr
1427 pushValue(I.getOperand(1), InstID, Vals, VE); // cmp.
1428 pushValue(I.getOperand(2), InstID, Vals, VE); // newval.
1429 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
1430 Vals.push_back(GetEncodedOrdering(
1431 cast<AtomicCmpXchgInst>(I).getOrdering()));
1432 Vals.push_back(GetEncodedSynchScope(
1433 cast<AtomicCmpXchgInst>(I).getSynchScope()));
1435 case Instruction::AtomicRMW:
1436 Code = bitc::FUNC_CODE_INST_ATOMICRMW;
1437 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr
1438 pushValue(I.getOperand(1), InstID, Vals, VE); // val.
1439 Vals.push_back(GetEncodedRMWOperation(
1440 cast<AtomicRMWInst>(I).getOperation()));
1441 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
1442 Vals.push_back(GetEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
1443 Vals.push_back(GetEncodedSynchScope(
1444 cast<AtomicRMWInst>(I).getSynchScope()));
1446 case Instruction::Fence:
1447 Code = bitc::FUNC_CODE_INST_FENCE;
1448 Vals.push_back(GetEncodedOrdering(cast<FenceInst>(I).getOrdering()));
1449 Vals.push_back(GetEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
1451 case Instruction::Call: {
1452 const CallInst &CI = cast<CallInst>(I);
1453 PointerType *PTy = cast<PointerType>(CI.getCalledValue()->getType());
1454 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1456 Code = bitc::FUNC_CODE_INST_CALL;
1458 Vals.push_back(VE.getAttributeID(CI.getAttributes()));
1459 Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall()));
1460 PushValueAndType(CI.getCalledValue(), InstID, Vals, VE); // Callee
1462 // Emit value #'s for the fixed parameters.
1463 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
1464 // Check for labels (can happen with asm labels).
1465 if (FTy->getParamType(i)->isLabelTy())
1466 Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
1468 pushValue(CI.getArgOperand(i), InstID, Vals, VE); // fixed param.
1471 // Emit type/value pairs for varargs params.
1472 if (FTy->isVarArg()) {
1473 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
1475 PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE); // varargs
1479 case Instruction::VAArg:
1480 Code = bitc::FUNC_CODE_INST_VAARG;
1481 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
1482 pushValue(I.getOperand(0), InstID, Vals, VE); // valist.
1483 Vals.push_back(VE.getTypeID(I.getType())); // restype.
1487 Stream.EmitRecord(Code, Vals, AbbrevToUse);
1491 // Emit names for globals/functions etc.
1492 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
1493 const ValueEnumerator &VE,
1494 BitstreamWriter &Stream) {
1495 if (VST.empty()) return;
1496 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
1498 // FIXME: Set up the abbrev, we know how many values there are!
1499 // FIXME: We know if the type names can use 7-bit ascii.
1500 SmallVector<unsigned, 64> NameVals;
1502 for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
1505 const ValueName &Name = *SI;
1507 // Figure out the encoding to use for the name.
1509 bool isChar6 = true;
1510 for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
1513 isChar6 = BitCodeAbbrevOp::isChar6(*C);
1514 if ((unsigned char)*C & 128) {
1516 break; // don't bother scanning the rest.
1520 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
1522 // VST_ENTRY: [valueid, namechar x N]
1523 // VST_BBENTRY: [bbid, namechar x N]
1525 if (isa<BasicBlock>(SI->getValue())) {
1526 Code = bitc::VST_CODE_BBENTRY;
1528 AbbrevToUse = VST_BBENTRY_6_ABBREV;
1530 Code = bitc::VST_CODE_ENTRY;
1532 AbbrevToUse = VST_ENTRY_6_ABBREV;
1534 AbbrevToUse = VST_ENTRY_7_ABBREV;
1537 NameVals.push_back(VE.getValueID(SI->getValue()));
1538 for (const char *P = Name.getKeyData(),
1539 *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
1540 NameVals.push_back((unsigned char)*P);
1542 // Emit the finished record.
1543 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
1549 /// WriteFunction - Emit a function body to the module stream.
1550 static void WriteFunction(const Function &F, ValueEnumerator &VE,
1551 BitstreamWriter &Stream) {
1552 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
1553 VE.incorporateFunction(F);
1555 SmallVector<unsigned, 64> Vals;
1557 // Emit the number of basic blocks, so the reader can create them ahead of
1559 Vals.push_back(VE.getBasicBlocks().size());
1560 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
1563 // If there are function-local constants, emit them now.
1564 unsigned CstStart, CstEnd;
1565 VE.getFunctionConstantRange(CstStart, CstEnd);
1566 WriteConstants(CstStart, CstEnd, VE, Stream, false);
1568 // If there is function-local metadata, emit it now.
1569 WriteFunctionLocalMetadata(F, VE, Stream);
1571 // Keep a running idea of what the instruction ID is.
1572 unsigned InstID = CstEnd;
1574 bool NeedsMetadataAttachment = false;
1578 // Finally, emit all the instructions, in order.
1579 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1580 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1582 WriteInstruction(*I, InstID, VE, Stream, Vals);
1584 if (!I->getType()->isVoidTy())
1587 // If the instruction has metadata, write a metadata attachment later.
1588 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
1590 // If the instruction has a debug location, emit it.
1591 DebugLoc DL = I->getDebugLoc();
1592 if (DL.isUnknown()) {
1594 } else if (DL == LastDL) {
1595 // Just repeat the same debug loc as last time.
1596 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
1599 DL.getScopeAndInlinedAt(Scope, IA, I->getContext());
1601 Vals.push_back(DL.getLine());
1602 Vals.push_back(DL.getCol());
1603 Vals.push_back(Scope ? VE.getValueID(Scope)+1 : 0);
1604 Vals.push_back(IA ? VE.getValueID(IA)+1 : 0);
1605 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
1612 // Emit names for all the instructions etc.
1613 WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
1615 if (NeedsMetadataAttachment)
1616 WriteMetadataAttachment(F, VE, Stream);
1621 // Emit blockinfo, which defines the standard abbreviations etc.
1622 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
1623 // We only want to emit block info records for blocks that have multiple
1624 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
1625 // Other blocks can define their abbrevs inline.
1626 Stream.EnterBlockInfoBlock(2);
1628 { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
1629 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1630 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
1631 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1632 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1633 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1634 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1635 Abbv) != VST_ENTRY_8_ABBREV)
1636 llvm_unreachable("Unexpected abbrev ordering!");
1639 { // 7-bit fixed width VST_ENTRY strings.
1640 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1641 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1642 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1643 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1644 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1645 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1646 Abbv) != VST_ENTRY_7_ABBREV)
1647 llvm_unreachable("Unexpected abbrev ordering!");
1649 { // 6-bit char6 VST_ENTRY strings.
1650 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1651 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1652 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1653 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1654 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1655 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1656 Abbv) != VST_ENTRY_6_ABBREV)
1657 llvm_unreachable("Unexpected abbrev ordering!");
1659 { // 6-bit char6 VST_BBENTRY strings.
1660 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1661 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
1662 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1663 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1664 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1665 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1666 Abbv) != VST_BBENTRY_6_ABBREV)
1667 llvm_unreachable("Unexpected abbrev ordering!");
1672 { // SETTYPE abbrev for CONSTANTS_BLOCK.
1673 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1674 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
1675 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1676 Log2_32_Ceil(VE.getTypes().size()+1)));
1677 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1678 Abbv) != CONSTANTS_SETTYPE_ABBREV)
1679 llvm_unreachable("Unexpected abbrev ordering!");
1682 { // INTEGER abbrev for CONSTANTS_BLOCK.
1683 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1684 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
1685 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1686 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1687 Abbv) != CONSTANTS_INTEGER_ABBREV)
1688 llvm_unreachable("Unexpected abbrev ordering!");
1691 { // CE_CAST abbrev for CONSTANTS_BLOCK.
1692 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1693 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
1694 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
1695 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
1696 Log2_32_Ceil(VE.getTypes().size()+1)));
1697 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
1699 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1700 Abbv) != CONSTANTS_CE_CAST_Abbrev)
1701 llvm_unreachable("Unexpected abbrev ordering!");
1703 { // NULL abbrev for CONSTANTS_BLOCK.
1704 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1705 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
1706 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1707 Abbv) != CONSTANTS_NULL_Abbrev)
1708 llvm_unreachable("Unexpected abbrev ordering!");
1711 // FIXME: This should only use space for first class types!
1713 { // INST_LOAD abbrev for FUNCTION_BLOCK.
1714 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1715 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
1716 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
1717 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
1718 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
1719 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1720 Abbv) != FUNCTION_INST_LOAD_ABBREV)
1721 llvm_unreachable("Unexpected abbrev ordering!");
1723 { // INST_BINOP abbrev for FUNCTION_BLOCK.
1724 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1725 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1726 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1727 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1728 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1729 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1730 Abbv) != FUNCTION_INST_BINOP_ABBREV)
1731 llvm_unreachable("Unexpected abbrev ordering!");
1733 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
1734 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1735 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1736 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1737 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1738 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1739 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
1740 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1741 Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV)
1742 llvm_unreachable("Unexpected abbrev ordering!");
1744 { // INST_CAST abbrev for FUNCTION_BLOCK.
1745 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1746 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
1747 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
1748 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
1749 Log2_32_Ceil(VE.getTypes().size()+1)));
1750 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1751 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1752 Abbv) != FUNCTION_INST_CAST_ABBREV)
1753 llvm_unreachable("Unexpected abbrev ordering!");
1756 { // INST_RET abbrev for FUNCTION_BLOCK.
1757 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1758 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1759 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1760 Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
1761 llvm_unreachable("Unexpected abbrev ordering!");
1763 { // INST_RET abbrev for FUNCTION_BLOCK.
1764 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1765 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1766 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
1767 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1768 Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
1769 llvm_unreachable("Unexpected abbrev ordering!");
1771 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
1772 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1773 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
1774 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1775 Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
1776 llvm_unreachable("Unexpected abbrev ordering!");
1782 // Sort the Users based on the order in which the reader parses the bitcode
1784 static bool bitcodereader_order(const User *lhs, const User *rhs) {
1789 static void WriteUseList(const Value *V, const ValueEnumerator &VE,
1790 BitstreamWriter &Stream) {
1792 // One or zero uses can't get out of order.
1793 if (V->use_empty() || V->hasNUses(1))
1796 // Make a copy of the in-memory use-list for sorting.
1797 unsigned UseListSize = std::distance(V->use_begin(), V->use_end());
1798 SmallVector<const User*, 8> UseList;
1799 UseList.reserve(UseListSize);
1800 for (Value::const_use_iterator I = V->use_begin(), E = V->use_end();
1803 UseList.push_back(U);
1806 // Sort the copy based on the order read by the BitcodeReader.
1807 std::sort(UseList.begin(), UseList.end(), bitcodereader_order);
1809 // TODO: Generate a diff between the BitcodeWriter in-memory use-list and the
1810 // sorted list (i.e., the expected BitcodeReader in-memory use-list).
1812 // TODO: Emit the USELIST_CODE_ENTRYs.
1815 static void WriteFunctionUseList(const Function *F, ValueEnumerator &VE,
1816 BitstreamWriter &Stream) {
1817 VE.incorporateFunction(*F);
1819 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1821 WriteUseList(AI, VE, Stream);
1822 for (Function::const_iterator BB = F->begin(), FE = F->end(); BB != FE;
1824 WriteUseList(BB, VE, Stream);
1825 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end(); II != IE;
1827 WriteUseList(II, VE, Stream);
1828 for (User::const_op_iterator OI = II->op_begin(), E = II->op_end();
1830 if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
1831 isa<InlineAsm>(*OI))
1832 WriteUseList(*OI, VE, Stream);
1840 static void WriteModuleUseLists(const Module *M, ValueEnumerator &VE,
1841 BitstreamWriter &Stream) {
1842 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
1844 // XXX: this modifies the module, but in a way that should never change the
1845 // behavior of any pass or codegen in LLVM. The problem is that GVs may
1846 // contain entries in the use_list that do not exist in the Module and are
1847 // not stored in the .bc file.
1848 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1850 I->removeDeadConstantUsers();
1852 // Write the global variables.
1853 for (Module::const_global_iterator GI = M->global_begin(),
1854 GE = M->global_end(); GI != GE; ++GI) {
1855 WriteUseList(GI, VE, Stream);
1857 // Write the global variable initializers.
1858 if (GI->hasInitializer())
1859 WriteUseList(GI->getInitializer(), VE, Stream);
1862 // Write the functions.
1863 for (Module::const_iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI) {
1864 WriteUseList(FI, VE, Stream);
1865 if (!FI->isDeclaration())
1866 WriteFunctionUseList(FI, VE, Stream);
1867 if (FI->hasPrefixData())
1868 WriteUseList(FI->getPrefixData(), VE, Stream);
1871 // Write the aliases.
1872 for (Module::const_alias_iterator AI = M->alias_begin(), AE = M->alias_end();
1874 WriteUseList(AI, VE, Stream);
1875 WriteUseList(AI->getAliasee(), VE, Stream);
1881 /// WriteModule - Emit the specified module to the bitstream.
1882 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
1883 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
1885 SmallVector<unsigned, 1> Vals;
1886 unsigned CurVersion = 1;
1887 Vals.push_back(CurVersion);
1888 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
1890 // Analyze the module, enumerating globals, functions, etc.
1891 ValueEnumerator VE(M);
1893 // Emit blockinfo, which defines the standard abbreviations etc.
1894 WriteBlockInfo(VE, Stream);
1896 // Emit information about attribute groups.
1897 WriteAttributeGroupTable(VE, Stream);
1899 // Emit information about parameter attributes.
1900 WriteAttributeTable(VE, Stream);
1902 // Emit information describing all of the types in the module.
1903 WriteTypeTable(VE, Stream);
1905 // Emit top-level description of module, including target triple, inline asm,
1906 // descriptors for global variables, and function prototype info.
1907 WriteModuleInfo(M, VE, Stream);
1910 WriteModuleConstants(VE, Stream);
1913 WriteModuleMetadata(M, VE, Stream);
1916 WriteModuleMetadataStore(M, Stream);
1918 // Emit names for globals/functions etc.
1919 WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
1922 if (EnablePreserveUseListOrdering)
1923 WriteModuleUseLists(M, VE, Stream);
1925 // Emit function bodies.
1926 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F)
1927 if (!F->isDeclaration())
1928 WriteFunction(*F, VE, Stream);
1933 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
1934 /// header and trailer to make it compatible with the system archiver. To do
1935 /// this we emit the following header, and then emit a trailer that pads the
1936 /// file out to be a multiple of 16 bytes.
1938 /// struct bc_header {
1939 /// uint32_t Magic; // 0x0B17C0DE
1940 /// uint32_t Version; // Version, currently always 0.
1941 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
1942 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
1943 /// uint32_t CPUType; // CPU specifier.
1944 /// ... potentially more later ...
1947 DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
1948 DarwinBCHeaderSize = 5*4
1951 static void WriteInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
1952 uint32_t &Position) {
1953 Buffer[Position + 0] = (unsigned char) (Value >> 0);
1954 Buffer[Position + 1] = (unsigned char) (Value >> 8);
1955 Buffer[Position + 2] = (unsigned char) (Value >> 16);
1956 Buffer[Position + 3] = (unsigned char) (Value >> 24);
1960 static void EmitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
1962 unsigned CPUType = ~0U;
1964 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
1965 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
1966 // number from /usr/include/mach/machine.h. It is ok to reproduce the
1967 // specific constants here because they are implicitly part of the Darwin ABI.
1969 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
1970 DARWIN_CPU_TYPE_X86 = 7,
1971 DARWIN_CPU_TYPE_ARM = 12,
1972 DARWIN_CPU_TYPE_POWERPC = 18
1975 Triple::ArchType Arch = TT.getArch();
1976 if (Arch == Triple::x86_64)
1977 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
1978 else if (Arch == Triple::x86)
1979 CPUType = DARWIN_CPU_TYPE_X86;
1980 else if (Arch == Triple::ppc)
1981 CPUType = DARWIN_CPU_TYPE_POWERPC;
1982 else if (Arch == Triple::ppc64)
1983 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
1984 else if (Arch == Triple::arm || Arch == Triple::thumb)
1985 CPUType = DARWIN_CPU_TYPE_ARM;
1987 // Traditional Bitcode starts after header.
1988 assert(Buffer.size() >= DarwinBCHeaderSize &&
1989 "Expected header size to be reserved");
1990 unsigned BCOffset = DarwinBCHeaderSize;
1991 unsigned BCSize = Buffer.size()-DarwinBCHeaderSize;
1993 // Write the magic and version.
1994 unsigned Position = 0;
1995 WriteInt32ToBuffer(0x0B17C0DE , Buffer, Position);
1996 WriteInt32ToBuffer(0 , Buffer, Position); // Version.
1997 WriteInt32ToBuffer(BCOffset , Buffer, Position);
1998 WriteInt32ToBuffer(BCSize , Buffer, Position);
1999 WriteInt32ToBuffer(CPUType , Buffer, Position);
2001 // If the file is not a multiple of 16 bytes, insert dummy padding.
2002 while (Buffer.size() & 15)
2003 Buffer.push_back(0);
2006 /// WriteBitcodeToFile - Write the specified module to the specified output
2008 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out) {
2009 SmallVector<char, 0> Buffer;
2010 Buffer.reserve(256*1024);
2012 // If this is darwin or another generic macho target, reserve space for the
2014 Triple TT(M->getTargetTriple());
2015 if (TT.isOSDarwin())
2016 Buffer.insert(Buffer.begin(), DarwinBCHeaderSize, 0);
2018 // Emit the module into the buffer.
2020 BitstreamWriter Stream(Buffer);
2022 // Emit the file header.
2023 Stream.Emit((unsigned)'B', 8);
2024 Stream.Emit((unsigned)'C', 8);
2025 Stream.Emit(0x0, 4);
2026 Stream.Emit(0xC, 4);
2027 Stream.Emit(0xE, 4);
2028 Stream.Emit(0xD, 4);
2031 WriteModule(M, Stream);
2034 if (TT.isOSDarwin())
2035 EmitDarwinBCHeaderAndTrailer(Buffer, TT);
2037 // Write the generated bitstream to "Out".
2038 Out.write((char*)&Buffer.front(), Buffer.size());