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