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