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