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