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