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