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