BitcodeWriter.cpp revision d04a8d4b33ff316ca4cf961e06c9e312eff8e64f
1//===--- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ----------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// Bitcode writer implementation. 11// 12//===----------------------------------------------------------------------===// 13 14#include "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" 31#include <cctype> 32#include <map> 33using namespace llvm; 34 35static cl::opt<bool> 36EnablePreserveUseListOrdering("enable-bc-uselist-preserve", 37 cl::desc("Turn on experimental support for " 38 "use-list order preservation."), 39 cl::init(false), cl::Hidden); 40 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. 43enum { 44 // VALUE_SYMTAB_BLOCK abbrev id's. 45 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV, 46 VST_ENTRY_7_ABBREV, 47 VST_ENTRY_6_ABBREV, 48 VST_BBENTRY_6_ABBREV, 49 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, 55 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, 64 65 // SwitchInst Magic 66 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex 67}; 68 69static unsigned GetEncodedCastOpcode(unsigned Opcode) { 70 switch (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; 84 } 85} 86 87static unsigned GetEncodedBinaryOpcode(unsigned Opcode) { 88 switch (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; 108 } 109} 110 111static unsigned GetEncodedRMWOperation(AtomicRMWInst::BinOp Op) { 112 switch (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; 125 } 126} 127 128static unsigned GetEncodedOrdering(AtomicOrdering Ordering) { 129 switch (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; 137 } 138 llvm_unreachable("Invalid ordering"); 139} 140 141static unsigned GetEncodedSynchScope(SynchronizationScope SynchScope) { 142 switch (SynchScope) { 143 case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD; 144 case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD; 145 } 146 llvm_unreachable("Invalid synch scope"); 147} 148 149static void WriteStringRecord(unsigned Code, StringRef Str, 150 unsigned AbbrevToUse, BitstreamWriter &Stream) { 151 SmallVector<unsigned, 64> Vals; 152 153 // Code: [strchar x N] 154 for (unsigned i = 0, e = Str.size(); i != e; ++i) { 155 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i])) 156 AbbrevToUse = 0; 157 Vals.push_back(Str[i]); 158 } 159 160 // Emit the finished record. 161 Stream.EmitRecord(Code, Vals, AbbrevToUse); 162} 163 164// Emit information about parameter attributes. 165static void WriteAttributeTable(const ValueEnumerator &VE, 166 BitstreamWriter &Stream) { 167 const std::vector<AttrListPtr> &Attrs = VE.getAttributes(); 168 if (Attrs.empty()) return; 169 170 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3); 171 172 SmallVector<uint64_t, 64> Record; 173 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) { 174 const AttrListPtr &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)); 179 } 180 181 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record); 182 Record.clear(); 183 } 184 185 Stream.ExitBlock(); 186} 187 188/// WriteTypeTable - Write out the type table for a module. 189static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) { 190 const ValueEnumerator::TypeList &TypeList = VE.getTypes(); 191 192 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */); 193 SmallVector<uint64_t, 64> TypeVals; 194 195 uint64_t NumBits = Log2_32_Ceil(VE.getTypes().size()+1); 196 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); 203 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)); 210 211 unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv); 212 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)); 219 220 unsigned StructAnonAbbrev = Stream.EmitAbbrev(Abbv); 221 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); 228 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)); 235 236 unsigned StructNamedAbbrev = Stream.EmitAbbrev(Abbv); 237 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)); 243 244 unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv); 245 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); 249 TypeVals.clear(); 250 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]; 254 int AbbrevToUse = 0; 255 unsigned Code = 0; 256 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: 270 // INTEGER: [width] 271 Code = bitc::TYPE_CODE_INTEGER; 272 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth()); 273 break; 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; 282 break; 283 } 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; 293 break; 294 } 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)); 303 304 if (ST->isLiteral()) { 305 Code = bitc::TYPE_CODE_STRUCT_ANON; 306 AbbrevToUse = StructAnonAbbrev; 307 } else { 308 if (ST->isOpaque()) { 309 Code = bitc::TYPE_CODE_OPAQUE; 310 } else { 311 Code = bitc::TYPE_CODE_STRUCT_NAMED; 312 AbbrevToUse = StructNamedAbbrev; 313 } 314 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); 319 } 320 break; 321 } 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; 329 break; 330 } 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())); 337 break; 338 } 339 } 340 341 // Emit the finished record. 342 Stream.EmitRecord(Code, TypeVals, AbbrevToUse); 343 TypeVals.clear(); 344 } 345 346 Stream.ExitBlock(); 347} 348 349static 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; 367 } 368 llvm_unreachable("Invalid linkage"); 369} 370 371static 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; 376 } 377 llvm_unreachable("Invalid visibility"); 378} 379 380static 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; 387 } 388 llvm_unreachable("Invalid TLS model"); 389} 390 391// Emit top-level description of module, including target triple, inline asm, 392// descriptors for global variables, and function prototype info. 393static 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(), 398 0/*TODO*/, Stream); 399 if (!M->getDataLayout().empty()) 400 WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(), 401 0/*TODO*/, Stream); 402 if (!M->getModuleInlineAsm().empty()) 403 WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(), 404 0/*TODO*/, Stream); 405 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(); 413 GV != E; ++GV) { 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()]; 419 if (!Entry) { 420 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(), 421 0/*TODO*/, Stream); 422 Entry = SectionMap.size(); 423 } 424 } 425 } 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()]; 431 if (!Entry) { 432 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(), 433 0/*TODO*/, Stream); 434 Entry = SectionMap.size(); 435 } 436 } 437 if (F->hasGC()) { 438 // Same for GC names. 439 unsigned &Entry = GCMap[F->getGC()]; 440 if (!Entry) { 441 WriteStringRecord(bitc::MODULE_CODE_GCNAME, F->getGC(), 442 0/*TODO*/, Stream); 443 Entry = GCMap.size(); 444 } 445 } 446 } 447 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)); 461 else { 462 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1; 463 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 464 Log2_32_Ceil(MaxEncAlignment+1))); 465 } 466 if (SectionMap.empty()) // Section. 467 Abbv->Add(BitCodeAbbrevOp(0)); 468 else 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); 473 } 474 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(); 478 GV != E; ++GV) { 479 unsigned AbbrevToUse = 0; 480 481 // GLOBALVAR: [type, isconst, initid, 482 // linkage, alignment, section, visibility, threadlocal, 483 // unnamed_addr] 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()); 497 } else { 498 AbbrevToUse = SimpleGVarAbbrev; 499 } 500 501 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse); 502 Vals.clear(); 503 } 504 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()); 519 520 unsigned AbbrevToUse = 0; 521 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse); 522 Vals.clear(); 523 } 524 525 // Emit the alias information. 526 for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end(); 527 AI != E; ++AI) { 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); 535 Vals.clear(); 536 } 537} 538 539static uint64_t GetOptimizationFlags(const Value *V) { 540 uint64_t Flags = 0; 541 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)) { 550 if (PEO->isExact()) 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; 564 } 565 566 return Flags; 567} 568 569static 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))); 577 } else { 578 Record.push_back(VE.getTypeID(Type::getVoidTy(N->getContext()))); 579 Record.push_back(0); 580 } 581 } 582 unsigned MDCode = N->isFunctionLocal() ? bitc::METADATA_FN_NODE : 583 bitc::METADATA_NODE; 584 Stream.EmitRecord(MDCode, Record, 0); 585 Record.clear(); 586} 587 588static 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) { 596 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; 602 } 603 WriteMDNode(N, VE, Stream, Record); 604 } 605 } else if (const MDString *MDS = dyn_cast<MDString>(Vals[i].first)) { 606 if (!StartedMetadataBlock) { 607 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3); 608 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; 616 } 617 618 // Code: [strchar x N] 619 Record.append(MDS->begin(), MDS->end()); 620 621 // Emit the finished record. 622 Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev); 623 Record.clear(); 624 } 625 } 626 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; 634 } 635 636 // Write name. 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*/); 641 Record.clear(); 642 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); 647 Record.clear(); 648 } 649 650 if (StartedMetadataBlock) 651 Stream.ExitBlock(); 652} 653 654static 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; 666 } 667 WriteMDNode(N, VE, Stream, Record); 668 } 669 670 if (StartedMetadataBlock) 671 Stream.ExitBlock(); 672} 673 674static void WriteMetadataAttachment(const Function &F, 675 const ValueEnumerator &VE, 676 BitstreamWriter &Stream) { 677 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3); 678 679 SmallVector<uint64_t, 64> Record; 680 681 // Write metadata attachments 682 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]] 683 SmallVector<std::pair<unsigned, MDNode*>, 4> MDs; 684 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(); 687 I != E; ++I) { 688 MDs.clear(); 689 I->getAllMetadataOtherThanDebugLoc(MDs); 690 691 // If no metadata, ignore instruction. 692 if (MDs.empty()) continue; 693 694 Record.push_back(VE.getInstructionID(I)); 695 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)); 699 } 700 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0); 701 Record.clear(); 702 } 703 704 Stream.ExitBlock(); 705} 706 707static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) { 708 SmallVector<uint64_t, 64> Record; 709 710 // Write metadata kinds 711 // METADATA_KIND - [n x [id, name]] 712 SmallVector<StringRef, 4> Names; 713 M->getMDKindNames(Names); 714 715 if (Names.empty()) return; 716 717 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3); 718 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()); 723 724 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0); 725 Record.clear(); 726 } 727 728 Stream.ExitBlock(); 729} 730 731static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) { 732 if ((int64_t)V >= 0) 733 Vals.push_back(V << 1); 734 else 735 Vals.push_back((-V << 1) | 1); 736} 737 738static void EmitAPInt(SmallVectorImpl<uint64_t> &Vals, 739 unsigned &Code, unsigned &AbbrevToUse, const APInt &Val, 740 bool EmitSizeForWideNumbers = false 741 ) { 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; 747 } else { 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(); 754 755 if (EmitSizeForWideNumbers) 756 Vals.push_back(NWords); 757 758 const uint64_t *RawWords = Val.getRawData(); 759 for (unsigned i = 0; i != NWords; ++i) { 760 emitSignedInt64(Vals, RawWords[i]); 761 } 762 Code = bitc::CST_CODE_WIDE_INTEGER; 763 } 764} 765 766static void WriteConstants(unsigned FirstVal, unsigned LastVal, 767 const ValueEnumerator &VE, 768 BitstreamWriter &Stream, bool isGlobal) { 769 if (FirstVal == LastVal) return; 770 771 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4); 772 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. 778 if (isGlobal) { 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); 785 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); 804 } 805 806 SmallVector<uint64_t, 64> Record; 807 808 const ValueEnumerator::ValueList &Vals = VE.getValues(); 809 Type *LastTy = 0; 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); 818 Record.clear(); 819 } 820 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); 825 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]); 831 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); 838 Record.clear(); 839 continue; 840 } 841 const Constant *C = cast<Constant>(V); 842 unsigned Code = -1U; 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]); 867 } else { 868 assert (0 && "Unknown FP type!"); 869 } 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. 879 } else { 880 Code = bitc::CST_CODE_STRING; 881 AbbrevToUse = String8Abbrev; 882 } 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); 887 Record.push_back(V); 888 isCStr7 &= (V & 128) == 0; 889 if (isCStrChar6) 890 isCStrChar6 = BitCodeAbbrevOp::isChar6(V); 891 } 892 893 if (isCStrChar6) 894 AbbrevToUse = CString6Abbrev; 895 else if (isCStr7) 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); 908 Record.push_back(I); 909 } 910 } else { 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); 915 Record.push_back(I); 916 } 917 } 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()) { 926 default: 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; 933 } else { 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); 940 if (Flags != 0) 941 Record.push_back(Flags); 942 } 943 break; 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))); 951 } 952 break; 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))); 958 break; 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))); 964 break; 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))); 970 break; 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; 978 } else { 979 Code = bitc::CST_CODE_CE_SHUFVEC_EX; 980 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 981 } 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))); 985 break; 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()); 993 break; 994 } 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())); 1000 } else { 1001#ifndef NDEBUG 1002 C->dump(); 1003#endif 1004 llvm_unreachable("Unknown constant!"); 1005 } 1006 Stream.EmitRecord(Code, Record, AbbrevToUse); 1007 Record.clear(); 1008 } 1009 1010 Stream.ExitBlock(); 1011} 1012 1013static void WriteModuleConstants(const ValueEnumerator &VE, 1014 BitstreamWriter &Stream) { 1015 const ValueEnumerator::ValueList &Vals = VE.getValues(); 1016 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); 1022 return; 1023 } 1024 } 1025} 1026 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. 1031/// 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. 1035static 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())); 1043 return true; 1044 } 1045 return false; 1046} 1047 1048/// pushValue - Like PushValueAndType, but where the type of the value is 1049/// omitted (perhaps it was already encoded in an earlier operand). 1050static 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); 1055} 1056 1057static 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); 1062} 1063 1064static 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); 1070} 1071 1072/// WriteInstruction - Emit an instruction to the specified stream. 1073static void WriteInstruction(const Instruction &I, unsigned InstID, 1074 ValueEnumerator &VE, BitstreamWriter &Stream, 1075 SmallVector<unsigned, 64> &Vals) { 1076 unsigned Code = 0; 1077 unsigned AbbrevToUse = 0; 1078 VE.setInstructionID(&I); 1079 switch (I.getOpcode()) { 1080 default: 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())); 1087 } else { 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); 1095 if (Flags != 0) { 1096 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV) 1097 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV; 1098 Vals.push_back(Flags); 1099 } 1100 } 1101 break; 1102 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); 1109 break; 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) 1115 Vals.push_back(*i); 1116 break; 1117 } 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) 1124 Vals.push_back(*i); 1125 break; 1126 } 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); 1132 break; 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); 1137 break; 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); 1143 break; 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); 1149 break; 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()); 1157 break; 1158 1159 case Instruction::Ret: 1160 { 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; 1168 } else { 1169 for (unsigned i = 0, e = NumOperands; i != e; ++i) 1170 PushValueAndType(I.getOperand(i), InstID, Vals, VE); 1171 } 1172 } 1173 break; 1174 case Instruction::Br: 1175 { 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); 1182 } 1183 } 1184 break; 1185 case Instruction::Switch: 1186 { 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; 1190 1191 Code = bitc::FUNC_CODE_INST_SWITCH; 1192 SwitchInst &SI = cast<SwitchInst>(I); 1193 1194 uint32_t SwitchRecordHeader = SI.hash() | (SWITCH_INST_MAGIC << 16); 1195 Vals64.push_back(SwitchRecordHeader); 1196 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(); 1202 i != e; ++i) { 1203 IntegersSubset& CaseRanges = i.getCaseValueEx(); 1204 unsigned Code, Abbrev; // will unused. 1205 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); 1210 } else { 1211 1212 Vals64.push_back(CaseRanges.getNumItems()); 1213 1214 if (CaseRanges.isSingleNumbersOnly()) { 1215 for (unsigned ri = 0, rn = CaseRanges.getNumItems(); 1216 ri != rn; ++ri) { 1217 1218 Vals64.push_back(true/*IsSingleNumber = true*/); 1219 1220 EmitAPInt(Vals64, Code, Abbrev, 1221 CaseRanges.getSingleNumber(ri), true); 1222 } 1223 } else 1224 for (unsigned ri = 0, rn = CaseRanges.getNumItems(); 1225 ri != rn; ++ri) { 1226 IntegersSubset::Range r = CaseRanges.getItem(ri); 1227 bool IsSingleNumber = CaseRanges.isSingleNumber(ri); 1228 1229 Vals64.push_back(IsSingleNumber); 1230 1231 EmitAPInt(Vals64, Code, Abbrev, r.getLow(), true); 1232 if (!IsSingleNumber) 1233 EmitAPInt(Vals64, Code, Abbrev, r.getHigh(), true); 1234 } 1235 } 1236 Vals64.push_back(VE.getValueID(i.getCaseSuccessor())); 1237 } 1238 1239 Stream.EmitRecord(Code, Vals64, AbbrevToUse); 1240 1241 // Also do expected action - clear external Vals collection: 1242 Vals.clear(); 1243 return; 1244 } 1245 break; 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))); 1253 break; 1254 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; 1261 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); 1267 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. 1271 1272 // Emit type/value pairs for varargs params. 1273 if (FTy->isVarArg()) { 1274 for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3; 1275 i != e; ++i) 1276 PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg 1277 } 1278 break; 1279 } 1280 case Instruction::Resume: 1281 Code = bitc::FUNC_CODE_INST_RESUME; 1282 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 1283 break; 1284 case Instruction::Unreachable: 1285 Code = bitc::FUNC_CODE_INST_UNREACHABLE; 1286 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV; 1287 break; 1288 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 1294 // signed VBRs. 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))); 1300 } 1301 // Emit a Vals64 vector and exit. 1302 Stream.EmitRecord(Code, Vals64, AbbrevToUse); 1303 Vals64.clear(); 1304 return; 1305 } 1306 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) { 1315 if (LP.isCatch(I)) 1316 Vals.push_back(LandingPadInst::Catch); 1317 else 1318 Vals.push_back(LandingPadInst::Filter); 1319 PushValueAndType(LP.getClause(I), InstID, Vals, VE); 1320 } 1321 break; 1322 } 1323 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); 1330 break; 1331 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); 1336 } else { 1337 Code = bitc::FUNC_CODE_INST_LOAD; 1338 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) // ptr 1339 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV; 1340 } 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())); 1346 } 1347 break; 1348 case Instruction::Store: 1349 if (cast<StoreInst>(I).isAtomic()) 1350 Code = bitc::FUNC_CODE_INST_STOREATOMIC; 1351 else 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())); 1360 } 1361 break; 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())); 1372 break; 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())); 1383 break; 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())); 1388 break; 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()); 1393 1394 Code = bitc::FUNC_CODE_INST_CALL; 1395 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 1399 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))); 1405 else 1406 pushValue(CI.getArgOperand(i), InstID, Vals, VE); // fixed param. 1407 } 1408 1409 // Emit type/value pairs for varargs params. 1410 if (FTy->isVarArg()) { 1411 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands(); 1412 i != e; ++i) 1413 PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE); // varargs 1414 } 1415 break; 1416 } 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. 1422 break; 1423 } 1424 1425 Stream.EmitRecord(Code, Vals, AbbrevToUse); 1426 Vals.clear(); 1427} 1428 1429// Emit names for globals/functions etc. 1430static 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); 1435 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; 1439 1440 for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end(); 1441 SI != SE; ++SI) { 1442 1443 const ValueName &Name = *SI; 1444 1445 // Figure out the encoding to use for the name. 1446 bool is7Bit = true; 1447 bool isChar6 = true; 1448 for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength(); 1449 C != E; ++C) { 1450 if (isChar6) 1451 isChar6 = BitCodeAbbrevOp::isChar6(*C); 1452 if ((unsigned char)*C & 128) { 1453 is7Bit = false; 1454 break; // don't bother scanning the rest. 1455 } 1456 } 1457 1458 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV; 1459 1460 // VST_ENTRY: [valueid, namechar x N] 1461 // VST_BBENTRY: [bbid, namechar x N] 1462 unsigned Code; 1463 if (isa<BasicBlock>(SI->getValue())) { 1464 Code = bitc::VST_CODE_BBENTRY; 1465 if (isChar6) 1466 AbbrevToUse = VST_BBENTRY_6_ABBREV; 1467 } else { 1468 Code = bitc::VST_CODE_ENTRY; 1469 if (isChar6) 1470 AbbrevToUse = VST_ENTRY_6_ABBREV; 1471 else if (is7Bit) 1472 AbbrevToUse = VST_ENTRY_7_ABBREV; 1473 } 1474 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); 1479 1480 // Emit the finished record. 1481 Stream.EmitRecord(Code, NameVals, AbbrevToUse); 1482 NameVals.clear(); 1483 } 1484 Stream.ExitBlock(); 1485} 1486 1487/// WriteFunction - Emit a function body to the module stream. 1488static void WriteFunction(const Function &F, ValueEnumerator &VE, 1489 BitstreamWriter &Stream) { 1490 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4); 1491 VE.incorporateFunction(F); 1492 1493 SmallVector<unsigned, 64> Vals; 1494 1495 // Emit the number of basic blocks, so the reader can create them ahead of 1496 // time. 1497 Vals.push_back(VE.getBasicBlocks().size()); 1498 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals); 1499 Vals.clear(); 1500 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); 1505 1506 // If there is function-local metadata, emit it now. 1507 WriteFunctionLocalMetadata(F, VE, Stream); 1508 1509 // Keep a running idea of what the instruction ID is. 1510 unsigned InstID = CstEnd; 1511 1512 bool NeedsMetadataAttachment = false; 1513 1514 DebugLoc LastDL; 1515 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(); 1519 I != E; ++I) { 1520 WriteInstruction(*I, InstID, VE, Stream, Vals); 1521 1522 if (!I->getType()->isVoidTy()) 1523 ++InstID; 1524 1525 // If the instruction has metadata, write a metadata attachment later. 1526 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc(); 1527 1528 // If the instruction has a debug location, emit it. 1529 DebugLoc DL = I->getDebugLoc(); 1530 if (DL.isUnknown()) { 1531 // nothing todo. 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); 1535 } else { 1536 MDNode *Scope, *IA; 1537 DL.getScopeAndInlinedAt(Scope, IA, I->getContext()); 1538 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); 1544 Vals.clear(); 1545 1546 LastDL = DL; 1547 } 1548 } 1549 1550 // Emit names for all the instructions etc. 1551 WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream); 1552 1553 if (NeedsMetadataAttachment) 1554 WriteMetadataAttachment(F, VE, Stream); 1555 VE.purgeFunction(); 1556 Stream.ExitBlock(); 1557} 1558 1559// Emit blockinfo, which defines the standard abbreviations etc. 1560static 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); 1565 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!"); 1575 } 1576 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!"); 1586 } 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!"); 1596 } 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!"); 1606 } 1607 1608 1609 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!"); 1618 } 1619 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!"); 1627 } 1628 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 1636 1637 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, 1638 Abbv) != CONSTANTS_CE_CAST_Abbrev) 1639 llvm_unreachable("Unexpected abbrev ordering!"); 1640 } 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!"); 1647 } 1648 1649 // FIXME: This should only use space for first class types! 1650 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!"); 1660 } 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!"); 1670 } 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!"); 1681 } 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!"); 1692 } 1693 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!"); 1700 } 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!"); 1708 } 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!"); 1715 } 1716 1717 Stream.ExitBlock(); 1718} 1719 1720// Sort the Users based on the order in which the reader parses the bitcode 1721// file. 1722static bool bitcodereader_order(const User *lhs, const User *rhs) { 1723 // TODO: Implement. 1724 return true; 1725} 1726 1727static void WriteUseList(const Value *V, const ValueEnumerator &VE, 1728 BitstreamWriter &Stream) { 1729 1730 // One or zero uses can't get out of order. 1731 if (V->use_empty() || V->hasNUses(1)) 1732 return; 1733 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(); 1739 I != E; ++I) { 1740 const User *U = *I; 1741 UseList.push_back(U); 1742 } 1743 1744 // Sort the copy based on the order read by the BitcodeReader. 1745 std::sort(UseList.begin(), UseList.end(), bitcodereader_order); 1746 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). 1749 1750 // TODO: Emit the USELIST_CODE_ENTRYs. 1751} 1752 1753static void WriteFunctionUseList(const Function *F, ValueEnumerator &VE, 1754 BitstreamWriter &Stream) { 1755 VE.incorporateFunction(*F); 1756 1757 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end(); 1758 AI != AE; ++AI) 1759 WriteUseList(AI, VE, Stream); 1760 for (Function::const_iterator BB = F->begin(), FE = F->end(); BB != FE; 1761 ++BB) { 1762 WriteUseList(BB, VE, Stream); 1763 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end(); II != IE; 1764 ++II) { 1765 WriteUseList(II, VE, Stream); 1766 for (User::const_op_iterator OI = II->op_begin(), E = II->op_end(); 1767 OI != E; ++OI) { 1768 if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) || 1769 isa<InlineAsm>(*OI)) 1770 WriteUseList(*OI, VE, Stream); 1771 } 1772 } 1773 } 1774 VE.purgeFunction(); 1775} 1776 1777// Emit use-lists. 1778static void WriteModuleUseLists(const Module *M, ValueEnumerator &VE, 1779 BitstreamWriter &Stream) { 1780 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3); 1781 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(); 1787 I != E; ++I) 1788 I->removeDeadConstantUsers(); 1789 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); 1794 1795 // Write the global variable initializers. 1796 if (GI->hasInitializer()) 1797 WriteUseList(GI->getInitializer(), VE, Stream); 1798 } 1799 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); 1805 } 1806 1807 // Write the aliases. 1808 for (Module::const_alias_iterator AI = M->alias_begin(), AE = M->alias_end(); 1809 AI != AE; ++AI) { 1810 WriteUseList(AI, VE, Stream); 1811 WriteUseList(AI->getAliasee(), VE, Stream); 1812 } 1813 1814 Stream.ExitBlock(); 1815} 1816 1817/// WriteModule - Emit the specified module to the bitstream. 1818static void WriteModule(const Module *M, BitstreamWriter &Stream) { 1819 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3); 1820 1821 SmallVector<unsigned, 1> Vals; 1822 unsigned CurVersion = 1; 1823 Vals.push_back(CurVersion); 1824 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals); 1825 1826 // Analyze the module, enumerating globals, functions, etc. 1827 ValueEnumerator VE(M); 1828 1829 // Emit blockinfo, which defines the standard abbreviations etc. 1830 WriteBlockInfo(VE, Stream); 1831 1832 // Emit information about parameter attributes. 1833 WriteAttributeTable(VE, Stream); 1834 1835 // Emit information describing all of the types in the module. 1836 WriteTypeTable(VE, Stream); 1837 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); 1841 1842 // Emit constants. 1843 WriteModuleConstants(VE, Stream); 1844 1845 // Emit metadata. 1846 WriteModuleMetadata(M, VE, Stream); 1847 1848 // Emit metadata. 1849 WriteModuleMetadataStore(M, Stream); 1850 1851 // Emit names for globals/functions etc. 1852 WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream); 1853 1854 // Emit use-lists. 1855 if (EnablePreserveUseListOrdering) 1856 WriteModuleUseLists(M, VE, Stream); 1857 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); 1862 1863 Stream.ExitBlock(); 1864} 1865 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. 1870/// 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 ... 1878/// }; 1879enum { 1880 DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size. 1881 DarwinBCHeaderSize = 5*4 1882}; 1883 1884static 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); 1890 Position += 4; 1891} 1892 1893static void EmitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer, 1894 const Triple &TT) { 1895 unsigned CPUType = ~0U; 1896 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. 1901 enum { 1902 DARWIN_CPU_ARCH_ABI64 = 0x01000000, 1903 DARWIN_CPU_TYPE_X86 = 7, 1904 DARWIN_CPU_TYPE_ARM = 12, 1905 DARWIN_CPU_TYPE_POWERPC = 18 1906 }; 1907 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; 1919 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; 1925 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); 1933 1934 // If the file is not a multiple of 16 bytes, insert dummy padding. 1935 while (Buffer.size() & 15) 1936 Buffer.push_back(0); 1937} 1938 1939/// WriteBitcodeToFile - Write the specified module to the specified output 1940/// stream. 1941void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out) { 1942 SmallVector<char, 1024> Buffer; 1943 Buffer.reserve(256*1024); 1944 1945 // If this is darwin or another generic macho target, reserve space for the 1946 // header. 1947 Triple TT(M->getTargetTriple()); 1948 if (TT.isOSDarwin()) 1949 Buffer.insert(Buffer.begin(), DarwinBCHeaderSize, 0); 1950 1951 // Emit the module into the buffer. 1952 { 1953 BitstreamWriter Stream(Buffer); 1954 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); 1962 1963 // Emit the module. 1964 WriteModule(M, Stream); 1965 } 1966 1967 if (TT.isOSDarwin()) 1968 EmitDarwinBCHeaderAndTrailer(Buffer, TT); 1969 1970 // Write the generated bitstream to "Out". 1971 Out.write((char*)&Buffer.front(), Buffer.size()); 1972} 1973