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