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