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 writeModuleMetadataKinds(); 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 static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) { 1000 switch (GV.getUnnamedAddr()) { 1001 case GlobalValue::UnnamedAddr::None: return 0; 1002 case GlobalValue::UnnamedAddr::Local: return 2; 1003 case GlobalValue::UnnamedAddr::Global: return 1; 1004 } 1005 llvm_unreachable("Invalid unnamed_addr"); 1006 } 1007 1008 void ModuleBitcodeWriter::writeComdats() { 1009 SmallVector<unsigned, 64> Vals; 1010 for (const Comdat *C : VE.getComdats()) { 1011 // COMDAT: [selection_kind, name] 1012 Vals.push_back(getEncodedComdatSelectionKind(*C)); 1013 size_t Size = C->getName().size(); 1014 assert(isUInt<32>(Size)); 1015 Vals.push_back(Size); 1016 for (char Chr : C->getName()) 1017 Vals.push_back((unsigned char)Chr); 1018 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0); 1019 Vals.clear(); 1020 } 1021 } 1022 1023 /// Write a record that will eventually hold the word offset of the 1024 /// module-level VST. For now the offset is 0, which will be backpatched 1025 /// after the real VST is written. Saves the bit offset to backpatch. 1026 void BitcodeWriter::writeValueSymbolTableForwardDecl() { 1027 // Write a placeholder value in for the offset of the real VST, 1028 // which is written after the function blocks so that it can include 1029 // the offset of each function. The placeholder offset will be 1030 // updated when the real VST is written. 1031 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1032 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET)); 1033 // Blocks are 32-bit aligned, so we can use a 32-bit word offset to 1034 // hold the real VST offset. Must use fixed instead of VBR as we don't 1035 // know how many VBR chunks to reserve ahead of time. 1036 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 1037 unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(Abbv); 1038 1039 // Emit the placeholder 1040 uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0}; 1041 Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals); 1042 1043 // Compute and save the bit offset to the placeholder, which will be 1044 // patched when the real VST is written. We can simply subtract the 32-bit 1045 // fixed size from the current bit number to get the location to backpatch. 1046 VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32; 1047 } 1048 1049 enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 }; 1050 1051 /// Determine the encoding to use for the given string name and length. 1052 static StringEncoding getStringEncoding(const char *Str, unsigned StrLen) { 1053 bool isChar6 = true; 1054 for (const char *C = Str, *E = C + StrLen; C != E; ++C) { 1055 if (isChar6) 1056 isChar6 = BitCodeAbbrevOp::isChar6(*C); 1057 if ((unsigned char)*C & 128) 1058 // don't bother scanning the rest. 1059 return SE_Fixed8; 1060 } 1061 if (isChar6) 1062 return SE_Char6; 1063 else 1064 return SE_Fixed7; 1065 } 1066 1067 /// Emit top-level description of module, including target triple, inline asm, 1068 /// descriptors for global variables, and function prototype info. 1069 /// Returns the bit offset to backpatch with the location of the real VST. 1070 void ModuleBitcodeWriter::writeModuleInfo() { 1071 // Emit various pieces of data attached to a module. 1072 if (!M.getTargetTriple().empty()) 1073 writeStringRecord(bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(), 1074 0 /*TODO*/); 1075 const std::string &DL = M.getDataLayoutStr(); 1076 if (!DL.empty()) 1077 writeStringRecord(bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/); 1078 if (!M.getModuleInlineAsm().empty()) 1079 writeStringRecord(bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(), 1080 0 /*TODO*/); 1081 1082 // Emit information about sections and GC, computing how many there are. Also 1083 // compute the maximum alignment value. 1084 std::map<std::string, unsigned> SectionMap; 1085 std::map<std::string, unsigned> GCMap; 1086 unsigned MaxAlignment = 0; 1087 unsigned MaxGlobalType = 0; 1088 for (const GlobalValue &GV : M.globals()) { 1089 MaxAlignment = std::max(MaxAlignment, GV.getAlignment()); 1090 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType())); 1091 if (GV.hasSection()) { 1092 // Give section names unique ID's. 1093 unsigned &Entry = SectionMap[GV.getSection()]; 1094 if (!Entry) { 1095 writeStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV.getSection(), 1096 0 /*TODO*/); 1097 Entry = SectionMap.size(); 1098 } 1099 } 1100 } 1101 for (const Function &F : M) { 1102 MaxAlignment = std::max(MaxAlignment, F.getAlignment()); 1103 if (F.hasSection()) { 1104 // Give section names unique ID's. 1105 unsigned &Entry = SectionMap[F.getSection()]; 1106 if (!Entry) { 1107 writeStringRecord(bitc::MODULE_CODE_SECTIONNAME, F.getSection(), 1108 0 /*TODO*/); 1109 Entry = SectionMap.size(); 1110 } 1111 } 1112 if (F.hasGC()) { 1113 // Same for GC names. 1114 unsigned &Entry = GCMap[F.getGC()]; 1115 if (!Entry) { 1116 writeStringRecord(bitc::MODULE_CODE_GCNAME, F.getGC(), 0 /*TODO*/); 1117 Entry = GCMap.size(); 1118 } 1119 } 1120 } 1121 1122 // Emit abbrev for globals, now that we know # sections and max alignment. 1123 unsigned SimpleGVarAbbrev = 0; 1124 if (!M.global_empty()) { 1125 // Add an abbrev for common globals with no visibility or thread localness. 1126 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1127 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR)); 1128 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1129 Log2_32_Ceil(MaxGlobalType+1))); 1130 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2 1131 //| explicitType << 1 1132 //| constant 1133 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer. 1134 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage. 1135 if (MaxAlignment == 0) // Alignment. 1136 Abbv->Add(BitCodeAbbrevOp(0)); 1137 else { 1138 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1; 1139 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1140 Log2_32_Ceil(MaxEncAlignment+1))); 1141 } 1142 if (SectionMap.empty()) // Section. 1143 Abbv->Add(BitCodeAbbrevOp(0)); 1144 else 1145 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1146 Log2_32_Ceil(SectionMap.size()+1))); 1147 // Don't bother emitting vis + thread local. 1148 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv); 1149 } 1150 1151 // Emit the global variable information. 1152 SmallVector<unsigned, 64> Vals; 1153 for (const GlobalVariable &GV : M.globals()) { 1154 unsigned AbbrevToUse = 0; 1155 1156 // GLOBALVAR: [type, isconst, initid, 1157 // linkage, alignment, section, visibility, threadlocal, 1158 // unnamed_addr, externally_initialized, dllstorageclass, 1159 // comdat] 1160 Vals.push_back(VE.getTypeID(GV.getValueType())); 1161 Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant()); 1162 Vals.push_back(GV.isDeclaration() ? 0 : 1163 (VE.getValueID(GV.getInitializer()) + 1)); 1164 Vals.push_back(getEncodedLinkage(GV)); 1165 Vals.push_back(Log2_32(GV.getAlignment())+1); 1166 Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0); 1167 if (GV.isThreadLocal() || 1168 GV.getVisibility() != GlobalValue::DefaultVisibility || 1169 GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None || 1170 GV.isExternallyInitialized() || 1171 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass || 1172 GV.hasComdat()) { 1173 Vals.push_back(getEncodedVisibility(GV)); 1174 Vals.push_back(getEncodedThreadLocalMode(GV)); 1175 Vals.push_back(getEncodedUnnamedAddr(GV)); 1176 Vals.push_back(GV.isExternallyInitialized()); 1177 Vals.push_back(getEncodedDLLStorageClass(GV)); 1178 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0); 1179 } else { 1180 AbbrevToUse = SimpleGVarAbbrev; 1181 } 1182 1183 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse); 1184 Vals.clear(); 1185 } 1186 1187 // Emit the function proto information. 1188 for (const Function &F : M) { 1189 // FUNCTION: [type, callingconv, isproto, linkage, paramattrs, alignment, 1190 // section, visibility, gc, unnamed_addr, prologuedata, 1191 // dllstorageclass, comdat, prefixdata, personalityfn] 1192 Vals.push_back(VE.getTypeID(F.getFunctionType())); 1193 Vals.push_back(F.getCallingConv()); 1194 Vals.push_back(F.isDeclaration()); 1195 Vals.push_back(getEncodedLinkage(F)); 1196 Vals.push_back(VE.getAttributeID(F.getAttributes())); 1197 Vals.push_back(Log2_32(F.getAlignment())+1); 1198 Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0); 1199 Vals.push_back(getEncodedVisibility(F)); 1200 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0); 1201 Vals.push_back(getEncodedUnnamedAddr(F)); 1202 Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1) 1203 : 0); 1204 Vals.push_back(getEncodedDLLStorageClass(F)); 1205 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0); 1206 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1) 1207 : 0); 1208 Vals.push_back( 1209 F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0); 1210 1211 unsigned AbbrevToUse = 0; 1212 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse); 1213 Vals.clear(); 1214 } 1215 1216 // Emit the alias information. 1217 for (const GlobalAlias &A : M.aliases()) { 1218 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass, 1219 // threadlocal, unnamed_addr] 1220 Vals.push_back(VE.getTypeID(A.getValueType())); 1221 Vals.push_back(A.getType()->getAddressSpace()); 1222 Vals.push_back(VE.getValueID(A.getAliasee())); 1223 Vals.push_back(getEncodedLinkage(A)); 1224 Vals.push_back(getEncodedVisibility(A)); 1225 Vals.push_back(getEncodedDLLStorageClass(A)); 1226 Vals.push_back(getEncodedThreadLocalMode(A)); 1227 Vals.push_back(getEncodedUnnamedAddr(A)); 1228 unsigned AbbrevToUse = 0; 1229 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse); 1230 Vals.clear(); 1231 } 1232 1233 // Emit the ifunc information. 1234 for (const GlobalIFunc &I : M.ifuncs()) { 1235 // IFUNC: [ifunc type, address space, resolver val#, linkage, visibility] 1236 Vals.push_back(VE.getTypeID(I.getValueType())); 1237 Vals.push_back(I.getType()->getAddressSpace()); 1238 Vals.push_back(VE.getValueID(I.getResolver())); 1239 Vals.push_back(getEncodedLinkage(I)); 1240 Vals.push_back(getEncodedVisibility(I)); 1241 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals); 1242 Vals.clear(); 1243 } 1244 1245 // Emit the module's source file name. 1246 { 1247 StringEncoding Bits = getStringEncoding(M.getSourceFileName().data(), 1248 M.getSourceFileName().size()); 1249 BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8); 1250 if (Bits == SE_Char6) 1251 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6); 1252 else if (Bits == SE_Fixed7) 1253 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7); 1254 1255 // MODULE_CODE_SOURCE_FILENAME: [namechar x N] 1256 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1257 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME)); 1258 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1259 Abbv->Add(AbbrevOpToUse); 1260 unsigned FilenameAbbrev = Stream.EmitAbbrev(Abbv); 1261 1262 for (const auto P : M.getSourceFileName()) 1263 Vals.push_back((unsigned char)P); 1264 1265 // Emit the finished record. 1266 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev); 1267 Vals.clear(); 1268 } 1269 1270 // If we have a VST, write the VSTOFFSET record placeholder. 1271 if (M.getValueSymbolTable().empty()) 1272 return; 1273 writeValueSymbolTableForwardDecl(); 1274 } 1275 1276 static uint64_t getOptimizationFlags(const Value *V) { 1277 uint64_t Flags = 0; 1278 1279 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) { 1280 if (OBO->hasNoSignedWrap()) 1281 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP; 1282 if (OBO->hasNoUnsignedWrap()) 1283 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP; 1284 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) { 1285 if (PEO->isExact()) 1286 Flags |= 1 << bitc::PEO_EXACT; 1287 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) { 1288 if (FPMO->hasUnsafeAlgebra()) 1289 Flags |= FastMathFlags::UnsafeAlgebra; 1290 if (FPMO->hasNoNaNs()) 1291 Flags |= FastMathFlags::NoNaNs; 1292 if (FPMO->hasNoInfs()) 1293 Flags |= FastMathFlags::NoInfs; 1294 if (FPMO->hasNoSignedZeros()) 1295 Flags |= FastMathFlags::NoSignedZeros; 1296 if (FPMO->hasAllowReciprocal()) 1297 Flags |= FastMathFlags::AllowReciprocal; 1298 } 1299 1300 return Flags; 1301 } 1302 1303 void ModuleBitcodeWriter::writeValueAsMetadata( 1304 const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) { 1305 // Mimic an MDNode with a value as one operand. 1306 Value *V = MD->getValue(); 1307 Record.push_back(VE.getTypeID(V->getType())); 1308 Record.push_back(VE.getValueID(V)); 1309 Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0); 1310 Record.clear(); 1311 } 1312 1313 void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N, 1314 SmallVectorImpl<uint64_t> &Record, 1315 unsigned Abbrev) { 1316 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 1317 Metadata *MD = N->getOperand(i); 1318 assert(!(MD && isa<LocalAsMetadata>(MD)) && 1319 "Unexpected function-local metadata"); 1320 Record.push_back(VE.getMetadataOrNullID(MD)); 1321 } 1322 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE 1323 : bitc::METADATA_NODE, 1324 Record, Abbrev); 1325 Record.clear(); 1326 } 1327 1328 unsigned ModuleBitcodeWriter::createDILocationAbbrev() { 1329 // Assume the column is usually under 128, and always output the inlined-at 1330 // location (it's never more expensive than building an array size 1). 1331 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1332 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION)); 1333 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); 1334 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1335 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 1336 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1337 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1338 return Stream.EmitAbbrev(Abbv); 1339 } 1340 1341 void ModuleBitcodeWriter::writeDILocation(const DILocation *N, 1342 SmallVectorImpl<uint64_t> &Record, 1343 unsigned &Abbrev) { 1344 if (!Abbrev) 1345 Abbrev = createDILocationAbbrev(); 1346 1347 Record.push_back(N->isDistinct()); 1348 Record.push_back(N->getLine()); 1349 Record.push_back(N->getColumn()); 1350 Record.push_back(VE.getMetadataID(N->getScope())); 1351 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt())); 1352 1353 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev); 1354 Record.clear(); 1355 } 1356 1357 unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() { 1358 // Assume the column is usually under 128, and always output the inlined-at 1359 // location (it's never more expensive than building an array size 1). 1360 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1361 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG)); 1362 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); 1363 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1364 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); 1365 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1366 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1367 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1368 return Stream.EmitAbbrev(Abbv); 1369 } 1370 1371 void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N, 1372 SmallVectorImpl<uint64_t> &Record, 1373 unsigned &Abbrev) { 1374 if (!Abbrev) 1375 Abbrev = createGenericDINodeAbbrev(); 1376 1377 Record.push_back(N->isDistinct()); 1378 Record.push_back(N->getTag()); 1379 Record.push_back(0); // Per-tag version field; unused for now. 1380 1381 for (auto &I : N->operands()) 1382 Record.push_back(VE.getMetadataOrNullID(I)); 1383 1384 Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev); 1385 Record.clear(); 1386 } 1387 1388 static uint64_t rotateSign(int64_t I) { 1389 uint64_t U = I; 1390 return I < 0 ? ~(U << 1) : U << 1; 1391 } 1392 1393 void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N, 1394 SmallVectorImpl<uint64_t> &Record, 1395 unsigned Abbrev) { 1396 Record.push_back(N->isDistinct()); 1397 Record.push_back(N->getCount()); 1398 Record.push_back(rotateSign(N->getLowerBound())); 1399 1400 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev); 1401 Record.clear(); 1402 } 1403 1404 void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N, 1405 SmallVectorImpl<uint64_t> &Record, 1406 unsigned Abbrev) { 1407 Record.push_back(N->isDistinct()); 1408 Record.push_back(rotateSign(N->getValue())); 1409 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1410 1411 Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev); 1412 Record.clear(); 1413 } 1414 1415 void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N, 1416 SmallVectorImpl<uint64_t> &Record, 1417 unsigned Abbrev) { 1418 Record.push_back(N->isDistinct()); 1419 Record.push_back(N->getTag()); 1420 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1421 Record.push_back(N->getSizeInBits()); 1422 Record.push_back(N->getAlignInBits()); 1423 Record.push_back(N->getEncoding()); 1424 1425 Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev); 1426 Record.clear(); 1427 } 1428 1429 void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N, 1430 SmallVectorImpl<uint64_t> &Record, 1431 unsigned Abbrev) { 1432 Record.push_back(N->isDistinct()); 1433 Record.push_back(N->getTag()); 1434 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1435 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1436 Record.push_back(N->getLine()); 1437 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1438 Record.push_back(VE.getMetadataOrNullID(N->getBaseType())); 1439 Record.push_back(N->getSizeInBits()); 1440 Record.push_back(N->getAlignInBits()); 1441 Record.push_back(N->getOffsetInBits()); 1442 Record.push_back(N->getFlags()); 1443 Record.push_back(VE.getMetadataOrNullID(N->getExtraData())); 1444 1445 Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev); 1446 Record.clear(); 1447 } 1448 1449 void ModuleBitcodeWriter::writeDICompositeType( 1450 const DICompositeType *N, SmallVectorImpl<uint64_t> &Record, 1451 unsigned Abbrev) { 1452 const unsigned IsNotUsedInOldTypeRef = 0x2; 1453 Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct()); 1454 Record.push_back(N->getTag()); 1455 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1456 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1457 Record.push_back(N->getLine()); 1458 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1459 Record.push_back(VE.getMetadataOrNullID(N->getBaseType())); 1460 Record.push_back(N->getSizeInBits()); 1461 Record.push_back(N->getAlignInBits()); 1462 Record.push_back(N->getOffsetInBits()); 1463 Record.push_back(N->getFlags()); 1464 Record.push_back(VE.getMetadataOrNullID(N->getElements().get())); 1465 Record.push_back(N->getRuntimeLang()); 1466 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder())); 1467 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get())); 1468 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier())); 1469 1470 Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev); 1471 Record.clear(); 1472 } 1473 1474 void ModuleBitcodeWriter::writeDISubroutineType( 1475 const DISubroutineType *N, SmallVectorImpl<uint64_t> &Record, 1476 unsigned Abbrev) { 1477 const unsigned HasNoOldTypeRefs = 0x2; 1478 Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct()); 1479 Record.push_back(N->getFlags()); 1480 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get())); 1481 Record.push_back(N->getCC()); 1482 1483 Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev); 1484 Record.clear(); 1485 } 1486 1487 void ModuleBitcodeWriter::writeDIFile(const DIFile *N, 1488 SmallVectorImpl<uint64_t> &Record, 1489 unsigned Abbrev) { 1490 Record.push_back(N->isDistinct()); 1491 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename())); 1492 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory())); 1493 1494 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev); 1495 Record.clear(); 1496 } 1497 1498 void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N, 1499 SmallVectorImpl<uint64_t> &Record, 1500 unsigned Abbrev) { 1501 assert(N->isDistinct() && "Expected distinct compile units"); 1502 Record.push_back(/* IsDistinct */ true); 1503 Record.push_back(N->getSourceLanguage()); 1504 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1505 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer())); 1506 Record.push_back(N->isOptimized()); 1507 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags())); 1508 Record.push_back(N->getRuntimeVersion()); 1509 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename())); 1510 Record.push_back(N->getEmissionKind()); 1511 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get())); 1512 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get())); 1513 Record.push_back(/* subprograms */ 0); 1514 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get())); 1515 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get())); 1516 Record.push_back(N->getDWOId()); 1517 Record.push_back(VE.getMetadataOrNullID(N->getMacros().get())); 1518 1519 Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev); 1520 Record.clear(); 1521 } 1522 1523 void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N, 1524 SmallVectorImpl<uint64_t> &Record, 1525 unsigned Abbrev) { 1526 uint64_t HasUnitFlag = 1 << 1; 1527 Record.push_back(N->isDistinct() | HasUnitFlag); 1528 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1529 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1530 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName())); 1531 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1532 Record.push_back(N->getLine()); 1533 Record.push_back(VE.getMetadataOrNullID(N->getType())); 1534 Record.push_back(N->isLocalToUnit()); 1535 Record.push_back(N->isDefinition()); 1536 Record.push_back(N->getScopeLine()); 1537 Record.push_back(VE.getMetadataOrNullID(N->getContainingType())); 1538 Record.push_back(N->getVirtuality()); 1539 Record.push_back(N->getVirtualIndex()); 1540 Record.push_back(N->getFlags()); 1541 Record.push_back(N->isOptimized()); 1542 Record.push_back(VE.getMetadataOrNullID(N->getRawUnit())); 1543 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get())); 1544 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration())); 1545 Record.push_back(VE.getMetadataOrNullID(N->getVariables().get())); 1546 1547 Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev); 1548 Record.clear(); 1549 } 1550 1551 void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N, 1552 SmallVectorImpl<uint64_t> &Record, 1553 unsigned Abbrev) { 1554 Record.push_back(N->isDistinct()); 1555 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1556 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1557 Record.push_back(N->getLine()); 1558 Record.push_back(N->getColumn()); 1559 1560 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev); 1561 Record.clear(); 1562 } 1563 1564 void ModuleBitcodeWriter::writeDILexicalBlockFile( 1565 const DILexicalBlockFile *N, 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(N->getDiscriminator()); 1571 1572 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev); 1573 Record.clear(); 1574 } 1575 1576 void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N, 1577 SmallVectorImpl<uint64_t> &Record, 1578 unsigned Abbrev) { 1579 Record.push_back(N->isDistinct()); 1580 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1581 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1582 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1583 Record.push_back(N->getLine()); 1584 1585 Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev); 1586 Record.clear(); 1587 } 1588 1589 void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N, 1590 SmallVectorImpl<uint64_t> &Record, 1591 unsigned Abbrev) { 1592 Record.push_back(N->isDistinct()); 1593 Record.push_back(N->getMacinfoType()); 1594 Record.push_back(N->getLine()); 1595 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1596 Record.push_back(VE.getMetadataOrNullID(N->getRawValue())); 1597 1598 Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev); 1599 Record.clear(); 1600 } 1601 1602 void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N, 1603 SmallVectorImpl<uint64_t> &Record, 1604 unsigned Abbrev) { 1605 Record.push_back(N->isDistinct()); 1606 Record.push_back(N->getMacinfoType()); 1607 Record.push_back(N->getLine()); 1608 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1609 Record.push_back(VE.getMetadataOrNullID(N->getElements().get())); 1610 1611 Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev); 1612 Record.clear(); 1613 } 1614 1615 void ModuleBitcodeWriter::writeDIModule(const DIModule *N, 1616 SmallVectorImpl<uint64_t> &Record, 1617 unsigned Abbrev) { 1618 Record.push_back(N->isDistinct()); 1619 for (auto &I : N->operands()) 1620 Record.push_back(VE.getMetadataOrNullID(I)); 1621 1622 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev); 1623 Record.clear(); 1624 } 1625 1626 void ModuleBitcodeWriter::writeDITemplateTypeParameter( 1627 const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record, 1628 unsigned Abbrev) { 1629 Record.push_back(N->isDistinct()); 1630 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1631 Record.push_back(VE.getMetadataOrNullID(N->getType())); 1632 1633 Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev); 1634 Record.clear(); 1635 } 1636 1637 void ModuleBitcodeWriter::writeDITemplateValueParameter( 1638 const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record, 1639 unsigned Abbrev) { 1640 Record.push_back(N->isDistinct()); 1641 Record.push_back(N->getTag()); 1642 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1643 Record.push_back(VE.getMetadataOrNullID(N->getType())); 1644 Record.push_back(VE.getMetadataOrNullID(N->getValue())); 1645 1646 Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev); 1647 Record.clear(); 1648 } 1649 1650 void ModuleBitcodeWriter::writeDIGlobalVariable( 1651 const DIGlobalVariable *N, SmallVectorImpl<uint64_t> &Record, 1652 unsigned Abbrev) { 1653 Record.push_back(N->isDistinct()); 1654 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1655 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1656 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName())); 1657 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1658 Record.push_back(N->getLine()); 1659 Record.push_back(VE.getMetadataOrNullID(N->getType())); 1660 Record.push_back(N->isLocalToUnit()); 1661 Record.push_back(N->isDefinition()); 1662 Record.push_back(VE.getMetadataOrNullID(N->getRawVariable())); 1663 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration())); 1664 1665 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev); 1666 Record.clear(); 1667 } 1668 1669 void ModuleBitcodeWriter::writeDILocalVariable( 1670 const DILocalVariable *N, SmallVectorImpl<uint64_t> &Record, 1671 unsigned Abbrev) { 1672 Record.push_back(N->isDistinct()); 1673 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1674 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1675 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1676 Record.push_back(N->getLine()); 1677 Record.push_back(VE.getMetadataOrNullID(N->getType())); 1678 Record.push_back(N->getArg()); 1679 Record.push_back(N->getFlags()); 1680 1681 Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev); 1682 Record.clear(); 1683 } 1684 1685 void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N, 1686 SmallVectorImpl<uint64_t> &Record, 1687 unsigned Abbrev) { 1688 Record.reserve(N->getElements().size() + 1); 1689 1690 Record.push_back(N->isDistinct()); 1691 Record.append(N->elements_begin(), N->elements_end()); 1692 1693 Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev); 1694 Record.clear(); 1695 } 1696 1697 void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N, 1698 SmallVectorImpl<uint64_t> &Record, 1699 unsigned Abbrev) { 1700 Record.push_back(N->isDistinct()); 1701 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1702 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1703 Record.push_back(N->getLine()); 1704 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName())); 1705 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName())); 1706 Record.push_back(N->getAttributes()); 1707 Record.push_back(VE.getMetadataOrNullID(N->getType())); 1708 1709 Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev); 1710 Record.clear(); 1711 } 1712 1713 void ModuleBitcodeWriter::writeDIImportedEntity( 1714 const DIImportedEntity *N, SmallVectorImpl<uint64_t> &Record, 1715 unsigned Abbrev) { 1716 Record.push_back(N->isDistinct()); 1717 Record.push_back(N->getTag()); 1718 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1719 Record.push_back(VE.getMetadataOrNullID(N->getEntity())); 1720 Record.push_back(N->getLine()); 1721 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1722 1723 Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev); 1724 Record.clear(); 1725 } 1726 1727 unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() { 1728 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1729 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME)); 1730 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1731 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 1732 return Stream.EmitAbbrev(Abbv); 1733 } 1734 1735 void ModuleBitcodeWriter::writeNamedMetadata( 1736 SmallVectorImpl<uint64_t> &Record) { 1737 if (M.named_metadata_empty()) 1738 return; 1739 1740 unsigned Abbrev = createNamedMetadataAbbrev(); 1741 for (const NamedMDNode &NMD : M.named_metadata()) { 1742 // Write name. 1743 StringRef Str = NMD.getName(); 1744 Record.append(Str.bytes_begin(), Str.bytes_end()); 1745 Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev); 1746 Record.clear(); 1747 1748 // Write named metadata operands. 1749 for (const MDNode *N : NMD.operands()) 1750 Record.push_back(VE.getMetadataID(N)); 1751 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0); 1752 Record.clear(); 1753 } 1754 } 1755 1756 unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() { 1757 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1758 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS)); 1759 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings 1760 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars 1761 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 1762 return Stream.EmitAbbrev(Abbv); 1763 } 1764 1765 /// Write out a record for MDString. 1766 /// 1767 /// All the metadata strings in a metadata block are emitted in a single 1768 /// record. The sizes and strings themselves are shoved into a blob. 1769 void ModuleBitcodeWriter::writeMetadataStrings( 1770 ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) { 1771 if (Strings.empty()) 1772 return; 1773 1774 // Start the record with the number of strings. 1775 Record.push_back(bitc::METADATA_STRINGS); 1776 Record.push_back(Strings.size()); 1777 1778 // Emit the sizes of the strings in the blob. 1779 SmallString<256> Blob; 1780 { 1781 BitstreamWriter W(Blob); 1782 for (const Metadata *MD : Strings) 1783 W.EmitVBR(cast<MDString>(MD)->getLength(), 6); 1784 W.FlushToWord(); 1785 } 1786 1787 // Add the offset to the strings to the record. 1788 Record.push_back(Blob.size()); 1789 1790 // Add the strings to the blob. 1791 for (const Metadata *MD : Strings) 1792 Blob.append(cast<MDString>(MD)->getString()); 1793 1794 // Emit the final record. 1795 Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob); 1796 Record.clear(); 1797 } 1798 1799 void ModuleBitcodeWriter::writeMetadataRecords( 1800 ArrayRef<const Metadata *> MDs, SmallVectorImpl<uint64_t> &Record) { 1801 if (MDs.empty()) 1802 return; 1803 1804 // Initialize MDNode abbreviations. 1805 #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0; 1806 #include "llvm/IR/Metadata.def" 1807 1808 for (const Metadata *MD : MDs) { 1809 if (const MDNode *N = dyn_cast<MDNode>(MD)) { 1810 assert(N->isResolved() && "Expected forward references to be resolved"); 1811 1812 switch (N->getMetadataID()) { 1813 default: 1814 llvm_unreachable("Invalid MDNode subclass"); 1815 #define HANDLE_MDNODE_LEAF(CLASS) \ 1816 case Metadata::CLASS##Kind: \ 1817 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \ 1818 continue; 1819 #include "llvm/IR/Metadata.def" 1820 } 1821 } 1822 writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record); 1823 } 1824 } 1825 1826 void ModuleBitcodeWriter::writeModuleMetadata() { 1827 if (!VE.hasMDs() && M.named_metadata_empty()) 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 writeNamedMetadata(Record); 1835 1836 auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) { 1837 SmallVector<uint64_t, 4> Record; 1838 Record.push_back(VE.getValueID(&GO)); 1839 pushGlobalMetadataAttachment(Record, GO); 1840 Stream.EmitRecord(bitc::METADATA_GLOBAL_DECL_ATTACHMENT, Record); 1841 }; 1842 for (const Function &F : M) 1843 if (F.isDeclaration() && F.hasMetadata()) 1844 AddDeclAttachedMetadata(F); 1845 // FIXME: Only store metadata for declarations here, and move data for global 1846 // variable definitions to a separate block (PR28134). 1847 for (const GlobalVariable &GV : M.globals()) 1848 if (GV.hasMetadata()) 1849 AddDeclAttachedMetadata(GV); 1850 1851 Stream.ExitBlock(); 1852 } 1853 1854 void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) { 1855 if (!VE.hasMDs()) 1856 return; 1857 1858 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3); 1859 SmallVector<uint64_t, 64> Record; 1860 writeMetadataStrings(VE.getMDStrings(), Record); 1861 writeMetadataRecords(VE.getNonMDStrings(), Record); 1862 Stream.ExitBlock(); 1863 } 1864 1865 void ModuleBitcodeWriter::pushGlobalMetadataAttachment( 1866 SmallVectorImpl<uint64_t> &Record, const GlobalObject &GO) { 1867 // [n x [id, mdnode]] 1868 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 1869 GO.getAllMetadata(MDs); 1870 for (const auto &I : MDs) { 1871 Record.push_back(I.first); 1872 Record.push_back(VE.getMetadataID(I.second)); 1873 } 1874 } 1875 1876 void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) { 1877 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3); 1878 1879 SmallVector<uint64_t, 64> Record; 1880 1881 if (F.hasMetadata()) { 1882 pushGlobalMetadataAttachment(Record, F); 1883 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0); 1884 Record.clear(); 1885 } 1886 1887 // Write metadata attachments 1888 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]] 1889 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 1890 for (const BasicBlock &BB : F) 1891 for (const Instruction &I : BB) { 1892 MDs.clear(); 1893 I.getAllMetadataOtherThanDebugLoc(MDs); 1894 1895 // If no metadata, ignore instruction. 1896 if (MDs.empty()) continue; 1897 1898 Record.push_back(VE.getInstructionID(&I)); 1899 1900 for (unsigned i = 0, e = MDs.size(); i != e; ++i) { 1901 Record.push_back(MDs[i].first); 1902 Record.push_back(VE.getMetadataID(MDs[i].second)); 1903 } 1904 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0); 1905 Record.clear(); 1906 } 1907 1908 Stream.ExitBlock(); 1909 } 1910 1911 void ModuleBitcodeWriter::writeModuleMetadataKinds() { 1912 SmallVector<uint64_t, 64> Record; 1913 1914 // Write metadata kinds 1915 // METADATA_KIND - [n x [id, name]] 1916 SmallVector<StringRef, 8> Names; 1917 M.getMDKindNames(Names); 1918 1919 if (Names.empty()) return; 1920 1921 Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3); 1922 1923 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) { 1924 Record.push_back(MDKindID); 1925 StringRef KName = Names[MDKindID]; 1926 Record.append(KName.begin(), KName.end()); 1927 1928 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0); 1929 Record.clear(); 1930 } 1931 1932 Stream.ExitBlock(); 1933 } 1934 1935 void ModuleBitcodeWriter::writeOperandBundleTags() { 1936 // Write metadata kinds 1937 // 1938 // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG 1939 // 1940 // OPERAND_BUNDLE_TAG - [strchr x N] 1941 1942 SmallVector<StringRef, 8> Tags; 1943 M.getOperandBundleTags(Tags); 1944 1945 if (Tags.empty()) 1946 return; 1947 1948 Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3); 1949 1950 SmallVector<uint64_t, 64> Record; 1951 1952 for (auto Tag : Tags) { 1953 Record.append(Tag.begin(), Tag.end()); 1954 1955 Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0); 1956 Record.clear(); 1957 } 1958 1959 Stream.ExitBlock(); 1960 } 1961 1962 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) { 1963 if ((int64_t)V >= 0) 1964 Vals.push_back(V << 1); 1965 else 1966 Vals.push_back((-V << 1) | 1); 1967 } 1968 1969 void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal, 1970 bool isGlobal) { 1971 if (FirstVal == LastVal) return; 1972 1973 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4); 1974 1975 unsigned AggregateAbbrev = 0; 1976 unsigned String8Abbrev = 0; 1977 unsigned CString7Abbrev = 0; 1978 unsigned CString6Abbrev = 0; 1979 // If this is a constant pool for the module, emit module-specific abbrevs. 1980 if (isGlobal) { 1981 // Abbrev for CST_CODE_AGGREGATE. 1982 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1983 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE)); 1984 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1985 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1))); 1986 AggregateAbbrev = Stream.EmitAbbrev(Abbv); 1987 1988 // Abbrev for CST_CODE_STRING. 1989 Abbv = new BitCodeAbbrev(); 1990 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING)); 1991 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1992 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 1993 String8Abbrev = Stream.EmitAbbrev(Abbv); 1994 // Abbrev for CST_CODE_CSTRING. 1995 Abbv = new BitCodeAbbrev(); 1996 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING)); 1997 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1998 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); 1999 CString7Abbrev = Stream.EmitAbbrev(Abbv); 2000 // Abbrev for CST_CODE_CSTRING. 2001 Abbv = new BitCodeAbbrev(); 2002 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING)); 2003 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2004 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 2005 CString6Abbrev = Stream.EmitAbbrev(Abbv); 2006 } 2007 2008 SmallVector<uint64_t, 64> Record; 2009 2010 const ValueEnumerator::ValueList &Vals = VE.getValues(); 2011 Type *LastTy = nullptr; 2012 for (unsigned i = FirstVal; i != LastVal; ++i) { 2013 const Value *V = Vals[i].first; 2014 // If we need to switch types, do so now. 2015 if (V->getType() != LastTy) { 2016 LastTy = V->getType(); 2017 Record.push_back(VE.getTypeID(LastTy)); 2018 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record, 2019 CONSTANTS_SETTYPE_ABBREV); 2020 Record.clear(); 2021 } 2022 2023 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) { 2024 Record.push_back(unsigned(IA->hasSideEffects()) | 2025 unsigned(IA->isAlignStack()) << 1 | 2026 unsigned(IA->getDialect()&1) << 2); 2027 2028 // Add the asm string. 2029 const std::string &AsmStr = IA->getAsmString(); 2030 Record.push_back(AsmStr.size()); 2031 Record.append(AsmStr.begin(), AsmStr.end()); 2032 2033 // Add the constraint string. 2034 const std::string &ConstraintStr = IA->getConstraintString(); 2035 Record.push_back(ConstraintStr.size()); 2036 Record.append(ConstraintStr.begin(), ConstraintStr.end()); 2037 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record); 2038 Record.clear(); 2039 continue; 2040 } 2041 const Constant *C = cast<Constant>(V); 2042 unsigned Code = -1U; 2043 unsigned AbbrevToUse = 0; 2044 if (C->isNullValue()) { 2045 Code = bitc::CST_CODE_NULL; 2046 } else if (isa<UndefValue>(C)) { 2047 Code = bitc::CST_CODE_UNDEF; 2048 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) { 2049 if (IV->getBitWidth() <= 64) { 2050 uint64_t V = IV->getSExtValue(); 2051 emitSignedInt64(Record, V); 2052 Code = bitc::CST_CODE_INTEGER; 2053 AbbrevToUse = CONSTANTS_INTEGER_ABBREV; 2054 } else { // Wide integers, > 64 bits in size. 2055 // We have an arbitrary precision integer value to write whose 2056 // bit width is > 64. However, in canonical unsigned integer 2057 // format it is likely that the high bits are going to be zero. 2058 // So, we only write the number of active words. 2059 unsigned NWords = IV->getValue().getActiveWords(); 2060 const uint64_t *RawWords = IV->getValue().getRawData(); 2061 for (unsigned i = 0; i != NWords; ++i) { 2062 emitSignedInt64(Record, RawWords[i]); 2063 } 2064 Code = bitc::CST_CODE_WIDE_INTEGER; 2065 } 2066 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) { 2067 Code = bitc::CST_CODE_FLOAT; 2068 Type *Ty = CFP->getType(); 2069 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) { 2070 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue()); 2071 } else if (Ty->isX86_FP80Ty()) { 2072 // api needed to prevent premature destruction 2073 // bits are not in the same order as a normal i80 APInt, compensate. 2074 APInt api = CFP->getValueAPF().bitcastToAPInt(); 2075 const uint64_t *p = api.getRawData(); 2076 Record.push_back((p[1] << 48) | (p[0] >> 16)); 2077 Record.push_back(p[0] & 0xffffLL); 2078 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) { 2079 APInt api = CFP->getValueAPF().bitcastToAPInt(); 2080 const uint64_t *p = api.getRawData(); 2081 Record.push_back(p[0]); 2082 Record.push_back(p[1]); 2083 } else { 2084 assert (0 && "Unknown FP type!"); 2085 } 2086 } else if (isa<ConstantDataSequential>(C) && 2087 cast<ConstantDataSequential>(C)->isString()) { 2088 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C); 2089 // Emit constant strings specially. 2090 unsigned NumElts = Str->getNumElements(); 2091 // If this is a null-terminated string, use the denser CSTRING encoding. 2092 if (Str->isCString()) { 2093 Code = bitc::CST_CODE_CSTRING; 2094 --NumElts; // Don't encode the null, which isn't allowed by char6. 2095 } else { 2096 Code = bitc::CST_CODE_STRING; 2097 AbbrevToUse = String8Abbrev; 2098 } 2099 bool isCStr7 = Code == bitc::CST_CODE_CSTRING; 2100 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING; 2101 for (unsigned i = 0; i != NumElts; ++i) { 2102 unsigned char V = Str->getElementAsInteger(i); 2103 Record.push_back(V); 2104 isCStr7 &= (V & 128) == 0; 2105 if (isCStrChar6) 2106 isCStrChar6 = BitCodeAbbrevOp::isChar6(V); 2107 } 2108 2109 if (isCStrChar6) 2110 AbbrevToUse = CString6Abbrev; 2111 else if (isCStr7) 2112 AbbrevToUse = CString7Abbrev; 2113 } else if (const ConstantDataSequential *CDS = 2114 dyn_cast<ConstantDataSequential>(C)) { 2115 Code = bitc::CST_CODE_DATA; 2116 Type *EltTy = CDS->getType()->getElementType(); 2117 if (isa<IntegerType>(EltTy)) { 2118 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) 2119 Record.push_back(CDS->getElementAsInteger(i)); 2120 } else { 2121 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) 2122 Record.push_back( 2123 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue()); 2124 } 2125 } else if (isa<ConstantAggregate>(C)) { 2126 Code = bitc::CST_CODE_AGGREGATE; 2127 for (const Value *Op : C->operands()) 2128 Record.push_back(VE.getValueID(Op)); 2129 AbbrevToUse = AggregateAbbrev; 2130 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 2131 switch (CE->getOpcode()) { 2132 default: 2133 if (Instruction::isCast(CE->getOpcode())) { 2134 Code = bitc::CST_CODE_CE_CAST; 2135 Record.push_back(getEncodedCastOpcode(CE->getOpcode())); 2136 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 2137 Record.push_back(VE.getValueID(C->getOperand(0))); 2138 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev; 2139 } else { 2140 assert(CE->getNumOperands() == 2 && "Unknown constant expr!"); 2141 Code = bitc::CST_CODE_CE_BINOP; 2142 Record.push_back(getEncodedBinaryOpcode(CE->getOpcode())); 2143 Record.push_back(VE.getValueID(C->getOperand(0))); 2144 Record.push_back(VE.getValueID(C->getOperand(1))); 2145 uint64_t Flags = getOptimizationFlags(CE); 2146 if (Flags != 0) 2147 Record.push_back(Flags); 2148 } 2149 break; 2150 case Instruction::GetElementPtr: { 2151 Code = bitc::CST_CODE_CE_GEP; 2152 const auto *GO = cast<GEPOperator>(C); 2153 if (GO->isInBounds()) 2154 Code = bitc::CST_CODE_CE_INBOUNDS_GEP; 2155 Record.push_back(VE.getTypeID(GO->getSourceElementType())); 2156 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) { 2157 Record.push_back(VE.getTypeID(C->getOperand(i)->getType())); 2158 Record.push_back(VE.getValueID(C->getOperand(i))); 2159 } 2160 break; 2161 } 2162 case Instruction::Select: 2163 Code = bitc::CST_CODE_CE_SELECT; 2164 Record.push_back(VE.getValueID(C->getOperand(0))); 2165 Record.push_back(VE.getValueID(C->getOperand(1))); 2166 Record.push_back(VE.getValueID(C->getOperand(2))); 2167 break; 2168 case Instruction::ExtractElement: 2169 Code = bitc::CST_CODE_CE_EXTRACTELT; 2170 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 2171 Record.push_back(VE.getValueID(C->getOperand(0))); 2172 Record.push_back(VE.getTypeID(C->getOperand(1)->getType())); 2173 Record.push_back(VE.getValueID(C->getOperand(1))); 2174 break; 2175 case Instruction::InsertElement: 2176 Code = bitc::CST_CODE_CE_INSERTELT; 2177 Record.push_back(VE.getValueID(C->getOperand(0))); 2178 Record.push_back(VE.getValueID(C->getOperand(1))); 2179 Record.push_back(VE.getTypeID(C->getOperand(2)->getType())); 2180 Record.push_back(VE.getValueID(C->getOperand(2))); 2181 break; 2182 case Instruction::ShuffleVector: 2183 // If the return type and argument types are the same, this is a 2184 // standard shufflevector instruction. If the types are different, 2185 // then the shuffle is widening or truncating the input vectors, and 2186 // the argument type must also be encoded. 2187 if (C->getType() == C->getOperand(0)->getType()) { 2188 Code = bitc::CST_CODE_CE_SHUFFLEVEC; 2189 } else { 2190 Code = bitc::CST_CODE_CE_SHUFVEC_EX; 2191 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 2192 } 2193 Record.push_back(VE.getValueID(C->getOperand(0))); 2194 Record.push_back(VE.getValueID(C->getOperand(1))); 2195 Record.push_back(VE.getValueID(C->getOperand(2))); 2196 break; 2197 case Instruction::ICmp: 2198 case Instruction::FCmp: 2199 Code = bitc::CST_CODE_CE_CMP; 2200 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 2201 Record.push_back(VE.getValueID(C->getOperand(0))); 2202 Record.push_back(VE.getValueID(C->getOperand(1))); 2203 Record.push_back(CE->getPredicate()); 2204 break; 2205 } 2206 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) { 2207 Code = bitc::CST_CODE_BLOCKADDRESS; 2208 Record.push_back(VE.getTypeID(BA->getFunction()->getType())); 2209 Record.push_back(VE.getValueID(BA->getFunction())); 2210 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock())); 2211 } else { 2212 #ifndef NDEBUG 2213 C->dump(); 2214 #endif 2215 llvm_unreachable("Unknown constant!"); 2216 } 2217 Stream.EmitRecord(Code, Record, AbbrevToUse); 2218 Record.clear(); 2219 } 2220 2221 Stream.ExitBlock(); 2222 } 2223 2224 void ModuleBitcodeWriter::writeModuleConstants() { 2225 const ValueEnumerator::ValueList &Vals = VE.getValues(); 2226 2227 // Find the first constant to emit, which is the first non-globalvalue value. 2228 // We know globalvalues have been emitted by WriteModuleInfo. 2229 for (unsigned i = 0, e = Vals.size(); i != e; ++i) { 2230 if (!isa<GlobalValue>(Vals[i].first)) { 2231 writeConstants(i, Vals.size(), true); 2232 return; 2233 } 2234 } 2235 } 2236 2237 /// pushValueAndType - The file has to encode both the value and type id for 2238 /// many values, because we need to know what type to create for forward 2239 /// references. However, most operands are not forward references, so this type 2240 /// field is not needed. 2241 /// 2242 /// This function adds V's value ID to Vals. If the value ID is higher than the 2243 /// instruction ID, then it is a forward reference, and it also includes the 2244 /// type ID. The value ID that is written is encoded relative to the InstID. 2245 bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID, 2246 SmallVectorImpl<unsigned> &Vals) { 2247 unsigned ValID = VE.getValueID(V); 2248 // Make encoding relative to the InstID. 2249 Vals.push_back(InstID - ValID); 2250 if (ValID >= InstID) { 2251 Vals.push_back(VE.getTypeID(V->getType())); 2252 return true; 2253 } 2254 return false; 2255 } 2256 2257 void ModuleBitcodeWriter::writeOperandBundles(ImmutableCallSite CS, 2258 unsigned InstID) { 2259 SmallVector<unsigned, 64> Record; 2260 LLVMContext &C = CS.getInstruction()->getContext(); 2261 2262 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) { 2263 const auto &Bundle = CS.getOperandBundleAt(i); 2264 Record.push_back(C.getOperandBundleTagID(Bundle.getTagName())); 2265 2266 for (auto &Input : Bundle.Inputs) 2267 pushValueAndType(Input, InstID, Record); 2268 2269 Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record); 2270 Record.clear(); 2271 } 2272 } 2273 2274 /// pushValue - Like pushValueAndType, but where the type of the value is 2275 /// omitted (perhaps it was already encoded in an earlier operand). 2276 void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID, 2277 SmallVectorImpl<unsigned> &Vals) { 2278 unsigned ValID = VE.getValueID(V); 2279 Vals.push_back(InstID - ValID); 2280 } 2281 2282 void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID, 2283 SmallVectorImpl<uint64_t> &Vals) { 2284 unsigned ValID = VE.getValueID(V); 2285 int64_t diff = ((int32_t)InstID - (int32_t)ValID); 2286 emitSignedInt64(Vals, diff); 2287 } 2288 2289 /// WriteInstruction - Emit an instruction to the specified stream. 2290 void ModuleBitcodeWriter::writeInstruction(const Instruction &I, 2291 unsigned InstID, 2292 SmallVectorImpl<unsigned> &Vals) { 2293 unsigned Code = 0; 2294 unsigned AbbrevToUse = 0; 2295 VE.setInstructionID(&I); 2296 switch (I.getOpcode()) { 2297 default: 2298 if (Instruction::isCast(I.getOpcode())) { 2299 Code = bitc::FUNC_CODE_INST_CAST; 2300 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) 2301 AbbrevToUse = FUNCTION_INST_CAST_ABBREV; 2302 Vals.push_back(VE.getTypeID(I.getType())); 2303 Vals.push_back(getEncodedCastOpcode(I.getOpcode())); 2304 } else { 2305 assert(isa<BinaryOperator>(I) && "Unknown instruction!"); 2306 Code = bitc::FUNC_CODE_INST_BINOP; 2307 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) 2308 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV; 2309 pushValue(I.getOperand(1), InstID, Vals); 2310 Vals.push_back(getEncodedBinaryOpcode(I.getOpcode())); 2311 uint64_t Flags = getOptimizationFlags(&I); 2312 if (Flags != 0) { 2313 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV) 2314 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV; 2315 Vals.push_back(Flags); 2316 } 2317 } 2318 break; 2319 2320 case Instruction::GetElementPtr: { 2321 Code = bitc::FUNC_CODE_INST_GEP; 2322 AbbrevToUse = FUNCTION_INST_GEP_ABBREV; 2323 auto &GEPInst = cast<GetElementPtrInst>(I); 2324 Vals.push_back(GEPInst.isInBounds()); 2325 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType())); 2326 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) 2327 pushValueAndType(I.getOperand(i), InstID, Vals); 2328 break; 2329 } 2330 case Instruction::ExtractValue: { 2331 Code = bitc::FUNC_CODE_INST_EXTRACTVAL; 2332 pushValueAndType(I.getOperand(0), InstID, Vals); 2333 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I); 2334 Vals.append(EVI->idx_begin(), EVI->idx_end()); 2335 break; 2336 } 2337 case Instruction::InsertValue: { 2338 Code = bitc::FUNC_CODE_INST_INSERTVAL; 2339 pushValueAndType(I.getOperand(0), InstID, Vals); 2340 pushValueAndType(I.getOperand(1), InstID, Vals); 2341 const InsertValueInst *IVI = cast<InsertValueInst>(&I); 2342 Vals.append(IVI->idx_begin(), IVI->idx_end()); 2343 break; 2344 } 2345 case Instruction::Select: 2346 Code = bitc::FUNC_CODE_INST_VSELECT; 2347 pushValueAndType(I.getOperand(1), InstID, Vals); 2348 pushValue(I.getOperand(2), InstID, Vals); 2349 pushValueAndType(I.getOperand(0), InstID, Vals); 2350 break; 2351 case Instruction::ExtractElement: 2352 Code = bitc::FUNC_CODE_INST_EXTRACTELT; 2353 pushValueAndType(I.getOperand(0), InstID, Vals); 2354 pushValueAndType(I.getOperand(1), InstID, Vals); 2355 break; 2356 case Instruction::InsertElement: 2357 Code = bitc::FUNC_CODE_INST_INSERTELT; 2358 pushValueAndType(I.getOperand(0), InstID, Vals); 2359 pushValue(I.getOperand(1), InstID, Vals); 2360 pushValueAndType(I.getOperand(2), InstID, Vals); 2361 break; 2362 case Instruction::ShuffleVector: 2363 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC; 2364 pushValueAndType(I.getOperand(0), InstID, Vals); 2365 pushValue(I.getOperand(1), InstID, Vals); 2366 pushValue(I.getOperand(2), InstID, Vals); 2367 break; 2368 case Instruction::ICmp: 2369 case Instruction::FCmp: { 2370 // compare returning Int1Ty or vector of Int1Ty 2371 Code = bitc::FUNC_CODE_INST_CMP2; 2372 pushValueAndType(I.getOperand(0), InstID, Vals); 2373 pushValue(I.getOperand(1), InstID, Vals); 2374 Vals.push_back(cast<CmpInst>(I).getPredicate()); 2375 uint64_t Flags = getOptimizationFlags(&I); 2376 if (Flags != 0) 2377 Vals.push_back(Flags); 2378 break; 2379 } 2380 2381 case Instruction::Ret: 2382 { 2383 Code = bitc::FUNC_CODE_INST_RET; 2384 unsigned NumOperands = I.getNumOperands(); 2385 if (NumOperands == 0) 2386 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV; 2387 else if (NumOperands == 1) { 2388 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) 2389 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV; 2390 } else { 2391 for (unsigned i = 0, e = NumOperands; i != e; ++i) 2392 pushValueAndType(I.getOperand(i), InstID, Vals); 2393 } 2394 } 2395 break; 2396 case Instruction::Br: 2397 { 2398 Code = bitc::FUNC_CODE_INST_BR; 2399 const BranchInst &II = cast<BranchInst>(I); 2400 Vals.push_back(VE.getValueID(II.getSuccessor(0))); 2401 if (II.isConditional()) { 2402 Vals.push_back(VE.getValueID(II.getSuccessor(1))); 2403 pushValue(II.getCondition(), InstID, Vals); 2404 } 2405 } 2406 break; 2407 case Instruction::Switch: 2408 { 2409 Code = bitc::FUNC_CODE_INST_SWITCH; 2410 const SwitchInst &SI = cast<SwitchInst>(I); 2411 Vals.push_back(VE.getTypeID(SI.getCondition()->getType())); 2412 pushValue(SI.getCondition(), InstID, Vals); 2413 Vals.push_back(VE.getValueID(SI.getDefaultDest())); 2414 for (SwitchInst::ConstCaseIt Case : SI.cases()) { 2415 Vals.push_back(VE.getValueID(Case.getCaseValue())); 2416 Vals.push_back(VE.getValueID(Case.getCaseSuccessor())); 2417 } 2418 } 2419 break; 2420 case Instruction::IndirectBr: 2421 Code = bitc::FUNC_CODE_INST_INDIRECTBR; 2422 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); 2423 // Encode the address operand as relative, but not the basic blocks. 2424 pushValue(I.getOperand(0), InstID, Vals); 2425 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) 2426 Vals.push_back(VE.getValueID(I.getOperand(i))); 2427 break; 2428 2429 case Instruction::Invoke: { 2430 const InvokeInst *II = cast<InvokeInst>(&I); 2431 const Value *Callee = II->getCalledValue(); 2432 FunctionType *FTy = II->getFunctionType(); 2433 2434 if (II->hasOperandBundles()) 2435 writeOperandBundles(II, InstID); 2436 2437 Code = bitc::FUNC_CODE_INST_INVOKE; 2438 2439 Vals.push_back(VE.getAttributeID(II->getAttributes())); 2440 Vals.push_back(II->getCallingConv() | 1 << 13); 2441 Vals.push_back(VE.getValueID(II->getNormalDest())); 2442 Vals.push_back(VE.getValueID(II->getUnwindDest())); 2443 Vals.push_back(VE.getTypeID(FTy)); 2444 pushValueAndType(Callee, InstID, Vals); 2445 2446 // Emit value #'s for the fixed parameters. 2447 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) 2448 pushValue(I.getOperand(i), InstID, Vals); // fixed param. 2449 2450 // Emit type/value pairs for varargs params. 2451 if (FTy->isVarArg()) { 2452 for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3; 2453 i != e; ++i) 2454 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg 2455 } 2456 break; 2457 } 2458 case Instruction::Resume: 2459 Code = bitc::FUNC_CODE_INST_RESUME; 2460 pushValueAndType(I.getOperand(0), InstID, Vals); 2461 break; 2462 case Instruction::CleanupRet: { 2463 Code = bitc::FUNC_CODE_INST_CLEANUPRET; 2464 const auto &CRI = cast<CleanupReturnInst>(I); 2465 pushValue(CRI.getCleanupPad(), InstID, Vals); 2466 if (CRI.hasUnwindDest()) 2467 Vals.push_back(VE.getValueID(CRI.getUnwindDest())); 2468 break; 2469 } 2470 case Instruction::CatchRet: { 2471 Code = bitc::FUNC_CODE_INST_CATCHRET; 2472 const auto &CRI = cast<CatchReturnInst>(I); 2473 pushValue(CRI.getCatchPad(), InstID, Vals); 2474 Vals.push_back(VE.getValueID(CRI.getSuccessor())); 2475 break; 2476 } 2477 case Instruction::CleanupPad: 2478 case Instruction::CatchPad: { 2479 const auto &FuncletPad = cast<FuncletPadInst>(I); 2480 Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD 2481 : bitc::FUNC_CODE_INST_CLEANUPPAD; 2482 pushValue(FuncletPad.getParentPad(), InstID, Vals); 2483 2484 unsigned NumArgOperands = FuncletPad.getNumArgOperands(); 2485 Vals.push_back(NumArgOperands); 2486 for (unsigned Op = 0; Op != NumArgOperands; ++Op) 2487 pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals); 2488 break; 2489 } 2490 case Instruction::CatchSwitch: { 2491 Code = bitc::FUNC_CODE_INST_CATCHSWITCH; 2492 const auto &CatchSwitch = cast<CatchSwitchInst>(I); 2493 2494 pushValue(CatchSwitch.getParentPad(), InstID, Vals); 2495 2496 unsigned NumHandlers = CatchSwitch.getNumHandlers(); 2497 Vals.push_back(NumHandlers); 2498 for (const BasicBlock *CatchPadBB : CatchSwitch.handlers()) 2499 Vals.push_back(VE.getValueID(CatchPadBB)); 2500 2501 if (CatchSwitch.hasUnwindDest()) 2502 Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest())); 2503 break; 2504 } 2505 case Instruction::Unreachable: 2506 Code = bitc::FUNC_CODE_INST_UNREACHABLE; 2507 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV; 2508 break; 2509 2510 case Instruction::PHI: { 2511 const PHINode &PN = cast<PHINode>(I); 2512 Code = bitc::FUNC_CODE_INST_PHI; 2513 // With the newer instruction encoding, forward references could give 2514 // negative valued IDs. This is most common for PHIs, so we use 2515 // signed VBRs. 2516 SmallVector<uint64_t, 128> Vals64; 2517 Vals64.push_back(VE.getTypeID(PN.getType())); 2518 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) { 2519 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64); 2520 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i))); 2521 } 2522 // Emit a Vals64 vector and exit. 2523 Stream.EmitRecord(Code, Vals64, AbbrevToUse); 2524 Vals64.clear(); 2525 return; 2526 } 2527 2528 case Instruction::LandingPad: { 2529 const LandingPadInst &LP = cast<LandingPadInst>(I); 2530 Code = bitc::FUNC_CODE_INST_LANDINGPAD; 2531 Vals.push_back(VE.getTypeID(LP.getType())); 2532 Vals.push_back(LP.isCleanup()); 2533 Vals.push_back(LP.getNumClauses()); 2534 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) { 2535 if (LP.isCatch(I)) 2536 Vals.push_back(LandingPadInst::Catch); 2537 else 2538 Vals.push_back(LandingPadInst::Filter); 2539 pushValueAndType(LP.getClause(I), InstID, Vals); 2540 } 2541 break; 2542 } 2543 2544 case Instruction::Alloca: { 2545 Code = bitc::FUNC_CODE_INST_ALLOCA; 2546 const AllocaInst &AI = cast<AllocaInst>(I); 2547 Vals.push_back(VE.getTypeID(AI.getAllocatedType())); 2548 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); 2549 Vals.push_back(VE.getValueID(I.getOperand(0))); // size. 2550 unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1; 2551 assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 && 2552 "not enough bits for maximum alignment"); 2553 assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64"); 2554 AlignRecord |= AI.isUsedWithInAlloca() << 5; 2555 AlignRecord |= 1 << 6; 2556 AlignRecord |= AI.isSwiftError() << 7; 2557 Vals.push_back(AlignRecord); 2558 break; 2559 } 2560 2561 case Instruction::Load: 2562 if (cast<LoadInst>(I).isAtomic()) { 2563 Code = bitc::FUNC_CODE_INST_LOADATOMIC; 2564 pushValueAndType(I.getOperand(0), InstID, Vals); 2565 } else { 2566 Code = bitc::FUNC_CODE_INST_LOAD; 2567 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr 2568 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV; 2569 } 2570 Vals.push_back(VE.getTypeID(I.getType())); 2571 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1); 2572 Vals.push_back(cast<LoadInst>(I).isVolatile()); 2573 if (cast<LoadInst>(I).isAtomic()) { 2574 Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering())); 2575 Vals.push_back(getEncodedSynchScope(cast<LoadInst>(I).getSynchScope())); 2576 } 2577 break; 2578 case Instruction::Store: 2579 if (cast<StoreInst>(I).isAtomic()) 2580 Code = bitc::FUNC_CODE_INST_STOREATOMIC; 2581 else 2582 Code = bitc::FUNC_CODE_INST_STORE; 2583 pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr 2584 pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val 2585 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1); 2586 Vals.push_back(cast<StoreInst>(I).isVolatile()); 2587 if (cast<StoreInst>(I).isAtomic()) { 2588 Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering())); 2589 Vals.push_back(getEncodedSynchScope(cast<StoreInst>(I).getSynchScope())); 2590 } 2591 break; 2592 case Instruction::AtomicCmpXchg: 2593 Code = bitc::FUNC_CODE_INST_CMPXCHG; 2594 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr 2595 pushValueAndType(I.getOperand(1), InstID, Vals); // cmp. 2596 pushValue(I.getOperand(2), InstID, Vals); // newval. 2597 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile()); 2598 Vals.push_back( 2599 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering())); 2600 Vals.push_back( 2601 getEncodedSynchScope(cast<AtomicCmpXchgInst>(I).getSynchScope())); 2602 Vals.push_back( 2603 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering())); 2604 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak()); 2605 break; 2606 case Instruction::AtomicRMW: 2607 Code = bitc::FUNC_CODE_INST_ATOMICRMW; 2608 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr 2609 pushValue(I.getOperand(1), InstID, Vals); // val. 2610 Vals.push_back( 2611 getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation())); 2612 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile()); 2613 Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering())); 2614 Vals.push_back( 2615 getEncodedSynchScope(cast<AtomicRMWInst>(I).getSynchScope())); 2616 break; 2617 case Instruction::Fence: 2618 Code = bitc::FUNC_CODE_INST_FENCE; 2619 Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering())); 2620 Vals.push_back(getEncodedSynchScope(cast<FenceInst>(I).getSynchScope())); 2621 break; 2622 case Instruction::Call: { 2623 const CallInst &CI = cast<CallInst>(I); 2624 FunctionType *FTy = CI.getFunctionType(); 2625 2626 if (CI.hasOperandBundles()) 2627 writeOperandBundles(&CI, InstID); 2628 2629 Code = bitc::FUNC_CODE_INST_CALL; 2630 2631 Vals.push_back(VE.getAttributeID(CI.getAttributes())); 2632 2633 unsigned Flags = getOptimizationFlags(&I); 2634 Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV | 2635 unsigned(CI.isTailCall()) << bitc::CALL_TAIL | 2636 unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL | 2637 1 << bitc::CALL_EXPLICIT_TYPE | 2638 unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL | 2639 unsigned(Flags != 0) << bitc::CALL_FMF); 2640 if (Flags != 0) 2641 Vals.push_back(Flags); 2642 2643 Vals.push_back(VE.getTypeID(FTy)); 2644 pushValueAndType(CI.getCalledValue(), InstID, Vals); // Callee 2645 2646 // Emit value #'s for the fixed parameters. 2647 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) { 2648 // Check for labels (can happen with asm labels). 2649 if (FTy->getParamType(i)->isLabelTy()) 2650 Vals.push_back(VE.getValueID(CI.getArgOperand(i))); 2651 else 2652 pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param. 2653 } 2654 2655 // Emit type/value pairs for varargs params. 2656 if (FTy->isVarArg()) { 2657 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands(); 2658 i != e; ++i) 2659 pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs 2660 } 2661 break; 2662 } 2663 case Instruction::VAArg: 2664 Code = bitc::FUNC_CODE_INST_VAARG; 2665 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty 2666 pushValue(I.getOperand(0), InstID, Vals); // valist. 2667 Vals.push_back(VE.getTypeID(I.getType())); // restype. 2668 break; 2669 } 2670 2671 Stream.EmitRecord(Code, Vals, AbbrevToUse); 2672 Vals.clear(); 2673 } 2674 2675 /// Emit names for globals/functions etc. \p IsModuleLevel is true when 2676 /// we are writing the module-level VST, where we are including a function 2677 /// bitcode index and need to backpatch the VST forward declaration record. 2678 void ModuleBitcodeWriter::writeValueSymbolTable( 2679 const ValueSymbolTable &VST, bool IsModuleLevel, 2680 DenseMap<const Function *, uint64_t> *FunctionToBitcodeIndex) { 2681 if (VST.empty()) { 2682 // writeValueSymbolTableForwardDecl should have returned early as 2683 // well. Ensure this handling remains in sync by asserting that 2684 // the placeholder offset is not set. 2685 assert(!IsModuleLevel || !hasVSTOffsetPlaceholder()); 2686 return; 2687 } 2688 2689 if (IsModuleLevel && hasVSTOffsetPlaceholder()) { 2690 // Get the offset of the VST we are writing, and backpatch it into 2691 // the VST forward declaration record. 2692 uint64_t VSTOffset = Stream.GetCurrentBitNo(); 2693 // The BitcodeStartBit was the stream offset of the actual bitcode 2694 // (e.g. excluding any initial darwin header). 2695 VSTOffset -= bitcodeStartBit(); 2696 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned"); 2697 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32); 2698 } 2699 2700 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4); 2701 2702 // For the module-level VST, add abbrev Ids for the VST_CODE_FNENTRY 2703 // records, which are not used in the per-function VSTs. 2704 unsigned FnEntry8BitAbbrev; 2705 unsigned FnEntry7BitAbbrev; 2706 unsigned FnEntry6BitAbbrev; 2707 if (IsModuleLevel && hasVSTOffsetPlaceholder()) { 2708 // 8-bit fixed-width VST_CODE_FNENTRY function strings. 2709 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2710 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY)); 2711 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id 2712 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset 2713 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2714 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 2715 FnEntry8BitAbbrev = Stream.EmitAbbrev(Abbv); 2716 2717 // 7-bit fixed width VST_CODE_FNENTRY function strings. 2718 Abbv = new BitCodeAbbrev(); 2719 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY)); 2720 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id 2721 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset 2722 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2723 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); 2724 FnEntry7BitAbbrev = Stream.EmitAbbrev(Abbv); 2725 2726 // 6-bit char6 VST_CODE_FNENTRY function strings. 2727 Abbv = new BitCodeAbbrev(); 2728 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY)); 2729 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id 2730 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset 2731 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2732 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 2733 FnEntry6BitAbbrev = Stream.EmitAbbrev(Abbv); 2734 } 2735 2736 // FIXME: Set up the abbrev, we know how many values there are! 2737 // FIXME: We know if the type names can use 7-bit ascii. 2738 SmallVector<unsigned, 64> NameVals; 2739 2740 for (const ValueName &Name : VST) { 2741 // Figure out the encoding to use for the name. 2742 StringEncoding Bits = 2743 getStringEncoding(Name.getKeyData(), Name.getKeyLength()); 2744 2745 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV; 2746 NameVals.push_back(VE.getValueID(Name.getValue())); 2747 2748 Function *F = dyn_cast<Function>(Name.getValue()); 2749 if (!F) { 2750 // If value is an alias, need to get the aliased base object to 2751 // see if it is a function. 2752 auto *GA = dyn_cast<GlobalAlias>(Name.getValue()); 2753 if (GA && GA->getBaseObject()) 2754 F = dyn_cast<Function>(GA->getBaseObject()); 2755 } 2756 2757 // VST_CODE_ENTRY: [valueid, namechar x N] 2758 // VST_CODE_FNENTRY: [valueid, funcoffset, namechar x N] 2759 // VST_CODE_BBENTRY: [bbid, namechar x N] 2760 unsigned Code; 2761 if (isa<BasicBlock>(Name.getValue())) { 2762 Code = bitc::VST_CODE_BBENTRY; 2763 if (Bits == SE_Char6) 2764 AbbrevToUse = VST_BBENTRY_6_ABBREV; 2765 } else if (F && !F->isDeclaration()) { 2766 // Must be the module-level VST, where we pass in the Index and 2767 // have a VSTOffsetPlaceholder. The function-level VST should not 2768 // contain any Function symbols. 2769 assert(FunctionToBitcodeIndex); 2770 assert(hasVSTOffsetPlaceholder()); 2771 2772 // Save the word offset of the function (from the start of the 2773 // actual bitcode written to the stream). 2774 uint64_t BitcodeIndex = (*FunctionToBitcodeIndex)[F] - bitcodeStartBit(); 2775 assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned"); 2776 NameVals.push_back(BitcodeIndex / 32); 2777 2778 Code = bitc::VST_CODE_FNENTRY; 2779 AbbrevToUse = FnEntry8BitAbbrev; 2780 if (Bits == SE_Char6) 2781 AbbrevToUse = FnEntry6BitAbbrev; 2782 else if (Bits == SE_Fixed7) 2783 AbbrevToUse = FnEntry7BitAbbrev; 2784 } else { 2785 Code = bitc::VST_CODE_ENTRY; 2786 if (Bits == SE_Char6) 2787 AbbrevToUse = VST_ENTRY_6_ABBREV; 2788 else if (Bits == SE_Fixed7) 2789 AbbrevToUse = VST_ENTRY_7_ABBREV; 2790 } 2791 2792 for (const auto P : Name.getKey()) 2793 NameVals.push_back((unsigned char)P); 2794 2795 // Emit the finished record. 2796 Stream.EmitRecord(Code, NameVals, AbbrevToUse); 2797 NameVals.clear(); 2798 } 2799 Stream.ExitBlock(); 2800 } 2801 2802 /// Emit function names and summary offsets for the combined index 2803 /// used by ThinLTO. 2804 void IndexBitcodeWriter::writeCombinedValueSymbolTable() { 2805 assert(hasVSTOffsetPlaceholder() && "Expected non-zero VSTOffsetPlaceholder"); 2806 // Get the offset of the VST we are writing, and backpatch it into 2807 // the VST forward declaration record. 2808 uint64_t VSTOffset = Stream.GetCurrentBitNo(); 2809 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned"); 2810 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32); 2811 2812 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4); 2813 2814 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2815 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_COMBINED_ENTRY)); 2816 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 2817 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // refguid 2818 unsigned EntryAbbrev = Stream.EmitAbbrev(Abbv); 2819 2820 SmallVector<uint64_t, 64> NameVals; 2821 for (const auto &GVI : valueIds()) { 2822 // VST_CODE_COMBINED_ENTRY: [valueid, refguid] 2823 NameVals.push_back(GVI.second); 2824 NameVals.push_back(GVI.first); 2825 2826 // Emit the finished record. 2827 Stream.EmitRecord(bitc::VST_CODE_COMBINED_ENTRY, NameVals, EntryAbbrev); 2828 NameVals.clear(); 2829 } 2830 Stream.ExitBlock(); 2831 } 2832 2833 void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) { 2834 assert(Order.Shuffle.size() >= 2 && "Shuffle too small"); 2835 unsigned Code; 2836 if (isa<BasicBlock>(Order.V)) 2837 Code = bitc::USELIST_CODE_BB; 2838 else 2839 Code = bitc::USELIST_CODE_DEFAULT; 2840 2841 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end()); 2842 Record.push_back(VE.getValueID(Order.V)); 2843 Stream.EmitRecord(Code, Record); 2844 } 2845 2846 void ModuleBitcodeWriter::writeUseListBlock(const Function *F) { 2847 assert(VE.shouldPreserveUseListOrder() && 2848 "Expected to be preserving use-list order"); 2849 2850 auto hasMore = [&]() { 2851 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F; 2852 }; 2853 if (!hasMore()) 2854 // Nothing to do. 2855 return; 2856 2857 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3); 2858 while (hasMore()) { 2859 writeUseList(std::move(VE.UseListOrders.back())); 2860 VE.UseListOrders.pop_back(); 2861 } 2862 Stream.ExitBlock(); 2863 } 2864 2865 /// Emit a function body to the module stream. 2866 void ModuleBitcodeWriter::writeFunction( 2867 const Function &F, 2868 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) { 2869 // Save the bitcode index of the start of this function block for recording 2870 // in the VST. 2871 FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo(); 2872 2873 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4); 2874 VE.incorporateFunction(F); 2875 2876 SmallVector<unsigned, 64> Vals; 2877 2878 // Emit the number of basic blocks, so the reader can create them ahead of 2879 // time. 2880 Vals.push_back(VE.getBasicBlocks().size()); 2881 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals); 2882 Vals.clear(); 2883 2884 // If there are function-local constants, emit them now. 2885 unsigned CstStart, CstEnd; 2886 VE.getFunctionConstantRange(CstStart, CstEnd); 2887 writeConstants(CstStart, CstEnd, false); 2888 2889 // If there is function-local metadata, emit it now. 2890 writeFunctionMetadata(F); 2891 2892 // Keep a running idea of what the instruction ID is. 2893 unsigned InstID = CstEnd; 2894 2895 bool NeedsMetadataAttachment = F.hasMetadata(); 2896 2897 DILocation *LastDL = nullptr; 2898 // Finally, emit all the instructions, in order. 2899 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) 2900 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); 2901 I != E; ++I) { 2902 writeInstruction(*I, InstID, Vals); 2903 2904 if (!I->getType()->isVoidTy()) 2905 ++InstID; 2906 2907 // If the instruction has metadata, write a metadata attachment later. 2908 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc(); 2909 2910 // If the instruction has a debug location, emit it. 2911 DILocation *DL = I->getDebugLoc(); 2912 if (!DL) 2913 continue; 2914 2915 if (DL == LastDL) { 2916 // Just repeat the same debug loc as last time. 2917 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals); 2918 continue; 2919 } 2920 2921 Vals.push_back(DL->getLine()); 2922 Vals.push_back(DL->getColumn()); 2923 Vals.push_back(VE.getMetadataOrNullID(DL->getScope())); 2924 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt())); 2925 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals); 2926 Vals.clear(); 2927 2928 LastDL = DL; 2929 } 2930 2931 // Emit names for all the instructions etc. 2932 writeValueSymbolTable(F.getValueSymbolTable()); 2933 2934 if (NeedsMetadataAttachment) 2935 writeFunctionMetadataAttachment(F); 2936 if (VE.shouldPreserveUseListOrder()) 2937 writeUseListBlock(&F); 2938 VE.purgeFunction(); 2939 Stream.ExitBlock(); 2940 } 2941 2942 // Emit blockinfo, which defines the standard abbreviations etc. 2943 void ModuleBitcodeWriter::writeBlockInfo() { 2944 // We only want to emit block info records for blocks that have multiple 2945 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK. 2946 // Other blocks can define their abbrevs inline. 2947 Stream.EnterBlockInfoBlock(2); 2948 2949 { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings. 2950 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2951 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); 2952 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 2953 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2954 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 2955 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) != 2956 VST_ENTRY_8_ABBREV) 2957 llvm_unreachable("Unexpected abbrev ordering!"); 2958 } 2959 2960 { // 7-bit fixed width VST_CODE_ENTRY strings. 2961 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2962 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY)); 2963 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 2964 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2965 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); 2966 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) != 2967 VST_ENTRY_7_ABBREV) 2968 llvm_unreachable("Unexpected abbrev ordering!"); 2969 } 2970 { // 6-bit char6 VST_CODE_ENTRY strings. 2971 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2972 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY)); 2973 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 2974 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2975 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 2976 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) != 2977 VST_ENTRY_6_ABBREV) 2978 llvm_unreachable("Unexpected abbrev ordering!"); 2979 } 2980 { // 6-bit char6 VST_CODE_BBENTRY strings. 2981 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2982 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY)); 2983 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 2984 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2985 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 2986 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) != 2987 VST_BBENTRY_6_ABBREV) 2988 llvm_unreachable("Unexpected abbrev ordering!"); 2989 } 2990 2991 2992 2993 { // SETTYPE abbrev for CONSTANTS_BLOCK. 2994 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2995 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE)); 2996 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2997 VE.computeBitsRequiredForTypeIndicies())); 2998 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) != 2999 CONSTANTS_SETTYPE_ABBREV) 3000 llvm_unreachable("Unexpected abbrev ordering!"); 3001 } 3002 3003 { // INTEGER abbrev for CONSTANTS_BLOCK. 3004 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 3005 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER)); 3006 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3007 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) != 3008 CONSTANTS_INTEGER_ABBREV) 3009 llvm_unreachable("Unexpected abbrev ordering!"); 3010 } 3011 3012 { // CE_CAST abbrev for CONSTANTS_BLOCK. 3013 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 3014 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST)); 3015 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc 3016 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid 3017 VE.computeBitsRequiredForTypeIndicies())); 3018 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id 3019 3020 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) != 3021 CONSTANTS_CE_CAST_Abbrev) 3022 llvm_unreachable("Unexpected abbrev ordering!"); 3023 } 3024 { // NULL abbrev for CONSTANTS_BLOCK. 3025 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 3026 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL)); 3027 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) != 3028 CONSTANTS_NULL_Abbrev) 3029 llvm_unreachable("Unexpected abbrev ordering!"); 3030 } 3031 3032 // FIXME: This should only use space for first class types! 3033 3034 { // INST_LOAD abbrev for FUNCTION_BLOCK. 3035 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 3036 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD)); 3037 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr 3038 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty 3039 VE.computeBitsRequiredForTypeIndicies())); 3040 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align 3041 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile 3042 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3043 FUNCTION_INST_LOAD_ABBREV) 3044 llvm_unreachable("Unexpected abbrev ordering!"); 3045 } 3046 { // INST_BINOP abbrev for FUNCTION_BLOCK. 3047 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 3048 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP)); 3049 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS 3050 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS 3051 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 3052 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3053 FUNCTION_INST_BINOP_ABBREV) 3054 llvm_unreachable("Unexpected abbrev ordering!"); 3055 } 3056 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK. 3057 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 3058 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP)); 3059 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS 3060 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS 3061 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 3062 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags 3063 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3064 FUNCTION_INST_BINOP_FLAGS_ABBREV) 3065 llvm_unreachable("Unexpected abbrev ordering!"); 3066 } 3067 { // INST_CAST abbrev for FUNCTION_BLOCK. 3068 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 3069 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST)); 3070 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal 3071 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty 3072 VE.computeBitsRequiredForTypeIndicies())); 3073 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 3074 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3075 FUNCTION_INST_CAST_ABBREV) 3076 llvm_unreachable("Unexpected abbrev ordering!"); 3077 } 3078 3079 { // INST_RET abbrev for FUNCTION_BLOCK. 3080 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 3081 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET)); 3082 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3083 FUNCTION_INST_RET_VOID_ABBREV) 3084 llvm_unreachable("Unexpected abbrev ordering!"); 3085 } 3086 { // INST_RET abbrev for FUNCTION_BLOCK. 3087 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 3088 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET)); 3089 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID 3090 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3091 FUNCTION_INST_RET_VAL_ABBREV) 3092 llvm_unreachable("Unexpected abbrev ordering!"); 3093 } 3094 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK. 3095 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 3096 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE)); 3097 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3098 FUNCTION_INST_UNREACHABLE_ABBREV) 3099 llvm_unreachable("Unexpected abbrev ordering!"); 3100 } 3101 { 3102 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 3103 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP)); 3104 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); 3105 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty 3106 Log2_32_Ceil(VE.getTypes().size() + 1))); 3107 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3108 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 3109 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3110 FUNCTION_INST_GEP_ABBREV) 3111 llvm_unreachable("Unexpected abbrev ordering!"); 3112 } 3113 3114 Stream.ExitBlock(); 3115 } 3116 3117 /// Write the module path strings, currently only used when generating 3118 /// a combined index file. 3119 void IndexBitcodeWriter::writeModStrings() { 3120 Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3); 3121 3122 // TODO: See which abbrev sizes we actually need to emit 3123 3124 // 8-bit fixed-width MST_ENTRY strings. 3125 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 3126 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY)); 3127 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3128 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3129 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 3130 unsigned Abbrev8Bit = Stream.EmitAbbrev(Abbv); 3131 3132 // 7-bit fixed width MST_ENTRY strings. 3133 Abbv = new BitCodeAbbrev(); 3134 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY)); 3135 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3136 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3137 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); 3138 unsigned Abbrev7Bit = Stream.EmitAbbrev(Abbv); 3139 3140 // 6-bit char6 MST_ENTRY strings. 3141 Abbv = new BitCodeAbbrev(); 3142 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY)); 3143 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3144 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3145 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 3146 unsigned Abbrev6Bit = Stream.EmitAbbrev(Abbv); 3147 3148 // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY. 3149 Abbv = new BitCodeAbbrev(); 3150 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH)); 3151 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 3152 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 3153 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 3154 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 3155 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 3156 unsigned AbbrevHash = Stream.EmitAbbrev(Abbv); 3157 3158 SmallVector<unsigned, 64> Vals; 3159 for (const auto &MPSE : Index.modulePaths()) { 3160 if (!doIncludeModule(MPSE.getKey())) 3161 continue; 3162 StringEncoding Bits = 3163 getStringEncoding(MPSE.getKey().data(), MPSE.getKey().size()); 3164 unsigned AbbrevToUse = Abbrev8Bit; 3165 if (Bits == SE_Char6) 3166 AbbrevToUse = Abbrev6Bit; 3167 else if (Bits == SE_Fixed7) 3168 AbbrevToUse = Abbrev7Bit; 3169 3170 Vals.push_back(MPSE.getValue().first); 3171 3172 for (const auto P : MPSE.getKey()) 3173 Vals.push_back((unsigned char)P); 3174 3175 // Emit the finished record. 3176 Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse); 3177 3178 Vals.clear(); 3179 // Emit an optional hash for the module now 3180 auto &Hash = MPSE.getValue().second; 3181 bool AllZero = true; // Detect if the hash is empty, and do not generate it 3182 for (auto Val : Hash) { 3183 if (Val) 3184 AllZero = false; 3185 Vals.push_back(Val); 3186 } 3187 if (!AllZero) { 3188 // Emit the hash record. 3189 Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash); 3190 } 3191 3192 Vals.clear(); 3193 } 3194 Stream.ExitBlock(); 3195 } 3196 3197 // Helper to emit a single function summary record. 3198 void ModuleBitcodeWriter::writePerModuleFunctionSummaryRecord( 3199 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary, 3200 unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev, 3201 const Function &F) { 3202 NameVals.push_back(ValueID); 3203 3204 FunctionSummary *FS = cast<FunctionSummary>(Summary); 3205 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags())); 3206 NameVals.push_back(FS->instCount()); 3207 NameVals.push_back(FS->refs().size()); 3208 3209 unsigned SizeBeforeRefs = NameVals.size(); 3210 for (auto &RI : FS->refs()) 3211 NameVals.push_back(VE.getValueID(RI.getValue())); 3212 // Sort the refs for determinism output, the vector returned by FS->refs() has 3213 // been initialized from a DenseSet. 3214 std::sort(NameVals.begin() + SizeBeforeRefs, NameVals.end()); 3215 3216 std::vector<FunctionSummary::EdgeTy> Calls = FS->calls(); 3217 std::sort(Calls.begin(), Calls.end(), 3218 [this](const FunctionSummary::EdgeTy &L, 3219 const FunctionSummary::EdgeTy &R) { 3220 return VE.getValueID(L.first.getValue()) < 3221 VE.getValueID(R.first.getValue()); 3222 }); 3223 bool HasProfileData = F.getEntryCount().hasValue(); 3224 for (auto &ECI : Calls) { 3225 NameVals.push_back(VE.getValueID(ECI.first.getValue())); 3226 assert(ECI.second.CallsiteCount > 0 && "Expected at least one callsite"); 3227 NameVals.push_back(ECI.second.CallsiteCount); 3228 if (HasProfileData) 3229 NameVals.push_back(ECI.second.ProfileCount); 3230 } 3231 3232 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev); 3233 unsigned Code = 3234 (HasProfileData ? bitc::FS_PERMODULE_PROFILE : bitc::FS_PERMODULE); 3235 3236 // Emit the finished record. 3237 Stream.EmitRecord(Code, NameVals, FSAbbrev); 3238 NameVals.clear(); 3239 } 3240 3241 // Collect the global value references in the given variable's initializer, 3242 // and emit them in a summary record. 3243 void ModuleBitcodeWriter::writeModuleLevelReferences( 3244 const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals, 3245 unsigned FSModRefsAbbrev) { 3246 // Only interested in recording variable defs in the summary. 3247 if (V.isDeclaration()) 3248 return; 3249 NameVals.push_back(VE.getValueID(&V)); 3250 NameVals.push_back(getEncodedGVSummaryFlags(V)); 3251 auto *Summary = Index->getGlobalValueSummary(V); 3252 GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary); 3253 3254 unsigned SizeBeforeRefs = NameVals.size(); 3255 for (auto &RI : VS->refs()) 3256 NameVals.push_back(VE.getValueID(RI.getValue())); 3257 // Sort the refs for determinism output, the vector returned by FS->refs() has 3258 // been initialized from a DenseSet. 3259 std::sort(NameVals.begin() + SizeBeforeRefs, NameVals.end()); 3260 3261 Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals, 3262 FSModRefsAbbrev); 3263 NameVals.clear(); 3264 } 3265 3266 // Current version for the summary. 3267 // This is bumped whenever we introduce changes in the way some record are 3268 // interpreted, like flags for instance. 3269 static const uint64_t INDEX_VERSION = 1; 3270 3271 /// Emit the per-module summary section alongside the rest of 3272 /// the module's bitcode. 3273 void ModuleBitcodeWriter::writePerModuleGlobalValueSummary() { 3274 if (M.empty()) 3275 return; 3276 3277 if (Index->begin() == Index->end()) 3278 return; 3279 3280 Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 4); 3281 3282 Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION}); 3283 3284 // Abbrev for FS_PERMODULE. 3285 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 3286 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE)); 3287 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 3288 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 3289 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount 3290 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs 3291 // numrefs x valueid, n x (valueid, callsitecount) 3292 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3293 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3294 unsigned FSCallsAbbrev = Stream.EmitAbbrev(Abbv); 3295 3296 // Abbrev for FS_PERMODULE_PROFILE. 3297 Abbv = new BitCodeAbbrev(); 3298 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE)); 3299 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 3300 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 3301 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount 3302 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs 3303 // numrefs x valueid, n x (valueid, callsitecount, profilecount) 3304 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3305 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3306 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(Abbv); 3307 3308 // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS. 3309 Abbv = new BitCodeAbbrev(); 3310 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS)); 3311 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 3312 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 3313 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids 3314 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3315 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(Abbv); 3316 3317 // Abbrev for FS_ALIAS. 3318 Abbv = new BitCodeAbbrev(); 3319 Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS)); 3320 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 3321 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 3322 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 3323 unsigned FSAliasAbbrev = Stream.EmitAbbrev(Abbv); 3324 3325 SmallVector<uint64_t, 64> NameVals; 3326 // Iterate over the list of functions instead of the Index to 3327 // ensure the ordering is stable. 3328 for (const Function &F : M) { 3329 if (F.isDeclaration()) 3330 continue; 3331 // Summary emission does not support anonymous functions, they have to 3332 // renamed using the anonymous function renaming pass. 3333 if (!F.hasName()) 3334 report_fatal_error("Unexpected anonymous function when writing summary"); 3335 3336 auto *Summary = Index->getGlobalValueSummary(F); 3337 writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.getValueID(&F), 3338 FSCallsAbbrev, FSCallsProfileAbbrev, F); 3339 } 3340 3341 // Capture references from GlobalVariable initializers, which are outside 3342 // of a function scope. 3343 for (const GlobalVariable &G : M.globals()) 3344 writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev); 3345 3346 for (const GlobalAlias &A : M.aliases()) { 3347 auto *Aliasee = A.getBaseObject(); 3348 if (!Aliasee->hasName()) 3349 // Nameless function don't have an entry in the summary, skip it. 3350 continue; 3351 auto AliasId = VE.getValueID(&A); 3352 auto AliaseeId = VE.getValueID(Aliasee); 3353 NameVals.push_back(AliasId); 3354 NameVals.push_back(getEncodedGVSummaryFlags(A)); 3355 NameVals.push_back(AliaseeId); 3356 Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev); 3357 NameVals.clear(); 3358 } 3359 3360 Stream.ExitBlock(); 3361 } 3362 3363 /// Emit the combined summary section into the combined index file. 3364 void IndexBitcodeWriter::writeCombinedGlobalValueSummary() { 3365 Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3); 3366 Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION}); 3367 3368 // Abbrev for FS_COMBINED. 3369 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 3370 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED)); 3371 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 3372 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid 3373 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 3374 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount 3375 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs 3376 // numrefs x valueid, n x (valueid, callsitecount) 3377 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3378 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3379 unsigned FSCallsAbbrev = Stream.EmitAbbrev(Abbv); 3380 3381 // Abbrev for FS_COMBINED_PROFILE. 3382 Abbv = new BitCodeAbbrev(); 3383 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE)); 3384 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 3385 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid 3386 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 3387 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount 3388 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs 3389 // numrefs x valueid, n x (valueid, callsitecount, profilecount) 3390 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3391 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3392 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(Abbv); 3393 3394 // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS. 3395 Abbv = new BitCodeAbbrev(); 3396 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS)); 3397 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 3398 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid 3399 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 3400 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids 3401 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3402 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(Abbv); 3403 3404 // Abbrev for FS_COMBINED_ALIAS. 3405 Abbv = new BitCodeAbbrev(); 3406 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS)); 3407 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 3408 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid 3409 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 3410 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 3411 unsigned FSAliasAbbrev = Stream.EmitAbbrev(Abbv); 3412 3413 // The aliases are emitted as a post-pass, and will point to the value 3414 // id of the aliasee. Save them in a vector for post-processing. 3415 SmallVector<AliasSummary *, 64> Aliases; 3416 3417 // Save the value id for each summary for alias emission. 3418 DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap; 3419 3420 SmallVector<uint64_t, 64> NameVals; 3421 3422 // For local linkage, we also emit the original name separately 3423 // immediately after the record. 3424 auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) { 3425 if (!GlobalValue::isLocalLinkage(S.linkage())) 3426 return; 3427 NameVals.push_back(S.getOriginalName()); 3428 Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals); 3429 NameVals.clear(); 3430 }; 3431 3432 for (const auto &I : *this) { 3433 GlobalValueSummary *S = I.second; 3434 assert(S); 3435 3436 assert(hasValueId(I.first)); 3437 unsigned ValueId = getValueId(I.first); 3438 SummaryToValueIdMap[S] = ValueId; 3439 3440 if (auto *AS = dyn_cast<AliasSummary>(S)) { 3441 // Will process aliases as a post-pass because the reader wants all 3442 // global to be loaded first. 3443 Aliases.push_back(AS); 3444 continue; 3445 } 3446 3447 if (auto *VS = dyn_cast<GlobalVarSummary>(S)) { 3448 NameVals.push_back(ValueId); 3449 NameVals.push_back(Index.getModuleId(VS->modulePath())); 3450 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags())); 3451 for (auto &RI : VS->refs()) { 3452 NameVals.push_back(getValueId(RI.getGUID())); 3453 } 3454 3455 // Emit the finished record. 3456 Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals, 3457 FSModRefsAbbrev); 3458 NameVals.clear(); 3459 MaybeEmitOriginalName(*S); 3460 continue; 3461 } 3462 3463 auto *FS = cast<FunctionSummary>(S); 3464 NameVals.push_back(ValueId); 3465 NameVals.push_back(Index.getModuleId(FS->modulePath())); 3466 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags())); 3467 NameVals.push_back(FS->instCount()); 3468 NameVals.push_back(FS->refs().size()); 3469 3470 for (auto &RI : FS->refs()) { 3471 NameVals.push_back(getValueId(RI.getGUID())); 3472 } 3473 3474 bool HasProfileData = false; 3475 for (auto &EI : FS->calls()) { 3476 HasProfileData |= EI.second.ProfileCount != 0; 3477 if (HasProfileData) 3478 break; 3479 } 3480 3481 for (auto &EI : FS->calls()) { 3482 // If this GUID doesn't have a value id, it doesn't have a function 3483 // summary and we don't need to record any calls to it. 3484 if (!hasValueId(EI.first.getGUID())) 3485 continue; 3486 NameVals.push_back(getValueId(EI.first.getGUID())); 3487 assert(EI.second.CallsiteCount > 0 && "Expected at least one callsite"); 3488 NameVals.push_back(EI.second.CallsiteCount); 3489 if (HasProfileData) 3490 NameVals.push_back(EI.second.ProfileCount); 3491 } 3492 3493 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev); 3494 unsigned Code = 3495 (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED); 3496 3497 // Emit the finished record. 3498 Stream.EmitRecord(Code, NameVals, FSAbbrev); 3499 NameVals.clear(); 3500 MaybeEmitOriginalName(*S); 3501 } 3502 3503 for (auto *AS : Aliases) { 3504 auto AliasValueId = SummaryToValueIdMap[AS]; 3505 assert(AliasValueId); 3506 NameVals.push_back(AliasValueId); 3507 NameVals.push_back(Index.getModuleId(AS->modulePath())); 3508 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags())); 3509 auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()]; 3510 assert(AliaseeValueId); 3511 NameVals.push_back(AliaseeValueId); 3512 3513 // Emit the finished record. 3514 Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev); 3515 NameVals.clear(); 3516 MaybeEmitOriginalName(*AS); 3517 } 3518 3519 Stream.ExitBlock(); 3520 } 3521 3522 void ModuleBitcodeWriter::writeIdentificationBlock() { 3523 Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5); 3524 3525 // Write the "user readable" string identifying the bitcode producer 3526 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 3527 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING)); 3528 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3529 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 3530 auto StringAbbrev = Stream.EmitAbbrev(Abbv); 3531 writeStringRecord(bitc::IDENTIFICATION_CODE_STRING, 3532 "LLVM" LLVM_VERSION_STRING, StringAbbrev); 3533 3534 // Write the epoch version 3535 Abbv = new BitCodeAbbrev(); 3536 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH)); 3537 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 3538 auto EpochAbbrev = Stream.EmitAbbrev(Abbv); 3539 SmallVector<unsigned, 1> Vals = {bitc::BITCODE_CURRENT_EPOCH}; 3540 Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev); 3541 Stream.ExitBlock(); 3542 } 3543 3544 void ModuleBitcodeWriter::writeModuleHash(size_t BlockStartPos) { 3545 // Emit the module's hash. 3546 // MODULE_CODE_HASH: [5*i32] 3547 SHA1 Hasher; 3548 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&(Buffer)[BlockStartPos], 3549 Buffer.size() - BlockStartPos)); 3550 auto Hash = Hasher.result(); 3551 SmallVector<uint64_t, 20> Vals; 3552 auto LShift = [&](unsigned char Val, unsigned Amount) 3553 -> uint64_t { return ((uint64_t)Val) << Amount; }; 3554 for (int Pos = 0; Pos < 20; Pos += 4) { 3555 uint32_t SubHash = LShift(Hash[Pos + 0], 24); 3556 SubHash |= LShift(Hash[Pos + 1], 16) | LShift(Hash[Pos + 2], 8) | 3557 (unsigned)(unsigned char)Hash[Pos + 3]; 3558 Vals.push_back(SubHash); 3559 } 3560 3561 // Emit the finished record. 3562 Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals); 3563 } 3564 3565 void BitcodeWriter::write() { 3566 // Emit the file header first. 3567 writeBitcodeHeader(); 3568 3569 writeBlocks(); 3570 } 3571 3572 void ModuleBitcodeWriter::writeBlocks() { 3573 writeIdentificationBlock(); 3574 writeModule(); 3575 } 3576 3577 void IndexBitcodeWriter::writeBlocks() { 3578 // Index contains only a single outer (module) block. 3579 writeIndex(); 3580 } 3581 3582 void ModuleBitcodeWriter::writeModule() { 3583 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3); 3584 size_t BlockStartPos = Buffer.size(); 3585 3586 SmallVector<unsigned, 1> Vals; 3587 unsigned CurVersion = 1; 3588 Vals.push_back(CurVersion); 3589 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals); 3590 3591 // Emit blockinfo, which defines the standard abbreviations etc. 3592 writeBlockInfo(); 3593 3594 // Emit information about attribute groups. 3595 writeAttributeGroupTable(); 3596 3597 // Emit information about parameter attributes. 3598 writeAttributeTable(); 3599 3600 // Emit information describing all of the types in the module. 3601 writeTypeTable(); 3602 3603 writeComdats(); 3604 3605 // Emit top-level description of module, including target triple, inline asm, 3606 // descriptors for global variables, and function prototype info. 3607 writeModuleInfo(); 3608 3609 // Emit constants. 3610 writeModuleConstants(); 3611 3612 // Emit metadata kind names. 3613 writeModuleMetadataKinds(); 3614 3615 // Emit metadata. 3616 writeModuleMetadata(); 3617 3618 // Emit module-level use-lists. 3619 if (VE.shouldPreserveUseListOrder()) 3620 writeUseListBlock(nullptr); 3621 3622 writeOperandBundleTags(); 3623 3624 // Emit function bodies. 3625 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex; 3626 for (Module::const_iterator F = M.begin(), E = M.end(); F != E; ++F) 3627 if (!F->isDeclaration()) 3628 writeFunction(*F, FunctionToBitcodeIndex); 3629 3630 // Need to write after the above call to WriteFunction which populates 3631 // the summary information in the index. 3632 if (Index) 3633 writePerModuleGlobalValueSummary(); 3634 3635 writeValueSymbolTable(M.getValueSymbolTable(), 3636 /* IsModuleLevel */ true, &FunctionToBitcodeIndex); 3637 3638 if (GenerateHash) { 3639 writeModuleHash(BlockStartPos); 3640 } 3641 3642 Stream.ExitBlock(); 3643 } 3644 3645 static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer, 3646 uint32_t &Position) { 3647 support::endian::write32le(&Buffer[Position], Value); 3648 Position += 4; 3649 } 3650 3651 /// If generating a bc file on darwin, we have to emit a 3652 /// header and trailer to make it compatible with the system archiver. To do 3653 /// this we emit the following header, and then emit a trailer that pads the 3654 /// file out to be a multiple of 16 bytes. 3655 /// 3656 /// struct bc_header { 3657 /// uint32_t Magic; // 0x0B17C0DE 3658 /// uint32_t Version; // Version, currently always 0. 3659 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file. 3660 /// uint32_t BitcodeSize; // Size of traditional bitcode file. 3661 /// uint32_t CPUType; // CPU specifier. 3662 /// ... potentially more later ... 3663 /// }; 3664 static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer, 3665 const Triple &TT) { 3666 unsigned CPUType = ~0U; 3667 3668 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*, 3669 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic 3670 // number from /usr/include/mach/machine.h. It is ok to reproduce the 3671 // specific constants here because they are implicitly part of the Darwin ABI. 3672 enum { 3673 DARWIN_CPU_ARCH_ABI64 = 0x01000000, 3674 DARWIN_CPU_TYPE_X86 = 7, 3675 DARWIN_CPU_TYPE_ARM = 12, 3676 DARWIN_CPU_TYPE_POWERPC = 18 3677 }; 3678 3679 Triple::ArchType Arch = TT.getArch(); 3680 if (Arch == Triple::x86_64) 3681 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64; 3682 else if (Arch == Triple::x86) 3683 CPUType = DARWIN_CPU_TYPE_X86; 3684 else if (Arch == Triple::ppc) 3685 CPUType = DARWIN_CPU_TYPE_POWERPC; 3686 else if (Arch == Triple::ppc64) 3687 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64; 3688 else if (Arch == Triple::arm || Arch == Triple::thumb) 3689 CPUType = DARWIN_CPU_TYPE_ARM; 3690 3691 // Traditional Bitcode starts after header. 3692 assert(Buffer.size() >= BWH_HeaderSize && 3693 "Expected header size to be reserved"); 3694 unsigned BCOffset = BWH_HeaderSize; 3695 unsigned BCSize = Buffer.size() - BWH_HeaderSize; 3696 3697 // Write the magic and version. 3698 unsigned Position = 0; 3699 writeInt32ToBuffer(0x0B17C0DE, Buffer, Position); 3700 writeInt32ToBuffer(0, Buffer, Position); // Version. 3701 writeInt32ToBuffer(BCOffset, Buffer, Position); 3702 writeInt32ToBuffer(BCSize, Buffer, Position); 3703 writeInt32ToBuffer(CPUType, Buffer, Position); 3704 3705 // If the file is not a multiple of 16 bytes, insert dummy padding. 3706 while (Buffer.size() & 15) 3707 Buffer.push_back(0); 3708 } 3709 3710 /// Helper to write the header common to all bitcode files. 3711 void BitcodeWriter::writeBitcodeHeader() { 3712 // Emit the file header. 3713 Stream.Emit((unsigned)'B', 8); 3714 Stream.Emit((unsigned)'C', 8); 3715 Stream.Emit(0x0, 4); 3716 Stream.Emit(0xC, 4); 3717 Stream.Emit(0xE, 4); 3718 Stream.Emit(0xD, 4); 3719 } 3720 3721 /// WriteBitcodeToFile - Write the specified module to the specified output 3722 /// stream. 3723 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out, 3724 bool ShouldPreserveUseListOrder, 3725 const ModuleSummaryIndex *Index, 3726 bool GenerateHash) { 3727 SmallVector<char, 0> Buffer; 3728 Buffer.reserve(256*1024); 3729 3730 // If this is darwin or another generic macho target, reserve space for the 3731 // header. 3732 Triple TT(M->getTargetTriple()); 3733 if (TT.isOSDarwin() || TT.isOSBinFormatMachO()) 3734 Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0); 3735 3736 // Emit the module into the buffer. 3737 ModuleBitcodeWriter ModuleWriter(M, Buffer, ShouldPreserveUseListOrder, Index, 3738 GenerateHash); 3739 ModuleWriter.write(); 3740 3741 if (TT.isOSDarwin() || TT.isOSBinFormatMachO()) 3742 emitDarwinBCHeaderAndTrailer(Buffer, TT); 3743 3744 // Write the generated bitstream to "Out". 3745 Out.write((char*)&Buffer.front(), Buffer.size()); 3746 } 3747 3748 void IndexBitcodeWriter::writeIndex() { 3749 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3); 3750 3751 SmallVector<unsigned, 1> Vals; 3752 unsigned CurVersion = 1; 3753 Vals.push_back(CurVersion); 3754 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals); 3755 3756 // If we have a VST, write the VSTOFFSET record placeholder. 3757 writeValueSymbolTableForwardDecl(); 3758 3759 // Write the module paths in the combined index. 3760 writeModStrings(); 3761 3762 // Write the summary combined index records. 3763 writeCombinedGlobalValueSummary(); 3764 3765 // Need a special VST writer for the combined index (we don't have a 3766 // real VST and real values when this is invoked). 3767 writeCombinedValueSymbolTable(); 3768 3769 Stream.ExitBlock(); 3770 } 3771 3772 // Write the specified module summary index to the given raw output stream, 3773 // where it will be written in a new bitcode block. This is used when 3774 // writing the combined index file for ThinLTO. When writing a subset of the 3775 // index for a distributed backend, provide a \p ModuleToSummariesForIndex map. 3776 void llvm::WriteIndexToFile( 3777 const ModuleSummaryIndex &Index, raw_ostream &Out, 3778 std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) { 3779 SmallVector<char, 0> Buffer; 3780 Buffer.reserve(256 * 1024); 3781 3782 IndexBitcodeWriter IndexWriter(Buffer, Index, ModuleToSummariesForIndex); 3783 IndexWriter.write(); 3784 3785 Out.write((char *)&Buffer.front(), Buffer.size()); 3786 } 3787