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