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