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