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