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