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