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