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