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