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