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