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