1 //===- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // Bitcode writer implementation. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/Bitcode/BitcodeWriter.h" 14 #include "ValueEnumerator.h" 15 #include "llvm/ADT/APFloat.h" 16 #include "llvm/ADT/APInt.h" 17 #include "llvm/ADT/ArrayRef.h" 18 #include "llvm/ADT/DenseMap.h" 19 #include "llvm/ADT/STLExtras.h" 20 #include "llvm/ADT/SetVector.h" 21 #include "llvm/ADT/SmallPtrSet.h" 22 #include "llvm/ADT/SmallString.h" 23 #include "llvm/ADT/SmallVector.h" 24 #include "llvm/ADT/StringMap.h" 25 #include "llvm/ADT/StringRef.h" 26 #include "llvm/Bitcode/BitcodeCommon.h" 27 #include "llvm/Bitcode/BitcodeReader.h" 28 #include "llvm/Bitcode/LLVMBitCodes.h" 29 #include "llvm/Bitstream/BitCodes.h" 30 #include "llvm/Bitstream/BitstreamWriter.h" 31 #include "llvm/Config/llvm-config.h" 32 #include "llvm/IR/Attributes.h" 33 #include "llvm/IR/BasicBlock.h" 34 #include "llvm/IR/Comdat.h" 35 #include "llvm/IR/Constant.h" 36 #include "llvm/IR/ConstantRangeList.h" 37 #include "llvm/IR/Constants.h" 38 #include "llvm/IR/DebugInfoMetadata.h" 39 #include "llvm/IR/DebugLoc.h" 40 #include "llvm/IR/DerivedTypes.h" 41 #include "llvm/IR/Function.h" 42 #include "llvm/IR/GlobalAlias.h" 43 #include "llvm/IR/GlobalIFunc.h" 44 #include "llvm/IR/GlobalObject.h" 45 #include "llvm/IR/GlobalValue.h" 46 #include "llvm/IR/GlobalVariable.h" 47 #include "llvm/IR/InlineAsm.h" 48 #include "llvm/IR/InstrTypes.h" 49 #include "llvm/IR/Instruction.h" 50 #include "llvm/IR/Instructions.h" 51 #include "llvm/IR/LLVMContext.h" 52 #include "llvm/IR/Metadata.h" 53 #include "llvm/IR/Module.h" 54 #include "llvm/IR/ModuleSummaryIndex.h" 55 #include "llvm/IR/Operator.h" 56 #include "llvm/IR/Type.h" 57 #include "llvm/IR/UseListOrder.h" 58 #include "llvm/IR/Value.h" 59 #include "llvm/IR/ValueSymbolTable.h" 60 #include "llvm/MC/StringTableBuilder.h" 61 #include "llvm/MC/TargetRegistry.h" 62 #include "llvm/Object/IRSymtab.h" 63 #include "llvm/ProfileData/MemProf.h" 64 #include "llvm/Support/AtomicOrdering.h" 65 #include "llvm/Support/Casting.h" 66 #include "llvm/Support/CommandLine.h" 67 #include "llvm/Support/Endian.h" 68 #include "llvm/Support/Error.h" 69 #include "llvm/Support/ErrorHandling.h" 70 #include "llvm/Support/MathExtras.h" 71 #include "llvm/Support/SHA1.h" 72 #include "llvm/Support/raw_ostream.h" 73 #include "llvm/TargetParser/Triple.h" 74 #include <algorithm> 75 #include <cassert> 76 #include <cstddef> 77 #include <cstdint> 78 #include <iterator> 79 #include <map> 80 #include <memory> 81 #include <optional> 82 #include <string> 83 #include <utility> 84 #include <vector> 85 86 using namespace llvm; 87 using namespace llvm::memprof; 88 89 static cl::opt<unsigned> 90 IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25), 91 cl::desc("Number of metadatas above which we emit an index " 92 "to enable lazy-loading")); 93 static cl::opt<uint32_t> FlushThreshold( 94 "bitcode-flush-threshold", cl::Hidden, cl::init(512), 95 cl::desc("The threshold (unit M) for flushing LLVM bitcode.")); 96 97 static cl::opt<bool> WriteRelBFToSummary( 98 "write-relbf-to-summary", cl::Hidden, cl::init(false), 99 cl::desc("Write relative block frequency to function summary ")); 100 101 namespace llvm { 102 extern FunctionSummary::ForceSummaryHotnessType ForceSummaryEdgesCold; 103 } 104 105 extern bool WriteNewDbgInfoFormatToBitcode; 106 extern llvm::cl::opt<bool> UseNewDbgInfoFormat; 107 108 namespace { 109 110 /// These are manifest constants used by the bitcode writer. They do not need to 111 /// be kept in sync with the reader, but need to be consistent within this file. 112 enum { 113 // VALUE_SYMTAB_BLOCK abbrev id's. 114 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV, 115 VST_ENTRY_7_ABBREV, 116 VST_ENTRY_6_ABBREV, 117 VST_BBENTRY_6_ABBREV, 118 119 // CONSTANTS_BLOCK abbrev id's. 120 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV, 121 CONSTANTS_INTEGER_ABBREV, 122 CONSTANTS_CE_CAST_Abbrev, 123 CONSTANTS_NULL_Abbrev, 124 125 // FUNCTION_BLOCK abbrev id's. 126 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV, 127 FUNCTION_INST_UNOP_ABBREV, 128 FUNCTION_INST_UNOP_FLAGS_ABBREV, 129 FUNCTION_INST_BINOP_ABBREV, 130 FUNCTION_INST_BINOP_FLAGS_ABBREV, 131 FUNCTION_INST_CAST_ABBREV, 132 FUNCTION_INST_CAST_FLAGS_ABBREV, 133 FUNCTION_INST_RET_VOID_ABBREV, 134 FUNCTION_INST_RET_VAL_ABBREV, 135 FUNCTION_INST_UNREACHABLE_ABBREV, 136 FUNCTION_INST_GEP_ABBREV, 137 FUNCTION_DEBUG_RECORD_VALUE_ABBREV, 138 }; 139 140 /// Abstract class to manage the bitcode writing, subclassed for each bitcode 141 /// file type. 142 class BitcodeWriterBase { 143 protected: 144 /// The stream created and owned by the client. 145 BitstreamWriter &Stream; 146 147 StringTableBuilder &StrtabBuilder; 148 149 public: 150 /// Constructs a BitcodeWriterBase object that writes to the provided 151 /// \p Stream. 152 BitcodeWriterBase(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder) 153 : Stream(Stream), StrtabBuilder(StrtabBuilder) {} 154 155 protected: 156 void writeModuleVersion(); 157 }; 158 159 void BitcodeWriterBase::writeModuleVersion() { 160 // VERSION: [version#] 161 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, ArrayRef<uint64_t>{2}); 162 } 163 164 /// Base class to manage the module bitcode writing, currently subclassed for 165 /// ModuleBitcodeWriter and ThinLinkBitcodeWriter. 166 class ModuleBitcodeWriterBase : public BitcodeWriterBase { 167 protected: 168 /// The Module to write to bitcode. 169 const Module &M; 170 171 /// Enumerates ids for all values in the module. 172 ValueEnumerator VE; 173 174 /// Optional per-module index to write for ThinLTO. 175 const ModuleSummaryIndex *Index; 176 177 /// Map that holds the correspondence between GUIDs in the summary index, 178 /// that came from indirect call profiles, and a value id generated by this 179 /// class to use in the VST and summary block records. 180 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap; 181 182 /// Tracks the last value id recorded in the GUIDToValueMap. 183 unsigned GlobalValueId; 184 185 /// Saves the offset of the VSTOffset record that must eventually be 186 /// backpatched with the offset of the actual VST. 187 uint64_t VSTOffsetPlaceholder = 0; 188 189 public: 190 /// Constructs a ModuleBitcodeWriterBase object for the given Module, 191 /// writing to the provided \p Buffer. 192 ModuleBitcodeWriterBase(const Module &M, StringTableBuilder &StrtabBuilder, 193 BitstreamWriter &Stream, 194 bool ShouldPreserveUseListOrder, 195 const ModuleSummaryIndex *Index) 196 : BitcodeWriterBase(Stream, StrtabBuilder), M(M), 197 VE(M, ShouldPreserveUseListOrder), Index(Index) { 198 // Assign ValueIds to any callee values in the index that came from 199 // indirect call profiles and were recorded as a GUID not a Value* 200 // (which would have been assigned an ID by the ValueEnumerator). 201 // The starting ValueId is just after the number of values in the 202 // ValueEnumerator, so that they can be emitted in the VST. 203 GlobalValueId = VE.getValues().size(); 204 if (!Index) 205 return; 206 for (const auto &GUIDSummaryLists : *Index) 207 // Examine all summaries for this GUID. 208 for (auto &Summary : GUIDSummaryLists.second.SummaryList) 209 if (auto FS = dyn_cast<FunctionSummary>(Summary.get())) { 210 // For each call in the function summary, see if the call 211 // is to a GUID (which means it is for an indirect call, 212 // otherwise we would have a Value for it). If so, synthesize 213 // a value id. 214 for (auto &CallEdge : FS->calls()) 215 if (!CallEdge.first.haveGVs() || !CallEdge.first.getValue()) 216 assignValueId(CallEdge.first.getGUID()); 217 218 // For each referenced variables in the function summary, see if the 219 // variable is represented by a GUID (as opposed to a symbol to 220 // declarations or definitions in the module). If so, synthesize a 221 // value id. 222 for (auto &RefEdge : FS->refs()) 223 if (!RefEdge.haveGVs() || !RefEdge.getValue()) 224 assignValueId(RefEdge.getGUID()); 225 } 226 } 227 228 protected: 229 void writePerModuleGlobalValueSummary(); 230 231 private: 232 void writePerModuleFunctionSummaryRecord( 233 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary, 234 unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev, 235 unsigned CallsiteAbbrev, unsigned AllocAbbrev, unsigned ContextIdAbbvId, 236 const Function &F, DenseMap<CallStackId, LinearCallStackId> &CallStackPos, 237 CallStackId &CallStackCount); 238 void writeModuleLevelReferences(const GlobalVariable &V, 239 SmallVector<uint64_t, 64> &NameVals, 240 unsigned FSModRefsAbbrev, 241 unsigned FSModVTableRefsAbbrev); 242 243 void assignValueId(GlobalValue::GUID ValGUID) { 244 GUIDToValueIdMap[ValGUID] = ++GlobalValueId; 245 } 246 247 unsigned getValueId(GlobalValue::GUID ValGUID) { 248 const auto &VMI = GUIDToValueIdMap.find(ValGUID); 249 // Expect that any GUID value had a value Id assigned by an 250 // earlier call to assignValueId. 251 assert(VMI != GUIDToValueIdMap.end() && 252 "GUID does not have assigned value Id"); 253 return VMI->second; 254 } 255 256 // Helper to get the valueId for the type of value recorded in VI. 257 unsigned getValueId(ValueInfo VI) { 258 if (!VI.haveGVs() || !VI.getValue()) 259 return getValueId(VI.getGUID()); 260 return VE.getValueID(VI.getValue()); 261 } 262 263 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; } 264 }; 265 266 /// Class to manage the bitcode writing for a module. 267 class ModuleBitcodeWriter : public ModuleBitcodeWriterBase { 268 /// True if a module hash record should be written. 269 bool GenerateHash; 270 271 /// If non-null, when GenerateHash is true, the resulting hash is written 272 /// into ModHash. 273 ModuleHash *ModHash; 274 275 SHA1 Hasher; 276 277 /// The start bit of the identification block. 278 uint64_t BitcodeStartBit; 279 280 public: 281 /// Constructs a ModuleBitcodeWriter object for the given Module, 282 /// writing to the provided \p Buffer. 283 ModuleBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder, 284 BitstreamWriter &Stream, bool ShouldPreserveUseListOrder, 285 const ModuleSummaryIndex *Index, bool GenerateHash, 286 ModuleHash *ModHash = nullptr) 287 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream, 288 ShouldPreserveUseListOrder, Index), 289 GenerateHash(GenerateHash), ModHash(ModHash), 290 BitcodeStartBit(Stream.GetCurrentBitNo()) {} 291 292 /// Emit the current module to the bitstream. 293 void write(); 294 295 private: 296 uint64_t bitcodeStartBit() { return BitcodeStartBit; } 297 298 size_t addToStrtab(StringRef Str); 299 300 void writeAttributeGroupTable(); 301 void writeAttributeTable(); 302 void writeTypeTable(); 303 void writeComdats(); 304 void writeValueSymbolTableForwardDecl(); 305 void writeModuleInfo(); 306 void writeValueAsMetadata(const ValueAsMetadata *MD, 307 SmallVectorImpl<uint64_t> &Record); 308 void writeMDTuple(const MDTuple *N, SmallVectorImpl<uint64_t> &Record, 309 unsigned Abbrev); 310 unsigned createDILocationAbbrev(); 311 void writeDILocation(const DILocation *N, SmallVectorImpl<uint64_t> &Record, 312 unsigned &Abbrev); 313 unsigned createGenericDINodeAbbrev(); 314 void writeGenericDINode(const GenericDINode *N, 315 SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev); 316 void writeDISubrange(const DISubrange *N, SmallVectorImpl<uint64_t> &Record, 317 unsigned Abbrev); 318 void writeDIGenericSubrange(const DIGenericSubrange *N, 319 SmallVectorImpl<uint64_t> &Record, 320 unsigned Abbrev); 321 void writeDIEnumerator(const DIEnumerator *N, 322 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 323 void writeDIBasicType(const DIBasicType *N, SmallVectorImpl<uint64_t> &Record, 324 unsigned Abbrev); 325 void writeDIStringType(const DIStringType *N, 326 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 327 void writeDIDerivedType(const DIDerivedType *N, 328 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 329 void writeDICompositeType(const DICompositeType *N, 330 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 331 void writeDISubroutineType(const DISubroutineType *N, 332 SmallVectorImpl<uint64_t> &Record, 333 unsigned Abbrev); 334 void writeDIFile(const DIFile *N, SmallVectorImpl<uint64_t> &Record, 335 unsigned Abbrev); 336 void writeDICompileUnit(const DICompileUnit *N, 337 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 338 void writeDISubprogram(const DISubprogram *N, 339 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 340 void writeDILexicalBlock(const DILexicalBlock *N, 341 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 342 void writeDILexicalBlockFile(const DILexicalBlockFile *N, 343 SmallVectorImpl<uint64_t> &Record, 344 unsigned Abbrev); 345 void writeDICommonBlock(const DICommonBlock *N, 346 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 347 void writeDINamespace(const DINamespace *N, SmallVectorImpl<uint64_t> &Record, 348 unsigned Abbrev); 349 void writeDIMacro(const DIMacro *N, SmallVectorImpl<uint64_t> &Record, 350 unsigned Abbrev); 351 void writeDIMacroFile(const DIMacroFile *N, SmallVectorImpl<uint64_t> &Record, 352 unsigned Abbrev); 353 void writeDIArgList(const DIArgList *N, SmallVectorImpl<uint64_t> &Record); 354 void writeDIModule(const DIModule *N, SmallVectorImpl<uint64_t> &Record, 355 unsigned Abbrev); 356 void writeDIAssignID(const DIAssignID *N, SmallVectorImpl<uint64_t> &Record, 357 unsigned Abbrev); 358 void writeDITemplateTypeParameter(const DITemplateTypeParameter *N, 359 SmallVectorImpl<uint64_t> &Record, 360 unsigned Abbrev); 361 void writeDITemplateValueParameter(const DITemplateValueParameter *N, 362 SmallVectorImpl<uint64_t> &Record, 363 unsigned Abbrev); 364 void writeDIGlobalVariable(const DIGlobalVariable *N, 365 SmallVectorImpl<uint64_t> &Record, 366 unsigned Abbrev); 367 void writeDILocalVariable(const DILocalVariable *N, 368 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 369 void writeDILabel(const DILabel *N, 370 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 371 void writeDIExpression(const DIExpression *N, 372 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 373 void writeDIGlobalVariableExpression(const DIGlobalVariableExpression *N, 374 SmallVectorImpl<uint64_t> &Record, 375 unsigned Abbrev); 376 void writeDIObjCProperty(const DIObjCProperty *N, 377 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 378 void writeDIImportedEntity(const DIImportedEntity *N, 379 SmallVectorImpl<uint64_t> &Record, 380 unsigned Abbrev); 381 unsigned createNamedMetadataAbbrev(); 382 void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record); 383 unsigned createMetadataStringsAbbrev(); 384 void writeMetadataStrings(ArrayRef<const Metadata *> Strings, 385 SmallVectorImpl<uint64_t> &Record); 386 void writeMetadataRecords(ArrayRef<const Metadata *> MDs, 387 SmallVectorImpl<uint64_t> &Record, 388 std::vector<unsigned> *MDAbbrevs = nullptr, 389 std::vector<uint64_t> *IndexPos = nullptr); 390 void writeModuleMetadata(); 391 void writeFunctionMetadata(const Function &F); 392 void writeFunctionMetadataAttachment(const Function &F); 393 void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record, 394 const GlobalObject &GO); 395 void writeModuleMetadataKinds(); 396 void writeOperandBundleTags(); 397 void writeSyncScopeNames(); 398 void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal); 399 void writeModuleConstants(); 400 bool pushValueAndType(const Value *V, unsigned InstID, 401 SmallVectorImpl<unsigned> &Vals); 402 bool pushValueOrMetadata(const Value *V, unsigned InstID, 403 SmallVectorImpl<unsigned> &Vals); 404 void writeOperandBundles(const CallBase &CB, unsigned InstID); 405 void pushValue(const Value *V, unsigned InstID, 406 SmallVectorImpl<unsigned> &Vals); 407 void pushValueSigned(const Value *V, unsigned InstID, 408 SmallVectorImpl<uint64_t> &Vals); 409 void writeInstruction(const Instruction &I, unsigned InstID, 410 SmallVectorImpl<unsigned> &Vals); 411 void writeFunctionLevelValueSymbolTable(const ValueSymbolTable &VST); 412 void writeGlobalValueSymbolTable( 413 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex); 414 void writeUseList(UseListOrder &&Order); 415 void writeUseListBlock(const Function *F); 416 void 417 writeFunction(const Function &F, 418 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex); 419 void writeBlockInfo(); 420 void writeModuleHash(StringRef View); 421 422 unsigned getEncodedSyncScopeID(SyncScope::ID SSID) { 423 return unsigned(SSID); 424 } 425 426 unsigned getEncodedAlign(MaybeAlign Alignment) { return encode(Alignment); } 427 }; 428 429 /// Class to manage the bitcode writing for a combined index. 430 class IndexBitcodeWriter : public BitcodeWriterBase { 431 /// The combined index to write to bitcode. 432 const ModuleSummaryIndex &Index; 433 434 /// When writing combined summaries, provides the set of global value 435 /// summaries for which the value (function, function alias, etc) should be 436 /// imported as a declaration. 437 const GVSummaryPtrSet *DecSummaries = nullptr; 438 439 /// When writing a subset of the index for distributed backends, client 440 /// provides a map of modules to the corresponding GUIDs/summaries to write. 441 const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex; 442 443 /// Map that holds the correspondence between the GUID used in the combined 444 /// index and a value id generated by this class to use in references. 445 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap; 446 447 // The stack ids used by this index, which will be a subset of those in 448 // the full index in the case of distributed indexes. 449 std::vector<uint64_t> StackIds; 450 451 // Keep a map of the stack id indices used by records being written for this 452 // index to the index of the corresponding stack id in the above StackIds 453 // vector. Ensures we write each referenced stack id once. 454 DenseMap<unsigned, unsigned> StackIdIndicesToIndex; 455 456 /// Tracks the last value id recorded in the GUIDToValueMap. 457 unsigned GlobalValueId = 0; 458 459 /// Tracks the assignment of module paths in the module path string table to 460 /// an id assigned for use in summary references to the module path. 461 DenseMap<StringRef, uint64_t> ModuleIdMap; 462 463 public: 464 /// Constructs a IndexBitcodeWriter object for the given combined index, 465 /// writing to the provided \p Buffer. When writing a subset of the index 466 /// for a distributed backend, provide a \p ModuleToSummariesForIndex map. 467 /// If provided, \p DecSummaries specifies the set of summaries for which 468 /// the corresponding functions or aliased functions should be imported as a 469 /// declaration (but not definition) for each module. 470 IndexBitcodeWriter( 471 BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder, 472 const ModuleSummaryIndex &Index, 473 const GVSummaryPtrSet *DecSummaries = nullptr, 474 const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex = nullptr) 475 : BitcodeWriterBase(Stream, StrtabBuilder), Index(Index), 476 DecSummaries(DecSummaries), 477 ModuleToSummariesForIndex(ModuleToSummariesForIndex) { 478 479 // See if the StackIdIndex was already added to the StackId map and 480 // vector. If not, record it. 481 auto RecordStackIdReference = [&](unsigned StackIdIndex) { 482 // If the StackIdIndex is not yet in the map, the below insert ensures 483 // that it will point to the new StackIds vector entry we push to just 484 // below. 485 auto Inserted = 486 StackIdIndicesToIndex.insert({StackIdIndex, StackIds.size()}); 487 if (Inserted.second) 488 StackIds.push_back(Index.getStackIdAtIndex(StackIdIndex)); 489 }; 490 491 // Assign unique value ids to all summaries to be written, for use 492 // in writing out the call graph edges. Save the mapping from GUID 493 // to the new global value id to use when writing those edges, which 494 // are currently saved in the index in terms of GUID. 495 forEachSummary([&](GVInfo I, bool IsAliasee) { 496 GUIDToValueIdMap[I.first] = ++GlobalValueId; 497 if (IsAliasee) 498 return; 499 auto *FS = dyn_cast<FunctionSummary>(I.second); 500 if (!FS) 501 return; 502 // Record all stack id indices actually used in the summary entries being 503 // written, so that we can compact them in the case of distributed ThinLTO 504 // indexes. 505 for (auto &CI : FS->callsites()) { 506 // If the stack id list is empty, this callsite info was synthesized for 507 // a missing tail call frame. Ensure that the callee's GUID gets a value 508 // id. Normally we only generate these for defined summaries, which in 509 // the case of distributed ThinLTO is only the functions already defined 510 // in the module or that we want to import. We don't bother to include 511 // all the callee symbols as they aren't normally needed in the backend. 512 // However, for the synthesized callsite infos we do need the callee 513 // GUID in the backend so that we can correlate the identified callee 514 // with this callsite info (which for non-tail calls is done by the 515 // ordering of the callsite infos and verified via stack ids). 516 if (CI.StackIdIndices.empty()) { 517 GUIDToValueIdMap[CI.Callee.getGUID()] = ++GlobalValueId; 518 continue; 519 } 520 for (auto Idx : CI.StackIdIndices) 521 RecordStackIdReference(Idx); 522 } 523 for (auto &AI : FS->allocs()) 524 for (auto &MIB : AI.MIBs) 525 for (auto Idx : MIB.StackIdIndices) 526 RecordStackIdReference(Idx); 527 }); 528 } 529 530 /// The below iterator returns the GUID and associated summary. 531 using GVInfo = std::pair<GlobalValue::GUID, GlobalValueSummary *>; 532 533 /// Calls the callback for each value GUID and summary to be written to 534 /// bitcode. This hides the details of whether they are being pulled from the 535 /// entire index or just those in a provided ModuleToSummariesForIndex map. 536 template<typename Functor> 537 void forEachSummary(Functor Callback) { 538 if (ModuleToSummariesForIndex) { 539 for (auto &M : *ModuleToSummariesForIndex) 540 for (auto &Summary : M.second) { 541 Callback(Summary, false); 542 // Ensure aliasee is handled, e.g. for assigning a valueId, 543 // even if we are not importing the aliasee directly (the 544 // imported alias will contain a copy of aliasee). 545 if (auto *AS = dyn_cast<AliasSummary>(Summary.getSecond())) 546 Callback({AS->getAliaseeGUID(), &AS->getAliasee()}, true); 547 } 548 } else { 549 for (auto &Summaries : Index) 550 for (auto &Summary : Summaries.second.SummaryList) 551 Callback({Summaries.first, Summary.get()}, false); 552 } 553 } 554 555 /// Calls the callback for each entry in the modulePaths StringMap that 556 /// should be written to the module path string table. This hides the details 557 /// of whether they are being pulled from the entire index or just those in a 558 /// provided ModuleToSummariesForIndex map. 559 template <typename Functor> void forEachModule(Functor Callback) { 560 if (ModuleToSummariesForIndex) { 561 for (const auto &M : *ModuleToSummariesForIndex) { 562 const auto &MPI = Index.modulePaths().find(M.first); 563 if (MPI == Index.modulePaths().end()) { 564 // This should only happen if the bitcode file was empty, in which 565 // case we shouldn't be importing (the ModuleToSummariesForIndex 566 // would only include the module we are writing and index for). 567 assert(ModuleToSummariesForIndex->size() == 1); 568 continue; 569 } 570 Callback(*MPI); 571 } 572 } else { 573 // Since StringMap iteration order isn't guaranteed, order by path string 574 // first. 575 // FIXME: Make this a vector of StringMapEntry instead to avoid the later 576 // map lookup. 577 std::vector<StringRef> ModulePaths; 578 for (auto &[ModPath, _] : Index.modulePaths()) 579 ModulePaths.push_back(ModPath); 580 llvm::sort(ModulePaths.begin(), ModulePaths.end()); 581 for (auto &ModPath : ModulePaths) 582 Callback(*Index.modulePaths().find(ModPath)); 583 } 584 } 585 586 /// Main entry point for writing a combined index to bitcode. 587 void write(); 588 589 private: 590 void writeModStrings(); 591 void writeCombinedGlobalValueSummary(); 592 593 std::optional<unsigned> getValueId(GlobalValue::GUID ValGUID) { 594 auto VMI = GUIDToValueIdMap.find(ValGUID); 595 if (VMI == GUIDToValueIdMap.end()) 596 return std::nullopt; 597 return VMI->second; 598 } 599 600 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; } 601 }; 602 603 } // end anonymous namespace 604 605 static unsigned getEncodedCastOpcode(unsigned Opcode) { 606 switch (Opcode) { 607 default: llvm_unreachable("Unknown cast instruction!"); 608 case Instruction::Trunc : return bitc::CAST_TRUNC; 609 case Instruction::ZExt : return bitc::CAST_ZEXT; 610 case Instruction::SExt : return bitc::CAST_SEXT; 611 case Instruction::FPToUI : return bitc::CAST_FPTOUI; 612 case Instruction::FPToSI : return bitc::CAST_FPTOSI; 613 case Instruction::UIToFP : return bitc::CAST_UITOFP; 614 case Instruction::SIToFP : return bitc::CAST_SITOFP; 615 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC; 616 case Instruction::FPExt : return bitc::CAST_FPEXT; 617 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT; 618 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR; 619 case Instruction::BitCast : return bitc::CAST_BITCAST; 620 case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST; 621 } 622 } 623 624 static unsigned getEncodedUnaryOpcode(unsigned Opcode) { 625 switch (Opcode) { 626 default: llvm_unreachable("Unknown binary instruction!"); 627 case Instruction::FNeg: return bitc::UNOP_FNEG; 628 } 629 } 630 631 static unsigned getEncodedBinaryOpcode(unsigned Opcode) { 632 switch (Opcode) { 633 default: llvm_unreachable("Unknown binary instruction!"); 634 case Instruction::Add: 635 case Instruction::FAdd: return bitc::BINOP_ADD; 636 case Instruction::Sub: 637 case Instruction::FSub: return bitc::BINOP_SUB; 638 case Instruction::Mul: 639 case Instruction::FMul: return bitc::BINOP_MUL; 640 case Instruction::UDiv: return bitc::BINOP_UDIV; 641 case Instruction::FDiv: 642 case Instruction::SDiv: return bitc::BINOP_SDIV; 643 case Instruction::URem: return bitc::BINOP_UREM; 644 case Instruction::FRem: 645 case Instruction::SRem: return bitc::BINOP_SREM; 646 case Instruction::Shl: return bitc::BINOP_SHL; 647 case Instruction::LShr: return bitc::BINOP_LSHR; 648 case Instruction::AShr: return bitc::BINOP_ASHR; 649 case Instruction::And: return bitc::BINOP_AND; 650 case Instruction::Or: return bitc::BINOP_OR; 651 case Instruction::Xor: return bitc::BINOP_XOR; 652 } 653 } 654 655 static unsigned getEncodedRMWOperation(AtomicRMWInst::BinOp Op) { 656 switch (Op) { 657 default: llvm_unreachable("Unknown RMW operation!"); 658 case AtomicRMWInst::Xchg: return bitc::RMW_XCHG; 659 case AtomicRMWInst::Add: return bitc::RMW_ADD; 660 case AtomicRMWInst::Sub: return bitc::RMW_SUB; 661 case AtomicRMWInst::And: return bitc::RMW_AND; 662 case AtomicRMWInst::Nand: return bitc::RMW_NAND; 663 case AtomicRMWInst::Or: return bitc::RMW_OR; 664 case AtomicRMWInst::Xor: return bitc::RMW_XOR; 665 case AtomicRMWInst::Max: return bitc::RMW_MAX; 666 case AtomicRMWInst::Min: return bitc::RMW_MIN; 667 case AtomicRMWInst::UMax: return bitc::RMW_UMAX; 668 case AtomicRMWInst::UMin: return bitc::RMW_UMIN; 669 case AtomicRMWInst::FAdd: return bitc::RMW_FADD; 670 case AtomicRMWInst::FSub: return bitc::RMW_FSUB; 671 case AtomicRMWInst::FMax: return bitc::RMW_FMAX; 672 case AtomicRMWInst::FMin: return bitc::RMW_FMIN; 673 case AtomicRMWInst::UIncWrap: 674 return bitc::RMW_UINC_WRAP; 675 case AtomicRMWInst::UDecWrap: 676 return bitc::RMW_UDEC_WRAP; 677 case AtomicRMWInst::USubCond: 678 return bitc::RMW_USUB_COND; 679 case AtomicRMWInst::USubSat: 680 return bitc::RMW_USUB_SAT; 681 } 682 } 683 684 static unsigned getEncodedOrdering(AtomicOrdering Ordering) { 685 switch (Ordering) { 686 case AtomicOrdering::NotAtomic: return bitc::ORDERING_NOTATOMIC; 687 case AtomicOrdering::Unordered: return bitc::ORDERING_UNORDERED; 688 case AtomicOrdering::Monotonic: return bitc::ORDERING_MONOTONIC; 689 case AtomicOrdering::Acquire: return bitc::ORDERING_ACQUIRE; 690 case AtomicOrdering::Release: return bitc::ORDERING_RELEASE; 691 case AtomicOrdering::AcquireRelease: return bitc::ORDERING_ACQREL; 692 case AtomicOrdering::SequentiallyConsistent: return bitc::ORDERING_SEQCST; 693 } 694 llvm_unreachable("Invalid ordering"); 695 } 696 697 static void writeStringRecord(BitstreamWriter &Stream, unsigned Code, 698 StringRef Str, unsigned AbbrevToUse) { 699 SmallVector<unsigned, 64> Vals; 700 701 // Code: [strchar x N] 702 for (char C : Str) { 703 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(C)) 704 AbbrevToUse = 0; 705 Vals.push_back(C); 706 } 707 708 // Emit the finished record. 709 Stream.EmitRecord(Code, Vals, AbbrevToUse); 710 } 711 712 static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) { 713 switch (Kind) { 714 case Attribute::Alignment: 715 return bitc::ATTR_KIND_ALIGNMENT; 716 case Attribute::AllocAlign: 717 return bitc::ATTR_KIND_ALLOC_ALIGN; 718 case Attribute::AllocSize: 719 return bitc::ATTR_KIND_ALLOC_SIZE; 720 case Attribute::AlwaysInline: 721 return bitc::ATTR_KIND_ALWAYS_INLINE; 722 case Attribute::Builtin: 723 return bitc::ATTR_KIND_BUILTIN; 724 case Attribute::ByVal: 725 return bitc::ATTR_KIND_BY_VAL; 726 case Attribute::Convergent: 727 return bitc::ATTR_KIND_CONVERGENT; 728 case Attribute::InAlloca: 729 return bitc::ATTR_KIND_IN_ALLOCA; 730 case Attribute::Cold: 731 return bitc::ATTR_KIND_COLD; 732 case Attribute::DisableSanitizerInstrumentation: 733 return bitc::ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION; 734 case Attribute::FnRetThunkExtern: 735 return bitc::ATTR_KIND_FNRETTHUNK_EXTERN; 736 case Attribute::Hot: 737 return bitc::ATTR_KIND_HOT; 738 case Attribute::ElementType: 739 return bitc::ATTR_KIND_ELEMENTTYPE; 740 case Attribute::HybridPatchable: 741 return bitc::ATTR_KIND_HYBRID_PATCHABLE; 742 case Attribute::InlineHint: 743 return bitc::ATTR_KIND_INLINE_HINT; 744 case Attribute::InReg: 745 return bitc::ATTR_KIND_IN_REG; 746 case Attribute::JumpTable: 747 return bitc::ATTR_KIND_JUMP_TABLE; 748 case Attribute::MinSize: 749 return bitc::ATTR_KIND_MIN_SIZE; 750 case Attribute::AllocatedPointer: 751 return bitc::ATTR_KIND_ALLOCATED_POINTER; 752 case Attribute::AllocKind: 753 return bitc::ATTR_KIND_ALLOC_KIND; 754 case Attribute::Memory: 755 return bitc::ATTR_KIND_MEMORY; 756 case Attribute::NoFPClass: 757 return bitc::ATTR_KIND_NOFPCLASS; 758 case Attribute::Naked: 759 return bitc::ATTR_KIND_NAKED; 760 case Attribute::Nest: 761 return bitc::ATTR_KIND_NEST; 762 case Attribute::NoAlias: 763 return bitc::ATTR_KIND_NO_ALIAS; 764 case Attribute::NoBuiltin: 765 return bitc::ATTR_KIND_NO_BUILTIN; 766 case Attribute::NoCallback: 767 return bitc::ATTR_KIND_NO_CALLBACK; 768 case Attribute::NoCapture: 769 return bitc::ATTR_KIND_NO_CAPTURE; 770 case Attribute::NoDivergenceSource: 771 return bitc::ATTR_KIND_NO_DIVERGENCE_SOURCE; 772 case Attribute::NoDuplicate: 773 return bitc::ATTR_KIND_NO_DUPLICATE; 774 case Attribute::NoFree: 775 return bitc::ATTR_KIND_NOFREE; 776 case Attribute::NoImplicitFloat: 777 return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT; 778 case Attribute::NoInline: 779 return bitc::ATTR_KIND_NO_INLINE; 780 case Attribute::NoRecurse: 781 return bitc::ATTR_KIND_NO_RECURSE; 782 case Attribute::NoMerge: 783 return bitc::ATTR_KIND_NO_MERGE; 784 case Attribute::NonLazyBind: 785 return bitc::ATTR_KIND_NON_LAZY_BIND; 786 case Attribute::NonNull: 787 return bitc::ATTR_KIND_NON_NULL; 788 case Attribute::Dereferenceable: 789 return bitc::ATTR_KIND_DEREFERENCEABLE; 790 case Attribute::DereferenceableOrNull: 791 return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL; 792 case Attribute::NoRedZone: 793 return bitc::ATTR_KIND_NO_RED_ZONE; 794 case Attribute::NoReturn: 795 return bitc::ATTR_KIND_NO_RETURN; 796 case Attribute::NoSync: 797 return bitc::ATTR_KIND_NOSYNC; 798 case Attribute::NoCfCheck: 799 return bitc::ATTR_KIND_NOCF_CHECK; 800 case Attribute::NoProfile: 801 return bitc::ATTR_KIND_NO_PROFILE; 802 case Attribute::SkipProfile: 803 return bitc::ATTR_KIND_SKIP_PROFILE; 804 case Attribute::NoUnwind: 805 return bitc::ATTR_KIND_NO_UNWIND; 806 case Attribute::NoSanitizeBounds: 807 return bitc::ATTR_KIND_NO_SANITIZE_BOUNDS; 808 case Attribute::NoSanitizeCoverage: 809 return bitc::ATTR_KIND_NO_SANITIZE_COVERAGE; 810 case Attribute::NullPointerIsValid: 811 return bitc::ATTR_KIND_NULL_POINTER_IS_VALID; 812 case Attribute::OptimizeForDebugging: 813 return bitc::ATTR_KIND_OPTIMIZE_FOR_DEBUGGING; 814 case Attribute::OptForFuzzing: 815 return bitc::ATTR_KIND_OPT_FOR_FUZZING; 816 case Attribute::OptimizeForSize: 817 return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE; 818 case Attribute::OptimizeNone: 819 return bitc::ATTR_KIND_OPTIMIZE_NONE; 820 case Attribute::ReadNone: 821 return bitc::ATTR_KIND_READ_NONE; 822 case Attribute::ReadOnly: 823 return bitc::ATTR_KIND_READ_ONLY; 824 case Attribute::Returned: 825 return bitc::ATTR_KIND_RETURNED; 826 case Attribute::ReturnsTwice: 827 return bitc::ATTR_KIND_RETURNS_TWICE; 828 case Attribute::SExt: 829 return bitc::ATTR_KIND_S_EXT; 830 case Attribute::Speculatable: 831 return bitc::ATTR_KIND_SPECULATABLE; 832 case Attribute::StackAlignment: 833 return bitc::ATTR_KIND_STACK_ALIGNMENT; 834 case Attribute::StackProtect: 835 return bitc::ATTR_KIND_STACK_PROTECT; 836 case Attribute::StackProtectReq: 837 return bitc::ATTR_KIND_STACK_PROTECT_REQ; 838 case Attribute::StackProtectStrong: 839 return bitc::ATTR_KIND_STACK_PROTECT_STRONG; 840 case Attribute::SafeStack: 841 return bitc::ATTR_KIND_SAFESTACK; 842 case Attribute::ShadowCallStack: 843 return bitc::ATTR_KIND_SHADOWCALLSTACK; 844 case Attribute::StrictFP: 845 return bitc::ATTR_KIND_STRICT_FP; 846 case Attribute::StructRet: 847 return bitc::ATTR_KIND_STRUCT_RET; 848 case Attribute::SanitizeAddress: 849 return bitc::ATTR_KIND_SANITIZE_ADDRESS; 850 case Attribute::SanitizeHWAddress: 851 return bitc::ATTR_KIND_SANITIZE_HWADDRESS; 852 case Attribute::SanitizeThread: 853 return bitc::ATTR_KIND_SANITIZE_THREAD; 854 case Attribute::SanitizeMemory: 855 return bitc::ATTR_KIND_SANITIZE_MEMORY; 856 case Attribute::SanitizeNumericalStability: 857 return bitc::ATTR_KIND_SANITIZE_NUMERICAL_STABILITY; 858 case Attribute::SanitizeRealtime: 859 return bitc::ATTR_KIND_SANITIZE_REALTIME; 860 case Attribute::SanitizeRealtimeBlocking: 861 return bitc::ATTR_KIND_SANITIZE_REALTIME_BLOCKING; 862 case Attribute::SpeculativeLoadHardening: 863 return bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING; 864 case Attribute::SwiftError: 865 return bitc::ATTR_KIND_SWIFT_ERROR; 866 case Attribute::SwiftSelf: 867 return bitc::ATTR_KIND_SWIFT_SELF; 868 case Attribute::SwiftAsync: 869 return bitc::ATTR_KIND_SWIFT_ASYNC; 870 case Attribute::UWTable: 871 return bitc::ATTR_KIND_UW_TABLE; 872 case Attribute::VScaleRange: 873 return bitc::ATTR_KIND_VSCALE_RANGE; 874 case Attribute::WillReturn: 875 return bitc::ATTR_KIND_WILLRETURN; 876 case Attribute::WriteOnly: 877 return bitc::ATTR_KIND_WRITEONLY; 878 case Attribute::ZExt: 879 return bitc::ATTR_KIND_Z_EXT; 880 case Attribute::ImmArg: 881 return bitc::ATTR_KIND_IMMARG; 882 case Attribute::SanitizeMemTag: 883 return bitc::ATTR_KIND_SANITIZE_MEMTAG; 884 case Attribute::Preallocated: 885 return bitc::ATTR_KIND_PREALLOCATED; 886 case Attribute::NoUndef: 887 return bitc::ATTR_KIND_NOUNDEF; 888 case Attribute::ByRef: 889 return bitc::ATTR_KIND_BYREF; 890 case Attribute::MustProgress: 891 return bitc::ATTR_KIND_MUSTPROGRESS; 892 case Attribute::PresplitCoroutine: 893 return bitc::ATTR_KIND_PRESPLIT_COROUTINE; 894 case Attribute::Writable: 895 return bitc::ATTR_KIND_WRITABLE; 896 case Attribute::CoroDestroyOnlyWhenComplete: 897 return bitc::ATTR_KIND_CORO_ONLY_DESTROY_WHEN_COMPLETE; 898 case Attribute::CoroElideSafe: 899 return bitc::ATTR_KIND_CORO_ELIDE_SAFE; 900 case Attribute::DeadOnUnwind: 901 return bitc::ATTR_KIND_DEAD_ON_UNWIND; 902 case Attribute::Range: 903 return bitc::ATTR_KIND_RANGE; 904 case Attribute::Initializes: 905 return bitc::ATTR_KIND_INITIALIZES; 906 case Attribute::NoExt: 907 return bitc::ATTR_KIND_NO_EXT; 908 case Attribute::EndAttrKinds: 909 llvm_unreachable("Can not encode end-attribute kinds marker."); 910 case Attribute::None: 911 llvm_unreachable("Can not encode none-attribute."); 912 case Attribute::EmptyKey: 913 case Attribute::TombstoneKey: 914 llvm_unreachable("Trying to encode EmptyKey/TombstoneKey"); 915 } 916 917 llvm_unreachable("Trying to encode unknown attribute"); 918 } 919 920 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) { 921 if ((int64_t)V >= 0) 922 Vals.push_back(V << 1); 923 else 924 Vals.push_back((-V << 1) | 1); 925 } 926 927 static void emitWideAPInt(SmallVectorImpl<uint64_t> &Vals, const APInt &A) { 928 // We have an arbitrary precision integer value to write whose 929 // bit width is > 64. However, in canonical unsigned integer 930 // format it is likely that the high bits are going to be zero. 931 // So, we only write the number of active words. 932 unsigned NumWords = A.getActiveWords(); 933 const uint64_t *RawData = A.getRawData(); 934 for (unsigned i = 0; i < NumWords; i++) 935 emitSignedInt64(Vals, RawData[i]); 936 } 937 938 static void emitConstantRange(SmallVectorImpl<uint64_t> &Record, 939 const ConstantRange &CR, bool EmitBitWidth) { 940 unsigned BitWidth = CR.getBitWidth(); 941 if (EmitBitWidth) 942 Record.push_back(BitWidth); 943 if (BitWidth > 64) { 944 Record.push_back(CR.getLower().getActiveWords() | 945 (uint64_t(CR.getUpper().getActiveWords()) << 32)); 946 emitWideAPInt(Record, CR.getLower()); 947 emitWideAPInt(Record, CR.getUpper()); 948 } else { 949 emitSignedInt64(Record, CR.getLower().getSExtValue()); 950 emitSignedInt64(Record, CR.getUpper().getSExtValue()); 951 } 952 } 953 954 void ModuleBitcodeWriter::writeAttributeGroupTable() { 955 const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps = 956 VE.getAttributeGroups(); 957 if (AttrGrps.empty()) return; 958 959 Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3); 960 961 SmallVector<uint64_t, 64> Record; 962 for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) { 963 unsigned AttrListIndex = Pair.first; 964 AttributeSet AS = Pair.second; 965 Record.push_back(VE.getAttributeGroupID(Pair)); 966 Record.push_back(AttrListIndex); 967 968 for (Attribute Attr : AS) { 969 if (Attr.isEnumAttribute()) { 970 Record.push_back(0); 971 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum())); 972 } else if (Attr.isIntAttribute()) { 973 Record.push_back(1); 974 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum())); 975 Record.push_back(Attr.getValueAsInt()); 976 } else if (Attr.isStringAttribute()) { 977 StringRef Kind = Attr.getKindAsString(); 978 StringRef Val = Attr.getValueAsString(); 979 980 Record.push_back(Val.empty() ? 3 : 4); 981 Record.append(Kind.begin(), Kind.end()); 982 Record.push_back(0); 983 if (!Val.empty()) { 984 Record.append(Val.begin(), Val.end()); 985 Record.push_back(0); 986 } 987 } else if (Attr.isTypeAttribute()) { 988 Type *Ty = Attr.getValueAsType(); 989 Record.push_back(Ty ? 6 : 5); 990 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum())); 991 if (Ty) 992 Record.push_back(VE.getTypeID(Attr.getValueAsType())); 993 } else if (Attr.isConstantRangeAttribute()) { 994 Record.push_back(7); 995 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum())); 996 emitConstantRange(Record, Attr.getValueAsConstantRange(), 997 /*EmitBitWidth=*/true); 998 } else { 999 assert(Attr.isConstantRangeListAttribute()); 1000 Record.push_back(8); 1001 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum())); 1002 ArrayRef<ConstantRange> Val = Attr.getValueAsConstantRangeList(); 1003 Record.push_back(Val.size()); 1004 Record.push_back(Val[0].getBitWidth()); 1005 for (auto &CR : Val) 1006 emitConstantRange(Record, CR, /*EmitBitWidth=*/false); 1007 } 1008 } 1009 1010 Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record); 1011 Record.clear(); 1012 } 1013 1014 Stream.ExitBlock(); 1015 } 1016 1017 void ModuleBitcodeWriter::writeAttributeTable() { 1018 const std::vector<AttributeList> &Attrs = VE.getAttributeLists(); 1019 if (Attrs.empty()) return; 1020 1021 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3); 1022 1023 SmallVector<uint64_t, 64> Record; 1024 for (const AttributeList &AL : Attrs) { 1025 for (unsigned i : AL.indexes()) { 1026 AttributeSet AS = AL.getAttributes(i); 1027 if (AS.hasAttributes()) 1028 Record.push_back(VE.getAttributeGroupID({i, AS})); 1029 } 1030 1031 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record); 1032 Record.clear(); 1033 } 1034 1035 Stream.ExitBlock(); 1036 } 1037 1038 /// WriteTypeTable - Write out the type table for a module. 1039 void ModuleBitcodeWriter::writeTypeTable() { 1040 const ValueEnumerator::TypeList &TypeList = VE.getTypes(); 1041 1042 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */); 1043 SmallVector<uint64_t, 64> TypeVals; 1044 1045 uint64_t NumBits = VE.computeBitsRequiredForTypeIndices(); 1046 1047 // Abbrev for TYPE_CODE_OPAQUE_POINTER. 1048 auto Abbv = std::make_shared<BitCodeAbbrev>(); 1049 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_OPAQUE_POINTER)); 1050 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0 1051 unsigned OpaquePtrAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 1052 1053 // Abbrev for TYPE_CODE_FUNCTION. 1054 Abbv = std::make_shared<BitCodeAbbrev>(); 1055 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION)); 1056 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg 1057 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1058 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 1059 unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 1060 1061 // Abbrev for TYPE_CODE_STRUCT_ANON. 1062 Abbv = std::make_shared<BitCodeAbbrev>(); 1063 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON)); 1064 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked 1065 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1066 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 1067 unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 1068 1069 // Abbrev for TYPE_CODE_STRUCT_NAME. 1070 Abbv = std::make_shared<BitCodeAbbrev>(); 1071 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME)); 1072 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1073 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 1074 unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 1075 1076 // Abbrev for TYPE_CODE_STRUCT_NAMED. 1077 Abbv = std::make_shared<BitCodeAbbrev>(); 1078 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED)); 1079 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked 1080 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1081 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 1082 unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 1083 1084 // Abbrev for TYPE_CODE_ARRAY. 1085 Abbv = std::make_shared<BitCodeAbbrev>(); 1086 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY)); 1087 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size 1088 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 1089 unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 1090 1091 // Emit an entry count so the reader can reserve space. 1092 TypeVals.push_back(TypeList.size()); 1093 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals); 1094 TypeVals.clear(); 1095 1096 // Loop over all of the types, emitting each in turn. 1097 for (Type *T : TypeList) { 1098 int AbbrevToUse = 0; 1099 unsigned Code = 0; 1100 1101 switch (T->getTypeID()) { 1102 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break; 1103 case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break; 1104 case Type::BFloatTyID: Code = bitc::TYPE_CODE_BFLOAT; break; 1105 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break; 1106 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break; 1107 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break; 1108 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break; 1109 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break; 1110 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break; 1111 case Type::MetadataTyID: 1112 Code = bitc::TYPE_CODE_METADATA; 1113 break; 1114 case Type::X86_AMXTyID: Code = bitc::TYPE_CODE_X86_AMX; break; 1115 case Type::TokenTyID: Code = bitc::TYPE_CODE_TOKEN; break; 1116 case Type::IntegerTyID: 1117 // INTEGER: [width] 1118 Code = bitc::TYPE_CODE_INTEGER; 1119 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth()); 1120 break; 1121 case Type::PointerTyID: { 1122 PointerType *PTy = cast<PointerType>(T); 1123 unsigned AddressSpace = PTy->getAddressSpace(); 1124 // OPAQUE_POINTER: [address space] 1125 Code = bitc::TYPE_CODE_OPAQUE_POINTER; 1126 TypeVals.push_back(AddressSpace); 1127 if (AddressSpace == 0) 1128 AbbrevToUse = OpaquePtrAbbrev; 1129 break; 1130 } 1131 case Type::FunctionTyID: { 1132 FunctionType *FT = cast<FunctionType>(T); 1133 // FUNCTION: [isvararg, retty, paramty x N] 1134 Code = bitc::TYPE_CODE_FUNCTION; 1135 TypeVals.push_back(FT->isVarArg()); 1136 TypeVals.push_back(VE.getTypeID(FT->getReturnType())); 1137 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) 1138 TypeVals.push_back(VE.getTypeID(FT->getParamType(i))); 1139 AbbrevToUse = FunctionAbbrev; 1140 break; 1141 } 1142 case Type::StructTyID: { 1143 StructType *ST = cast<StructType>(T); 1144 // STRUCT: [ispacked, eltty x N] 1145 TypeVals.push_back(ST->isPacked()); 1146 // Output all of the element types. 1147 for (Type *ET : ST->elements()) 1148 TypeVals.push_back(VE.getTypeID(ET)); 1149 1150 if (ST->isLiteral()) { 1151 Code = bitc::TYPE_CODE_STRUCT_ANON; 1152 AbbrevToUse = StructAnonAbbrev; 1153 } else { 1154 if (ST->isOpaque()) { 1155 Code = bitc::TYPE_CODE_OPAQUE; 1156 } else { 1157 Code = bitc::TYPE_CODE_STRUCT_NAMED; 1158 AbbrevToUse = StructNamedAbbrev; 1159 } 1160 1161 // Emit the name if it is present. 1162 if (!ST->getName().empty()) 1163 writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, ST->getName(), 1164 StructNameAbbrev); 1165 } 1166 break; 1167 } 1168 case Type::ArrayTyID: { 1169 ArrayType *AT = cast<ArrayType>(T); 1170 // ARRAY: [numelts, eltty] 1171 Code = bitc::TYPE_CODE_ARRAY; 1172 TypeVals.push_back(AT->getNumElements()); 1173 TypeVals.push_back(VE.getTypeID(AT->getElementType())); 1174 AbbrevToUse = ArrayAbbrev; 1175 break; 1176 } 1177 case Type::FixedVectorTyID: 1178 case Type::ScalableVectorTyID: { 1179 VectorType *VT = cast<VectorType>(T); 1180 // VECTOR [numelts, eltty] or 1181 // [numelts, eltty, scalable] 1182 Code = bitc::TYPE_CODE_VECTOR; 1183 TypeVals.push_back(VT->getElementCount().getKnownMinValue()); 1184 TypeVals.push_back(VE.getTypeID(VT->getElementType())); 1185 if (isa<ScalableVectorType>(VT)) 1186 TypeVals.push_back(true); 1187 break; 1188 } 1189 case Type::TargetExtTyID: { 1190 TargetExtType *TET = cast<TargetExtType>(T); 1191 Code = bitc::TYPE_CODE_TARGET_TYPE; 1192 writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, TET->getName(), 1193 StructNameAbbrev); 1194 TypeVals.push_back(TET->getNumTypeParameters()); 1195 for (Type *InnerTy : TET->type_params()) 1196 TypeVals.push_back(VE.getTypeID(InnerTy)); 1197 for (unsigned IntParam : TET->int_params()) 1198 TypeVals.push_back(IntParam); 1199 break; 1200 } 1201 case Type::TypedPointerTyID: 1202 llvm_unreachable("Typed pointers cannot be added to IR modules"); 1203 } 1204 1205 // Emit the finished record. 1206 Stream.EmitRecord(Code, TypeVals, AbbrevToUse); 1207 TypeVals.clear(); 1208 } 1209 1210 Stream.ExitBlock(); 1211 } 1212 1213 static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) { 1214 switch (Linkage) { 1215 case GlobalValue::ExternalLinkage: 1216 return 0; 1217 case GlobalValue::WeakAnyLinkage: 1218 return 16; 1219 case GlobalValue::AppendingLinkage: 1220 return 2; 1221 case GlobalValue::InternalLinkage: 1222 return 3; 1223 case GlobalValue::LinkOnceAnyLinkage: 1224 return 18; 1225 case GlobalValue::ExternalWeakLinkage: 1226 return 7; 1227 case GlobalValue::CommonLinkage: 1228 return 8; 1229 case GlobalValue::PrivateLinkage: 1230 return 9; 1231 case GlobalValue::WeakODRLinkage: 1232 return 17; 1233 case GlobalValue::LinkOnceODRLinkage: 1234 return 19; 1235 case GlobalValue::AvailableExternallyLinkage: 1236 return 12; 1237 } 1238 llvm_unreachable("Invalid linkage"); 1239 } 1240 1241 static unsigned getEncodedLinkage(const GlobalValue &GV) { 1242 return getEncodedLinkage(GV.getLinkage()); 1243 } 1244 1245 static uint64_t getEncodedFFlags(FunctionSummary::FFlags Flags) { 1246 uint64_t RawFlags = 0; 1247 RawFlags |= Flags.ReadNone; 1248 RawFlags |= (Flags.ReadOnly << 1); 1249 RawFlags |= (Flags.NoRecurse << 2); 1250 RawFlags |= (Flags.ReturnDoesNotAlias << 3); 1251 RawFlags |= (Flags.NoInline << 4); 1252 RawFlags |= (Flags.AlwaysInline << 5); 1253 RawFlags |= (Flags.NoUnwind << 6); 1254 RawFlags |= (Flags.MayThrow << 7); 1255 RawFlags |= (Flags.HasUnknownCall << 8); 1256 RawFlags |= (Flags.MustBeUnreachable << 9); 1257 return RawFlags; 1258 } 1259 1260 // Decode the flags for GlobalValue in the summary. See getDecodedGVSummaryFlags 1261 // in BitcodeReader.cpp. 1262 static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags, 1263 bool ImportAsDecl = false) { 1264 uint64_t RawFlags = 0; 1265 1266 RawFlags |= Flags.NotEligibleToImport; // bool 1267 RawFlags |= (Flags.Live << 1); 1268 RawFlags |= (Flags.DSOLocal << 2); 1269 RawFlags |= (Flags.CanAutoHide << 3); 1270 1271 // Linkage don't need to be remapped at that time for the summary. Any future 1272 // change to the getEncodedLinkage() function will need to be taken into 1273 // account here as well. 1274 RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits 1275 1276 RawFlags |= (Flags.Visibility << 8); // 2 bits 1277 1278 unsigned ImportType = Flags.ImportType | ImportAsDecl; 1279 RawFlags |= (ImportType << 10); // 1 bit 1280 1281 return RawFlags; 1282 } 1283 1284 static uint64_t getEncodedGVarFlags(GlobalVarSummary::GVarFlags Flags) { 1285 uint64_t RawFlags = Flags.MaybeReadOnly | (Flags.MaybeWriteOnly << 1) | 1286 (Flags.Constant << 2) | Flags.VCallVisibility << 3; 1287 return RawFlags; 1288 } 1289 1290 static uint64_t getEncodedHotnessCallEdgeInfo(const CalleeInfo &CI) { 1291 uint64_t RawFlags = 0; 1292 1293 RawFlags |= CI.Hotness; // 3 bits 1294 RawFlags |= (CI.HasTailCall << 3); // 1 bit 1295 1296 return RawFlags; 1297 } 1298 1299 static uint64_t getEncodedRelBFCallEdgeInfo(const CalleeInfo &CI) { 1300 uint64_t RawFlags = 0; 1301 1302 RawFlags |= CI.RelBlockFreq; // CalleeInfo::RelBlockFreqBits bits 1303 RawFlags |= (CI.HasTailCall << CalleeInfo::RelBlockFreqBits); // 1 bit 1304 1305 return RawFlags; 1306 } 1307 1308 static unsigned getEncodedVisibility(const GlobalValue &GV) { 1309 switch (GV.getVisibility()) { 1310 case GlobalValue::DefaultVisibility: return 0; 1311 case GlobalValue::HiddenVisibility: return 1; 1312 case GlobalValue::ProtectedVisibility: return 2; 1313 } 1314 llvm_unreachable("Invalid visibility"); 1315 } 1316 1317 static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) { 1318 switch (GV.getDLLStorageClass()) { 1319 case GlobalValue::DefaultStorageClass: return 0; 1320 case GlobalValue::DLLImportStorageClass: return 1; 1321 case GlobalValue::DLLExportStorageClass: return 2; 1322 } 1323 llvm_unreachable("Invalid DLL storage class"); 1324 } 1325 1326 static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) { 1327 switch (GV.getThreadLocalMode()) { 1328 case GlobalVariable::NotThreadLocal: return 0; 1329 case GlobalVariable::GeneralDynamicTLSModel: return 1; 1330 case GlobalVariable::LocalDynamicTLSModel: return 2; 1331 case GlobalVariable::InitialExecTLSModel: return 3; 1332 case GlobalVariable::LocalExecTLSModel: return 4; 1333 } 1334 llvm_unreachable("Invalid TLS model"); 1335 } 1336 1337 static unsigned getEncodedComdatSelectionKind(const Comdat &C) { 1338 switch (C.getSelectionKind()) { 1339 case Comdat::Any: 1340 return bitc::COMDAT_SELECTION_KIND_ANY; 1341 case Comdat::ExactMatch: 1342 return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH; 1343 case Comdat::Largest: 1344 return bitc::COMDAT_SELECTION_KIND_LARGEST; 1345 case Comdat::NoDeduplicate: 1346 return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES; 1347 case Comdat::SameSize: 1348 return bitc::COMDAT_SELECTION_KIND_SAME_SIZE; 1349 } 1350 llvm_unreachable("Invalid selection kind"); 1351 } 1352 1353 static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) { 1354 switch (GV.getUnnamedAddr()) { 1355 case GlobalValue::UnnamedAddr::None: return 0; 1356 case GlobalValue::UnnamedAddr::Local: return 2; 1357 case GlobalValue::UnnamedAddr::Global: return 1; 1358 } 1359 llvm_unreachable("Invalid unnamed_addr"); 1360 } 1361 1362 size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) { 1363 if (GenerateHash) 1364 Hasher.update(Str); 1365 return StrtabBuilder.add(Str); 1366 } 1367 1368 void ModuleBitcodeWriter::writeComdats() { 1369 SmallVector<unsigned, 64> Vals; 1370 for (const Comdat *C : VE.getComdats()) { 1371 // COMDAT: [strtab offset, strtab size, selection_kind] 1372 Vals.push_back(addToStrtab(C->getName())); 1373 Vals.push_back(C->getName().size()); 1374 Vals.push_back(getEncodedComdatSelectionKind(*C)); 1375 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0); 1376 Vals.clear(); 1377 } 1378 } 1379 1380 /// Write a record that will eventually hold the word offset of the 1381 /// module-level VST. For now the offset is 0, which will be backpatched 1382 /// after the real VST is written. Saves the bit offset to backpatch. 1383 void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() { 1384 // Write a placeholder value in for the offset of the real VST, 1385 // which is written after the function blocks so that it can include 1386 // the offset of each function. The placeholder offset will be 1387 // updated when the real VST is written. 1388 auto Abbv = std::make_shared<BitCodeAbbrev>(); 1389 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET)); 1390 // Blocks are 32-bit aligned, so we can use a 32-bit word offset to 1391 // hold the real VST offset. Must use fixed instead of VBR as we don't 1392 // know how many VBR chunks to reserve ahead of time. 1393 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 1394 unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 1395 1396 // Emit the placeholder 1397 uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0}; 1398 Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals); 1399 1400 // Compute and save the bit offset to the placeholder, which will be 1401 // patched when the real VST is written. We can simply subtract the 32-bit 1402 // fixed size from the current bit number to get the location to backpatch. 1403 VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32; 1404 } 1405 1406 enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 }; 1407 1408 /// Determine the encoding to use for the given string name and length. 1409 static StringEncoding getStringEncoding(StringRef Str) { 1410 bool isChar6 = true; 1411 for (char C : Str) { 1412 if (isChar6) 1413 isChar6 = BitCodeAbbrevOp::isChar6(C); 1414 if ((unsigned char)C & 128) 1415 // don't bother scanning the rest. 1416 return SE_Fixed8; 1417 } 1418 if (isChar6) 1419 return SE_Char6; 1420 return SE_Fixed7; 1421 } 1422 1423 static_assert(sizeof(GlobalValue::SanitizerMetadata) <= sizeof(unsigned), 1424 "Sanitizer Metadata is too large for naive serialization."); 1425 static unsigned 1426 serializeSanitizerMetadata(const GlobalValue::SanitizerMetadata &Meta) { 1427 return Meta.NoAddress | (Meta.NoHWAddress << 1) | 1428 (Meta.Memtag << 2) | (Meta.IsDynInit << 3); 1429 } 1430 1431 /// Emit top-level description of module, including target triple, inline asm, 1432 /// descriptors for global variables, and function prototype info. 1433 /// Returns the bit offset to backpatch with the location of the real VST. 1434 void ModuleBitcodeWriter::writeModuleInfo() { 1435 // Emit various pieces of data attached to a module. 1436 if (!M.getTargetTriple().empty()) 1437 writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(), 1438 0 /*TODO*/); 1439 const std::string &DL = M.getDataLayoutStr(); 1440 if (!DL.empty()) 1441 writeStringRecord(Stream, bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/); 1442 if (!M.getModuleInlineAsm().empty()) 1443 writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(), 1444 0 /*TODO*/); 1445 1446 // Emit information about sections and GC, computing how many there are. Also 1447 // compute the maximum alignment value. 1448 std::map<std::string, unsigned> SectionMap; 1449 std::map<std::string, unsigned> GCMap; 1450 MaybeAlign MaxAlignment; 1451 unsigned MaxGlobalType = 0; 1452 const auto UpdateMaxAlignment = [&MaxAlignment](const MaybeAlign A) { 1453 if (A) 1454 MaxAlignment = !MaxAlignment ? *A : std::max(*MaxAlignment, *A); 1455 }; 1456 for (const GlobalVariable &GV : M.globals()) { 1457 UpdateMaxAlignment(GV.getAlign()); 1458 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType())); 1459 if (GV.hasSection()) { 1460 // Give section names unique ID's. 1461 unsigned &Entry = SectionMap[std::string(GV.getSection())]; 1462 if (!Entry) { 1463 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(), 1464 0 /*TODO*/); 1465 Entry = SectionMap.size(); 1466 } 1467 } 1468 } 1469 for (const Function &F : M) { 1470 UpdateMaxAlignment(F.getAlign()); 1471 if (F.hasSection()) { 1472 // Give section names unique ID's. 1473 unsigned &Entry = SectionMap[std::string(F.getSection())]; 1474 if (!Entry) { 1475 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, F.getSection(), 1476 0 /*TODO*/); 1477 Entry = SectionMap.size(); 1478 } 1479 } 1480 if (F.hasGC()) { 1481 // Same for GC names. 1482 unsigned &Entry = GCMap[F.getGC()]; 1483 if (!Entry) { 1484 writeStringRecord(Stream, bitc::MODULE_CODE_GCNAME, F.getGC(), 1485 0 /*TODO*/); 1486 Entry = GCMap.size(); 1487 } 1488 } 1489 } 1490 1491 // Emit abbrev for globals, now that we know # sections and max alignment. 1492 unsigned SimpleGVarAbbrev = 0; 1493 if (!M.global_empty()) { 1494 // Add an abbrev for common globals with no visibility or thread localness. 1495 auto Abbv = std::make_shared<BitCodeAbbrev>(); 1496 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR)); 1497 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 1498 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 1499 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1500 Log2_32_Ceil(MaxGlobalType+1))); 1501 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2 1502 //| explicitType << 1 1503 //| constant 1504 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer. 1505 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage. 1506 if (!MaxAlignment) // Alignment. 1507 Abbv->Add(BitCodeAbbrevOp(0)); 1508 else { 1509 unsigned MaxEncAlignment = getEncodedAlign(MaxAlignment); 1510 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1511 Log2_32_Ceil(MaxEncAlignment+1))); 1512 } 1513 if (SectionMap.empty()) // Section. 1514 Abbv->Add(BitCodeAbbrevOp(0)); 1515 else 1516 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1517 Log2_32_Ceil(SectionMap.size()+1))); 1518 // Don't bother emitting vis + thread local. 1519 SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 1520 } 1521 1522 SmallVector<unsigned, 64> Vals; 1523 // Emit the module's source file name. 1524 { 1525 StringEncoding Bits = getStringEncoding(M.getSourceFileName()); 1526 BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8); 1527 if (Bits == SE_Char6) 1528 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6); 1529 else if (Bits == SE_Fixed7) 1530 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7); 1531 1532 // MODULE_CODE_SOURCE_FILENAME: [namechar x N] 1533 auto Abbv = std::make_shared<BitCodeAbbrev>(); 1534 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME)); 1535 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1536 Abbv->Add(AbbrevOpToUse); 1537 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 1538 1539 for (const auto P : M.getSourceFileName()) 1540 Vals.push_back((unsigned char)P); 1541 1542 // Emit the finished record. 1543 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev); 1544 Vals.clear(); 1545 } 1546 1547 // Emit the global variable information. 1548 for (const GlobalVariable &GV : M.globals()) { 1549 unsigned AbbrevToUse = 0; 1550 1551 // GLOBALVAR: [strtab offset, strtab size, type, isconst, initid, 1552 // linkage, alignment, section, visibility, threadlocal, 1553 // unnamed_addr, externally_initialized, dllstorageclass, 1554 // comdat, attributes, DSO_Local, GlobalSanitizer, code_model] 1555 Vals.push_back(addToStrtab(GV.getName())); 1556 Vals.push_back(GV.getName().size()); 1557 Vals.push_back(VE.getTypeID(GV.getValueType())); 1558 Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant()); 1559 Vals.push_back(GV.isDeclaration() ? 0 : 1560 (VE.getValueID(GV.getInitializer()) + 1)); 1561 Vals.push_back(getEncodedLinkage(GV)); 1562 Vals.push_back(getEncodedAlign(GV.getAlign())); 1563 Vals.push_back(GV.hasSection() ? SectionMap[std::string(GV.getSection())] 1564 : 0); 1565 if (GV.isThreadLocal() || 1566 GV.getVisibility() != GlobalValue::DefaultVisibility || 1567 GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None || 1568 GV.isExternallyInitialized() || 1569 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass || 1570 GV.hasComdat() || GV.hasAttributes() || GV.isDSOLocal() || 1571 GV.hasPartition() || GV.hasSanitizerMetadata() || GV.getCodeModel()) { 1572 Vals.push_back(getEncodedVisibility(GV)); 1573 Vals.push_back(getEncodedThreadLocalMode(GV)); 1574 Vals.push_back(getEncodedUnnamedAddr(GV)); 1575 Vals.push_back(GV.isExternallyInitialized()); 1576 Vals.push_back(getEncodedDLLStorageClass(GV)); 1577 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0); 1578 1579 auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex); 1580 Vals.push_back(VE.getAttributeListID(AL)); 1581 1582 Vals.push_back(GV.isDSOLocal()); 1583 Vals.push_back(addToStrtab(GV.getPartition())); 1584 Vals.push_back(GV.getPartition().size()); 1585 1586 Vals.push_back((GV.hasSanitizerMetadata() ? serializeSanitizerMetadata( 1587 GV.getSanitizerMetadata()) 1588 : 0)); 1589 Vals.push_back(GV.getCodeModelRaw()); 1590 } else { 1591 AbbrevToUse = SimpleGVarAbbrev; 1592 } 1593 1594 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse); 1595 Vals.clear(); 1596 } 1597 1598 // Emit the function proto information. 1599 for (const Function &F : M) { 1600 // FUNCTION: [strtab offset, strtab size, type, callingconv, isproto, 1601 // linkage, paramattrs, alignment, section, visibility, gc, 1602 // unnamed_addr, prologuedata, dllstorageclass, comdat, 1603 // prefixdata, personalityfn, DSO_Local, addrspace] 1604 Vals.push_back(addToStrtab(F.getName())); 1605 Vals.push_back(F.getName().size()); 1606 Vals.push_back(VE.getTypeID(F.getFunctionType())); 1607 Vals.push_back(F.getCallingConv()); 1608 Vals.push_back(F.isDeclaration()); 1609 Vals.push_back(getEncodedLinkage(F)); 1610 Vals.push_back(VE.getAttributeListID(F.getAttributes())); 1611 Vals.push_back(getEncodedAlign(F.getAlign())); 1612 Vals.push_back(F.hasSection() ? SectionMap[std::string(F.getSection())] 1613 : 0); 1614 Vals.push_back(getEncodedVisibility(F)); 1615 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0); 1616 Vals.push_back(getEncodedUnnamedAddr(F)); 1617 Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1) 1618 : 0); 1619 Vals.push_back(getEncodedDLLStorageClass(F)); 1620 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0); 1621 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1) 1622 : 0); 1623 Vals.push_back( 1624 F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0); 1625 1626 Vals.push_back(F.isDSOLocal()); 1627 Vals.push_back(F.getAddressSpace()); 1628 Vals.push_back(addToStrtab(F.getPartition())); 1629 Vals.push_back(F.getPartition().size()); 1630 1631 unsigned AbbrevToUse = 0; 1632 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse); 1633 Vals.clear(); 1634 } 1635 1636 // Emit the alias information. 1637 for (const GlobalAlias &A : M.aliases()) { 1638 // ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage, 1639 // visibility, dllstorageclass, threadlocal, unnamed_addr, 1640 // DSO_Local] 1641 Vals.push_back(addToStrtab(A.getName())); 1642 Vals.push_back(A.getName().size()); 1643 Vals.push_back(VE.getTypeID(A.getValueType())); 1644 Vals.push_back(A.getType()->getAddressSpace()); 1645 Vals.push_back(VE.getValueID(A.getAliasee())); 1646 Vals.push_back(getEncodedLinkage(A)); 1647 Vals.push_back(getEncodedVisibility(A)); 1648 Vals.push_back(getEncodedDLLStorageClass(A)); 1649 Vals.push_back(getEncodedThreadLocalMode(A)); 1650 Vals.push_back(getEncodedUnnamedAddr(A)); 1651 Vals.push_back(A.isDSOLocal()); 1652 Vals.push_back(addToStrtab(A.getPartition())); 1653 Vals.push_back(A.getPartition().size()); 1654 1655 unsigned AbbrevToUse = 0; 1656 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse); 1657 Vals.clear(); 1658 } 1659 1660 // Emit the ifunc information. 1661 for (const GlobalIFunc &I : M.ifuncs()) { 1662 // IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver 1663 // val#, linkage, visibility, DSO_Local] 1664 Vals.push_back(addToStrtab(I.getName())); 1665 Vals.push_back(I.getName().size()); 1666 Vals.push_back(VE.getTypeID(I.getValueType())); 1667 Vals.push_back(I.getType()->getAddressSpace()); 1668 Vals.push_back(VE.getValueID(I.getResolver())); 1669 Vals.push_back(getEncodedLinkage(I)); 1670 Vals.push_back(getEncodedVisibility(I)); 1671 Vals.push_back(I.isDSOLocal()); 1672 Vals.push_back(addToStrtab(I.getPartition())); 1673 Vals.push_back(I.getPartition().size()); 1674 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals); 1675 Vals.clear(); 1676 } 1677 1678 writeValueSymbolTableForwardDecl(); 1679 } 1680 1681 static uint64_t getOptimizationFlags(const Value *V) { 1682 uint64_t Flags = 0; 1683 1684 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) { 1685 if (OBO->hasNoSignedWrap()) 1686 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP; 1687 if (OBO->hasNoUnsignedWrap()) 1688 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP; 1689 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) { 1690 if (PEO->isExact()) 1691 Flags |= 1 << bitc::PEO_EXACT; 1692 } else if (const auto *PDI = dyn_cast<PossiblyDisjointInst>(V)) { 1693 if (PDI->isDisjoint()) 1694 Flags |= 1 << bitc::PDI_DISJOINT; 1695 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) { 1696 if (FPMO->hasAllowReassoc()) 1697 Flags |= bitc::AllowReassoc; 1698 if (FPMO->hasNoNaNs()) 1699 Flags |= bitc::NoNaNs; 1700 if (FPMO->hasNoInfs()) 1701 Flags |= bitc::NoInfs; 1702 if (FPMO->hasNoSignedZeros()) 1703 Flags |= bitc::NoSignedZeros; 1704 if (FPMO->hasAllowReciprocal()) 1705 Flags |= bitc::AllowReciprocal; 1706 if (FPMO->hasAllowContract()) 1707 Flags |= bitc::AllowContract; 1708 if (FPMO->hasApproxFunc()) 1709 Flags |= bitc::ApproxFunc; 1710 } else if (const auto *NNI = dyn_cast<PossiblyNonNegInst>(V)) { 1711 if (NNI->hasNonNeg()) 1712 Flags |= 1 << bitc::PNNI_NON_NEG; 1713 } else if (const auto *TI = dyn_cast<TruncInst>(V)) { 1714 if (TI->hasNoSignedWrap()) 1715 Flags |= 1 << bitc::TIO_NO_SIGNED_WRAP; 1716 if (TI->hasNoUnsignedWrap()) 1717 Flags |= 1 << bitc::TIO_NO_UNSIGNED_WRAP; 1718 } else if (const auto *GEP = dyn_cast<GEPOperator>(V)) { 1719 if (GEP->isInBounds()) 1720 Flags |= 1 << bitc::GEP_INBOUNDS; 1721 if (GEP->hasNoUnsignedSignedWrap()) 1722 Flags |= 1 << bitc::GEP_NUSW; 1723 if (GEP->hasNoUnsignedWrap()) 1724 Flags |= 1 << bitc::GEP_NUW; 1725 } else if (const auto *ICmp = dyn_cast<ICmpInst>(V)) { 1726 if (ICmp->hasSameSign()) 1727 Flags |= 1 << bitc::ICMP_SAME_SIGN; 1728 } 1729 1730 return Flags; 1731 } 1732 1733 void ModuleBitcodeWriter::writeValueAsMetadata( 1734 const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) { 1735 // Mimic an MDNode with a value as one operand. 1736 Value *V = MD->getValue(); 1737 Record.push_back(VE.getTypeID(V->getType())); 1738 Record.push_back(VE.getValueID(V)); 1739 Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0); 1740 Record.clear(); 1741 } 1742 1743 void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N, 1744 SmallVectorImpl<uint64_t> &Record, 1745 unsigned Abbrev) { 1746 for (const MDOperand &MDO : N->operands()) { 1747 Metadata *MD = MDO; 1748 assert(!(MD && isa<LocalAsMetadata>(MD)) && 1749 "Unexpected function-local metadata"); 1750 Record.push_back(VE.getMetadataOrNullID(MD)); 1751 } 1752 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE 1753 : bitc::METADATA_NODE, 1754 Record, Abbrev); 1755 Record.clear(); 1756 } 1757 1758 unsigned ModuleBitcodeWriter::createDILocationAbbrev() { 1759 // Assume the column is usually under 128, and always output the inlined-at 1760 // location (it's never more expensive than building an array size 1). 1761 auto Abbv = std::make_shared<BitCodeAbbrev>(); 1762 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION)); 1763 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); 1764 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1765 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 1766 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1767 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1768 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); 1769 return Stream.EmitAbbrev(std::move(Abbv)); 1770 } 1771 1772 void ModuleBitcodeWriter::writeDILocation(const DILocation *N, 1773 SmallVectorImpl<uint64_t> &Record, 1774 unsigned &Abbrev) { 1775 if (!Abbrev) 1776 Abbrev = createDILocationAbbrev(); 1777 1778 Record.push_back(N->isDistinct()); 1779 Record.push_back(N->getLine()); 1780 Record.push_back(N->getColumn()); 1781 Record.push_back(VE.getMetadataID(N->getScope())); 1782 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt())); 1783 Record.push_back(N->isImplicitCode()); 1784 1785 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev); 1786 Record.clear(); 1787 } 1788 1789 unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() { 1790 // Assume the column is usually under 128, and always output the inlined-at 1791 // location (it's never more expensive than building an array size 1). 1792 auto Abbv = std::make_shared<BitCodeAbbrev>(); 1793 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG)); 1794 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); 1795 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1796 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); 1797 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1798 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1799 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1800 return Stream.EmitAbbrev(std::move(Abbv)); 1801 } 1802 1803 void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N, 1804 SmallVectorImpl<uint64_t> &Record, 1805 unsigned &Abbrev) { 1806 if (!Abbrev) 1807 Abbrev = createGenericDINodeAbbrev(); 1808 1809 Record.push_back(N->isDistinct()); 1810 Record.push_back(N->getTag()); 1811 Record.push_back(0); // Per-tag version field; unused for now. 1812 1813 for (auto &I : N->operands()) 1814 Record.push_back(VE.getMetadataOrNullID(I)); 1815 1816 Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev); 1817 Record.clear(); 1818 } 1819 1820 void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N, 1821 SmallVectorImpl<uint64_t> &Record, 1822 unsigned Abbrev) { 1823 const uint64_t Version = 2 << 1; 1824 Record.push_back((uint64_t)N->isDistinct() | Version); 1825 Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode())); 1826 Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound())); 1827 Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound())); 1828 Record.push_back(VE.getMetadataOrNullID(N->getRawStride())); 1829 1830 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev); 1831 Record.clear(); 1832 } 1833 1834 void ModuleBitcodeWriter::writeDIGenericSubrange( 1835 const DIGenericSubrange *N, SmallVectorImpl<uint64_t> &Record, 1836 unsigned Abbrev) { 1837 Record.push_back((uint64_t)N->isDistinct()); 1838 Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode())); 1839 Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound())); 1840 Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound())); 1841 Record.push_back(VE.getMetadataOrNullID(N->getRawStride())); 1842 1843 Stream.EmitRecord(bitc::METADATA_GENERIC_SUBRANGE, Record, Abbrev); 1844 Record.clear(); 1845 } 1846 1847 void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N, 1848 SmallVectorImpl<uint64_t> &Record, 1849 unsigned Abbrev) { 1850 const uint64_t IsBigInt = 1 << 2; 1851 Record.push_back(IsBigInt | (N->isUnsigned() << 1) | N->isDistinct()); 1852 Record.push_back(N->getValue().getBitWidth()); 1853 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1854 emitWideAPInt(Record, N->getValue()); 1855 1856 Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev); 1857 Record.clear(); 1858 } 1859 1860 void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N, 1861 SmallVectorImpl<uint64_t> &Record, 1862 unsigned Abbrev) { 1863 Record.push_back(N->isDistinct()); 1864 Record.push_back(N->getTag()); 1865 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1866 Record.push_back(N->getSizeInBits()); 1867 Record.push_back(N->getAlignInBits()); 1868 Record.push_back(N->getEncoding()); 1869 Record.push_back(N->getFlags()); 1870 Record.push_back(N->getNumExtraInhabitants()); 1871 1872 Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev); 1873 Record.clear(); 1874 } 1875 1876 void ModuleBitcodeWriter::writeDIStringType(const DIStringType *N, 1877 SmallVectorImpl<uint64_t> &Record, 1878 unsigned Abbrev) { 1879 Record.push_back(N->isDistinct()); 1880 Record.push_back(N->getTag()); 1881 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1882 Record.push_back(VE.getMetadataOrNullID(N->getStringLength())); 1883 Record.push_back(VE.getMetadataOrNullID(N->getStringLengthExp())); 1884 Record.push_back(VE.getMetadataOrNullID(N->getStringLocationExp())); 1885 Record.push_back(N->getSizeInBits()); 1886 Record.push_back(N->getAlignInBits()); 1887 Record.push_back(N->getEncoding()); 1888 1889 Stream.EmitRecord(bitc::METADATA_STRING_TYPE, Record, Abbrev); 1890 Record.clear(); 1891 } 1892 1893 void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N, 1894 SmallVectorImpl<uint64_t> &Record, 1895 unsigned Abbrev) { 1896 Record.push_back(N->isDistinct()); 1897 Record.push_back(N->getTag()); 1898 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1899 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1900 Record.push_back(N->getLine()); 1901 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1902 Record.push_back(VE.getMetadataOrNullID(N->getBaseType())); 1903 Record.push_back(N->getSizeInBits()); 1904 Record.push_back(N->getAlignInBits()); 1905 Record.push_back(N->getOffsetInBits()); 1906 Record.push_back(N->getFlags()); 1907 Record.push_back(VE.getMetadataOrNullID(N->getExtraData())); 1908 1909 // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means 1910 // that there is no DWARF address space associated with DIDerivedType. 1911 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace()) 1912 Record.push_back(*DWARFAddressSpace + 1); 1913 else 1914 Record.push_back(0); 1915 1916 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get())); 1917 1918 if (auto PtrAuthData = N->getPtrAuthData()) 1919 Record.push_back(PtrAuthData->RawData); 1920 else 1921 Record.push_back(0); 1922 1923 Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev); 1924 Record.clear(); 1925 } 1926 1927 void ModuleBitcodeWriter::writeDICompositeType( 1928 const DICompositeType *N, SmallVectorImpl<uint64_t> &Record, 1929 unsigned Abbrev) { 1930 const unsigned IsNotUsedInOldTypeRef = 0x2; 1931 Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct()); 1932 Record.push_back(N->getTag()); 1933 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1934 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1935 Record.push_back(N->getLine()); 1936 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1937 Record.push_back(VE.getMetadataOrNullID(N->getBaseType())); 1938 Record.push_back(N->getSizeInBits()); 1939 Record.push_back(N->getAlignInBits()); 1940 Record.push_back(N->getOffsetInBits()); 1941 Record.push_back(N->getFlags()); 1942 Record.push_back(VE.getMetadataOrNullID(N->getElements().get())); 1943 Record.push_back(N->getRuntimeLang()); 1944 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder())); 1945 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get())); 1946 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier())); 1947 Record.push_back(VE.getMetadataOrNullID(N->getDiscriminator())); 1948 Record.push_back(VE.getMetadataOrNullID(N->getRawDataLocation())); 1949 Record.push_back(VE.getMetadataOrNullID(N->getRawAssociated())); 1950 Record.push_back(VE.getMetadataOrNullID(N->getRawAllocated())); 1951 Record.push_back(VE.getMetadataOrNullID(N->getRawRank())); 1952 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get())); 1953 Record.push_back(N->getNumExtraInhabitants()); 1954 Record.push_back(VE.getMetadataOrNullID(N->getRawSpecification())); 1955 1956 Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev); 1957 Record.clear(); 1958 } 1959 1960 void ModuleBitcodeWriter::writeDISubroutineType( 1961 const DISubroutineType *N, SmallVectorImpl<uint64_t> &Record, 1962 unsigned Abbrev) { 1963 const unsigned HasNoOldTypeRefs = 0x2; 1964 Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct()); 1965 Record.push_back(N->getFlags()); 1966 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get())); 1967 Record.push_back(N->getCC()); 1968 1969 Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev); 1970 Record.clear(); 1971 } 1972 1973 void ModuleBitcodeWriter::writeDIFile(const DIFile *N, 1974 SmallVectorImpl<uint64_t> &Record, 1975 unsigned Abbrev) { 1976 Record.push_back(N->isDistinct()); 1977 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename())); 1978 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory())); 1979 if (N->getRawChecksum()) { 1980 Record.push_back(N->getRawChecksum()->Kind); 1981 Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()->Value)); 1982 } else { 1983 // Maintain backwards compatibility with the old internal representation of 1984 // CSK_None in ChecksumKind by writing nulls here when Checksum is None. 1985 Record.push_back(0); 1986 Record.push_back(VE.getMetadataOrNullID(nullptr)); 1987 } 1988 auto Source = N->getRawSource(); 1989 if (Source) 1990 Record.push_back(VE.getMetadataOrNullID(Source)); 1991 1992 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev); 1993 Record.clear(); 1994 } 1995 1996 void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N, 1997 SmallVectorImpl<uint64_t> &Record, 1998 unsigned Abbrev) { 1999 assert(N->isDistinct() && "Expected distinct compile units"); 2000 Record.push_back(/* IsDistinct */ true); 2001 Record.push_back(N->getSourceLanguage()); 2002 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 2003 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer())); 2004 Record.push_back(N->isOptimized()); 2005 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags())); 2006 Record.push_back(N->getRuntimeVersion()); 2007 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename())); 2008 Record.push_back(N->getEmissionKind()); 2009 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get())); 2010 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get())); 2011 Record.push_back(/* subprograms */ 0); 2012 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get())); 2013 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get())); 2014 Record.push_back(N->getDWOId()); 2015 Record.push_back(VE.getMetadataOrNullID(N->getMacros().get())); 2016 Record.push_back(N->getSplitDebugInlining()); 2017 Record.push_back(N->getDebugInfoForProfiling()); 2018 Record.push_back((unsigned)N->getNameTableKind()); 2019 Record.push_back(N->getRangesBaseAddress()); 2020 Record.push_back(VE.getMetadataOrNullID(N->getRawSysRoot())); 2021 Record.push_back(VE.getMetadataOrNullID(N->getRawSDK())); 2022 2023 Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev); 2024 Record.clear(); 2025 } 2026 2027 void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N, 2028 SmallVectorImpl<uint64_t> &Record, 2029 unsigned Abbrev) { 2030 const uint64_t HasUnitFlag = 1 << 1; 2031 const uint64_t HasSPFlagsFlag = 1 << 2; 2032 Record.push_back(uint64_t(N->isDistinct()) | HasUnitFlag | HasSPFlagsFlag); 2033 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 2034 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 2035 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName())); 2036 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 2037 Record.push_back(N->getLine()); 2038 Record.push_back(VE.getMetadataOrNullID(N->getType())); 2039 Record.push_back(N->getScopeLine()); 2040 Record.push_back(VE.getMetadataOrNullID(N->getContainingType())); 2041 Record.push_back(N->getSPFlags()); 2042 Record.push_back(N->getVirtualIndex()); 2043 Record.push_back(N->getFlags()); 2044 Record.push_back(VE.getMetadataOrNullID(N->getRawUnit())); 2045 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get())); 2046 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration())); 2047 Record.push_back(VE.getMetadataOrNullID(N->getRetainedNodes().get())); 2048 Record.push_back(N->getThisAdjustment()); 2049 Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get())); 2050 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get())); 2051 Record.push_back(VE.getMetadataOrNullID(N->getRawTargetFuncName())); 2052 2053 Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev); 2054 Record.clear(); 2055 } 2056 2057 void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N, 2058 SmallVectorImpl<uint64_t> &Record, 2059 unsigned Abbrev) { 2060 Record.push_back(N->isDistinct()); 2061 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 2062 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 2063 Record.push_back(N->getLine()); 2064 Record.push_back(N->getColumn()); 2065 2066 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev); 2067 Record.clear(); 2068 } 2069 2070 void ModuleBitcodeWriter::writeDILexicalBlockFile( 2071 const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record, 2072 unsigned Abbrev) { 2073 Record.push_back(N->isDistinct()); 2074 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 2075 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 2076 Record.push_back(N->getDiscriminator()); 2077 2078 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev); 2079 Record.clear(); 2080 } 2081 2082 void ModuleBitcodeWriter::writeDICommonBlock(const DICommonBlock *N, 2083 SmallVectorImpl<uint64_t> &Record, 2084 unsigned Abbrev) { 2085 Record.push_back(N->isDistinct()); 2086 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 2087 Record.push_back(VE.getMetadataOrNullID(N->getDecl())); 2088 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 2089 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 2090 Record.push_back(N->getLineNo()); 2091 2092 Stream.EmitRecord(bitc::METADATA_COMMON_BLOCK, Record, Abbrev); 2093 Record.clear(); 2094 } 2095 2096 void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N, 2097 SmallVectorImpl<uint64_t> &Record, 2098 unsigned Abbrev) { 2099 Record.push_back(N->isDistinct() | N->getExportSymbols() << 1); 2100 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 2101 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 2102 2103 Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev); 2104 Record.clear(); 2105 } 2106 2107 void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N, 2108 SmallVectorImpl<uint64_t> &Record, 2109 unsigned Abbrev) { 2110 Record.push_back(N->isDistinct()); 2111 Record.push_back(N->getMacinfoType()); 2112 Record.push_back(N->getLine()); 2113 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 2114 Record.push_back(VE.getMetadataOrNullID(N->getRawValue())); 2115 2116 Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev); 2117 Record.clear(); 2118 } 2119 2120 void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N, 2121 SmallVectorImpl<uint64_t> &Record, 2122 unsigned Abbrev) { 2123 Record.push_back(N->isDistinct()); 2124 Record.push_back(N->getMacinfoType()); 2125 Record.push_back(N->getLine()); 2126 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 2127 Record.push_back(VE.getMetadataOrNullID(N->getElements().get())); 2128 2129 Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev); 2130 Record.clear(); 2131 } 2132 2133 void ModuleBitcodeWriter::writeDIArgList(const DIArgList *N, 2134 SmallVectorImpl<uint64_t> &Record) { 2135 Record.reserve(N->getArgs().size()); 2136 for (ValueAsMetadata *MD : N->getArgs()) 2137 Record.push_back(VE.getMetadataID(MD)); 2138 2139 Stream.EmitRecord(bitc::METADATA_ARG_LIST, Record); 2140 Record.clear(); 2141 } 2142 2143 void ModuleBitcodeWriter::writeDIModule(const DIModule *N, 2144 SmallVectorImpl<uint64_t> &Record, 2145 unsigned Abbrev) { 2146 Record.push_back(N->isDistinct()); 2147 for (auto &I : N->operands()) 2148 Record.push_back(VE.getMetadataOrNullID(I)); 2149 Record.push_back(N->getLineNo()); 2150 Record.push_back(N->getIsDecl()); 2151 2152 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev); 2153 Record.clear(); 2154 } 2155 2156 void ModuleBitcodeWriter::writeDIAssignID(const DIAssignID *N, 2157 SmallVectorImpl<uint64_t> &Record, 2158 unsigned Abbrev) { 2159 // There are no arguments for this metadata type. 2160 Record.push_back(N->isDistinct()); 2161 Stream.EmitRecord(bitc::METADATA_ASSIGN_ID, Record, Abbrev); 2162 Record.clear(); 2163 } 2164 2165 void ModuleBitcodeWriter::writeDITemplateTypeParameter( 2166 const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record, 2167 unsigned Abbrev) { 2168 Record.push_back(N->isDistinct()); 2169 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 2170 Record.push_back(VE.getMetadataOrNullID(N->getType())); 2171 Record.push_back(N->isDefault()); 2172 2173 Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev); 2174 Record.clear(); 2175 } 2176 2177 void ModuleBitcodeWriter::writeDITemplateValueParameter( 2178 const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record, 2179 unsigned Abbrev) { 2180 Record.push_back(N->isDistinct()); 2181 Record.push_back(N->getTag()); 2182 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 2183 Record.push_back(VE.getMetadataOrNullID(N->getType())); 2184 Record.push_back(N->isDefault()); 2185 Record.push_back(VE.getMetadataOrNullID(N->getValue())); 2186 2187 Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev); 2188 Record.clear(); 2189 } 2190 2191 void ModuleBitcodeWriter::writeDIGlobalVariable( 2192 const DIGlobalVariable *N, SmallVectorImpl<uint64_t> &Record, 2193 unsigned Abbrev) { 2194 const uint64_t Version = 2 << 1; 2195 Record.push_back((uint64_t)N->isDistinct() | Version); 2196 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 2197 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 2198 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName())); 2199 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 2200 Record.push_back(N->getLine()); 2201 Record.push_back(VE.getMetadataOrNullID(N->getType())); 2202 Record.push_back(N->isLocalToUnit()); 2203 Record.push_back(N->isDefinition()); 2204 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration())); 2205 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams())); 2206 Record.push_back(N->getAlignInBits()); 2207 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get())); 2208 2209 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev); 2210 Record.clear(); 2211 } 2212 2213 void ModuleBitcodeWriter::writeDILocalVariable( 2214 const DILocalVariable *N, SmallVectorImpl<uint64_t> &Record, 2215 unsigned Abbrev) { 2216 // In order to support all possible bitcode formats in BitcodeReader we need 2217 // to distinguish the following cases: 2218 // 1) Record has no artificial tag (Record[1]), 2219 // has no obsolete inlinedAt field (Record[9]). 2220 // In this case Record size will be 8, HasAlignment flag is false. 2221 // 2) Record has artificial tag (Record[1]), 2222 // has no obsolete inlignedAt field (Record[9]). 2223 // In this case Record size will be 9, HasAlignment flag is false. 2224 // 3) Record has both artificial tag (Record[1]) and 2225 // obsolete inlignedAt field (Record[9]). 2226 // In this case Record size will be 10, HasAlignment flag is false. 2227 // 4) Record has neither artificial tag, nor inlignedAt field, but 2228 // HasAlignment flag is true and Record[8] contains alignment value. 2229 const uint64_t HasAlignmentFlag = 1 << 1; 2230 Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag); 2231 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 2232 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 2233 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 2234 Record.push_back(N->getLine()); 2235 Record.push_back(VE.getMetadataOrNullID(N->getType())); 2236 Record.push_back(N->getArg()); 2237 Record.push_back(N->getFlags()); 2238 Record.push_back(N->getAlignInBits()); 2239 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get())); 2240 2241 Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev); 2242 Record.clear(); 2243 } 2244 2245 void ModuleBitcodeWriter::writeDILabel( 2246 const DILabel *N, SmallVectorImpl<uint64_t> &Record, 2247 unsigned Abbrev) { 2248 Record.push_back((uint64_t)N->isDistinct()); 2249 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 2250 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 2251 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 2252 Record.push_back(N->getLine()); 2253 2254 Stream.EmitRecord(bitc::METADATA_LABEL, Record, Abbrev); 2255 Record.clear(); 2256 } 2257 2258 void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N, 2259 SmallVectorImpl<uint64_t> &Record, 2260 unsigned Abbrev) { 2261 Record.reserve(N->getElements().size() + 1); 2262 const uint64_t Version = 3 << 1; 2263 Record.push_back((uint64_t)N->isDistinct() | Version); 2264 Record.append(N->elements_begin(), N->elements_end()); 2265 2266 Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev); 2267 Record.clear(); 2268 } 2269 2270 void ModuleBitcodeWriter::writeDIGlobalVariableExpression( 2271 const DIGlobalVariableExpression *N, SmallVectorImpl<uint64_t> &Record, 2272 unsigned Abbrev) { 2273 Record.push_back(N->isDistinct()); 2274 Record.push_back(VE.getMetadataOrNullID(N->getVariable())); 2275 Record.push_back(VE.getMetadataOrNullID(N->getExpression())); 2276 2277 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR, Record, Abbrev); 2278 Record.clear(); 2279 } 2280 2281 void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N, 2282 SmallVectorImpl<uint64_t> &Record, 2283 unsigned Abbrev) { 2284 Record.push_back(N->isDistinct()); 2285 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 2286 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 2287 Record.push_back(N->getLine()); 2288 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName())); 2289 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName())); 2290 Record.push_back(N->getAttributes()); 2291 Record.push_back(VE.getMetadataOrNullID(N->getType())); 2292 2293 Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev); 2294 Record.clear(); 2295 } 2296 2297 void ModuleBitcodeWriter::writeDIImportedEntity( 2298 const DIImportedEntity *N, SmallVectorImpl<uint64_t> &Record, 2299 unsigned Abbrev) { 2300 Record.push_back(N->isDistinct()); 2301 Record.push_back(N->getTag()); 2302 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 2303 Record.push_back(VE.getMetadataOrNullID(N->getEntity())); 2304 Record.push_back(N->getLine()); 2305 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 2306 Record.push_back(VE.getMetadataOrNullID(N->getRawFile())); 2307 Record.push_back(VE.getMetadataOrNullID(N->getElements().get())); 2308 2309 Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev); 2310 Record.clear(); 2311 } 2312 2313 unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() { 2314 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2315 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME)); 2316 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2317 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 2318 return Stream.EmitAbbrev(std::move(Abbv)); 2319 } 2320 2321 void ModuleBitcodeWriter::writeNamedMetadata( 2322 SmallVectorImpl<uint64_t> &Record) { 2323 if (M.named_metadata_empty()) 2324 return; 2325 2326 unsigned Abbrev = createNamedMetadataAbbrev(); 2327 for (const NamedMDNode &NMD : M.named_metadata()) { 2328 // Write name. 2329 StringRef Str = NMD.getName(); 2330 Record.append(Str.bytes_begin(), Str.bytes_end()); 2331 Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev); 2332 Record.clear(); 2333 2334 // Write named metadata operands. 2335 for (const MDNode *N : NMD.operands()) 2336 Record.push_back(VE.getMetadataID(N)); 2337 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0); 2338 Record.clear(); 2339 } 2340 } 2341 2342 unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() { 2343 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2344 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS)); 2345 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings 2346 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars 2347 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 2348 return Stream.EmitAbbrev(std::move(Abbv)); 2349 } 2350 2351 /// Write out a record for MDString. 2352 /// 2353 /// All the metadata strings in a metadata block are emitted in a single 2354 /// record. The sizes and strings themselves are shoved into a blob. 2355 void ModuleBitcodeWriter::writeMetadataStrings( 2356 ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) { 2357 if (Strings.empty()) 2358 return; 2359 2360 // Start the record with the number of strings. 2361 Record.push_back(bitc::METADATA_STRINGS); 2362 Record.push_back(Strings.size()); 2363 2364 // Emit the sizes of the strings in the blob. 2365 SmallString<256> Blob; 2366 { 2367 BitstreamWriter W(Blob); 2368 for (const Metadata *MD : Strings) 2369 W.EmitVBR(cast<MDString>(MD)->getLength(), 6); 2370 W.FlushToWord(); 2371 } 2372 2373 // Add the offset to the strings to the record. 2374 Record.push_back(Blob.size()); 2375 2376 // Add the strings to the blob. 2377 for (const Metadata *MD : Strings) 2378 Blob.append(cast<MDString>(MD)->getString()); 2379 2380 // Emit the final record. 2381 Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob); 2382 Record.clear(); 2383 } 2384 2385 // Generates an enum to use as an index in the Abbrev array of Metadata record. 2386 enum MetadataAbbrev : unsigned { 2387 #define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID, 2388 #include "llvm/IR/Metadata.def" 2389 LastPlusOne 2390 }; 2391 2392 void ModuleBitcodeWriter::writeMetadataRecords( 2393 ArrayRef<const Metadata *> MDs, SmallVectorImpl<uint64_t> &Record, 2394 std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) { 2395 if (MDs.empty()) 2396 return; 2397 2398 // Initialize MDNode abbreviations. 2399 #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0; 2400 #include "llvm/IR/Metadata.def" 2401 2402 for (const Metadata *MD : MDs) { 2403 if (IndexPos) 2404 IndexPos->push_back(Stream.GetCurrentBitNo()); 2405 if (const MDNode *N = dyn_cast<MDNode>(MD)) { 2406 assert(N->isResolved() && "Expected forward references to be resolved"); 2407 2408 switch (N->getMetadataID()) { 2409 default: 2410 llvm_unreachable("Invalid MDNode subclass"); 2411 #define HANDLE_MDNODE_LEAF(CLASS) \ 2412 case Metadata::CLASS##Kind: \ 2413 if (MDAbbrevs) \ 2414 write##CLASS(cast<CLASS>(N), Record, \ 2415 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \ 2416 else \ 2417 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \ 2418 continue; 2419 #include "llvm/IR/Metadata.def" 2420 } 2421 } 2422 if (auto *AL = dyn_cast<DIArgList>(MD)) { 2423 writeDIArgList(AL, Record); 2424 continue; 2425 } 2426 writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record); 2427 } 2428 } 2429 2430 void ModuleBitcodeWriter::writeModuleMetadata() { 2431 if (!VE.hasMDs() && M.named_metadata_empty()) 2432 return; 2433 2434 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 4); 2435 SmallVector<uint64_t, 64> Record; 2436 2437 // Emit all abbrevs upfront, so that the reader can jump in the middle of the 2438 // block and load any metadata. 2439 std::vector<unsigned> MDAbbrevs; 2440 2441 MDAbbrevs.resize(MetadataAbbrev::LastPlusOne); 2442 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev(); 2443 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] = 2444 createGenericDINodeAbbrev(); 2445 2446 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2447 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX_OFFSET)); 2448 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 2449 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 2450 unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 2451 2452 Abbv = std::make_shared<BitCodeAbbrev>(); 2453 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX)); 2454 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2455 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 2456 unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 2457 2458 // Emit MDStrings together upfront. 2459 writeMetadataStrings(VE.getMDStrings(), Record); 2460 2461 // We only emit an index for the metadata record if we have more than a given 2462 // (naive) threshold of metadatas, otherwise it is not worth it. 2463 if (VE.getNonMDStrings().size() > IndexThreshold) { 2464 // Write a placeholder value in for the offset of the metadata index, 2465 // which is written after the records, so that it can include 2466 // the offset of each entry. The placeholder offset will be 2467 // updated after all records are emitted. 2468 uint64_t Vals[] = {0, 0}; 2469 Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev); 2470 } 2471 2472 // Compute and save the bit offset to the current position, which will be 2473 // patched when we emit the index later. We can simply subtract the 64-bit 2474 // fixed size from the current bit number to get the location to backpatch. 2475 uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo(); 2476 2477 // This index will contain the bitpos for each individual record. 2478 std::vector<uint64_t> IndexPos; 2479 IndexPos.reserve(VE.getNonMDStrings().size()); 2480 2481 // Write all the records 2482 writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos); 2483 2484 if (VE.getNonMDStrings().size() > IndexThreshold) { 2485 // Now that we have emitted all the records we will emit the index. But 2486 // first 2487 // backpatch the forward reference so that the reader can skip the records 2488 // efficiently. 2489 Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64, 2490 Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos); 2491 2492 // Delta encode the index. 2493 uint64_t PreviousValue = IndexOffsetRecordBitPos; 2494 for (auto &Elt : IndexPos) { 2495 auto EltDelta = Elt - PreviousValue; 2496 PreviousValue = Elt; 2497 Elt = EltDelta; 2498 } 2499 // Emit the index record. 2500 Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev); 2501 IndexPos.clear(); 2502 } 2503 2504 // Write the named metadata now. 2505 writeNamedMetadata(Record); 2506 2507 auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) { 2508 SmallVector<uint64_t, 4> Record; 2509 Record.push_back(VE.getValueID(&GO)); 2510 pushGlobalMetadataAttachment(Record, GO); 2511 Stream.EmitRecord(bitc::METADATA_GLOBAL_DECL_ATTACHMENT, Record); 2512 }; 2513 for (const Function &F : M) 2514 if (F.isDeclaration() && F.hasMetadata()) 2515 AddDeclAttachedMetadata(F); 2516 // FIXME: Only store metadata for declarations here, and move data for global 2517 // variable definitions to a separate block (PR28134). 2518 for (const GlobalVariable &GV : M.globals()) 2519 if (GV.hasMetadata()) 2520 AddDeclAttachedMetadata(GV); 2521 2522 Stream.ExitBlock(); 2523 } 2524 2525 void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) { 2526 if (!VE.hasMDs()) 2527 return; 2528 2529 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3); 2530 SmallVector<uint64_t, 64> Record; 2531 writeMetadataStrings(VE.getMDStrings(), Record); 2532 writeMetadataRecords(VE.getNonMDStrings(), Record); 2533 Stream.ExitBlock(); 2534 } 2535 2536 void ModuleBitcodeWriter::pushGlobalMetadataAttachment( 2537 SmallVectorImpl<uint64_t> &Record, const GlobalObject &GO) { 2538 // [n x [id, mdnode]] 2539 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 2540 GO.getAllMetadata(MDs); 2541 for (const auto &I : MDs) { 2542 Record.push_back(I.first); 2543 Record.push_back(VE.getMetadataID(I.second)); 2544 } 2545 } 2546 2547 void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) { 2548 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3); 2549 2550 SmallVector<uint64_t, 64> Record; 2551 2552 if (F.hasMetadata()) { 2553 pushGlobalMetadataAttachment(Record, F); 2554 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0); 2555 Record.clear(); 2556 } 2557 2558 // Write metadata attachments 2559 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]] 2560 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 2561 for (const BasicBlock &BB : F) 2562 for (const Instruction &I : BB) { 2563 MDs.clear(); 2564 I.getAllMetadataOtherThanDebugLoc(MDs); 2565 2566 // If no metadata, ignore instruction. 2567 if (MDs.empty()) continue; 2568 2569 Record.push_back(VE.getInstructionID(&I)); 2570 2571 for (unsigned i = 0, e = MDs.size(); i != e; ++i) { 2572 Record.push_back(MDs[i].first); 2573 Record.push_back(VE.getMetadataID(MDs[i].second)); 2574 } 2575 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0); 2576 Record.clear(); 2577 } 2578 2579 Stream.ExitBlock(); 2580 } 2581 2582 void ModuleBitcodeWriter::writeModuleMetadataKinds() { 2583 SmallVector<uint64_t, 64> Record; 2584 2585 // Write metadata kinds 2586 // METADATA_KIND - [n x [id, name]] 2587 SmallVector<StringRef, 8> Names; 2588 M.getMDKindNames(Names); 2589 2590 if (Names.empty()) return; 2591 2592 Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3); 2593 2594 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) { 2595 Record.push_back(MDKindID); 2596 StringRef KName = Names[MDKindID]; 2597 Record.append(KName.begin(), KName.end()); 2598 2599 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0); 2600 Record.clear(); 2601 } 2602 2603 Stream.ExitBlock(); 2604 } 2605 2606 void ModuleBitcodeWriter::writeOperandBundleTags() { 2607 // Write metadata kinds 2608 // 2609 // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG 2610 // 2611 // OPERAND_BUNDLE_TAG - [strchr x N] 2612 2613 SmallVector<StringRef, 8> Tags; 2614 M.getOperandBundleTags(Tags); 2615 2616 if (Tags.empty()) 2617 return; 2618 2619 Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3); 2620 2621 SmallVector<uint64_t, 64> Record; 2622 2623 for (auto Tag : Tags) { 2624 Record.append(Tag.begin(), Tag.end()); 2625 2626 Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0); 2627 Record.clear(); 2628 } 2629 2630 Stream.ExitBlock(); 2631 } 2632 2633 void ModuleBitcodeWriter::writeSyncScopeNames() { 2634 SmallVector<StringRef, 8> SSNs; 2635 M.getContext().getSyncScopeNames(SSNs); 2636 if (SSNs.empty()) 2637 return; 2638 2639 Stream.EnterSubblock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID, 2); 2640 2641 SmallVector<uint64_t, 64> Record; 2642 for (auto SSN : SSNs) { 2643 Record.append(SSN.begin(), SSN.end()); 2644 Stream.EmitRecord(bitc::SYNC_SCOPE_NAME, Record, 0); 2645 Record.clear(); 2646 } 2647 2648 Stream.ExitBlock(); 2649 } 2650 2651 void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal, 2652 bool isGlobal) { 2653 if (FirstVal == LastVal) return; 2654 2655 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4); 2656 2657 unsigned AggregateAbbrev = 0; 2658 unsigned String8Abbrev = 0; 2659 unsigned CString7Abbrev = 0; 2660 unsigned CString6Abbrev = 0; 2661 // If this is a constant pool for the module, emit module-specific abbrevs. 2662 if (isGlobal) { 2663 // Abbrev for CST_CODE_AGGREGATE. 2664 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2665 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE)); 2666 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2667 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1))); 2668 AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 2669 2670 // Abbrev for CST_CODE_STRING. 2671 Abbv = std::make_shared<BitCodeAbbrev>(); 2672 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING)); 2673 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2674 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 2675 String8Abbrev = Stream.EmitAbbrev(std::move(Abbv)); 2676 // Abbrev for CST_CODE_CSTRING. 2677 Abbv = std::make_shared<BitCodeAbbrev>(); 2678 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING)); 2679 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2680 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); 2681 CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv)); 2682 // Abbrev for CST_CODE_CSTRING. 2683 Abbv = std::make_shared<BitCodeAbbrev>(); 2684 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING)); 2685 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2686 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 2687 CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv)); 2688 } 2689 2690 SmallVector<uint64_t, 64> Record; 2691 2692 const ValueEnumerator::ValueList &Vals = VE.getValues(); 2693 Type *LastTy = nullptr; 2694 for (unsigned i = FirstVal; i != LastVal; ++i) { 2695 const Value *V = Vals[i].first; 2696 // If we need to switch types, do so now. 2697 if (V->getType() != LastTy) { 2698 LastTy = V->getType(); 2699 Record.push_back(VE.getTypeID(LastTy)); 2700 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record, 2701 CONSTANTS_SETTYPE_ABBREV); 2702 Record.clear(); 2703 } 2704 2705 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) { 2706 Record.push_back(VE.getTypeID(IA->getFunctionType())); 2707 Record.push_back( 2708 unsigned(IA->hasSideEffects()) | unsigned(IA->isAlignStack()) << 1 | 2709 unsigned(IA->getDialect() & 1) << 2 | unsigned(IA->canThrow()) << 3); 2710 2711 // Add the asm string. 2712 const std::string &AsmStr = IA->getAsmString(); 2713 Record.push_back(AsmStr.size()); 2714 Record.append(AsmStr.begin(), AsmStr.end()); 2715 2716 // Add the constraint string. 2717 const std::string &ConstraintStr = IA->getConstraintString(); 2718 Record.push_back(ConstraintStr.size()); 2719 Record.append(ConstraintStr.begin(), ConstraintStr.end()); 2720 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record); 2721 Record.clear(); 2722 continue; 2723 } 2724 const Constant *C = cast<Constant>(V); 2725 unsigned Code = -1U; 2726 unsigned AbbrevToUse = 0; 2727 if (C->isNullValue()) { 2728 Code = bitc::CST_CODE_NULL; 2729 } else if (isa<PoisonValue>(C)) { 2730 Code = bitc::CST_CODE_POISON; 2731 } else if (isa<UndefValue>(C)) { 2732 Code = bitc::CST_CODE_UNDEF; 2733 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) { 2734 if (IV->getBitWidth() <= 64) { 2735 uint64_t V = IV->getSExtValue(); 2736 emitSignedInt64(Record, V); 2737 Code = bitc::CST_CODE_INTEGER; 2738 AbbrevToUse = CONSTANTS_INTEGER_ABBREV; 2739 } else { // Wide integers, > 64 bits in size. 2740 emitWideAPInt(Record, IV->getValue()); 2741 Code = bitc::CST_CODE_WIDE_INTEGER; 2742 } 2743 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) { 2744 Code = bitc::CST_CODE_FLOAT; 2745 Type *Ty = CFP->getType()->getScalarType(); 2746 if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() || 2747 Ty->isDoubleTy()) { 2748 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue()); 2749 } else if (Ty->isX86_FP80Ty()) { 2750 // api needed to prevent premature destruction 2751 // bits are not in the same order as a normal i80 APInt, compensate. 2752 APInt api = CFP->getValueAPF().bitcastToAPInt(); 2753 const uint64_t *p = api.getRawData(); 2754 Record.push_back((p[1] << 48) | (p[0] >> 16)); 2755 Record.push_back(p[0] & 0xffffLL); 2756 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) { 2757 APInt api = CFP->getValueAPF().bitcastToAPInt(); 2758 const uint64_t *p = api.getRawData(); 2759 Record.push_back(p[0]); 2760 Record.push_back(p[1]); 2761 } else { 2762 assert(0 && "Unknown FP type!"); 2763 } 2764 } else if (isa<ConstantDataSequential>(C) && 2765 cast<ConstantDataSequential>(C)->isString()) { 2766 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C); 2767 // Emit constant strings specially. 2768 unsigned NumElts = Str->getNumElements(); 2769 // If this is a null-terminated string, use the denser CSTRING encoding. 2770 if (Str->isCString()) { 2771 Code = bitc::CST_CODE_CSTRING; 2772 --NumElts; // Don't encode the null, which isn't allowed by char6. 2773 } else { 2774 Code = bitc::CST_CODE_STRING; 2775 AbbrevToUse = String8Abbrev; 2776 } 2777 bool isCStr7 = Code == bitc::CST_CODE_CSTRING; 2778 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING; 2779 for (unsigned i = 0; i != NumElts; ++i) { 2780 unsigned char V = Str->getElementAsInteger(i); 2781 Record.push_back(V); 2782 isCStr7 &= (V & 128) == 0; 2783 if (isCStrChar6) 2784 isCStrChar6 = BitCodeAbbrevOp::isChar6(V); 2785 } 2786 2787 if (isCStrChar6) 2788 AbbrevToUse = CString6Abbrev; 2789 else if (isCStr7) 2790 AbbrevToUse = CString7Abbrev; 2791 } else if (const ConstantDataSequential *CDS = 2792 dyn_cast<ConstantDataSequential>(C)) { 2793 Code = bitc::CST_CODE_DATA; 2794 Type *EltTy = CDS->getElementType(); 2795 if (isa<IntegerType>(EltTy)) { 2796 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) 2797 Record.push_back(CDS->getElementAsInteger(i)); 2798 } else { 2799 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) 2800 Record.push_back( 2801 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue()); 2802 } 2803 } else if (isa<ConstantAggregate>(C)) { 2804 Code = bitc::CST_CODE_AGGREGATE; 2805 for (const Value *Op : C->operands()) 2806 Record.push_back(VE.getValueID(Op)); 2807 AbbrevToUse = AggregateAbbrev; 2808 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 2809 switch (CE->getOpcode()) { 2810 default: 2811 if (Instruction::isCast(CE->getOpcode())) { 2812 Code = bitc::CST_CODE_CE_CAST; 2813 Record.push_back(getEncodedCastOpcode(CE->getOpcode())); 2814 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 2815 Record.push_back(VE.getValueID(C->getOperand(0))); 2816 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev; 2817 } else { 2818 assert(CE->getNumOperands() == 2 && "Unknown constant expr!"); 2819 Code = bitc::CST_CODE_CE_BINOP; 2820 Record.push_back(getEncodedBinaryOpcode(CE->getOpcode())); 2821 Record.push_back(VE.getValueID(C->getOperand(0))); 2822 Record.push_back(VE.getValueID(C->getOperand(1))); 2823 uint64_t Flags = getOptimizationFlags(CE); 2824 if (Flags != 0) 2825 Record.push_back(Flags); 2826 } 2827 break; 2828 case Instruction::FNeg: { 2829 assert(CE->getNumOperands() == 1 && "Unknown constant expr!"); 2830 Code = bitc::CST_CODE_CE_UNOP; 2831 Record.push_back(getEncodedUnaryOpcode(CE->getOpcode())); 2832 Record.push_back(VE.getValueID(C->getOperand(0))); 2833 uint64_t Flags = getOptimizationFlags(CE); 2834 if (Flags != 0) 2835 Record.push_back(Flags); 2836 break; 2837 } 2838 case Instruction::GetElementPtr: { 2839 Code = bitc::CST_CODE_CE_GEP; 2840 const auto *GO = cast<GEPOperator>(C); 2841 Record.push_back(VE.getTypeID(GO->getSourceElementType())); 2842 Record.push_back(getOptimizationFlags(GO)); 2843 if (std::optional<ConstantRange> Range = GO->getInRange()) { 2844 Code = bitc::CST_CODE_CE_GEP_WITH_INRANGE; 2845 emitConstantRange(Record, *Range, /*EmitBitWidth=*/true); 2846 } 2847 for (const Value *Op : CE->operands()) { 2848 Record.push_back(VE.getTypeID(Op->getType())); 2849 Record.push_back(VE.getValueID(Op)); 2850 } 2851 break; 2852 } 2853 case Instruction::ExtractElement: 2854 Code = bitc::CST_CODE_CE_EXTRACTELT; 2855 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 2856 Record.push_back(VE.getValueID(C->getOperand(0))); 2857 Record.push_back(VE.getTypeID(C->getOperand(1)->getType())); 2858 Record.push_back(VE.getValueID(C->getOperand(1))); 2859 break; 2860 case Instruction::InsertElement: 2861 Code = bitc::CST_CODE_CE_INSERTELT; 2862 Record.push_back(VE.getValueID(C->getOperand(0))); 2863 Record.push_back(VE.getValueID(C->getOperand(1))); 2864 Record.push_back(VE.getTypeID(C->getOperand(2)->getType())); 2865 Record.push_back(VE.getValueID(C->getOperand(2))); 2866 break; 2867 case Instruction::ShuffleVector: 2868 // If the return type and argument types are the same, this is a 2869 // standard shufflevector instruction. If the types are different, 2870 // then the shuffle is widening or truncating the input vectors, and 2871 // the argument type must also be encoded. 2872 if (C->getType() == C->getOperand(0)->getType()) { 2873 Code = bitc::CST_CODE_CE_SHUFFLEVEC; 2874 } else { 2875 Code = bitc::CST_CODE_CE_SHUFVEC_EX; 2876 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 2877 } 2878 Record.push_back(VE.getValueID(C->getOperand(0))); 2879 Record.push_back(VE.getValueID(C->getOperand(1))); 2880 Record.push_back(VE.getValueID(CE->getShuffleMaskForBitcode())); 2881 break; 2882 } 2883 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) { 2884 Code = bitc::CST_CODE_BLOCKADDRESS; 2885 Record.push_back(VE.getTypeID(BA->getFunction()->getType())); 2886 Record.push_back(VE.getValueID(BA->getFunction())); 2887 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock())); 2888 } else if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) { 2889 Code = bitc::CST_CODE_DSO_LOCAL_EQUIVALENT; 2890 Record.push_back(VE.getTypeID(Equiv->getGlobalValue()->getType())); 2891 Record.push_back(VE.getValueID(Equiv->getGlobalValue())); 2892 } else if (const auto *NC = dyn_cast<NoCFIValue>(C)) { 2893 Code = bitc::CST_CODE_NO_CFI_VALUE; 2894 Record.push_back(VE.getTypeID(NC->getGlobalValue()->getType())); 2895 Record.push_back(VE.getValueID(NC->getGlobalValue())); 2896 } else if (const auto *CPA = dyn_cast<ConstantPtrAuth>(C)) { 2897 Code = bitc::CST_CODE_PTRAUTH; 2898 Record.push_back(VE.getValueID(CPA->getPointer())); 2899 Record.push_back(VE.getValueID(CPA->getKey())); 2900 Record.push_back(VE.getValueID(CPA->getDiscriminator())); 2901 Record.push_back(VE.getValueID(CPA->getAddrDiscriminator())); 2902 } else { 2903 #ifndef NDEBUG 2904 C->dump(); 2905 #endif 2906 llvm_unreachable("Unknown constant!"); 2907 } 2908 Stream.EmitRecord(Code, Record, AbbrevToUse); 2909 Record.clear(); 2910 } 2911 2912 Stream.ExitBlock(); 2913 } 2914 2915 void ModuleBitcodeWriter::writeModuleConstants() { 2916 const ValueEnumerator::ValueList &Vals = VE.getValues(); 2917 2918 // Find the first constant to emit, which is the first non-globalvalue value. 2919 // We know globalvalues have been emitted by WriteModuleInfo. 2920 for (unsigned i = 0, e = Vals.size(); i != e; ++i) { 2921 if (!isa<GlobalValue>(Vals[i].first)) { 2922 writeConstants(i, Vals.size(), true); 2923 return; 2924 } 2925 } 2926 } 2927 2928 /// pushValueAndType - The file has to encode both the value and type id for 2929 /// many values, because we need to know what type to create for forward 2930 /// references. However, most operands are not forward references, so this type 2931 /// field is not needed. 2932 /// 2933 /// This function adds V's value ID to Vals. If the value ID is higher than the 2934 /// instruction ID, then it is a forward reference, and it also includes the 2935 /// type ID. The value ID that is written is encoded relative to the InstID. 2936 bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID, 2937 SmallVectorImpl<unsigned> &Vals) { 2938 unsigned ValID = VE.getValueID(V); 2939 // Make encoding relative to the InstID. 2940 Vals.push_back(InstID - ValID); 2941 if (ValID >= InstID) { 2942 Vals.push_back(VE.getTypeID(V->getType())); 2943 return true; 2944 } 2945 return false; 2946 } 2947 2948 bool ModuleBitcodeWriter::pushValueOrMetadata(const Value *V, unsigned InstID, 2949 SmallVectorImpl<unsigned> &Vals) { 2950 bool IsMetadata = V->getType()->isMetadataTy(); 2951 if (IsMetadata) { 2952 Vals.push_back(bitc::OB_METADATA); 2953 Metadata *MD = cast<MetadataAsValue>(V)->getMetadata(); 2954 unsigned ValID = VE.getMetadataID(MD); 2955 Vals.push_back(InstID - ValID); 2956 return false; 2957 } 2958 return pushValueAndType(V, InstID, Vals); 2959 } 2960 2961 void ModuleBitcodeWriter::writeOperandBundles(const CallBase &CS, 2962 unsigned InstID) { 2963 SmallVector<unsigned, 64> Record; 2964 LLVMContext &C = CS.getContext(); 2965 2966 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) { 2967 const auto &Bundle = CS.getOperandBundleAt(i); 2968 Record.push_back(C.getOperandBundleTagID(Bundle.getTagName())); 2969 2970 for (auto &Input : Bundle.Inputs) 2971 pushValueOrMetadata(Input, InstID, Record); 2972 2973 Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record); 2974 Record.clear(); 2975 } 2976 } 2977 2978 /// pushValue - Like pushValueAndType, but where the type of the value is 2979 /// omitted (perhaps it was already encoded in an earlier operand). 2980 void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID, 2981 SmallVectorImpl<unsigned> &Vals) { 2982 unsigned ValID = VE.getValueID(V); 2983 Vals.push_back(InstID - ValID); 2984 } 2985 2986 void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID, 2987 SmallVectorImpl<uint64_t> &Vals) { 2988 unsigned ValID = VE.getValueID(V); 2989 int64_t diff = ((int32_t)InstID - (int32_t)ValID); 2990 emitSignedInt64(Vals, diff); 2991 } 2992 2993 /// WriteInstruction - Emit an instruction to the specified stream. 2994 void ModuleBitcodeWriter::writeInstruction(const Instruction &I, 2995 unsigned InstID, 2996 SmallVectorImpl<unsigned> &Vals) { 2997 unsigned Code = 0; 2998 unsigned AbbrevToUse = 0; 2999 VE.setInstructionID(&I); 3000 switch (I.getOpcode()) { 3001 default: 3002 if (Instruction::isCast(I.getOpcode())) { 3003 Code = bitc::FUNC_CODE_INST_CAST; 3004 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) 3005 AbbrevToUse = FUNCTION_INST_CAST_ABBREV; 3006 Vals.push_back(VE.getTypeID(I.getType())); 3007 Vals.push_back(getEncodedCastOpcode(I.getOpcode())); 3008 uint64_t Flags = getOptimizationFlags(&I); 3009 if (Flags != 0) { 3010 if (AbbrevToUse == FUNCTION_INST_CAST_ABBREV) 3011 AbbrevToUse = FUNCTION_INST_CAST_FLAGS_ABBREV; 3012 Vals.push_back(Flags); 3013 } 3014 } else { 3015 assert(isa<BinaryOperator>(I) && "Unknown instruction!"); 3016 Code = bitc::FUNC_CODE_INST_BINOP; 3017 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) 3018 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV; 3019 pushValue(I.getOperand(1), InstID, Vals); 3020 Vals.push_back(getEncodedBinaryOpcode(I.getOpcode())); 3021 uint64_t Flags = getOptimizationFlags(&I); 3022 if (Flags != 0) { 3023 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV) 3024 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV; 3025 Vals.push_back(Flags); 3026 } 3027 } 3028 break; 3029 case Instruction::FNeg: { 3030 Code = bitc::FUNC_CODE_INST_UNOP; 3031 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) 3032 AbbrevToUse = FUNCTION_INST_UNOP_ABBREV; 3033 Vals.push_back(getEncodedUnaryOpcode(I.getOpcode())); 3034 uint64_t Flags = getOptimizationFlags(&I); 3035 if (Flags != 0) { 3036 if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV) 3037 AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV; 3038 Vals.push_back(Flags); 3039 } 3040 break; 3041 } 3042 case Instruction::GetElementPtr: { 3043 Code = bitc::FUNC_CODE_INST_GEP; 3044 AbbrevToUse = FUNCTION_INST_GEP_ABBREV; 3045 auto &GEPInst = cast<GetElementPtrInst>(I); 3046 Vals.push_back(getOptimizationFlags(&I)); 3047 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType())); 3048 for (const Value *Op : I.operands()) 3049 pushValueAndType(Op, InstID, Vals); 3050 break; 3051 } 3052 case Instruction::ExtractValue: { 3053 Code = bitc::FUNC_CODE_INST_EXTRACTVAL; 3054 pushValueAndType(I.getOperand(0), InstID, Vals); 3055 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I); 3056 Vals.append(EVI->idx_begin(), EVI->idx_end()); 3057 break; 3058 } 3059 case Instruction::InsertValue: { 3060 Code = bitc::FUNC_CODE_INST_INSERTVAL; 3061 pushValueAndType(I.getOperand(0), InstID, Vals); 3062 pushValueAndType(I.getOperand(1), InstID, Vals); 3063 const InsertValueInst *IVI = cast<InsertValueInst>(&I); 3064 Vals.append(IVI->idx_begin(), IVI->idx_end()); 3065 break; 3066 } 3067 case Instruction::Select: { 3068 Code = bitc::FUNC_CODE_INST_VSELECT; 3069 pushValueAndType(I.getOperand(1), InstID, Vals); 3070 pushValue(I.getOperand(2), InstID, Vals); 3071 pushValueAndType(I.getOperand(0), InstID, Vals); 3072 uint64_t Flags = getOptimizationFlags(&I); 3073 if (Flags != 0) 3074 Vals.push_back(Flags); 3075 break; 3076 } 3077 case Instruction::ExtractElement: 3078 Code = bitc::FUNC_CODE_INST_EXTRACTELT; 3079 pushValueAndType(I.getOperand(0), InstID, Vals); 3080 pushValueAndType(I.getOperand(1), InstID, Vals); 3081 break; 3082 case Instruction::InsertElement: 3083 Code = bitc::FUNC_CODE_INST_INSERTELT; 3084 pushValueAndType(I.getOperand(0), InstID, Vals); 3085 pushValue(I.getOperand(1), InstID, Vals); 3086 pushValueAndType(I.getOperand(2), InstID, Vals); 3087 break; 3088 case Instruction::ShuffleVector: 3089 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC; 3090 pushValueAndType(I.getOperand(0), InstID, Vals); 3091 pushValue(I.getOperand(1), InstID, Vals); 3092 pushValue(cast<ShuffleVectorInst>(I).getShuffleMaskForBitcode(), InstID, 3093 Vals); 3094 break; 3095 case Instruction::ICmp: 3096 case Instruction::FCmp: { 3097 // compare returning Int1Ty or vector of Int1Ty 3098 Code = bitc::FUNC_CODE_INST_CMP2; 3099 pushValueAndType(I.getOperand(0), InstID, Vals); 3100 pushValue(I.getOperand(1), InstID, Vals); 3101 Vals.push_back(cast<CmpInst>(I).getPredicate()); 3102 uint64_t Flags = getOptimizationFlags(&I); 3103 if (Flags != 0) 3104 Vals.push_back(Flags); 3105 break; 3106 } 3107 3108 case Instruction::Ret: 3109 { 3110 Code = bitc::FUNC_CODE_INST_RET; 3111 unsigned NumOperands = I.getNumOperands(); 3112 if (NumOperands == 0) 3113 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV; 3114 else if (NumOperands == 1) { 3115 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) 3116 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV; 3117 } else { 3118 for (const Value *Op : I.operands()) 3119 pushValueAndType(Op, InstID, Vals); 3120 } 3121 } 3122 break; 3123 case Instruction::Br: 3124 { 3125 Code = bitc::FUNC_CODE_INST_BR; 3126 const BranchInst &II = cast<BranchInst>(I); 3127 Vals.push_back(VE.getValueID(II.getSuccessor(0))); 3128 if (II.isConditional()) { 3129 Vals.push_back(VE.getValueID(II.getSuccessor(1))); 3130 pushValue(II.getCondition(), InstID, Vals); 3131 } 3132 } 3133 break; 3134 case Instruction::Switch: 3135 { 3136 Code = bitc::FUNC_CODE_INST_SWITCH; 3137 const SwitchInst &SI = cast<SwitchInst>(I); 3138 Vals.push_back(VE.getTypeID(SI.getCondition()->getType())); 3139 pushValue(SI.getCondition(), InstID, Vals); 3140 Vals.push_back(VE.getValueID(SI.getDefaultDest())); 3141 for (auto Case : SI.cases()) { 3142 Vals.push_back(VE.getValueID(Case.getCaseValue())); 3143 Vals.push_back(VE.getValueID(Case.getCaseSuccessor())); 3144 } 3145 } 3146 break; 3147 case Instruction::IndirectBr: 3148 Code = bitc::FUNC_CODE_INST_INDIRECTBR; 3149 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); 3150 // Encode the address operand as relative, but not the basic blocks. 3151 pushValue(I.getOperand(0), InstID, Vals); 3152 for (const Value *Op : drop_begin(I.operands())) 3153 Vals.push_back(VE.getValueID(Op)); 3154 break; 3155 3156 case Instruction::Invoke: { 3157 const InvokeInst *II = cast<InvokeInst>(&I); 3158 const Value *Callee = II->getCalledOperand(); 3159 FunctionType *FTy = II->getFunctionType(); 3160 3161 if (II->hasOperandBundles()) 3162 writeOperandBundles(*II, InstID); 3163 3164 Code = bitc::FUNC_CODE_INST_INVOKE; 3165 3166 Vals.push_back(VE.getAttributeListID(II->getAttributes())); 3167 Vals.push_back(II->getCallingConv() | 1 << 13); 3168 Vals.push_back(VE.getValueID(II->getNormalDest())); 3169 Vals.push_back(VE.getValueID(II->getUnwindDest())); 3170 Vals.push_back(VE.getTypeID(FTy)); 3171 pushValueAndType(Callee, InstID, Vals); 3172 3173 // Emit value #'s for the fixed parameters. 3174 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) 3175 pushValue(I.getOperand(i), InstID, Vals); // fixed param. 3176 3177 // Emit type/value pairs for varargs params. 3178 if (FTy->isVarArg()) { 3179 for (unsigned i = FTy->getNumParams(), e = II->arg_size(); i != e; ++i) 3180 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg 3181 } 3182 break; 3183 } 3184 case Instruction::Resume: 3185 Code = bitc::FUNC_CODE_INST_RESUME; 3186 pushValueAndType(I.getOperand(0), InstID, Vals); 3187 break; 3188 case Instruction::CleanupRet: { 3189 Code = bitc::FUNC_CODE_INST_CLEANUPRET; 3190 const auto &CRI = cast<CleanupReturnInst>(I); 3191 pushValue(CRI.getCleanupPad(), InstID, Vals); 3192 if (CRI.hasUnwindDest()) 3193 Vals.push_back(VE.getValueID(CRI.getUnwindDest())); 3194 break; 3195 } 3196 case Instruction::CatchRet: { 3197 Code = bitc::FUNC_CODE_INST_CATCHRET; 3198 const auto &CRI = cast<CatchReturnInst>(I); 3199 pushValue(CRI.getCatchPad(), InstID, Vals); 3200 Vals.push_back(VE.getValueID(CRI.getSuccessor())); 3201 break; 3202 } 3203 case Instruction::CleanupPad: 3204 case Instruction::CatchPad: { 3205 const auto &FuncletPad = cast<FuncletPadInst>(I); 3206 Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD 3207 : bitc::FUNC_CODE_INST_CLEANUPPAD; 3208 pushValue(FuncletPad.getParentPad(), InstID, Vals); 3209 3210 unsigned NumArgOperands = FuncletPad.arg_size(); 3211 Vals.push_back(NumArgOperands); 3212 for (unsigned Op = 0; Op != NumArgOperands; ++Op) 3213 pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals); 3214 break; 3215 } 3216 case Instruction::CatchSwitch: { 3217 Code = bitc::FUNC_CODE_INST_CATCHSWITCH; 3218 const auto &CatchSwitch = cast<CatchSwitchInst>(I); 3219 3220 pushValue(CatchSwitch.getParentPad(), InstID, Vals); 3221 3222 unsigned NumHandlers = CatchSwitch.getNumHandlers(); 3223 Vals.push_back(NumHandlers); 3224 for (const BasicBlock *CatchPadBB : CatchSwitch.handlers()) 3225 Vals.push_back(VE.getValueID(CatchPadBB)); 3226 3227 if (CatchSwitch.hasUnwindDest()) 3228 Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest())); 3229 break; 3230 } 3231 case Instruction::CallBr: { 3232 const CallBrInst *CBI = cast<CallBrInst>(&I); 3233 const Value *Callee = CBI->getCalledOperand(); 3234 FunctionType *FTy = CBI->getFunctionType(); 3235 3236 if (CBI->hasOperandBundles()) 3237 writeOperandBundles(*CBI, InstID); 3238 3239 Code = bitc::FUNC_CODE_INST_CALLBR; 3240 3241 Vals.push_back(VE.getAttributeListID(CBI->getAttributes())); 3242 3243 Vals.push_back(CBI->getCallingConv() << bitc::CALL_CCONV | 3244 1 << bitc::CALL_EXPLICIT_TYPE); 3245 3246 Vals.push_back(VE.getValueID(CBI->getDefaultDest())); 3247 Vals.push_back(CBI->getNumIndirectDests()); 3248 for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i) 3249 Vals.push_back(VE.getValueID(CBI->getIndirectDest(i))); 3250 3251 Vals.push_back(VE.getTypeID(FTy)); 3252 pushValueAndType(Callee, InstID, Vals); 3253 3254 // Emit value #'s for the fixed parameters. 3255 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) 3256 pushValue(I.getOperand(i), InstID, Vals); // fixed param. 3257 3258 // Emit type/value pairs for varargs params. 3259 if (FTy->isVarArg()) { 3260 for (unsigned i = FTy->getNumParams(), e = CBI->arg_size(); i != e; ++i) 3261 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg 3262 } 3263 break; 3264 } 3265 case Instruction::Unreachable: 3266 Code = bitc::FUNC_CODE_INST_UNREACHABLE; 3267 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV; 3268 break; 3269 3270 case Instruction::PHI: { 3271 const PHINode &PN = cast<PHINode>(I); 3272 Code = bitc::FUNC_CODE_INST_PHI; 3273 // With the newer instruction encoding, forward references could give 3274 // negative valued IDs. This is most common for PHIs, so we use 3275 // signed VBRs. 3276 SmallVector<uint64_t, 128> Vals64; 3277 Vals64.push_back(VE.getTypeID(PN.getType())); 3278 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) { 3279 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64); 3280 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i))); 3281 } 3282 3283 uint64_t Flags = getOptimizationFlags(&I); 3284 if (Flags != 0) 3285 Vals64.push_back(Flags); 3286 3287 // Emit a Vals64 vector and exit. 3288 Stream.EmitRecord(Code, Vals64, AbbrevToUse); 3289 Vals64.clear(); 3290 return; 3291 } 3292 3293 case Instruction::LandingPad: { 3294 const LandingPadInst &LP = cast<LandingPadInst>(I); 3295 Code = bitc::FUNC_CODE_INST_LANDINGPAD; 3296 Vals.push_back(VE.getTypeID(LP.getType())); 3297 Vals.push_back(LP.isCleanup()); 3298 Vals.push_back(LP.getNumClauses()); 3299 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) { 3300 if (LP.isCatch(I)) 3301 Vals.push_back(LandingPadInst::Catch); 3302 else 3303 Vals.push_back(LandingPadInst::Filter); 3304 pushValueAndType(LP.getClause(I), InstID, Vals); 3305 } 3306 break; 3307 } 3308 3309 case Instruction::Alloca: { 3310 Code = bitc::FUNC_CODE_INST_ALLOCA; 3311 const AllocaInst &AI = cast<AllocaInst>(I); 3312 Vals.push_back(VE.getTypeID(AI.getAllocatedType())); 3313 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); 3314 Vals.push_back(VE.getValueID(I.getOperand(0))); // size. 3315 using APV = AllocaPackedValues; 3316 unsigned Record = 0; 3317 unsigned EncodedAlign = getEncodedAlign(AI.getAlign()); 3318 Bitfield::set<APV::AlignLower>( 3319 Record, EncodedAlign & ((1 << APV::AlignLower::Bits) - 1)); 3320 Bitfield::set<APV::AlignUpper>(Record, 3321 EncodedAlign >> APV::AlignLower::Bits); 3322 Bitfield::set<APV::UsedWithInAlloca>(Record, AI.isUsedWithInAlloca()); 3323 Bitfield::set<APV::ExplicitType>(Record, true); 3324 Bitfield::set<APV::SwiftError>(Record, AI.isSwiftError()); 3325 Vals.push_back(Record); 3326 3327 unsigned AS = AI.getAddressSpace(); 3328 if (AS != M.getDataLayout().getAllocaAddrSpace()) 3329 Vals.push_back(AS); 3330 break; 3331 } 3332 3333 case Instruction::Load: 3334 if (cast<LoadInst>(I).isAtomic()) { 3335 Code = bitc::FUNC_CODE_INST_LOADATOMIC; 3336 pushValueAndType(I.getOperand(0), InstID, Vals); 3337 } else { 3338 Code = bitc::FUNC_CODE_INST_LOAD; 3339 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr 3340 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV; 3341 } 3342 Vals.push_back(VE.getTypeID(I.getType())); 3343 Vals.push_back(getEncodedAlign(cast<LoadInst>(I).getAlign())); 3344 Vals.push_back(cast<LoadInst>(I).isVolatile()); 3345 if (cast<LoadInst>(I).isAtomic()) { 3346 Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering())); 3347 Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID())); 3348 } 3349 break; 3350 case Instruction::Store: 3351 if (cast<StoreInst>(I).isAtomic()) 3352 Code = bitc::FUNC_CODE_INST_STOREATOMIC; 3353 else 3354 Code = bitc::FUNC_CODE_INST_STORE; 3355 pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr 3356 pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val 3357 Vals.push_back(getEncodedAlign(cast<StoreInst>(I).getAlign())); 3358 Vals.push_back(cast<StoreInst>(I).isVolatile()); 3359 if (cast<StoreInst>(I).isAtomic()) { 3360 Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering())); 3361 Vals.push_back( 3362 getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID())); 3363 } 3364 break; 3365 case Instruction::AtomicCmpXchg: 3366 Code = bitc::FUNC_CODE_INST_CMPXCHG; 3367 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr 3368 pushValueAndType(I.getOperand(1), InstID, Vals); // cmp. 3369 pushValue(I.getOperand(2), InstID, Vals); // newval. 3370 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile()); 3371 Vals.push_back( 3372 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering())); 3373 Vals.push_back( 3374 getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID())); 3375 Vals.push_back( 3376 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering())); 3377 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak()); 3378 Vals.push_back(getEncodedAlign(cast<AtomicCmpXchgInst>(I).getAlign())); 3379 break; 3380 case Instruction::AtomicRMW: 3381 Code = bitc::FUNC_CODE_INST_ATOMICRMW; 3382 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr 3383 pushValueAndType(I.getOperand(1), InstID, Vals); // valty + val 3384 Vals.push_back( 3385 getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation())); 3386 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile()); 3387 Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering())); 3388 Vals.push_back( 3389 getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID())); 3390 Vals.push_back(getEncodedAlign(cast<AtomicRMWInst>(I).getAlign())); 3391 break; 3392 case Instruction::Fence: 3393 Code = bitc::FUNC_CODE_INST_FENCE; 3394 Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering())); 3395 Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID())); 3396 break; 3397 case Instruction::Call: { 3398 const CallInst &CI = cast<CallInst>(I); 3399 FunctionType *FTy = CI.getFunctionType(); 3400 3401 if (CI.hasOperandBundles()) 3402 writeOperandBundles(CI, InstID); 3403 3404 Code = bitc::FUNC_CODE_INST_CALL; 3405 3406 Vals.push_back(VE.getAttributeListID(CI.getAttributes())); 3407 3408 unsigned Flags = getOptimizationFlags(&I); 3409 Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV | 3410 unsigned(CI.isTailCall()) << bitc::CALL_TAIL | 3411 unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL | 3412 1 << bitc::CALL_EXPLICIT_TYPE | 3413 unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL | 3414 unsigned(Flags != 0) << bitc::CALL_FMF); 3415 if (Flags != 0) 3416 Vals.push_back(Flags); 3417 3418 Vals.push_back(VE.getTypeID(FTy)); 3419 pushValueAndType(CI.getCalledOperand(), InstID, Vals); // Callee 3420 3421 // Emit value #'s for the fixed parameters. 3422 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) { 3423 // Check for labels (can happen with asm labels). 3424 if (FTy->getParamType(i)->isLabelTy()) 3425 Vals.push_back(VE.getValueID(CI.getArgOperand(i))); 3426 else 3427 pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param. 3428 } 3429 3430 // Emit type/value pairs for varargs params. 3431 if (FTy->isVarArg()) { 3432 for (unsigned i = FTy->getNumParams(), e = CI.arg_size(); i != e; ++i) 3433 pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs 3434 } 3435 break; 3436 } 3437 case Instruction::VAArg: 3438 Code = bitc::FUNC_CODE_INST_VAARG; 3439 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty 3440 pushValue(I.getOperand(0), InstID, Vals); // valist. 3441 Vals.push_back(VE.getTypeID(I.getType())); // restype. 3442 break; 3443 case Instruction::Freeze: 3444 Code = bitc::FUNC_CODE_INST_FREEZE; 3445 pushValueAndType(I.getOperand(0), InstID, Vals); 3446 break; 3447 } 3448 3449 Stream.EmitRecord(Code, Vals, AbbrevToUse); 3450 Vals.clear(); 3451 } 3452 3453 /// Write a GlobalValue VST to the module. The purpose of this data structure is 3454 /// to allow clients to efficiently find the function body. 3455 void ModuleBitcodeWriter::writeGlobalValueSymbolTable( 3456 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) { 3457 // Get the offset of the VST we are writing, and backpatch it into 3458 // the VST forward declaration record. 3459 uint64_t VSTOffset = Stream.GetCurrentBitNo(); 3460 // The BitcodeStartBit was the stream offset of the identification block. 3461 VSTOffset -= bitcodeStartBit(); 3462 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned"); 3463 // Note that we add 1 here because the offset is relative to one word 3464 // before the start of the identification block, which was historically 3465 // always the start of the regular bitcode header. 3466 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1); 3467 3468 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4); 3469 3470 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3471 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY)); 3472 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id 3473 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset 3474 unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 3475 3476 for (const Function &F : M) { 3477 uint64_t Record[2]; 3478 3479 if (F.isDeclaration()) 3480 continue; 3481 3482 Record[0] = VE.getValueID(&F); 3483 3484 // Save the word offset of the function (from the start of the 3485 // actual bitcode written to the stream). 3486 uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit(); 3487 assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned"); 3488 // Note that we add 1 here because the offset is relative to one word 3489 // before the start of the identification block, which was historically 3490 // always the start of the regular bitcode header. 3491 Record[1] = BitcodeIndex / 32 + 1; 3492 3493 Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev); 3494 } 3495 3496 Stream.ExitBlock(); 3497 } 3498 3499 /// Emit names for arguments, instructions and basic blocks in a function. 3500 void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable( 3501 const ValueSymbolTable &VST) { 3502 if (VST.empty()) 3503 return; 3504 3505 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4); 3506 3507 // FIXME: Set up the abbrev, we know how many values there are! 3508 // FIXME: We know if the type names can use 7-bit ascii. 3509 SmallVector<uint64_t, 64> NameVals; 3510 3511 for (const ValueName &Name : VST) { 3512 // Figure out the encoding to use for the name. 3513 StringEncoding Bits = getStringEncoding(Name.getKey()); 3514 3515 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV; 3516 NameVals.push_back(VE.getValueID(Name.getValue())); 3517 3518 // VST_CODE_ENTRY: [valueid, namechar x N] 3519 // VST_CODE_BBENTRY: [bbid, namechar x N] 3520 unsigned Code; 3521 if (isa<BasicBlock>(Name.getValue())) { 3522 Code = bitc::VST_CODE_BBENTRY; 3523 if (Bits == SE_Char6) 3524 AbbrevToUse = VST_BBENTRY_6_ABBREV; 3525 } else { 3526 Code = bitc::VST_CODE_ENTRY; 3527 if (Bits == SE_Char6) 3528 AbbrevToUse = VST_ENTRY_6_ABBREV; 3529 else if (Bits == SE_Fixed7) 3530 AbbrevToUse = VST_ENTRY_7_ABBREV; 3531 } 3532 3533 for (const auto P : Name.getKey()) 3534 NameVals.push_back((unsigned char)P); 3535 3536 // Emit the finished record. 3537 Stream.EmitRecord(Code, NameVals, AbbrevToUse); 3538 NameVals.clear(); 3539 } 3540 3541 Stream.ExitBlock(); 3542 } 3543 3544 void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) { 3545 assert(Order.Shuffle.size() >= 2 && "Shuffle too small"); 3546 unsigned Code; 3547 if (isa<BasicBlock>(Order.V)) 3548 Code = bitc::USELIST_CODE_BB; 3549 else 3550 Code = bitc::USELIST_CODE_DEFAULT; 3551 3552 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end()); 3553 Record.push_back(VE.getValueID(Order.V)); 3554 Stream.EmitRecord(Code, Record); 3555 } 3556 3557 void ModuleBitcodeWriter::writeUseListBlock(const Function *F) { 3558 assert(VE.shouldPreserveUseListOrder() && 3559 "Expected to be preserving use-list order"); 3560 3561 auto hasMore = [&]() { 3562 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F; 3563 }; 3564 if (!hasMore()) 3565 // Nothing to do. 3566 return; 3567 3568 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3); 3569 while (hasMore()) { 3570 writeUseList(std::move(VE.UseListOrders.back())); 3571 VE.UseListOrders.pop_back(); 3572 } 3573 Stream.ExitBlock(); 3574 } 3575 3576 /// Emit a function body to the module stream. 3577 void ModuleBitcodeWriter::writeFunction( 3578 const Function &F, 3579 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) { 3580 // Save the bitcode index of the start of this function block for recording 3581 // in the VST. 3582 FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo(); 3583 3584 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4); 3585 VE.incorporateFunction(F); 3586 3587 SmallVector<unsigned, 64> Vals; 3588 3589 // Emit the number of basic blocks, so the reader can create them ahead of 3590 // time. 3591 Vals.push_back(VE.getBasicBlocks().size()); 3592 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals); 3593 Vals.clear(); 3594 3595 // If there are function-local constants, emit them now. 3596 unsigned CstStart, CstEnd; 3597 VE.getFunctionConstantRange(CstStart, CstEnd); 3598 writeConstants(CstStart, CstEnd, false); 3599 3600 // If there is function-local metadata, emit it now. 3601 writeFunctionMetadata(F); 3602 3603 // Keep a running idea of what the instruction ID is. 3604 unsigned InstID = CstEnd; 3605 3606 bool NeedsMetadataAttachment = F.hasMetadata(); 3607 3608 DILocation *LastDL = nullptr; 3609 SmallSetVector<Function *, 4> BlockAddressUsers; 3610 3611 // Finally, emit all the instructions, in order. 3612 for (const BasicBlock &BB : F) { 3613 for (const Instruction &I : BB) { 3614 writeInstruction(I, InstID, Vals); 3615 3616 if (!I.getType()->isVoidTy()) 3617 ++InstID; 3618 3619 // If the instruction has metadata, write a metadata attachment later. 3620 NeedsMetadataAttachment |= I.hasMetadataOtherThanDebugLoc(); 3621 3622 // If the instruction has a debug location, emit it. 3623 if (DILocation *DL = I.getDebugLoc()) { 3624 if (DL == LastDL) { 3625 // Just repeat the same debug loc as last time. 3626 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals); 3627 } else { 3628 Vals.push_back(DL->getLine()); 3629 Vals.push_back(DL->getColumn()); 3630 Vals.push_back(VE.getMetadataOrNullID(DL->getScope())); 3631 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt())); 3632 Vals.push_back(DL->isImplicitCode()); 3633 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals); 3634 Vals.clear(); 3635 LastDL = DL; 3636 } 3637 } 3638 3639 // If the instruction has DbgRecords attached to it, emit them. Note that 3640 // they come after the instruction so that it's easy to attach them again 3641 // when reading the bitcode, even though conceptually the debug locations 3642 // start "before" the instruction. 3643 if (I.hasDbgRecords() && WriteNewDbgInfoFormatToBitcode) { 3644 /// Try to push the value only (unwrapped), otherwise push the 3645 /// metadata wrapped value. Returns true if the value was pushed 3646 /// without the ValueAsMetadata wrapper. 3647 auto PushValueOrMetadata = [&Vals, InstID, 3648 this](Metadata *RawLocation) { 3649 assert(RawLocation && 3650 "RawLocation unexpectedly null in DbgVariableRecord"); 3651 if (ValueAsMetadata *VAM = dyn_cast<ValueAsMetadata>(RawLocation)) { 3652 SmallVector<unsigned, 2> ValAndType; 3653 // If the value is a fwd-ref the type is also pushed. We don't 3654 // want the type, so fwd-refs are kept wrapped (pushValueAndType 3655 // returns false if the value is pushed without type). 3656 if (!pushValueAndType(VAM->getValue(), InstID, ValAndType)) { 3657 Vals.push_back(ValAndType[0]); 3658 return true; 3659 } 3660 } 3661 // The metadata is a DIArgList, or ValueAsMetadata wrapping a 3662 // fwd-ref. Push the metadata ID. 3663 Vals.push_back(VE.getMetadataID(RawLocation)); 3664 return false; 3665 }; 3666 3667 // Write out non-instruction debug information attached to this 3668 // instruction. Write it after the instruction so that it's easy to 3669 // re-attach to the instruction reading the records in. 3670 for (DbgRecord &DR : I.DebugMarker->getDbgRecordRange()) { 3671 if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) { 3672 Vals.push_back(VE.getMetadataID(&*DLR->getDebugLoc())); 3673 Vals.push_back(VE.getMetadataID(DLR->getLabel())); 3674 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_RECORD_LABEL, Vals); 3675 Vals.clear(); 3676 continue; 3677 } 3678 3679 // First 3 fields are common to all kinds: 3680 // DILocation, DILocalVariable, DIExpression 3681 // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE) 3682 // ..., LocationMetadata 3683 // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE - abbrev'd) 3684 // ..., Value 3685 // dbg_declare (FUNC_CODE_DEBUG_RECORD_DECLARE) 3686 // ..., LocationMetadata 3687 // dbg_assign (FUNC_CODE_DEBUG_RECORD_ASSIGN) 3688 // ..., LocationMetadata, DIAssignID, DIExpression, LocationMetadata 3689 DbgVariableRecord &DVR = cast<DbgVariableRecord>(DR); 3690 Vals.push_back(VE.getMetadataID(&*DVR.getDebugLoc())); 3691 Vals.push_back(VE.getMetadataID(DVR.getVariable())); 3692 Vals.push_back(VE.getMetadataID(DVR.getExpression())); 3693 if (DVR.isDbgValue()) { 3694 if (PushValueOrMetadata(DVR.getRawLocation())) 3695 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE, Vals, 3696 FUNCTION_DEBUG_RECORD_VALUE_ABBREV); 3697 else 3698 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_RECORD_VALUE, Vals); 3699 } else if (DVR.isDbgDeclare()) { 3700 Vals.push_back(VE.getMetadataID(DVR.getRawLocation())); 3701 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_RECORD_DECLARE, Vals); 3702 } else { 3703 assert(DVR.isDbgAssign() && "Unexpected DbgRecord kind"); 3704 Vals.push_back(VE.getMetadataID(DVR.getRawLocation())); 3705 Vals.push_back(VE.getMetadataID(DVR.getAssignID())); 3706 Vals.push_back(VE.getMetadataID(DVR.getAddressExpression())); 3707 Vals.push_back(VE.getMetadataID(DVR.getRawAddress())); 3708 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_RECORD_ASSIGN, Vals); 3709 } 3710 Vals.clear(); 3711 } 3712 } 3713 } 3714 3715 if (BlockAddress *BA = BlockAddress::lookup(&BB)) { 3716 SmallVector<Value *> Worklist{BA}; 3717 SmallPtrSet<Value *, 8> Visited{BA}; 3718 while (!Worklist.empty()) { 3719 Value *V = Worklist.pop_back_val(); 3720 for (User *U : V->users()) { 3721 if (auto *I = dyn_cast<Instruction>(U)) { 3722 Function *P = I->getFunction(); 3723 if (P != &F) 3724 BlockAddressUsers.insert(P); 3725 } else if (isa<Constant>(U) && !isa<GlobalValue>(U) && 3726 Visited.insert(U).second) 3727 Worklist.push_back(U); 3728 } 3729 } 3730 } 3731 } 3732 3733 if (!BlockAddressUsers.empty()) { 3734 Vals.resize(BlockAddressUsers.size()); 3735 for (auto I : llvm::enumerate(BlockAddressUsers)) 3736 Vals[I.index()] = VE.getValueID(I.value()); 3737 Stream.EmitRecord(bitc::FUNC_CODE_BLOCKADDR_USERS, Vals); 3738 Vals.clear(); 3739 } 3740 3741 // Emit names for all the instructions etc. 3742 if (auto *Symtab = F.getValueSymbolTable()) 3743 writeFunctionLevelValueSymbolTable(*Symtab); 3744 3745 if (NeedsMetadataAttachment) 3746 writeFunctionMetadataAttachment(F); 3747 if (VE.shouldPreserveUseListOrder()) 3748 writeUseListBlock(&F); 3749 VE.purgeFunction(); 3750 Stream.ExitBlock(); 3751 } 3752 3753 // Emit blockinfo, which defines the standard abbreviations etc. 3754 void ModuleBitcodeWriter::writeBlockInfo() { 3755 // We only want to emit block info records for blocks that have multiple 3756 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK. 3757 // Other blocks can define their abbrevs inline. 3758 Stream.EnterBlockInfoBlock(); 3759 3760 { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings. 3761 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3762 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); 3763 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3764 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3765 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 3766 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) != 3767 VST_ENTRY_8_ABBREV) 3768 llvm_unreachable("Unexpected abbrev ordering!"); 3769 } 3770 3771 { // 7-bit fixed width VST_CODE_ENTRY strings. 3772 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3773 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY)); 3774 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3775 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3776 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); 3777 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) != 3778 VST_ENTRY_7_ABBREV) 3779 llvm_unreachable("Unexpected abbrev ordering!"); 3780 } 3781 { // 6-bit char6 VST_CODE_ENTRY strings. 3782 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3783 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY)); 3784 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3785 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3786 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 3787 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) != 3788 VST_ENTRY_6_ABBREV) 3789 llvm_unreachable("Unexpected abbrev ordering!"); 3790 } 3791 { // 6-bit char6 VST_CODE_BBENTRY strings. 3792 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3793 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY)); 3794 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3795 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3796 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 3797 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) != 3798 VST_BBENTRY_6_ABBREV) 3799 llvm_unreachable("Unexpected abbrev ordering!"); 3800 } 3801 3802 { // SETTYPE abbrev for CONSTANTS_BLOCK. 3803 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3804 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE)); 3805 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3806 VE.computeBitsRequiredForTypeIndices())); 3807 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) != 3808 CONSTANTS_SETTYPE_ABBREV) 3809 llvm_unreachable("Unexpected abbrev ordering!"); 3810 } 3811 3812 { // INTEGER abbrev for CONSTANTS_BLOCK. 3813 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3814 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER)); 3815 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3816 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) != 3817 CONSTANTS_INTEGER_ABBREV) 3818 llvm_unreachable("Unexpected abbrev ordering!"); 3819 } 3820 3821 { // CE_CAST abbrev for CONSTANTS_BLOCK. 3822 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3823 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST)); 3824 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc 3825 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid 3826 VE.computeBitsRequiredForTypeIndices())); 3827 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id 3828 3829 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) != 3830 CONSTANTS_CE_CAST_Abbrev) 3831 llvm_unreachable("Unexpected abbrev ordering!"); 3832 } 3833 { // NULL abbrev for CONSTANTS_BLOCK. 3834 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3835 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL)); 3836 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) != 3837 CONSTANTS_NULL_Abbrev) 3838 llvm_unreachable("Unexpected abbrev ordering!"); 3839 } 3840 3841 // FIXME: This should only use space for first class types! 3842 3843 { // INST_LOAD abbrev for FUNCTION_BLOCK. 3844 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3845 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD)); 3846 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr 3847 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty 3848 VE.computeBitsRequiredForTypeIndices())); 3849 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align 3850 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile 3851 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3852 FUNCTION_INST_LOAD_ABBREV) 3853 llvm_unreachable("Unexpected abbrev ordering!"); 3854 } 3855 { // INST_UNOP abbrev for FUNCTION_BLOCK. 3856 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3857 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP)); 3858 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS 3859 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 3860 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3861 FUNCTION_INST_UNOP_ABBREV) 3862 llvm_unreachable("Unexpected abbrev ordering!"); 3863 } 3864 { // INST_UNOP_FLAGS abbrev for FUNCTION_BLOCK. 3865 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3866 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP)); 3867 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS 3868 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 3869 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags 3870 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3871 FUNCTION_INST_UNOP_FLAGS_ABBREV) 3872 llvm_unreachable("Unexpected abbrev ordering!"); 3873 } 3874 { // INST_BINOP abbrev for FUNCTION_BLOCK. 3875 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3876 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP)); 3877 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS 3878 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS 3879 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 3880 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3881 FUNCTION_INST_BINOP_ABBREV) 3882 llvm_unreachable("Unexpected abbrev ordering!"); 3883 } 3884 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK. 3885 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3886 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP)); 3887 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS 3888 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS 3889 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 3890 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags 3891 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3892 FUNCTION_INST_BINOP_FLAGS_ABBREV) 3893 llvm_unreachable("Unexpected abbrev ordering!"); 3894 } 3895 { // INST_CAST abbrev for FUNCTION_BLOCK. 3896 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3897 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST)); 3898 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal 3899 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty 3900 VE.computeBitsRequiredForTypeIndices())); 3901 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 3902 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3903 FUNCTION_INST_CAST_ABBREV) 3904 llvm_unreachable("Unexpected abbrev ordering!"); 3905 } 3906 { // INST_CAST_FLAGS abbrev for FUNCTION_BLOCK. 3907 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3908 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST)); 3909 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal 3910 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty 3911 VE.computeBitsRequiredForTypeIndices())); 3912 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 3913 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags 3914 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3915 FUNCTION_INST_CAST_FLAGS_ABBREV) 3916 llvm_unreachable("Unexpected abbrev ordering!"); 3917 } 3918 3919 { // INST_RET abbrev for FUNCTION_BLOCK. 3920 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3921 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET)); 3922 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3923 FUNCTION_INST_RET_VOID_ABBREV) 3924 llvm_unreachable("Unexpected abbrev ordering!"); 3925 } 3926 { // INST_RET abbrev for FUNCTION_BLOCK. 3927 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3928 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET)); 3929 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID 3930 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3931 FUNCTION_INST_RET_VAL_ABBREV) 3932 llvm_unreachable("Unexpected abbrev ordering!"); 3933 } 3934 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK. 3935 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3936 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE)); 3937 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3938 FUNCTION_INST_UNREACHABLE_ABBREV) 3939 llvm_unreachable("Unexpected abbrev ordering!"); 3940 } 3941 { 3942 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3943 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP)); 3944 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); 3945 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty 3946 Log2_32_Ceil(VE.getTypes().size() + 1))); 3947 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3948 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 3949 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3950 FUNCTION_INST_GEP_ABBREV) 3951 llvm_unreachable("Unexpected abbrev ordering!"); 3952 } 3953 { 3954 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3955 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE)); 3956 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // dbgloc 3957 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // var 3958 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // expr 3959 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // val 3960 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3961 FUNCTION_DEBUG_RECORD_VALUE_ABBREV) 3962 llvm_unreachable("Unexpected abbrev ordering! 1"); 3963 } 3964 Stream.ExitBlock(); 3965 } 3966 3967 /// Write the module path strings, currently only used when generating 3968 /// a combined index file. 3969 void IndexBitcodeWriter::writeModStrings() { 3970 Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3); 3971 3972 // TODO: See which abbrev sizes we actually need to emit 3973 3974 // 8-bit fixed-width MST_ENTRY strings. 3975 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3976 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY)); 3977 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3978 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3979 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 3980 unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv)); 3981 3982 // 7-bit fixed width MST_ENTRY strings. 3983 Abbv = std::make_shared<BitCodeAbbrev>(); 3984 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY)); 3985 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3986 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3987 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); 3988 unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv)); 3989 3990 // 6-bit char6 MST_ENTRY strings. 3991 Abbv = std::make_shared<BitCodeAbbrev>(); 3992 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY)); 3993 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3994 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3995 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 3996 unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv)); 3997 3998 // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY. 3999 Abbv = std::make_shared<BitCodeAbbrev>(); 4000 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH)); 4001 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 4002 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 4003 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 4004 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 4005 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 4006 unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv)); 4007 4008 SmallVector<unsigned, 64> Vals; 4009 forEachModule([&](const StringMapEntry<ModuleHash> &MPSE) { 4010 StringRef Key = MPSE.getKey(); 4011 const auto &Hash = MPSE.getValue(); 4012 StringEncoding Bits = getStringEncoding(Key); 4013 unsigned AbbrevToUse = Abbrev8Bit; 4014 if (Bits == SE_Char6) 4015 AbbrevToUse = Abbrev6Bit; 4016 else if (Bits == SE_Fixed7) 4017 AbbrevToUse = Abbrev7Bit; 4018 4019 auto ModuleId = ModuleIdMap.size(); 4020 ModuleIdMap[Key] = ModuleId; 4021 Vals.push_back(ModuleId); 4022 Vals.append(Key.begin(), Key.end()); 4023 4024 // Emit the finished record. 4025 Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse); 4026 4027 // Emit an optional hash for the module now 4028 if (llvm::any_of(Hash, [](uint32_t H) { return H; })) { 4029 Vals.assign(Hash.begin(), Hash.end()); 4030 // Emit the hash record. 4031 Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash); 4032 } 4033 4034 Vals.clear(); 4035 }); 4036 Stream.ExitBlock(); 4037 } 4038 4039 /// Write the function type metadata related records that need to appear before 4040 /// a function summary entry (whether per-module or combined). 4041 template <typename Fn> 4042 static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream, 4043 FunctionSummary *FS, 4044 Fn GetValueID) { 4045 if (!FS->type_tests().empty()) 4046 Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests()); 4047 4048 SmallVector<uint64_t, 64> Record; 4049 4050 auto WriteVFuncIdVec = [&](uint64_t Ty, 4051 ArrayRef<FunctionSummary::VFuncId> VFs) { 4052 if (VFs.empty()) 4053 return; 4054 Record.clear(); 4055 for (auto &VF : VFs) { 4056 Record.push_back(VF.GUID); 4057 Record.push_back(VF.Offset); 4058 } 4059 Stream.EmitRecord(Ty, Record); 4060 }; 4061 4062 WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS, 4063 FS->type_test_assume_vcalls()); 4064 WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS, 4065 FS->type_checked_load_vcalls()); 4066 4067 auto WriteConstVCallVec = [&](uint64_t Ty, 4068 ArrayRef<FunctionSummary::ConstVCall> VCs) { 4069 for (auto &VC : VCs) { 4070 Record.clear(); 4071 Record.push_back(VC.VFunc.GUID); 4072 Record.push_back(VC.VFunc.Offset); 4073 llvm::append_range(Record, VC.Args); 4074 Stream.EmitRecord(Ty, Record); 4075 } 4076 }; 4077 4078 WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL, 4079 FS->type_test_assume_const_vcalls()); 4080 WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL, 4081 FS->type_checked_load_const_vcalls()); 4082 4083 auto WriteRange = [&](ConstantRange Range) { 4084 Range = Range.sextOrTrunc(FunctionSummary::ParamAccess::RangeWidth); 4085 assert(Range.getLower().getNumWords() == 1); 4086 assert(Range.getUpper().getNumWords() == 1); 4087 emitSignedInt64(Record, *Range.getLower().getRawData()); 4088 emitSignedInt64(Record, *Range.getUpper().getRawData()); 4089 }; 4090 4091 if (!FS->paramAccesses().empty()) { 4092 Record.clear(); 4093 for (auto &Arg : FS->paramAccesses()) { 4094 size_t UndoSize = Record.size(); 4095 Record.push_back(Arg.ParamNo); 4096 WriteRange(Arg.Use); 4097 Record.push_back(Arg.Calls.size()); 4098 for (auto &Call : Arg.Calls) { 4099 Record.push_back(Call.ParamNo); 4100 std::optional<unsigned> ValueID = GetValueID(Call.Callee); 4101 if (!ValueID) { 4102 // If ValueID is unknown we can't drop just this call, we must drop 4103 // entire parameter. 4104 Record.resize(UndoSize); 4105 break; 4106 } 4107 Record.push_back(*ValueID); 4108 WriteRange(Call.Offsets); 4109 } 4110 } 4111 if (!Record.empty()) 4112 Stream.EmitRecord(bitc::FS_PARAM_ACCESS, Record); 4113 } 4114 } 4115 4116 /// Collect type IDs from type tests used by function. 4117 static void 4118 getReferencedTypeIds(FunctionSummary *FS, 4119 std::set<GlobalValue::GUID> &ReferencedTypeIds) { 4120 if (!FS->type_tests().empty()) 4121 for (auto &TT : FS->type_tests()) 4122 ReferencedTypeIds.insert(TT); 4123 4124 auto GetReferencedTypesFromVFuncIdVec = 4125 [&](ArrayRef<FunctionSummary::VFuncId> VFs) { 4126 for (auto &VF : VFs) 4127 ReferencedTypeIds.insert(VF.GUID); 4128 }; 4129 4130 GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls()); 4131 GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls()); 4132 4133 auto GetReferencedTypesFromConstVCallVec = 4134 [&](ArrayRef<FunctionSummary::ConstVCall> VCs) { 4135 for (auto &VC : VCs) 4136 ReferencedTypeIds.insert(VC.VFunc.GUID); 4137 }; 4138 4139 GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls()); 4140 GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls()); 4141 } 4142 4143 static void writeWholeProgramDevirtResolutionByArg( 4144 SmallVector<uint64_t, 64> &NameVals, const std::vector<uint64_t> &args, 4145 const WholeProgramDevirtResolution::ByArg &ByArg) { 4146 NameVals.push_back(args.size()); 4147 llvm::append_range(NameVals, args); 4148 4149 NameVals.push_back(ByArg.TheKind); 4150 NameVals.push_back(ByArg.Info); 4151 NameVals.push_back(ByArg.Byte); 4152 NameVals.push_back(ByArg.Bit); 4153 } 4154 4155 static void writeWholeProgramDevirtResolution( 4156 SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder, 4157 uint64_t Id, const WholeProgramDevirtResolution &Wpd) { 4158 NameVals.push_back(Id); 4159 4160 NameVals.push_back(Wpd.TheKind); 4161 NameVals.push_back(StrtabBuilder.add(Wpd.SingleImplName)); 4162 NameVals.push_back(Wpd.SingleImplName.size()); 4163 4164 NameVals.push_back(Wpd.ResByArg.size()); 4165 for (auto &A : Wpd.ResByArg) 4166 writeWholeProgramDevirtResolutionByArg(NameVals, A.first, A.second); 4167 } 4168 4169 static void writeTypeIdSummaryRecord(SmallVector<uint64_t, 64> &NameVals, 4170 StringTableBuilder &StrtabBuilder, 4171 StringRef Id, 4172 const TypeIdSummary &Summary) { 4173 NameVals.push_back(StrtabBuilder.add(Id)); 4174 NameVals.push_back(Id.size()); 4175 4176 NameVals.push_back(Summary.TTRes.TheKind); 4177 NameVals.push_back(Summary.TTRes.SizeM1BitWidth); 4178 NameVals.push_back(Summary.TTRes.AlignLog2); 4179 NameVals.push_back(Summary.TTRes.SizeM1); 4180 NameVals.push_back(Summary.TTRes.BitMask); 4181 NameVals.push_back(Summary.TTRes.InlineBits); 4182 4183 for (auto &W : Summary.WPDRes) 4184 writeWholeProgramDevirtResolution(NameVals, StrtabBuilder, W.first, 4185 W.second); 4186 } 4187 4188 static void writeTypeIdCompatibleVtableSummaryRecord( 4189 SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder, 4190 StringRef Id, const TypeIdCompatibleVtableInfo &Summary, 4191 ValueEnumerator &VE) { 4192 NameVals.push_back(StrtabBuilder.add(Id)); 4193 NameVals.push_back(Id.size()); 4194 4195 for (auto &P : Summary) { 4196 NameVals.push_back(P.AddressPointOffset); 4197 NameVals.push_back(VE.getValueID(P.VTableVI.getValue())); 4198 } 4199 } 4200 4201 // Adds the allocation contexts to the CallStacks map. We simply use the 4202 // size at the time the context was added as the CallStackId. This works because 4203 // when we look up the call stacks later on we process the function summaries 4204 // and their allocation records in the same exact order. 4205 static void collectMemProfCallStacks( 4206 FunctionSummary *FS, std::function<LinearFrameId(unsigned)> GetStackIndex, 4207 MapVector<CallStackId, llvm::SmallVector<LinearFrameId>> &CallStacks) { 4208 // The interfaces in ProfileData/MemProf.h use a type alias for a stack frame 4209 // id offset into the index of the full stack frames. The ModuleSummaryIndex 4210 // currently uses unsigned. Make sure these stay in sync. 4211 static_assert(std::is_same_v<LinearFrameId, unsigned>); 4212 for (auto &AI : FS->allocs()) { 4213 for (auto &MIB : AI.MIBs) { 4214 SmallVector<unsigned> StackIdIndices; 4215 StackIdIndices.reserve(MIB.StackIdIndices.size()); 4216 for (auto Id : MIB.StackIdIndices) 4217 StackIdIndices.push_back(GetStackIndex(Id)); 4218 // The CallStackId is the size at the time this context was inserted. 4219 CallStacks.insert({CallStacks.size(), StackIdIndices}); 4220 } 4221 } 4222 } 4223 4224 // Build the radix tree from the accumulated CallStacks, write out the resulting 4225 // linearized radix tree array, and return the map of call stack positions into 4226 // this array for use when writing the allocation records. The returned map is 4227 // indexed by a CallStackId which in this case is implicitly determined by the 4228 // order of function summaries and their allocation infos being written. 4229 static DenseMap<CallStackId, LinearCallStackId> writeMemoryProfileRadixTree( 4230 MapVector<CallStackId, llvm::SmallVector<LinearFrameId>> &&CallStacks, 4231 BitstreamWriter &Stream, unsigned RadixAbbrev) { 4232 assert(!CallStacks.empty()); 4233 DenseMap<unsigned, FrameStat> FrameHistogram = 4234 computeFrameHistogram<LinearFrameId>(CallStacks); 4235 CallStackRadixTreeBuilder<LinearFrameId> Builder; 4236 // We don't need a MemProfFrameIndexes map as we have already converted the 4237 // full stack id hash to a linear offset into the StackIds array. 4238 Builder.build(std::move(CallStacks), /*MemProfFrameIndexes=*/std::nullopt, 4239 FrameHistogram); 4240 Stream.EmitRecord(bitc::FS_CONTEXT_RADIX_TREE_ARRAY, Builder.getRadixArray(), 4241 RadixAbbrev); 4242 return Builder.takeCallStackPos(); 4243 } 4244 4245 static void writeFunctionHeapProfileRecords( 4246 BitstreamWriter &Stream, FunctionSummary *FS, unsigned CallsiteAbbrev, 4247 unsigned AllocAbbrev, unsigned ContextIdAbbvId, bool PerModule, 4248 std::function<unsigned(const ValueInfo &VI)> GetValueID, 4249 std::function<unsigned(unsigned)> GetStackIndex, 4250 bool WriteContextSizeInfoIndex, 4251 DenseMap<CallStackId, LinearCallStackId> &CallStackPos, 4252 CallStackId &CallStackCount) { 4253 SmallVector<uint64_t> Record; 4254 4255 for (auto &CI : FS->callsites()) { 4256 Record.clear(); 4257 // Per module callsite clones should always have a single entry of 4258 // value 0. 4259 assert(!PerModule || (CI.Clones.size() == 1 && CI.Clones[0] == 0)); 4260 Record.push_back(GetValueID(CI.Callee)); 4261 if (!PerModule) { 4262 Record.push_back(CI.StackIdIndices.size()); 4263 Record.push_back(CI.Clones.size()); 4264 } 4265 for (auto Id : CI.StackIdIndices) 4266 Record.push_back(GetStackIndex(Id)); 4267 if (!PerModule) { 4268 for (auto V : CI.Clones) 4269 Record.push_back(V); 4270 } 4271 Stream.EmitRecord(PerModule ? bitc::FS_PERMODULE_CALLSITE_INFO 4272 : bitc::FS_COMBINED_CALLSITE_INFO, 4273 Record, CallsiteAbbrev); 4274 } 4275 4276 for (auto &AI : FS->allocs()) { 4277 Record.clear(); 4278 // Per module alloc versions should always have a single entry of 4279 // value 0. 4280 assert(!PerModule || (AI.Versions.size() == 1 && AI.Versions[0] == 0)); 4281 Record.push_back(AI.MIBs.size()); 4282 if (!PerModule) 4283 Record.push_back(AI.Versions.size()); 4284 for (auto &MIB : AI.MIBs) { 4285 Record.push_back((uint8_t)MIB.AllocType); 4286 // Record the index into the radix tree array for this context. 4287 assert(CallStackCount <= CallStackPos.size()); 4288 Record.push_back(CallStackPos[CallStackCount++]); 4289 } 4290 if (!PerModule) { 4291 for (auto V : AI.Versions) 4292 Record.push_back(V); 4293 } 4294 assert(AI.ContextSizeInfos.empty() || 4295 AI.ContextSizeInfos.size() == AI.MIBs.size()); 4296 // Optionally emit the context size information if it exists. 4297 if (WriteContextSizeInfoIndex && !AI.ContextSizeInfos.empty()) { 4298 // The abbreviation id for the context ids record should have been created 4299 // if we are emitting the per-module index, which is where we write this 4300 // info. 4301 assert(ContextIdAbbvId); 4302 SmallVector<uint32_t> ContextIds; 4303 // At least one context id per ContextSizeInfos entry (MIB), broken into 2 4304 // halves. 4305 ContextIds.reserve(AI.ContextSizeInfos.size() * 2); 4306 for (auto &Infos : AI.ContextSizeInfos) { 4307 Record.push_back(Infos.size()); 4308 for (auto [FullStackId, TotalSize] : Infos) { 4309 // The context ids are emitted separately as a fixed width array, 4310 // which is more efficient than a VBR given that these hashes are 4311 // typically close to 64-bits. The max fixed width entry is 32 bits so 4312 // it is split into 2. 4313 ContextIds.push_back(static_cast<uint32_t>(FullStackId >> 32)); 4314 ContextIds.push_back(static_cast<uint32_t>(FullStackId)); 4315 Record.push_back(TotalSize); 4316 } 4317 } 4318 // The context ids are expected by the reader to immediately precede the 4319 // associated alloc info record. 4320 Stream.EmitRecord(bitc::FS_ALLOC_CONTEXT_IDS, ContextIds, 4321 ContextIdAbbvId); 4322 } 4323 Stream.EmitRecord(PerModule ? bitc::FS_PERMODULE_ALLOC_INFO 4324 : bitc::FS_COMBINED_ALLOC_INFO, 4325 Record, AllocAbbrev); 4326 } 4327 } 4328 4329 // Helper to emit a single function summary record. 4330 void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord( 4331 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary, 4332 unsigned ValueID, unsigned FSCallsRelBFAbbrev, 4333 unsigned FSCallsProfileAbbrev, unsigned CallsiteAbbrev, 4334 unsigned AllocAbbrev, unsigned ContextIdAbbvId, const Function &F, 4335 DenseMap<CallStackId, LinearCallStackId> &CallStackPos, 4336 CallStackId &CallStackCount) { 4337 NameVals.push_back(ValueID); 4338 4339 FunctionSummary *FS = cast<FunctionSummary>(Summary); 4340 4341 writeFunctionTypeMetadataRecords( 4342 Stream, FS, [&](const ValueInfo &VI) -> std::optional<unsigned> { 4343 return {VE.getValueID(VI.getValue())}; 4344 }); 4345 4346 writeFunctionHeapProfileRecords( 4347 Stream, FS, CallsiteAbbrev, AllocAbbrev, ContextIdAbbvId, 4348 /*PerModule*/ true, 4349 /*GetValueId*/ [&](const ValueInfo &VI) { return getValueId(VI); }, 4350 /*GetStackIndex*/ [&](unsigned I) { return I; }, 4351 /*WriteContextSizeInfoIndex*/ true, CallStackPos, CallStackCount); 4352 4353 auto SpecialRefCnts = FS->specialRefCounts(); 4354 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags())); 4355 NameVals.push_back(FS->instCount()); 4356 NameVals.push_back(getEncodedFFlags(FS->fflags())); 4357 NameVals.push_back(FS->refs().size()); 4358 NameVals.push_back(SpecialRefCnts.first); // rorefcnt 4359 NameVals.push_back(SpecialRefCnts.second); // worefcnt 4360 4361 for (auto &RI : FS->refs()) 4362 NameVals.push_back(getValueId(RI)); 4363 4364 const bool UseRelBFRecord = 4365 WriteRelBFToSummary && !F.hasProfileData() && 4366 ForceSummaryEdgesCold == FunctionSummary::FSHT_None; 4367 for (auto &ECI : FS->calls()) { 4368 NameVals.push_back(getValueId(ECI.first)); 4369 if (UseRelBFRecord) 4370 NameVals.push_back(getEncodedRelBFCallEdgeInfo(ECI.second)); 4371 else 4372 NameVals.push_back(getEncodedHotnessCallEdgeInfo(ECI.second)); 4373 } 4374 4375 unsigned FSAbbrev = 4376 (UseRelBFRecord ? FSCallsRelBFAbbrev : FSCallsProfileAbbrev); 4377 unsigned Code = 4378 (UseRelBFRecord ? bitc::FS_PERMODULE_RELBF : bitc::FS_PERMODULE_PROFILE); 4379 4380 // Emit the finished record. 4381 Stream.EmitRecord(Code, NameVals, FSAbbrev); 4382 NameVals.clear(); 4383 } 4384 4385 // Collect the global value references in the given variable's initializer, 4386 // and emit them in a summary record. 4387 void ModuleBitcodeWriterBase::writeModuleLevelReferences( 4388 const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals, 4389 unsigned FSModRefsAbbrev, unsigned FSModVTableRefsAbbrev) { 4390 auto VI = Index->getValueInfo(V.getGUID()); 4391 if (!VI || VI.getSummaryList().empty()) { 4392 // Only declarations should not have a summary (a declaration might however 4393 // have a summary if the def was in module level asm). 4394 assert(V.isDeclaration()); 4395 return; 4396 } 4397 auto *Summary = VI.getSummaryList()[0].get(); 4398 NameVals.push_back(VE.getValueID(&V)); 4399 GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary); 4400 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags())); 4401 NameVals.push_back(getEncodedGVarFlags(VS->varflags())); 4402 4403 auto VTableFuncs = VS->vTableFuncs(); 4404 if (!VTableFuncs.empty()) 4405 NameVals.push_back(VS->refs().size()); 4406 4407 unsigned SizeBeforeRefs = NameVals.size(); 4408 for (auto &RI : VS->refs()) 4409 NameVals.push_back(VE.getValueID(RI.getValue())); 4410 // Sort the refs for determinism output, the vector returned by FS->refs() has 4411 // been initialized from a DenseSet. 4412 llvm::sort(drop_begin(NameVals, SizeBeforeRefs)); 4413 4414 if (VTableFuncs.empty()) 4415 Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals, 4416 FSModRefsAbbrev); 4417 else { 4418 // VTableFuncs pairs should already be sorted by offset. 4419 for (auto &P : VTableFuncs) { 4420 NameVals.push_back(VE.getValueID(P.FuncVI.getValue())); 4421 NameVals.push_back(P.VTableOffset); 4422 } 4423 4424 Stream.EmitRecord(bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS, NameVals, 4425 FSModVTableRefsAbbrev); 4426 } 4427 NameVals.clear(); 4428 } 4429 4430 /// Emit the per-module summary section alongside the rest of 4431 /// the module's bitcode. 4432 void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() { 4433 // By default we compile with ThinLTO if the module has a summary, but the 4434 // client can request full LTO with a module flag. 4435 bool IsThinLTO = true; 4436 if (auto *MD = 4437 mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO"))) 4438 IsThinLTO = MD->getZExtValue(); 4439 Stream.EnterSubblock(IsThinLTO ? bitc::GLOBALVAL_SUMMARY_BLOCK_ID 4440 : bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID, 4441 4); 4442 4443 Stream.EmitRecord( 4444 bitc::FS_VERSION, 4445 ArrayRef<uint64_t>{ModuleSummaryIndex::BitcodeSummaryVersion}); 4446 4447 // Write the index flags. 4448 uint64_t Flags = 0; 4449 // Bits 1-3 are set only in the combined index, skip them. 4450 if (Index->enableSplitLTOUnit()) 4451 Flags |= 0x8; 4452 if (Index->hasUnifiedLTO()) 4453 Flags |= 0x200; 4454 4455 Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Flags}); 4456 4457 if (Index->begin() == Index->end()) { 4458 Stream.ExitBlock(); 4459 return; 4460 } 4461 4462 auto Abbv = std::make_shared<BitCodeAbbrev>(); 4463 Abbv->Add(BitCodeAbbrevOp(bitc::FS_VALUE_GUID)); 4464 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 4465 // GUIDS often use up most of 64-bits, so encode as two Fixed 32. 4466 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 4467 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 4468 unsigned ValueGuidAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4469 4470 for (const auto &GVI : valueIds()) { 4471 Stream.EmitRecord(bitc::FS_VALUE_GUID, 4472 ArrayRef<uint32_t>{GVI.second, 4473 static_cast<uint32_t>(GVI.first >> 32), 4474 static_cast<uint32_t>(GVI.first)}, 4475 ValueGuidAbbrev); 4476 } 4477 4478 if (!Index->stackIds().empty()) { 4479 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>(); 4480 StackIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_STACK_IDS)); 4481 // numids x stackid 4482 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 4483 // The stack ids are hashes that are close to 64 bits in size, so emitting 4484 // as a pair of 32-bit fixed-width values is more efficient than a VBR. 4485 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 4486 unsigned StackIdAbbvId = Stream.EmitAbbrev(std::move(StackIdAbbv)); 4487 SmallVector<uint32_t> Vals; 4488 Vals.reserve(Index->stackIds().size() * 2); 4489 for (auto Id : Index->stackIds()) { 4490 Vals.push_back(static_cast<uint32_t>(Id >> 32)); 4491 Vals.push_back(static_cast<uint32_t>(Id)); 4492 } 4493 Stream.EmitRecord(bitc::FS_STACK_IDS, Vals, StackIdAbbvId); 4494 } 4495 4496 // n x context id 4497 auto ContextIdAbbv = std::make_shared<BitCodeAbbrev>(); 4498 ContextIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_ALLOC_CONTEXT_IDS)); 4499 ContextIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 4500 // The context ids are hashes that are close to 64 bits in size, so emitting 4501 // as a pair of 32-bit fixed-width values is more efficient than a VBR. 4502 ContextIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 4503 unsigned ContextIdAbbvId = Stream.EmitAbbrev(std::move(ContextIdAbbv)); 4504 4505 // Abbrev for FS_PERMODULE_PROFILE. 4506 Abbv = std::make_shared<BitCodeAbbrev>(); 4507 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE)); 4508 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 4509 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // flags 4510 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount 4511 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags 4512 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs 4513 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt 4514 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt 4515 // numrefs x valueid, n x (valueid, hotness+tailcall flags) 4516 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 4517 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 4518 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4519 4520 // Abbrev for FS_PERMODULE_RELBF. 4521 Abbv = std::make_shared<BitCodeAbbrev>(); 4522 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_RELBF)); 4523 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 4524 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 4525 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount 4526 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags 4527 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs 4528 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt 4529 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt 4530 // numrefs x valueid, n x (valueid, rel_block_freq+tailcall]) 4531 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 4532 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 4533 unsigned FSCallsRelBFAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4534 4535 // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS. 4536 Abbv = std::make_shared<BitCodeAbbrev>(); 4537 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS)); 4538 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 4539 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 4540 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids 4541 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 4542 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4543 4544 // Abbrev for FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS. 4545 Abbv = std::make_shared<BitCodeAbbrev>(); 4546 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS)); 4547 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 4548 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 4549 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs 4550 // numrefs x valueid, n x (valueid , offset) 4551 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 4552 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 4553 unsigned FSModVTableRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4554 4555 // Abbrev for FS_ALIAS. 4556 Abbv = std::make_shared<BitCodeAbbrev>(); 4557 Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS)); 4558 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 4559 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 4560 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 4561 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4562 4563 // Abbrev for FS_TYPE_ID_METADATA 4564 Abbv = std::make_shared<BitCodeAbbrev>(); 4565 Abbv->Add(BitCodeAbbrevOp(bitc::FS_TYPE_ID_METADATA)); 4566 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid strtab index 4567 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid length 4568 // n x (valueid , offset) 4569 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 4570 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 4571 unsigned TypeIdCompatibleVtableAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4572 4573 Abbv = std::make_shared<BitCodeAbbrev>(); 4574 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_CALLSITE_INFO)); 4575 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 4576 // n x stackidindex 4577 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 4578 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 4579 unsigned CallsiteAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4580 4581 Abbv = std::make_shared<BitCodeAbbrev>(); 4582 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_ALLOC_INFO)); 4583 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // nummib 4584 // n x (alloc type, context radix tree index) 4585 // optional: nummib x (numcontext x total size) 4586 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 4587 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 4588 unsigned AllocAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4589 4590 Abbv = std::make_shared<BitCodeAbbrev>(); 4591 Abbv->Add(BitCodeAbbrevOp(bitc::FS_CONTEXT_RADIX_TREE_ARRAY)); 4592 // n x entry 4593 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 4594 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 4595 unsigned RadixAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4596 4597 // First walk through all the functions and collect the allocation contexts in 4598 // their associated summaries, for use in constructing a radix tree of 4599 // contexts. Note that we need to do this in the same order as the functions 4600 // are processed further below since the call stack positions in the resulting 4601 // radix tree array are identified based on this order. 4602 MapVector<CallStackId, llvm::SmallVector<LinearFrameId>> CallStacks; 4603 for (const Function &F : M) { 4604 // Summary emission does not support anonymous functions, they have to be 4605 // renamed using the anonymous function renaming pass. 4606 if (!F.hasName()) 4607 report_fatal_error("Unexpected anonymous function when writing summary"); 4608 4609 ValueInfo VI = Index->getValueInfo(F.getGUID()); 4610 if (!VI || VI.getSummaryList().empty()) { 4611 // Only declarations should not have a summary (a declaration might 4612 // however have a summary if the def was in module level asm). 4613 assert(F.isDeclaration()); 4614 continue; 4615 } 4616 auto *Summary = VI.getSummaryList()[0].get(); 4617 FunctionSummary *FS = cast<FunctionSummary>(Summary); 4618 collectMemProfCallStacks( 4619 FS, /*GetStackIndex*/ [](unsigned I) { return I; }, CallStacks); 4620 } 4621 // Finalize the radix tree, write it out, and get the map of positions in the 4622 // linearized tree array. 4623 DenseMap<CallStackId, LinearCallStackId> CallStackPos; 4624 if (!CallStacks.empty()) { 4625 CallStackPos = 4626 writeMemoryProfileRadixTree(std::move(CallStacks), Stream, RadixAbbrev); 4627 } 4628 4629 // Keep track of the current index into the CallStackPos map. 4630 CallStackId CallStackCount = 0; 4631 4632 SmallVector<uint64_t, 64> NameVals; 4633 // Iterate over the list of functions instead of the Index to 4634 // ensure the ordering is stable. 4635 for (const Function &F : M) { 4636 // Summary emission does not support anonymous functions, they have to 4637 // renamed using the anonymous function renaming pass. 4638 if (!F.hasName()) 4639 report_fatal_error("Unexpected anonymous function when writing summary"); 4640 4641 ValueInfo VI = Index->getValueInfo(F.getGUID()); 4642 if (!VI || VI.getSummaryList().empty()) { 4643 // Only declarations should not have a summary (a declaration might 4644 // however have a summary if the def was in module level asm). 4645 assert(F.isDeclaration()); 4646 continue; 4647 } 4648 auto *Summary = VI.getSummaryList()[0].get(); 4649 writePerModuleFunctionSummaryRecord( 4650 NameVals, Summary, VE.getValueID(&F), FSCallsRelBFAbbrev, 4651 FSCallsProfileAbbrev, CallsiteAbbrev, AllocAbbrev, ContextIdAbbvId, F, 4652 CallStackPos, CallStackCount); 4653 } 4654 4655 // Capture references from GlobalVariable initializers, which are outside 4656 // of a function scope. 4657 for (const GlobalVariable &G : M.globals()) 4658 writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev, 4659 FSModVTableRefsAbbrev); 4660 4661 for (const GlobalAlias &A : M.aliases()) { 4662 auto *Aliasee = A.getAliaseeObject(); 4663 // Skip ifunc and nameless functions which don't have an entry in the 4664 // summary. 4665 if (!Aliasee->hasName() || isa<GlobalIFunc>(Aliasee)) 4666 continue; 4667 auto AliasId = VE.getValueID(&A); 4668 auto AliaseeId = VE.getValueID(Aliasee); 4669 NameVals.push_back(AliasId); 4670 auto *Summary = Index->getGlobalValueSummary(A); 4671 AliasSummary *AS = cast<AliasSummary>(Summary); 4672 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags())); 4673 NameVals.push_back(AliaseeId); 4674 Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev); 4675 NameVals.clear(); 4676 } 4677 4678 for (auto &S : Index->typeIdCompatibleVtableMap()) { 4679 writeTypeIdCompatibleVtableSummaryRecord(NameVals, StrtabBuilder, S.first, 4680 S.second, VE); 4681 Stream.EmitRecord(bitc::FS_TYPE_ID_METADATA, NameVals, 4682 TypeIdCompatibleVtableAbbrev); 4683 NameVals.clear(); 4684 } 4685 4686 if (Index->getBlockCount()) 4687 Stream.EmitRecord(bitc::FS_BLOCK_COUNT, 4688 ArrayRef<uint64_t>{Index->getBlockCount()}); 4689 4690 Stream.ExitBlock(); 4691 } 4692 4693 /// Emit the combined summary section into the combined index file. 4694 void IndexBitcodeWriter::writeCombinedGlobalValueSummary() { 4695 Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 4); 4696 Stream.EmitRecord( 4697 bitc::FS_VERSION, 4698 ArrayRef<uint64_t>{ModuleSummaryIndex::BitcodeSummaryVersion}); 4699 4700 // Write the index flags. 4701 Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Index.getFlags()}); 4702 4703 auto Abbv = std::make_shared<BitCodeAbbrev>(); 4704 Abbv->Add(BitCodeAbbrevOp(bitc::FS_VALUE_GUID)); 4705 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 4706 // GUIDS often use up most of 64-bits, so encode as two Fixed 32. 4707 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 4708 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 4709 unsigned ValueGuidAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4710 4711 for (const auto &GVI : valueIds()) { 4712 Stream.EmitRecord(bitc::FS_VALUE_GUID, 4713 ArrayRef<uint32_t>{GVI.second, 4714 static_cast<uint32_t>(GVI.first >> 32), 4715 static_cast<uint32_t>(GVI.first)}, 4716 ValueGuidAbbrev); 4717 } 4718 4719 // Write the stack ids used by this index, which will be a subset of those in 4720 // the full index in the case of distributed indexes. 4721 if (!StackIds.empty()) { 4722 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>(); 4723 StackIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_STACK_IDS)); 4724 // numids x stackid 4725 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 4726 // The stack ids are hashes that are close to 64 bits in size, so emitting 4727 // as a pair of 32-bit fixed-width values is more efficient than a VBR. 4728 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 4729 unsigned StackIdAbbvId = Stream.EmitAbbrev(std::move(StackIdAbbv)); 4730 SmallVector<uint32_t> Vals; 4731 Vals.reserve(StackIds.size() * 2); 4732 for (auto Id : StackIds) { 4733 Vals.push_back(static_cast<uint32_t>(Id >> 32)); 4734 Vals.push_back(static_cast<uint32_t>(Id)); 4735 } 4736 Stream.EmitRecord(bitc::FS_STACK_IDS, Vals, StackIdAbbvId); 4737 } 4738 4739 // Abbrev for FS_COMBINED_PROFILE. 4740 Abbv = std::make_shared<BitCodeAbbrev>(); 4741 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE)); 4742 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 4743 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid 4744 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 4745 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount 4746 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags 4747 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // entrycount 4748 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs 4749 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt 4750 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt 4751 // numrefs x valueid, n x (valueid, hotness+tailcall flags) 4752 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 4753 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 4754 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4755 4756 // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS. 4757 Abbv = std::make_shared<BitCodeAbbrev>(); 4758 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS)); 4759 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 4760 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid 4761 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 4762 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids 4763 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 4764 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4765 4766 // Abbrev for FS_COMBINED_ALIAS. 4767 Abbv = std::make_shared<BitCodeAbbrev>(); 4768 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS)); 4769 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 4770 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid 4771 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 4772 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 4773 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4774 4775 Abbv = std::make_shared<BitCodeAbbrev>(); 4776 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_CALLSITE_INFO)); 4777 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 4778 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numstackindices 4779 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numver 4780 // numstackindices x stackidindex, numver x version 4781 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 4782 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 4783 unsigned CallsiteAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4784 4785 Abbv = std::make_shared<BitCodeAbbrev>(); 4786 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALLOC_INFO)); 4787 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // nummib 4788 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numver 4789 // nummib x (alloc type, context radix tree index), 4790 // numver x version 4791 // optional: nummib x total size 4792 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 4793 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 4794 unsigned AllocAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4795 4796 Abbv = std::make_shared<BitCodeAbbrev>(); 4797 Abbv->Add(BitCodeAbbrevOp(bitc::FS_CONTEXT_RADIX_TREE_ARRAY)); 4798 // n x entry 4799 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 4800 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 4801 unsigned RadixAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4802 4803 auto shouldImportValueAsDecl = [&](GlobalValueSummary *GVS) -> bool { 4804 if (DecSummaries == nullptr) 4805 return false; 4806 return DecSummaries->count(GVS); 4807 }; 4808 4809 // The aliases are emitted as a post-pass, and will point to the value 4810 // id of the aliasee. Save them in a vector for post-processing. 4811 SmallVector<AliasSummary *, 64> Aliases; 4812 4813 // Save the value id for each summary for alias emission. 4814 DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap; 4815 4816 SmallVector<uint64_t, 64> NameVals; 4817 4818 // Set that will be populated during call to writeFunctionTypeMetadataRecords 4819 // with the type ids referenced by this index file. 4820 std::set<GlobalValue::GUID> ReferencedTypeIds; 4821 4822 // For local linkage, we also emit the original name separately 4823 // immediately after the record. 4824 auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) { 4825 // We don't need to emit the original name if we are writing the index for 4826 // distributed backends (in which case ModuleToSummariesForIndex is 4827 // non-null). The original name is only needed during the thin link, since 4828 // for SamplePGO the indirect call targets for local functions have 4829 // have the original name annotated in profile. 4830 // Continue to emit it when writing out the entire combined index, which is 4831 // used in testing the thin link via llvm-lto. 4832 if (ModuleToSummariesForIndex || !GlobalValue::isLocalLinkage(S.linkage())) 4833 return; 4834 NameVals.push_back(S.getOriginalName()); 4835 Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals); 4836 NameVals.clear(); 4837 }; 4838 4839 // First walk through all the functions and collect the allocation contexts in 4840 // their associated summaries, for use in constructing a radix tree of 4841 // contexts. Note that we need to do this in the same order as the functions 4842 // are processed further below since the call stack positions in the resulting 4843 // radix tree array are identified based on this order. 4844 MapVector<CallStackId, llvm::SmallVector<LinearFrameId>> CallStacks; 4845 forEachSummary([&](GVInfo I, bool IsAliasee) { 4846 GlobalValueSummary *S = I.second; 4847 assert(S); 4848 auto *FS = dyn_cast<FunctionSummary>(S); 4849 if (!FS) 4850 return; 4851 collectMemProfCallStacks( 4852 FS, 4853 /*GetStackIndex*/ 4854 [&](unsigned I) { 4855 // Get the corresponding index into the list of StackIds actually 4856 // being written for this combined index (which may be a subset in 4857 // the case of distributed indexes). 4858 assert(StackIdIndicesToIndex.contains(I)); 4859 return StackIdIndicesToIndex[I]; 4860 }, 4861 CallStacks); 4862 }); 4863 // Finalize the radix tree, write it out, and get the map of positions in the 4864 // linearized tree array. 4865 DenseMap<CallStackId, LinearCallStackId> CallStackPos; 4866 if (!CallStacks.empty()) { 4867 CallStackPos = 4868 writeMemoryProfileRadixTree(std::move(CallStacks), Stream, RadixAbbrev); 4869 } 4870 4871 // Keep track of the current index into the CallStackPos map. 4872 CallStackId CallStackCount = 0; 4873 4874 DenseSet<GlobalValue::GUID> DefOrUseGUIDs; 4875 forEachSummary([&](GVInfo I, bool IsAliasee) { 4876 GlobalValueSummary *S = I.second; 4877 assert(S); 4878 DefOrUseGUIDs.insert(I.first); 4879 for (const ValueInfo &VI : S->refs()) 4880 DefOrUseGUIDs.insert(VI.getGUID()); 4881 4882 auto ValueId = getValueId(I.first); 4883 assert(ValueId); 4884 SummaryToValueIdMap[S] = *ValueId; 4885 4886 // If this is invoked for an aliasee, we want to record the above 4887 // mapping, but then not emit a summary entry (if the aliasee is 4888 // to be imported, we will invoke this separately with IsAliasee=false). 4889 if (IsAliasee) 4890 return; 4891 4892 if (auto *AS = dyn_cast<AliasSummary>(S)) { 4893 // Will process aliases as a post-pass because the reader wants all 4894 // global to be loaded first. 4895 Aliases.push_back(AS); 4896 return; 4897 } 4898 4899 if (auto *VS = dyn_cast<GlobalVarSummary>(S)) { 4900 NameVals.push_back(*ValueId); 4901 assert(ModuleIdMap.count(VS->modulePath())); 4902 NameVals.push_back(ModuleIdMap[VS->modulePath()]); 4903 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags())); 4904 NameVals.push_back(getEncodedGVarFlags(VS->varflags())); 4905 for (auto &RI : VS->refs()) { 4906 auto RefValueId = getValueId(RI.getGUID()); 4907 if (!RefValueId) 4908 continue; 4909 NameVals.push_back(*RefValueId); 4910 } 4911 4912 // Emit the finished record. 4913 Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals, 4914 FSModRefsAbbrev); 4915 NameVals.clear(); 4916 MaybeEmitOriginalName(*S); 4917 return; 4918 } 4919 4920 auto GetValueId = [&](const ValueInfo &VI) -> std::optional<unsigned> { 4921 if (!VI) 4922 return std::nullopt; 4923 return getValueId(VI.getGUID()); 4924 }; 4925 4926 auto *FS = cast<FunctionSummary>(S); 4927 writeFunctionTypeMetadataRecords(Stream, FS, GetValueId); 4928 getReferencedTypeIds(FS, ReferencedTypeIds); 4929 4930 writeFunctionHeapProfileRecords( 4931 Stream, FS, CallsiteAbbrev, AllocAbbrev, /*ContextIdAbbvId*/ 0, 4932 /*PerModule*/ false, 4933 /*GetValueId*/ 4934 [&](const ValueInfo &VI) -> unsigned { 4935 std::optional<unsigned> ValueID = GetValueId(VI); 4936 // This can happen in shared index files for distributed ThinLTO if 4937 // the callee function summary is not included. Record 0 which we 4938 // will have to deal with conservatively when doing any kind of 4939 // validation in the ThinLTO backends. 4940 if (!ValueID) 4941 return 0; 4942 return *ValueID; 4943 }, 4944 /*GetStackIndex*/ 4945 [&](unsigned I) { 4946 // Get the corresponding index into the list of StackIds actually 4947 // being written for this combined index (which may be a subset in 4948 // the case of distributed indexes). 4949 assert(StackIdIndicesToIndex.contains(I)); 4950 return StackIdIndicesToIndex[I]; 4951 }, 4952 /*WriteContextSizeInfoIndex*/ false, CallStackPos, CallStackCount); 4953 4954 NameVals.push_back(*ValueId); 4955 assert(ModuleIdMap.count(FS->modulePath())); 4956 NameVals.push_back(ModuleIdMap[FS->modulePath()]); 4957 NameVals.push_back( 4958 getEncodedGVSummaryFlags(FS->flags(), shouldImportValueAsDecl(FS))); 4959 NameVals.push_back(FS->instCount()); 4960 NameVals.push_back(getEncodedFFlags(FS->fflags())); 4961 // TODO: Stop writing entry count and bump bitcode version. 4962 NameVals.push_back(0 /* EntryCount */); 4963 4964 // Fill in below 4965 NameVals.push_back(0); // numrefs 4966 NameVals.push_back(0); // rorefcnt 4967 NameVals.push_back(0); // worefcnt 4968 4969 unsigned Count = 0, RORefCnt = 0, WORefCnt = 0; 4970 for (auto &RI : FS->refs()) { 4971 auto RefValueId = getValueId(RI.getGUID()); 4972 if (!RefValueId) 4973 continue; 4974 NameVals.push_back(*RefValueId); 4975 if (RI.isReadOnly()) 4976 RORefCnt++; 4977 else if (RI.isWriteOnly()) 4978 WORefCnt++; 4979 Count++; 4980 } 4981 NameVals[6] = Count; 4982 NameVals[7] = RORefCnt; 4983 NameVals[8] = WORefCnt; 4984 4985 for (auto &EI : FS->calls()) { 4986 // If this GUID doesn't have a value id, it doesn't have a function 4987 // summary and we don't need to record any calls to it. 4988 std::optional<unsigned> CallValueId = GetValueId(EI.first); 4989 if (!CallValueId) 4990 continue; 4991 NameVals.push_back(*CallValueId); 4992 NameVals.push_back(getEncodedHotnessCallEdgeInfo(EI.second)); 4993 } 4994 4995 // Emit the finished record. 4996 Stream.EmitRecord(bitc::FS_COMBINED_PROFILE, NameVals, 4997 FSCallsProfileAbbrev); 4998 NameVals.clear(); 4999 MaybeEmitOriginalName(*S); 5000 }); 5001 5002 for (auto *AS : Aliases) { 5003 auto AliasValueId = SummaryToValueIdMap[AS]; 5004 assert(AliasValueId); 5005 NameVals.push_back(AliasValueId); 5006 assert(ModuleIdMap.count(AS->modulePath())); 5007 NameVals.push_back(ModuleIdMap[AS->modulePath()]); 5008 NameVals.push_back( 5009 getEncodedGVSummaryFlags(AS->flags(), shouldImportValueAsDecl(AS))); 5010 auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()]; 5011 assert(AliaseeValueId); 5012 NameVals.push_back(AliaseeValueId); 5013 5014 // Emit the finished record. 5015 Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev); 5016 NameVals.clear(); 5017 MaybeEmitOriginalName(*AS); 5018 5019 if (auto *FS = dyn_cast<FunctionSummary>(&AS->getAliasee())) 5020 getReferencedTypeIds(FS, ReferencedTypeIds); 5021 } 5022 5023 if (!Index.cfiFunctionDefs().empty()) { 5024 for (auto &S : Index.cfiFunctionDefs()) { 5025 if (DefOrUseGUIDs.contains( 5026 GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(S)))) { 5027 NameVals.push_back(StrtabBuilder.add(S)); 5028 NameVals.push_back(S.size()); 5029 } 5030 } 5031 if (!NameVals.empty()) { 5032 Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DEFS, NameVals); 5033 NameVals.clear(); 5034 } 5035 } 5036 5037 if (!Index.cfiFunctionDecls().empty()) { 5038 for (auto &S : Index.cfiFunctionDecls()) { 5039 if (DefOrUseGUIDs.contains( 5040 GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(S)))) { 5041 NameVals.push_back(StrtabBuilder.add(S)); 5042 NameVals.push_back(S.size()); 5043 } 5044 } 5045 if (!NameVals.empty()) { 5046 Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DECLS, NameVals); 5047 NameVals.clear(); 5048 } 5049 } 5050 5051 // Walk the GUIDs that were referenced, and write the 5052 // corresponding type id records. 5053 for (auto &T : ReferencedTypeIds) { 5054 auto TidIter = Index.typeIds().equal_range(T); 5055 for (const auto &[GUID, TypeIdPair] : make_range(TidIter)) { 5056 writeTypeIdSummaryRecord(NameVals, StrtabBuilder, TypeIdPair.first, 5057 TypeIdPair.second); 5058 Stream.EmitRecord(bitc::FS_TYPE_ID, NameVals); 5059 NameVals.clear(); 5060 } 5061 } 5062 5063 if (Index.getBlockCount()) 5064 Stream.EmitRecord(bitc::FS_BLOCK_COUNT, 5065 ArrayRef<uint64_t>{Index.getBlockCount()}); 5066 5067 Stream.ExitBlock(); 5068 } 5069 5070 /// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the 5071 /// current llvm version, and a record for the epoch number. 5072 static void writeIdentificationBlock(BitstreamWriter &Stream) { 5073 Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5); 5074 5075 // Write the "user readable" string identifying the bitcode producer 5076 auto Abbv = std::make_shared<BitCodeAbbrev>(); 5077 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING)); 5078 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 5079 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 5080 auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 5081 writeStringRecord(Stream, bitc::IDENTIFICATION_CODE_STRING, 5082 "LLVM" LLVM_VERSION_STRING, StringAbbrev); 5083 5084 // Write the epoch version 5085 Abbv = std::make_shared<BitCodeAbbrev>(); 5086 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH)); 5087 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 5088 auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 5089 constexpr std::array<unsigned, 1> Vals = {{bitc::BITCODE_CURRENT_EPOCH}}; 5090 Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev); 5091 Stream.ExitBlock(); 5092 } 5093 5094 void ModuleBitcodeWriter::writeModuleHash(StringRef View) { 5095 // Emit the module's hash. 5096 // MODULE_CODE_HASH: [5*i32] 5097 if (GenerateHash) { 5098 uint32_t Vals[5]; 5099 Hasher.update(ArrayRef<uint8_t>( 5100 reinterpret_cast<const uint8_t *>(View.data()), View.size())); 5101 std::array<uint8_t, 20> Hash = Hasher.result(); 5102 for (int Pos = 0; Pos < 20; Pos += 4) { 5103 Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos); 5104 } 5105 5106 // Emit the finished record. 5107 Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals); 5108 5109 if (ModHash) 5110 // Save the written hash value. 5111 llvm::copy(Vals, std::begin(*ModHash)); 5112 } 5113 } 5114 5115 void ModuleBitcodeWriter::write() { 5116 writeIdentificationBlock(Stream); 5117 5118 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3); 5119 // We will want to write the module hash at this point. Block any flushing so 5120 // we can have access to the whole underlying data later. 5121 Stream.markAndBlockFlushing(); 5122 5123 writeModuleVersion(); 5124 5125 // Emit blockinfo, which defines the standard abbreviations etc. 5126 writeBlockInfo(); 5127 5128 // Emit information describing all of the types in the module. 5129 writeTypeTable(); 5130 5131 // Emit information about attribute groups. 5132 writeAttributeGroupTable(); 5133 5134 // Emit information about parameter attributes. 5135 writeAttributeTable(); 5136 5137 writeComdats(); 5138 5139 // Emit top-level description of module, including target triple, inline asm, 5140 // descriptors for global variables, and function prototype info. 5141 writeModuleInfo(); 5142 5143 // Emit constants. 5144 writeModuleConstants(); 5145 5146 // Emit metadata kind names. 5147 writeModuleMetadataKinds(); 5148 5149 // Emit metadata. 5150 writeModuleMetadata(); 5151 5152 // Emit module-level use-lists. 5153 if (VE.shouldPreserveUseListOrder()) 5154 writeUseListBlock(nullptr); 5155 5156 writeOperandBundleTags(); 5157 writeSyncScopeNames(); 5158 5159 // Emit function bodies. 5160 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex; 5161 for (const Function &F : M) 5162 if (!F.isDeclaration()) 5163 writeFunction(F, FunctionToBitcodeIndex); 5164 5165 // Need to write after the above call to WriteFunction which populates 5166 // the summary information in the index. 5167 if (Index) 5168 writePerModuleGlobalValueSummary(); 5169 5170 writeGlobalValueSymbolTable(FunctionToBitcodeIndex); 5171 5172 writeModuleHash(Stream.getMarkedBufferAndResumeFlushing()); 5173 5174 Stream.ExitBlock(); 5175 } 5176 5177 static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer, 5178 uint32_t &Position) { 5179 support::endian::write32le(&Buffer[Position], Value); 5180 Position += 4; 5181 } 5182 5183 /// If generating a bc file on darwin, we have to emit a 5184 /// header and trailer to make it compatible with the system archiver. To do 5185 /// this we emit the following header, and then emit a trailer that pads the 5186 /// file out to be a multiple of 16 bytes. 5187 /// 5188 /// struct bc_header { 5189 /// uint32_t Magic; // 0x0B17C0DE 5190 /// uint32_t Version; // Version, currently always 0. 5191 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file. 5192 /// uint32_t BitcodeSize; // Size of traditional bitcode file. 5193 /// uint32_t CPUType; // CPU specifier. 5194 /// ... potentially more later ... 5195 /// }; 5196 static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer, 5197 const Triple &TT) { 5198 unsigned CPUType = ~0U; 5199 5200 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*, 5201 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic 5202 // number from /usr/include/mach/machine.h. It is ok to reproduce the 5203 // specific constants here because they are implicitly part of the Darwin ABI. 5204 enum { 5205 DARWIN_CPU_ARCH_ABI64 = 0x01000000, 5206 DARWIN_CPU_TYPE_X86 = 7, 5207 DARWIN_CPU_TYPE_ARM = 12, 5208 DARWIN_CPU_TYPE_POWERPC = 18 5209 }; 5210 5211 Triple::ArchType Arch = TT.getArch(); 5212 if (Arch == Triple::x86_64) 5213 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64; 5214 else if (Arch == Triple::x86) 5215 CPUType = DARWIN_CPU_TYPE_X86; 5216 else if (Arch == Triple::ppc) 5217 CPUType = DARWIN_CPU_TYPE_POWERPC; 5218 else if (Arch == Triple::ppc64) 5219 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64; 5220 else if (Arch == Triple::arm || Arch == Triple::thumb) 5221 CPUType = DARWIN_CPU_TYPE_ARM; 5222 5223 // Traditional Bitcode starts after header. 5224 assert(Buffer.size() >= BWH_HeaderSize && 5225 "Expected header size to be reserved"); 5226 unsigned BCOffset = BWH_HeaderSize; 5227 unsigned BCSize = Buffer.size() - BWH_HeaderSize; 5228 5229 // Write the magic and version. 5230 unsigned Position = 0; 5231 writeInt32ToBuffer(0x0B17C0DE, Buffer, Position); 5232 writeInt32ToBuffer(0, Buffer, Position); // Version. 5233 writeInt32ToBuffer(BCOffset, Buffer, Position); 5234 writeInt32ToBuffer(BCSize, Buffer, Position); 5235 writeInt32ToBuffer(CPUType, Buffer, Position); 5236 5237 // If the file is not a multiple of 16 bytes, insert dummy padding. 5238 while (Buffer.size() & 15) 5239 Buffer.push_back(0); 5240 } 5241 5242 /// Helper to write the header common to all bitcode files. 5243 static void writeBitcodeHeader(BitstreamWriter &Stream) { 5244 // Emit the file header. 5245 Stream.Emit((unsigned)'B', 8); 5246 Stream.Emit((unsigned)'C', 8); 5247 Stream.Emit(0x0, 4); 5248 Stream.Emit(0xC, 4); 5249 Stream.Emit(0xE, 4); 5250 Stream.Emit(0xD, 4); 5251 } 5252 5253 BitcodeWriter::BitcodeWriter(SmallVectorImpl<char> &Buffer) 5254 : Stream(new BitstreamWriter(Buffer)) { 5255 writeBitcodeHeader(*Stream); 5256 } 5257 5258 BitcodeWriter::BitcodeWriter(raw_ostream &FS) 5259 : Stream(new BitstreamWriter(FS, FlushThreshold)) { 5260 writeBitcodeHeader(*Stream); 5261 } 5262 5263 BitcodeWriter::~BitcodeWriter() { assert(WroteStrtab); } 5264 5265 void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) { 5266 Stream->EnterSubblock(Block, 3); 5267 5268 auto Abbv = std::make_shared<BitCodeAbbrev>(); 5269 Abbv->Add(BitCodeAbbrevOp(Record)); 5270 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 5271 auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv)); 5272 5273 Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob); 5274 5275 Stream->ExitBlock(); 5276 } 5277 5278 void BitcodeWriter::writeSymtab() { 5279 assert(!WroteStrtab && !WroteSymtab); 5280 5281 // If any module has module-level inline asm, we will require a registered asm 5282 // parser for the target so that we can create an accurate symbol table for 5283 // the module. 5284 for (Module *M : Mods) { 5285 if (M->getModuleInlineAsm().empty()) 5286 continue; 5287 5288 std::string Err; 5289 const Triple TT(M->getTargetTriple()); 5290 const Target *T = TargetRegistry::lookupTarget(TT.str(), Err); 5291 if (!T || !T->hasMCAsmParser()) 5292 return; 5293 } 5294 5295 WroteSymtab = true; 5296 SmallVector<char, 0> Symtab; 5297 // The irsymtab::build function may be unable to create a symbol table if the 5298 // module is malformed (e.g. it contains an invalid alias). Writing a symbol 5299 // table is not required for correctness, but we still want to be able to 5300 // write malformed modules to bitcode files, so swallow the error. 5301 if (Error E = irsymtab::build(Mods, Symtab, StrtabBuilder, Alloc)) { 5302 consumeError(std::move(E)); 5303 return; 5304 } 5305 5306 writeBlob(bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB, 5307 {Symtab.data(), Symtab.size()}); 5308 } 5309 5310 void BitcodeWriter::writeStrtab() { 5311 assert(!WroteStrtab); 5312 5313 std::vector<char> Strtab; 5314 StrtabBuilder.finalizeInOrder(); 5315 Strtab.resize(StrtabBuilder.getSize()); 5316 StrtabBuilder.write((uint8_t *)Strtab.data()); 5317 5318 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, 5319 {Strtab.data(), Strtab.size()}); 5320 5321 WroteStrtab = true; 5322 } 5323 5324 void BitcodeWriter::copyStrtab(StringRef Strtab) { 5325 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab); 5326 WroteStrtab = true; 5327 } 5328 5329 void BitcodeWriter::writeModule(const Module &M, 5330 bool ShouldPreserveUseListOrder, 5331 const ModuleSummaryIndex *Index, 5332 bool GenerateHash, ModuleHash *ModHash) { 5333 assert(!WroteStrtab); 5334 5335 // The Mods vector is used by irsymtab::build, which requires non-const 5336 // Modules in case it needs to materialize metadata. But the bitcode writer 5337 // requires that the module is materialized, so we can cast to non-const here, 5338 // after checking that it is in fact materialized. 5339 assert(M.isMaterialized()); 5340 Mods.push_back(const_cast<Module *>(&M)); 5341 5342 ModuleBitcodeWriter ModuleWriter(M, StrtabBuilder, *Stream, 5343 ShouldPreserveUseListOrder, Index, 5344 GenerateHash, ModHash); 5345 ModuleWriter.write(); 5346 } 5347 5348 void BitcodeWriter::writeIndex( 5349 const ModuleSummaryIndex *Index, 5350 const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex, 5351 const GVSummaryPtrSet *DecSummaries) { 5352 IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index, DecSummaries, 5353 ModuleToSummariesForIndex); 5354 IndexWriter.write(); 5355 } 5356 5357 /// Write the specified module to the specified output stream. 5358 void llvm::WriteBitcodeToFile(const Module &M, raw_ostream &Out, 5359 bool ShouldPreserveUseListOrder, 5360 const ModuleSummaryIndex *Index, 5361 bool GenerateHash, ModuleHash *ModHash) { 5362 auto Write = [&](BitcodeWriter &Writer) { 5363 Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash, 5364 ModHash); 5365 Writer.writeSymtab(); 5366 Writer.writeStrtab(); 5367 }; 5368 Triple TT(M.getTargetTriple()); 5369 if (TT.isOSDarwin() || TT.isOSBinFormatMachO()) { 5370 // If this is darwin or another generic macho target, reserve space for the 5371 // header. Note that the header is computed *after* the output is known, so 5372 // we currently explicitly use a buffer, write to it, and then subsequently 5373 // flush to Out. 5374 SmallVector<char, 0> Buffer; 5375 Buffer.reserve(256 * 1024); 5376 Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0); 5377 BitcodeWriter Writer(Buffer); 5378 Write(Writer); 5379 emitDarwinBCHeaderAndTrailer(Buffer, TT); 5380 Out.write(Buffer.data(), Buffer.size()); 5381 } else { 5382 BitcodeWriter Writer(Out); 5383 Write(Writer); 5384 } 5385 } 5386 5387 void IndexBitcodeWriter::write() { 5388 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3); 5389 5390 writeModuleVersion(); 5391 5392 // Write the module paths in the combined index. 5393 writeModStrings(); 5394 5395 // Write the summary combined index records. 5396 writeCombinedGlobalValueSummary(); 5397 5398 Stream.ExitBlock(); 5399 } 5400 5401 // Write the specified module summary index to the given raw output stream, 5402 // where it will be written in a new bitcode block. This is used when 5403 // writing the combined index file for ThinLTO. When writing a subset of the 5404 // index for a distributed backend, provide a \p ModuleToSummariesForIndex map. 5405 void llvm::writeIndexToFile( 5406 const ModuleSummaryIndex &Index, raw_ostream &Out, 5407 const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex, 5408 const GVSummaryPtrSet *DecSummaries) { 5409 SmallVector<char, 0> Buffer; 5410 Buffer.reserve(256 * 1024); 5411 5412 BitcodeWriter Writer(Buffer); 5413 Writer.writeIndex(&Index, ModuleToSummariesForIndex, DecSummaries); 5414 Writer.writeStrtab(); 5415 5416 Out.write((char *)&Buffer.front(), Buffer.size()); 5417 } 5418 5419 namespace { 5420 5421 /// Class to manage the bitcode writing for a thin link bitcode file. 5422 class ThinLinkBitcodeWriter : public ModuleBitcodeWriterBase { 5423 /// ModHash is for use in ThinLTO incremental build, generated while writing 5424 /// the module bitcode file. 5425 const ModuleHash *ModHash; 5426 5427 public: 5428 ThinLinkBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder, 5429 BitstreamWriter &Stream, 5430 const ModuleSummaryIndex &Index, 5431 const ModuleHash &ModHash) 5432 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream, 5433 /*ShouldPreserveUseListOrder=*/false, &Index), 5434 ModHash(&ModHash) {} 5435 5436 void write(); 5437 5438 private: 5439 void writeSimplifiedModuleInfo(); 5440 }; 5441 5442 } // end anonymous namespace 5443 5444 // This function writes a simpilified module info for thin link bitcode file. 5445 // It only contains the source file name along with the name(the offset and 5446 // size in strtab) and linkage for global values. For the global value info 5447 // entry, in order to keep linkage at offset 5, there are three zeros used 5448 // as padding. 5449 void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() { 5450 SmallVector<unsigned, 64> Vals; 5451 // Emit the module's source file name. 5452 { 5453 StringEncoding Bits = getStringEncoding(M.getSourceFileName()); 5454 BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8); 5455 if (Bits == SE_Char6) 5456 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6); 5457 else if (Bits == SE_Fixed7) 5458 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7); 5459 5460 // MODULE_CODE_SOURCE_FILENAME: [namechar x N] 5461 auto Abbv = std::make_shared<BitCodeAbbrev>(); 5462 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME)); 5463 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 5464 Abbv->Add(AbbrevOpToUse); 5465 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 5466 5467 for (const auto P : M.getSourceFileName()) 5468 Vals.push_back((unsigned char)P); 5469 5470 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev); 5471 Vals.clear(); 5472 } 5473 5474 // Emit the global variable information. 5475 for (const GlobalVariable &GV : M.globals()) { 5476 // GLOBALVAR: [strtab offset, strtab size, 0, 0, 0, linkage] 5477 Vals.push_back(StrtabBuilder.add(GV.getName())); 5478 Vals.push_back(GV.getName().size()); 5479 Vals.push_back(0); 5480 Vals.push_back(0); 5481 Vals.push_back(0); 5482 Vals.push_back(getEncodedLinkage(GV)); 5483 5484 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals); 5485 Vals.clear(); 5486 } 5487 5488 // Emit the function proto information. 5489 for (const Function &F : M) { 5490 // FUNCTION: [strtab offset, strtab size, 0, 0, 0, linkage] 5491 Vals.push_back(StrtabBuilder.add(F.getName())); 5492 Vals.push_back(F.getName().size()); 5493 Vals.push_back(0); 5494 Vals.push_back(0); 5495 Vals.push_back(0); 5496 Vals.push_back(getEncodedLinkage(F)); 5497 5498 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals); 5499 Vals.clear(); 5500 } 5501 5502 // Emit the alias information. 5503 for (const GlobalAlias &A : M.aliases()) { 5504 // ALIAS: [strtab offset, strtab size, 0, 0, 0, linkage] 5505 Vals.push_back(StrtabBuilder.add(A.getName())); 5506 Vals.push_back(A.getName().size()); 5507 Vals.push_back(0); 5508 Vals.push_back(0); 5509 Vals.push_back(0); 5510 Vals.push_back(getEncodedLinkage(A)); 5511 5512 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals); 5513 Vals.clear(); 5514 } 5515 5516 // Emit the ifunc information. 5517 for (const GlobalIFunc &I : M.ifuncs()) { 5518 // IFUNC: [strtab offset, strtab size, 0, 0, 0, linkage] 5519 Vals.push_back(StrtabBuilder.add(I.getName())); 5520 Vals.push_back(I.getName().size()); 5521 Vals.push_back(0); 5522 Vals.push_back(0); 5523 Vals.push_back(0); 5524 Vals.push_back(getEncodedLinkage(I)); 5525 5526 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals); 5527 Vals.clear(); 5528 } 5529 } 5530 5531 void ThinLinkBitcodeWriter::write() { 5532 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3); 5533 5534 writeModuleVersion(); 5535 5536 writeSimplifiedModuleInfo(); 5537 5538 writePerModuleGlobalValueSummary(); 5539 5540 // Write module hash. 5541 Stream.EmitRecord(bitc::MODULE_CODE_HASH, ArrayRef<uint32_t>(*ModHash)); 5542 5543 Stream.ExitBlock(); 5544 } 5545 5546 void BitcodeWriter::writeThinLinkBitcode(const Module &M, 5547 const ModuleSummaryIndex &Index, 5548 const ModuleHash &ModHash) { 5549 assert(!WroteStrtab); 5550 5551 // The Mods vector is used by irsymtab::build, which requires non-const 5552 // Modules in case it needs to materialize metadata. But the bitcode writer 5553 // requires that the module is materialized, so we can cast to non-const here, 5554 // after checking that it is in fact materialized. 5555 assert(M.isMaterialized()); 5556 Mods.push_back(const_cast<Module *>(&M)); 5557 5558 ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index, 5559 ModHash); 5560 ThinLinkWriter.write(); 5561 } 5562 5563 // Write the specified thin link bitcode file to the given raw output stream, 5564 // where it will be written in a new bitcode block. This is used when 5565 // writing the per-module index file for ThinLTO. 5566 void llvm::writeThinLinkBitcodeToFile(const Module &M, raw_ostream &Out, 5567 const ModuleSummaryIndex &Index, 5568 const ModuleHash &ModHash) { 5569 SmallVector<char, 0> Buffer; 5570 Buffer.reserve(256 * 1024); 5571 5572 BitcodeWriter Writer(Buffer); 5573 Writer.writeThinLinkBitcode(M, Index, ModHash); 5574 Writer.writeSymtab(); 5575 Writer.writeStrtab(); 5576 5577 Out.write((char *)&Buffer.front(), Buffer.size()); 5578 } 5579 5580 static const char *getSectionNameForBitcode(const Triple &T) { 5581 switch (T.getObjectFormat()) { 5582 case Triple::MachO: 5583 return "__LLVM,__bitcode"; 5584 case Triple::COFF: 5585 case Triple::ELF: 5586 case Triple::Wasm: 5587 case Triple::UnknownObjectFormat: 5588 return ".llvmbc"; 5589 case Triple::GOFF: 5590 llvm_unreachable("GOFF is not yet implemented"); 5591 break; 5592 case Triple::SPIRV: 5593 if (T.getVendor() == Triple::AMD) 5594 return ".llvmbc"; 5595 llvm_unreachable("SPIRV is not yet implemented"); 5596 break; 5597 case Triple::XCOFF: 5598 llvm_unreachable("XCOFF is not yet implemented"); 5599 break; 5600 case Triple::DXContainer: 5601 llvm_unreachable("DXContainer is not yet implemented"); 5602 break; 5603 } 5604 llvm_unreachable("Unimplemented ObjectFormatType"); 5605 } 5606 5607 static const char *getSectionNameForCommandline(const Triple &T) { 5608 switch (T.getObjectFormat()) { 5609 case Triple::MachO: 5610 return "__LLVM,__cmdline"; 5611 case Triple::COFF: 5612 case Triple::ELF: 5613 case Triple::Wasm: 5614 case Triple::UnknownObjectFormat: 5615 return ".llvmcmd"; 5616 case Triple::GOFF: 5617 llvm_unreachable("GOFF is not yet implemented"); 5618 break; 5619 case Triple::SPIRV: 5620 if (T.getVendor() == Triple::AMD) 5621 return ".llvmcmd"; 5622 llvm_unreachable("SPIRV is not yet implemented"); 5623 break; 5624 case Triple::XCOFF: 5625 llvm_unreachable("XCOFF is not yet implemented"); 5626 break; 5627 case Triple::DXContainer: 5628 llvm_unreachable("DXC is not yet implemented"); 5629 break; 5630 } 5631 llvm_unreachable("Unimplemented ObjectFormatType"); 5632 } 5633 5634 void llvm::embedBitcodeInModule(llvm::Module &M, llvm::MemoryBufferRef Buf, 5635 bool EmbedBitcode, bool EmbedCmdline, 5636 const std::vector<uint8_t> &CmdArgs) { 5637 // Save llvm.compiler.used and remove it. 5638 SmallVector<Constant *, 2> UsedArray; 5639 SmallVector<GlobalValue *, 4> UsedGlobals; 5640 GlobalVariable *Used = collectUsedGlobalVariables(M, UsedGlobals, true); 5641 Type *UsedElementType = Used ? Used->getValueType()->getArrayElementType() 5642 : PointerType::getUnqual(M.getContext()); 5643 for (auto *GV : UsedGlobals) { 5644 if (GV->getName() != "llvm.embedded.module" && 5645 GV->getName() != "llvm.cmdline") 5646 UsedArray.push_back( 5647 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType)); 5648 } 5649 if (Used) 5650 Used->eraseFromParent(); 5651 5652 // Embed the bitcode for the llvm module. 5653 std::string Data; 5654 ArrayRef<uint8_t> ModuleData; 5655 Triple T(M.getTargetTriple()); 5656 5657 if (EmbedBitcode) { 5658 if (Buf.getBufferSize() == 0 || 5659 !isBitcode((const unsigned char *)Buf.getBufferStart(), 5660 (const unsigned char *)Buf.getBufferEnd())) { 5661 // If the input is LLVM Assembly, bitcode is produced by serializing 5662 // the module. Use-lists order need to be preserved in this case. 5663 llvm::raw_string_ostream OS(Data); 5664 llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true); 5665 ModuleData = 5666 ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size()); 5667 } else 5668 // If the input is LLVM bitcode, write the input byte stream directly. 5669 ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(), 5670 Buf.getBufferSize()); 5671 } 5672 llvm::Constant *ModuleConstant = 5673 llvm::ConstantDataArray::get(M.getContext(), ModuleData); 5674 llvm::GlobalVariable *GV = new llvm::GlobalVariable( 5675 M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage, 5676 ModuleConstant); 5677 GV->setSection(getSectionNameForBitcode(T)); 5678 // Set alignment to 1 to prevent padding between two contributions from input 5679 // sections after linking. 5680 GV->setAlignment(Align(1)); 5681 UsedArray.push_back( 5682 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType)); 5683 if (llvm::GlobalVariable *Old = 5684 M.getGlobalVariable("llvm.embedded.module", true)) { 5685 assert(Old->hasZeroLiveUses() && 5686 "llvm.embedded.module can only be used once in llvm.compiler.used"); 5687 GV->takeName(Old); 5688 Old->eraseFromParent(); 5689 } else { 5690 GV->setName("llvm.embedded.module"); 5691 } 5692 5693 // Skip if only bitcode needs to be embedded. 5694 if (EmbedCmdline) { 5695 // Embed command-line options. 5696 ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CmdArgs.data()), 5697 CmdArgs.size()); 5698 llvm::Constant *CmdConstant = 5699 llvm::ConstantDataArray::get(M.getContext(), CmdData); 5700 GV = new llvm::GlobalVariable(M, CmdConstant->getType(), true, 5701 llvm::GlobalValue::PrivateLinkage, 5702 CmdConstant); 5703 GV->setSection(getSectionNameForCommandline(T)); 5704 GV->setAlignment(Align(1)); 5705 UsedArray.push_back( 5706 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType)); 5707 if (llvm::GlobalVariable *Old = M.getGlobalVariable("llvm.cmdline", true)) { 5708 assert(Old->hasZeroLiveUses() && 5709 "llvm.cmdline can only be used once in llvm.compiler.used"); 5710 GV->takeName(Old); 5711 Old->eraseFromParent(); 5712 } else { 5713 GV->setName("llvm.cmdline"); 5714 } 5715 } 5716 5717 if (UsedArray.empty()) 5718 return; 5719 5720 // Recreate llvm.compiler.used. 5721 ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size()); 5722 auto *NewUsed = new GlobalVariable( 5723 M, ATy, false, llvm::GlobalValue::AppendingLinkage, 5724 llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used"); 5725 NewUsed->setSection("llvm.metadata"); 5726 } 5727