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