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