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