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 "llvm/Bitcode/BitstreamWriter.h"
16 #include "llvm/Bitcode/LLVMBitCodes.h"
17 #include "ValueEnumerator.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/InlineAsm.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/Module.h"
23 #include "llvm/Operator.h"
24 #include "llvm/ValueSymbolTable.h"
25 #include "llvm/ADT/Triple.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/MathExtras.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/Support/Program.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.
46 // VALUE_SYMTAB_BLOCK abbrev id's.
47 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
52 // CONSTANTS_BLOCK abbrev id's.
53 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
54 CONSTANTS_INTEGER_ABBREV,
55 CONSTANTS_CE_CAST_Abbrev,
56 CONSTANTS_NULL_Abbrev,
58 // FUNCTION_BLOCK abbrev id's.
59 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
60 FUNCTION_INST_BINOP_ABBREV,
61 FUNCTION_INST_BINOP_FLAGS_ABBREV,
62 FUNCTION_INST_CAST_ABBREV,
63 FUNCTION_INST_RET_VOID_ABBREV,
64 FUNCTION_INST_RET_VAL_ABBREV,
65 FUNCTION_INST_UNREACHABLE_ABBREV,
68 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
71 static unsigned GetEncodedCastOpcode(unsigned Opcode) {
73 default: llvm_unreachable("Unknown cast instruction!");
74 case Instruction::Trunc : return bitc::CAST_TRUNC;
75 case Instruction::ZExt : return bitc::CAST_ZEXT;
76 case Instruction::SExt : return bitc::CAST_SEXT;
77 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
78 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
79 case Instruction::UIToFP : return bitc::CAST_UITOFP;
80 case Instruction::SIToFP : return bitc::CAST_SITOFP;
81 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
82 case Instruction::FPExt : return bitc::CAST_FPEXT;
83 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
84 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
85 case Instruction::BitCast : return bitc::CAST_BITCAST;
89 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
91 default: llvm_unreachable("Unknown binary instruction!");
92 case Instruction::Add:
93 case Instruction::FAdd: return bitc::BINOP_ADD;
94 case Instruction::Sub:
95 case Instruction::FSub: return bitc::BINOP_SUB;
96 case Instruction::Mul:
97 case Instruction::FMul: return bitc::BINOP_MUL;
98 case Instruction::UDiv: return bitc::BINOP_UDIV;
99 case Instruction::FDiv:
100 case Instruction::SDiv: return bitc::BINOP_SDIV;
101 case Instruction::URem: return bitc::BINOP_UREM;
102 case Instruction::FRem:
103 case Instruction::SRem: return bitc::BINOP_SREM;
104 case Instruction::Shl: return bitc::BINOP_SHL;
105 case Instruction::LShr: return bitc::BINOP_LSHR;
106 case Instruction::AShr: return bitc::BINOP_ASHR;
107 case Instruction::And: return bitc::BINOP_AND;
108 case Instruction::Or: return bitc::BINOP_OR;
109 case Instruction::Xor: return bitc::BINOP_XOR;
113 static unsigned GetEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
115 default: llvm_unreachable("Unknown RMW operation!");
116 case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
117 case AtomicRMWInst::Add: return bitc::RMW_ADD;
118 case AtomicRMWInst::Sub: return bitc::RMW_SUB;
119 case AtomicRMWInst::And: return bitc::RMW_AND;
120 case AtomicRMWInst::Nand: return bitc::RMW_NAND;
121 case AtomicRMWInst::Or: return bitc::RMW_OR;
122 case AtomicRMWInst::Xor: return bitc::RMW_XOR;
123 case AtomicRMWInst::Max: return bitc::RMW_MAX;
124 case AtomicRMWInst::Min: return bitc::RMW_MIN;
125 case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
126 case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
130 static unsigned GetEncodedOrdering(AtomicOrdering Ordering) {
132 case NotAtomic: return bitc::ORDERING_NOTATOMIC;
133 case Unordered: return bitc::ORDERING_UNORDERED;
134 case Monotonic: return bitc::ORDERING_MONOTONIC;
135 case Acquire: return bitc::ORDERING_ACQUIRE;
136 case Release: return bitc::ORDERING_RELEASE;
137 case AcquireRelease: return bitc::ORDERING_ACQREL;
138 case SequentiallyConsistent: return bitc::ORDERING_SEQCST;
140 llvm_unreachable("Invalid ordering");
143 static unsigned GetEncodedSynchScope(SynchronizationScope SynchScope) {
144 switch (SynchScope) {
145 case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD;
146 case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD;
148 llvm_unreachable("Invalid synch scope");
151 static void WriteStringRecord(unsigned Code, StringRef Str,
152 unsigned AbbrevToUse, BitstreamWriter &Stream) {
153 SmallVector<unsigned, 64> Vals;
155 // Code: [strchar x N]
156 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
157 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
159 Vals.push_back(Str[i]);
162 // Emit the finished record.
163 Stream.EmitRecord(Code, Vals, AbbrevToUse);
166 // Emit information about parameter attributes.
167 static void WriteAttributeTable(const ValueEnumerator &VE,
168 BitstreamWriter &Stream) {
169 const std::vector<AttrListPtr> &Attrs = VE.getAttributes();
170 if (Attrs.empty()) return;
172 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
174 SmallVector<uint64_t, 64> Record;
175 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
176 const AttrListPtr &A = Attrs[i];
177 for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i) {
178 const AttributeWithIndex &PAWI = A.getSlot(i);
179 Record.push_back(PAWI.Index);
180 Record.push_back(Attribute::encodeLLVMAttributesForBitcode(PAWI.Attrs));
183 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
190 /// WriteTypeTable - Write out the type table for a module.
191 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
192 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
194 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
195 SmallVector<uint64_t, 64> TypeVals;
197 uint64_t NumBits = Log2_32_Ceil(VE.getTypes().size()+1);
199 // Abbrev for TYPE_CODE_POINTER.
200 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
201 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
202 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
203 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
204 unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
206 // Abbrev for TYPE_CODE_FUNCTION.
207 Abbv = new BitCodeAbbrev();
208 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
209 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
210 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
211 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
213 unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
215 // Abbrev for TYPE_CODE_STRUCT_ANON.
216 Abbv = new BitCodeAbbrev();
217 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
218 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
219 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
220 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
222 unsigned StructAnonAbbrev = Stream.EmitAbbrev(Abbv);
224 // Abbrev for TYPE_CODE_STRUCT_NAME.
225 Abbv = new BitCodeAbbrev();
226 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
227 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
228 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
229 unsigned StructNameAbbrev = Stream.EmitAbbrev(Abbv);
231 // Abbrev for TYPE_CODE_STRUCT_NAMED.
232 Abbv = new BitCodeAbbrev();
233 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
234 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
235 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
236 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
238 unsigned StructNamedAbbrev = Stream.EmitAbbrev(Abbv);
240 // Abbrev for TYPE_CODE_ARRAY.
241 Abbv = new BitCodeAbbrev();
242 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
243 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
244 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
246 unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
248 // Emit an entry count so the reader can reserve space.
249 TypeVals.push_back(TypeList.size());
250 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
253 // Loop over all of the types, emitting each in turn.
254 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
255 Type *T = TypeList[i];
259 switch (T->getTypeID()) {
260 default: llvm_unreachable("Unknown type!");
261 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
262 case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break;
263 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
264 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
265 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
266 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
267 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
268 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
269 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
270 case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break;
271 case Type::IntegerTyID:
273 Code = bitc::TYPE_CODE_INTEGER;
274 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
276 case Type::PointerTyID: {
277 PointerType *PTy = cast<PointerType>(T);
278 // POINTER: [pointee type, address space]
279 Code = bitc::TYPE_CODE_POINTER;
280 TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
281 unsigned AddressSpace = PTy->getAddressSpace();
282 TypeVals.push_back(AddressSpace);
283 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
286 case Type::FunctionTyID: {
287 FunctionType *FT = cast<FunctionType>(T);
288 // FUNCTION: [isvararg, retty, paramty x N]
289 Code = bitc::TYPE_CODE_FUNCTION;
290 TypeVals.push_back(FT->isVarArg());
291 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
292 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
293 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
294 AbbrevToUse = FunctionAbbrev;
297 case Type::StructTyID: {
298 StructType *ST = cast<StructType>(T);
299 // STRUCT: [ispacked, eltty x N]
300 TypeVals.push_back(ST->isPacked());
301 // Output all of the element types.
302 for (StructType::element_iterator I = ST->element_begin(),
303 E = ST->element_end(); I != E; ++I)
304 TypeVals.push_back(VE.getTypeID(*I));
306 if (ST->isLiteral()) {
307 Code = bitc::TYPE_CODE_STRUCT_ANON;
308 AbbrevToUse = StructAnonAbbrev;
310 if (ST->isOpaque()) {
311 Code = bitc::TYPE_CODE_OPAQUE;
313 Code = bitc::TYPE_CODE_STRUCT_NAMED;
314 AbbrevToUse = StructNamedAbbrev;
317 // Emit the name if it is present.
318 if (!ST->getName().empty())
319 WriteStringRecord(bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
320 StructNameAbbrev, Stream);
324 case Type::ArrayTyID: {
325 ArrayType *AT = cast<ArrayType>(T);
326 // ARRAY: [numelts, eltty]
327 Code = bitc::TYPE_CODE_ARRAY;
328 TypeVals.push_back(AT->getNumElements());
329 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
330 AbbrevToUse = ArrayAbbrev;
333 case Type::VectorTyID: {
334 VectorType *VT = cast<VectorType>(T);
335 // VECTOR [numelts, eltty]
336 Code = bitc::TYPE_CODE_VECTOR;
337 TypeVals.push_back(VT->getNumElements());
338 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
343 // Emit the finished record.
344 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
351 static unsigned getEncodedLinkage(const GlobalValue *GV) {
352 switch (GV->getLinkage()) {
353 case GlobalValue::ExternalLinkage: return 0;
354 case GlobalValue::WeakAnyLinkage: return 1;
355 case GlobalValue::AppendingLinkage: return 2;
356 case GlobalValue::InternalLinkage: return 3;
357 case GlobalValue::LinkOnceAnyLinkage: return 4;
358 case GlobalValue::DLLImportLinkage: return 5;
359 case GlobalValue::DLLExportLinkage: return 6;
360 case GlobalValue::ExternalWeakLinkage: return 7;
361 case GlobalValue::CommonLinkage: return 8;
362 case GlobalValue::PrivateLinkage: return 9;
363 case GlobalValue::WeakODRLinkage: return 10;
364 case GlobalValue::LinkOnceODRLinkage: return 11;
365 case GlobalValue::AvailableExternallyLinkage: return 12;
366 case GlobalValue::LinkerPrivateLinkage: return 13;
367 case GlobalValue::LinkerPrivateWeakLinkage: return 14;
368 case GlobalValue::LinkOnceODRAutoHideLinkage: return 15;
370 llvm_unreachable("Invalid linkage");
373 static unsigned getEncodedVisibility(const GlobalValue *GV) {
374 switch (GV->getVisibility()) {
375 case GlobalValue::DefaultVisibility: return 0;
376 case GlobalValue::HiddenVisibility: return 1;
377 case GlobalValue::ProtectedVisibility: return 2;
379 llvm_unreachable("Invalid visibility");
382 static unsigned getEncodedThreadLocalMode(const GlobalVariable *GV) {
383 switch (GV->getThreadLocalMode()) {
384 case GlobalVariable::NotThreadLocal: return 0;
385 case GlobalVariable::GeneralDynamicTLSModel: return 1;
386 case GlobalVariable::LocalDynamicTLSModel: return 2;
387 case GlobalVariable::InitialExecTLSModel: return 3;
388 case GlobalVariable::LocalExecTLSModel: return 4;
390 llvm_unreachable("Invalid TLS model");
393 // Emit top-level description of module, including target triple, inline asm,
394 // descriptors for global variables, and function prototype info.
395 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
396 BitstreamWriter &Stream) {
397 // Emit the list of dependent libraries for the Module.
398 for (Module::lib_iterator I = M->lib_begin(), E = M->lib_end(); I != E; ++I)
399 WriteStringRecord(bitc::MODULE_CODE_DEPLIB, *I, 0/*TODO*/, Stream);
401 // Emit various pieces of data attached to a module.
402 if (!M->getTargetTriple().empty())
403 WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
405 if (!M->getDataLayout().empty())
406 WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(),
408 if (!M->getModuleInlineAsm().empty())
409 WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
412 // Emit information about sections and GC, computing how many there are. Also
413 // compute the maximum alignment value.
414 std::map<std::string, unsigned> SectionMap;
415 std::map<std::string, unsigned> GCMap;
416 unsigned MaxAlignment = 0;
417 unsigned MaxGlobalType = 0;
418 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
420 MaxAlignment = std::max(MaxAlignment, GV->getAlignment());
421 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType()));
422 if (GV->hasSection()) {
423 // Give section names unique ID's.
424 unsigned &Entry = SectionMap[GV->getSection()];
426 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(),
428 Entry = SectionMap.size();
432 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
433 MaxAlignment = std::max(MaxAlignment, F->getAlignment());
434 if (F->hasSection()) {
435 // Give section names unique ID's.
436 unsigned &Entry = SectionMap[F->getSection()];
438 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(),
440 Entry = SectionMap.size();
444 // Same for GC names.
445 unsigned &Entry = GCMap[F->getGC()];
447 WriteStringRecord(bitc::MODULE_CODE_GCNAME, F->getGC(),
449 Entry = GCMap.size();
454 // Emit abbrev for globals, now that we know # sections and max alignment.
455 unsigned SimpleGVarAbbrev = 0;
456 if (!M->global_empty()) {
457 // Add an abbrev for common globals with no visibility or thread localness.
458 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
459 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
460 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
461 Log2_32_Ceil(MaxGlobalType+1)));
462 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Constant.
463 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
464 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // Linkage.
465 if (MaxAlignment == 0) // Alignment.
466 Abbv->Add(BitCodeAbbrevOp(0));
468 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
469 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
470 Log2_32_Ceil(MaxEncAlignment+1)));
472 if (SectionMap.empty()) // Section.
473 Abbv->Add(BitCodeAbbrevOp(0));
475 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
476 Log2_32_Ceil(SectionMap.size()+1)));
477 // Don't bother emitting vis + thread local.
478 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
481 // Emit the global variable information.
482 SmallVector<unsigned, 64> Vals;
483 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
485 unsigned AbbrevToUse = 0;
487 // GLOBALVAR: [type, isconst, initid,
488 // linkage, alignment, section, visibility, threadlocal,
490 Vals.push_back(VE.getTypeID(GV->getType()));
491 Vals.push_back(GV->isConstant());
492 Vals.push_back(GV->isDeclaration() ? 0 :
493 (VE.getValueID(GV->getInitializer()) + 1));
494 Vals.push_back(getEncodedLinkage(GV));
495 Vals.push_back(Log2_32(GV->getAlignment())+1);
496 Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0);
497 if (GV->isThreadLocal() ||
498 GV->getVisibility() != GlobalValue::DefaultVisibility ||
499 GV->hasUnnamedAddr()) {
500 Vals.push_back(getEncodedVisibility(GV));
501 Vals.push_back(getEncodedThreadLocalMode(GV));
502 Vals.push_back(GV->hasUnnamedAddr());
504 AbbrevToUse = SimpleGVarAbbrev;
507 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
511 // Emit the function proto information.
512 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
513 // FUNCTION: [type, callingconv, isproto, linkage, paramattrs, alignment,
514 // section, visibility, gc, unnamed_addr]
515 Vals.push_back(VE.getTypeID(F->getType()));
516 Vals.push_back(F->getCallingConv());
517 Vals.push_back(F->isDeclaration());
518 Vals.push_back(getEncodedLinkage(F));
519 Vals.push_back(VE.getAttributeID(F->getAttributes()));
520 Vals.push_back(Log2_32(F->getAlignment())+1);
521 Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
522 Vals.push_back(getEncodedVisibility(F));
523 Vals.push_back(F->hasGC() ? GCMap[F->getGC()] : 0);
524 Vals.push_back(F->hasUnnamedAddr());
526 unsigned AbbrevToUse = 0;
527 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
531 // Emit the alias information.
532 for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end();
534 // ALIAS: [alias type, aliasee val#, linkage, visibility]
535 Vals.push_back(VE.getTypeID(AI->getType()));
536 Vals.push_back(VE.getValueID(AI->getAliasee()));
537 Vals.push_back(getEncodedLinkage(AI));
538 Vals.push_back(getEncodedVisibility(AI));
539 unsigned AbbrevToUse = 0;
540 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
545 static uint64_t GetOptimizationFlags(const Value *V) {
548 if (const OverflowingBinaryOperator *OBO =
549 dyn_cast<OverflowingBinaryOperator>(V)) {
550 if (OBO->hasNoSignedWrap())
551 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
552 if (OBO->hasNoUnsignedWrap())
553 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
554 } else if (const PossiblyExactOperator *PEO =
555 dyn_cast<PossiblyExactOperator>(V)) {
557 Flags |= 1 << bitc::PEO_EXACT;
563 static void WriteMDNode(const MDNode *N,
564 const ValueEnumerator &VE,
565 BitstreamWriter &Stream,
566 SmallVector<uint64_t, 64> &Record) {
567 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
568 if (N->getOperand(i)) {
569 Record.push_back(VE.getTypeID(N->getOperand(i)->getType()));
570 Record.push_back(VE.getValueID(N->getOperand(i)));
572 Record.push_back(VE.getTypeID(Type::getVoidTy(N->getContext())));
576 unsigned MDCode = N->isFunctionLocal() ? bitc::METADATA_FN_NODE :
578 Stream.EmitRecord(MDCode, Record, 0);
582 static void WriteModuleMetadata(const Module *M,
583 const ValueEnumerator &VE,
584 BitstreamWriter &Stream) {
585 const ValueEnumerator::ValueList &Vals = VE.getMDValues();
586 bool StartedMetadataBlock = false;
587 unsigned MDSAbbrev = 0;
588 SmallVector<uint64_t, 64> Record;
589 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
591 if (const MDNode *N = dyn_cast<MDNode>(Vals[i].first)) {
592 if (!N->isFunctionLocal() || !N->getFunction()) {
593 if (!StartedMetadataBlock) {
594 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
595 StartedMetadataBlock = true;
597 WriteMDNode(N, VE, Stream, Record);
599 } else if (const MDString *MDS = dyn_cast<MDString>(Vals[i].first)) {
600 if (!StartedMetadataBlock) {
601 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
603 // Abbrev for METADATA_STRING.
604 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
605 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING));
606 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
607 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
608 MDSAbbrev = Stream.EmitAbbrev(Abbv);
609 StartedMetadataBlock = true;
612 // Code: [strchar x N]
613 Record.append(MDS->begin(), MDS->end());
615 // Emit the finished record.
616 Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev);
621 // Write named metadata.
622 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
623 E = M->named_metadata_end(); I != E; ++I) {
624 const NamedMDNode *NMD = I;
625 if (!StartedMetadataBlock) {
626 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
627 StartedMetadataBlock = true;
631 StringRef Str = NMD->getName();
632 for (unsigned i = 0, e = Str.size(); i != e; ++i)
633 Record.push_back(Str[i]);
634 Stream.EmitRecord(bitc::METADATA_NAME, Record, 0/*TODO*/);
637 // Write named metadata operands.
638 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
639 Record.push_back(VE.getValueID(NMD->getOperand(i)));
640 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
644 if (StartedMetadataBlock)
648 static void WriteFunctionLocalMetadata(const Function &F,
649 const ValueEnumerator &VE,
650 BitstreamWriter &Stream) {
651 bool StartedMetadataBlock = false;
652 SmallVector<uint64_t, 64> Record;
653 const SmallVector<const MDNode *, 8> &Vals = VE.getFunctionLocalMDValues();
654 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
655 if (const MDNode *N = Vals[i])
656 if (N->isFunctionLocal() && N->getFunction() == &F) {
657 if (!StartedMetadataBlock) {
658 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
659 StartedMetadataBlock = true;
661 WriteMDNode(N, VE, Stream, Record);
664 if (StartedMetadataBlock)
668 static void WriteMetadataAttachment(const Function &F,
669 const ValueEnumerator &VE,
670 BitstreamWriter &Stream) {
671 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
673 SmallVector<uint64_t, 64> Record;
675 // Write metadata attachments
676 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
677 SmallVector<std::pair<unsigned, MDNode*>, 4> MDs;
679 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
680 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
683 I->getAllMetadataOtherThanDebugLoc(MDs);
685 // If no metadata, ignore instruction.
686 if (MDs.empty()) continue;
688 Record.push_back(VE.getInstructionID(I));
690 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
691 Record.push_back(MDs[i].first);
692 Record.push_back(VE.getValueID(MDs[i].second));
694 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
701 static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) {
702 SmallVector<uint64_t, 64> Record;
704 // Write metadata kinds
705 // METADATA_KIND - [n x [id, name]]
706 SmallVector<StringRef, 4> Names;
707 M->getMDKindNames(Names);
709 if (Names.empty()) return;
711 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
713 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
714 Record.push_back(MDKindID);
715 StringRef KName = Names[MDKindID];
716 Record.append(KName.begin(), KName.end());
718 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
725 static void EmitAPInt(SmallVectorImpl<uint64_t> &Vals,
726 unsigned &Code, unsigned &AbbrevToUse, const APInt &Val,
727 bool EmitSizeForWideNumbers = false
729 if (Val.getBitWidth() <= 64) {
730 uint64_t V = Val.getSExtValue();
732 Vals.push_back(V << 1);
734 Vals.push_back((-V << 1) | 1);
735 Code = bitc::CST_CODE_INTEGER;
736 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
738 // Wide integers, > 64 bits in size.
739 // We have an arbitrary precision integer value to write whose
740 // bit width is > 64. However, in canonical unsigned integer
741 // format it is likely that the high bits are going to be zero.
742 // So, we only write the number of active words.
743 unsigned NWords = Val.getActiveWords();
745 if (EmitSizeForWideNumbers)
746 Vals.push_back(NWords);
748 const uint64_t *RawWords = Val.getRawData();
749 for (unsigned i = 0; i != NWords; ++i) {
750 int64_t V = RawWords[i];
752 Vals.push_back(V << 1);
754 Vals.push_back((-V << 1) | 1);
756 Code = bitc::CST_CODE_WIDE_INTEGER;
760 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
761 const ValueEnumerator &VE,
762 BitstreamWriter &Stream, bool isGlobal) {
763 if (FirstVal == LastVal) return;
765 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
767 unsigned AggregateAbbrev = 0;
768 unsigned String8Abbrev = 0;
769 unsigned CString7Abbrev = 0;
770 unsigned CString6Abbrev = 0;
771 // If this is a constant pool for the module, emit module-specific abbrevs.
773 // Abbrev for CST_CODE_AGGREGATE.
774 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
775 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
776 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
777 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
778 AggregateAbbrev = Stream.EmitAbbrev(Abbv);
780 // Abbrev for CST_CODE_STRING.
781 Abbv = new BitCodeAbbrev();
782 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
783 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
784 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
785 String8Abbrev = Stream.EmitAbbrev(Abbv);
786 // Abbrev for CST_CODE_CSTRING.
787 Abbv = new BitCodeAbbrev();
788 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
789 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
790 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
791 CString7Abbrev = 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::Char6));
797 CString6Abbrev = Stream.EmitAbbrev(Abbv);
800 SmallVector<uint64_t, 64> Record;
802 const ValueEnumerator::ValueList &Vals = VE.getValues();
804 for (unsigned i = FirstVal; i != LastVal; ++i) {
805 const Value *V = Vals[i].first;
806 // If we need to switch types, do so now.
807 if (V->getType() != LastTy) {
808 LastTy = V->getType();
809 Record.push_back(VE.getTypeID(LastTy));
810 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
811 CONSTANTS_SETTYPE_ABBREV);
815 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
816 Record.push_back(unsigned(IA->hasSideEffects()) |
817 unsigned(IA->isAlignStack()) << 1);
819 // Add the asm string.
820 const std::string &AsmStr = IA->getAsmString();
821 Record.push_back(AsmStr.size());
822 for (unsigned i = 0, e = AsmStr.size(); i != e; ++i)
823 Record.push_back(AsmStr[i]);
825 // Add the constraint string.
826 const std::string &ConstraintStr = IA->getConstraintString();
827 Record.push_back(ConstraintStr.size());
828 for (unsigned i = 0, e = ConstraintStr.size(); i != e; ++i)
829 Record.push_back(ConstraintStr[i]);
830 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
834 const Constant *C = cast<Constant>(V);
836 unsigned AbbrevToUse = 0;
837 if (C->isNullValue()) {
838 Code = bitc::CST_CODE_NULL;
839 } else if (isa<UndefValue>(C)) {
840 Code = bitc::CST_CODE_UNDEF;
841 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
842 EmitAPInt(Record, Code, AbbrevToUse, IV->getValue());
843 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
844 Code = bitc::CST_CODE_FLOAT;
845 Type *Ty = CFP->getType();
846 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
847 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
848 } else if (Ty->isX86_FP80Ty()) {
849 // api needed to prevent premature destruction
850 // bits are not in the same order as a normal i80 APInt, compensate.
851 APInt api = CFP->getValueAPF().bitcastToAPInt();
852 const uint64_t *p = api.getRawData();
853 Record.push_back((p[1] << 48) | (p[0] >> 16));
854 Record.push_back(p[0] & 0xffffLL);
855 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
856 APInt api = CFP->getValueAPF().bitcastToAPInt();
857 const uint64_t *p = api.getRawData();
858 Record.push_back(p[0]);
859 Record.push_back(p[1]);
861 assert (0 && "Unknown FP type!");
863 } else if (isa<ConstantDataSequential>(C) &&
864 cast<ConstantDataSequential>(C)->isString()) {
865 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
866 // Emit constant strings specially.
867 unsigned NumElts = Str->getNumElements();
868 // If this is a null-terminated string, use the denser CSTRING encoding.
869 if (Str->isCString()) {
870 Code = bitc::CST_CODE_CSTRING;
871 --NumElts; // Don't encode the null, which isn't allowed by char6.
873 Code = bitc::CST_CODE_STRING;
874 AbbrevToUse = String8Abbrev;
876 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
877 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
878 for (unsigned i = 0; i != NumElts; ++i) {
879 unsigned char V = Str->getElementAsInteger(i);
881 isCStr7 &= (V & 128) == 0;
883 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
887 AbbrevToUse = CString6Abbrev;
889 AbbrevToUse = CString7Abbrev;
890 } else if (const ConstantDataSequential *CDS =
891 dyn_cast<ConstantDataSequential>(C)) {
892 Code = bitc::CST_CODE_DATA;
893 Type *EltTy = CDS->getType()->getElementType();
894 if (isa<IntegerType>(EltTy)) {
895 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
896 Record.push_back(CDS->getElementAsInteger(i));
897 } else if (EltTy->isFloatTy()) {
898 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
899 union { float F; uint32_t I; };
900 F = CDS->getElementAsFloat(i);
904 assert(EltTy->isDoubleTy() && "Unknown ConstantData element type");
905 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
906 union { double F; uint64_t I; };
907 F = CDS->getElementAsDouble(i);
911 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
912 isa<ConstantVector>(C)) {
913 Code = bitc::CST_CODE_AGGREGATE;
914 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
915 Record.push_back(VE.getValueID(C->getOperand(i)));
916 AbbrevToUse = AggregateAbbrev;
917 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
918 switch (CE->getOpcode()) {
920 if (Instruction::isCast(CE->getOpcode())) {
921 Code = bitc::CST_CODE_CE_CAST;
922 Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
923 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
924 Record.push_back(VE.getValueID(C->getOperand(0)));
925 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
927 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
928 Code = bitc::CST_CODE_CE_BINOP;
929 Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
930 Record.push_back(VE.getValueID(C->getOperand(0)));
931 Record.push_back(VE.getValueID(C->getOperand(1)));
932 uint64_t Flags = GetOptimizationFlags(CE);
934 Record.push_back(Flags);
937 case Instruction::GetElementPtr:
938 Code = bitc::CST_CODE_CE_GEP;
939 if (cast<GEPOperator>(C)->isInBounds())
940 Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
941 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
942 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
943 Record.push_back(VE.getValueID(C->getOperand(i)));
946 case Instruction::Select:
947 Code = bitc::CST_CODE_CE_SELECT;
948 Record.push_back(VE.getValueID(C->getOperand(0)));
949 Record.push_back(VE.getValueID(C->getOperand(1)));
950 Record.push_back(VE.getValueID(C->getOperand(2)));
952 case Instruction::ExtractElement:
953 Code = bitc::CST_CODE_CE_EXTRACTELT;
954 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
955 Record.push_back(VE.getValueID(C->getOperand(0)));
956 Record.push_back(VE.getValueID(C->getOperand(1)));
958 case Instruction::InsertElement:
959 Code = bitc::CST_CODE_CE_INSERTELT;
960 Record.push_back(VE.getValueID(C->getOperand(0)));
961 Record.push_back(VE.getValueID(C->getOperand(1)));
962 Record.push_back(VE.getValueID(C->getOperand(2)));
964 case Instruction::ShuffleVector:
965 // If the return type and argument types are the same, this is a
966 // standard shufflevector instruction. If the types are different,
967 // then the shuffle is widening or truncating the input vectors, and
968 // the argument type must also be encoded.
969 if (C->getType() == C->getOperand(0)->getType()) {
970 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
972 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
973 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
975 Record.push_back(VE.getValueID(C->getOperand(0)));
976 Record.push_back(VE.getValueID(C->getOperand(1)));
977 Record.push_back(VE.getValueID(C->getOperand(2)));
979 case Instruction::ICmp:
980 case Instruction::FCmp:
981 Code = bitc::CST_CODE_CE_CMP;
982 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
983 Record.push_back(VE.getValueID(C->getOperand(0)));
984 Record.push_back(VE.getValueID(C->getOperand(1)));
985 Record.push_back(CE->getPredicate());
988 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
989 Code = bitc::CST_CODE_BLOCKADDRESS;
990 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
991 Record.push_back(VE.getValueID(BA->getFunction()));
992 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
997 llvm_unreachable("Unknown constant!");
999 Stream.EmitRecord(Code, Record, AbbrevToUse);
1006 static void WriteModuleConstants(const ValueEnumerator &VE,
1007 BitstreamWriter &Stream) {
1008 const ValueEnumerator::ValueList &Vals = VE.getValues();
1010 // Find the first constant to emit, which is the first non-globalvalue value.
1011 // We know globalvalues have been emitted by WriteModuleInfo.
1012 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1013 if (!isa<GlobalValue>(Vals[i].first)) {
1014 WriteConstants(i, Vals.size(), VE, Stream, true);
1020 /// PushValueAndType - The file has to encode both the value and type id for
1021 /// many values, because we need to know what type to create for forward
1022 /// references. However, most operands are not forward references, so this type
1023 /// field is not needed.
1025 /// This function adds V's value ID to Vals. If the value ID is higher than the
1026 /// instruction ID, then it is a forward reference, and it also includes the
1028 static bool PushValueAndType(const Value *V, unsigned InstID,
1029 SmallVector<unsigned, 64> &Vals,
1030 ValueEnumerator &VE) {
1031 unsigned ValID = VE.getValueID(V);
1032 Vals.push_back(ValID);
1033 if (ValID >= InstID) {
1034 Vals.push_back(VE.getTypeID(V->getType()));
1040 /// WriteInstruction - Emit an instruction to the specified stream.
1041 static void WriteInstruction(const Instruction &I, unsigned InstID,
1042 ValueEnumerator &VE, BitstreamWriter &Stream,
1043 SmallVector<unsigned, 64> &Vals) {
1045 unsigned AbbrevToUse = 0;
1046 VE.setInstructionID(&I);
1047 switch (I.getOpcode()) {
1049 if (Instruction::isCast(I.getOpcode())) {
1050 Code = bitc::FUNC_CODE_INST_CAST;
1051 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1052 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
1053 Vals.push_back(VE.getTypeID(I.getType()));
1054 Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
1056 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
1057 Code = bitc::FUNC_CODE_INST_BINOP;
1058 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1059 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
1060 Vals.push_back(VE.getValueID(I.getOperand(1)));
1061 Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
1062 uint64_t Flags = GetOptimizationFlags(&I);
1064 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
1065 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
1066 Vals.push_back(Flags);
1071 case Instruction::GetElementPtr:
1072 Code = bitc::FUNC_CODE_INST_GEP;
1073 if (cast<GEPOperator>(&I)->isInBounds())
1074 Code = bitc::FUNC_CODE_INST_INBOUNDS_GEP;
1075 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1076 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1078 case Instruction::ExtractValue: {
1079 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
1080 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1081 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
1082 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1086 case Instruction::InsertValue: {
1087 Code = bitc::FUNC_CODE_INST_INSERTVAL;
1088 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1089 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1090 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
1091 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1095 case Instruction::Select:
1096 Code = bitc::FUNC_CODE_INST_VSELECT;
1097 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1098 Vals.push_back(VE.getValueID(I.getOperand(2)));
1099 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1101 case Instruction::ExtractElement:
1102 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
1103 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1104 Vals.push_back(VE.getValueID(I.getOperand(1)));
1106 case Instruction::InsertElement:
1107 Code = bitc::FUNC_CODE_INST_INSERTELT;
1108 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1109 Vals.push_back(VE.getValueID(I.getOperand(1)));
1110 Vals.push_back(VE.getValueID(I.getOperand(2)));
1112 case Instruction::ShuffleVector:
1113 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
1114 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1115 Vals.push_back(VE.getValueID(I.getOperand(1)));
1116 Vals.push_back(VE.getValueID(I.getOperand(2)));
1118 case Instruction::ICmp:
1119 case Instruction::FCmp:
1120 // compare returning Int1Ty or vector of Int1Ty
1121 Code = bitc::FUNC_CODE_INST_CMP2;
1122 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1123 Vals.push_back(VE.getValueID(I.getOperand(1)));
1124 Vals.push_back(cast<CmpInst>(I).getPredicate());
1127 case Instruction::Ret:
1129 Code = bitc::FUNC_CODE_INST_RET;
1130 unsigned NumOperands = I.getNumOperands();
1131 if (NumOperands == 0)
1132 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
1133 else if (NumOperands == 1) {
1134 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1135 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
1137 for (unsigned i = 0, e = NumOperands; i != e; ++i)
1138 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1142 case Instruction::Br:
1144 Code = bitc::FUNC_CODE_INST_BR;
1145 BranchInst &II = cast<BranchInst>(I);
1146 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
1147 if (II.isConditional()) {
1148 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
1149 Vals.push_back(VE.getValueID(II.getCondition()));
1153 case Instruction::Switch:
1155 // Redefine Vals, since here we need to use 64 bit values
1156 // explicitly to store large APInt numbers.
1157 SmallVector<uint64_t, 128> Vals64;
1159 Code = bitc::FUNC_CODE_INST_SWITCH;
1160 SwitchInst &SI = cast<SwitchInst>(I);
1162 uint32_t SwitchRecordHeader = SI.hash() | (SWITCH_INST_MAGIC << 16);
1163 Vals64.push_back(SwitchRecordHeader);
1165 Vals64.push_back(VE.getTypeID(SI.getCondition()->getType()));
1166 Vals64.push_back(VE.getValueID(SI.getCondition()));
1167 Vals64.push_back(VE.getValueID(SI.getDefaultDest()));
1168 Vals64.push_back(SI.getNumCases());
1169 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end();
1171 IntegersSubset& CaseRanges = i.getCaseValueEx();
1172 unsigned Code, Abbrev; // will unused.
1174 if (CaseRanges.isSingleNumber()) {
1175 Vals64.push_back(1/*NumItems = 1*/);
1176 Vals64.push_back(true/*IsSingleNumber = true*/);
1177 EmitAPInt(Vals64, Code, Abbrev, CaseRanges.getSingleNumber(0), true);
1180 Vals64.push_back(CaseRanges.getNumItems());
1182 if (CaseRanges.isSingleNumbersOnly()) {
1183 for (unsigned ri = 0, rn = CaseRanges.getNumItems();
1186 Vals64.push_back(true/*IsSingleNumber = true*/);
1188 EmitAPInt(Vals64, Code, Abbrev,
1189 CaseRanges.getSingleNumber(ri), true);
1192 for (unsigned ri = 0, rn = CaseRanges.getNumItems();
1194 IntegersSubset::Range r = CaseRanges.getItem(ri);
1195 bool IsSingleNumber = CaseRanges.isSingleNumber(ri);
1197 Vals64.push_back(IsSingleNumber);
1199 EmitAPInt(Vals64, Code, Abbrev, r.getLow(), true);
1200 if (!IsSingleNumber)
1201 EmitAPInt(Vals64, Code, Abbrev, r.getHigh(), true);
1204 Vals64.push_back(VE.getValueID(i.getCaseSuccessor()));
1207 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
1209 // Also do expected action - clear external Vals collection:
1214 case Instruction::IndirectBr:
1215 Code = bitc::FUNC_CODE_INST_INDIRECTBR;
1216 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1217 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1218 Vals.push_back(VE.getValueID(I.getOperand(i)));
1221 case Instruction::Invoke: {
1222 const InvokeInst *II = cast<InvokeInst>(&I);
1223 const Value *Callee(II->getCalledValue());
1224 PointerType *PTy = cast<PointerType>(Callee->getType());
1225 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1226 Code = bitc::FUNC_CODE_INST_INVOKE;
1228 Vals.push_back(VE.getAttributeID(II->getAttributes()));
1229 Vals.push_back(II->getCallingConv());
1230 Vals.push_back(VE.getValueID(II->getNormalDest()));
1231 Vals.push_back(VE.getValueID(II->getUnwindDest()));
1232 PushValueAndType(Callee, InstID, Vals, VE);
1234 // Emit value #'s for the fixed parameters.
1235 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1236 Vals.push_back(VE.getValueID(I.getOperand(i))); // fixed param.
1238 // Emit type/value pairs for varargs params.
1239 if (FTy->isVarArg()) {
1240 for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
1242 PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
1246 case Instruction::Resume:
1247 Code = bitc::FUNC_CODE_INST_RESUME;
1248 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1250 case Instruction::Unreachable:
1251 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
1252 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
1255 case Instruction::PHI: {
1256 const PHINode &PN = cast<PHINode>(I);
1257 Code = bitc::FUNC_CODE_INST_PHI;
1258 Vals.push_back(VE.getTypeID(PN.getType()));
1259 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1260 Vals.push_back(VE.getValueID(PN.getIncomingValue(i)));
1261 Vals.push_back(VE.getValueID(PN.getIncomingBlock(i)));
1266 case Instruction::LandingPad: {
1267 const LandingPadInst &LP = cast<LandingPadInst>(I);
1268 Code = bitc::FUNC_CODE_INST_LANDINGPAD;
1269 Vals.push_back(VE.getTypeID(LP.getType()));
1270 PushValueAndType(LP.getPersonalityFn(), InstID, Vals, VE);
1271 Vals.push_back(LP.isCleanup());
1272 Vals.push_back(LP.getNumClauses());
1273 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
1275 Vals.push_back(LandingPadInst::Catch);
1277 Vals.push_back(LandingPadInst::Filter);
1278 PushValueAndType(LP.getClause(I), InstID, Vals, VE);
1283 case Instruction::Alloca:
1284 Code = bitc::FUNC_CODE_INST_ALLOCA;
1285 Vals.push_back(VE.getTypeID(I.getType()));
1286 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1287 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
1288 Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1);
1291 case Instruction::Load:
1292 if (cast<LoadInst>(I).isAtomic()) {
1293 Code = bitc::FUNC_CODE_INST_LOADATOMIC;
1294 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1296 Code = bitc::FUNC_CODE_INST_LOAD;
1297 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) // ptr
1298 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
1300 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
1301 Vals.push_back(cast<LoadInst>(I).isVolatile());
1302 if (cast<LoadInst>(I).isAtomic()) {
1303 Vals.push_back(GetEncodedOrdering(cast<LoadInst>(I).getOrdering()));
1304 Vals.push_back(GetEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
1307 case Instruction::Store:
1308 if (cast<StoreInst>(I).isAtomic())
1309 Code = bitc::FUNC_CODE_INST_STOREATOMIC;
1311 Code = bitc::FUNC_CODE_INST_STORE;
1312 PushValueAndType(I.getOperand(1), InstID, Vals, VE); // ptrty + ptr
1313 Vals.push_back(VE.getValueID(I.getOperand(0))); // val.
1314 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
1315 Vals.push_back(cast<StoreInst>(I).isVolatile());
1316 if (cast<StoreInst>(I).isAtomic()) {
1317 Vals.push_back(GetEncodedOrdering(cast<StoreInst>(I).getOrdering()));
1318 Vals.push_back(GetEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
1321 case Instruction::AtomicCmpXchg:
1322 Code = bitc::FUNC_CODE_INST_CMPXCHG;
1323 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr
1324 Vals.push_back(VE.getValueID(I.getOperand(1))); // cmp.
1325 Vals.push_back(VE.getValueID(I.getOperand(2))); // newval.
1326 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
1327 Vals.push_back(GetEncodedOrdering(
1328 cast<AtomicCmpXchgInst>(I).getOrdering()));
1329 Vals.push_back(GetEncodedSynchScope(
1330 cast<AtomicCmpXchgInst>(I).getSynchScope()));
1332 case Instruction::AtomicRMW:
1333 Code = bitc::FUNC_CODE_INST_ATOMICRMW;
1334 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr
1335 Vals.push_back(VE.getValueID(I.getOperand(1))); // val.
1336 Vals.push_back(GetEncodedRMWOperation(
1337 cast<AtomicRMWInst>(I).getOperation()));
1338 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
1339 Vals.push_back(GetEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
1340 Vals.push_back(GetEncodedSynchScope(
1341 cast<AtomicRMWInst>(I).getSynchScope()));
1343 case Instruction::Fence:
1344 Code = bitc::FUNC_CODE_INST_FENCE;
1345 Vals.push_back(GetEncodedOrdering(cast<FenceInst>(I).getOrdering()));
1346 Vals.push_back(GetEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
1348 case Instruction::Call: {
1349 const CallInst &CI = cast<CallInst>(I);
1350 PointerType *PTy = cast<PointerType>(CI.getCalledValue()->getType());
1351 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1353 Code = bitc::FUNC_CODE_INST_CALL;
1355 Vals.push_back(VE.getAttributeID(CI.getAttributes()));
1356 Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall()));
1357 PushValueAndType(CI.getCalledValue(), InstID, Vals, VE); // Callee
1359 // Emit value #'s for the fixed parameters.
1360 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1361 Vals.push_back(VE.getValueID(CI.getArgOperand(i))); // fixed param.
1363 // Emit type/value pairs for varargs params.
1364 if (FTy->isVarArg()) {
1365 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
1367 PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE); // varargs
1371 case Instruction::VAArg:
1372 Code = bitc::FUNC_CODE_INST_VAARG;
1373 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
1374 Vals.push_back(VE.getValueID(I.getOperand(0))); // valist.
1375 Vals.push_back(VE.getTypeID(I.getType())); // restype.
1379 Stream.EmitRecord(Code, Vals, AbbrevToUse);
1383 // Emit names for globals/functions etc.
1384 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
1385 const ValueEnumerator &VE,
1386 BitstreamWriter &Stream) {
1387 if (VST.empty()) return;
1388 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
1390 // FIXME: Set up the abbrev, we know how many values there are!
1391 // FIXME: We know if the type names can use 7-bit ascii.
1392 SmallVector<unsigned, 64> NameVals;
1394 for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
1397 const ValueName &Name = *SI;
1399 // Figure out the encoding to use for the name.
1401 bool isChar6 = true;
1402 for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
1405 isChar6 = BitCodeAbbrevOp::isChar6(*C);
1406 if ((unsigned char)*C & 128) {
1408 break; // don't bother scanning the rest.
1412 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
1414 // VST_ENTRY: [valueid, namechar x N]
1415 // VST_BBENTRY: [bbid, namechar x N]
1417 if (isa<BasicBlock>(SI->getValue())) {
1418 Code = bitc::VST_CODE_BBENTRY;
1420 AbbrevToUse = VST_BBENTRY_6_ABBREV;
1422 Code = bitc::VST_CODE_ENTRY;
1424 AbbrevToUse = VST_ENTRY_6_ABBREV;
1426 AbbrevToUse = VST_ENTRY_7_ABBREV;
1429 NameVals.push_back(VE.getValueID(SI->getValue()));
1430 for (const char *P = Name.getKeyData(),
1431 *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
1432 NameVals.push_back((unsigned char)*P);
1434 // Emit the finished record.
1435 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
1441 /// WriteFunction - Emit a function body to the module stream.
1442 static void WriteFunction(const Function &F, ValueEnumerator &VE,
1443 BitstreamWriter &Stream) {
1444 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
1445 VE.incorporateFunction(F);
1447 SmallVector<unsigned, 64> Vals;
1449 // Emit the number of basic blocks, so the reader can create them ahead of
1451 Vals.push_back(VE.getBasicBlocks().size());
1452 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
1455 // If there are function-local constants, emit them now.
1456 unsigned CstStart, CstEnd;
1457 VE.getFunctionConstantRange(CstStart, CstEnd);
1458 WriteConstants(CstStart, CstEnd, VE, Stream, false);
1460 // If there is function-local metadata, emit it now.
1461 WriteFunctionLocalMetadata(F, VE, Stream);
1463 // Keep a running idea of what the instruction ID is.
1464 unsigned InstID = CstEnd;
1466 bool NeedsMetadataAttachment = false;
1470 // Finally, emit all the instructions, in order.
1471 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1472 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1474 WriteInstruction(*I, InstID, VE, Stream, Vals);
1476 if (!I->getType()->isVoidTy())
1479 // If the instruction has metadata, write a metadata attachment later.
1480 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
1482 // If the instruction has a debug location, emit it.
1483 DebugLoc DL = I->getDebugLoc();
1484 if (DL.isUnknown()) {
1486 } else if (DL == LastDL) {
1487 // Just repeat the same debug loc as last time.
1488 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
1491 DL.getScopeAndInlinedAt(Scope, IA, I->getContext());
1493 Vals.push_back(DL.getLine());
1494 Vals.push_back(DL.getCol());
1495 Vals.push_back(Scope ? VE.getValueID(Scope)+1 : 0);
1496 Vals.push_back(IA ? VE.getValueID(IA)+1 : 0);
1497 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
1504 // Emit names for all the instructions etc.
1505 WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
1507 if (NeedsMetadataAttachment)
1508 WriteMetadataAttachment(F, VE, Stream);
1513 // Emit blockinfo, which defines the standard abbreviations etc.
1514 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
1515 // We only want to emit block info records for blocks that have multiple
1516 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK. Other
1517 // blocks can defined their abbrevs inline.
1518 Stream.EnterBlockInfoBlock(2);
1520 { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
1521 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1522 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
1523 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1524 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1525 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1526 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1527 Abbv) != VST_ENTRY_8_ABBREV)
1528 llvm_unreachable("Unexpected abbrev ordering!");
1531 { // 7-bit fixed width VST_ENTRY strings.
1532 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1533 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1534 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1535 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1536 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1537 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1538 Abbv) != VST_ENTRY_7_ABBREV)
1539 llvm_unreachable("Unexpected abbrev ordering!");
1541 { // 6-bit char6 VST_ENTRY strings.
1542 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1543 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1544 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1545 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1546 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1547 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1548 Abbv) != VST_ENTRY_6_ABBREV)
1549 llvm_unreachable("Unexpected abbrev ordering!");
1551 { // 6-bit char6 VST_BBENTRY strings.
1552 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1553 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
1554 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1555 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1556 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1557 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1558 Abbv) != VST_BBENTRY_6_ABBREV)
1559 llvm_unreachable("Unexpected abbrev ordering!");
1564 { // SETTYPE abbrev for CONSTANTS_BLOCK.
1565 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1566 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
1567 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1568 Log2_32_Ceil(VE.getTypes().size()+1)));
1569 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1570 Abbv) != CONSTANTS_SETTYPE_ABBREV)
1571 llvm_unreachable("Unexpected abbrev ordering!");
1574 { // INTEGER abbrev for CONSTANTS_BLOCK.
1575 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1576 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
1577 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1578 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1579 Abbv) != CONSTANTS_INTEGER_ABBREV)
1580 llvm_unreachable("Unexpected abbrev ordering!");
1583 { // CE_CAST abbrev for CONSTANTS_BLOCK.
1584 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1585 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
1586 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
1587 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
1588 Log2_32_Ceil(VE.getTypes().size()+1)));
1589 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
1591 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1592 Abbv) != CONSTANTS_CE_CAST_Abbrev)
1593 llvm_unreachable("Unexpected abbrev ordering!");
1595 { // NULL abbrev for CONSTANTS_BLOCK.
1596 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1597 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
1598 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1599 Abbv) != CONSTANTS_NULL_Abbrev)
1600 llvm_unreachable("Unexpected abbrev ordering!");
1603 // FIXME: This should only use space for first class types!
1605 { // INST_LOAD abbrev for FUNCTION_BLOCK.
1606 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1607 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
1608 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
1609 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
1610 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
1611 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1612 Abbv) != FUNCTION_INST_LOAD_ABBREV)
1613 llvm_unreachable("Unexpected abbrev ordering!");
1615 { // INST_BINOP abbrev for FUNCTION_BLOCK.
1616 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1617 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1618 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1619 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1620 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1621 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1622 Abbv) != FUNCTION_INST_BINOP_ABBREV)
1623 llvm_unreachable("Unexpected abbrev ordering!");
1625 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
1626 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1627 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1628 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1629 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1630 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1631 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
1632 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1633 Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV)
1634 llvm_unreachable("Unexpected abbrev ordering!");
1636 { // INST_CAST abbrev for FUNCTION_BLOCK.
1637 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1638 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
1639 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
1640 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
1641 Log2_32_Ceil(VE.getTypes().size()+1)));
1642 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1643 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1644 Abbv) != FUNCTION_INST_CAST_ABBREV)
1645 llvm_unreachable("Unexpected abbrev ordering!");
1648 { // INST_RET abbrev for FUNCTION_BLOCK.
1649 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1650 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1651 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1652 Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
1653 llvm_unreachable("Unexpected abbrev ordering!");
1655 { // INST_RET abbrev for FUNCTION_BLOCK.
1656 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1657 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1658 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
1659 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1660 Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
1661 llvm_unreachable("Unexpected abbrev ordering!");
1663 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
1664 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1665 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
1666 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1667 Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
1668 llvm_unreachable("Unexpected abbrev ordering!");
1674 // Sort the Users based on the order in which the reader parses the bitcode
1676 static bool bitcodereader_order(const User *lhs, const User *rhs) {
1681 static void WriteUseList(const Value *V, const ValueEnumerator &VE,
1682 BitstreamWriter &Stream) {
1684 // One or zero uses can't get out of order.
1685 if (V->use_empty() || V->hasNUses(1))
1688 // Make a copy of the in-memory use-list for sorting.
1689 unsigned UseListSize = std::distance(V->use_begin(), V->use_end());
1690 SmallVector<const User*, 8> UseList;
1691 UseList.reserve(UseListSize);
1692 for (Value::const_use_iterator I = V->use_begin(), E = V->use_end();
1695 UseList.push_back(U);
1698 // Sort the copy based on the order read by the BitcodeReader.
1699 std::sort(UseList.begin(), UseList.end(), bitcodereader_order);
1701 // TODO: Generate a diff between the BitcodeWriter in-memory use-list and the
1702 // sorted list (i.e., the expected BitcodeReader in-memory use-list).
1704 // TODO: Emit the USELIST_CODE_ENTRYs.
1707 static void WriteFunctionUseList(const Function *F, ValueEnumerator &VE,
1708 BitstreamWriter &Stream) {
1709 VE.incorporateFunction(*F);
1711 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1713 WriteUseList(AI, VE, Stream);
1714 for (Function::const_iterator BB = F->begin(), FE = F->end(); BB != FE;
1716 WriteUseList(BB, VE, Stream);
1717 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end(); II != IE;
1719 WriteUseList(II, VE, Stream);
1720 for (User::const_op_iterator OI = II->op_begin(), E = II->op_end();
1722 if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
1723 isa<InlineAsm>(*OI))
1724 WriteUseList(*OI, VE, Stream);
1732 static void WriteModuleUseLists(const Module *M, ValueEnumerator &VE,
1733 BitstreamWriter &Stream) {
1734 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
1736 // XXX: this modifies the module, but in a way that should never change the
1737 // behavior of any pass or codegen in LLVM. The problem is that GVs may
1738 // contain entries in the use_list that do not exist in the Module and are
1739 // not stored in the .bc file.
1740 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1742 I->removeDeadConstantUsers();
1744 // Write the global variables.
1745 for (Module::const_global_iterator GI = M->global_begin(),
1746 GE = M->global_end(); GI != GE; ++GI) {
1747 WriteUseList(GI, VE, Stream);
1749 // Write the global variable initializers.
1750 if (GI->hasInitializer())
1751 WriteUseList(GI->getInitializer(), VE, Stream);
1754 // Write the functions.
1755 for (Module::const_iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI) {
1756 WriteUseList(FI, VE, Stream);
1757 if (!FI->isDeclaration())
1758 WriteFunctionUseList(FI, VE, Stream);
1761 // Write the aliases.
1762 for (Module::const_alias_iterator AI = M->alias_begin(), AE = M->alias_end();
1764 WriteUseList(AI, VE, Stream);
1765 WriteUseList(AI->getAliasee(), VE, Stream);
1771 /// WriteModule - Emit the specified module to the bitstream.
1772 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
1773 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
1775 // Emit the version number if it is non-zero.
1777 SmallVector<unsigned, 1> Vals;
1778 Vals.push_back(CurVersion);
1779 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
1782 // Analyze the module, enumerating globals, functions, etc.
1783 ValueEnumerator VE(M);
1785 // Emit blockinfo, which defines the standard abbreviations etc.
1786 WriteBlockInfo(VE, Stream);
1788 // Emit information about parameter attributes.
1789 WriteAttributeTable(VE, Stream);
1791 // Emit information describing all of the types in the module.
1792 WriteTypeTable(VE, Stream);
1794 // Emit top-level description of module, including target triple, inline asm,
1795 // descriptors for global variables, and function prototype info.
1796 WriteModuleInfo(M, VE, Stream);
1799 WriteModuleConstants(VE, Stream);
1802 WriteModuleMetadata(M, VE, Stream);
1805 WriteModuleMetadataStore(M, Stream);
1807 // Emit names for globals/functions etc.
1808 WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
1811 if (EnablePreserveUseListOrdering)
1812 WriteModuleUseLists(M, VE, Stream);
1814 // Emit function bodies.
1815 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F)
1816 if (!F->isDeclaration())
1817 WriteFunction(*F, VE, Stream);
1822 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
1823 /// header and trailer to make it compatible with the system archiver. To do
1824 /// this we emit the following header, and then emit a trailer that pads the
1825 /// file out to be a multiple of 16 bytes.
1827 /// struct bc_header {
1828 /// uint32_t Magic; // 0x0B17C0DE
1829 /// uint32_t Version; // Version, currently always 0.
1830 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
1831 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
1832 /// uint32_t CPUType; // CPU specifier.
1833 /// ... potentially more later ...
1836 DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
1837 DarwinBCHeaderSize = 5*4
1840 static void WriteInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
1841 uint32_t &Position) {
1842 Buffer[Position + 0] = (unsigned char) (Value >> 0);
1843 Buffer[Position + 1] = (unsigned char) (Value >> 8);
1844 Buffer[Position + 2] = (unsigned char) (Value >> 16);
1845 Buffer[Position + 3] = (unsigned char) (Value >> 24);
1849 static void EmitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
1851 unsigned CPUType = ~0U;
1853 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
1854 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
1855 // number from /usr/include/mach/machine.h. It is ok to reproduce the
1856 // specific constants here because they are implicitly part of the Darwin ABI.
1858 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
1859 DARWIN_CPU_TYPE_X86 = 7,
1860 DARWIN_CPU_TYPE_ARM = 12,
1861 DARWIN_CPU_TYPE_POWERPC = 18
1864 Triple::ArchType Arch = TT.getArch();
1865 if (Arch == Triple::x86_64)
1866 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
1867 else if (Arch == Triple::x86)
1868 CPUType = DARWIN_CPU_TYPE_X86;
1869 else if (Arch == Triple::ppc)
1870 CPUType = DARWIN_CPU_TYPE_POWERPC;
1871 else if (Arch == Triple::ppc64)
1872 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
1873 else if (Arch == Triple::arm || Arch == Triple::thumb)
1874 CPUType = DARWIN_CPU_TYPE_ARM;
1876 // Traditional Bitcode starts after header.
1877 assert(Buffer.size() >= DarwinBCHeaderSize &&
1878 "Expected header size to be reserved");
1879 unsigned BCOffset = DarwinBCHeaderSize;
1880 unsigned BCSize = Buffer.size()-DarwinBCHeaderSize;
1882 // Write the magic and version.
1883 unsigned Position = 0;
1884 WriteInt32ToBuffer(0x0B17C0DE , Buffer, Position);
1885 WriteInt32ToBuffer(0 , Buffer, Position); // Version.
1886 WriteInt32ToBuffer(BCOffset , Buffer, Position);
1887 WriteInt32ToBuffer(BCSize , Buffer, Position);
1888 WriteInt32ToBuffer(CPUType , Buffer, Position);
1890 // If the file is not a multiple of 16 bytes, insert dummy padding.
1891 while (Buffer.size() & 15)
1892 Buffer.push_back(0);
1895 /// WriteBitcodeToFile - Write the specified module to the specified output
1897 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out) {
1898 SmallVector<char, 1024> Buffer;
1899 Buffer.reserve(256*1024);
1901 // If this is darwin or another generic macho target, reserve space for the
1903 Triple TT(M->getTargetTriple());
1904 if (TT.isOSDarwin())
1905 Buffer.insert(Buffer.begin(), DarwinBCHeaderSize, 0);
1907 // Emit the module into the buffer.
1909 BitstreamWriter Stream(Buffer);
1911 // Emit the file header.
1912 Stream.Emit((unsigned)'B', 8);
1913 Stream.Emit((unsigned)'C', 8);
1914 Stream.Emit(0x0, 4);
1915 Stream.Emit(0xC, 4);
1916 Stream.Emit(0xE, 4);
1917 Stream.Emit(0xD, 4);
1920 WriteModule(M, Stream);
1923 if (TT.isOSDarwin())
1924 EmitDarwinBCHeaderAndTrailer(Buffer, TT);
1926 // Write the generated bitstream to "Out".
1927 Out.write((char*)&Buffer.front(), Buffer.size());