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