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