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