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