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/Constants.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/InlineAsm.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/Module.h"
24 #include "llvm/Operator.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/MathExtras.h"
28 #include "llvm/Support/Program.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/ValueSymbolTable.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 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
69 static unsigned GetEncodedCastOpcode(unsigned Opcode) {
71 default: llvm_unreachable("Unknown cast instruction!");
72 case Instruction::Trunc : return bitc::CAST_TRUNC;
73 case Instruction::ZExt : return bitc::CAST_ZEXT;
74 case Instruction::SExt : return bitc::CAST_SEXT;
75 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
76 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
77 case Instruction::UIToFP : return bitc::CAST_UITOFP;
78 case Instruction::SIToFP : return bitc::CAST_SITOFP;
79 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
80 case Instruction::FPExt : return bitc::CAST_FPEXT;
81 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
82 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
83 case Instruction::BitCast : return bitc::CAST_BITCAST;
87 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
89 default: llvm_unreachable("Unknown binary instruction!");
90 case Instruction::Add:
91 case Instruction::FAdd: return bitc::BINOP_ADD;
92 case Instruction::Sub:
93 case Instruction::FSub: return bitc::BINOP_SUB;
94 case Instruction::Mul:
95 case Instruction::FMul: return bitc::BINOP_MUL;
96 case Instruction::UDiv: return bitc::BINOP_UDIV;
97 case Instruction::FDiv:
98 case Instruction::SDiv: return bitc::BINOP_SDIV;
99 case Instruction::URem: return bitc::BINOP_UREM;
100 case Instruction::FRem:
101 case Instruction::SRem: return bitc::BINOP_SREM;
102 case Instruction::Shl: return bitc::BINOP_SHL;
103 case Instruction::LShr: return bitc::BINOP_LSHR;
104 case Instruction::AShr: return bitc::BINOP_ASHR;
105 case Instruction::And: return bitc::BINOP_AND;
106 case Instruction::Or: return bitc::BINOP_OR;
107 case Instruction::Xor: return bitc::BINOP_XOR;
111 static unsigned GetEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
113 default: llvm_unreachable("Unknown RMW operation!");
114 case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
115 case AtomicRMWInst::Add: return bitc::RMW_ADD;
116 case AtomicRMWInst::Sub: return bitc::RMW_SUB;
117 case AtomicRMWInst::And: return bitc::RMW_AND;
118 case AtomicRMWInst::Nand: return bitc::RMW_NAND;
119 case AtomicRMWInst::Or: return bitc::RMW_OR;
120 case AtomicRMWInst::Xor: return bitc::RMW_XOR;
121 case AtomicRMWInst::Max: return bitc::RMW_MAX;
122 case AtomicRMWInst::Min: return bitc::RMW_MIN;
123 case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
124 case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
128 static unsigned GetEncodedOrdering(AtomicOrdering Ordering) {
130 case NotAtomic: return bitc::ORDERING_NOTATOMIC;
131 case Unordered: return bitc::ORDERING_UNORDERED;
132 case Monotonic: return bitc::ORDERING_MONOTONIC;
133 case Acquire: return bitc::ORDERING_ACQUIRE;
134 case Release: return bitc::ORDERING_RELEASE;
135 case AcquireRelease: return bitc::ORDERING_ACQREL;
136 case SequentiallyConsistent: return bitc::ORDERING_SEQCST;
138 llvm_unreachable("Invalid ordering");
141 static unsigned GetEncodedSynchScope(SynchronizationScope SynchScope) {
142 switch (SynchScope) {
143 case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD;
144 case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD;
146 llvm_unreachable("Invalid synch scope");
149 static void WriteStringRecord(unsigned Code, StringRef Str,
150 unsigned AbbrevToUse, BitstreamWriter &Stream) {
151 SmallVector<unsigned, 64> Vals;
153 // Code: [strchar x N]
154 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
155 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
157 Vals.push_back(Str[i]);
160 // Emit the finished record.
161 Stream.EmitRecord(Code, Vals, AbbrevToUse);
164 // Emit information about parameter attributes.
165 static void WriteAttributeTable(const ValueEnumerator &VE,
166 BitstreamWriter &Stream) {
167 const std::vector<AttributeSet> &Attrs = VE.getAttributes();
168 if (Attrs.empty()) return;
170 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
172 SmallVector<uint64_t, 64> Record;
173 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
174 const AttributeSet &A = Attrs[i];
175 for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i) {
176 const AttributeWithIndex &PAWI = A.getSlot(i);
177 Record.push_back(PAWI.Index);
178 Record.push_back(Attributes::encodeLLVMAttributesForBitcode(PAWI.Attrs));
181 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
188 /// WriteTypeTable - Write out the type table for a module.
189 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
190 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
192 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
193 SmallVector<uint64_t, 64> TypeVals;
195 uint64_t NumBits = Log2_32_Ceil(VE.getTypes().size()+1);
197 // Abbrev for TYPE_CODE_POINTER.
198 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
199 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
200 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
201 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
202 unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
204 // Abbrev for TYPE_CODE_FUNCTION.
205 Abbv = new BitCodeAbbrev();
206 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
207 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
208 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
209 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
211 unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
213 // Abbrev for TYPE_CODE_STRUCT_ANON.
214 Abbv = new BitCodeAbbrev();
215 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
216 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
217 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
218 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
220 unsigned StructAnonAbbrev = Stream.EmitAbbrev(Abbv);
222 // Abbrev for TYPE_CODE_STRUCT_NAME.
223 Abbv = new BitCodeAbbrev();
224 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
225 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
226 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
227 unsigned StructNameAbbrev = Stream.EmitAbbrev(Abbv);
229 // Abbrev for TYPE_CODE_STRUCT_NAMED.
230 Abbv = new BitCodeAbbrev();
231 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
232 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
233 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
234 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
236 unsigned StructNamedAbbrev = Stream.EmitAbbrev(Abbv);
238 // Abbrev for TYPE_CODE_ARRAY.
239 Abbv = new BitCodeAbbrev();
240 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
241 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
242 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
244 unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
246 // Emit an entry count so the reader can reserve space.
247 TypeVals.push_back(TypeList.size());
248 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
251 // Loop over all of the types, emitting each in turn.
252 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
253 Type *T = TypeList[i];
257 switch (T->getTypeID()) {
258 default: llvm_unreachable("Unknown type!");
259 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
260 case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break;
261 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
262 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
263 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
264 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
265 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
266 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
267 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
268 case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break;
269 case Type::IntegerTyID:
271 Code = bitc::TYPE_CODE_INTEGER;
272 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
274 case Type::PointerTyID: {
275 PointerType *PTy = cast<PointerType>(T);
276 // POINTER: [pointee type, address space]
277 Code = bitc::TYPE_CODE_POINTER;
278 TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
279 unsigned AddressSpace = PTy->getAddressSpace();
280 TypeVals.push_back(AddressSpace);
281 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
284 case Type::FunctionTyID: {
285 FunctionType *FT = cast<FunctionType>(T);
286 // FUNCTION: [isvararg, retty, paramty x N]
287 Code = bitc::TYPE_CODE_FUNCTION;
288 TypeVals.push_back(FT->isVarArg());
289 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
290 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
291 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
292 AbbrevToUse = FunctionAbbrev;
295 case Type::StructTyID: {
296 StructType *ST = cast<StructType>(T);
297 // STRUCT: [ispacked, eltty x N]
298 TypeVals.push_back(ST->isPacked());
299 // Output all of the element types.
300 for (StructType::element_iterator I = ST->element_begin(),
301 E = ST->element_end(); I != E; ++I)
302 TypeVals.push_back(VE.getTypeID(*I));
304 if (ST->isLiteral()) {
305 Code = bitc::TYPE_CODE_STRUCT_ANON;
306 AbbrevToUse = StructAnonAbbrev;
308 if (ST->isOpaque()) {
309 Code = bitc::TYPE_CODE_OPAQUE;
311 Code = bitc::TYPE_CODE_STRUCT_NAMED;
312 AbbrevToUse = StructNamedAbbrev;
315 // Emit the name if it is present.
316 if (!ST->getName().empty())
317 WriteStringRecord(bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
318 StructNameAbbrev, Stream);
322 case Type::ArrayTyID: {
323 ArrayType *AT = cast<ArrayType>(T);
324 // ARRAY: [numelts, eltty]
325 Code = bitc::TYPE_CODE_ARRAY;
326 TypeVals.push_back(AT->getNumElements());
327 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
328 AbbrevToUse = ArrayAbbrev;
331 case Type::VectorTyID: {
332 VectorType *VT = cast<VectorType>(T);
333 // VECTOR [numelts, eltty]
334 Code = bitc::TYPE_CODE_VECTOR;
335 TypeVals.push_back(VT->getNumElements());
336 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
341 // Emit the finished record.
342 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
349 static unsigned getEncodedLinkage(const GlobalValue *GV) {
350 switch (GV->getLinkage()) {
351 case GlobalValue::ExternalLinkage: return 0;
352 case GlobalValue::WeakAnyLinkage: return 1;
353 case GlobalValue::AppendingLinkage: return 2;
354 case GlobalValue::InternalLinkage: return 3;
355 case GlobalValue::LinkOnceAnyLinkage: return 4;
356 case GlobalValue::DLLImportLinkage: return 5;
357 case GlobalValue::DLLExportLinkage: return 6;
358 case GlobalValue::ExternalWeakLinkage: return 7;
359 case GlobalValue::CommonLinkage: return 8;
360 case GlobalValue::PrivateLinkage: return 9;
361 case GlobalValue::WeakODRLinkage: return 10;
362 case GlobalValue::LinkOnceODRLinkage: return 11;
363 case GlobalValue::AvailableExternallyLinkage: return 12;
364 case GlobalValue::LinkerPrivateLinkage: return 13;
365 case GlobalValue::LinkerPrivateWeakLinkage: return 14;
366 case GlobalValue::LinkOnceODRAutoHideLinkage: return 15;
368 llvm_unreachable("Invalid linkage");
371 static unsigned getEncodedVisibility(const GlobalValue *GV) {
372 switch (GV->getVisibility()) {
373 case GlobalValue::DefaultVisibility: return 0;
374 case GlobalValue::HiddenVisibility: return 1;
375 case GlobalValue::ProtectedVisibility: return 2;
377 llvm_unreachable("Invalid visibility");
380 static unsigned getEncodedThreadLocalMode(const GlobalVariable *GV) {
381 switch (GV->getThreadLocalMode()) {
382 case GlobalVariable::NotThreadLocal: return 0;
383 case GlobalVariable::GeneralDynamicTLSModel: return 1;
384 case GlobalVariable::LocalDynamicTLSModel: return 2;
385 case GlobalVariable::InitialExecTLSModel: return 3;
386 case GlobalVariable::LocalExecTLSModel: return 4;
388 llvm_unreachable("Invalid TLS model");
391 // Emit top-level description of module, including target triple, inline asm,
392 // descriptors for global variables, and function prototype info.
393 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
394 BitstreamWriter &Stream) {
395 // Emit various pieces of data attached to a module.
396 if (!M->getTargetTriple().empty())
397 WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
399 if (!M->getDataLayout().empty())
400 WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(),
402 if (!M->getModuleInlineAsm().empty())
403 WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
406 // Emit information about sections and GC, computing how many there are. Also
407 // compute the maximum alignment value.
408 std::map<std::string, unsigned> SectionMap;
409 std::map<std::string, unsigned> GCMap;
410 unsigned MaxAlignment = 0;
411 unsigned MaxGlobalType = 0;
412 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
414 MaxAlignment = std::max(MaxAlignment, GV->getAlignment());
415 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType()));
416 if (GV->hasSection()) {
417 // Give section names unique ID's.
418 unsigned &Entry = SectionMap[GV->getSection()];
420 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(),
422 Entry = SectionMap.size();
426 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
427 MaxAlignment = std::max(MaxAlignment, F->getAlignment());
428 if (F->hasSection()) {
429 // Give section names unique ID's.
430 unsigned &Entry = SectionMap[F->getSection()];
432 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(),
434 Entry = SectionMap.size();
438 // Same for GC names.
439 unsigned &Entry = GCMap[F->getGC()];
441 WriteStringRecord(bitc::MODULE_CODE_GCNAME, F->getGC(),
443 Entry = GCMap.size();
448 // Emit abbrev for globals, now that we know # sections and max alignment.
449 unsigned SimpleGVarAbbrev = 0;
450 if (!M->global_empty()) {
451 // Add an abbrev for common globals with no visibility or thread localness.
452 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
453 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
454 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
455 Log2_32_Ceil(MaxGlobalType+1)));
456 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Constant.
457 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
458 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // Linkage.
459 if (MaxAlignment == 0) // Alignment.
460 Abbv->Add(BitCodeAbbrevOp(0));
462 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
463 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
464 Log2_32_Ceil(MaxEncAlignment+1)));
466 if (SectionMap.empty()) // Section.
467 Abbv->Add(BitCodeAbbrevOp(0));
469 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
470 Log2_32_Ceil(SectionMap.size()+1)));
471 // Don't bother emitting vis + thread local.
472 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
475 // Emit the global variable information.
476 SmallVector<unsigned, 64> Vals;
477 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
479 unsigned AbbrevToUse = 0;
481 // GLOBALVAR: [type, isconst, initid,
482 // linkage, alignment, section, visibility, threadlocal,
484 Vals.push_back(VE.getTypeID(GV->getType()));
485 Vals.push_back(GV->isConstant());
486 Vals.push_back(GV->isDeclaration() ? 0 :
487 (VE.getValueID(GV->getInitializer()) + 1));
488 Vals.push_back(getEncodedLinkage(GV));
489 Vals.push_back(Log2_32(GV->getAlignment())+1);
490 Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0);
491 if (GV->isThreadLocal() ||
492 GV->getVisibility() != GlobalValue::DefaultVisibility ||
493 GV->hasUnnamedAddr()) {
494 Vals.push_back(getEncodedVisibility(GV));
495 Vals.push_back(getEncodedThreadLocalMode(GV));
496 Vals.push_back(GV->hasUnnamedAddr());
498 AbbrevToUse = SimpleGVarAbbrev;
501 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
505 // Emit the function proto information.
506 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
507 // FUNCTION: [type, callingconv, isproto, linkage, paramattrs, alignment,
508 // section, visibility, gc, unnamed_addr]
509 Vals.push_back(VE.getTypeID(F->getType()));
510 Vals.push_back(F->getCallingConv());
511 Vals.push_back(F->isDeclaration());
512 Vals.push_back(getEncodedLinkage(F));
513 Vals.push_back(VE.getAttributeID(F->getAttributes()));
514 Vals.push_back(Log2_32(F->getAlignment())+1);
515 Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
516 Vals.push_back(getEncodedVisibility(F));
517 Vals.push_back(F->hasGC() ? GCMap[F->getGC()] : 0);
518 Vals.push_back(F->hasUnnamedAddr());
520 unsigned AbbrevToUse = 0;
521 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
525 // Emit the alias information.
526 for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end();
528 // ALIAS: [alias type, aliasee val#, linkage, visibility]
529 Vals.push_back(VE.getTypeID(AI->getType()));
530 Vals.push_back(VE.getValueID(AI->getAliasee()));
531 Vals.push_back(getEncodedLinkage(AI));
532 Vals.push_back(getEncodedVisibility(AI));
533 unsigned AbbrevToUse = 0;
534 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
539 static uint64_t GetOptimizationFlags(const Value *V) {
542 if (const OverflowingBinaryOperator *OBO =
543 dyn_cast<OverflowingBinaryOperator>(V)) {
544 if (OBO->hasNoSignedWrap())
545 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
546 if (OBO->hasNoUnsignedWrap())
547 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
548 } else if (const PossiblyExactOperator *PEO =
549 dyn_cast<PossiblyExactOperator>(V)) {
551 Flags |= 1 << bitc::PEO_EXACT;
552 } else if (const FPMathOperator *FPMO =
553 dyn_cast<const FPMathOperator>(V)) {
554 if (FPMO->hasUnsafeAlgebra())
555 Flags |= 1 << bitc::FMF_UNSAFE_ALGEBRA;
556 if (FPMO->hasNoNaNs())
557 Flags |= 1 << bitc::FMF_NO_NANS;
558 if (FPMO->hasNoInfs())
559 Flags |= 1 << bitc::FMF_NO_INFS;
560 if (FPMO->hasNoSignedZeros())
561 Flags |= 1 << bitc::FMF_NO_SIGNED_ZEROS;
562 if (FPMO->hasAllowReciprocal())
563 Flags |= 1 << bitc::FMF_ALLOW_RECIPROCAL;
569 static void WriteMDNode(const MDNode *N,
570 const ValueEnumerator &VE,
571 BitstreamWriter &Stream,
572 SmallVector<uint64_t, 64> &Record) {
573 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
574 if (N->getOperand(i)) {
575 Record.push_back(VE.getTypeID(N->getOperand(i)->getType()));
576 Record.push_back(VE.getValueID(N->getOperand(i)));
578 Record.push_back(VE.getTypeID(Type::getVoidTy(N->getContext())));
582 unsigned MDCode = N->isFunctionLocal() ? bitc::METADATA_FN_NODE :
584 Stream.EmitRecord(MDCode, Record, 0);
588 static void WriteModuleMetadata(const Module *M,
589 const ValueEnumerator &VE,
590 BitstreamWriter &Stream) {
591 const ValueEnumerator::ValueList &Vals = VE.getMDValues();
592 bool StartedMetadataBlock = false;
593 unsigned MDSAbbrev = 0;
594 SmallVector<uint64_t, 64> Record;
595 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
597 if (const MDNode *N = dyn_cast<MDNode>(Vals[i].first)) {
598 if (!N->isFunctionLocal() || !N->getFunction()) {
599 if (!StartedMetadataBlock) {
600 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
601 StartedMetadataBlock = true;
603 WriteMDNode(N, VE, Stream, Record);
605 } else if (const MDString *MDS = dyn_cast<MDString>(Vals[i].first)) {
606 if (!StartedMetadataBlock) {
607 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
609 // Abbrev for METADATA_STRING.
610 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
611 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING));
612 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
613 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
614 MDSAbbrev = Stream.EmitAbbrev(Abbv);
615 StartedMetadataBlock = true;
618 // Code: [strchar x N]
619 Record.append(MDS->begin(), MDS->end());
621 // Emit the finished record.
622 Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev);
627 // Write named metadata.
628 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
629 E = M->named_metadata_end(); I != E; ++I) {
630 const NamedMDNode *NMD = I;
631 if (!StartedMetadataBlock) {
632 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
633 StartedMetadataBlock = true;
637 StringRef Str = NMD->getName();
638 for (unsigned i = 0, e = Str.size(); i != e; ++i)
639 Record.push_back(Str[i]);
640 Stream.EmitRecord(bitc::METADATA_NAME, Record, 0/*TODO*/);
643 // Write named metadata operands.
644 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
645 Record.push_back(VE.getValueID(NMD->getOperand(i)));
646 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
650 if (StartedMetadataBlock)
654 static void WriteFunctionLocalMetadata(const Function &F,
655 const ValueEnumerator &VE,
656 BitstreamWriter &Stream) {
657 bool StartedMetadataBlock = false;
658 SmallVector<uint64_t, 64> Record;
659 const SmallVector<const MDNode *, 8> &Vals = VE.getFunctionLocalMDValues();
660 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
661 if (const MDNode *N = Vals[i])
662 if (N->isFunctionLocal() && N->getFunction() == &F) {
663 if (!StartedMetadataBlock) {
664 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
665 StartedMetadataBlock = true;
667 WriteMDNode(N, VE, Stream, Record);
670 if (StartedMetadataBlock)
674 static void WriteMetadataAttachment(const Function &F,
675 const ValueEnumerator &VE,
676 BitstreamWriter &Stream) {
677 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
679 SmallVector<uint64_t, 64> Record;
681 // Write metadata attachments
682 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
683 SmallVector<std::pair<unsigned, MDNode*>, 4> MDs;
685 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
686 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
689 I->getAllMetadataOtherThanDebugLoc(MDs);
691 // If no metadata, ignore instruction.
692 if (MDs.empty()) continue;
694 Record.push_back(VE.getInstructionID(I));
696 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
697 Record.push_back(MDs[i].first);
698 Record.push_back(VE.getValueID(MDs[i].second));
700 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
707 static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) {
708 SmallVector<uint64_t, 64> Record;
710 // Write metadata kinds
711 // METADATA_KIND - [n x [id, name]]
712 SmallVector<StringRef, 8> Names;
713 M->getMDKindNames(Names);
715 if (Names.empty()) return;
717 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
719 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
720 Record.push_back(MDKindID);
721 StringRef KName = Names[MDKindID];
722 Record.append(KName.begin(), KName.end());
724 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
731 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
733 Vals.push_back(V << 1);
735 Vals.push_back((-V << 1) | 1);
738 static void EmitAPInt(SmallVectorImpl<uint64_t> &Vals,
739 unsigned &Code, unsigned &AbbrevToUse, const APInt &Val,
740 bool EmitSizeForWideNumbers = false
742 if (Val.getBitWidth() <= 64) {
743 uint64_t V = Val.getSExtValue();
744 emitSignedInt64(Vals, V);
745 Code = bitc::CST_CODE_INTEGER;
746 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
748 // Wide integers, > 64 bits in size.
749 // We have an arbitrary precision integer value to write whose
750 // bit width is > 64. However, in canonical unsigned integer
751 // format it is likely that the high bits are going to be zero.
752 // So, we only write the number of active words.
753 unsigned NWords = Val.getActiveWords();
755 if (EmitSizeForWideNumbers)
756 Vals.push_back(NWords);
758 const uint64_t *RawWords = Val.getRawData();
759 for (unsigned i = 0; i != NWords; ++i) {
760 emitSignedInt64(Vals, RawWords[i]);
762 Code = bitc::CST_CODE_WIDE_INTEGER;
766 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
767 const ValueEnumerator &VE,
768 BitstreamWriter &Stream, bool isGlobal) {
769 if (FirstVal == LastVal) return;
771 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
773 unsigned AggregateAbbrev = 0;
774 unsigned String8Abbrev = 0;
775 unsigned CString7Abbrev = 0;
776 unsigned CString6Abbrev = 0;
777 // If this is a constant pool for the module, emit module-specific abbrevs.
779 // Abbrev for CST_CODE_AGGREGATE.
780 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
781 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
782 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
783 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
784 AggregateAbbrev = Stream.EmitAbbrev(Abbv);
786 // Abbrev for CST_CODE_STRING.
787 Abbv = new BitCodeAbbrev();
788 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
789 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
790 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
791 String8Abbrev = Stream.EmitAbbrev(Abbv);
792 // Abbrev for CST_CODE_CSTRING.
793 Abbv = new BitCodeAbbrev();
794 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
795 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
796 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
797 CString7Abbrev = Stream.EmitAbbrev(Abbv);
798 // Abbrev for CST_CODE_CSTRING.
799 Abbv = new BitCodeAbbrev();
800 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
801 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
802 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
803 CString6Abbrev = Stream.EmitAbbrev(Abbv);
806 SmallVector<uint64_t, 64> Record;
808 const ValueEnumerator::ValueList &Vals = VE.getValues();
810 for (unsigned i = FirstVal; i != LastVal; ++i) {
811 const Value *V = Vals[i].first;
812 // If we need to switch types, do so now.
813 if (V->getType() != LastTy) {
814 LastTy = V->getType();
815 Record.push_back(VE.getTypeID(LastTy));
816 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
817 CONSTANTS_SETTYPE_ABBREV);
821 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
822 Record.push_back(unsigned(IA->hasSideEffects()) |
823 unsigned(IA->isAlignStack()) << 1 |
824 unsigned(IA->getDialect()&1) << 2);
826 // Add the asm string.
827 const std::string &AsmStr = IA->getAsmString();
828 Record.push_back(AsmStr.size());
829 for (unsigned i = 0, e = AsmStr.size(); i != e; ++i)
830 Record.push_back(AsmStr[i]);
832 // Add the constraint string.
833 const std::string &ConstraintStr = IA->getConstraintString();
834 Record.push_back(ConstraintStr.size());
835 for (unsigned i = 0, e = ConstraintStr.size(); i != e; ++i)
836 Record.push_back(ConstraintStr[i]);
837 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
841 const Constant *C = cast<Constant>(V);
843 unsigned AbbrevToUse = 0;
844 if (C->isNullValue()) {
845 Code = bitc::CST_CODE_NULL;
846 } else if (isa<UndefValue>(C)) {
847 Code = bitc::CST_CODE_UNDEF;
848 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
849 EmitAPInt(Record, Code, AbbrevToUse, IV->getValue());
850 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
851 Code = bitc::CST_CODE_FLOAT;
852 Type *Ty = CFP->getType();
853 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
854 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
855 } else if (Ty->isX86_FP80Ty()) {
856 // api needed to prevent premature destruction
857 // bits are not in the same order as a normal i80 APInt, compensate.
858 APInt api = CFP->getValueAPF().bitcastToAPInt();
859 const uint64_t *p = api.getRawData();
860 Record.push_back((p[1] << 48) | (p[0] >> 16));
861 Record.push_back(p[0] & 0xffffLL);
862 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
863 APInt api = CFP->getValueAPF().bitcastToAPInt();
864 const uint64_t *p = api.getRawData();
865 Record.push_back(p[0]);
866 Record.push_back(p[1]);
868 assert (0 && "Unknown FP type!");
870 } else if (isa<ConstantDataSequential>(C) &&
871 cast<ConstantDataSequential>(C)->isString()) {
872 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
873 // Emit constant strings specially.
874 unsigned NumElts = Str->getNumElements();
875 // If this is a null-terminated string, use the denser CSTRING encoding.
876 if (Str->isCString()) {
877 Code = bitc::CST_CODE_CSTRING;
878 --NumElts; // Don't encode the null, which isn't allowed by char6.
880 Code = bitc::CST_CODE_STRING;
881 AbbrevToUse = String8Abbrev;
883 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
884 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
885 for (unsigned i = 0; i != NumElts; ++i) {
886 unsigned char V = Str->getElementAsInteger(i);
888 isCStr7 &= (V & 128) == 0;
890 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
894 AbbrevToUse = CString6Abbrev;
896 AbbrevToUse = CString7Abbrev;
897 } else if (const ConstantDataSequential *CDS =
898 dyn_cast<ConstantDataSequential>(C)) {
899 Code = bitc::CST_CODE_DATA;
900 Type *EltTy = CDS->getType()->getElementType();
901 if (isa<IntegerType>(EltTy)) {
902 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
903 Record.push_back(CDS->getElementAsInteger(i));
904 } else if (EltTy->isFloatTy()) {
905 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
906 union { float F; uint32_t I; };
907 F = CDS->getElementAsFloat(i);
911 assert(EltTy->isDoubleTy() && "Unknown ConstantData element type");
912 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
913 union { double F; uint64_t I; };
914 F = CDS->getElementAsDouble(i);
918 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
919 isa<ConstantVector>(C)) {
920 Code = bitc::CST_CODE_AGGREGATE;
921 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
922 Record.push_back(VE.getValueID(C->getOperand(i)));
923 AbbrevToUse = AggregateAbbrev;
924 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
925 switch (CE->getOpcode()) {
927 if (Instruction::isCast(CE->getOpcode())) {
928 Code = bitc::CST_CODE_CE_CAST;
929 Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
930 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
931 Record.push_back(VE.getValueID(C->getOperand(0)));
932 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
934 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
935 Code = bitc::CST_CODE_CE_BINOP;
936 Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
937 Record.push_back(VE.getValueID(C->getOperand(0)));
938 Record.push_back(VE.getValueID(C->getOperand(1)));
939 uint64_t Flags = GetOptimizationFlags(CE);
941 Record.push_back(Flags);
944 case Instruction::GetElementPtr:
945 Code = bitc::CST_CODE_CE_GEP;
946 if (cast<GEPOperator>(C)->isInBounds())
947 Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
948 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
949 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
950 Record.push_back(VE.getValueID(C->getOperand(i)));
953 case Instruction::Select:
954 Code = bitc::CST_CODE_CE_SELECT;
955 Record.push_back(VE.getValueID(C->getOperand(0)));
956 Record.push_back(VE.getValueID(C->getOperand(1)));
957 Record.push_back(VE.getValueID(C->getOperand(2)));
959 case Instruction::ExtractElement:
960 Code = bitc::CST_CODE_CE_EXTRACTELT;
961 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
962 Record.push_back(VE.getValueID(C->getOperand(0)));
963 Record.push_back(VE.getValueID(C->getOperand(1)));
965 case Instruction::InsertElement:
966 Code = bitc::CST_CODE_CE_INSERTELT;
967 Record.push_back(VE.getValueID(C->getOperand(0)));
968 Record.push_back(VE.getValueID(C->getOperand(1)));
969 Record.push_back(VE.getValueID(C->getOperand(2)));
971 case Instruction::ShuffleVector:
972 // If the return type and argument types are the same, this is a
973 // standard shufflevector instruction. If the types are different,
974 // then the shuffle is widening or truncating the input vectors, and
975 // the argument type must also be encoded.
976 if (C->getType() == C->getOperand(0)->getType()) {
977 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
979 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
980 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
982 Record.push_back(VE.getValueID(C->getOperand(0)));
983 Record.push_back(VE.getValueID(C->getOperand(1)));
984 Record.push_back(VE.getValueID(C->getOperand(2)));
986 case Instruction::ICmp:
987 case Instruction::FCmp:
988 Code = bitc::CST_CODE_CE_CMP;
989 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
990 Record.push_back(VE.getValueID(C->getOperand(0)));
991 Record.push_back(VE.getValueID(C->getOperand(1)));
992 Record.push_back(CE->getPredicate());
995 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
996 Code = bitc::CST_CODE_BLOCKADDRESS;
997 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
998 Record.push_back(VE.getValueID(BA->getFunction()));
999 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
1004 llvm_unreachable("Unknown constant!");
1006 Stream.EmitRecord(Code, Record, AbbrevToUse);
1013 static void WriteModuleConstants(const ValueEnumerator &VE,
1014 BitstreamWriter &Stream) {
1015 const ValueEnumerator::ValueList &Vals = VE.getValues();
1017 // Find the first constant to emit, which is the first non-globalvalue value.
1018 // We know globalvalues have been emitted by WriteModuleInfo.
1019 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1020 if (!isa<GlobalValue>(Vals[i].first)) {
1021 WriteConstants(i, Vals.size(), VE, Stream, true);
1027 /// PushValueAndType - The file has to encode both the value and type id for
1028 /// many values, because we need to know what type to create for forward
1029 /// references. However, most operands are not forward references, so this type
1030 /// field is not needed.
1032 /// This function adds V's value ID to Vals. If the value ID is higher than the
1033 /// instruction ID, then it is a forward reference, and it also includes the
1034 /// type ID. The value ID that is written is encoded relative to the InstID.
1035 static bool PushValueAndType(const Value *V, unsigned InstID,
1036 SmallVector<unsigned, 64> &Vals,
1037 ValueEnumerator &VE) {
1038 unsigned ValID = VE.getValueID(V);
1039 // Make encoding relative to the InstID.
1040 Vals.push_back(InstID - ValID);
1041 if (ValID >= InstID) {
1042 Vals.push_back(VE.getTypeID(V->getType()));
1048 /// pushValue - Like PushValueAndType, but where the type of the value is
1049 /// omitted (perhaps it was already encoded in an earlier operand).
1050 static void pushValue(const Value *V, unsigned InstID,
1051 SmallVector<unsigned, 64> &Vals,
1052 ValueEnumerator &VE) {
1053 unsigned ValID = VE.getValueID(V);
1054 Vals.push_back(InstID - ValID);
1057 static void pushValue64(const Value *V, unsigned InstID,
1058 SmallVector<uint64_t, 128> &Vals,
1059 ValueEnumerator &VE) {
1060 uint64_t ValID = VE.getValueID(V);
1061 Vals.push_back(InstID - ValID);
1064 static void pushValueSigned(const Value *V, unsigned InstID,
1065 SmallVector<uint64_t, 128> &Vals,
1066 ValueEnumerator &VE) {
1067 unsigned ValID = VE.getValueID(V);
1068 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
1069 emitSignedInt64(Vals, diff);
1072 /// WriteInstruction - Emit an instruction to the specified stream.
1073 static void WriteInstruction(const Instruction &I, unsigned InstID,
1074 ValueEnumerator &VE, BitstreamWriter &Stream,
1075 SmallVector<unsigned, 64> &Vals) {
1077 unsigned AbbrevToUse = 0;
1078 VE.setInstructionID(&I);
1079 switch (I.getOpcode()) {
1081 if (Instruction::isCast(I.getOpcode())) {
1082 Code = bitc::FUNC_CODE_INST_CAST;
1083 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1084 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
1085 Vals.push_back(VE.getTypeID(I.getType()));
1086 Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
1088 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
1089 Code = bitc::FUNC_CODE_INST_BINOP;
1090 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1091 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
1092 pushValue(I.getOperand(1), InstID, Vals, VE);
1093 Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
1094 uint64_t Flags = GetOptimizationFlags(&I);
1096 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
1097 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
1098 Vals.push_back(Flags);
1103 case Instruction::GetElementPtr:
1104 Code = bitc::FUNC_CODE_INST_GEP;
1105 if (cast<GEPOperator>(&I)->isInBounds())
1106 Code = bitc::FUNC_CODE_INST_INBOUNDS_GEP;
1107 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1108 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1110 case Instruction::ExtractValue: {
1111 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
1112 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1113 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
1114 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1118 case Instruction::InsertValue: {
1119 Code = bitc::FUNC_CODE_INST_INSERTVAL;
1120 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1121 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1122 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
1123 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1127 case Instruction::Select:
1128 Code = bitc::FUNC_CODE_INST_VSELECT;
1129 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1130 pushValue(I.getOperand(2), InstID, Vals, VE);
1131 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1133 case Instruction::ExtractElement:
1134 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
1135 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1136 pushValue(I.getOperand(1), InstID, Vals, VE);
1138 case Instruction::InsertElement:
1139 Code = bitc::FUNC_CODE_INST_INSERTELT;
1140 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1141 pushValue(I.getOperand(1), InstID, Vals, VE);
1142 pushValue(I.getOperand(2), InstID, Vals, VE);
1144 case Instruction::ShuffleVector:
1145 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
1146 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1147 pushValue(I.getOperand(1), InstID, Vals, VE);
1148 pushValue(I.getOperand(2), InstID, Vals, VE);
1150 case Instruction::ICmp:
1151 case Instruction::FCmp:
1152 // compare returning Int1Ty or vector of Int1Ty
1153 Code = bitc::FUNC_CODE_INST_CMP2;
1154 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1155 pushValue(I.getOperand(1), InstID, Vals, VE);
1156 Vals.push_back(cast<CmpInst>(I).getPredicate());
1159 case Instruction::Ret:
1161 Code = bitc::FUNC_CODE_INST_RET;
1162 unsigned NumOperands = I.getNumOperands();
1163 if (NumOperands == 0)
1164 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
1165 else if (NumOperands == 1) {
1166 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1167 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
1169 for (unsigned i = 0, e = NumOperands; i != e; ++i)
1170 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1174 case Instruction::Br:
1176 Code = bitc::FUNC_CODE_INST_BR;
1177 BranchInst &II = cast<BranchInst>(I);
1178 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
1179 if (II.isConditional()) {
1180 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
1181 pushValue(II.getCondition(), InstID, Vals, VE);
1185 case Instruction::Switch:
1187 // Redefine Vals, since here we need to use 64 bit values
1188 // explicitly to store large APInt numbers.
1189 SmallVector<uint64_t, 128> Vals64;
1191 Code = bitc::FUNC_CODE_INST_SWITCH;
1192 SwitchInst &SI = cast<SwitchInst>(I);
1194 uint32_t SwitchRecordHeader = SI.hash() | (SWITCH_INST_MAGIC << 16);
1195 Vals64.push_back(SwitchRecordHeader);
1197 Vals64.push_back(VE.getTypeID(SI.getCondition()->getType()));
1198 pushValue64(SI.getCondition(), InstID, Vals64, VE);
1199 Vals64.push_back(VE.getValueID(SI.getDefaultDest()));
1200 Vals64.push_back(SI.getNumCases());
1201 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end();
1203 IntegersSubset& CaseRanges = i.getCaseValueEx();
1204 unsigned Code, Abbrev; // will unused.
1206 if (CaseRanges.isSingleNumber()) {
1207 Vals64.push_back(1/*NumItems = 1*/);
1208 Vals64.push_back(true/*IsSingleNumber = true*/);
1209 EmitAPInt(Vals64, Code, Abbrev, CaseRanges.getSingleNumber(0), true);
1212 Vals64.push_back(CaseRanges.getNumItems());
1214 if (CaseRanges.isSingleNumbersOnly()) {
1215 for (unsigned ri = 0, rn = CaseRanges.getNumItems();
1218 Vals64.push_back(true/*IsSingleNumber = true*/);
1220 EmitAPInt(Vals64, Code, Abbrev,
1221 CaseRanges.getSingleNumber(ri), true);
1224 for (unsigned ri = 0, rn = CaseRanges.getNumItems();
1226 IntegersSubset::Range r = CaseRanges.getItem(ri);
1227 bool IsSingleNumber = CaseRanges.isSingleNumber(ri);
1229 Vals64.push_back(IsSingleNumber);
1231 EmitAPInt(Vals64, Code, Abbrev, r.getLow(), true);
1232 if (!IsSingleNumber)
1233 EmitAPInt(Vals64, Code, Abbrev, r.getHigh(), true);
1236 Vals64.push_back(VE.getValueID(i.getCaseSuccessor()));
1239 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
1241 // Also do expected action - clear external Vals collection:
1246 case Instruction::IndirectBr:
1247 Code = bitc::FUNC_CODE_INST_INDIRECTBR;
1248 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1249 // Encode the address operand as relative, but not the basic blocks.
1250 pushValue(I.getOperand(0), InstID, Vals, VE);
1251 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
1252 Vals.push_back(VE.getValueID(I.getOperand(i)));
1255 case Instruction::Invoke: {
1256 const InvokeInst *II = cast<InvokeInst>(&I);
1257 const Value *Callee(II->getCalledValue());
1258 PointerType *PTy = cast<PointerType>(Callee->getType());
1259 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1260 Code = bitc::FUNC_CODE_INST_INVOKE;
1262 Vals.push_back(VE.getAttributeID(II->getAttributes()));
1263 Vals.push_back(II->getCallingConv());
1264 Vals.push_back(VE.getValueID(II->getNormalDest()));
1265 Vals.push_back(VE.getValueID(II->getUnwindDest()));
1266 PushValueAndType(Callee, InstID, Vals, VE);
1268 // Emit value #'s for the fixed parameters.
1269 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1270 pushValue(I.getOperand(i), InstID, Vals, VE); // fixed param.
1272 // Emit type/value pairs for varargs params.
1273 if (FTy->isVarArg()) {
1274 for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
1276 PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
1280 case Instruction::Resume:
1281 Code = bitc::FUNC_CODE_INST_RESUME;
1282 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1284 case Instruction::Unreachable:
1285 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
1286 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
1289 case Instruction::PHI: {
1290 const PHINode &PN = cast<PHINode>(I);
1291 Code = bitc::FUNC_CODE_INST_PHI;
1292 // With the newer instruction encoding, forward references could give
1293 // negative valued IDs. This is most common for PHIs, so we use
1295 SmallVector<uint64_t, 128> Vals64;
1296 Vals64.push_back(VE.getTypeID(PN.getType()));
1297 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1298 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64, VE);
1299 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
1301 // Emit a Vals64 vector and exit.
1302 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
1307 case Instruction::LandingPad: {
1308 const LandingPadInst &LP = cast<LandingPadInst>(I);
1309 Code = bitc::FUNC_CODE_INST_LANDINGPAD;
1310 Vals.push_back(VE.getTypeID(LP.getType()));
1311 PushValueAndType(LP.getPersonalityFn(), InstID, Vals, VE);
1312 Vals.push_back(LP.isCleanup());
1313 Vals.push_back(LP.getNumClauses());
1314 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
1316 Vals.push_back(LandingPadInst::Catch);
1318 Vals.push_back(LandingPadInst::Filter);
1319 PushValueAndType(LP.getClause(I), InstID, Vals, VE);
1324 case Instruction::Alloca:
1325 Code = bitc::FUNC_CODE_INST_ALLOCA;
1326 Vals.push_back(VE.getTypeID(I.getType()));
1327 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1328 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
1329 Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1);
1332 case Instruction::Load:
1333 if (cast<LoadInst>(I).isAtomic()) {
1334 Code = bitc::FUNC_CODE_INST_LOADATOMIC;
1335 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1337 Code = bitc::FUNC_CODE_INST_LOAD;
1338 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) // ptr
1339 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
1341 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
1342 Vals.push_back(cast<LoadInst>(I).isVolatile());
1343 if (cast<LoadInst>(I).isAtomic()) {
1344 Vals.push_back(GetEncodedOrdering(cast<LoadInst>(I).getOrdering()));
1345 Vals.push_back(GetEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
1348 case Instruction::Store:
1349 if (cast<StoreInst>(I).isAtomic())
1350 Code = bitc::FUNC_CODE_INST_STOREATOMIC;
1352 Code = bitc::FUNC_CODE_INST_STORE;
1353 PushValueAndType(I.getOperand(1), InstID, Vals, VE); // ptrty + ptr
1354 pushValue(I.getOperand(0), InstID, Vals, VE); // val.
1355 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
1356 Vals.push_back(cast<StoreInst>(I).isVolatile());
1357 if (cast<StoreInst>(I).isAtomic()) {
1358 Vals.push_back(GetEncodedOrdering(cast<StoreInst>(I).getOrdering()));
1359 Vals.push_back(GetEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
1362 case Instruction::AtomicCmpXchg:
1363 Code = bitc::FUNC_CODE_INST_CMPXCHG;
1364 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr
1365 pushValue(I.getOperand(1), InstID, Vals, VE); // cmp.
1366 pushValue(I.getOperand(2), InstID, Vals, VE); // newval.
1367 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
1368 Vals.push_back(GetEncodedOrdering(
1369 cast<AtomicCmpXchgInst>(I).getOrdering()));
1370 Vals.push_back(GetEncodedSynchScope(
1371 cast<AtomicCmpXchgInst>(I).getSynchScope()));
1373 case Instruction::AtomicRMW:
1374 Code = bitc::FUNC_CODE_INST_ATOMICRMW;
1375 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr
1376 pushValue(I.getOperand(1), InstID, Vals, VE); // val.
1377 Vals.push_back(GetEncodedRMWOperation(
1378 cast<AtomicRMWInst>(I).getOperation()));
1379 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
1380 Vals.push_back(GetEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
1381 Vals.push_back(GetEncodedSynchScope(
1382 cast<AtomicRMWInst>(I).getSynchScope()));
1384 case Instruction::Fence:
1385 Code = bitc::FUNC_CODE_INST_FENCE;
1386 Vals.push_back(GetEncodedOrdering(cast<FenceInst>(I).getOrdering()));
1387 Vals.push_back(GetEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
1389 case Instruction::Call: {
1390 const CallInst &CI = cast<CallInst>(I);
1391 PointerType *PTy = cast<PointerType>(CI.getCalledValue()->getType());
1392 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1394 Code = bitc::FUNC_CODE_INST_CALL;
1396 Vals.push_back(VE.getAttributeID(CI.getAttributes()));
1397 Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall()));
1398 PushValueAndType(CI.getCalledValue(), InstID, Vals, VE); // Callee
1400 // Emit value #'s for the fixed parameters.
1401 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
1402 // Check for labels (can happen with asm labels).
1403 if (FTy->getParamType(i)->isLabelTy())
1404 Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
1406 pushValue(CI.getArgOperand(i), InstID, Vals, VE); // fixed param.
1409 // Emit type/value pairs for varargs params.
1410 if (FTy->isVarArg()) {
1411 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
1413 PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE); // varargs
1417 case Instruction::VAArg:
1418 Code = bitc::FUNC_CODE_INST_VAARG;
1419 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
1420 pushValue(I.getOperand(0), InstID, Vals, VE); // valist.
1421 Vals.push_back(VE.getTypeID(I.getType())); // restype.
1425 Stream.EmitRecord(Code, Vals, AbbrevToUse);
1429 // Emit names for globals/functions etc.
1430 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
1431 const ValueEnumerator &VE,
1432 BitstreamWriter &Stream) {
1433 if (VST.empty()) return;
1434 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
1436 // FIXME: Set up the abbrev, we know how many values there are!
1437 // FIXME: We know if the type names can use 7-bit ascii.
1438 SmallVector<unsigned, 64> NameVals;
1440 for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
1443 const ValueName &Name = *SI;
1445 // Figure out the encoding to use for the name.
1447 bool isChar6 = true;
1448 for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
1451 isChar6 = BitCodeAbbrevOp::isChar6(*C);
1452 if ((unsigned char)*C & 128) {
1454 break; // don't bother scanning the rest.
1458 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
1460 // VST_ENTRY: [valueid, namechar x N]
1461 // VST_BBENTRY: [bbid, namechar x N]
1463 if (isa<BasicBlock>(SI->getValue())) {
1464 Code = bitc::VST_CODE_BBENTRY;
1466 AbbrevToUse = VST_BBENTRY_6_ABBREV;
1468 Code = bitc::VST_CODE_ENTRY;
1470 AbbrevToUse = VST_ENTRY_6_ABBREV;
1472 AbbrevToUse = VST_ENTRY_7_ABBREV;
1475 NameVals.push_back(VE.getValueID(SI->getValue()));
1476 for (const char *P = Name.getKeyData(),
1477 *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
1478 NameVals.push_back((unsigned char)*P);
1480 // Emit the finished record.
1481 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
1487 /// WriteFunction - Emit a function body to the module stream.
1488 static void WriteFunction(const Function &F, ValueEnumerator &VE,
1489 BitstreamWriter &Stream) {
1490 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
1491 VE.incorporateFunction(F);
1493 SmallVector<unsigned, 64> Vals;
1495 // Emit the number of basic blocks, so the reader can create them ahead of
1497 Vals.push_back(VE.getBasicBlocks().size());
1498 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
1501 // If there are function-local constants, emit them now.
1502 unsigned CstStart, CstEnd;
1503 VE.getFunctionConstantRange(CstStart, CstEnd);
1504 WriteConstants(CstStart, CstEnd, VE, Stream, false);
1506 // If there is function-local metadata, emit it now.
1507 WriteFunctionLocalMetadata(F, VE, Stream);
1509 // Keep a running idea of what the instruction ID is.
1510 unsigned InstID = CstEnd;
1512 bool NeedsMetadataAttachment = false;
1516 // Finally, emit all the instructions, in order.
1517 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1518 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1520 WriteInstruction(*I, InstID, VE, Stream, Vals);
1522 if (!I->getType()->isVoidTy())
1525 // If the instruction has metadata, write a metadata attachment later.
1526 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
1528 // If the instruction has a debug location, emit it.
1529 DebugLoc DL = I->getDebugLoc();
1530 if (DL.isUnknown()) {
1532 } else if (DL == LastDL) {
1533 // Just repeat the same debug loc as last time.
1534 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
1537 DL.getScopeAndInlinedAt(Scope, IA, I->getContext());
1539 Vals.push_back(DL.getLine());
1540 Vals.push_back(DL.getCol());
1541 Vals.push_back(Scope ? VE.getValueID(Scope)+1 : 0);
1542 Vals.push_back(IA ? VE.getValueID(IA)+1 : 0);
1543 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
1550 // Emit names for all the instructions etc.
1551 WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
1553 if (NeedsMetadataAttachment)
1554 WriteMetadataAttachment(F, VE, Stream);
1559 // Emit blockinfo, which defines the standard abbreviations etc.
1560 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
1561 // We only want to emit block info records for blocks that have multiple
1562 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
1563 // Other blocks can define their abbrevs inline.
1564 Stream.EnterBlockInfoBlock(2);
1566 { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
1567 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1568 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
1569 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1570 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1571 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1572 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1573 Abbv) != VST_ENTRY_8_ABBREV)
1574 llvm_unreachable("Unexpected abbrev ordering!");
1577 { // 7-bit fixed width VST_ENTRY strings.
1578 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1579 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1580 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1581 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1582 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1583 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1584 Abbv) != VST_ENTRY_7_ABBREV)
1585 llvm_unreachable("Unexpected abbrev ordering!");
1587 { // 6-bit char6 VST_ENTRY strings.
1588 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1589 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1590 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1591 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1592 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1593 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1594 Abbv) != VST_ENTRY_6_ABBREV)
1595 llvm_unreachable("Unexpected abbrev ordering!");
1597 { // 6-bit char6 VST_BBENTRY strings.
1598 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1599 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
1600 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1601 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1602 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1603 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1604 Abbv) != VST_BBENTRY_6_ABBREV)
1605 llvm_unreachable("Unexpected abbrev ordering!");
1610 { // SETTYPE abbrev for CONSTANTS_BLOCK.
1611 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1612 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
1613 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1614 Log2_32_Ceil(VE.getTypes().size()+1)));
1615 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1616 Abbv) != CONSTANTS_SETTYPE_ABBREV)
1617 llvm_unreachable("Unexpected abbrev ordering!");
1620 { // INTEGER abbrev for CONSTANTS_BLOCK.
1621 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1622 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
1623 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1624 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1625 Abbv) != CONSTANTS_INTEGER_ABBREV)
1626 llvm_unreachable("Unexpected abbrev ordering!");
1629 { // CE_CAST abbrev for CONSTANTS_BLOCK.
1630 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1631 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
1632 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
1633 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
1634 Log2_32_Ceil(VE.getTypes().size()+1)));
1635 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
1637 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1638 Abbv) != CONSTANTS_CE_CAST_Abbrev)
1639 llvm_unreachable("Unexpected abbrev ordering!");
1641 { // NULL abbrev for CONSTANTS_BLOCK.
1642 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1643 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
1644 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1645 Abbv) != CONSTANTS_NULL_Abbrev)
1646 llvm_unreachable("Unexpected abbrev ordering!");
1649 // FIXME: This should only use space for first class types!
1651 { // INST_LOAD abbrev for FUNCTION_BLOCK.
1652 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1653 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
1654 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
1655 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
1656 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
1657 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1658 Abbv) != FUNCTION_INST_LOAD_ABBREV)
1659 llvm_unreachable("Unexpected abbrev ordering!");
1661 { // INST_BINOP abbrev for FUNCTION_BLOCK.
1662 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1663 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1664 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1665 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1666 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1667 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1668 Abbv) != FUNCTION_INST_BINOP_ABBREV)
1669 llvm_unreachable("Unexpected abbrev ordering!");
1671 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
1672 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1673 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1674 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1675 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1676 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1677 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
1678 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1679 Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV)
1680 llvm_unreachable("Unexpected abbrev ordering!");
1682 { // INST_CAST abbrev for FUNCTION_BLOCK.
1683 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1684 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
1685 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
1686 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
1687 Log2_32_Ceil(VE.getTypes().size()+1)));
1688 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1689 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1690 Abbv) != FUNCTION_INST_CAST_ABBREV)
1691 llvm_unreachable("Unexpected abbrev ordering!");
1694 { // INST_RET abbrev for FUNCTION_BLOCK.
1695 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1696 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1697 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1698 Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
1699 llvm_unreachable("Unexpected abbrev ordering!");
1701 { // INST_RET abbrev for FUNCTION_BLOCK.
1702 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1703 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1704 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
1705 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1706 Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
1707 llvm_unreachable("Unexpected abbrev ordering!");
1709 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
1710 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1711 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
1712 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1713 Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
1714 llvm_unreachable("Unexpected abbrev ordering!");
1720 // Sort the Users based on the order in which the reader parses the bitcode
1722 static bool bitcodereader_order(const User *lhs, const User *rhs) {
1727 static void WriteUseList(const Value *V, const ValueEnumerator &VE,
1728 BitstreamWriter &Stream) {
1730 // One or zero uses can't get out of order.
1731 if (V->use_empty() || V->hasNUses(1))
1734 // Make a copy of the in-memory use-list for sorting.
1735 unsigned UseListSize = std::distance(V->use_begin(), V->use_end());
1736 SmallVector<const User*, 8> UseList;
1737 UseList.reserve(UseListSize);
1738 for (Value::const_use_iterator I = V->use_begin(), E = V->use_end();
1741 UseList.push_back(U);
1744 // Sort the copy based on the order read by the BitcodeReader.
1745 std::sort(UseList.begin(), UseList.end(), bitcodereader_order);
1747 // TODO: Generate a diff between the BitcodeWriter in-memory use-list and the
1748 // sorted list (i.e., the expected BitcodeReader in-memory use-list).
1750 // TODO: Emit the USELIST_CODE_ENTRYs.
1753 static void WriteFunctionUseList(const Function *F, ValueEnumerator &VE,
1754 BitstreamWriter &Stream) {
1755 VE.incorporateFunction(*F);
1757 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1759 WriteUseList(AI, VE, Stream);
1760 for (Function::const_iterator BB = F->begin(), FE = F->end(); BB != FE;
1762 WriteUseList(BB, VE, Stream);
1763 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end(); II != IE;
1765 WriteUseList(II, VE, Stream);
1766 for (User::const_op_iterator OI = II->op_begin(), E = II->op_end();
1768 if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
1769 isa<InlineAsm>(*OI))
1770 WriteUseList(*OI, VE, Stream);
1778 static void WriteModuleUseLists(const Module *M, ValueEnumerator &VE,
1779 BitstreamWriter &Stream) {
1780 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
1782 // XXX: this modifies the module, but in a way that should never change the
1783 // behavior of any pass or codegen in LLVM. The problem is that GVs may
1784 // contain entries in the use_list that do not exist in the Module and are
1785 // not stored in the .bc file.
1786 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1788 I->removeDeadConstantUsers();
1790 // Write the global variables.
1791 for (Module::const_global_iterator GI = M->global_begin(),
1792 GE = M->global_end(); GI != GE; ++GI) {
1793 WriteUseList(GI, VE, Stream);
1795 // Write the global variable initializers.
1796 if (GI->hasInitializer())
1797 WriteUseList(GI->getInitializer(), VE, Stream);
1800 // Write the functions.
1801 for (Module::const_iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI) {
1802 WriteUseList(FI, VE, Stream);
1803 if (!FI->isDeclaration())
1804 WriteFunctionUseList(FI, VE, Stream);
1807 // Write the aliases.
1808 for (Module::const_alias_iterator AI = M->alias_begin(), AE = M->alias_end();
1810 WriteUseList(AI, VE, Stream);
1811 WriteUseList(AI->getAliasee(), VE, Stream);
1817 /// WriteModule - Emit the specified module to the bitstream.
1818 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
1819 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
1821 SmallVector<unsigned, 1> Vals;
1822 unsigned CurVersion = 1;
1823 Vals.push_back(CurVersion);
1824 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
1826 // Analyze the module, enumerating globals, functions, etc.
1827 ValueEnumerator VE(M);
1829 // Emit blockinfo, which defines the standard abbreviations etc.
1830 WriteBlockInfo(VE, Stream);
1832 // Emit information about parameter attributes.
1833 WriteAttributeTable(VE, Stream);
1835 // Emit information describing all of the types in the module.
1836 WriteTypeTable(VE, Stream);
1838 // Emit top-level description of module, including target triple, inline asm,
1839 // descriptors for global variables, and function prototype info.
1840 WriteModuleInfo(M, VE, Stream);
1843 WriteModuleConstants(VE, Stream);
1846 WriteModuleMetadata(M, VE, Stream);
1849 WriteModuleMetadataStore(M, Stream);
1851 // Emit names for globals/functions etc.
1852 WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
1855 if (EnablePreserveUseListOrdering)
1856 WriteModuleUseLists(M, VE, Stream);
1858 // Emit function bodies.
1859 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F)
1860 if (!F->isDeclaration())
1861 WriteFunction(*F, VE, Stream);
1866 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
1867 /// header and trailer to make it compatible with the system archiver. To do
1868 /// this we emit the following header, and then emit a trailer that pads the
1869 /// file out to be a multiple of 16 bytes.
1871 /// struct bc_header {
1872 /// uint32_t Magic; // 0x0B17C0DE
1873 /// uint32_t Version; // Version, currently always 0.
1874 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
1875 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
1876 /// uint32_t CPUType; // CPU specifier.
1877 /// ... potentially more later ...
1880 DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
1881 DarwinBCHeaderSize = 5*4
1884 static void WriteInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
1885 uint32_t &Position) {
1886 Buffer[Position + 0] = (unsigned char) (Value >> 0);
1887 Buffer[Position + 1] = (unsigned char) (Value >> 8);
1888 Buffer[Position + 2] = (unsigned char) (Value >> 16);
1889 Buffer[Position + 3] = (unsigned char) (Value >> 24);
1893 static void EmitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
1895 unsigned CPUType = ~0U;
1897 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
1898 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
1899 // number from /usr/include/mach/machine.h. It is ok to reproduce the
1900 // specific constants here because they are implicitly part of the Darwin ABI.
1902 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
1903 DARWIN_CPU_TYPE_X86 = 7,
1904 DARWIN_CPU_TYPE_ARM = 12,
1905 DARWIN_CPU_TYPE_POWERPC = 18
1908 Triple::ArchType Arch = TT.getArch();
1909 if (Arch == Triple::x86_64)
1910 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
1911 else if (Arch == Triple::x86)
1912 CPUType = DARWIN_CPU_TYPE_X86;
1913 else if (Arch == Triple::ppc)
1914 CPUType = DARWIN_CPU_TYPE_POWERPC;
1915 else if (Arch == Triple::ppc64)
1916 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
1917 else if (Arch == Triple::arm || Arch == Triple::thumb)
1918 CPUType = DARWIN_CPU_TYPE_ARM;
1920 // Traditional Bitcode starts after header.
1921 assert(Buffer.size() >= DarwinBCHeaderSize &&
1922 "Expected header size to be reserved");
1923 unsigned BCOffset = DarwinBCHeaderSize;
1924 unsigned BCSize = Buffer.size()-DarwinBCHeaderSize;
1926 // Write the magic and version.
1927 unsigned Position = 0;
1928 WriteInt32ToBuffer(0x0B17C0DE , Buffer, Position);
1929 WriteInt32ToBuffer(0 , Buffer, Position); // Version.
1930 WriteInt32ToBuffer(BCOffset , Buffer, Position);
1931 WriteInt32ToBuffer(BCSize , Buffer, Position);
1932 WriteInt32ToBuffer(CPUType , Buffer, Position);
1934 // If the file is not a multiple of 16 bytes, insert dummy padding.
1935 while (Buffer.size() & 15)
1936 Buffer.push_back(0);
1939 /// WriteBitcodeToFile - Write the specified module to the specified output
1941 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out) {
1942 SmallVector<char, 0> Buffer;
1943 Buffer.reserve(256*1024);
1945 // If this is darwin or another generic macho target, reserve space for the
1947 Triple TT(M->getTargetTriple());
1948 if (TT.isOSDarwin())
1949 Buffer.insert(Buffer.begin(), DarwinBCHeaderSize, 0);
1951 // Emit the module into the buffer.
1953 BitstreamWriter Stream(Buffer);
1955 // Emit the file header.
1956 Stream.Emit((unsigned)'B', 8);
1957 Stream.Emit((unsigned)'C', 8);
1958 Stream.Emit(0x0, 4);
1959 Stream.Emit(0xC, 4);
1960 Stream.Emit(0xE, 4);
1961 Stream.Emit(0xD, 4);
1964 WriteModule(M, Stream);
1967 if (TT.isOSDarwin())
1968 EmitDarwinBCHeaderAndTrailer(Buffer, TT);
1970 // Write the generated bitstream to "Out".
1971 Out.write((char*)&Buffer.front(), Buffer.size());