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