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 "ValueEnumerator.h" 15 #include "llvm/ADT/StringExtras.h" 16 #include "llvm/ADT/Triple.h" 17 #include "llvm/Bitcode/BitstreamWriter.h" 18 #include "llvm/Bitcode/LLVMBitCodes.h" 19 #include "llvm/Bitcode/ReaderWriter.h" 20 #include "llvm/IR/CallSite.h" 21 #include "llvm/IR/Constants.h" 22 #include "llvm/IR/DebugInfoMetadata.h" 23 #include "llvm/IR/DerivedTypes.h" 24 #include "llvm/IR/InlineAsm.h" 25 #include "llvm/IR/Instructions.h" 26 #include "llvm/IR/LLVMContext.h" 27 #include "llvm/IR/Module.h" 28 #include "llvm/IR/Operator.h" 29 #include "llvm/IR/UseListOrder.h" 30 #include "llvm/IR/ValueSymbolTable.h" 31 #include "llvm/Support/CommandLine.h" 32 #include "llvm/Support/ErrorHandling.h" 33 #include "llvm/Support/MathExtras.h" 34 #include "llvm/Support/Program.h" 35 #include "llvm/Support/raw_ostream.h" 36 #include "llvm/Support/SHA1.h" 37 #include <cctype> 38 #include <map> 39 using namespace llvm; 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 FUNCTION_INST_GEP_ABBREV, 65 }; 66 67 static unsigned GetEncodedCastOpcode(unsigned Opcode) { 68 switch (Opcode) { 69 default: llvm_unreachable("Unknown cast instruction!"); 70 case Instruction::Trunc : return bitc::CAST_TRUNC; 71 case Instruction::ZExt : return bitc::CAST_ZEXT; 72 case Instruction::SExt : return bitc::CAST_SEXT; 73 case Instruction::FPToUI : return bitc::CAST_FPTOUI; 74 case Instruction::FPToSI : return bitc::CAST_FPTOSI; 75 case Instruction::UIToFP : return bitc::CAST_UITOFP; 76 case Instruction::SIToFP : return bitc::CAST_SITOFP; 77 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC; 78 case Instruction::FPExt : return bitc::CAST_FPEXT; 79 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT; 80 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR; 81 case Instruction::BitCast : return bitc::CAST_BITCAST; 82 case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST; 83 } 84 } 85 86 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) { 87 switch (Opcode) { 88 default: llvm_unreachable("Unknown binary instruction!"); 89 case Instruction::Add: 90 case Instruction::FAdd: return bitc::BINOP_ADD; 91 case Instruction::Sub: 92 case Instruction::FSub: return bitc::BINOP_SUB; 93 case Instruction::Mul: 94 case Instruction::FMul: return bitc::BINOP_MUL; 95 case Instruction::UDiv: return bitc::BINOP_UDIV; 96 case Instruction::FDiv: 97 case Instruction::SDiv: return bitc::BINOP_SDIV; 98 case Instruction::URem: return bitc::BINOP_UREM; 99 case Instruction::FRem: 100 case Instruction::SRem: return bitc::BINOP_SREM; 101 case Instruction::Shl: return bitc::BINOP_SHL; 102 case Instruction::LShr: return bitc::BINOP_LSHR; 103 case Instruction::AShr: return bitc::BINOP_ASHR; 104 case Instruction::And: return bitc::BINOP_AND; 105 case Instruction::Or: return bitc::BINOP_OR; 106 case Instruction::Xor: return bitc::BINOP_XOR; 107 } 108 } 109 110 static unsigned GetEncodedRMWOperation(AtomicRMWInst::BinOp Op) { 111 switch (Op) { 112 default: llvm_unreachable("Unknown RMW operation!"); 113 case AtomicRMWInst::Xchg: return bitc::RMW_XCHG; 114 case AtomicRMWInst::Add: return bitc::RMW_ADD; 115 case AtomicRMWInst::Sub: return bitc::RMW_SUB; 116 case AtomicRMWInst::And: return bitc::RMW_AND; 117 case AtomicRMWInst::Nand: return bitc::RMW_NAND; 118 case AtomicRMWInst::Or: return bitc::RMW_OR; 119 case AtomicRMWInst::Xor: return bitc::RMW_XOR; 120 case AtomicRMWInst::Max: return bitc::RMW_MAX; 121 case AtomicRMWInst::Min: return bitc::RMW_MIN; 122 case AtomicRMWInst::UMax: return bitc::RMW_UMAX; 123 case AtomicRMWInst::UMin: return bitc::RMW_UMIN; 124 } 125 } 126 127 static unsigned GetEncodedOrdering(AtomicOrdering Ordering) { 128 switch (Ordering) { 129 case AtomicOrdering::NotAtomic: return bitc::ORDERING_NOTATOMIC; 130 case AtomicOrdering::Unordered: return bitc::ORDERING_UNORDERED; 131 case AtomicOrdering::Monotonic: return bitc::ORDERING_MONOTONIC; 132 case AtomicOrdering::Acquire: return bitc::ORDERING_ACQUIRE; 133 case AtomicOrdering::Release: return bitc::ORDERING_RELEASE; 134 case AtomicOrdering::AcquireRelease: return bitc::ORDERING_ACQREL; 135 case AtomicOrdering::SequentiallyConsistent: return bitc::ORDERING_SEQCST; 136 } 137 llvm_unreachable("Invalid ordering"); 138 } 139 140 static unsigned GetEncodedSynchScope(SynchronizationScope SynchScope) { 141 switch (SynchScope) { 142 case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD; 143 case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD; 144 } 145 llvm_unreachable("Invalid synch scope"); 146 } 147 148 static void WriteStringRecord(unsigned Code, StringRef Str, 149 unsigned AbbrevToUse, BitstreamWriter &Stream) { 150 SmallVector<unsigned, 64> Vals; 151 152 // Code: [strchar x N] 153 for (unsigned i = 0, e = Str.size(); i != e; ++i) { 154 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i])) 155 AbbrevToUse = 0; 156 Vals.push_back(Str[i]); 157 } 158 159 // Emit the finished record. 160 Stream.EmitRecord(Code, Vals, AbbrevToUse); 161 } 162 163 static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) { 164 switch (Kind) { 165 case Attribute::Alignment: 166 return bitc::ATTR_KIND_ALIGNMENT; 167 case Attribute::AlwaysInline: 168 return bitc::ATTR_KIND_ALWAYS_INLINE; 169 case Attribute::ArgMemOnly: 170 return bitc::ATTR_KIND_ARGMEMONLY; 171 case Attribute::Builtin: 172 return bitc::ATTR_KIND_BUILTIN; 173 case Attribute::ByVal: 174 return bitc::ATTR_KIND_BY_VAL; 175 case Attribute::Convergent: 176 return bitc::ATTR_KIND_CONVERGENT; 177 case Attribute::InAlloca: 178 return bitc::ATTR_KIND_IN_ALLOCA; 179 case Attribute::Cold: 180 return bitc::ATTR_KIND_COLD; 181 case Attribute::InaccessibleMemOnly: 182 return bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY; 183 case Attribute::InaccessibleMemOrArgMemOnly: 184 return bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY; 185 case Attribute::InlineHint: 186 return bitc::ATTR_KIND_INLINE_HINT; 187 case Attribute::InReg: 188 return bitc::ATTR_KIND_IN_REG; 189 case Attribute::JumpTable: 190 return bitc::ATTR_KIND_JUMP_TABLE; 191 case Attribute::MinSize: 192 return bitc::ATTR_KIND_MIN_SIZE; 193 case Attribute::Naked: 194 return bitc::ATTR_KIND_NAKED; 195 case Attribute::Nest: 196 return bitc::ATTR_KIND_NEST; 197 case Attribute::NoAlias: 198 return bitc::ATTR_KIND_NO_ALIAS; 199 case Attribute::NoBuiltin: 200 return bitc::ATTR_KIND_NO_BUILTIN; 201 case Attribute::NoCapture: 202 return bitc::ATTR_KIND_NO_CAPTURE; 203 case Attribute::NoDuplicate: 204 return bitc::ATTR_KIND_NO_DUPLICATE; 205 case Attribute::NoImplicitFloat: 206 return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT; 207 case Attribute::NoInline: 208 return bitc::ATTR_KIND_NO_INLINE; 209 case Attribute::NoRecurse: 210 return bitc::ATTR_KIND_NO_RECURSE; 211 case Attribute::NonLazyBind: 212 return bitc::ATTR_KIND_NON_LAZY_BIND; 213 case Attribute::NonNull: 214 return bitc::ATTR_KIND_NON_NULL; 215 case Attribute::Dereferenceable: 216 return bitc::ATTR_KIND_DEREFERENCEABLE; 217 case Attribute::DereferenceableOrNull: 218 return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL; 219 case Attribute::NoRedZone: 220 return bitc::ATTR_KIND_NO_RED_ZONE; 221 case Attribute::NoReturn: 222 return bitc::ATTR_KIND_NO_RETURN; 223 case Attribute::NoUnwind: 224 return bitc::ATTR_KIND_NO_UNWIND; 225 case Attribute::OptimizeForSize: 226 return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE; 227 case Attribute::OptimizeNone: 228 return bitc::ATTR_KIND_OPTIMIZE_NONE; 229 case Attribute::ReadNone: 230 return bitc::ATTR_KIND_READ_NONE; 231 case Attribute::ReadOnly: 232 return bitc::ATTR_KIND_READ_ONLY; 233 case Attribute::Returned: 234 return bitc::ATTR_KIND_RETURNED; 235 case Attribute::ReturnsTwice: 236 return bitc::ATTR_KIND_RETURNS_TWICE; 237 case Attribute::SExt: 238 return bitc::ATTR_KIND_S_EXT; 239 case Attribute::StackAlignment: 240 return bitc::ATTR_KIND_STACK_ALIGNMENT; 241 case Attribute::StackProtect: 242 return bitc::ATTR_KIND_STACK_PROTECT; 243 case Attribute::StackProtectReq: 244 return bitc::ATTR_KIND_STACK_PROTECT_REQ; 245 case Attribute::StackProtectStrong: 246 return bitc::ATTR_KIND_STACK_PROTECT_STRONG; 247 case Attribute::SafeStack: 248 return bitc::ATTR_KIND_SAFESTACK; 249 case Attribute::StructRet: 250 return bitc::ATTR_KIND_STRUCT_RET; 251 case Attribute::SanitizeAddress: 252 return bitc::ATTR_KIND_SANITIZE_ADDRESS; 253 case Attribute::SanitizeThread: 254 return bitc::ATTR_KIND_SANITIZE_THREAD; 255 case Attribute::SanitizeMemory: 256 return bitc::ATTR_KIND_SANITIZE_MEMORY; 257 case Attribute::SwiftError: 258 return bitc::ATTR_KIND_SWIFT_ERROR; 259 case Attribute::SwiftSelf: 260 return bitc::ATTR_KIND_SWIFT_SELF; 261 case Attribute::UWTable: 262 return bitc::ATTR_KIND_UW_TABLE; 263 case Attribute::ZExt: 264 return bitc::ATTR_KIND_Z_EXT; 265 case Attribute::EndAttrKinds: 266 llvm_unreachable("Can not encode end-attribute kinds marker."); 267 case Attribute::None: 268 llvm_unreachable("Can not encode none-attribute."); 269 } 270 271 llvm_unreachable("Trying to encode unknown attribute"); 272 } 273 274 static void WriteAttributeGroupTable(const ValueEnumerator &VE, 275 BitstreamWriter &Stream) { 276 const std::vector<AttributeSet> &AttrGrps = VE.getAttributeGroups(); 277 if (AttrGrps.empty()) return; 278 279 Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3); 280 281 SmallVector<uint64_t, 64> Record; 282 for (unsigned i = 0, e = AttrGrps.size(); i != e; ++i) { 283 AttributeSet AS = AttrGrps[i]; 284 for (unsigned i = 0, e = AS.getNumSlots(); i != e; ++i) { 285 AttributeSet A = AS.getSlotAttributes(i); 286 287 Record.push_back(VE.getAttributeGroupID(A)); 288 Record.push_back(AS.getSlotIndex(i)); 289 290 for (AttributeSet::iterator I = AS.begin(0), E = AS.end(0); 291 I != E; ++I) { 292 Attribute Attr = *I; 293 if (Attr.isEnumAttribute()) { 294 Record.push_back(0); 295 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum())); 296 } else if (Attr.isIntAttribute()) { 297 Record.push_back(1); 298 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum())); 299 Record.push_back(Attr.getValueAsInt()); 300 } else { 301 StringRef Kind = Attr.getKindAsString(); 302 StringRef Val = Attr.getValueAsString(); 303 304 Record.push_back(Val.empty() ? 3 : 4); 305 Record.append(Kind.begin(), Kind.end()); 306 Record.push_back(0); 307 if (!Val.empty()) { 308 Record.append(Val.begin(), Val.end()); 309 Record.push_back(0); 310 } 311 } 312 } 313 314 Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record); 315 Record.clear(); 316 } 317 } 318 319 Stream.ExitBlock(); 320 } 321 322 static void WriteAttributeTable(const ValueEnumerator &VE, 323 BitstreamWriter &Stream) { 324 const std::vector<AttributeSet> &Attrs = VE.getAttributes(); 325 if (Attrs.empty()) return; 326 327 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3); 328 329 SmallVector<uint64_t, 64> Record; 330 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) { 331 const AttributeSet &A = Attrs[i]; 332 for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i) 333 Record.push_back(VE.getAttributeGroupID(A.getSlotAttributes(i))); 334 335 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record); 336 Record.clear(); 337 } 338 339 Stream.ExitBlock(); 340 } 341 342 /// WriteTypeTable - Write out the type table for a module. 343 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) { 344 const ValueEnumerator::TypeList &TypeList = VE.getTypes(); 345 346 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */); 347 SmallVector<uint64_t, 64> TypeVals; 348 349 uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies(); 350 351 // Abbrev for TYPE_CODE_POINTER. 352 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 353 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER)); 354 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 355 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0 356 unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv); 357 358 // Abbrev for TYPE_CODE_FUNCTION. 359 Abbv = new BitCodeAbbrev(); 360 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION)); 361 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg 362 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 363 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 364 365 unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv); 366 367 // Abbrev for TYPE_CODE_STRUCT_ANON. 368 Abbv = new BitCodeAbbrev(); 369 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON)); 370 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked 371 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 372 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 373 374 unsigned StructAnonAbbrev = Stream.EmitAbbrev(Abbv); 375 376 // Abbrev for TYPE_CODE_STRUCT_NAME. 377 Abbv = new BitCodeAbbrev(); 378 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME)); 379 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 380 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 381 unsigned StructNameAbbrev = Stream.EmitAbbrev(Abbv); 382 383 // Abbrev for TYPE_CODE_STRUCT_NAMED. 384 Abbv = new BitCodeAbbrev(); 385 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED)); 386 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked 387 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 388 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 389 390 unsigned StructNamedAbbrev = Stream.EmitAbbrev(Abbv); 391 392 // Abbrev for TYPE_CODE_ARRAY. 393 Abbv = new BitCodeAbbrev(); 394 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY)); 395 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size 396 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 397 398 unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv); 399 400 // Emit an entry count so the reader can reserve space. 401 TypeVals.push_back(TypeList.size()); 402 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals); 403 TypeVals.clear(); 404 405 // Loop over all of the types, emitting each in turn. 406 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) { 407 Type *T = TypeList[i]; 408 int AbbrevToUse = 0; 409 unsigned Code = 0; 410 411 switch (T->getTypeID()) { 412 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break; 413 case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break; 414 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break; 415 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break; 416 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break; 417 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break; 418 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break; 419 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break; 420 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break; 421 case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break; 422 case Type::TokenTyID: Code = bitc::TYPE_CODE_TOKEN; break; 423 case Type::IntegerTyID: 424 // INTEGER: [width] 425 Code = bitc::TYPE_CODE_INTEGER; 426 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth()); 427 break; 428 case Type::PointerTyID: { 429 PointerType *PTy = cast<PointerType>(T); 430 // POINTER: [pointee type, address space] 431 Code = bitc::TYPE_CODE_POINTER; 432 TypeVals.push_back(VE.getTypeID(PTy->getElementType())); 433 unsigned AddressSpace = PTy->getAddressSpace(); 434 TypeVals.push_back(AddressSpace); 435 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev; 436 break; 437 } 438 case Type::FunctionTyID: { 439 FunctionType *FT = cast<FunctionType>(T); 440 // FUNCTION: [isvararg, retty, paramty x N] 441 Code = bitc::TYPE_CODE_FUNCTION; 442 TypeVals.push_back(FT->isVarArg()); 443 TypeVals.push_back(VE.getTypeID(FT->getReturnType())); 444 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) 445 TypeVals.push_back(VE.getTypeID(FT->getParamType(i))); 446 AbbrevToUse = FunctionAbbrev; 447 break; 448 } 449 case Type::StructTyID: { 450 StructType *ST = cast<StructType>(T); 451 // STRUCT: [ispacked, eltty x N] 452 TypeVals.push_back(ST->isPacked()); 453 // Output all of the element types. 454 for (StructType::element_iterator I = ST->element_begin(), 455 E = ST->element_end(); I != E; ++I) 456 TypeVals.push_back(VE.getTypeID(*I)); 457 458 if (ST->isLiteral()) { 459 Code = bitc::TYPE_CODE_STRUCT_ANON; 460 AbbrevToUse = StructAnonAbbrev; 461 } else { 462 if (ST->isOpaque()) { 463 Code = bitc::TYPE_CODE_OPAQUE; 464 } else { 465 Code = bitc::TYPE_CODE_STRUCT_NAMED; 466 AbbrevToUse = StructNamedAbbrev; 467 } 468 469 // Emit the name if it is present. 470 if (!ST->getName().empty()) 471 WriteStringRecord(bitc::TYPE_CODE_STRUCT_NAME, ST->getName(), 472 StructNameAbbrev, Stream); 473 } 474 break; 475 } 476 case Type::ArrayTyID: { 477 ArrayType *AT = cast<ArrayType>(T); 478 // ARRAY: [numelts, eltty] 479 Code = bitc::TYPE_CODE_ARRAY; 480 TypeVals.push_back(AT->getNumElements()); 481 TypeVals.push_back(VE.getTypeID(AT->getElementType())); 482 AbbrevToUse = ArrayAbbrev; 483 break; 484 } 485 case Type::VectorTyID: { 486 VectorType *VT = cast<VectorType>(T); 487 // VECTOR [numelts, eltty] 488 Code = bitc::TYPE_CODE_VECTOR; 489 TypeVals.push_back(VT->getNumElements()); 490 TypeVals.push_back(VE.getTypeID(VT->getElementType())); 491 break; 492 } 493 } 494 495 // Emit the finished record. 496 Stream.EmitRecord(Code, TypeVals, AbbrevToUse); 497 TypeVals.clear(); 498 } 499 500 Stream.ExitBlock(); 501 } 502 503 static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) { 504 switch (Linkage) { 505 case GlobalValue::ExternalLinkage: 506 return 0; 507 case GlobalValue::WeakAnyLinkage: 508 return 16; 509 case GlobalValue::AppendingLinkage: 510 return 2; 511 case GlobalValue::InternalLinkage: 512 return 3; 513 case GlobalValue::LinkOnceAnyLinkage: 514 return 18; 515 case GlobalValue::ExternalWeakLinkage: 516 return 7; 517 case GlobalValue::CommonLinkage: 518 return 8; 519 case GlobalValue::PrivateLinkage: 520 return 9; 521 case GlobalValue::WeakODRLinkage: 522 return 17; 523 case GlobalValue::LinkOnceODRLinkage: 524 return 19; 525 case GlobalValue::AvailableExternallyLinkage: 526 return 12; 527 } 528 llvm_unreachable("Invalid linkage"); 529 } 530 531 static unsigned getEncodedLinkage(const GlobalValue &GV) { 532 return getEncodedLinkage(GV.getLinkage()); 533 } 534 535 static unsigned getEncodedVisibility(const GlobalValue &GV) { 536 switch (GV.getVisibility()) { 537 case GlobalValue::DefaultVisibility: return 0; 538 case GlobalValue::HiddenVisibility: return 1; 539 case GlobalValue::ProtectedVisibility: return 2; 540 } 541 llvm_unreachable("Invalid visibility"); 542 } 543 544 static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) { 545 switch (GV.getDLLStorageClass()) { 546 case GlobalValue::DefaultStorageClass: return 0; 547 case GlobalValue::DLLImportStorageClass: return 1; 548 case GlobalValue::DLLExportStorageClass: return 2; 549 } 550 llvm_unreachable("Invalid DLL storage class"); 551 } 552 553 static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) { 554 switch (GV.getThreadLocalMode()) { 555 case GlobalVariable::NotThreadLocal: return 0; 556 case GlobalVariable::GeneralDynamicTLSModel: return 1; 557 case GlobalVariable::LocalDynamicTLSModel: return 2; 558 case GlobalVariable::InitialExecTLSModel: return 3; 559 case GlobalVariable::LocalExecTLSModel: return 4; 560 } 561 llvm_unreachable("Invalid TLS model"); 562 } 563 564 static unsigned getEncodedComdatSelectionKind(const Comdat &C) { 565 switch (C.getSelectionKind()) { 566 case Comdat::Any: 567 return bitc::COMDAT_SELECTION_KIND_ANY; 568 case Comdat::ExactMatch: 569 return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH; 570 case Comdat::Largest: 571 return bitc::COMDAT_SELECTION_KIND_LARGEST; 572 case Comdat::NoDuplicates: 573 return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES; 574 case Comdat::SameSize: 575 return bitc::COMDAT_SELECTION_KIND_SAME_SIZE; 576 } 577 llvm_unreachable("Invalid selection kind"); 578 } 579 580 static void writeComdats(const ValueEnumerator &VE, BitstreamWriter &Stream) { 581 SmallVector<unsigned, 64> Vals; 582 for (const Comdat *C : VE.getComdats()) { 583 // COMDAT: [selection_kind, name] 584 Vals.push_back(getEncodedComdatSelectionKind(*C)); 585 size_t Size = C->getName().size(); 586 assert(isUInt<32>(Size)); 587 Vals.push_back(Size); 588 for (char Chr : C->getName()) 589 Vals.push_back((unsigned char)Chr); 590 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0); 591 Vals.clear(); 592 } 593 } 594 595 /// Write a record that will eventually hold the word offset of the 596 /// module-level VST. For now the offset is 0, which will be backpatched 597 /// after the real VST is written. Returns the bit offset to backpatch. 598 static uint64_t WriteValueSymbolTableForwardDecl(BitstreamWriter &Stream) { 599 // Write a placeholder value in for the offset of the real VST, 600 // which is written after the function blocks so that it can include 601 // the offset of each function. The placeholder offset will be 602 // updated when the real VST is written. 603 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 604 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET)); 605 // Blocks are 32-bit aligned, so we can use a 32-bit word offset to 606 // hold the real VST offset. Must use fixed instead of VBR as we don't 607 // know how many VBR chunks to reserve ahead of time. 608 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 609 unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(Abbv); 610 611 // Emit the placeholder 612 uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0}; 613 Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals); 614 615 // Compute and return the bit offset to the placeholder, which will be 616 // patched when the real VST is written. We can simply subtract the 32-bit 617 // fixed size from the current bit number to get the location to backpatch. 618 return Stream.GetCurrentBitNo() - 32; 619 } 620 621 enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 }; 622 623 /// Determine the encoding to use for the given string name and length. 624 static StringEncoding getStringEncoding(const char *Str, unsigned StrLen) { 625 bool isChar6 = true; 626 for (const char *C = Str, *E = C + StrLen; C != E; ++C) { 627 if (isChar6) 628 isChar6 = BitCodeAbbrevOp::isChar6(*C); 629 if ((unsigned char)*C & 128) 630 // don't bother scanning the rest. 631 return SE_Fixed8; 632 } 633 if (isChar6) 634 return SE_Char6; 635 else 636 return SE_Fixed7; 637 } 638 639 /// Emit top-level description of module, including target triple, inline asm, 640 /// descriptors for global variables, and function prototype info. 641 /// Returns the bit offset to backpatch with the location of the real VST. 642 static uint64_t WriteModuleInfo(const Module *M, const ValueEnumerator &VE, 643 BitstreamWriter &Stream) { 644 // Emit various pieces of data attached to a module. 645 if (!M->getTargetTriple().empty()) 646 WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(), 647 0/*TODO*/, Stream); 648 const std::string &DL = M->getDataLayoutStr(); 649 if (!DL.empty()) 650 WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/, Stream); 651 if (!M->getModuleInlineAsm().empty()) 652 WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(), 653 0/*TODO*/, Stream); 654 655 // Emit information about sections and GC, computing how many there are. Also 656 // compute the maximum alignment value. 657 std::map<std::string, unsigned> SectionMap; 658 std::map<std::string, unsigned> GCMap; 659 unsigned MaxAlignment = 0; 660 unsigned MaxGlobalType = 0; 661 for (const GlobalValue &GV : M->globals()) { 662 MaxAlignment = std::max(MaxAlignment, GV.getAlignment()); 663 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType())); 664 if (GV.hasSection()) { 665 // Give section names unique ID's. 666 unsigned &Entry = SectionMap[GV.getSection()]; 667 if (!Entry) { 668 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV.getSection(), 669 0/*TODO*/, Stream); 670 Entry = SectionMap.size(); 671 } 672 } 673 } 674 for (const Function &F : *M) { 675 MaxAlignment = std::max(MaxAlignment, F.getAlignment()); 676 if (F.hasSection()) { 677 // Give section names unique ID's. 678 unsigned &Entry = SectionMap[F.getSection()]; 679 if (!Entry) { 680 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F.getSection(), 681 0/*TODO*/, Stream); 682 Entry = SectionMap.size(); 683 } 684 } 685 if (F.hasGC()) { 686 // Same for GC names. 687 unsigned &Entry = GCMap[F.getGC()]; 688 if (!Entry) { 689 WriteStringRecord(bitc::MODULE_CODE_GCNAME, F.getGC(), 690 0/*TODO*/, Stream); 691 Entry = GCMap.size(); 692 } 693 } 694 } 695 696 // Emit abbrev for globals, now that we know # sections and max alignment. 697 unsigned SimpleGVarAbbrev = 0; 698 if (!M->global_empty()) { 699 // Add an abbrev for common globals with no visibility or thread localness. 700 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 701 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR)); 702 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 703 Log2_32_Ceil(MaxGlobalType+1))); 704 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2 705 //| explicitType << 1 706 //| constant 707 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer. 708 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage. 709 if (MaxAlignment == 0) // Alignment. 710 Abbv->Add(BitCodeAbbrevOp(0)); 711 else { 712 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1; 713 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 714 Log2_32_Ceil(MaxEncAlignment+1))); 715 } 716 if (SectionMap.empty()) // Section. 717 Abbv->Add(BitCodeAbbrevOp(0)); 718 else 719 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 720 Log2_32_Ceil(SectionMap.size()+1))); 721 // Don't bother emitting vis + thread local. 722 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv); 723 } 724 725 // Emit the global variable information. 726 SmallVector<unsigned, 64> Vals; 727 for (const GlobalVariable &GV : M->globals()) { 728 unsigned AbbrevToUse = 0; 729 730 // GLOBALVAR: [type, isconst, initid, 731 // linkage, alignment, section, visibility, threadlocal, 732 // unnamed_addr, externally_initialized, dllstorageclass, 733 // comdat] 734 Vals.push_back(VE.getTypeID(GV.getValueType())); 735 Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant()); 736 Vals.push_back(GV.isDeclaration() ? 0 : 737 (VE.getValueID(GV.getInitializer()) + 1)); 738 Vals.push_back(getEncodedLinkage(GV)); 739 Vals.push_back(Log2_32(GV.getAlignment())+1); 740 Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0); 741 if (GV.isThreadLocal() || 742 GV.getVisibility() != GlobalValue::DefaultVisibility || 743 GV.hasUnnamedAddr() || GV.isExternallyInitialized() || 744 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass || 745 GV.hasComdat()) { 746 Vals.push_back(getEncodedVisibility(GV)); 747 Vals.push_back(getEncodedThreadLocalMode(GV)); 748 Vals.push_back(GV.hasUnnamedAddr()); 749 Vals.push_back(GV.isExternallyInitialized()); 750 Vals.push_back(getEncodedDLLStorageClass(GV)); 751 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0); 752 } else { 753 AbbrevToUse = SimpleGVarAbbrev; 754 } 755 756 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse); 757 Vals.clear(); 758 } 759 760 // Emit the function proto information. 761 for (const Function &F : *M) { 762 // FUNCTION: [type, callingconv, isproto, linkage, paramattrs, alignment, 763 // section, visibility, gc, unnamed_addr, prologuedata, 764 // dllstorageclass, comdat, prefixdata, personalityfn] 765 Vals.push_back(VE.getTypeID(F.getFunctionType())); 766 Vals.push_back(F.getCallingConv()); 767 Vals.push_back(F.isDeclaration()); 768 Vals.push_back(getEncodedLinkage(F)); 769 Vals.push_back(VE.getAttributeID(F.getAttributes())); 770 Vals.push_back(Log2_32(F.getAlignment())+1); 771 Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0); 772 Vals.push_back(getEncodedVisibility(F)); 773 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0); 774 Vals.push_back(F.hasUnnamedAddr()); 775 Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1) 776 : 0); 777 Vals.push_back(getEncodedDLLStorageClass(F)); 778 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0); 779 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1) 780 : 0); 781 Vals.push_back( 782 F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0); 783 784 unsigned AbbrevToUse = 0; 785 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse); 786 Vals.clear(); 787 } 788 789 // Emit the alias information. 790 for (const GlobalAlias &A : M->aliases()) { 791 // ALIAS: [alias type, aliasee val#, linkage, visibility] 792 Vals.push_back(VE.getTypeID(A.getValueType())); 793 Vals.push_back(A.getType()->getAddressSpace()); 794 Vals.push_back(VE.getValueID(A.getAliasee())); 795 Vals.push_back(getEncodedLinkage(A)); 796 Vals.push_back(getEncodedVisibility(A)); 797 Vals.push_back(getEncodedDLLStorageClass(A)); 798 Vals.push_back(getEncodedThreadLocalMode(A)); 799 Vals.push_back(A.hasUnnamedAddr()); 800 unsigned AbbrevToUse = 0; 801 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse); 802 Vals.clear(); 803 } 804 805 // Emit the ifunc information. 806 for (const GlobalIFunc &I : M->ifuncs()) { 807 // IFUNC: [ifunc type, address space, resolver val#, linkage, visibility] 808 Vals.push_back(VE.getTypeID(I.getValueType())); 809 Vals.push_back(I.getType()->getAddressSpace()); 810 Vals.push_back(VE.getValueID(I.getResolver())); 811 Vals.push_back(getEncodedLinkage(I)); 812 Vals.push_back(getEncodedVisibility(I)); 813 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals); 814 Vals.clear(); 815 } 816 817 // Emit the module's source file name. 818 { 819 StringEncoding Bits = getStringEncoding(M->getSourceFileName().data(), 820 M->getSourceFileName().size()); 821 BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8); 822 if (Bits == SE_Char6) 823 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6); 824 else if (Bits == SE_Fixed7) 825 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7); 826 827 // MODULE_CODE_SOURCE_FILENAME: [namechar x N] 828 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 829 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME)); 830 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 831 Abbv->Add(AbbrevOpToUse); 832 unsigned FilenameAbbrev = Stream.EmitAbbrev(Abbv); 833 834 for (const auto P : M->getSourceFileName()) 835 Vals.push_back((unsigned char)P); 836 837 // Emit the finished record. 838 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev); 839 Vals.clear(); 840 } 841 842 // If we have a VST, write the VSTOFFSET record placeholder and return 843 // its offset. 844 if (M->getValueSymbolTable().empty()) 845 return 0; 846 return WriteValueSymbolTableForwardDecl(Stream); 847 } 848 849 static uint64_t GetOptimizationFlags(const Value *V) { 850 uint64_t Flags = 0; 851 852 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) { 853 if (OBO->hasNoSignedWrap()) 854 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP; 855 if (OBO->hasNoUnsignedWrap()) 856 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP; 857 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) { 858 if (PEO->isExact()) 859 Flags |= 1 << bitc::PEO_EXACT; 860 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) { 861 if (FPMO->hasUnsafeAlgebra()) 862 Flags |= FastMathFlags::UnsafeAlgebra; 863 if (FPMO->hasNoNaNs()) 864 Flags |= FastMathFlags::NoNaNs; 865 if (FPMO->hasNoInfs()) 866 Flags |= FastMathFlags::NoInfs; 867 if (FPMO->hasNoSignedZeros()) 868 Flags |= FastMathFlags::NoSignedZeros; 869 if (FPMO->hasAllowReciprocal()) 870 Flags |= FastMathFlags::AllowReciprocal; 871 } 872 873 return Flags; 874 } 875 876 static void writeValueAsMetadata(const ValueAsMetadata *MD, 877 const ValueEnumerator &VE, 878 BitstreamWriter &Stream, 879 SmallVectorImpl<uint64_t> &Record) { 880 // Mimic an MDNode with a value as one operand. 881 Value *V = MD->getValue(); 882 Record.push_back(VE.getTypeID(V->getType())); 883 Record.push_back(VE.getValueID(V)); 884 Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0); 885 Record.clear(); 886 } 887 888 static void writeMDTuple(const MDTuple *N, const ValueEnumerator &VE, 889 BitstreamWriter &Stream, 890 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) { 891 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 892 Metadata *MD = N->getOperand(i); 893 assert(!(MD && isa<LocalAsMetadata>(MD)) && 894 "Unexpected function-local metadata"); 895 Record.push_back(VE.getMetadataOrNullID(MD)); 896 } 897 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE 898 : bitc::METADATA_NODE, 899 Record, Abbrev); 900 Record.clear(); 901 } 902 903 static unsigned createDILocationAbbrev(BitstreamWriter &Stream) { 904 // Assume the column is usually under 128, and always output the inlined-at 905 // location (it's never more expensive than building an array size 1). 906 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 907 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION)); 908 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); 909 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 910 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 911 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 912 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 913 return Stream.EmitAbbrev(Abbv); 914 } 915 916 static void writeDILocation(const DILocation *N, const ValueEnumerator &VE, 917 BitstreamWriter &Stream, 918 SmallVectorImpl<uint64_t> &Record, 919 unsigned &Abbrev) { 920 if (!Abbrev) 921 Abbrev = createDILocationAbbrev(Stream); 922 923 Record.push_back(N->isDistinct()); 924 Record.push_back(N->getLine()); 925 Record.push_back(N->getColumn()); 926 Record.push_back(VE.getMetadataID(N->getScope())); 927 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt())); 928 929 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev); 930 Record.clear(); 931 } 932 933 static unsigned createGenericDINodeAbbrev(BitstreamWriter &Stream) { 934 // Assume the column is usually under 128, and always output the inlined-at 935 // location (it's never more expensive than building an array size 1). 936 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 937 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG)); 938 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); 939 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 940 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); 941 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 942 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 943 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 944 return Stream.EmitAbbrev(Abbv); 945 } 946 947 static void writeGenericDINode(const GenericDINode *N, 948 const ValueEnumerator &VE, 949 BitstreamWriter &Stream, 950 SmallVectorImpl<uint64_t> &Record, 951 unsigned &Abbrev) { 952 if (!Abbrev) 953 Abbrev = createGenericDINodeAbbrev(Stream); 954 955 Record.push_back(N->isDistinct()); 956 Record.push_back(N->getTag()); 957 Record.push_back(0); // Per-tag version field; unused for now. 958 959 for (auto &I : N->operands()) 960 Record.push_back(VE.getMetadataOrNullID(I)); 961 962 Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev); 963 Record.clear(); 964 } 965 966 static uint64_t rotateSign(int64_t I) { 967 uint64_t U = I; 968 return I < 0 ? ~(U << 1) : U << 1; 969 } 970 971 static void writeDISubrange(const DISubrange *N, const ValueEnumerator &, 972 BitstreamWriter &Stream, 973 SmallVectorImpl<uint64_t> &Record, 974 unsigned Abbrev) { 975 Record.push_back(N->isDistinct()); 976 Record.push_back(N->getCount()); 977 Record.push_back(rotateSign(N->getLowerBound())); 978 979 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev); 980 Record.clear(); 981 } 982 983 static void writeDIEnumerator(const DIEnumerator *N, const ValueEnumerator &VE, 984 BitstreamWriter &Stream, 985 SmallVectorImpl<uint64_t> &Record, 986 unsigned Abbrev) { 987 Record.push_back(N->isDistinct()); 988 Record.push_back(rotateSign(N->getValue())); 989 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 990 991 Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev); 992 Record.clear(); 993 } 994 995 static void writeDIBasicType(const DIBasicType *N, const ValueEnumerator &VE, 996 BitstreamWriter &Stream, 997 SmallVectorImpl<uint64_t> &Record, 998 unsigned Abbrev) { 999 Record.push_back(N->isDistinct()); 1000 Record.push_back(N->getTag()); 1001 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1002 Record.push_back(N->getSizeInBits()); 1003 Record.push_back(N->getAlignInBits()); 1004 Record.push_back(N->getEncoding()); 1005 1006 Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev); 1007 Record.clear(); 1008 } 1009 1010 static void writeDIDerivedType(const DIDerivedType *N, 1011 const ValueEnumerator &VE, 1012 BitstreamWriter &Stream, 1013 SmallVectorImpl<uint64_t> &Record, 1014 unsigned Abbrev) { 1015 Record.push_back(N->isDistinct()); 1016 Record.push_back(N->getTag()); 1017 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1018 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1019 Record.push_back(N->getLine()); 1020 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1021 Record.push_back(VE.getMetadataOrNullID(N->getBaseType())); 1022 Record.push_back(N->getSizeInBits()); 1023 Record.push_back(N->getAlignInBits()); 1024 Record.push_back(N->getOffsetInBits()); 1025 Record.push_back(N->getFlags()); 1026 Record.push_back(VE.getMetadataOrNullID(N->getExtraData())); 1027 1028 Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev); 1029 Record.clear(); 1030 } 1031 1032 static void writeDICompositeType(const DICompositeType *N, 1033 const ValueEnumerator &VE, 1034 BitstreamWriter &Stream, 1035 SmallVectorImpl<uint64_t> &Record, 1036 unsigned Abbrev) { 1037 Record.push_back(N->isDistinct()); 1038 Record.push_back(N->getTag()); 1039 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1040 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1041 Record.push_back(N->getLine()); 1042 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1043 Record.push_back(VE.getMetadataOrNullID(N->getBaseType())); 1044 Record.push_back(N->getSizeInBits()); 1045 Record.push_back(N->getAlignInBits()); 1046 Record.push_back(N->getOffsetInBits()); 1047 Record.push_back(N->getFlags()); 1048 Record.push_back(VE.getMetadataOrNullID(N->getElements().get())); 1049 Record.push_back(N->getRuntimeLang()); 1050 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder())); 1051 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get())); 1052 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier())); 1053 1054 Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev); 1055 Record.clear(); 1056 } 1057 1058 static void writeDISubroutineType(const DISubroutineType *N, 1059 const ValueEnumerator &VE, 1060 BitstreamWriter &Stream, 1061 SmallVectorImpl<uint64_t> &Record, 1062 unsigned Abbrev) { 1063 Record.push_back(N->isDistinct()); 1064 Record.push_back(N->getFlags()); 1065 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get())); 1066 1067 Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev); 1068 Record.clear(); 1069 } 1070 1071 static void writeDIFile(const DIFile *N, const ValueEnumerator &VE, 1072 BitstreamWriter &Stream, 1073 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) { 1074 Record.push_back(N->isDistinct()); 1075 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename())); 1076 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory())); 1077 1078 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev); 1079 Record.clear(); 1080 } 1081 1082 static void writeDICompileUnit(const DICompileUnit *N, 1083 const ValueEnumerator &VE, 1084 BitstreamWriter &Stream, 1085 SmallVectorImpl<uint64_t> &Record, 1086 unsigned Abbrev) { 1087 assert(N->isDistinct() && "Expected distinct compile units"); 1088 Record.push_back(/* IsDistinct */ true); 1089 Record.push_back(N->getSourceLanguage()); 1090 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1091 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer())); 1092 Record.push_back(N->isOptimized()); 1093 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags())); 1094 Record.push_back(N->getRuntimeVersion()); 1095 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename())); 1096 Record.push_back(N->getEmissionKind()); 1097 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get())); 1098 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get())); 1099 Record.push_back(VE.getMetadataOrNullID(N->getSubprograms().get())); 1100 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get())); 1101 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get())); 1102 Record.push_back(N->getDWOId()); 1103 Record.push_back(VE.getMetadataOrNullID(N->getMacros().get())); 1104 1105 Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev); 1106 Record.clear(); 1107 } 1108 1109 static void writeDISubprogram(const DISubprogram *N, const ValueEnumerator &VE, 1110 BitstreamWriter &Stream, 1111 SmallVectorImpl<uint64_t> &Record, 1112 unsigned Abbrev) { 1113 Record.push_back(N->isDistinct()); 1114 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1115 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1116 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName())); 1117 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1118 Record.push_back(N->getLine()); 1119 Record.push_back(VE.getMetadataOrNullID(N->getType())); 1120 Record.push_back(N->isLocalToUnit()); 1121 Record.push_back(N->isDefinition()); 1122 Record.push_back(N->getScopeLine()); 1123 Record.push_back(VE.getMetadataOrNullID(N->getContainingType())); 1124 Record.push_back(N->getVirtuality()); 1125 Record.push_back(N->getVirtualIndex()); 1126 Record.push_back(N->getFlags()); 1127 Record.push_back(N->isOptimized()); 1128 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get())); 1129 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration())); 1130 Record.push_back(VE.getMetadataOrNullID(N->getVariables().get())); 1131 1132 Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev); 1133 Record.clear(); 1134 } 1135 1136 static void writeDILexicalBlock(const DILexicalBlock *N, 1137 const ValueEnumerator &VE, 1138 BitstreamWriter &Stream, 1139 SmallVectorImpl<uint64_t> &Record, 1140 unsigned Abbrev) { 1141 Record.push_back(N->isDistinct()); 1142 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1143 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1144 Record.push_back(N->getLine()); 1145 Record.push_back(N->getColumn()); 1146 1147 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev); 1148 Record.clear(); 1149 } 1150 1151 static void writeDILexicalBlockFile(const DILexicalBlockFile *N, 1152 const ValueEnumerator &VE, 1153 BitstreamWriter &Stream, 1154 SmallVectorImpl<uint64_t> &Record, 1155 unsigned Abbrev) { 1156 Record.push_back(N->isDistinct()); 1157 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1158 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1159 Record.push_back(N->getDiscriminator()); 1160 1161 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev); 1162 Record.clear(); 1163 } 1164 1165 static void writeDINamespace(const DINamespace *N, const ValueEnumerator &VE, 1166 BitstreamWriter &Stream, 1167 SmallVectorImpl<uint64_t> &Record, 1168 unsigned Abbrev) { 1169 Record.push_back(N->isDistinct()); 1170 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1171 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1172 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1173 Record.push_back(N->getLine()); 1174 1175 Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev); 1176 Record.clear(); 1177 } 1178 1179 static void writeDIMacro(const DIMacro *N, const ValueEnumerator &VE, 1180 BitstreamWriter &Stream, 1181 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) { 1182 Record.push_back(N->isDistinct()); 1183 Record.push_back(N->getMacinfoType()); 1184 Record.push_back(N->getLine()); 1185 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1186 Record.push_back(VE.getMetadataOrNullID(N->getRawValue())); 1187 1188 Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev); 1189 Record.clear(); 1190 } 1191 1192 static void writeDIMacroFile(const DIMacroFile *N, const ValueEnumerator &VE, 1193 BitstreamWriter &Stream, 1194 SmallVectorImpl<uint64_t> &Record, 1195 unsigned Abbrev) { 1196 Record.push_back(N->isDistinct()); 1197 Record.push_back(N->getMacinfoType()); 1198 Record.push_back(N->getLine()); 1199 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1200 Record.push_back(VE.getMetadataOrNullID(N->getElements().get())); 1201 1202 Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev); 1203 Record.clear(); 1204 } 1205 1206 static void writeDIModule(const DIModule *N, const ValueEnumerator &VE, 1207 BitstreamWriter &Stream, 1208 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) { 1209 Record.push_back(N->isDistinct()); 1210 for (auto &I : N->operands()) 1211 Record.push_back(VE.getMetadataOrNullID(I)); 1212 1213 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev); 1214 Record.clear(); 1215 } 1216 1217 static void writeDITemplateTypeParameter(const DITemplateTypeParameter *N, 1218 const ValueEnumerator &VE, 1219 BitstreamWriter &Stream, 1220 SmallVectorImpl<uint64_t> &Record, 1221 unsigned Abbrev) { 1222 Record.push_back(N->isDistinct()); 1223 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1224 Record.push_back(VE.getMetadataOrNullID(N->getType())); 1225 1226 Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev); 1227 Record.clear(); 1228 } 1229 1230 static void writeDITemplateValueParameter(const DITemplateValueParameter *N, 1231 const ValueEnumerator &VE, 1232 BitstreamWriter &Stream, 1233 SmallVectorImpl<uint64_t> &Record, 1234 unsigned Abbrev) { 1235 Record.push_back(N->isDistinct()); 1236 Record.push_back(N->getTag()); 1237 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1238 Record.push_back(VE.getMetadataOrNullID(N->getType())); 1239 Record.push_back(VE.getMetadataOrNullID(N->getValue())); 1240 1241 Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev); 1242 Record.clear(); 1243 } 1244 1245 static void writeDIGlobalVariable(const DIGlobalVariable *N, 1246 const ValueEnumerator &VE, 1247 BitstreamWriter &Stream, 1248 SmallVectorImpl<uint64_t> &Record, 1249 unsigned Abbrev) { 1250 Record.push_back(N->isDistinct()); 1251 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1252 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1253 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName())); 1254 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1255 Record.push_back(N->getLine()); 1256 Record.push_back(VE.getMetadataOrNullID(N->getType())); 1257 Record.push_back(N->isLocalToUnit()); 1258 Record.push_back(N->isDefinition()); 1259 Record.push_back(VE.getMetadataOrNullID(N->getRawVariable())); 1260 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration())); 1261 1262 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev); 1263 Record.clear(); 1264 } 1265 1266 static void writeDILocalVariable(const DILocalVariable *N, 1267 const ValueEnumerator &VE, 1268 BitstreamWriter &Stream, 1269 SmallVectorImpl<uint64_t> &Record, 1270 unsigned Abbrev) { 1271 Record.push_back(N->isDistinct()); 1272 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1273 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1274 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1275 Record.push_back(N->getLine()); 1276 Record.push_back(VE.getMetadataOrNullID(N->getType())); 1277 Record.push_back(N->getArg()); 1278 Record.push_back(N->getFlags()); 1279 1280 Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev); 1281 Record.clear(); 1282 } 1283 1284 static void writeDIExpression(const DIExpression *N, const ValueEnumerator &, 1285 BitstreamWriter &Stream, 1286 SmallVectorImpl<uint64_t> &Record, 1287 unsigned Abbrev) { 1288 Record.reserve(N->getElements().size() + 1); 1289 1290 Record.push_back(N->isDistinct()); 1291 Record.append(N->elements_begin(), N->elements_end()); 1292 1293 Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev); 1294 Record.clear(); 1295 } 1296 1297 static void writeDIObjCProperty(const DIObjCProperty *N, 1298 const ValueEnumerator &VE, 1299 BitstreamWriter &Stream, 1300 SmallVectorImpl<uint64_t> &Record, 1301 unsigned Abbrev) { 1302 Record.push_back(N->isDistinct()); 1303 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1304 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1305 Record.push_back(N->getLine()); 1306 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName())); 1307 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName())); 1308 Record.push_back(N->getAttributes()); 1309 Record.push_back(VE.getMetadataOrNullID(N->getType())); 1310 1311 Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev); 1312 Record.clear(); 1313 } 1314 1315 static void writeDIImportedEntity(const DIImportedEntity *N, 1316 const ValueEnumerator &VE, 1317 BitstreamWriter &Stream, 1318 SmallVectorImpl<uint64_t> &Record, 1319 unsigned Abbrev) { 1320 Record.push_back(N->isDistinct()); 1321 Record.push_back(N->getTag()); 1322 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1323 Record.push_back(VE.getMetadataOrNullID(N->getEntity())); 1324 Record.push_back(N->getLine()); 1325 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1326 1327 Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev); 1328 Record.clear(); 1329 } 1330 1331 static unsigned createNamedMetadataAbbrev(BitstreamWriter &Stream) { 1332 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1333 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME)); 1334 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1335 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 1336 return Stream.EmitAbbrev(Abbv); 1337 } 1338 1339 static void writeNamedMetadata(const Module &M, const ValueEnumerator &VE, 1340 BitstreamWriter &Stream, 1341 SmallVectorImpl<uint64_t> &Record) { 1342 if (M.named_metadata_empty()) 1343 return; 1344 1345 unsigned Abbrev = createNamedMetadataAbbrev(Stream); 1346 for (const NamedMDNode &NMD : M.named_metadata()) { 1347 // Write name. 1348 StringRef Str = NMD.getName(); 1349 Record.append(Str.bytes_begin(), Str.bytes_end()); 1350 Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev); 1351 Record.clear(); 1352 1353 // Write named metadata operands. 1354 for (const MDNode *N : NMD.operands()) 1355 Record.push_back(VE.getMetadataID(N)); 1356 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0); 1357 Record.clear(); 1358 } 1359 } 1360 1361 static unsigned createMetadataStringsAbbrev(BitstreamWriter &Stream) { 1362 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1363 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS)); 1364 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings 1365 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars 1366 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 1367 return Stream.EmitAbbrev(Abbv); 1368 } 1369 1370 /// Write out a record for MDString. 1371 /// 1372 /// All the metadata strings in a metadata block are emitted in a single 1373 /// record. The sizes and strings themselves are shoved into a blob. 1374 static void writeMetadataStrings(ArrayRef<const Metadata *> Strings, 1375 BitstreamWriter &Stream, 1376 SmallVectorImpl<uint64_t> &Record) { 1377 if (Strings.empty()) 1378 return; 1379 1380 // Start the record with the number of strings. 1381 Record.push_back(bitc::METADATA_STRINGS); 1382 Record.push_back(Strings.size()); 1383 1384 // Emit the sizes of the strings in the blob. 1385 SmallString<256> Blob; 1386 { 1387 BitstreamWriter W(Blob); 1388 for (const Metadata *MD : Strings) 1389 W.EmitVBR(cast<MDString>(MD)->getLength(), 6); 1390 W.FlushToWord(); 1391 } 1392 1393 // Add the offset to the strings to the record. 1394 Record.push_back(Blob.size()); 1395 1396 // Add the strings to the blob. 1397 for (const Metadata *MD : Strings) 1398 Blob.append(cast<MDString>(MD)->getString()); 1399 1400 // Emit the final record. 1401 Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(Stream), Record, Blob); 1402 Record.clear(); 1403 } 1404 1405 static void writeMetadataRecords(ArrayRef<const Metadata *> MDs, 1406 const ValueEnumerator &VE, 1407 BitstreamWriter &Stream, 1408 SmallVectorImpl<uint64_t> &Record) { 1409 if (MDs.empty()) 1410 return; 1411 1412 // Initialize MDNode abbreviations. 1413 #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0; 1414 #include "llvm/IR/Metadata.def" 1415 1416 for (const Metadata *MD : MDs) { 1417 if (const MDNode *N = dyn_cast<MDNode>(MD)) { 1418 assert(N->isResolved() && "Expected forward references to be resolved"); 1419 1420 switch (N->getMetadataID()) { 1421 default: 1422 llvm_unreachable("Invalid MDNode subclass"); 1423 #define HANDLE_MDNODE_LEAF(CLASS) \ 1424 case Metadata::CLASS##Kind: \ 1425 write##CLASS(cast<CLASS>(N), VE, Stream, Record, CLASS##Abbrev); \ 1426 continue; 1427 #include "llvm/IR/Metadata.def" 1428 } 1429 } 1430 writeValueAsMetadata(cast<ValueAsMetadata>(MD), VE, Stream, Record); 1431 } 1432 } 1433 1434 static void writeModuleMetadata(const Module &M, 1435 const ValueEnumerator &VE, 1436 BitstreamWriter &Stream) { 1437 if (!VE.hasMDs() && M.named_metadata_empty()) 1438 return; 1439 1440 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3); 1441 SmallVector<uint64_t, 64> Record; 1442 writeMetadataStrings(VE.getMDStrings(), Stream, Record); 1443 writeMetadataRecords(VE.getNonMDStrings(), VE, Stream, Record); 1444 writeNamedMetadata(M, VE, Stream, Record); 1445 Stream.ExitBlock(); 1446 } 1447 1448 static void writeFunctionMetadata(const Function &F, const ValueEnumerator &VE, 1449 BitstreamWriter &Stream) { 1450 if (!VE.hasMDs()) 1451 return; 1452 1453 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3); 1454 SmallVector<uint64_t, 64> Record; 1455 writeMetadataStrings(VE.getMDStrings(), Stream, Record); 1456 writeMetadataRecords(VE.getNonMDStrings(), VE, Stream, Record); 1457 Stream.ExitBlock(); 1458 } 1459 1460 static void WriteMetadataAttachment(const Function &F, 1461 const ValueEnumerator &VE, 1462 BitstreamWriter &Stream) { 1463 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3); 1464 1465 SmallVector<uint64_t, 64> Record; 1466 1467 // Write metadata attachments 1468 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]] 1469 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 1470 F.getAllMetadata(MDs); 1471 if (!MDs.empty()) { 1472 for (const auto &I : MDs) { 1473 Record.push_back(I.first); 1474 Record.push_back(VE.getMetadataID(I.second)); 1475 } 1476 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0); 1477 Record.clear(); 1478 } 1479 1480 for (const BasicBlock &BB : F) 1481 for (const Instruction &I : BB) { 1482 MDs.clear(); 1483 I.getAllMetadataOtherThanDebugLoc(MDs); 1484 1485 // If no metadata, ignore instruction. 1486 if (MDs.empty()) continue; 1487 1488 Record.push_back(VE.getInstructionID(&I)); 1489 1490 for (unsigned i = 0, e = MDs.size(); i != e; ++i) { 1491 Record.push_back(MDs[i].first); 1492 Record.push_back(VE.getMetadataID(MDs[i].second)); 1493 } 1494 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0); 1495 Record.clear(); 1496 } 1497 1498 Stream.ExitBlock(); 1499 } 1500 1501 static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) { 1502 SmallVector<uint64_t, 64> Record; 1503 1504 // Write metadata kinds 1505 // METADATA_KIND - [n x [id, name]] 1506 SmallVector<StringRef, 8> Names; 1507 M->getMDKindNames(Names); 1508 1509 if (Names.empty()) return; 1510 1511 Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3); 1512 1513 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) { 1514 Record.push_back(MDKindID); 1515 StringRef KName = Names[MDKindID]; 1516 Record.append(KName.begin(), KName.end()); 1517 1518 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0); 1519 Record.clear(); 1520 } 1521 1522 Stream.ExitBlock(); 1523 } 1524 1525 static void WriteOperandBundleTags(const Module *M, BitstreamWriter &Stream) { 1526 // Write metadata kinds 1527 // 1528 // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG 1529 // 1530 // OPERAND_BUNDLE_TAG - [strchr x N] 1531 1532 SmallVector<StringRef, 8> Tags; 1533 M->getOperandBundleTags(Tags); 1534 1535 if (Tags.empty()) 1536 return; 1537 1538 Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3); 1539 1540 SmallVector<uint64_t, 64> Record; 1541 1542 for (auto Tag : Tags) { 1543 Record.append(Tag.begin(), Tag.end()); 1544 1545 Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0); 1546 Record.clear(); 1547 } 1548 1549 Stream.ExitBlock(); 1550 } 1551 1552 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) { 1553 if ((int64_t)V >= 0) 1554 Vals.push_back(V << 1); 1555 else 1556 Vals.push_back((-V << 1) | 1); 1557 } 1558 1559 static void WriteConstants(unsigned FirstVal, unsigned LastVal, 1560 const ValueEnumerator &VE, 1561 BitstreamWriter &Stream, bool isGlobal) { 1562 if (FirstVal == LastVal) return; 1563 1564 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4); 1565 1566 unsigned AggregateAbbrev = 0; 1567 unsigned String8Abbrev = 0; 1568 unsigned CString7Abbrev = 0; 1569 unsigned CString6Abbrev = 0; 1570 // If this is a constant pool for the module, emit module-specific abbrevs. 1571 if (isGlobal) { 1572 // Abbrev for CST_CODE_AGGREGATE. 1573 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1574 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE)); 1575 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1576 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1))); 1577 AggregateAbbrev = Stream.EmitAbbrev(Abbv); 1578 1579 // Abbrev for CST_CODE_STRING. 1580 Abbv = new BitCodeAbbrev(); 1581 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING)); 1582 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1583 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 1584 String8Abbrev = Stream.EmitAbbrev(Abbv); 1585 // Abbrev for CST_CODE_CSTRING. 1586 Abbv = new BitCodeAbbrev(); 1587 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING)); 1588 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1589 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); 1590 CString7Abbrev = Stream.EmitAbbrev(Abbv); 1591 // Abbrev for CST_CODE_CSTRING. 1592 Abbv = new BitCodeAbbrev(); 1593 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING)); 1594 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1595 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 1596 CString6Abbrev = Stream.EmitAbbrev(Abbv); 1597 } 1598 1599 SmallVector<uint64_t, 64> Record; 1600 1601 const ValueEnumerator::ValueList &Vals = VE.getValues(); 1602 Type *LastTy = nullptr; 1603 for (unsigned i = FirstVal; i != LastVal; ++i) { 1604 const Value *V = Vals[i].first; 1605 // If we need to switch types, do so now. 1606 if (V->getType() != LastTy) { 1607 LastTy = V->getType(); 1608 Record.push_back(VE.getTypeID(LastTy)); 1609 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record, 1610 CONSTANTS_SETTYPE_ABBREV); 1611 Record.clear(); 1612 } 1613 1614 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) { 1615 Record.push_back(unsigned(IA->hasSideEffects()) | 1616 unsigned(IA->isAlignStack()) << 1 | 1617 unsigned(IA->getDialect()&1) << 2); 1618 1619 // Add the asm string. 1620 const std::string &AsmStr = IA->getAsmString(); 1621 Record.push_back(AsmStr.size()); 1622 Record.append(AsmStr.begin(), AsmStr.end()); 1623 1624 // Add the constraint string. 1625 const std::string &ConstraintStr = IA->getConstraintString(); 1626 Record.push_back(ConstraintStr.size()); 1627 Record.append(ConstraintStr.begin(), ConstraintStr.end()); 1628 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record); 1629 Record.clear(); 1630 continue; 1631 } 1632 const Constant *C = cast<Constant>(V); 1633 unsigned Code = -1U; 1634 unsigned AbbrevToUse = 0; 1635 if (C->isNullValue()) { 1636 Code = bitc::CST_CODE_NULL; 1637 } else if (isa<UndefValue>(C)) { 1638 Code = bitc::CST_CODE_UNDEF; 1639 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) { 1640 if (IV->getBitWidth() <= 64) { 1641 uint64_t V = IV->getSExtValue(); 1642 emitSignedInt64(Record, V); 1643 Code = bitc::CST_CODE_INTEGER; 1644 AbbrevToUse = CONSTANTS_INTEGER_ABBREV; 1645 } else { // Wide integers, > 64 bits in size. 1646 // We have an arbitrary precision integer value to write whose 1647 // bit width is > 64. However, in canonical unsigned integer 1648 // format it is likely that the high bits are going to be zero. 1649 // So, we only write the number of active words. 1650 unsigned NWords = IV->getValue().getActiveWords(); 1651 const uint64_t *RawWords = IV->getValue().getRawData(); 1652 for (unsigned i = 0; i != NWords; ++i) { 1653 emitSignedInt64(Record, RawWords[i]); 1654 } 1655 Code = bitc::CST_CODE_WIDE_INTEGER; 1656 } 1657 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) { 1658 Code = bitc::CST_CODE_FLOAT; 1659 Type *Ty = CFP->getType(); 1660 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) { 1661 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue()); 1662 } else if (Ty->isX86_FP80Ty()) { 1663 // api needed to prevent premature destruction 1664 // bits are not in the same order as a normal i80 APInt, compensate. 1665 APInt api = CFP->getValueAPF().bitcastToAPInt(); 1666 const uint64_t *p = api.getRawData(); 1667 Record.push_back((p[1] << 48) | (p[0] >> 16)); 1668 Record.push_back(p[0] & 0xffffLL); 1669 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) { 1670 APInt api = CFP->getValueAPF().bitcastToAPInt(); 1671 const uint64_t *p = api.getRawData(); 1672 Record.push_back(p[0]); 1673 Record.push_back(p[1]); 1674 } else { 1675 assert (0 && "Unknown FP type!"); 1676 } 1677 } else if (isa<ConstantDataSequential>(C) && 1678 cast<ConstantDataSequential>(C)->isString()) { 1679 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C); 1680 // Emit constant strings specially. 1681 unsigned NumElts = Str->getNumElements(); 1682 // If this is a null-terminated string, use the denser CSTRING encoding. 1683 if (Str->isCString()) { 1684 Code = bitc::CST_CODE_CSTRING; 1685 --NumElts; // Don't encode the null, which isn't allowed by char6. 1686 } else { 1687 Code = bitc::CST_CODE_STRING; 1688 AbbrevToUse = String8Abbrev; 1689 } 1690 bool isCStr7 = Code == bitc::CST_CODE_CSTRING; 1691 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING; 1692 for (unsigned i = 0; i != NumElts; ++i) { 1693 unsigned char V = Str->getElementAsInteger(i); 1694 Record.push_back(V); 1695 isCStr7 &= (V & 128) == 0; 1696 if (isCStrChar6) 1697 isCStrChar6 = BitCodeAbbrevOp::isChar6(V); 1698 } 1699 1700 if (isCStrChar6) 1701 AbbrevToUse = CString6Abbrev; 1702 else if (isCStr7) 1703 AbbrevToUse = CString7Abbrev; 1704 } else if (const ConstantDataSequential *CDS = 1705 dyn_cast<ConstantDataSequential>(C)) { 1706 Code = bitc::CST_CODE_DATA; 1707 Type *EltTy = CDS->getType()->getElementType(); 1708 if (isa<IntegerType>(EltTy)) { 1709 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) 1710 Record.push_back(CDS->getElementAsInteger(i)); 1711 } else { 1712 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) 1713 Record.push_back( 1714 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue()); 1715 } 1716 } else if (isa<ConstantAggregate>(C)) { 1717 Code = bitc::CST_CODE_AGGREGATE; 1718 for (const Value *Op : C->operands()) 1719 Record.push_back(VE.getValueID(Op)); 1720 AbbrevToUse = AggregateAbbrev; 1721 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1722 switch (CE->getOpcode()) { 1723 default: 1724 if (Instruction::isCast(CE->getOpcode())) { 1725 Code = bitc::CST_CODE_CE_CAST; 1726 Record.push_back(GetEncodedCastOpcode(CE->getOpcode())); 1727 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 1728 Record.push_back(VE.getValueID(C->getOperand(0))); 1729 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev; 1730 } else { 1731 assert(CE->getNumOperands() == 2 && "Unknown constant expr!"); 1732 Code = bitc::CST_CODE_CE_BINOP; 1733 Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode())); 1734 Record.push_back(VE.getValueID(C->getOperand(0))); 1735 Record.push_back(VE.getValueID(C->getOperand(1))); 1736 uint64_t Flags = GetOptimizationFlags(CE); 1737 if (Flags != 0) 1738 Record.push_back(Flags); 1739 } 1740 break; 1741 case Instruction::GetElementPtr: { 1742 Code = bitc::CST_CODE_CE_GEP; 1743 const auto *GO = cast<GEPOperator>(C); 1744 if (GO->isInBounds()) 1745 Code = bitc::CST_CODE_CE_INBOUNDS_GEP; 1746 Record.push_back(VE.getTypeID(GO->getSourceElementType())); 1747 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) { 1748 Record.push_back(VE.getTypeID(C->getOperand(i)->getType())); 1749 Record.push_back(VE.getValueID(C->getOperand(i))); 1750 } 1751 break; 1752 } 1753 case Instruction::Select: 1754 Code = bitc::CST_CODE_CE_SELECT; 1755 Record.push_back(VE.getValueID(C->getOperand(0))); 1756 Record.push_back(VE.getValueID(C->getOperand(1))); 1757 Record.push_back(VE.getValueID(C->getOperand(2))); 1758 break; 1759 case Instruction::ExtractElement: 1760 Code = bitc::CST_CODE_CE_EXTRACTELT; 1761 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 1762 Record.push_back(VE.getValueID(C->getOperand(0))); 1763 Record.push_back(VE.getTypeID(C->getOperand(1)->getType())); 1764 Record.push_back(VE.getValueID(C->getOperand(1))); 1765 break; 1766 case Instruction::InsertElement: 1767 Code = bitc::CST_CODE_CE_INSERTELT; 1768 Record.push_back(VE.getValueID(C->getOperand(0))); 1769 Record.push_back(VE.getValueID(C->getOperand(1))); 1770 Record.push_back(VE.getTypeID(C->getOperand(2)->getType())); 1771 Record.push_back(VE.getValueID(C->getOperand(2))); 1772 break; 1773 case Instruction::ShuffleVector: 1774 // If the return type and argument types are the same, this is a 1775 // standard shufflevector instruction. If the types are different, 1776 // then the shuffle is widening or truncating the input vectors, and 1777 // the argument type must also be encoded. 1778 if (C->getType() == C->getOperand(0)->getType()) { 1779 Code = bitc::CST_CODE_CE_SHUFFLEVEC; 1780 } else { 1781 Code = bitc::CST_CODE_CE_SHUFVEC_EX; 1782 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 1783 } 1784 Record.push_back(VE.getValueID(C->getOperand(0))); 1785 Record.push_back(VE.getValueID(C->getOperand(1))); 1786 Record.push_back(VE.getValueID(C->getOperand(2))); 1787 break; 1788 case Instruction::ICmp: 1789 case Instruction::FCmp: 1790 Code = bitc::CST_CODE_CE_CMP; 1791 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 1792 Record.push_back(VE.getValueID(C->getOperand(0))); 1793 Record.push_back(VE.getValueID(C->getOperand(1))); 1794 Record.push_back(CE->getPredicate()); 1795 break; 1796 } 1797 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) { 1798 Code = bitc::CST_CODE_BLOCKADDRESS; 1799 Record.push_back(VE.getTypeID(BA->getFunction()->getType())); 1800 Record.push_back(VE.getValueID(BA->getFunction())); 1801 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock())); 1802 } else { 1803 #ifndef NDEBUG 1804 C->dump(); 1805 #endif 1806 llvm_unreachable("Unknown constant!"); 1807 } 1808 Stream.EmitRecord(Code, Record, AbbrevToUse); 1809 Record.clear(); 1810 } 1811 1812 Stream.ExitBlock(); 1813 } 1814 1815 static void WriteModuleConstants(const ValueEnumerator &VE, 1816 BitstreamWriter &Stream) { 1817 const ValueEnumerator::ValueList &Vals = VE.getValues(); 1818 1819 // Find the first constant to emit, which is the first non-globalvalue value. 1820 // We know globalvalues have been emitted by WriteModuleInfo. 1821 for (unsigned i = 0, e = Vals.size(); i != e; ++i) { 1822 if (!isa<GlobalValue>(Vals[i].first)) { 1823 WriteConstants(i, Vals.size(), VE, Stream, true); 1824 return; 1825 } 1826 } 1827 } 1828 1829 /// PushValueAndType - The file has to encode both the value and type id for 1830 /// many values, because we need to know what type to create for forward 1831 /// references. However, most operands are not forward references, so this type 1832 /// field is not needed. 1833 /// 1834 /// This function adds V's value ID to Vals. If the value ID is higher than the 1835 /// instruction ID, then it is a forward reference, and it also includes the 1836 /// type ID. The value ID that is written is encoded relative to the InstID. 1837 static bool PushValueAndType(const Value *V, unsigned InstID, 1838 SmallVectorImpl<unsigned> &Vals, 1839 ValueEnumerator &VE) { 1840 unsigned ValID = VE.getValueID(V); 1841 // Make encoding relative to the InstID. 1842 Vals.push_back(InstID - ValID); 1843 if (ValID >= InstID) { 1844 Vals.push_back(VE.getTypeID(V->getType())); 1845 return true; 1846 } 1847 return false; 1848 } 1849 1850 static void WriteOperandBundles(BitstreamWriter &Stream, ImmutableCallSite CS, 1851 unsigned InstID, ValueEnumerator &VE) { 1852 SmallVector<unsigned, 64> Record; 1853 LLVMContext &C = CS.getInstruction()->getContext(); 1854 1855 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) { 1856 const auto &Bundle = CS.getOperandBundleAt(i); 1857 Record.push_back(C.getOperandBundleTagID(Bundle.getTagName())); 1858 1859 for (auto &Input : Bundle.Inputs) 1860 PushValueAndType(Input, InstID, Record, VE); 1861 1862 Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record); 1863 Record.clear(); 1864 } 1865 } 1866 1867 /// pushValue - Like PushValueAndType, but where the type of the value is 1868 /// omitted (perhaps it was already encoded in an earlier operand). 1869 static void pushValue(const Value *V, unsigned InstID, 1870 SmallVectorImpl<unsigned> &Vals, 1871 ValueEnumerator &VE) { 1872 unsigned ValID = VE.getValueID(V); 1873 Vals.push_back(InstID - ValID); 1874 } 1875 1876 static void pushValueSigned(const Value *V, unsigned InstID, 1877 SmallVectorImpl<uint64_t> &Vals, 1878 ValueEnumerator &VE) { 1879 unsigned ValID = VE.getValueID(V); 1880 int64_t diff = ((int32_t)InstID - (int32_t)ValID); 1881 emitSignedInt64(Vals, diff); 1882 } 1883 1884 /// WriteInstruction - Emit an instruction to the specified stream. 1885 static void WriteInstruction(const Instruction &I, unsigned InstID, 1886 ValueEnumerator &VE, BitstreamWriter &Stream, 1887 SmallVectorImpl<unsigned> &Vals) { 1888 unsigned Code = 0; 1889 unsigned AbbrevToUse = 0; 1890 VE.setInstructionID(&I); 1891 switch (I.getOpcode()) { 1892 default: 1893 if (Instruction::isCast(I.getOpcode())) { 1894 Code = bitc::FUNC_CODE_INST_CAST; 1895 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) 1896 AbbrevToUse = FUNCTION_INST_CAST_ABBREV; 1897 Vals.push_back(VE.getTypeID(I.getType())); 1898 Vals.push_back(GetEncodedCastOpcode(I.getOpcode())); 1899 } else { 1900 assert(isa<BinaryOperator>(I) && "Unknown instruction!"); 1901 Code = bitc::FUNC_CODE_INST_BINOP; 1902 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) 1903 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV; 1904 pushValue(I.getOperand(1), InstID, Vals, VE); 1905 Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode())); 1906 uint64_t Flags = GetOptimizationFlags(&I); 1907 if (Flags != 0) { 1908 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV) 1909 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV; 1910 Vals.push_back(Flags); 1911 } 1912 } 1913 break; 1914 1915 case Instruction::GetElementPtr: { 1916 Code = bitc::FUNC_CODE_INST_GEP; 1917 AbbrevToUse = FUNCTION_INST_GEP_ABBREV; 1918 auto &GEPInst = cast<GetElementPtrInst>(I); 1919 Vals.push_back(GEPInst.isInBounds()); 1920 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType())); 1921 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) 1922 PushValueAndType(I.getOperand(i), InstID, Vals, VE); 1923 break; 1924 } 1925 case Instruction::ExtractValue: { 1926 Code = bitc::FUNC_CODE_INST_EXTRACTVAL; 1927 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 1928 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I); 1929 Vals.append(EVI->idx_begin(), EVI->idx_end()); 1930 break; 1931 } 1932 case Instruction::InsertValue: { 1933 Code = bitc::FUNC_CODE_INST_INSERTVAL; 1934 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 1935 PushValueAndType(I.getOperand(1), InstID, Vals, VE); 1936 const InsertValueInst *IVI = cast<InsertValueInst>(&I); 1937 Vals.append(IVI->idx_begin(), IVI->idx_end()); 1938 break; 1939 } 1940 case Instruction::Select: 1941 Code = bitc::FUNC_CODE_INST_VSELECT; 1942 PushValueAndType(I.getOperand(1), InstID, Vals, VE); 1943 pushValue(I.getOperand(2), InstID, Vals, VE); 1944 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 1945 break; 1946 case Instruction::ExtractElement: 1947 Code = bitc::FUNC_CODE_INST_EXTRACTELT; 1948 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 1949 PushValueAndType(I.getOperand(1), InstID, Vals, VE); 1950 break; 1951 case Instruction::InsertElement: 1952 Code = bitc::FUNC_CODE_INST_INSERTELT; 1953 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 1954 pushValue(I.getOperand(1), InstID, Vals, VE); 1955 PushValueAndType(I.getOperand(2), InstID, Vals, VE); 1956 break; 1957 case Instruction::ShuffleVector: 1958 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC; 1959 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 1960 pushValue(I.getOperand(1), InstID, Vals, VE); 1961 pushValue(I.getOperand(2), InstID, Vals, VE); 1962 break; 1963 case Instruction::ICmp: 1964 case Instruction::FCmp: { 1965 // compare returning Int1Ty or vector of Int1Ty 1966 Code = bitc::FUNC_CODE_INST_CMP2; 1967 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 1968 pushValue(I.getOperand(1), InstID, Vals, VE); 1969 Vals.push_back(cast<CmpInst>(I).getPredicate()); 1970 uint64_t Flags = GetOptimizationFlags(&I); 1971 if (Flags != 0) 1972 Vals.push_back(Flags); 1973 break; 1974 } 1975 1976 case Instruction::Ret: 1977 { 1978 Code = bitc::FUNC_CODE_INST_RET; 1979 unsigned NumOperands = I.getNumOperands(); 1980 if (NumOperands == 0) 1981 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV; 1982 else if (NumOperands == 1) { 1983 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) 1984 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV; 1985 } else { 1986 for (unsigned i = 0, e = NumOperands; i != e; ++i) 1987 PushValueAndType(I.getOperand(i), InstID, Vals, VE); 1988 } 1989 } 1990 break; 1991 case Instruction::Br: 1992 { 1993 Code = bitc::FUNC_CODE_INST_BR; 1994 const BranchInst &II = cast<BranchInst>(I); 1995 Vals.push_back(VE.getValueID(II.getSuccessor(0))); 1996 if (II.isConditional()) { 1997 Vals.push_back(VE.getValueID(II.getSuccessor(1))); 1998 pushValue(II.getCondition(), InstID, Vals, VE); 1999 } 2000 } 2001 break; 2002 case Instruction::Switch: 2003 { 2004 Code = bitc::FUNC_CODE_INST_SWITCH; 2005 const SwitchInst &SI = cast<SwitchInst>(I); 2006 Vals.push_back(VE.getTypeID(SI.getCondition()->getType())); 2007 pushValue(SI.getCondition(), InstID, Vals, VE); 2008 Vals.push_back(VE.getValueID(SI.getDefaultDest())); 2009 for (SwitchInst::ConstCaseIt Case : SI.cases()) { 2010 Vals.push_back(VE.getValueID(Case.getCaseValue())); 2011 Vals.push_back(VE.getValueID(Case.getCaseSuccessor())); 2012 } 2013 } 2014 break; 2015 case Instruction::IndirectBr: 2016 Code = bitc::FUNC_CODE_INST_INDIRECTBR; 2017 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); 2018 // Encode the address operand as relative, but not the basic blocks. 2019 pushValue(I.getOperand(0), InstID, Vals, VE); 2020 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) 2021 Vals.push_back(VE.getValueID(I.getOperand(i))); 2022 break; 2023 2024 case Instruction::Invoke: { 2025 const InvokeInst *II = cast<InvokeInst>(&I); 2026 const Value *Callee = II->getCalledValue(); 2027 FunctionType *FTy = II->getFunctionType(); 2028 2029 if (II->hasOperandBundles()) 2030 WriteOperandBundles(Stream, II, InstID, VE); 2031 2032 Code = bitc::FUNC_CODE_INST_INVOKE; 2033 2034 Vals.push_back(VE.getAttributeID(II->getAttributes())); 2035 Vals.push_back(II->getCallingConv() | 1 << 13); 2036 Vals.push_back(VE.getValueID(II->getNormalDest())); 2037 Vals.push_back(VE.getValueID(II->getUnwindDest())); 2038 Vals.push_back(VE.getTypeID(FTy)); 2039 PushValueAndType(Callee, InstID, Vals, VE); 2040 2041 // Emit value #'s for the fixed parameters. 2042 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) 2043 pushValue(I.getOperand(i), InstID, Vals, VE); // fixed param. 2044 2045 // Emit type/value pairs for varargs params. 2046 if (FTy->isVarArg()) { 2047 for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3; 2048 i != e; ++i) 2049 PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg 2050 } 2051 break; 2052 } 2053 case Instruction::Resume: 2054 Code = bitc::FUNC_CODE_INST_RESUME; 2055 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 2056 break; 2057 case Instruction::CleanupRet: { 2058 Code = bitc::FUNC_CODE_INST_CLEANUPRET; 2059 const auto &CRI = cast<CleanupReturnInst>(I); 2060 pushValue(CRI.getCleanupPad(), InstID, Vals, VE); 2061 if (CRI.hasUnwindDest()) 2062 Vals.push_back(VE.getValueID(CRI.getUnwindDest())); 2063 break; 2064 } 2065 case Instruction::CatchRet: { 2066 Code = bitc::FUNC_CODE_INST_CATCHRET; 2067 const auto &CRI = cast<CatchReturnInst>(I); 2068 pushValue(CRI.getCatchPad(), InstID, Vals, VE); 2069 Vals.push_back(VE.getValueID(CRI.getSuccessor())); 2070 break; 2071 } 2072 case Instruction::CleanupPad: 2073 case Instruction::CatchPad: { 2074 const auto &FuncletPad = cast<FuncletPadInst>(I); 2075 Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD 2076 : bitc::FUNC_CODE_INST_CLEANUPPAD; 2077 pushValue(FuncletPad.getParentPad(), InstID, Vals, VE); 2078 2079 unsigned NumArgOperands = FuncletPad.getNumArgOperands(); 2080 Vals.push_back(NumArgOperands); 2081 for (unsigned Op = 0; Op != NumArgOperands; ++Op) 2082 PushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals, VE); 2083 break; 2084 } 2085 case Instruction::CatchSwitch: { 2086 Code = bitc::FUNC_CODE_INST_CATCHSWITCH; 2087 const auto &CatchSwitch = cast<CatchSwitchInst>(I); 2088 2089 pushValue(CatchSwitch.getParentPad(), InstID, Vals, VE); 2090 2091 unsigned NumHandlers = CatchSwitch.getNumHandlers(); 2092 Vals.push_back(NumHandlers); 2093 for (const BasicBlock *CatchPadBB : CatchSwitch.handlers()) 2094 Vals.push_back(VE.getValueID(CatchPadBB)); 2095 2096 if (CatchSwitch.hasUnwindDest()) 2097 Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest())); 2098 break; 2099 } 2100 case Instruction::Unreachable: 2101 Code = bitc::FUNC_CODE_INST_UNREACHABLE; 2102 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV; 2103 break; 2104 2105 case Instruction::PHI: { 2106 const PHINode &PN = cast<PHINode>(I); 2107 Code = bitc::FUNC_CODE_INST_PHI; 2108 // With the newer instruction encoding, forward references could give 2109 // negative valued IDs. This is most common for PHIs, so we use 2110 // signed VBRs. 2111 SmallVector<uint64_t, 128> Vals64; 2112 Vals64.push_back(VE.getTypeID(PN.getType())); 2113 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) { 2114 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64, VE); 2115 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i))); 2116 } 2117 // Emit a Vals64 vector and exit. 2118 Stream.EmitRecord(Code, Vals64, AbbrevToUse); 2119 Vals64.clear(); 2120 return; 2121 } 2122 2123 case Instruction::LandingPad: { 2124 const LandingPadInst &LP = cast<LandingPadInst>(I); 2125 Code = bitc::FUNC_CODE_INST_LANDINGPAD; 2126 Vals.push_back(VE.getTypeID(LP.getType())); 2127 Vals.push_back(LP.isCleanup()); 2128 Vals.push_back(LP.getNumClauses()); 2129 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) { 2130 if (LP.isCatch(I)) 2131 Vals.push_back(LandingPadInst::Catch); 2132 else 2133 Vals.push_back(LandingPadInst::Filter); 2134 PushValueAndType(LP.getClause(I), InstID, Vals, VE); 2135 } 2136 break; 2137 } 2138 2139 case Instruction::Alloca: { 2140 Code = bitc::FUNC_CODE_INST_ALLOCA; 2141 const AllocaInst &AI = cast<AllocaInst>(I); 2142 Vals.push_back(VE.getTypeID(AI.getAllocatedType())); 2143 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); 2144 Vals.push_back(VE.getValueID(I.getOperand(0))); // size. 2145 unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1; 2146 assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 && 2147 "not enough bits for maximum alignment"); 2148 assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64"); 2149 AlignRecord |= AI.isUsedWithInAlloca() << 5; 2150 AlignRecord |= 1 << 6; 2151 AlignRecord |= AI.isSwiftError() << 7; 2152 Vals.push_back(AlignRecord); 2153 break; 2154 } 2155 2156 case Instruction::Load: 2157 if (cast<LoadInst>(I).isAtomic()) { 2158 Code = bitc::FUNC_CODE_INST_LOADATOMIC; 2159 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 2160 } else { 2161 Code = bitc::FUNC_CODE_INST_LOAD; 2162 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) // ptr 2163 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV; 2164 } 2165 Vals.push_back(VE.getTypeID(I.getType())); 2166 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1); 2167 Vals.push_back(cast<LoadInst>(I).isVolatile()); 2168 if (cast<LoadInst>(I).isAtomic()) { 2169 Vals.push_back(GetEncodedOrdering(cast<LoadInst>(I).getOrdering())); 2170 Vals.push_back(GetEncodedSynchScope(cast<LoadInst>(I).getSynchScope())); 2171 } 2172 break; 2173 case Instruction::Store: 2174 if (cast<StoreInst>(I).isAtomic()) 2175 Code = bitc::FUNC_CODE_INST_STOREATOMIC; 2176 else 2177 Code = bitc::FUNC_CODE_INST_STORE; 2178 PushValueAndType(I.getOperand(1), InstID, Vals, VE); // ptrty + ptr 2179 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // valty + val 2180 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1); 2181 Vals.push_back(cast<StoreInst>(I).isVolatile()); 2182 if (cast<StoreInst>(I).isAtomic()) { 2183 Vals.push_back(GetEncodedOrdering(cast<StoreInst>(I).getOrdering())); 2184 Vals.push_back(GetEncodedSynchScope(cast<StoreInst>(I).getSynchScope())); 2185 } 2186 break; 2187 case Instruction::AtomicCmpXchg: 2188 Code = bitc::FUNC_CODE_INST_CMPXCHG; 2189 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr 2190 PushValueAndType(I.getOperand(1), InstID, Vals, VE); // cmp. 2191 pushValue(I.getOperand(2), InstID, Vals, VE); // newval. 2192 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile()); 2193 Vals.push_back(GetEncodedOrdering( 2194 cast<AtomicCmpXchgInst>(I).getSuccessOrdering())); 2195 Vals.push_back(GetEncodedSynchScope( 2196 cast<AtomicCmpXchgInst>(I).getSynchScope())); 2197 Vals.push_back(GetEncodedOrdering( 2198 cast<AtomicCmpXchgInst>(I).getFailureOrdering())); 2199 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak()); 2200 break; 2201 case Instruction::AtomicRMW: 2202 Code = bitc::FUNC_CODE_INST_ATOMICRMW; 2203 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr 2204 pushValue(I.getOperand(1), InstID, Vals, VE); // val. 2205 Vals.push_back(GetEncodedRMWOperation( 2206 cast<AtomicRMWInst>(I).getOperation())); 2207 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile()); 2208 Vals.push_back(GetEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering())); 2209 Vals.push_back(GetEncodedSynchScope( 2210 cast<AtomicRMWInst>(I).getSynchScope())); 2211 break; 2212 case Instruction::Fence: 2213 Code = bitc::FUNC_CODE_INST_FENCE; 2214 Vals.push_back(GetEncodedOrdering(cast<FenceInst>(I).getOrdering())); 2215 Vals.push_back(GetEncodedSynchScope(cast<FenceInst>(I).getSynchScope())); 2216 break; 2217 case Instruction::Call: { 2218 const CallInst &CI = cast<CallInst>(I); 2219 FunctionType *FTy = CI.getFunctionType(); 2220 2221 if (CI.hasOperandBundles()) 2222 WriteOperandBundles(Stream, &CI, InstID, VE); 2223 2224 Code = bitc::FUNC_CODE_INST_CALL; 2225 2226 Vals.push_back(VE.getAttributeID(CI.getAttributes())); 2227 2228 unsigned Flags = GetOptimizationFlags(&I); 2229 Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV | 2230 unsigned(CI.isTailCall()) << bitc::CALL_TAIL | 2231 unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL | 2232 1 << bitc::CALL_EXPLICIT_TYPE | 2233 unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL | 2234 unsigned(Flags != 0) << bitc::CALL_FMF); 2235 if (Flags != 0) 2236 Vals.push_back(Flags); 2237 2238 Vals.push_back(VE.getTypeID(FTy)); 2239 PushValueAndType(CI.getCalledValue(), InstID, Vals, VE); // Callee 2240 2241 // Emit value #'s for the fixed parameters. 2242 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) { 2243 // Check for labels (can happen with asm labels). 2244 if (FTy->getParamType(i)->isLabelTy()) 2245 Vals.push_back(VE.getValueID(CI.getArgOperand(i))); 2246 else 2247 pushValue(CI.getArgOperand(i), InstID, Vals, VE); // fixed param. 2248 } 2249 2250 // Emit type/value pairs for varargs params. 2251 if (FTy->isVarArg()) { 2252 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands(); 2253 i != e; ++i) 2254 PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE); // varargs 2255 } 2256 break; 2257 } 2258 case Instruction::VAArg: 2259 Code = bitc::FUNC_CODE_INST_VAARG; 2260 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty 2261 pushValue(I.getOperand(0), InstID, Vals, VE); // valist. 2262 Vals.push_back(VE.getTypeID(I.getType())); // restype. 2263 break; 2264 } 2265 2266 Stream.EmitRecord(Code, Vals, AbbrevToUse); 2267 Vals.clear(); 2268 } 2269 2270 /// Emit names for globals/functions etc. The VSTOffsetPlaceholder, 2271 /// BitcodeStartBit and ModuleSummaryIndex are only passed for the module-level 2272 /// VST, where we are including a function bitcode index and need to 2273 /// backpatch the VST forward declaration record. 2274 static void WriteValueSymbolTable( 2275 const ValueSymbolTable &VST, const ValueEnumerator &VE, 2276 BitstreamWriter &Stream, uint64_t VSTOffsetPlaceholder = 0, 2277 uint64_t BitcodeStartBit = 0, 2278 DenseMap<const Function *, uint64_t> *FunctionToBitcodeIndex = nullptr) { 2279 if (VST.empty()) { 2280 // WriteValueSymbolTableForwardDecl should have returned early as 2281 // well. Ensure this handling remains in sync by asserting that 2282 // the placeholder offset is not set. 2283 assert(VSTOffsetPlaceholder == 0); 2284 return; 2285 } 2286 2287 if (VSTOffsetPlaceholder > 0) { 2288 // Get the offset of the VST we are writing, and backpatch it into 2289 // the VST forward declaration record. 2290 uint64_t VSTOffset = Stream.GetCurrentBitNo(); 2291 // The BitcodeStartBit was the stream offset of the actual bitcode 2292 // (e.g. excluding any initial darwin header). 2293 VSTOffset -= BitcodeStartBit; 2294 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned"); 2295 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32); 2296 } 2297 2298 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4); 2299 2300 // For the module-level VST, add abbrev Ids for the VST_CODE_FNENTRY 2301 // records, which are not used in the per-function VSTs. 2302 unsigned FnEntry8BitAbbrev; 2303 unsigned FnEntry7BitAbbrev; 2304 unsigned FnEntry6BitAbbrev; 2305 if (VSTOffsetPlaceholder > 0) { 2306 // 8-bit fixed-width VST_CODE_FNENTRY function strings. 2307 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2308 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY)); 2309 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id 2310 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset 2311 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2312 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 2313 FnEntry8BitAbbrev = Stream.EmitAbbrev(Abbv); 2314 2315 // 7-bit fixed width VST_CODE_FNENTRY function strings. 2316 Abbv = new BitCodeAbbrev(); 2317 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY)); 2318 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id 2319 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset 2320 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2321 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); 2322 FnEntry7BitAbbrev = Stream.EmitAbbrev(Abbv); 2323 2324 // 6-bit char6 VST_CODE_FNENTRY function strings. 2325 Abbv = new BitCodeAbbrev(); 2326 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY)); 2327 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id 2328 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset 2329 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2330 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 2331 FnEntry6BitAbbrev = Stream.EmitAbbrev(Abbv); 2332 } 2333 2334 // FIXME: Set up the abbrev, we know how many values there are! 2335 // FIXME: We know if the type names can use 7-bit ascii. 2336 SmallVector<unsigned, 64> NameVals; 2337 2338 for (const ValueName &Name : VST) { 2339 // Figure out the encoding to use for the name. 2340 StringEncoding Bits = 2341 getStringEncoding(Name.getKeyData(), Name.getKeyLength()); 2342 2343 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV; 2344 NameVals.push_back(VE.getValueID(Name.getValue())); 2345 2346 Function *F = dyn_cast<Function>(Name.getValue()); 2347 if (!F) { 2348 // If value is an alias, need to get the aliased base object to 2349 // see if it is a function. 2350 auto *GA = dyn_cast<GlobalAlias>(Name.getValue()); 2351 if (GA && GA->getBaseObject()) 2352 F = dyn_cast<Function>(GA->getBaseObject()); 2353 } 2354 2355 // VST_CODE_ENTRY: [valueid, namechar x N] 2356 // VST_CODE_FNENTRY: [valueid, funcoffset, namechar x N] 2357 // VST_CODE_BBENTRY: [bbid, namechar x N] 2358 unsigned Code; 2359 if (isa<BasicBlock>(Name.getValue())) { 2360 Code = bitc::VST_CODE_BBENTRY; 2361 if (Bits == SE_Char6) 2362 AbbrevToUse = VST_BBENTRY_6_ABBREV; 2363 } else if (F && !F->isDeclaration()) { 2364 // Must be the module-level VST, where we pass in the Index and 2365 // have a VSTOffsetPlaceholder. The function-level VST should not 2366 // contain any Function symbols. 2367 assert(FunctionToBitcodeIndex); 2368 assert(VSTOffsetPlaceholder > 0); 2369 2370 // Save the word offset of the function (from the start of the 2371 // actual bitcode written to the stream). 2372 uint64_t BitcodeIndex = (*FunctionToBitcodeIndex)[F] - BitcodeStartBit; 2373 assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned"); 2374 NameVals.push_back(BitcodeIndex / 32); 2375 2376 Code = bitc::VST_CODE_FNENTRY; 2377 AbbrevToUse = FnEntry8BitAbbrev; 2378 if (Bits == SE_Char6) 2379 AbbrevToUse = FnEntry6BitAbbrev; 2380 else if (Bits == SE_Fixed7) 2381 AbbrevToUse = FnEntry7BitAbbrev; 2382 } else { 2383 Code = bitc::VST_CODE_ENTRY; 2384 if (Bits == SE_Char6) 2385 AbbrevToUse = VST_ENTRY_6_ABBREV; 2386 else if (Bits == SE_Fixed7) 2387 AbbrevToUse = VST_ENTRY_7_ABBREV; 2388 } 2389 2390 for (const auto P : Name.getKey()) 2391 NameVals.push_back((unsigned char)P); 2392 2393 // Emit the finished record. 2394 Stream.EmitRecord(Code, NameVals, AbbrevToUse); 2395 NameVals.clear(); 2396 } 2397 Stream.ExitBlock(); 2398 } 2399 2400 /// Emit function names and summary offsets for the combined index 2401 /// used by ThinLTO. 2402 static void WriteCombinedValueSymbolTable( 2403 const ModuleSummaryIndex &Index, BitstreamWriter &Stream, 2404 std::map<GlobalValue::GUID, unsigned> &GUIDToValueIdMap, 2405 uint64_t VSTOffsetPlaceholder) { 2406 assert(VSTOffsetPlaceholder > 0 && "Expected non-zero VSTOffsetPlaceholder"); 2407 // Get the offset of the VST we are writing, and backpatch it into 2408 // the VST forward declaration record. 2409 uint64_t VSTOffset = Stream.GetCurrentBitNo(); 2410 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned"); 2411 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32); 2412 2413 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4); 2414 2415 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2416 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_COMBINED_GVDEFENTRY)); 2417 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 2418 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // sumoffset 2419 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // guid 2420 unsigned DefEntryAbbrev = Stream.EmitAbbrev(Abbv); 2421 2422 Abbv = new BitCodeAbbrev(); 2423 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_COMBINED_ENTRY)); 2424 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 2425 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // refguid 2426 unsigned EntryAbbrev = Stream.EmitAbbrev(Abbv); 2427 2428 SmallVector<uint64_t, 64> NameVals; 2429 2430 for (const auto &FII : Index) { 2431 GlobalValue::GUID FuncGUID = FII.first; 2432 const auto &VMI = GUIDToValueIdMap.find(FuncGUID); 2433 assert(VMI != GUIDToValueIdMap.end()); 2434 2435 for (const auto &FI : FII.second) { 2436 // VST_CODE_COMBINED_GVDEFENTRY: [valueid, sumoffset, guid] 2437 NameVals.push_back(VMI->second); 2438 NameVals.push_back(FI->bitcodeIndex()); 2439 NameVals.push_back(FuncGUID); 2440 2441 // Emit the finished record. 2442 Stream.EmitRecord(bitc::VST_CODE_COMBINED_GVDEFENTRY, NameVals, 2443 DefEntryAbbrev); 2444 NameVals.clear(); 2445 } 2446 GUIDToValueIdMap.erase(VMI); 2447 } 2448 for (const auto &GVI : GUIDToValueIdMap) { 2449 // VST_CODE_COMBINED_ENTRY: [valueid, refguid] 2450 NameVals.push_back(GVI.second); 2451 NameVals.push_back(GVI.first); 2452 2453 // Emit the finished record. 2454 Stream.EmitRecord(bitc::VST_CODE_COMBINED_ENTRY, NameVals, EntryAbbrev); 2455 NameVals.clear(); 2456 } 2457 Stream.ExitBlock(); 2458 } 2459 2460 static void WriteUseList(ValueEnumerator &VE, UseListOrder &&Order, 2461 BitstreamWriter &Stream) { 2462 assert(Order.Shuffle.size() >= 2 && "Shuffle too small"); 2463 unsigned Code; 2464 if (isa<BasicBlock>(Order.V)) 2465 Code = bitc::USELIST_CODE_BB; 2466 else 2467 Code = bitc::USELIST_CODE_DEFAULT; 2468 2469 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end()); 2470 Record.push_back(VE.getValueID(Order.V)); 2471 Stream.EmitRecord(Code, Record); 2472 } 2473 2474 static void WriteUseListBlock(const Function *F, ValueEnumerator &VE, 2475 BitstreamWriter &Stream) { 2476 assert(VE.shouldPreserveUseListOrder() && 2477 "Expected to be preserving use-list order"); 2478 2479 auto hasMore = [&]() { 2480 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F; 2481 }; 2482 if (!hasMore()) 2483 // Nothing to do. 2484 return; 2485 2486 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3); 2487 while (hasMore()) { 2488 WriteUseList(VE, std::move(VE.UseListOrders.back()), Stream); 2489 VE.UseListOrders.pop_back(); 2490 } 2491 Stream.ExitBlock(); 2492 } 2493 2494 /// Emit a function body to the module stream. 2495 static void 2496 WriteFunction(const Function &F, const Module *M, ValueEnumerator &VE, 2497 BitstreamWriter &Stream, 2498 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) { 2499 // Save the bitcode index of the start of this function block for recording 2500 // in the VST. 2501 FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo(); 2502 2503 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4); 2504 VE.incorporateFunction(F); 2505 2506 SmallVector<unsigned, 64> Vals; 2507 2508 // Emit the number of basic blocks, so the reader can create them ahead of 2509 // time. 2510 Vals.push_back(VE.getBasicBlocks().size()); 2511 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals); 2512 Vals.clear(); 2513 2514 // If there are function-local constants, emit them now. 2515 unsigned CstStart, CstEnd; 2516 VE.getFunctionConstantRange(CstStart, CstEnd); 2517 WriteConstants(CstStart, CstEnd, VE, Stream, false); 2518 2519 // If there is function-local metadata, emit it now. 2520 writeFunctionMetadata(F, VE, Stream); 2521 2522 // Keep a running idea of what the instruction ID is. 2523 unsigned InstID = CstEnd; 2524 2525 bool NeedsMetadataAttachment = F.hasMetadata(); 2526 2527 DILocation *LastDL = nullptr; 2528 // Finally, emit all the instructions, in order. 2529 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) 2530 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); 2531 I != E; ++I) { 2532 WriteInstruction(*I, InstID, VE, Stream, Vals); 2533 2534 if (!I->getType()->isVoidTy()) 2535 ++InstID; 2536 2537 // If the instruction has metadata, write a metadata attachment later. 2538 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc(); 2539 2540 // If the instruction has a debug location, emit it. 2541 DILocation *DL = I->getDebugLoc(); 2542 if (!DL) 2543 continue; 2544 2545 if (DL == LastDL) { 2546 // Just repeat the same debug loc as last time. 2547 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals); 2548 continue; 2549 } 2550 2551 Vals.push_back(DL->getLine()); 2552 Vals.push_back(DL->getColumn()); 2553 Vals.push_back(VE.getMetadataOrNullID(DL->getScope())); 2554 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt())); 2555 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals); 2556 Vals.clear(); 2557 2558 LastDL = DL; 2559 } 2560 2561 // Emit names for all the instructions etc. 2562 WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream); 2563 2564 if (NeedsMetadataAttachment) 2565 WriteMetadataAttachment(F, VE, Stream); 2566 if (VE.shouldPreserveUseListOrder()) 2567 WriteUseListBlock(&F, VE, Stream); 2568 VE.purgeFunction(); 2569 Stream.ExitBlock(); 2570 } 2571 2572 // Emit blockinfo, which defines the standard abbreviations etc. 2573 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) { 2574 // We only want to emit block info records for blocks that have multiple 2575 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK. 2576 // Other blocks can define their abbrevs inline. 2577 Stream.EnterBlockInfoBlock(2); 2578 2579 { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings. 2580 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2581 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); 2582 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 2583 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2584 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 2585 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, 2586 Abbv) != VST_ENTRY_8_ABBREV) 2587 llvm_unreachable("Unexpected abbrev ordering!"); 2588 } 2589 2590 { // 7-bit fixed width VST_CODE_ENTRY strings. 2591 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2592 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY)); 2593 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 2594 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2595 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); 2596 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, 2597 Abbv) != VST_ENTRY_7_ABBREV) 2598 llvm_unreachable("Unexpected abbrev ordering!"); 2599 } 2600 { // 6-bit char6 VST_CODE_ENTRY strings. 2601 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2602 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY)); 2603 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 2604 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2605 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 2606 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, 2607 Abbv) != VST_ENTRY_6_ABBREV) 2608 llvm_unreachable("Unexpected abbrev ordering!"); 2609 } 2610 { // 6-bit char6 VST_CODE_BBENTRY strings. 2611 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2612 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY)); 2613 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 2614 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2615 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 2616 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, 2617 Abbv) != VST_BBENTRY_6_ABBREV) 2618 llvm_unreachable("Unexpected abbrev ordering!"); 2619 } 2620 2621 2622 2623 { // SETTYPE abbrev for CONSTANTS_BLOCK. 2624 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2625 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE)); 2626 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2627 VE.computeBitsRequiredForTypeIndicies())); 2628 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, 2629 Abbv) != CONSTANTS_SETTYPE_ABBREV) 2630 llvm_unreachable("Unexpected abbrev ordering!"); 2631 } 2632 2633 { // INTEGER abbrev for CONSTANTS_BLOCK. 2634 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2635 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER)); 2636 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 2637 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, 2638 Abbv) != CONSTANTS_INTEGER_ABBREV) 2639 llvm_unreachable("Unexpected abbrev ordering!"); 2640 } 2641 2642 { // CE_CAST abbrev for CONSTANTS_BLOCK. 2643 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2644 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST)); 2645 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc 2646 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid 2647 VE.computeBitsRequiredForTypeIndicies())); 2648 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id 2649 2650 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, 2651 Abbv) != CONSTANTS_CE_CAST_Abbrev) 2652 llvm_unreachable("Unexpected abbrev ordering!"); 2653 } 2654 { // NULL abbrev for CONSTANTS_BLOCK. 2655 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2656 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL)); 2657 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, 2658 Abbv) != CONSTANTS_NULL_Abbrev) 2659 llvm_unreachable("Unexpected abbrev ordering!"); 2660 } 2661 2662 // FIXME: This should only use space for first class types! 2663 2664 { // INST_LOAD abbrev for FUNCTION_BLOCK. 2665 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2666 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD)); 2667 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr 2668 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty 2669 VE.computeBitsRequiredForTypeIndicies())); 2670 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align 2671 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile 2672 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, 2673 Abbv) != FUNCTION_INST_LOAD_ABBREV) 2674 llvm_unreachable("Unexpected abbrev ordering!"); 2675 } 2676 { // INST_BINOP abbrev for FUNCTION_BLOCK. 2677 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2678 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP)); 2679 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS 2680 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS 2681 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 2682 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, 2683 Abbv) != FUNCTION_INST_BINOP_ABBREV) 2684 llvm_unreachable("Unexpected abbrev ordering!"); 2685 } 2686 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK. 2687 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2688 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP)); 2689 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS 2690 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS 2691 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 2692 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags 2693 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, 2694 Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV) 2695 llvm_unreachable("Unexpected abbrev ordering!"); 2696 } 2697 { // INST_CAST abbrev for FUNCTION_BLOCK. 2698 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2699 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST)); 2700 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal 2701 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty 2702 VE.computeBitsRequiredForTypeIndicies())); 2703 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 2704 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, 2705 Abbv) != FUNCTION_INST_CAST_ABBREV) 2706 llvm_unreachable("Unexpected abbrev ordering!"); 2707 } 2708 2709 { // INST_RET abbrev for FUNCTION_BLOCK. 2710 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2711 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET)); 2712 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, 2713 Abbv) != FUNCTION_INST_RET_VOID_ABBREV) 2714 llvm_unreachable("Unexpected abbrev ordering!"); 2715 } 2716 { // INST_RET abbrev for FUNCTION_BLOCK. 2717 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2718 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET)); 2719 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID 2720 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, 2721 Abbv) != FUNCTION_INST_RET_VAL_ABBREV) 2722 llvm_unreachable("Unexpected abbrev ordering!"); 2723 } 2724 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK. 2725 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2726 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE)); 2727 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, 2728 Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV) 2729 llvm_unreachable("Unexpected abbrev ordering!"); 2730 } 2731 { 2732 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2733 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP)); 2734 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); 2735 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty 2736 Log2_32_Ceil(VE.getTypes().size() + 1))); 2737 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2738 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 2739 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 2740 FUNCTION_INST_GEP_ABBREV) 2741 llvm_unreachable("Unexpected abbrev ordering!"); 2742 } 2743 2744 Stream.ExitBlock(); 2745 } 2746 2747 /// Write the module path strings, currently only used when generating 2748 /// a combined index file. 2749 static void WriteModStrings(const ModuleSummaryIndex &I, 2750 BitstreamWriter &Stream) { 2751 Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3); 2752 2753 // TODO: See which abbrev sizes we actually need to emit 2754 2755 // 8-bit fixed-width MST_ENTRY strings. 2756 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2757 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY)); 2758 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 2759 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2760 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 2761 unsigned Abbrev8Bit = Stream.EmitAbbrev(Abbv); 2762 2763 // 7-bit fixed width MST_ENTRY strings. 2764 Abbv = new BitCodeAbbrev(); 2765 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY)); 2766 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 2767 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2768 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); 2769 unsigned Abbrev7Bit = Stream.EmitAbbrev(Abbv); 2770 2771 // 6-bit char6 MST_ENTRY strings. 2772 Abbv = new BitCodeAbbrev(); 2773 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY)); 2774 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 2775 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2776 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 2777 unsigned Abbrev6Bit = Stream.EmitAbbrev(Abbv); 2778 2779 // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY. 2780 Abbv = new BitCodeAbbrev(); 2781 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH)); 2782 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 2783 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 2784 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 2785 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 2786 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 2787 unsigned AbbrevHash = Stream.EmitAbbrev(Abbv); 2788 2789 SmallVector<unsigned, 64> Vals; 2790 for (const auto &MPSE : I.modulePaths()) { 2791 StringEncoding Bits = 2792 getStringEncoding(MPSE.getKey().data(), MPSE.getKey().size()); 2793 unsigned AbbrevToUse = Abbrev8Bit; 2794 if (Bits == SE_Char6) 2795 AbbrevToUse = Abbrev6Bit; 2796 else if (Bits == SE_Fixed7) 2797 AbbrevToUse = Abbrev7Bit; 2798 2799 Vals.push_back(MPSE.getValue().first); 2800 2801 for (const auto P : MPSE.getKey()) 2802 Vals.push_back((unsigned char)P); 2803 2804 // Emit the finished record. 2805 Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse); 2806 2807 Vals.clear(); 2808 // Emit an optional hash for the module now 2809 auto &Hash = MPSE.getValue().second; 2810 bool AllZero = true; // Detect if the hash is empty, and do not generate it 2811 for (auto Val : Hash) { 2812 if (Val) 2813 AllZero = false; 2814 Vals.push_back(Val); 2815 } 2816 if (!AllZero) { 2817 // Emit the hash record. 2818 Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash); 2819 } 2820 2821 Vals.clear(); 2822 } 2823 Stream.ExitBlock(); 2824 } 2825 2826 // Helper to emit a single function summary record. 2827 static void WritePerModuleFunctionSummaryRecord( 2828 SmallVector<uint64_t, 64> &NameVals, GlobalValueInfo *Info, 2829 unsigned ValueID, const ValueEnumerator &VE, unsigned FSCallsAbbrev, 2830 unsigned FSCallsProfileAbbrev, BitstreamWriter &Stream, const Function &F) { 2831 NameVals.push_back(ValueID); 2832 2833 FunctionSummary *FS = cast<FunctionSummary>(Info->summary()); 2834 NameVals.push_back(getEncodedLinkage(FS->linkage())); 2835 NameVals.push_back(FS->instCount()); 2836 NameVals.push_back(FS->refs().size()); 2837 2838 for (auto &RI : FS->refs()) 2839 NameVals.push_back(VE.getValueID(RI.getValue())); 2840 2841 bool HasProfileData = F.getEntryCount().hasValue(); 2842 for (auto &ECI : FS->calls()) { 2843 NameVals.push_back(VE.getValueID(ECI.first.getValue())); 2844 assert(ECI.second.CallsiteCount > 0 && "Expected at least one callsite"); 2845 NameVals.push_back(ECI.second.CallsiteCount); 2846 if (HasProfileData) 2847 NameVals.push_back(ECI.second.ProfileCount); 2848 } 2849 2850 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev); 2851 unsigned Code = 2852 (HasProfileData ? bitc::FS_PERMODULE_PROFILE : bitc::FS_PERMODULE); 2853 2854 // Emit the finished record. 2855 Stream.EmitRecord(Code, NameVals, FSAbbrev); 2856 NameVals.clear(); 2857 } 2858 2859 // Collect the global value references in the given variable's initializer, 2860 // and emit them in a summary record. 2861 static void WriteModuleLevelReferences(const GlobalVariable &V, 2862 const ModuleSummaryIndex &Index, 2863 const ValueEnumerator &VE, 2864 SmallVector<uint64_t, 64> &NameVals, 2865 unsigned FSModRefsAbbrev, 2866 BitstreamWriter &Stream) { 2867 // Only interested in recording variable defs in the summary. 2868 if (V.isDeclaration()) 2869 return; 2870 NameVals.push_back(VE.getValueID(&V)); 2871 NameVals.push_back(getEncodedLinkage(V.getLinkage())); 2872 auto *Info = Index.getGlobalValueInfo(V); 2873 GlobalVarSummary *VS = cast<GlobalVarSummary>(Info->summary()); 2874 for (auto Ref : VS->refs()) 2875 NameVals.push_back(VE.getValueID(Ref.getValue())); 2876 Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals, 2877 FSModRefsAbbrev); 2878 NameVals.clear(); 2879 } 2880 2881 /// Emit the per-module summary section alongside the rest of 2882 /// the module's bitcode. 2883 static void WritePerModuleGlobalValueSummary(const Module *M, 2884 const ModuleSummaryIndex &Index, 2885 const ValueEnumerator &VE, 2886 BitstreamWriter &Stream) { 2887 if (M->empty()) 2888 return; 2889 2890 Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3); 2891 2892 // Abbrev for FS_PERMODULE. 2893 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2894 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE)); 2895 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 2896 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // linkage 2897 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount 2898 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs 2899 // numrefs x valueid, n x (valueid, callsitecount) 2900 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2901 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 2902 unsigned FSCallsAbbrev = Stream.EmitAbbrev(Abbv); 2903 2904 // Abbrev for FS_PERMODULE_PROFILE. 2905 Abbv = new BitCodeAbbrev(); 2906 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE)); 2907 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 2908 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // linkage 2909 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount 2910 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs 2911 // numrefs x valueid, n x (valueid, callsitecount, profilecount) 2912 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2913 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 2914 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(Abbv); 2915 2916 // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS. 2917 Abbv = new BitCodeAbbrev(); 2918 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS)); 2919 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 2920 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // linkage 2921 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids 2922 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 2923 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(Abbv); 2924 2925 SmallVector<uint64_t, 64> NameVals; 2926 // Iterate over the list of functions instead of the Index to 2927 // ensure the ordering is stable. 2928 for (const Function &F : *M) { 2929 if (F.isDeclaration()) 2930 continue; 2931 // Skip anonymous functions. We will emit a function summary for 2932 // any aliases below. 2933 if (!F.hasName()) 2934 continue; 2935 2936 auto *Info = Index.getGlobalValueInfo(F); 2937 WritePerModuleFunctionSummaryRecord( 2938 NameVals, Info, 2939 VE.getValueID(M->getValueSymbolTable().lookup(F.getName())), VE, 2940 FSCallsAbbrev, FSCallsProfileAbbrev, Stream, F); 2941 } 2942 2943 // Capture references from GlobalVariable initializers, which are outside 2944 // of a function scope. 2945 for (const GlobalVariable &G : M->globals()) 2946 WriteModuleLevelReferences(G, Index, VE, NameVals, FSModRefsAbbrev, Stream); 2947 2948 Stream.ExitBlock(); 2949 } 2950 2951 /// Emit the combined summary section into the combined index file. 2952 static void WriteCombinedGlobalValueSummary( 2953 const ModuleSummaryIndex &Index, BitstreamWriter &Stream, 2954 std::map<GlobalValue::GUID, unsigned> &GUIDToValueIdMap, 2955 unsigned GlobalValueId) { 2956 Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3); 2957 2958 // Abbrev for FS_COMBINED. 2959 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2960 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED)); 2961 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid 2962 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // linkage 2963 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount 2964 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs 2965 // numrefs x valueid, n x (valueid, callsitecount) 2966 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2967 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 2968 unsigned FSCallsAbbrev = Stream.EmitAbbrev(Abbv); 2969 2970 // Abbrev for FS_COMBINED_PROFILE. 2971 Abbv = new BitCodeAbbrev(); 2972 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE)); 2973 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid 2974 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // linkage 2975 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount 2976 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs 2977 // numrefs x valueid, n x (valueid, callsitecount, profilecount) 2978 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2979 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 2980 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(Abbv); 2981 2982 // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS. 2983 Abbv = new BitCodeAbbrev(); 2984 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS)); 2985 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid 2986 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // linkage 2987 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids 2988 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 2989 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(Abbv); 2990 2991 SmallVector<uint64_t, 64> NameVals; 2992 for (const auto &FII : Index) { 2993 for (auto &FI : FII.second) { 2994 GlobalValueSummary *S = FI->summary(); 2995 assert(S); 2996 2997 if (auto *VS = dyn_cast<GlobalVarSummary>(S)) { 2998 NameVals.push_back(Index.getModuleId(VS->modulePath())); 2999 NameVals.push_back(getEncodedLinkage(VS->linkage())); 3000 for (auto &RI : VS->refs()) { 3001 const auto &VMI = GUIDToValueIdMap.find(RI.getGUID()); 3002 unsigned RefId; 3003 // If this GUID doesn't have an entry, assign one. 3004 if (VMI == GUIDToValueIdMap.end()) { 3005 GUIDToValueIdMap[RI.getGUID()] = ++GlobalValueId; 3006 RefId = GlobalValueId; 3007 } else { 3008 RefId = VMI->second; 3009 } 3010 NameVals.push_back(RefId); 3011 } 3012 3013 // Record the starting offset of this summary entry for use 3014 // in the VST entry. Add the current code size since the 3015 // reader will invoke readRecord after the abbrev id read. 3016 FI->setBitcodeIndex(Stream.GetCurrentBitNo() + 3017 Stream.GetAbbrevIDWidth()); 3018 3019 // Emit the finished record. 3020 Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals, 3021 FSModRefsAbbrev); 3022 NameVals.clear(); 3023 continue; 3024 } 3025 3026 auto *FS = cast<FunctionSummary>(S); 3027 NameVals.push_back(Index.getModuleId(FS->modulePath())); 3028 NameVals.push_back(getEncodedLinkage(FS->linkage())); 3029 NameVals.push_back(FS->instCount()); 3030 NameVals.push_back(FS->refs().size()); 3031 3032 for (auto &RI : FS->refs()) { 3033 const auto &VMI = GUIDToValueIdMap.find(RI.getGUID()); 3034 unsigned RefId; 3035 // If this GUID doesn't have an entry, assign one. 3036 if (VMI == GUIDToValueIdMap.end()) { 3037 GUIDToValueIdMap[RI.getGUID()] = ++GlobalValueId; 3038 RefId = GlobalValueId; 3039 } else { 3040 RefId = VMI->second; 3041 } 3042 NameVals.push_back(RefId); 3043 } 3044 3045 bool HasProfileData = false; 3046 for (auto &EI : FS->calls()) { 3047 HasProfileData |= EI.second.ProfileCount != 0; 3048 if (HasProfileData) 3049 break; 3050 } 3051 3052 for (auto &EI : FS->calls()) { 3053 const auto &VMI = GUIDToValueIdMap.find(EI.first.getGUID()); 3054 // If this GUID doesn't have an entry, it doesn't have a function 3055 // summary and we don't need to record any calls to it. 3056 if (VMI == GUIDToValueIdMap.end()) 3057 continue; 3058 NameVals.push_back(VMI->second); 3059 assert(EI.second.CallsiteCount > 0 && "Expected at least one callsite"); 3060 NameVals.push_back(EI.second.CallsiteCount); 3061 if (HasProfileData) 3062 NameVals.push_back(EI.second.ProfileCount); 3063 } 3064 3065 // Record the starting offset of this summary entry for use 3066 // in the VST entry. Add the current code size since the 3067 // reader will invoke readRecord after the abbrev id read. 3068 FI->setBitcodeIndex(Stream.GetCurrentBitNo() + Stream.GetAbbrevIDWidth()); 3069 3070 unsigned FSAbbrev = 3071 (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev); 3072 unsigned Code = 3073 (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED); 3074 3075 // Emit the finished record. 3076 Stream.EmitRecord(Code, NameVals, FSAbbrev); 3077 NameVals.clear(); 3078 } 3079 } 3080 3081 Stream.ExitBlock(); 3082 } 3083 3084 // Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the 3085 // current llvm version, and a record for the epoch number. 3086 static void WriteIdentificationBlock(const Module *M, BitstreamWriter &Stream) { 3087 Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5); 3088 3089 // Write the "user readable" string identifying the bitcode producer 3090 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 3091 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING)); 3092 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3093 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 3094 auto StringAbbrev = Stream.EmitAbbrev(Abbv); 3095 WriteStringRecord(bitc::IDENTIFICATION_CODE_STRING, 3096 "LLVM" LLVM_VERSION_STRING, StringAbbrev, Stream); 3097 3098 // Write the epoch version 3099 Abbv = new BitCodeAbbrev(); 3100 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH)); 3101 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 3102 auto EpochAbbrev = Stream.EmitAbbrev(Abbv); 3103 SmallVector<unsigned, 1> Vals = {bitc::BITCODE_CURRENT_EPOCH}; 3104 Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev); 3105 Stream.ExitBlock(); 3106 } 3107 3108 static void writeModuleHash(BitstreamWriter &Stream, 3109 SmallVectorImpl<char> &Buffer, 3110 size_t BlockStartPos) { 3111 // Emit the module's hash. 3112 // MODULE_CODE_HASH: [5*i32] 3113 SHA1 Hasher; 3114 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&Buffer[BlockStartPos], 3115 Buffer.size() - BlockStartPos)); 3116 auto Hash = Hasher.result(); 3117 SmallVector<uint64_t, 20> Vals; 3118 auto LShift = [&](unsigned char Val, unsigned Amount) 3119 -> uint64_t { return ((uint64_t)Val) << Amount; }; 3120 for (int Pos = 0; Pos < 20; Pos += 4) { 3121 uint32_t SubHash = LShift(Hash[Pos + 0], 24); 3122 SubHash |= LShift(Hash[Pos + 1], 16) | LShift(Hash[Pos + 2], 8) | 3123 (unsigned)(unsigned char)Hash[Pos + 3]; 3124 Vals.push_back(SubHash); 3125 } 3126 3127 // Emit the finished record. 3128 Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals); 3129 } 3130 3131 /// WriteModule - Emit the specified module to the bitstream. 3132 static void WriteModule(const Module *M, BitstreamWriter &Stream, 3133 bool ShouldPreserveUseListOrder, 3134 uint64_t BitcodeStartBit, 3135 const ModuleSummaryIndex *Index, bool GenerateHash, 3136 SmallVectorImpl<char> &Buffer) { 3137 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3); 3138 size_t BlockStartPos = Buffer.size(); 3139 3140 SmallVector<unsigned, 1> Vals; 3141 unsigned CurVersion = 1; 3142 Vals.push_back(CurVersion); 3143 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals); 3144 3145 // Analyze the module, enumerating globals, functions, etc. 3146 ValueEnumerator VE(*M, ShouldPreserveUseListOrder); 3147 3148 // Emit blockinfo, which defines the standard abbreviations etc. 3149 WriteBlockInfo(VE, Stream); 3150 3151 // Emit information about attribute groups. 3152 WriteAttributeGroupTable(VE, Stream); 3153 3154 // Emit information about parameter attributes. 3155 WriteAttributeTable(VE, Stream); 3156 3157 // Emit information describing all of the types in the module. 3158 WriteTypeTable(VE, Stream); 3159 3160 writeComdats(VE, Stream); 3161 3162 // Emit top-level description of module, including target triple, inline asm, 3163 // descriptors for global variables, and function prototype info. 3164 uint64_t VSTOffsetPlaceholder = WriteModuleInfo(M, VE, Stream); 3165 3166 // Emit constants. 3167 WriteModuleConstants(VE, Stream); 3168 3169 // Emit metadata. 3170 writeModuleMetadata(*M, VE, Stream); 3171 3172 // Emit metadata. 3173 WriteModuleMetadataStore(M, Stream); 3174 3175 // Emit module-level use-lists. 3176 if (VE.shouldPreserveUseListOrder()) 3177 WriteUseListBlock(nullptr, VE, Stream); 3178 3179 WriteOperandBundleTags(M, Stream); 3180 3181 // Emit function bodies. 3182 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex; 3183 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) 3184 if (!F->isDeclaration()) 3185 WriteFunction(*F, M, VE, Stream, FunctionToBitcodeIndex); 3186 3187 // Need to write after the above call to WriteFunction which populates 3188 // the summary information in the index. 3189 if (Index) 3190 WritePerModuleGlobalValueSummary(M, *Index, VE, Stream); 3191 3192 WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream, 3193 VSTOffsetPlaceholder, BitcodeStartBit, 3194 &FunctionToBitcodeIndex); 3195 3196 if (GenerateHash) { 3197 writeModuleHash(Stream, Buffer, BlockStartPos); 3198 } 3199 3200 Stream.ExitBlock(); 3201 } 3202 3203 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a 3204 /// header and trailer to make it compatible with the system archiver. To do 3205 /// this we emit the following header, and then emit a trailer that pads the 3206 /// file out to be a multiple of 16 bytes. 3207 /// 3208 /// struct bc_header { 3209 /// uint32_t Magic; // 0x0B17C0DE 3210 /// uint32_t Version; // Version, currently always 0. 3211 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file. 3212 /// uint32_t BitcodeSize; // Size of traditional bitcode file. 3213 /// uint32_t CPUType; // CPU specifier. 3214 /// ... potentially more later ... 3215 /// }; 3216 3217 static void WriteInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer, 3218 uint32_t &Position) { 3219 support::endian::write32le(&Buffer[Position], Value); 3220 Position += 4; 3221 } 3222 3223 static void EmitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer, 3224 const Triple &TT) { 3225 unsigned CPUType = ~0U; 3226 3227 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*, 3228 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic 3229 // number from /usr/include/mach/machine.h. It is ok to reproduce the 3230 // specific constants here because they are implicitly part of the Darwin ABI. 3231 enum { 3232 DARWIN_CPU_ARCH_ABI64 = 0x01000000, 3233 DARWIN_CPU_TYPE_X86 = 7, 3234 DARWIN_CPU_TYPE_ARM = 12, 3235 DARWIN_CPU_TYPE_POWERPC = 18 3236 }; 3237 3238 Triple::ArchType Arch = TT.getArch(); 3239 if (Arch == Triple::x86_64) 3240 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64; 3241 else if (Arch == Triple::x86) 3242 CPUType = DARWIN_CPU_TYPE_X86; 3243 else if (Arch == Triple::ppc) 3244 CPUType = DARWIN_CPU_TYPE_POWERPC; 3245 else if (Arch == Triple::ppc64) 3246 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64; 3247 else if (Arch == Triple::arm || Arch == Triple::thumb) 3248 CPUType = DARWIN_CPU_TYPE_ARM; 3249 3250 // Traditional Bitcode starts after header. 3251 assert(Buffer.size() >= BWH_HeaderSize && 3252 "Expected header size to be reserved"); 3253 unsigned BCOffset = BWH_HeaderSize; 3254 unsigned BCSize = Buffer.size() - BWH_HeaderSize; 3255 3256 // Write the magic and version. 3257 unsigned Position = 0; 3258 WriteInt32ToBuffer(0x0B17C0DE , Buffer, Position); 3259 WriteInt32ToBuffer(0 , Buffer, Position); // Version. 3260 WriteInt32ToBuffer(BCOffset , Buffer, Position); 3261 WriteInt32ToBuffer(BCSize , Buffer, Position); 3262 WriteInt32ToBuffer(CPUType , Buffer, Position); 3263 3264 // If the file is not a multiple of 16 bytes, insert dummy padding. 3265 while (Buffer.size() & 15) 3266 Buffer.push_back(0); 3267 } 3268 3269 /// Helper to write the header common to all bitcode files. 3270 static void WriteBitcodeHeader(BitstreamWriter &Stream) { 3271 // Emit the file header. 3272 Stream.Emit((unsigned)'B', 8); 3273 Stream.Emit((unsigned)'C', 8); 3274 Stream.Emit(0x0, 4); 3275 Stream.Emit(0xC, 4); 3276 Stream.Emit(0xE, 4); 3277 Stream.Emit(0xD, 4); 3278 } 3279 3280 /// WriteBitcodeToFile - Write the specified module to the specified output 3281 /// stream. 3282 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out, 3283 bool ShouldPreserveUseListOrder, 3284 const ModuleSummaryIndex *Index, 3285 bool GenerateHash) { 3286 SmallVector<char, 0> Buffer; 3287 Buffer.reserve(256*1024); 3288 3289 // If this is darwin or another generic macho target, reserve space for the 3290 // header. 3291 Triple TT(M->getTargetTriple()); 3292 if (TT.isOSDarwin() || TT.isOSBinFormatMachO()) 3293 Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0); 3294 3295 // Emit the module into the buffer. 3296 { 3297 BitstreamWriter Stream(Buffer); 3298 // Save the start bit of the actual bitcode, in case there is space 3299 // saved at the start for the darwin header above. The reader stream 3300 // will start at the bitcode, and we need the offset of the VST 3301 // to line up. 3302 uint64_t BitcodeStartBit = Stream.GetCurrentBitNo(); 3303 3304 // Emit the file header. 3305 WriteBitcodeHeader(Stream); 3306 3307 WriteIdentificationBlock(M, Stream); 3308 3309 // Emit the module. 3310 WriteModule(M, Stream, ShouldPreserveUseListOrder, BitcodeStartBit, Index, 3311 GenerateHash, Buffer); 3312 } 3313 3314 if (TT.isOSDarwin() || TT.isOSBinFormatMachO()) 3315 EmitDarwinBCHeaderAndTrailer(Buffer, TT); 3316 3317 // Write the generated bitstream to "Out". 3318 Out.write((char*)&Buffer.front(), Buffer.size()); 3319 } 3320 3321 // Write the specified module summary index to the given raw output stream, 3322 // where it will be written in a new bitcode block. This is used when 3323 // writing the combined index file for ThinLTO. 3324 void llvm::WriteIndexToFile(const ModuleSummaryIndex &Index, raw_ostream &Out) { 3325 SmallVector<char, 0> Buffer; 3326 Buffer.reserve(256 * 1024); 3327 3328 BitstreamWriter Stream(Buffer); 3329 3330 // Emit the bitcode header. 3331 WriteBitcodeHeader(Stream); 3332 3333 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3); 3334 3335 SmallVector<unsigned, 1> Vals; 3336 unsigned CurVersion = 1; 3337 Vals.push_back(CurVersion); 3338 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals); 3339 3340 // If we have a VST, write the VSTOFFSET record placeholder and record 3341 // its offset. 3342 uint64_t VSTOffsetPlaceholder = WriteValueSymbolTableForwardDecl(Stream); 3343 3344 // Write the module paths in the combined index. 3345 WriteModStrings(Index, Stream); 3346 3347 // Assign unique value ids to all functions in the index for use 3348 // in writing out the call graph edges. Save the mapping from GUID 3349 // to the new global value id to use when writing those edges, which 3350 // are currently saved in the index in terms of GUID. 3351 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap; 3352 unsigned GlobalValueId = 0; 3353 for (auto &II : Index) 3354 GUIDToValueIdMap[II.first] = ++GlobalValueId; 3355 3356 // Write the summary combined index records. 3357 WriteCombinedGlobalValueSummary(Index, Stream, GUIDToValueIdMap, 3358 GlobalValueId); 3359 3360 // Need a special VST writer for the combined index (we don't have a 3361 // real VST and real values when this is invoked). 3362 WriteCombinedValueSymbolTable(Index, Stream, GUIDToValueIdMap, 3363 VSTOffsetPlaceholder); 3364 3365 Stream.ExitBlock(); 3366 3367 Out.write((char *)&Buffer.front(), Buffer.size()); 3368 } 3369