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