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