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( 2462 unsigned(IA->hasSideEffects()) | unsigned(IA->isAlignStack()) << 1 | 2463 unsigned(IA->getDialect() & 1) << 2 | unsigned(IA->canThrow()) << 3); 2464 2465 // Add the asm string. 2466 const std::string &AsmStr = IA->getAsmString(); 2467 Record.push_back(AsmStr.size()); 2468 Record.append(AsmStr.begin(), AsmStr.end()); 2469 2470 // Add the constraint string. 2471 const std::string &ConstraintStr = IA->getConstraintString(); 2472 Record.push_back(ConstraintStr.size()); 2473 Record.append(ConstraintStr.begin(), ConstraintStr.end()); 2474 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record); 2475 Record.clear(); 2476 continue; 2477 } 2478 const Constant *C = cast<Constant>(V); 2479 unsigned Code = -1U; 2480 unsigned AbbrevToUse = 0; 2481 if (C->isNullValue()) { 2482 Code = bitc::CST_CODE_NULL; 2483 } else if (isa<PoisonValue>(C)) { 2484 Code = bitc::CST_CODE_POISON; 2485 } else if (isa<UndefValue>(C)) { 2486 Code = bitc::CST_CODE_UNDEF; 2487 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) { 2488 if (IV->getBitWidth() <= 64) { 2489 uint64_t V = IV->getSExtValue(); 2490 emitSignedInt64(Record, V); 2491 Code = bitc::CST_CODE_INTEGER; 2492 AbbrevToUse = CONSTANTS_INTEGER_ABBREV; 2493 } else { // Wide integers, > 64 bits in size. 2494 emitWideAPInt(Record, IV->getValue()); 2495 Code = bitc::CST_CODE_WIDE_INTEGER; 2496 } 2497 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) { 2498 Code = bitc::CST_CODE_FLOAT; 2499 Type *Ty = CFP->getType(); 2500 if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() || 2501 Ty->isDoubleTy()) { 2502 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue()); 2503 } else if (Ty->isX86_FP80Ty()) { 2504 // api needed to prevent premature destruction 2505 // bits are not in the same order as a normal i80 APInt, compensate. 2506 APInt api = CFP->getValueAPF().bitcastToAPInt(); 2507 const uint64_t *p = api.getRawData(); 2508 Record.push_back((p[1] << 48) | (p[0] >> 16)); 2509 Record.push_back(p[0] & 0xffffLL); 2510 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) { 2511 APInt api = CFP->getValueAPF().bitcastToAPInt(); 2512 const uint64_t *p = api.getRawData(); 2513 Record.push_back(p[0]); 2514 Record.push_back(p[1]); 2515 } else { 2516 assert(0 && "Unknown FP type!"); 2517 } 2518 } else if (isa<ConstantDataSequential>(C) && 2519 cast<ConstantDataSequential>(C)->isString()) { 2520 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C); 2521 // Emit constant strings specially. 2522 unsigned NumElts = Str->getNumElements(); 2523 // If this is a null-terminated string, use the denser CSTRING encoding. 2524 if (Str->isCString()) { 2525 Code = bitc::CST_CODE_CSTRING; 2526 --NumElts; // Don't encode the null, which isn't allowed by char6. 2527 } else { 2528 Code = bitc::CST_CODE_STRING; 2529 AbbrevToUse = String8Abbrev; 2530 } 2531 bool isCStr7 = Code == bitc::CST_CODE_CSTRING; 2532 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING; 2533 for (unsigned i = 0; i != NumElts; ++i) { 2534 unsigned char V = Str->getElementAsInteger(i); 2535 Record.push_back(V); 2536 isCStr7 &= (V & 128) == 0; 2537 if (isCStrChar6) 2538 isCStrChar6 = BitCodeAbbrevOp::isChar6(V); 2539 } 2540 2541 if (isCStrChar6) 2542 AbbrevToUse = CString6Abbrev; 2543 else if (isCStr7) 2544 AbbrevToUse = CString7Abbrev; 2545 } else if (const ConstantDataSequential *CDS = 2546 dyn_cast<ConstantDataSequential>(C)) { 2547 Code = bitc::CST_CODE_DATA; 2548 Type *EltTy = CDS->getElementType(); 2549 if (isa<IntegerType>(EltTy)) { 2550 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) 2551 Record.push_back(CDS->getElementAsInteger(i)); 2552 } else { 2553 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) 2554 Record.push_back( 2555 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue()); 2556 } 2557 } else if (isa<ConstantAggregate>(C)) { 2558 Code = bitc::CST_CODE_AGGREGATE; 2559 for (const Value *Op : C->operands()) 2560 Record.push_back(VE.getValueID(Op)); 2561 AbbrevToUse = AggregateAbbrev; 2562 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 2563 switch (CE->getOpcode()) { 2564 default: 2565 if (Instruction::isCast(CE->getOpcode())) { 2566 Code = bitc::CST_CODE_CE_CAST; 2567 Record.push_back(getEncodedCastOpcode(CE->getOpcode())); 2568 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 2569 Record.push_back(VE.getValueID(C->getOperand(0))); 2570 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev; 2571 } else { 2572 assert(CE->getNumOperands() == 2 && "Unknown constant expr!"); 2573 Code = bitc::CST_CODE_CE_BINOP; 2574 Record.push_back(getEncodedBinaryOpcode(CE->getOpcode())); 2575 Record.push_back(VE.getValueID(C->getOperand(0))); 2576 Record.push_back(VE.getValueID(C->getOperand(1))); 2577 uint64_t Flags = getOptimizationFlags(CE); 2578 if (Flags != 0) 2579 Record.push_back(Flags); 2580 } 2581 break; 2582 case Instruction::FNeg: { 2583 assert(CE->getNumOperands() == 1 && "Unknown constant expr!"); 2584 Code = bitc::CST_CODE_CE_UNOP; 2585 Record.push_back(getEncodedUnaryOpcode(CE->getOpcode())); 2586 Record.push_back(VE.getValueID(C->getOperand(0))); 2587 uint64_t Flags = getOptimizationFlags(CE); 2588 if (Flags != 0) 2589 Record.push_back(Flags); 2590 break; 2591 } 2592 case Instruction::GetElementPtr: { 2593 Code = bitc::CST_CODE_CE_GEP; 2594 const auto *GO = cast<GEPOperator>(C); 2595 Record.push_back(VE.getTypeID(GO->getSourceElementType())); 2596 if (Optional<unsigned> Idx = GO->getInRangeIndex()) { 2597 Code = bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX; 2598 Record.push_back((*Idx << 1) | GO->isInBounds()); 2599 } else if (GO->isInBounds()) 2600 Code = bitc::CST_CODE_CE_INBOUNDS_GEP; 2601 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) { 2602 Record.push_back(VE.getTypeID(C->getOperand(i)->getType())); 2603 Record.push_back(VE.getValueID(C->getOperand(i))); 2604 } 2605 break; 2606 } 2607 case Instruction::Select: 2608 Code = bitc::CST_CODE_CE_SELECT; 2609 Record.push_back(VE.getValueID(C->getOperand(0))); 2610 Record.push_back(VE.getValueID(C->getOperand(1))); 2611 Record.push_back(VE.getValueID(C->getOperand(2))); 2612 break; 2613 case Instruction::ExtractElement: 2614 Code = bitc::CST_CODE_CE_EXTRACTELT; 2615 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 2616 Record.push_back(VE.getValueID(C->getOperand(0))); 2617 Record.push_back(VE.getTypeID(C->getOperand(1)->getType())); 2618 Record.push_back(VE.getValueID(C->getOperand(1))); 2619 break; 2620 case Instruction::InsertElement: 2621 Code = bitc::CST_CODE_CE_INSERTELT; 2622 Record.push_back(VE.getValueID(C->getOperand(0))); 2623 Record.push_back(VE.getValueID(C->getOperand(1))); 2624 Record.push_back(VE.getTypeID(C->getOperand(2)->getType())); 2625 Record.push_back(VE.getValueID(C->getOperand(2))); 2626 break; 2627 case Instruction::ShuffleVector: 2628 // If the return type and argument types are the same, this is a 2629 // standard shufflevector instruction. If the types are different, 2630 // then the shuffle is widening or truncating the input vectors, and 2631 // the argument type must also be encoded. 2632 if (C->getType() == C->getOperand(0)->getType()) { 2633 Code = bitc::CST_CODE_CE_SHUFFLEVEC; 2634 } else { 2635 Code = bitc::CST_CODE_CE_SHUFVEC_EX; 2636 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 2637 } 2638 Record.push_back(VE.getValueID(C->getOperand(0))); 2639 Record.push_back(VE.getValueID(C->getOperand(1))); 2640 Record.push_back(VE.getValueID(CE->getShuffleMaskForBitcode())); 2641 break; 2642 case Instruction::ICmp: 2643 case Instruction::FCmp: 2644 Code = bitc::CST_CODE_CE_CMP; 2645 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 2646 Record.push_back(VE.getValueID(C->getOperand(0))); 2647 Record.push_back(VE.getValueID(C->getOperand(1))); 2648 Record.push_back(CE->getPredicate()); 2649 break; 2650 } 2651 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) { 2652 Code = bitc::CST_CODE_BLOCKADDRESS; 2653 Record.push_back(VE.getTypeID(BA->getFunction()->getType())); 2654 Record.push_back(VE.getValueID(BA->getFunction())); 2655 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock())); 2656 } else if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) { 2657 Code = bitc::CST_CODE_DSO_LOCAL_EQUIVALENT; 2658 Record.push_back(VE.getTypeID(Equiv->getGlobalValue()->getType())); 2659 Record.push_back(VE.getValueID(Equiv->getGlobalValue())); 2660 } else { 2661 #ifndef NDEBUG 2662 C->dump(); 2663 #endif 2664 llvm_unreachable("Unknown constant!"); 2665 } 2666 Stream.EmitRecord(Code, Record, AbbrevToUse); 2667 Record.clear(); 2668 } 2669 2670 Stream.ExitBlock(); 2671 } 2672 2673 void ModuleBitcodeWriter::writeModuleConstants() { 2674 const ValueEnumerator::ValueList &Vals = VE.getValues(); 2675 2676 // Find the first constant to emit, which is the first non-globalvalue value. 2677 // We know globalvalues have been emitted by WriteModuleInfo. 2678 for (unsigned i = 0, e = Vals.size(); i != e; ++i) { 2679 if (!isa<GlobalValue>(Vals[i].first)) { 2680 writeConstants(i, Vals.size(), true); 2681 return; 2682 } 2683 } 2684 } 2685 2686 /// pushValueAndType - The file has to encode both the value and type id for 2687 /// many values, because we need to know what type to create for forward 2688 /// references. However, most operands are not forward references, so this type 2689 /// field is not needed. 2690 /// 2691 /// This function adds V's value ID to Vals. If the value ID is higher than the 2692 /// instruction ID, then it is a forward reference, and it also includes the 2693 /// type ID. The value ID that is written is encoded relative to the InstID. 2694 bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID, 2695 SmallVectorImpl<unsigned> &Vals) { 2696 unsigned ValID = VE.getValueID(V); 2697 // Make encoding relative to the InstID. 2698 Vals.push_back(InstID - ValID); 2699 if (ValID >= InstID) { 2700 Vals.push_back(VE.getTypeID(V->getType())); 2701 return true; 2702 } 2703 return false; 2704 } 2705 2706 void ModuleBitcodeWriter::writeOperandBundles(const CallBase &CS, 2707 unsigned InstID) { 2708 SmallVector<unsigned, 64> Record; 2709 LLVMContext &C = CS.getContext(); 2710 2711 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) { 2712 const auto &Bundle = CS.getOperandBundleAt(i); 2713 Record.push_back(C.getOperandBundleTagID(Bundle.getTagName())); 2714 2715 for (auto &Input : Bundle.Inputs) 2716 pushValueAndType(Input, InstID, Record); 2717 2718 Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record); 2719 Record.clear(); 2720 } 2721 } 2722 2723 /// pushValue - Like pushValueAndType, but where the type of the value is 2724 /// omitted (perhaps it was already encoded in an earlier operand). 2725 void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID, 2726 SmallVectorImpl<unsigned> &Vals) { 2727 unsigned ValID = VE.getValueID(V); 2728 Vals.push_back(InstID - ValID); 2729 } 2730 2731 void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID, 2732 SmallVectorImpl<uint64_t> &Vals) { 2733 unsigned ValID = VE.getValueID(V); 2734 int64_t diff = ((int32_t)InstID - (int32_t)ValID); 2735 emitSignedInt64(Vals, diff); 2736 } 2737 2738 /// WriteInstruction - Emit an instruction to the specified stream. 2739 void ModuleBitcodeWriter::writeInstruction(const Instruction &I, 2740 unsigned InstID, 2741 SmallVectorImpl<unsigned> &Vals) { 2742 unsigned Code = 0; 2743 unsigned AbbrevToUse = 0; 2744 VE.setInstructionID(&I); 2745 switch (I.getOpcode()) { 2746 default: 2747 if (Instruction::isCast(I.getOpcode())) { 2748 Code = bitc::FUNC_CODE_INST_CAST; 2749 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) 2750 AbbrevToUse = FUNCTION_INST_CAST_ABBREV; 2751 Vals.push_back(VE.getTypeID(I.getType())); 2752 Vals.push_back(getEncodedCastOpcode(I.getOpcode())); 2753 } else { 2754 assert(isa<BinaryOperator>(I) && "Unknown instruction!"); 2755 Code = bitc::FUNC_CODE_INST_BINOP; 2756 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) 2757 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV; 2758 pushValue(I.getOperand(1), InstID, Vals); 2759 Vals.push_back(getEncodedBinaryOpcode(I.getOpcode())); 2760 uint64_t Flags = getOptimizationFlags(&I); 2761 if (Flags != 0) { 2762 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV) 2763 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV; 2764 Vals.push_back(Flags); 2765 } 2766 } 2767 break; 2768 case Instruction::FNeg: { 2769 Code = bitc::FUNC_CODE_INST_UNOP; 2770 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) 2771 AbbrevToUse = FUNCTION_INST_UNOP_ABBREV; 2772 Vals.push_back(getEncodedUnaryOpcode(I.getOpcode())); 2773 uint64_t Flags = getOptimizationFlags(&I); 2774 if (Flags != 0) { 2775 if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV) 2776 AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV; 2777 Vals.push_back(Flags); 2778 } 2779 break; 2780 } 2781 case Instruction::GetElementPtr: { 2782 Code = bitc::FUNC_CODE_INST_GEP; 2783 AbbrevToUse = FUNCTION_INST_GEP_ABBREV; 2784 auto &GEPInst = cast<GetElementPtrInst>(I); 2785 Vals.push_back(GEPInst.isInBounds()); 2786 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType())); 2787 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) 2788 pushValueAndType(I.getOperand(i), InstID, Vals); 2789 break; 2790 } 2791 case Instruction::ExtractValue: { 2792 Code = bitc::FUNC_CODE_INST_EXTRACTVAL; 2793 pushValueAndType(I.getOperand(0), InstID, Vals); 2794 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I); 2795 Vals.append(EVI->idx_begin(), EVI->idx_end()); 2796 break; 2797 } 2798 case Instruction::InsertValue: { 2799 Code = bitc::FUNC_CODE_INST_INSERTVAL; 2800 pushValueAndType(I.getOperand(0), InstID, Vals); 2801 pushValueAndType(I.getOperand(1), InstID, Vals); 2802 const InsertValueInst *IVI = cast<InsertValueInst>(&I); 2803 Vals.append(IVI->idx_begin(), IVI->idx_end()); 2804 break; 2805 } 2806 case Instruction::Select: { 2807 Code = bitc::FUNC_CODE_INST_VSELECT; 2808 pushValueAndType(I.getOperand(1), InstID, Vals); 2809 pushValue(I.getOperand(2), InstID, Vals); 2810 pushValueAndType(I.getOperand(0), InstID, Vals); 2811 uint64_t Flags = getOptimizationFlags(&I); 2812 if (Flags != 0) 2813 Vals.push_back(Flags); 2814 break; 2815 } 2816 case Instruction::ExtractElement: 2817 Code = bitc::FUNC_CODE_INST_EXTRACTELT; 2818 pushValueAndType(I.getOperand(0), InstID, Vals); 2819 pushValueAndType(I.getOperand(1), InstID, Vals); 2820 break; 2821 case Instruction::InsertElement: 2822 Code = bitc::FUNC_CODE_INST_INSERTELT; 2823 pushValueAndType(I.getOperand(0), InstID, Vals); 2824 pushValue(I.getOperand(1), InstID, Vals); 2825 pushValueAndType(I.getOperand(2), InstID, Vals); 2826 break; 2827 case Instruction::ShuffleVector: 2828 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC; 2829 pushValueAndType(I.getOperand(0), InstID, Vals); 2830 pushValue(I.getOperand(1), InstID, Vals); 2831 pushValue(cast<ShuffleVectorInst>(I).getShuffleMaskForBitcode(), InstID, 2832 Vals); 2833 break; 2834 case Instruction::ICmp: 2835 case Instruction::FCmp: { 2836 // compare returning Int1Ty or vector of Int1Ty 2837 Code = bitc::FUNC_CODE_INST_CMP2; 2838 pushValueAndType(I.getOperand(0), InstID, Vals); 2839 pushValue(I.getOperand(1), InstID, Vals); 2840 Vals.push_back(cast<CmpInst>(I).getPredicate()); 2841 uint64_t Flags = getOptimizationFlags(&I); 2842 if (Flags != 0) 2843 Vals.push_back(Flags); 2844 break; 2845 } 2846 2847 case Instruction::Ret: 2848 { 2849 Code = bitc::FUNC_CODE_INST_RET; 2850 unsigned NumOperands = I.getNumOperands(); 2851 if (NumOperands == 0) 2852 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV; 2853 else if (NumOperands == 1) { 2854 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) 2855 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV; 2856 } else { 2857 for (unsigned i = 0, e = NumOperands; i != e; ++i) 2858 pushValueAndType(I.getOperand(i), InstID, Vals); 2859 } 2860 } 2861 break; 2862 case Instruction::Br: 2863 { 2864 Code = bitc::FUNC_CODE_INST_BR; 2865 const BranchInst &II = cast<BranchInst>(I); 2866 Vals.push_back(VE.getValueID(II.getSuccessor(0))); 2867 if (II.isConditional()) { 2868 Vals.push_back(VE.getValueID(II.getSuccessor(1))); 2869 pushValue(II.getCondition(), InstID, Vals); 2870 } 2871 } 2872 break; 2873 case Instruction::Switch: 2874 { 2875 Code = bitc::FUNC_CODE_INST_SWITCH; 2876 const SwitchInst &SI = cast<SwitchInst>(I); 2877 Vals.push_back(VE.getTypeID(SI.getCondition()->getType())); 2878 pushValue(SI.getCondition(), InstID, Vals); 2879 Vals.push_back(VE.getValueID(SI.getDefaultDest())); 2880 for (auto Case : SI.cases()) { 2881 Vals.push_back(VE.getValueID(Case.getCaseValue())); 2882 Vals.push_back(VE.getValueID(Case.getCaseSuccessor())); 2883 } 2884 } 2885 break; 2886 case Instruction::IndirectBr: 2887 Code = bitc::FUNC_CODE_INST_INDIRECTBR; 2888 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); 2889 // Encode the address operand as relative, but not the basic blocks. 2890 pushValue(I.getOperand(0), InstID, Vals); 2891 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) 2892 Vals.push_back(VE.getValueID(I.getOperand(i))); 2893 break; 2894 2895 case Instruction::Invoke: { 2896 const InvokeInst *II = cast<InvokeInst>(&I); 2897 const Value *Callee = II->getCalledOperand(); 2898 FunctionType *FTy = II->getFunctionType(); 2899 2900 if (II->hasOperandBundles()) 2901 writeOperandBundles(*II, InstID); 2902 2903 Code = bitc::FUNC_CODE_INST_INVOKE; 2904 2905 Vals.push_back(VE.getAttributeListID(II->getAttributes())); 2906 Vals.push_back(II->getCallingConv() | 1 << 13); 2907 Vals.push_back(VE.getValueID(II->getNormalDest())); 2908 Vals.push_back(VE.getValueID(II->getUnwindDest())); 2909 Vals.push_back(VE.getTypeID(FTy)); 2910 pushValueAndType(Callee, InstID, Vals); 2911 2912 // Emit value #'s for the fixed parameters. 2913 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) 2914 pushValue(I.getOperand(i), InstID, Vals); // fixed param. 2915 2916 // Emit type/value pairs for varargs params. 2917 if (FTy->isVarArg()) { 2918 for (unsigned i = FTy->getNumParams(), e = II->arg_size(); i != e; ++i) 2919 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg 2920 } 2921 break; 2922 } 2923 case Instruction::Resume: 2924 Code = bitc::FUNC_CODE_INST_RESUME; 2925 pushValueAndType(I.getOperand(0), InstID, Vals); 2926 break; 2927 case Instruction::CleanupRet: { 2928 Code = bitc::FUNC_CODE_INST_CLEANUPRET; 2929 const auto &CRI = cast<CleanupReturnInst>(I); 2930 pushValue(CRI.getCleanupPad(), InstID, Vals); 2931 if (CRI.hasUnwindDest()) 2932 Vals.push_back(VE.getValueID(CRI.getUnwindDest())); 2933 break; 2934 } 2935 case Instruction::CatchRet: { 2936 Code = bitc::FUNC_CODE_INST_CATCHRET; 2937 const auto &CRI = cast<CatchReturnInst>(I); 2938 pushValue(CRI.getCatchPad(), InstID, Vals); 2939 Vals.push_back(VE.getValueID(CRI.getSuccessor())); 2940 break; 2941 } 2942 case Instruction::CleanupPad: 2943 case Instruction::CatchPad: { 2944 const auto &FuncletPad = cast<FuncletPadInst>(I); 2945 Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD 2946 : bitc::FUNC_CODE_INST_CLEANUPPAD; 2947 pushValue(FuncletPad.getParentPad(), InstID, Vals); 2948 2949 unsigned NumArgOperands = FuncletPad.getNumArgOperands(); 2950 Vals.push_back(NumArgOperands); 2951 for (unsigned Op = 0; Op != NumArgOperands; ++Op) 2952 pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals); 2953 break; 2954 } 2955 case Instruction::CatchSwitch: { 2956 Code = bitc::FUNC_CODE_INST_CATCHSWITCH; 2957 const auto &CatchSwitch = cast<CatchSwitchInst>(I); 2958 2959 pushValue(CatchSwitch.getParentPad(), InstID, Vals); 2960 2961 unsigned NumHandlers = CatchSwitch.getNumHandlers(); 2962 Vals.push_back(NumHandlers); 2963 for (const BasicBlock *CatchPadBB : CatchSwitch.handlers()) 2964 Vals.push_back(VE.getValueID(CatchPadBB)); 2965 2966 if (CatchSwitch.hasUnwindDest()) 2967 Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest())); 2968 break; 2969 } 2970 case Instruction::CallBr: { 2971 const CallBrInst *CBI = cast<CallBrInst>(&I); 2972 const Value *Callee = CBI->getCalledOperand(); 2973 FunctionType *FTy = CBI->getFunctionType(); 2974 2975 if (CBI->hasOperandBundles()) 2976 writeOperandBundles(*CBI, InstID); 2977 2978 Code = bitc::FUNC_CODE_INST_CALLBR; 2979 2980 Vals.push_back(VE.getAttributeListID(CBI->getAttributes())); 2981 2982 Vals.push_back(CBI->getCallingConv() << bitc::CALL_CCONV | 2983 1 << bitc::CALL_EXPLICIT_TYPE); 2984 2985 Vals.push_back(VE.getValueID(CBI->getDefaultDest())); 2986 Vals.push_back(CBI->getNumIndirectDests()); 2987 for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i) 2988 Vals.push_back(VE.getValueID(CBI->getIndirectDest(i))); 2989 2990 Vals.push_back(VE.getTypeID(FTy)); 2991 pushValueAndType(Callee, InstID, Vals); 2992 2993 // Emit value #'s for the fixed parameters. 2994 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) 2995 pushValue(I.getOperand(i), InstID, Vals); // fixed param. 2996 2997 // Emit type/value pairs for varargs params. 2998 if (FTy->isVarArg()) { 2999 for (unsigned i = FTy->getNumParams(), e = CBI->arg_size(); i != e; ++i) 3000 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg 3001 } 3002 break; 3003 } 3004 case Instruction::Unreachable: 3005 Code = bitc::FUNC_CODE_INST_UNREACHABLE; 3006 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV; 3007 break; 3008 3009 case Instruction::PHI: { 3010 const PHINode &PN = cast<PHINode>(I); 3011 Code = bitc::FUNC_CODE_INST_PHI; 3012 // With the newer instruction encoding, forward references could give 3013 // negative valued IDs. This is most common for PHIs, so we use 3014 // signed VBRs. 3015 SmallVector<uint64_t, 128> Vals64; 3016 Vals64.push_back(VE.getTypeID(PN.getType())); 3017 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) { 3018 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64); 3019 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i))); 3020 } 3021 3022 uint64_t Flags = getOptimizationFlags(&I); 3023 if (Flags != 0) 3024 Vals64.push_back(Flags); 3025 3026 // Emit a Vals64 vector and exit. 3027 Stream.EmitRecord(Code, Vals64, AbbrevToUse); 3028 Vals64.clear(); 3029 return; 3030 } 3031 3032 case Instruction::LandingPad: { 3033 const LandingPadInst &LP = cast<LandingPadInst>(I); 3034 Code = bitc::FUNC_CODE_INST_LANDINGPAD; 3035 Vals.push_back(VE.getTypeID(LP.getType())); 3036 Vals.push_back(LP.isCleanup()); 3037 Vals.push_back(LP.getNumClauses()); 3038 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) { 3039 if (LP.isCatch(I)) 3040 Vals.push_back(LandingPadInst::Catch); 3041 else 3042 Vals.push_back(LandingPadInst::Filter); 3043 pushValueAndType(LP.getClause(I), InstID, Vals); 3044 } 3045 break; 3046 } 3047 3048 case Instruction::Alloca: { 3049 Code = bitc::FUNC_CODE_INST_ALLOCA; 3050 const AllocaInst &AI = cast<AllocaInst>(I); 3051 Vals.push_back(VE.getTypeID(AI.getAllocatedType())); 3052 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); 3053 Vals.push_back(VE.getValueID(I.getOperand(0))); // size. 3054 using APV = AllocaPackedValues; 3055 unsigned Record = 0; 3056 unsigned EncodedAlign = getEncodedAlign(AI.getAlign()); 3057 Bitfield::set<APV::AlignLower>( 3058 Record, EncodedAlign & ((1 << APV::AlignLower::Bits) - 1)); 3059 Bitfield::set<APV::AlignUpper>(Record, 3060 EncodedAlign >> APV::AlignLower::Bits); 3061 Bitfield::set<APV::UsedWithInAlloca>(Record, AI.isUsedWithInAlloca()); 3062 Bitfield::set<APV::ExplicitType>(Record, true); 3063 Bitfield::set<APV::SwiftError>(Record, AI.isSwiftError()); 3064 Vals.push_back(Record); 3065 break; 3066 } 3067 3068 case Instruction::Load: 3069 if (cast<LoadInst>(I).isAtomic()) { 3070 Code = bitc::FUNC_CODE_INST_LOADATOMIC; 3071 pushValueAndType(I.getOperand(0), InstID, Vals); 3072 } else { 3073 Code = bitc::FUNC_CODE_INST_LOAD; 3074 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr 3075 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV; 3076 } 3077 Vals.push_back(VE.getTypeID(I.getType())); 3078 Vals.push_back(getEncodedAlign(cast<LoadInst>(I).getAlign())); 3079 Vals.push_back(cast<LoadInst>(I).isVolatile()); 3080 if (cast<LoadInst>(I).isAtomic()) { 3081 Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering())); 3082 Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID())); 3083 } 3084 break; 3085 case Instruction::Store: 3086 if (cast<StoreInst>(I).isAtomic()) 3087 Code = bitc::FUNC_CODE_INST_STOREATOMIC; 3088 else 3089 Code = bitc::FUNC_CODE_INST_STORE; 3090 pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr 3091 pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val 3092 Vals.push_back(getEncodedAlign(cast<StoreInst>(I).getAlign())); 3093 Vals.push_back(cast<StoreInst>(I).isVolatile()); 3094 if (cast<StoreInst>(I).isAtomic()) { 3095 Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering())); 3096 Vals.push_back( 3097 getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID())); 3098 } 3099 break; 3100 case Instruction::AtomicCmpXchg: 3101 Code = bitc::FUNC_CODE_INST_CMPXCHG; 3102 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr 3103 pushValueAndType(I.getOperand(1), InstID, Vals); // cmp. 3104 pushValue(I.getOperand(2), InstID, Vals); // newval. 3105 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile()); 3106 Vals.push_back( 3107 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering())); 3108 Vals.push_back( 3109 getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID())); 3110 Vals.push_back( 3111 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering())); 3112 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak()); 3113 Vals.push_back(getEncodedAlign(cast<AtomicCmpXchgInst>(I).getAlign())); 3114 break; 3115 case Instruction::AtomicRMW: 3116 Code = bitc::FUNC_CODE_INST_ATOMICRMW; 3117 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr 3118 pushValueAndType(I.getOperand(1), InstID, Vals); // valty + val 3119 Vals.push_back( 3120 getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation())); 3121 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile()); 3122 Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering())); 3123 Vals.push_back( 3124 getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID())); 3125 Vals.push_back(getEncodedAlign(cast<AtomicRMWInst>(I).getAlign())); 3126 break; 3127 case Instruction::Fence: 3128 Code = bitc::FUNC_CODE_INST_FENCE; 3129 Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering())); 3130 Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID())); 3131 break; 3132 case Instruction::Call: { 3133 const CallInst &CI = cast<CallInst>(I); 3134 FunctionType *FTy = CI.getFunctionType(); 3135 3136 if (CI.hasOperandBundles()) 3137 writeOperandBundles(CI, InstID); 3138 3139 Code = bitc::FUNC_CODE_INST_CALL; 3140 3141 Vals.push_back(VE.getAttributeListID(CI.getAttributes())); 3142 3143 unsigned Flags = getOptimizationFlags(&I); 3144 Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV | 3145 unsigned(CI.isTailCall()) << bitc::CALL_TAIL | 3146 unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL | 3147 1 << bitc::CALL_EXPLICIT_TYPE | 3148 unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL | 3149 unsigned(Flags != 0) << bitc::CALL_FMF); 3150 if (Flags != 0) 3151 Vals.push_back(Flags); 3152 3153 Vals.push_back(VE.getTypeID(FTy)); 3154 pushValueAndType(CI.getCalledOperand(), InstID, Vals); // Callee 3155 3156 // Emit value #'s for the fixed parameters. 3157 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) { 3158 // Check for labels (can happen with asm labels). 3159 if (FTy->getParamType(i)->isLabelTy()) 3160 Vals.push_back(VE.getValueID(CI.getArgOperand(i))); 3161 else 3162 pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param. 3163 } 3164 3165 // Emit type/value pairs for varargs params. 3166 if (FTy->isVarArg()) { 3167 for (unsigned i = FTy->getNumParams(), e = CI.arg_size(); i != e; ++i) 3168 pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs 3169 } 3170 break; 3171 } 3172 case Instruction::VAArg: 3173 Code = bitc::FUNC_CODE_INST_VAARG; 3174 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty 3175 pushValue(I.getOperand(0), InstID, Vals); // valist. 3176 Vals.push_back(VE.getTypeID(I.getType())); // restype. 3177 break; 3178 case Instruction::Freeze: 3179 Code = bitc::FUNC_CODE_INST_FREEZE; 3180 pushValueAndType(I.getOperand(0), InstID, Vals); 3181 break; 3182 } 3183 3184 Stream.EmitRecord(Code, Vals, AbbrevToUse); 3185 Vals.clear(); 3186 } 3187 3188 /// Write a GlobalValue VST to the module. The purpose of this data structure is 3189 /// to allow clients to efficiently find the function body. 3190 void ModuleBitcodeWriter::writeGlobalValueSymbolTable( 3191 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) { 3192 // Get the offset of the VST we are writing, and backpatch it into 3193 // the VST forward declaration record. 3194 uint64_t VSTOffset = Stream.GetCurrentBitNo(); 3195 // The BitcodeStartBit was the stream offset of the identification block. 3196 VSTOffset -= bitcodeStartBit(); 3197 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned"); 3198 // Note that we add 1 here because the offset is relative to one word 3199 // before the start of the identification block, which was historically 3200 // always the start of the regular bitcode header. 3201 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1); 3202 3203 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4); 3204 3205 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3206 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY)); 3207 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id 3208 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset 3209 unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 3210 3211 for (const Function &F : M) { 3212 uint64_t Record[2]; 3213 3214 if (F.isDeclaration()) 3215 continue; 3216 3217 Record[0] = VE.getValueID(&F); 3218 3219 // Save the word offset of the function (from the start of the 3220 // actual bitcode written to the stream). 3221 uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit(); 3222 assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned"); 3223 // Note that we add 1 here because the offset is relative to one word 3224 // before the start of the identification block, which was historically 3225 // always the start of the regular bitcode header. 3226 Record[1] = BitcodeIndex / 32 + 1; 3227 3228 Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev); 3229 } 3230 3231 Stream.ExitBlock(); 3232 } 3233 3234 /// Emit names for arguments, instructions and basic blocks in a function. 3235 void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable( 3236 const ValueSymbolTable &VST) { 3237 if (VST.empty()) 3238 return; 3239 3240 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4); 3241 3242 // FIXME: Set up the abbrev, we know how many values there are! 3243 // FIXME: We know if the type names can use 7-bit ascii. 3244 SmallVector<uint64_t, 64> NameVals; 3245 3246 for (const ValueName &Name : VST) { 3247 // Figure out the encoding to use for the name. 3248 StringEncoding Bits = getStringEncoding(Name.getKey()); 3249 3250 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV; 3251 NameVals.push_back(VE.getValueID(Name.getValue())); 3252 3253 // VST_CODE_ENTRY: [valueid, namechar x N] 3254 // VST_CODE_BBENTRY: [bbid, namechar x N] 3255 unsigned Code; 3256 if (isa<BasicBlock>(Name.getValue())) { 3257 Code = bitc::VST_CODE_BBENTRY; 3258 if (Bits == SE_Char6) 3259 AbbrevToUse = VST_BBENTRY_6_ABBREV; 3260 } else { 3261 Code = bitc::VST_CODE_ENTRY; 3262 if (Bits == SE_Char6) 3263 AbbrevToUse = VST_ENTRY_6_ABBREV; 3264 else if (Bits == SE_Fixed7) 3265 AbbrevToUse = VST_ENTRY_7_ABBREV; 3266 } 3267 3268 for (const auto P : Name.getKey()) 3269 NameVals.push_back((unsigned char)P); 3270 3271 // Emit the finished record. 3272 Stream.EmitRecord(Code, NameVals, AbbrevToUse); 3273 NameVals.clear(); 3274 } 3275 3276 Stream.ExitBlock(); 3277 } 3278 3279 void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) { 3280 assert(Order.Shuffle.size() >= 2 && "Shuffle too small"); 3281 unsigned Code; 3282 if (isa<BasicBlock>(Order.V)) 3283 Code = bitc::USELIST_CODE_BB; 3284 else 3285 Code = bitc::USELIST_CODE_DEFAULT; 3286 3287 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end()); 3288 Record.push_back(VE.getValueID(Order.V)); 3289 Stream.EmitRecord(Code, Record); 3290 } 3291 3292 void ModuleBitcodeWriter::writeUseListBlock(const Function *F) { 3293 assert(VE.shouldPreserveUseListOrder() && 3294 "Expected to be preserving use-list order"); 3295 3296 auto hasMore = [&]() { 3297 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F; 3298 }; 3299 if (!hasMore()) 3300 // Nothing to do. 3301 return; 3302 3303 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3); 3304 while (hasMore()) { 3305 writeUseList(std::move(VE.UseListOrders.back())); 3306 VE.UseListOrders.pop_back(); 3307 } 3308 Stream.ExitBlock(); 3309 } 3310 3311 /// Emit a function body to the module stream. 3312 void ModuleBitcodeWriter::writeFunction( 3313 const Function &F, 3314 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) { 3315 // Save the bitcode index of the start of this function block for recording 3316 // in the VST. 3317 FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo(); 3318 3319 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4); 3320 VE.incorporateFunction(F); 3321 3322 SmallVector<unsigned, 64> Vals; 3323 3324 // Emit the number of basic blocks, so the reader can create them ahead of 3325 // time. 3326 Vals.push_back(VE.getBasicBlocks().size()); 3327 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals); 3328 Vals.clear(); 3329 3330 // If there are function-local constants, emit them now. 3331 unsigned CstStart, CstEnd; 3332 VE.getFunctionConstantRange(CstStart, CstEnd); 3333 writeConstants(CstStart, CstEnd, false); 3334 3335 // If there is function-local metadata, emit it now. 3336 writeFunctionMetadata(F); 3337 3338 // Keep a running idea of what the instruction ID is. 3339 unsigned InstID = CstEnd; 3340 3341 bool NeedsMetadataAttachment = F.hasMetadata(); 3342 3343 DILocation *LastDL = nullptr; 3344 // Finally, emit all the instructions, in order. 3345 for (const BasicBlock &BB : F) 3346 for (const Instruction &I : BB) { 3347 writeInstruction(I, InstID, Vals); 3348 3349 if (!I.getType()->isVoidTy()) 3350 ++InstID; 3351 3352 // If the instruction has metadata, write a metadata attachment later. 3353 NeedsMetadataAttachment |= I.hasMetadataOtherThanDebugLoc(); 3354 3355 // If the instruction has a debug location, emit it. 3356 DILocation *DL = I.getDebugLoc(); 3357 if (!DL) 3358 continue; 3359 3360 if (DL == LastDL) { 3361 // Just repeat the same debug loc as last time. 3362 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals); 3363 continue; 3364 } 3365 3366 Vals.push_back(DL->getLine()); 3367 Vals.push_back(DL->getColumn()); 3368 Vals.push_back(VE.getMetadataOrNullID(DL->getScope())); 3369 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt())); 3370 Vals.push_back(DL->isImplicitCode()); 3371 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals); 3372 Vals.clear(); 3373 3374 LastDL = DL; 3375 } 3376 3377 // Emit names for all the instructions etc. 3378 if (auto *Symtab = F.getValueSymbolTable()) 3379 writeFunctionLevelValueSymbolTable(*Symtab); 3380 3381 if (NeedsMetadataAttachment) 3382 writeFunctionMetadataAttachment(F); 3383 if (VE.shouldPreserveUseListOrder()) 3384 writeUseListBlock(&F); 3385 VE.purgeFunction(); 3386 Stream.ExitBlock(); 3387 } 3388 3389 // Emit blockinfo, which defines the standard abbreviations etc. 3390 void ModuleBitcodeWriter::writeBlockInfo() { 3391 // We only want to emit block info records for blocks that have multiple 3392 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK. 3393 // Other blocks can define their abbrevs inline. 3394 Stream.EnterBlockInfoBlock(); 3395 3396 { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings. 3397 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3398 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); 3399 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3400 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3401 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 3402 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) != 3403 VST_ENTRY_8_ABBREV) 3404 llvm_unreachable("Unexpected abbrev ordering!"); 3405 } 3406 3407 { // 7-bit fixed width VST_CODE_ENTRY strings. 3408 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3409 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY)); 3410 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3411 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3412 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); 3413 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) != 3414 VST_ENTRY_7_ABBREV) 3415 llvm_unreachable("Unexpected abbrev ordering!"); 3416 } 3417 { // 6-bit char6 VST_CODE_ENTRY strings. 3418 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3419 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY)); 3420 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3421 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3422 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 3423 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) != 3424 VST_ENTRY_6_ABBREV) 3425 llvm_unreachable("Unexpected abbrev ordering!"); 3426 } 3427 { // 6-bit char6 VST_CODE_BBENTRY strings. 3428 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3429 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY)); 3430 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3431 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3432 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 3433 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) != 3434 VST_BBENTRY_6_ABBREV) 3435 llvm_unreachable("Unexpected abbrev ordering!"); 3436 } 3437 3438 { // SETTYPE abbrev for CONSTANTS_BLOCK. 3439 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3440 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE)); 3441 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3442 VE.computeBitsRequiredForTypeIndicies())); 3443 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) != 3444 CONSTANTS_SETTYPE_ABBREV) 3445 llvm_unreachable("Unexpected abbrev ordering!"); 3446 } 3447 3448 { // INTEGER abbrev for CONSTANTS_BLOCK. 3449 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3450 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER)); 3451 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3452 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) != 3453 CONSTANTS_INTEGER_ABBREV) 3454 llvm_unreachable("Unexpected abbrev ordering!"); 3455 } 3456 3457 { // CE_CAST abbrev for CONSTANTS_BLOCK. 3458 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3459 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST)); 3460 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc 3461 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid 3462 VE.computeBitsRequiredForTypeIndicies())); 3463 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id 3464 3465 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) != 3466 CONSTANTS_CE_CAST_Abbrev) 3467 llvm_unreachable("Unexpected abbrev ordering!"); 3468 } 3469 { // NULL abbrev for CONSTANTS_BLOCK. 3470 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3471 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL)); 3472 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) != 3473 CONSTANTS_NULL_Abbrev) 3474 llvm_unreachable("Unexpected abbrev ordering!"); 3475 } 3476 3477 // FIXME: This should only use space for first class types! 3478 3479 { // INST_LOAD abbrev for FUNCTION_BLOCK. 3480 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3481 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD)); 3482 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr 3483 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty 3484 VE.computeBitsRequiredForTypeIndicies())); 3485 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align 3486 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile 3487 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3488 FUNCTION_INST_LOAD_ABBREV) 3489 llvm_unreachable("Unexpected abbrev ordering!"); 3490 } 3491 { // INST_UNOP abbrev for FUNCTION_BLOCK. 3492 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3493 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP)); 3494 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS 3495 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 3496 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3497 FUNCTION_INST_UNOP_ABBREV) 3498 llvm_unreachable("Unexpected abbrev ordering!"); 3499 } 3500 { // INST_UNOP_FLAGS abbrev for FUNCTION_BLOCK. 3501 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3502 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP)); 3503 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS 3504 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 3505 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags 3506 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3507 FUNCTION_INST_UNOP_FLAGS_ABBREV) 3508 llvm_unreachable("Unexpected abbrev ordering!"); 3509 } 3510 { // INST_BINOP abbrev for FUNCTION_BLOCK. 3511 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3512 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP)); 3513 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS 3514 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS 3515 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 3516 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3517 FUNCTION_INST_BINOP_ABBREV) 3518 llvm_unreachable("Unexpected abbrev ordering!"); 3519 } 3520 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK. 3521 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3522 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP)); 3523 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS 3524 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS 3525 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 3526 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags 3527 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3528 FUNCTION_INST_BINOP_FLAGS_ABBREV) 3529 llvm_unreachable("Unexpected abbrev ordering!"); 3530 } 3531 { // INST_CAST abbrev for FUNCTION_BLOCK. 3532 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3533 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST)); 3534 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal 3535 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty 3536 VE.computeBitsRequiredForTypeIndicies())); 3537 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 3538 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3539 FUNCTION_INST_CAST_ABBREV) 3540 llvm_unreachable("Unexpected abbrev ordering!"); 3541 } 3542 3543 { // INST_RET abbrev for FUNCTION_BLOCK. 3544 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3545 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET)); 3546 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3547 FUNCTION_INST_RET_VOID_ABBREV) 3548 llvm_unreachable("Unexpected abbrev ordering!"); 3549 } 3550 { // INST_RET abbrev for FUNCTION_BLOCK. 3551 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3552 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET)); 3553 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID 3554 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3555 FUNCTION_INST_RET_VAL_ABBREV) 3556 llvm_unreachable("Unexpected abbrev ordering!"); 3557 } 3558 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK. 3559 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3560 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE)); 3561 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3562 FUNCTION_INST_UNREACHABLE_ABBREV) 3563 llvm_unreachable("Unexpected abbrev ordering!"); 3564 } 3565 { 3566 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3567 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP)); 3568 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); 3569 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty 3570 Log2_32_Ceil(VE.getTypes().size() + 1))); 3571 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3572 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 3573 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3574 FUNCTION_INST_GEP_ABBREV) 3575 llvm_unreachable("Unexpected abbrev ordering!"); 3576 } 3577 3578 Stream.ExitBlock(); 3579 } 3580 3581 /// Write the module path strings, currently only used when generating 3582 /// a combined index file. 3583 void IndexBitcodeWriter::writeModStrings() { 3584 Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3); 3585 3586 // TODO: See which abbrev sizes we actually need to emit 3587 3588 // 8-bit fixed-width MST_ENTRY strings. 3589 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3590 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY)); 3591 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3592 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3593 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 3594 unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv)); 3595 3596 // 7-bit fixed width MST_ENTRY strings. 3597 Abbv = std::make_shared<BitCodeAbbrev>(); 3598 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY)); 3599 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3600 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3601 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); 3602 unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv)); 3603 3604 // 6-bit char6 MST_ENTRY strings. 3605 Abbv = std::make_shared<BitCodeAbbrev>(); 3606 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY)); 3607 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3608 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3609 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 3610 unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv)); 3611 3612 // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY. 3613 Abbv = std::make_shared<BitCodeAbbrev>(); 3614 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH)); 3615 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 3616 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 3617 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 3618 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 3619 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 3620 unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv)); 3621 3622 SmallVector<unsigned, 64> Vals; 3623 forEachModule( 3624 [&](const StringMapEntry<std::pair<uint64_t, ModuleHash>> &MPSE) { 3625 StringRef Key = MPSE.getKey(); 3626 const auto &Value = MPSE.getValue(); 3627 StringEncoding Bits = getStringEncoding(Key); 3628 unsigned AbbrevToUse = Abbrev8Bit; 3629 if (Bits == SE_Char6) 3630 AbbrevToUse = Abbrev6Bit; 3631 else if (Bits == SE_Fixed7) 3632 AbbrevToUse = Abbrev7Bit; 3633 3634 Vals.push_back(Value.first); 3635 Vals.append(Key.begin(), Key.end()); 3636 3637 // Emit the finished record. 3638 Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse); 3639 3640 // Emit an optional hash for the module now 3641 const auto &Hash = Value.second; 3642 if (llvm::any_of(Hash, [](uint32_t H) { return H; })) { 3643 Vals.assign(Hash.begin(), Hash.end()); 3644 // Emit the hash record. 3645 Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash); 3646 } 3647 3648 Vals.clear(); 3649 }); 3650 Stream.ExitBlock(); 3651 } 3652 3653 /// Write the function type metadata related records that need to appear before 3654 /// a function summary entry (whether per-module or combined). 3655 template <typename Fn> 3656 static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream, 3657 FunctionSummary *FS, 3658 Fn GetValueID) { 3659 if (!FS->type_tests().empty()) 3660 Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests()); 3661 3662 SmallVector<uint64_t, 64> Record; 3663 3664 auto WriteVFuncIdVec = [&](uint64_t Ty, 3665 ArrayRef<FunctionSummary::VFuncId> VFs) { 3666 if (VFs.empty()) 3667 return; 3668 Record.clear(); 3669 for (auto &VF : VFs) { 3670 Record.push_back(VF.GUID); 3671 Record.push_back(VF.Offset); 3672 } 3673 Stream.EmitRecord(Ty, Record); 3674 }; 3675 3676 WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS, 3677 FS->type_test_assume_vcalls()); 3678 WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS, 3679 FS->type_checked_load_vcalls()); 3680 3681 auto WriteConstVCallVec = [&](uint64_t Ty, 3682 ArrayRef<FunctionSummary::ConstVCall> VCs) { 3683 for (auto &VC : VCs) { 3684 Record.clear(); 3685 Record.push_back(VC.VFunc.GUID); 3686 Record.push_back(VC.VFunc.Offset); 3687 llvm::append_range(Record, VC.Args); 3688 Stream.EmitRecord(Ty, Record); 3689 } 3690 }; 3691 3692 WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL, 3693 FS->type_test_assume_const_vcalls()); 3694 WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL, 3695 FS->type_checked_load_const_vcalls()); 3696 3697 auto WriteRange = [&](ConstantRange Range) { 3698 Range = Range.sextOrTrunc(FunctionSummary::ParamAccess::RangeWidth); 3699 assert(Range.getLower().getNumWords() == 1); 3700 assert(Range.getUpper().getNumWords() == 1); 3701 emitSignedInt64(Record, *Range.getLower().getRawData()); 3702 emitSignedInt64(Record, *Range.getUpper().getRawData()); 3703 }; 3704 3705 if (!FS->paramAccesses().empty()) { 3706 Record.clear(); 3707 for (auto &Arg : FS->paramAccesses()) { 3708 size_t UndoSize = Record.size(); 3709 Record.push_back(Arg.ParamNo); 3710 WriteRange(Arg.Use); 3711 Record.push_back(Arg.Calls.size()); 3712 for (auto &Call : Arg.Calls) { 3713 Record.push_back(Call.ParamNo); 3714 Optional<unsigned> ValueID = GetValueID(Call.Callee); 3715 if (!ValueID) { 3716 // If ValueID is unknown we can't drop just this call, we must drop 3717 // entire parameter. 3718 Record.resize(UndoSize); 3719 break; 3720 } 3721 Record.push_back(*ValueID); 3722 WriteRange(Call.Offsets); 3723 } 3724 } 3725 if (!Record.empty()) 3726 Stream.EmitRecord(bitc::FS_PARAM_ACCESS, Record); 3727 } 3728 } 3729 3730 /// Collect type IDs from type tests used by function. 3731 static void 3732 getReferencedTypeIds(FunctionSummary *FS, 3733 std::set<GlobalValue::GUID> &ReferencedTypeIds) { 3734 if (!FS->type_tests().empty()) 3735 for (auto &TT : FS->type_tests()) 3736 ReferencedTypeIds.insert(TT); 3737 3738 auto GetReferencedTypesFromVFuncIdVec = 3739 [&](ArrayRef<FunctionSummary::VFuncId> VFs) { 3740 for (auto &VF : VFs) 3741 ReferencedTypeIds.insert(VF.GUID); 3742 }; 3743 3744 GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls()); 3745 GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls()); 3746 3747 auto GetReferencedTypesFromConstVCallVec = 3748 [&](ArrayRef<FunctionSummary::ConstVCall> VCs) { 3749 for (auto &VC : VCs) 3750 ReferencedTypeIds.insert(VC.VFunc.GUID); 3751 }; 3752 3753 GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls()); 3754 GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls()); 3755 } 3756 3757 static void writeWholeProgramDevirtResolutionByArg( 3758 SmallVector<uint64_t, 64> &NameVals, const std::vector<uint64_t> &args, 3759 const WholeProgramDevirtResolution::ByArg &ByArg) { 3760 NameVals.push_back(args.size()); 3761 llvm::append_range(NameVals, args); 3762 3763 NameVals.push_back(ByArg.TheKind); 3764 NameVals.push_back(ByArg.Info); 3765 NameVals.push_back(ByArg.Byte); 3766 NameVals.push_back(ByArg.Bit); 3767 } 3768 3769 static void writeWholeProgramDevirtResolution( 3770 SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder, 3771 uint64_t Id, const WholeProgramDevirtResolution &Wpd) { 3772 NameVals.push_back(Id); 3773 3774 NameVals.push_back(Wpd.TheKind); 3775 NameVals.push_back(StrtabBuilder.add(Wpd.SingleImplName)); 3776 NameVals.push_back(Wpd.SingleImplName.size()); 3777 3778 NameVals.push_back(Wpd.ResByArg.size()); 3779 for (auto &A : Wpd.ResByArg) 3780 writeWholeProgramDevirtResolutionByArg(NameVals, A.first, A.second); 3781 } 3782 3783 static void writeTypeIdSummaryRecord(SmallVector<uint64_t, 64> &NameVals, 3784 StringTableBuilder &StrtabBuilder, 3785 const std::string &Id, 3786 const TypeIdSummary &Summary) { 3787 NameVals.push_back(StrtabBuilder.add(Id)); 3788 NameVals.push_back(Id.size()); 3789 3790 NameVals.push_back(Summary.TTRes.TheKind); 3791 NameVals.push_back(Summary.TTRes.SizeM1BitWidth); 3792 NameVals.push_back(Summary.TTRes.AlignLog2); 3793 NameVals.push_back(Summary.TTRes.SizeM1); 3794 NameVals.push_back(Summary.TTRes.BitMask); 3795 NameVals.push_back(Summary.TTRes.InlineBits); 3796 3797 for (auto &W : Summary.WPDRes) 3798 writeWholeProgramDevirtResolution(NameVals, StrtabBuilder, W.first, 3799 W.second); 3800 } 3801 3802 static void writeTypeIdCompatibleVtableSummaryRecord( 3803 SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder, 3804 const std::string &Id, const TypeIdCompatibleVtableInfo &Summary, 3805 ValueEnumerator &VE) { 3806 NameVals.push_back(StrtabBuilder.add(Id)); 3807 NameVals.push_back(Id.size()); 3808 3809 for (auto &P : Summary) { 3810 NameVals.push_back(P.AddressPointOffset); 3811 NameVals.push_back(VE.getValueID(P.VTableVI.getValue())); 3812 } 3813 } 3814 3815 // Helper to emit a single function summary record. 3816 void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord( 3817 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary, 3818 unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev, 3819 const Function &F) { 3820 NameVals.push_back(ValueID); 3821 3822 FunctionSummary *FS = cast<FunctionSummary>(Summary); 3823 3824 writeFunctionTypeMetadataRecords( 3825 Stream, FS, [&](const ValueInfo &VI) -> Optional<unsigned> { 3826 return {VE.getValueID(VI.getValue())}; 3827 }); 3828 3829 auto SpecialRefCnts = FS->specialRefCounts(); 3830 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags())); 3831 NameVals.push_back(FS->instCount()); 3832 NameVals.push_back(getEncodedFFlags(FS->fflags())); 3833 NameVals.push_back(FS->refs().size()); 3834 NameVals.push_back(SpecialRefCnts.first); // rorefcnt 3835 NameVals.push_back(SpecialRefCnts.second); // worefcnt 3836 3837 for (auto &RI : FS->refs()) 3838 NameVals.push_back(VE.getValueID(RI.getValue())); 3839 3840 bool HasProfileData = 3841 F.hasProfileData() || ForceSummaryEdgesCold != FunctionSummary::FSHT_None; 3842 for (auto &ECI : FS->calls()) { 3843 NameVals.push_back(getValueId(ECI.first)); 3844 if (HasProfileData) 3845 NameVals.push_back(static_cast<uint8_t>(ECI.second.Hotness)); 3846 else if (WriteRelBFToSummary) 3847 NameVals.push_back(ECI.second.RelBlockFreq); 3848 } 3849 3850 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev); 3851 unsigned Code = 3852 (HasProfileData ? bitc::FS_PERMODULE_PROFILE 3853 : (WriteRelBFToSummary ? bitc::FS_PERMODULE_RELBF 3854 : bitc::FS_PERMODULE)); 3855 3856 // Emit the finished record. 3857 Stream.EmitRecord(Code, NameVals, FSAbbrev); 3858 NameVals.clear(); 3859 } 3860 3861 // Collect the global value references in the given variable's initializer, 3862 // and emit them in a summary record. 3863 void ModuleBitcodeWriterBase::writeModuleLevelReferences( 3864 const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals, 3865 unsigned FSModRefsAbbrev, unsigned FSModVTableRefsAbbrev) { 3866 auto VI = Index->getValueInfo(V.getGUID()); 3867 if (!VI || VI.getSummaryList().empty()) { 3868 // Only declarations should not have a summary (a declaration might however 3869 // have a summary if the def was in module level asm). 3870 assert(V.isDeclaration()); 3871 return; 3872 } 3873 auto *Summary = VI.getSummaryList()[0].get(); 3874 NameVals.push_back(VE.getValueID(&V)); 3875 GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary); 3876 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags())); 3877 NameVals.push_back(getEncodedGVarFlags(VS->varflags())); 3878 3879 auto VTableFuncs = VS->vTableFuncs(); 3880 if (!VTableFuncs.empty()) 3881 NameVals.push_back(VS->refs().size()); 3882 3883 unsigned SizeBeforeRefs = NameVals.size(); 3884 for (auto &RI : VS->refs()) 3885 NameVals.push_back(VE.getValueID(RI.getValue())); 3886 // Sort the refs for determinism output, the vector returned by FS->refs() has 3887 // been initialized from a DenseSet. 3888 llvm::sort(drop_begin(NameVals, SizeBeforeRefs)); 3889 3890 if (VTableFuncs.empty()) 3891 Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals, 3892 FSModRefsAbbrev); 3893 else { 3894 // VTableFuncs pairs should already be sorted by offset. 3895 for (auto &P : VTableFuncs) { 3896 NameVals.push_back(VE.getValueID(P.FuncVI.getValue())); 3897 NameVals.push_back(P.VTableOffset); 3898 } 3899 3900 Stream.EmitRecord(bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS, NameVals, 3901 FSModVTableRefsAbbrev); 3902 } 3903 NameVals.clear(); 3904 } 3905 3906 /// Emit the per-module summary section alongside the rest of 3907 /// the module's bitcode. 3908 void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() { 3909 // By default we compile with ThinLTO if the module has a summary, but the 3910 // client can request full LTO with a module flag. 3911 bool IsThinLTO = true; 3912 if (auto *MD = 3913 mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO"))) 3914 IsThinLTO = MD->getZExtValue(); 3915 Stream.EnterSubblock(IsThinLTO ? bitc::GLOBALVAL_SUMMARY_BLOCK_ID 3916 : bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID, 3917 4); 3918 3919 Stream.EmitRecord( 3920 bitc::FS_VERSION, 3921 ArrayRef<uint64_t>{ModuleSummaryIndex::BitcodeSummaryVersion}); 3922 3923 // Write the index flags. 3924 uint64_t Flags = 0; 3925 // Bits 1-3 are set only in the combined index, skip them. 3926 if (Index->enableSplitLTOUnit()) 3927 Flags |= 0x8; 3928 Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Flags}); 3929 3930 if (Index->begin() == Index->end()) { 3931 Stream.ExitBlock(); 3932 return; 3933 } 3934 3935 for (const auto &GVI : valueIds()) { 3936 Stream.EmitRecord(bitc::FS_VALUE_GUID, 3937 ArrayRef<uint64_t>{GVI.second, GVI.first}); 3938 } 3939 3940 // Abbrev for FS_PERMODULE_PROFILE. 3941 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3942 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE)); 3943 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 3944 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 3945 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount 3946 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags 3947 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs 3948 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt 3949 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt 3950 // numrefs x valueid, n x (valueid, hotness) 3951 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3952 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3953 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 3954 3955 // Abbrev for FS_PERMODULE or FS_PERMODULE_RELBF. 3956 Abbv = std::make_shared<BitCodeAbbrev>(); 3957 if (WriteRelBFToSummary) 3958 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_RELBF)); 3959 else 3960 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE)); 3961 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 3962 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 3963 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount 3964 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags 3965 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs 3966 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt 3967 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt 3968 // numrefs x valueid, n x (valueid [, rel_block_freq]) 3969 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3970 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3971 unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 3972 3973 // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS. 3974 Abbv = std::make_shared<BitCodeAbbrev>(); 3975 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS)); 3976 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 3977 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 3978 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids 3979 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3980 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 3981 3982 // Abbrev for FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS. 3983 Abbv = std::make_shared<BitCodeAbbrev>(); 3984 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS)); 3985 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 3986 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 3987 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs 3988 // numrefs x valueid, n x (valueid , offset) 3989 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3990 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3991 unsigned FSModVTableRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 3992 3993 // Abbrev for FS_ALIAS. 3994 Abbv = std::make_shared<BitCodeAbbrev>(); 3995 Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS)); 3996 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 3997 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 3998 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 3999 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4000 4001 // Abbrev for FS_TYPE_ID_METADATA 4002 Abbv = std::make_shared<BitCodeAbbrev>(); 4003 Abbv->Add(BitCodeAbbrevOp(bitc::FS_TYPE_ID_METADATA)); 4004 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid strtab index 4005 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid length 4006 // n x (valueid , offset) 4007 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 4008 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 4009 unsigned TypeIdCompatibleVtableAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4010 4011 SmallVector<uint64_t, 64> NameVals; 4012 // Iterate over the list of functions instead of the Index to 4013 // ensure the ordering is stable. 4014 for (const Function &F : M) { 4015 // Summary emission does not support anonymous functions, they have to 4016 // renamed using the anonymous function renaming pass. 4017 if (!F.hasName()) 4018 report_fatal_error("Unexpected anonymous function when writing summary"); 4019 4020 ValueInfo VI = Index->getValueInfo(F.getGUID()); 4021 if (!VI || VI.getSummaryList().empty()) { 4022 // Only declarations should not have a summary (a declaration might 4023 // however have a summary if the def was in module level asm). 4024 assert(F.isDeclaration()); 4025 continue; 4026 } 4027 auto *Summary = VI.getSummaryList()[0].get(); 4028 writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.getValueID(&F), 4029 FSCallsAbbrev, FSCallsProfileAbbrev, F); 4030 } 4031 4032 // Capture references from GlobalVariable initializers, which are outside 4033 // of a function scope. 4034 for (const GlobalVariable &G : M.globals()) 4035 writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev, 4036 FSModVTableRefsAbbrev); 4037 4038 for (const GlobalAlias &A : M.aliases()) { 4039 auto *Aliasee = A.getAliaseeObject(); 4040 if (!Aliasee->hasName()) 4041 // Nameless function don't have an entry in the summary, skip it. 4042 continue; 4043 auto AliasId = VE.getValueID(&A); 4044 auto AliaseeId = VE.getValueID(Aliasee); 4045 NameVals.push_back(AliasId); 4046 auto *Summary = Index->getGlobalValueSummary(A); 4047 AliasSummary *AS = cast<AliasSummary>(Summary); 4048 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags())); 4049 NameVals.push_back(AliaseeId); 4050 Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev); 4051 NameVals.clear(); 4052 } 4053 4054 for (auto &S : Index->typeIdCompatibleVtableMap()) { 4055 writeTypeIdCompatibleVtableSummaryRecord(NameVals, StrtabBuilder, S.first, 4056 S.second, VE); 4057 Stream.EmitRecord(bitc::FS_TYPE_ID_METADATA, NameVals, 4058 TypeIdCompatibleVtableAbbrev); 4059 NameVals.clear(); 4060 } 4061 4062 Stream.EmitRecord(bitc::FS_BLOCK_COUNT, 4063 ArrayRef<uint64_t>{Index->getBlockCount()}); 4064 4065 Stream.ExitBlock(); 4066 } 4067 4068 /// Emit the combined summary section into the combined index file. 4069 void IndexBitcodeWriter::writeCombinedGlobalValueSummary() { 4070 Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3); 4071 Stream.EmitRecord( 4072 bitc::FS_VERSION, 4073 ArrayRef<uint64_t>{ModuleSummaryIndex::BitcodeSummaryVersion}); 4074 4075 // Write the index flags. 4076 Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Index.getFlags()}); 4077 4078 for (const auto &GVI : valueIds()) { 4079 Stream.EmitRecord(bitc::FS_VALUE_GUID, 4080 ArrayRef<uint64_t>{GVI.second, GVI.first}); 4081 } 4082 4083 // Abbrev for FS_COMBINED. 4084 auto Abbv = std::make_shared<BitCodeAbbrev>(); 4085 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED)); 4086 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 4087 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid 4088 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 4089 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount 4090 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags 4091 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // entrycount 4092 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs 4093 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt 4094 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt 4095 // numrefs x valueid, n x (valueid) 4096 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 4097 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 4098 unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4099 4100 // Abbrev for FS_COMBINED_PROFILE. 4101 Abbv = std::make_shared<BitCodeAbbrev>(); 4102 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE)); 4103 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 4104 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid 4105 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 4106 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount 4107 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags 4108 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // entrycount 4109 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs 4110 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt 4111 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt 4112 // numrefs x valueid, n x (valueid, hotness) 4113 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 4114 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 4115 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4116 4117 // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS. 4118 Abbv = std::make_shared<BitCodeAbbrev>(); 4119 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS)); 4120 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 4121 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid 4122 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 4123 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids 4124 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 4125 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4126 4127 // Abbrev for FS_COMBINED_ALIAS. 4128 Abbv = std::make_shared<BitCodeAbbrev>(); 4129 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS)); 4130 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 4131 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid 4132 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 4133 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 4134 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4135 4136 // The aliases are emitted as a post-pass, and will point to the value 4137 // id of the aliasee. Save them in a vector for post-processing. 4138 SmallVector<AliasSummary *, 64> Aliases; 4139 4140 // Save the value id for each summary for alias emission. 4141 DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap; 4142 4143 SmallVector<uint64_t, 64> NameVals; 4144 4145 // Set that will be populated during call to writeFunctionTypeMetadataRecords 4146 // with the type ids referenced by this index file. 4147 std::set<GlobalValue::GUID> ReferencedTypeIds; 4148 4149 // For local linkage, we also emit the original name separately 4150 // immediately after the record. 4151 auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) { 4152 // We don't need to emit the original name if we are writing the index for 4153 // distributed backends (in which case ModuleToSummariesForIndex is 4154 // non-null). The original name is only needed during the thin link, since 4155 // for SamplePGO the indirect call targets for local functions have 4156 // have the original name annotated in profile. 4157 // Continue to emit it when writing out the entire combined index, which is 4158 // used in testing the thin link via llvm-lto. 4159 if (ModuleToSummariesForIndex || !GlobalValue::isLocalLinkage(S.linkage())) 4160 return; 4161 NameVals.push_back(S.getOriginalName()); 4162 Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals); 4163 NameVals.clear(); 4164 }; 4165 4166 std::set<GlobalValue::GUID> DefOrUseGUIDs; 4167 forEachSummary([&](GVInfo I, bool IsAliasee) { 4168 GlobalValueSummary *S = I.second; 4169 assert(S); 4170 DefOrUseGUIDs.insert(I.first); 4171 for (const ValueInfo &VI : S->refs()) 4172 DefOrUseGUIDs.insert(VI.getGUID()); 4173 4174 auto ValueId = getValueId(I.first); 4175 assert(ValueId); 4176 SummaryToValueIdMap[S] = *ValueId; 4177 4178 // If this is invoked for an aliasee, we want to record the above 4179 // mapping, but then not emit a summary entry (if the aliasee is 4180 // to be imported, we will invoke this separately with IsAliasee=false). 4181 if (IsAliasee) 4182 return; 4183 4184 if (auto *AS = dyn_cast<AliasSummary>(S)) { 4185 // Will process aliases as a post-pass because the reader wants all 4186 // global to be loaded first. 4187 Aliases.push_back(AS); 4188 return; 4189 } 4190 4191 if (auto *VS = dyn_cast<GlobalVarSummary>(S)) { 4192 NameVals.push_back(*ValueId); 4193 NameVals.push_back(Index.getModuleId(VS->modulePath())); 4194 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags())); 4195 NameVals.push_back(getEncodedGVarFlags(VS->varflags())); 4196 for (auto &RI : VS->refs()) { 4197 auto RefValueId = getValueId(RI.getGUID()); 4198 if (!RefValueId) 4199 continue; 4200 NameVals.push_back(*RefValueId); 4201 } 4202 4203 // Emit the finished record. 4204 Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals, 4205 FSModRefsAbbrev); 4206 NameVals.clear(); 4207 MaybeEmitOriginalName(*S); 4208 return; 4209 } 4210 4211 auto GetValueId = [&](const ValueInfo &VI) -> Optional<unsigned> { 4212 return getValueId(VI.getGUID()); 4213 }; 4214 4215 auto *FS = cast<FunctionSummary>(S); 4216 writeFunctionTypeMetadataRecords(Stream, FS, GetValueId); 4217 getReferencedTypeIds(FS, ReferencedTypeIds); 4218 4219 NameVals.push_back(*ValueId); 4220 NameVals.push_back(Index.getModuleId(FS->modulePath())); 4221 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags())); 4222 NameVals.push_back(FS->instCount()); 4223 NameVals.push_back(getEncodedFFlags(FS->fflags())); 4224 NameVals.push_back(FS->entryCount()); 4225 4226 // Fill in below 4227 NameVals.push_back(0); // numrefs 4228 NameVals.push_back(0); // rorefcnt 4229 NameVals.push_back(0); // worefcnt 4230 4231 unsigned Count = 0, RORefCnt = 0, WORefCnt = 0; 4232 for (auto &RI : FS->refs()) { 4233 auto RefValueId = getValueId(RI.getGUID()); 4234 if (!RefValueId) 4235 continue; 4236 NameVals.push_back(*RefValueId); 4237 if (RI.isReadOnly()) 4238 RORefCnt++; 4239 else if (RI.isWriteOnly()) 4240 WORefCnt++; 4241 Count++; 4242 } 4243 NameVals[6] = Count; 4244 NameVals[7] = RORefCnt; 4245 NameVals[8] = WORefCnt; 4246 4247 bool HasProfileData = false; 4248 for (auto &EI : FS->calls()) { 4249 HasProfileData |= 4250 EI.second.getHotness() != CalleeInfo::HotnessType::Unknown; 4251 if (HasProfileData) 4252 break; 4253 } 4254 4255 for (auto &EI : FS->calls()) { 4256 // If this GUID doesn't have a value id, it doesn't have a function 4257 // summary and we don't need to record any calls to it. 4258 Optional<unsigned> CallValueId = GetValueId(EI.first); 4259 if (!CallValueId) 4260 continue; 4261 NameVals.push_back(*CallValueId); 4262 if (HasProfileData) 4263 NameVals.push_back(static_cast<uint8_t>(EI.second.Hotness)); 4264 } 4265 4266 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev); 4267 unsigned Code = 4268 (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED); 4269 4270 // Emit the finished record. 4271 Stream.EmitRecord(Code, NameVals, FSAbbrev); 4272 NameVals.clear(); 4273 MaybeEmitOriginalName(*S); 4274 }); 4275 4276 for (auto *AS : Aliases) { 4277 auto AliasValueId = SummaryToValueIdMap[AS]; 4278 assert(AliasValueId); 4279 NameVals.push_back(AliasValueId); 4280 NameVals.push_back(Index.getModuleId(AS->modulePath())); 4281 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags())); 4282 auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()]; 4283 assert(AliaseeValueId); 4284 NameVals.push_back(AliaseeValueId); 4285 4286 // Emit the finished record. 4287 Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev); 4288 NameVals.clear(); 4289 MaybeEmitOriginalName(*AS); 4290 4291 if (auto *FS = dyn_cast<FunctionSummary>(&AS->getAliasee())) 4292 getReferencedTypeIds(FS, ReferencedTypeIds); 4293 } 4294 4295 if (!Index.cfiFunctionDefs().empty()) { 4296 for (auto &S : Index.cfiFunctionDefs()) { 4297 if (DefOrUseGUIDs.count( 4298 GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(S)))) { 4299 NameVals.push_back(StrtabBuilder.add(S)); 4300 NameVals.push_back(S.size()); 4301 } 4302 } 4303 if (!NameVals.empty()) { 4304 Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DEFS, NameVals); 4305 NameVals.clear(); 4306 } 4307 } 4308 4309 if (!Index.cfiFunctionDecls().empty()) { 4310 for (auto &S : Index.cfiFunctionDecls()) { 4311 if (DefOrUseGUIDs.count( 4312 GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(S)))) { 4313 NameVals.push_back(StrtabBuilder.add(S)); 4314 NameVals.push_back(S.size()); 4315 } 4316 } 4317 if (!NameVals.empty()) { 4318 Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DECLS, NameVals); 4319 NameVals.clear(); 4320 } 4321 } 4322 4323 // Walk the GUIDs that were referenced, and write the 4324 // corresponding type id records. 4325 for (auto &T : ReferencedTypeIds) { 4326 auto TidIter = Index.typeIds().equal_range(T); 4327 for (auto It = TidIter.first; It != TidIter.second; ++It) { 4328 writeTypeIdSummaryRecord(NameVals, StrtabBuilder, It->second.first, 4329 It->second.second); 4330 Stream.EmitRecord(bitc::FS_TYPE_ID, NameVals); 4331 NameVals.clear(); 4332 } 4333 } 4334 4335 Stream.EmitRecord(bitc::FS_BLOCK_COUNT, 4336 ArrayRef<uint64_t>{Index.getBlockCount()}); 4337 4338 Stream.ExitBlock(); 4339 } 4340 4341 /// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the 4342 /// current llvm version, and a record for the epoch number. 4343 static void writeIdentificationBlock(BitstreamWriter &Stream) { 4344 Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5); 4345 4346 // Write the "user readable" string identifying the bitcode producer 4347 auto Abbv = std::make_shared<BitCodeAbbrev>(); 4348 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING)); 4349 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 4350 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 4351 auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4352 writeStringRecord(Stream, bitc::IDENTIFICATION_CODE_STRING, 4353 "LLVM" LLVM_VERSION_STRING, StringAbbrev); 4354 4355 // Write the epoch version 4356 Abbv = std::make_shared<BitCodeAbbrev>(); 4357 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH)); 4358 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 4359 auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4360 constexpr std::array<unsigned, 1> Vals = {{bitc::BITCODE_CURRENT_EPOCH}}; 4361 Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev); 4362 Stream.ExitBlock(); 4363 } 4364 4365 void ModuleBitcodeWriter::writeModuleHash(size_t BlockStartPos) { 4366 // Emit the module's hash. 4367 // MODULE_CODE_HASH: [5*i32] 4368 if (GenerateHash) { 4369 uint32_t Vals[5]; 4370 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&(Buffer)[BlockStartPos], 4371 Buffer.size() - BlockStartPos)); 4372 StringRef Hash = Hasher.result(); 4373 for (int Pos = 0; Pos < 20; Pos += 4) { 4374 Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos); 4375 } 4376 4377 // Emit the finished record. 4378 Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals); 4379 4380 if (ModHash) 4381 // Save the written hash value. 4382 llvm::copy(Vals, std::begin(*ModHash)); 4383 } 4384 } 4385 4386 void ModuleBitcodeWriter::write() { 4387 writeIdentificationBlock(Stream); 4388 4389 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3); 4390 size_t BlockStartPos = Buffer.size(); 4391 4392 writeModuleVersion(); 4393 4394 // Emit blockinfo, which defines the standard abbreviations etc. 4395 writeBlockInfo(); 4396 4397 // Emit information describing all of the types in the module. 4398 writeTypeTable(); 4399 4400 // Emit information about attribute groups. 4401 writeAttributeGroupTable(); 4402 4403 // Emit information about parameter attributes. 4404 writeAttributeTable(); 4405 4406 writeComdats(); 4407 4408 // Emit top-level description of module, including target triple, inline asm, 4409 // descriptors for global variables, and function prototype info. 4410 writeModuleInfo(); 4411 4412 // Emit constants. 4413 writeModuleConstants(); 4414 4415 // Emit metadata kind names. 4416 writeModuleMetadataKinds(); 4417 4418 // Emit metadata. 4419 writeModuleMetadata(); 4420 4421 // Emit module-level use-lists. 4422 if (VE.shouldPreserveUseListOrder()) 4423 writeUseListBlock(nullptr); 4424 4425 writeOperandBundleTags(); 4426 writeSyncScopeNames(); 4427 4428 // Emit function bodies. 4429 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex; 4430 for (const Function &F : M) 4431 if (!F.isDeclaration()) 4432 writeFunction(F, FunctionToBitcodeIndex); 4433 4434 // Need to write after the above call to WriteFunction which populates 4435 // the summary information in the index. 4436 if (Index) 4437 writePerModuleGlobalValueSummary(); 4438 4439 writeGlobalValueSymbolTable(FunctionToBitcodeIndex); 4440 4441 writeModuleHash(BlockStartPos); 4442 4443 Stream.ExitBlock(); 4444 } 4445 4446 static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer, 4447 uint32_t &Position) { 4448 support::endian::write32le(&Buffer[Position], Value); 4449 Position += 4; 4450 } 4451 4452 /// If generating a bc file on darwin, we have to emit a 4453 /// header and trailer to make it compatible with the system archiver. To do 4454 /// this we emit the following header, and then emit a trailer that pads the 4455 /// file out to be a multiple of 16 bytes. 4456 /// 4457 /// struct bc_header { 4458 /// uint32_t Magic; // 0x0B17C0DE 4459 /// uint32_t Version; // Version, currently always 0. 4460 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file. 4461 /// uint32_t BitcodeSize; // Size of traditional bitcode file. 4462 /// uint32_t CPUType; // CPU specifier. 4463 /// ... potentially more later ... 4464 /// }; 4465 static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer, 4466 const Triple &TT) { 4467 unsigned CPUType = ~0U; 4468 4469 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*, 4470 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic 4471 // number from /usr/include/mach/machine.h. It is ok to reproduce the 4472 // specific constants here because they are implicitly part of the Darwin ABI. 4473 enum { 4474 DARWIN_CPU_ARCH_ABI64 = 0x01000000, 4475 DARWIN_CPU_TYPE_X86 = 7, 4476 DARWIN_CPU_TYPE_ARM = 12, 4477 DARWIN_CPU_TYPE_POWERPC = 18 4478 }; 4479 4480 Triple::ArchType Arch = TT.getArch(); 4481 if (Arch == Triple::x86_64) 4482 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64; 4483 else if (Arch == Triple::x86) 4484 CPUType = DARWIN_CPU_TYPE_X86; 4485 else if (Arch == Triple::ppc) 4486 CPUType = DARWIN_CPU_TYPE_POWERPC; 4487 else if (Arch == Triple::ppc64) 4488 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64; 4489 else if (Arch == Triple::arm || Arch == Triple::thumb) 4490 CPUType = DARWIN_CPU_TYPE_ARM; 4491 4492 // Traditional Bitcode starts after header. 4493 assert(Buffer.size() >= BWH_HeaderSize && 4494 "Expected header size to be reserved"); 4495 unsigned BCOffset = BWH_HeaderSize; 4496 unsigned BCSize = Buffer.size() - BWH_HeaderSize; 4497 4498 // Write the magic and version. 4499 unsigned Position = 0; 4500 writeInt32ToBuffer(0x0B17C0DE, Buffer, Position); 4501 writeInt32ToBuffer(0, Buffer, Position); // Version. 4502 writeInt32ToBuffer(BCOffset, Buffer, Position); 4503 writeInt32ToBuffer(BCSize, Buffer, Position); 4504 writeInt32ToBuffer(CPUType, Buffer, Position); 4505 4506 // If the file is not a multiple of 16 bytes, insert dummy padding. 4507 while (Buffer.size() & 15) 4508 Buffer.push_back(0); 4509 } 4510 4511 /// Helper to write the header common to all bitcode files. 4512 static void writeBitcodeHeader(BitstreamWriter &Stream) { 4513 // Emit the file header. 4514 Stream.Emit((unsigned)'B', 8); 4515 Stream.Emit((unsigned)'C', 8); 4516 Stream.Emit(0x0, 4); 4517 Stream.Emit(0xC, 4); 4518 Stream.Emit(0xE, 4); 4519 Stream.Emit(0xD, 4); 4520 } 4521 4522 BitcodeWriter::BitcodeWriter(SmallVectorImpl<char> &Buffer, raw_fd_stream *FS) 4523 : Buffer(Buffer), Stream(new BitstreamWriter(Buffer, FS, FlushThreshold)) { 4524 writeBitcodeHeader(*Stream); 4525 } 4526 4527 BitcodeWriter::~BitcodeWriter() { assert(WroteStrtab); } 4528 4529 void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) { 4530 Stream->EnterSubblock(Block, 3); 4531 4532 auto Abbv = std::make_shared<BitCodeAbbrev>(); 4533 Abbv->Add(BitCodeAbbrevOp(Record)); 4534 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 4535 auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv)); 4536 4537 Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob); 4538 4539 Stream->ExitBlock(); 4540 } 4541 4542 void BitcodeWriter::writeSymtab() { 4543 assert(!WroteStrtab && !WroteSymtab); 4544 4545 // If any module has module-level inline asm, we will require a registered asm 4546 // parser for the target so that we can create an accurate symbol table for 4547 // the module. 4548 for (Module *M : Mods) { 4549 if (M->getModuleInlineAsm().empty()) 4550 continue; 4551 4552 std::string Err; 4553 const Triple TT(M->getTargetTriple()); 4554 const Target *T = TargetRegistry::lookupTarget(TT.str(), Err); 4555 if (!T || !T->hasMCAsmParser()) 4556 return; 4557 } 4558 4559 WroteSymtab = true; 4560 SmallVector<char, 0> Symtab; 4561 // The irsymtab::build function may be unable to create a symbol table if the 4562 // module is malformed (e.g. it contains an invalid alias). Writing a symbol 4563 // table is not required for correctness, but we still want to be able to 4564 // write malformed modules to bitcode files, so swallow the error. 4565 if (Error E = irsymtab::build(Mods, Symtab, StrtabBuilder, Alloc)) { 4566 consumeError(std::move(E)); 4567 return; 4568 } 4569 4570 writeBlob(bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB, 4571 {Symtab.data(), Symtab.size()}); 4572 } 4573 4574 void BitcodeWriter::writeStrtab() { 4575 assert(!WroteStrtab); 4576 4577 std::vector<char> Strtab; 4578 StrtabBuilder.finalizeInOrder(); 4579 Strtab.resize(StrtabBuilder.getSize()); 4580 StrtabBuilder.write((uint8_t *)Strtab.data()); 4581 4582 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, 4583 {Strtab.data(), Strtab.size()}); 4584 4585 WroteStrtab = true; 4586 } 4587 4588 void BitcodeWriter::copyStrtab(StringRef Strtab) { 4589 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab); 4590 WroteStrtab = true; 4591 } 4592 4593 void BitcodeWriter::writeModule(const Module &M, 4594 bool ShouldPreserveUseListOrder, 4595 const ModuleSummaryIndex *Index, 4596 bool GenerateHash, ModuleHash *ModHash) { 4597 assert(!WroteStrtab); 4598 4599 // The Mods vector is used by irsymtab::build, which requires non-const 4600 // Modules in case it needs to materialize metadata. But the bitcode writer 4601 // requires that the module is materialized, so we can cast to non-const here, 4602 // after checking that it is in fact materialized. 4603 assert(M.isMaterialized()); 4604 Mods.push_back(const_cast<Module *>(&M)); 4605 4606 ModuleBitcodeWriter ModuleWriter(M, Buffer, StrtabBuilder, *Stream, 4607 ShouldPreserveUseListOrder, Index, 4608 GenerateHash, ModHash); 4609 ModuleWriter.write(); 4610 } 4611 4612 void BitcodeWriter::writeIndex( 4613 const ModuleSummaryIndex *Index, 4614 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) { 4615 IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index, 4616 ModuleToSummariesForIndex); 4617 IndexWriter.write(); 4618 } 4619 4620 /// Write the specified module to the specified output stream. 4621 void llvm::WriteBitcodeToFile(const Module &M, raw_ostream &Out, 4622 bool ShouldPreserveUseListOrder, 4623 const ModuleSummaryIndex *Index, 4624 bool GenerateHash, ModuleHash *ModHash) { 4625 SmallVector<char, 0> Buffer; 4626 Buffer.reserve(256*1024); 4627 4628 // If this is darwin or another generic macho target, reserve space for the 4629 // header. 4630 Triple TT(M.getTargetTriple()); 4631 if (TT.isOSDarwin() || TT.isOSBinFormatMachO()) 4632 Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0); 4633 4634 BitcodeWriter Writer(Buffer, dyn_cast<raw_fd_stream>(&Out)); 4635 Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash, 4636 ModHash); 4637 Writer.writeSymtab(); 4638 Writer.writeStrtab(); 4639 4640 if (TT.isOSDarwin() || TT.isOSBinFormatMachO()) 4641 emitDarwinBCHeaderAndTrailer(Buffer, TT); 4642 4643 // Write the generated bitstream to "Out". 4644 if (!Buffer.empty()) 4645 Out.write((char *)&Buffer.front(), Buffer.size()); 4646 } 4647 4648 void IndexBitcodeWriter::write() { 4649 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3); 4650 4651 writeModuleVersion(); 4652 4653 // Write the module paths in the combined index. 4654 writeModStrings(); 4655 4656 // Write the summary combined index records. 4657 writeCombinedGlobalValueSummary(); 4658 4659 Stream.ExitBlock(); 4660 } 4661 4662 // Write the specified module summary index to the given raw output stream, 4663 // where it will be written in a new bitcode block. This is used when 4664 // writing the combined index file for ThinLTO. When writing a subset of the 4665 // index for a distributed backend, provide a \p ModuleToSummariesForIndex map. 4666 void llvm::WriteIndexToFile( 4667 const ModuleSummaryIndex &Index, raw_ostream &Out, 4668 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) { 4669 SmallVector<char, 0> Buffer; 4670 Buffer.reserve(256 * 1024); 4671 4672 BitcodeWriter Writer(Buffer); 4673 Writer.writeIndex(&Index, ModuleToSummariesForIndex); 4674 Writer.writeStrtab(); 4675 4676 Out.write((char *)&Buffer.front(), Buffer.size()); 4677 } 4678 4679 namespace { 4680 4681 /// Class to manage the bitcode writing for a thin link bitcode file. 4682 class ThinLinkBitcodeWriter : public ModuleBitcodeWriterBase { 4683 /// ModHash is for use in ThinLTO incremental build, generated while writing 4684 /// the module bitcode file. 4685 const ModuleHash *ModHash; 4686 4687 public: 4688 ThinLinkBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder, 4689 BitstreamWriter &Stream, 4690 const ModuleSummaryIndex &Index, 4691 const ModuleHash &ModHash) 4692 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream, 4693 /*ShouldPreserveUseListOrder=*/false, &Index), 4694 ModHash(&ModHash) {} 4695 4696 void write(); 4697 4698 private: 4699 void writeSimplifiedModuleInfo(); 4700 }; 4701 4702 } // end anonymous namespace 4703 4704 // This function writes a simpilified module info for thin link bitcode file. 4705 // It only contains the source file name along with the name(the offset and 4706 // size in strtab) and linkage for global values. For the global value info 4707 // entry, in order to keep linkage at offset 5, there are three zeros used 4708 // as padding. 4709 void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() { 4710 SmallVector<unsigned, 64> Vals; 4711 // Emit the module's source file name. 4712 { 4713 StringEncoding Bits = getStringEncoding(M.getSourceFileName()); 4714 BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8); 4715 if (Bits == SE_Char6) 4716 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6); 4717 else if (Bits == SE_Fixed7) 4718 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7); 4719 4720 // MODULE_CODE_SOURCE_FILENAME: [namechar x N] 4721 auto Abbv = std::make_shared<BitCodeAbbrev>(); 4722 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME)); 4723 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 4724 Abbv->Add(AbbrevOpToUse); 4725 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4726 4727 for (const auto P : M.getSourceFileName()) 4728 Vals.push_back((unsigned char)P); 4729 4730 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev); 4731 Vals.clear(); 4732 } 4733 4734 // Emit the global variable information. 4735 for (const GlobalVariable &GV : M.globals()) { 4736 // GLOBALVAR: [strtab offset, strtab size, 0, 0, 0, linkage] 4737 Vals.push_back(StrtabBuilder.add(GV.getName())); 4738 Vals.push_back(GV.getName().size()); 4739 Vals.push_back(0); 4740 Vals.push_back(0); 4741 Vals.push_back(0); 4742 Vals.push_back(getEncodedLinkage(GV)); 4743 4744 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals); 4745 Vals.clear(); 4746 } 4747 4748 // Emit the function proto information. 4749 for (const Function &F : M) { 4750 // FUNCTION: [strtab offset, strtab size, 0, 0, 0, linkage] 4751 Vals.push_back(StrtabBuilder.add(F.getName())); 4752 Vals.push_back(F.getName().size()); 4753 Vals.push_back(0); 4754 Vals.push_back(0); 4755 Vals.push_back(0); 4756 Vals.push_back(getEncodedLinkage(F)); 4757 4758 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals); 4759 Vals.clear(); 4760 } 4761 4762 // Emit the alias information. 4763 for (const GlobalAlias &A : M.aliases()) { 4764 // ALIAS: [strtab offset, strtab size, 0, 0, 0, linkage] 4765 Vals.push_back(StrtabBuilder.add(A.getName())); 4766 Vals.push_back(A.getName().size()); 4767 Vals.push_back(0); 4768 Vals.push_back(0); 4769 Vals.push_back(0); 4770 Vals.push_back(getEncodedLinkage(A)); 4771 4772 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals); 4773 Vals.clear(); 4774 } 4775 4776 // Emit the ifunc information. 4777 for (const GlobalIFunc &I : M.ifuncs()) { 4778 // IFUNC: [strtab offset, strtab size, 0, 0, 0, linkage] 4779 Vals.push_back(StrtabBuilder.add(I.getName())); 4780 Vals.push_back(I.getName().size()); 4781 Vals.push_back(0); 4782 Vals.push_back(0); 4783 Vals.push_back(0); 4784 Vals.push_back(getEncodedLinkage(I)); 4785 4786 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals); 4787 Vals.clear(); 4788 } 4789 } 4790 4791 void ThinLinkBitcodeWriter::write() { 4792 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3); 4793 4794 writeModuleVersion(); 4795 4796 writeSimplifiedModuleInfo(); 4797 4798 writePerModuleGlobalValueSummary(); 4799 4800 // Write module hash. 4801 Stream.EmitRecord(bitc::MODULE_CODE_HASH, ArrayRef<uint32_t>(*ModHash)); 4802 4803 Stream.ExitBlock(); 4804 } 4805 4806 void BitcodeWriter::writeThinLinkBitcode(const Module &M, 4807 const ModuleSummaryIndex &Index, 4808 const ModuleHash &ModHash) { 4809 assert(!WroteStrtab); 4810 4811 // The Mods vector is used by irsymtab::build, which requires non-const 4812 // Modules in case it needs to materialize metadata. But the bitcode writer 4813 // requires that the module is materialized, so we can cast to non-const here, 4814 // after checking that it is in fact materialized. 4815 assert(M.isMaterialized()); 4816 Mods.push_back(const_cast<Module *>(&M)); 4817 4818 ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index, 4819 ModHash); 4820 ThinLinkWriter.write(); 4821 } 4822 4823 // Write the specified thin link bitcode file to the given raw output stream, 4824 // where it will be written in a new bitcode block. This is used when 4825 // writing the per-module index file for ThinLTO. 4826 void llvm::WriteThinLinkBitcodeToFile(const Module &M, raw_ostream &Out, 4827 const ModuleSummaryIndex &Index, 4828 const ModuleHash &ModHash) { 4829 SmallVector<char, 0> Buffer; 4830 Buffer.reserve(256 * 1024); 4831 4832 BitcodeWriter Writer(Buffer); 4833 Writer.writeThinLinkBitcode(M, Index, ModHash); 4834 Writer.writeSymtab(); 4835 Writer.writeStrtab(); 4836 4837 Out.write((char *)&Buffer.front(), Buffer.size()); 4838 } 4839 4840 static const char *getSectionNameForBitcode(const Triple &T) { 4841 switch (T.getObjectFormat()) { 4842 case Triple::MachO: 4843 return "__LLVM,__bitcode"; 4844 case Triple::COFF: 4845 case Triple::ELF: 4846 case Triple::Wasm: 4847 case Triple::UnknownObjectFormat: 4848 return ".llvmbc"; 4849 case Triple::GOFF: 4850 llvm_unreachable("GOFF is not yet implemented"); 4851 break; 4852 case Triple::XCOFF: 4853 llvm_unreachable("XCOFF is not yet implemented"); 4854 break; 4855 } 4856 llvm_unreachable("Unimplemented ObjectFormatType"); 4857 } 4858 4859 static const char *getSectionNameForCommandline(const Triple &T) { 4860 switch (T.getObjectFormat()) { 4861 case Triple::MachO: 4862 return "__LLVM,__cmdline"; 4863 case Triple::COFF: 4864 case Triple::ELF: 4865 case Triple::Wasm: 4866 case Triple::UnknownObjectFormat: 4867 return ".llvmcmd"; 4868 case Triple::GOFF: 4869 llvm_unreachable("GOFF is not yet implemented"); 4870 break; 4871 case Triple::XCOFF: 4872 llvm_unreachable("XCOFF is not yet implemented"); 4873 break; 4874 } 4875 llvm_unreachable("Unimplemented ObjectFormatType"); 4876 } 4877 4878 void llvm::EmbedBitcodeInModule(llvm::Module &M, llvm::MemoryBufferRef Buf, 4879 bool EmbedBitcode, bool EmbedCmdline, 4880 const std::vector<uint8_t> &CmdArgs) { 4881 // Save llvm.compiler.used and remove it. 4882 SmallVector<Constant *, 2> UsedArray; 4883 SmallVector<GlobalValue *, 4> UsedGlobals; 4884 Type *UsedElementType = Type::getInt8Ty(M.getContext())->getPointerTo(0); 4885 GlobalVariable *Used = collectUsedGlobalVariables(M, UsedGlobals, true); 4886 for (auto *GV : UsedGlobals) { 4887 if (GV->getName() != "llvm.embedded.module" && 4888 GV->getName() != "llvm.cmdline") 4889 UsedArray.push_back( 4890 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType)); 4891 } 4892 if (Used) 4893 Used->eraseFromParent(); 4894 4895 // Embed the bitcode for the llvm module. 4896 std::string Data; 4897 ArrayRef<uint8_t> ModuleData; 4898 Triple T(M.getTargetTriple()); 4899 4900 if (EmbedBitcode) { 4901 if (Buf.getBufferSize() == 0 || 4902 !isBitcode((const unsigned char *)Buf.getBufferStart(), 4903 (const unsigned char *)Buf.getBufferEnd())) { 4904 // If the input is LLVM Assembly, bitcode is produced by serializing 4905 // the module. Use-lists order need to be preserved in this case. 4906 llvm::raw_string_ostream OS(Data); 4907 llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true); 4908 ModuleData = 4909 ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size()); 4910 } else 4911 // If the input is LLVM bitcode, write the input byte stream directly. 4912 ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(), 4913 Buf.getBufferSize()); 4914 } 4915 llvm::Constant *ModuleConstant = 4916 llvm::ConstantDataArray::get(M.getContext(), ModuleData); 4917 llvm::GlobalVariable *GV = new llvm::GlobalVariable( 4918 M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage, 4919 ModuleConstant); 4920 GV->setSection(getSectionNameForBitcode(T)); 4921 // Set alignment to 1 to prevent padding between two contributions from input 4922 // sections after linking. 4923 GV->setAlignment(Align(1)); 4924 UsedArray.push_back( 4925 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType)); 4926 if (llvm::GlobalVariable *Old = 4927 M.getGlobalVariable("llvm.embedded.module", true)) { 4928 assert(Old->hasOneUse() && 4929 "llvm.embedded.module can only be used once in llvm.compiler.used"); 4930 GV->takeName(Old); 4931 Old->eraseFromParent(); 4932 } else { 4933 GV->setName("llvm.embedded.module"); 4934 } 4935 4936 // Skip if only bitcode needs to be embedded. 4937 if (EmbedCmdline) { 4938 // Embed command-line options. 4939 ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CmdArgs.data()), 4940 CmdArgs.size()); 4941 llvm::Constant *CmdConstant = 4942 llvm::ConstantDataArray::get(M.getContext(), CmdData); 4943 GV = new llvm::GlobalVariable(M, CmdConstant->getType(), true, 4944 llvm::GlobalValue::PrivateLinkage, 4945 CmdConstant); 4946 GV->setSection(getSectionNameForCommandline(T)); 4947 GV->setAlignment(Align(1)); 4948 UsedArray.push_back( 4949 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType)); 4950 if (llvm::GlobalVariable *Old = M.getGlobalVariable("llvm.cmdline", true)) { 4951 assert(Old->hasOneUse() && 4952 "llvm.cmdline can only be used once in llvm.compiler.used"); 4953 GV->takeName(Old); 4954 Old->eraseFromParent(); 4955 } else { 4956 GV->setName("llvm.cmdline"); 4957 } 4958 } 4959 4960 if (UsedArray.empty()) 4961 return; 4962 4963 // Recreate llvm.compiler.used. 4964 ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size()); 4965 auto *NewUsed = new GlobalVariable( 4966 M, ATy, false, llvm::GlobalValue::AppendingLinkage, 4967 llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used"); 4968 NewUsed->setSection("llvm.metadata"); 4969 } 4970