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