1 //===- Bitcode/Writer/DXILBitcodeWriter.cpp - DXIL Bitcode Writer ---------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // Bitcode writer implementation. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "DXILBitcodeWriter.h" 14 #include "DXILValueEnumerator.h" 15 #include "llvm/ADT/Triple.h" 16 #include "llvm/Bitcode/BitcodeCommon.h" 17 #include "llvm/Bitcode/BitcodeReader.h" 18 #include "llvm/Bitcode/LLVMBitCodes.h" 19 #include "llvm/Bitstream/BitCodes.h" 20 #include "llvm/Bitstream/BitstreamWriter.h" 21 #include "llvm/IR/Attributes.h" 22 #include "llvm/IR/BasicBlock.h" 23 #include "llvm/IR/Comdat.h" 24 #include "llvm/IR/Constant.h" 25 #include "llvm/IR/Constants.h" 26 #include "llvm/IR/DebugInfoMetadata.h" 27 #include "llvm/IR/DebugLoc.h" 28 #include "llvm/IR/DerivedTypes.h" 29 #include "llvm/IR/Function.h" 30 #include "llvm/IR/GlobalAlias.h" 31 #include "llvm/IR/GlobalIFunc.h" 32 #include "llvm/IR/GlobalObject.h" 33 #include "llvm/IR/GlobalValue.h" 34 #include "llvm/IR/GlobalVariable.h" 35 #include "llvm/IR/InlineAsm.h" 36 #include "llvm/IR/InstrTypes.h" 37 #include "llvm/IR/Instruction.h" 38 #include "llvm/IR/Instructions.h" 39 #include "llvm/IR/LLVMContext.h" 40 #include "llvm/IR/Metadata.h" 41 #include "llvm/IR/Module.h" 42 #include "llvm/IR/ModuleSummaryIndex.h" 43 #include "llvm/IR/Operator.h" 44 #include "llvm/IR/Type.h" 45 #include "llvm/IR/UseListOrder.h" 46 #include "llvm/IR/Value.h" 47 #include "llvm/IR/ValueSymbolTable.h" 48 #include "llvm/Object/IRSymtab.h" 49 #include "llvm/Support/ErrorHandling.h" 50 #include "llvm/Support/SHA1.h" 51 52 namespace llvm { 53 namespace dxil { 54 55 // Generates an enum to use as an index in the Abbrev array of Metadata record. 56 enum MetadataAbbrev : unsigned { 57 #define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID, 58 #include "llvm/IR/Metadata.def" 59 LastPlusOne 60 }; 61 62 class DXILBitcodeWriter { 63 64 /// These are manifest constants used by the bitcode writer. They do not need 65 /// to be kept in sync with the reader, but need to be consistent within this 66 /// file. 67 enum { 68 // VALUE_SYMTAB_BLOCK abbrev id's. 69 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV, 70 VST_ENTRY_7_ABBREV, 71 VST_ENTRY_6_ABBREV, 72 VST_BBENTRY_6_ABBREV, 73 74 // CONSTANTS_BLOCK abbrev id's. 75 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV, 76 CONSTANTS_INTEGER_ABBREV, 77 CONSTANTS_CE_CAST_Abbrev, 78 CONSTANTS_NULL_Abbrev, 79 80 // FUNCTION_BLOCK abbrev id's. 81 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV, 82 FUNCTION_INST_BINOP_ABBREV, 83 FUNCTION_INST_BINOP_FLAGS_ABBREV, 84 FUNCTION_INST_CAST_ABBREV, 85 FUNCTION_INST_RET_VOID_ABBREV, 86 FUNCTION_INST_RET_VAL_ABBREV, 87 FUNCTION_INST_UNREACHABLE_ABBREV, 88 FUNCTION_INST_GEP_ABBREV, 89 }; 90 91 /// The stream created and owned by the client. 92 BitstreamWriter &Stream; 93 94 StringTableBuilder &StrtabBuilder; 95 96 /// The Module to write to bitcode. 97 const Module &M; 98 99 /// Enumerates ids for all values in the module. 100 ValueEnumerator VE; 101 102 /// Map that holds the correspondence between GUIDs in the summary index, 103 /// that came from indirect call profiles, and a value id generated by this 104 /// class to use in the VST and summary block records. 105 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap; 106 107 /// Tracks the last value id recorded in the GUIDToValueMap. 108 unsigned GlobalValueId; 109 110 /// Saves the offset of the VSTOffset record that must eventually be 111 /// backpatched with the offset of the actual VST. 112 uint64_t VSTOffsetPlaceholder = 0; 113 114 /// Pointer to the buffer allocated by caller for bitcode writing. 115 const SmallVectorImpl<char> &Buffer; 116 117 /// The start bit of the identification block. 118 uint64_t BitcodeStartBit; 119 120 public: 121 /// Constructs a ModuleBitcodeWriter object for the given Module, 122 /// writing to the provided \p Buffer. 123 DXILBitcodeWriter(const Module &M, SmallVectorImpl<char> &Buffer, 124 StringTableBuilder &StrtabBuilder, BitstreamWriter &Stream) 125 : Stream(Stream), StrtabBuilder(StrtabBuilder), M(M), 126 VE(M, true), Buffer(Buffer), 127 BitcodeStartBit(Stream.GetCurrentBitNo()) { 128 GlobalValueId = VE.getValues().size(); 129 } 130 131 /// Emit the current module to the bitstream. 132 void write(); 133 134 static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind); 135 static void writeStringRecord(BitstreamWriter &Stream, unsigned Code, 136 StringRef Str, unsigned AbbrevToUse); 137 static void writeIdentificationBlock(BitstreamWriter &Stream); 138 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V); 139 static void emitWideAPInt(SmallVectorImpl<uint64_t> &Vals, const APInt &A); 140 141 static unsigned getEncodedComdatSelectionKind(const Comdat &C); 142 static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage); 143 static unsigned getEncodedLinkage(const GlobalValue &GV); 144 static unsigned getEncodedVisibility(const GlobalValue &GV); 145 static unsigned getEncodedThreadLocalMode(const GlobalValue &GV); 146 static unsigned getEncodedDLLStorageClass(const GlobalValue &GV); 147 static unsigned getEncodedCastOpcode(unsigned Opcode); 148 static unsigned getEncodedUnaryOpcode(unsigned Opcode); 149 static unsigned getEncodedBinaryOpcode(unsigned Opcode); 150 static unsigned getEncodedRMWOperation(AtomicRMWInst::BinOp Op); 151 static unsigned getEncodedOrdering(AtomicOrdering Ordering); 152 static uint64_t getOptimizationFlags(const Value *V); 153 154 private: 155 void writeModuleVersion(); 156 void writePerModuleGlobalValueSummary(); 157 158 void writePerModuleFunctionSummaryRecord(SmallVector<uint64_t, 64> &NameVals, 159 GlobalValueSummary *Summary, 160 unsigned ValueID, 161 unsigned FSCallsAbbrev, 162 unsigned FSCallsProfileAbbrev, 163 const Function &F); 164 void writeModuleLevelReferences(const GlobalVariable &V, 165 SmallVector<uint64_t, 64> &NameVals, 166 unsigned FSModRefsAbbrev, 167 unsigned FSModVTableRefsAbbrev); 168 169 void assignValueId(GlobalValue::GUID ValGUID) { 170 GUIDToValueIdMap[ValGUID] = ++GlobalValueId; 171 } 172 173 unsigned getValueId(GlobalValue::GUID ValGUID) { 174 const auto &VMI = GUIDToValueIdMap.find(ValGUID); 175 // Expect that any GUID value had a value Id assigned by an 176 // earlier call to assignValueId. 177 assert(VMI != GUIDToValueIdMap.end() && 178 "GUID does not have assigned value Id"); 179 return VMI->second; 180 } 181 182 // Helper to get the valueId for the type of value recorded in VI. 183 unsigned getValueId(ValueInfo VI) { 184 if (!VI.haveGVs() || !VI.getValue()) 185 return getValueId(VI.getGUID()); 186 return VE.getValueID(VI.getValue()); 187 } 188 189 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; } 190 191 uint64_t bitcodeStartBit() { return BitcodeStartBit; } 192 193 size_t addToStrtab(StringRef Str); 194 195 unsigned createDILocationAbbrev(); 196 unsigned createGenericDINodeAbbrev(); 197 198 void writeAttributeGroupTable(); 199 void writeAttributeTable(); 200 void writeTypeTable(); 201 void writeComdats(); 202 void writeValueSymbolTableForwardDecl(); 203 void writeModuleInfo(); 204 void writeValueAsMetadata(const ValueAsMetadata *MD, 205 SmallVectorImpl<uint64_t> &Record); 206 void writeMDTuple(const MDTuple *N, SmallVectorImpl<uint64_t> &Record, 207 unsigned Abbrev); 208 void writeDILocation(const DILocation *N, SmallVectorImpl<uint64_t> &Record, 209 unsigned &Abbrev); 210 void writeGenericDINode(const GenericDINode *N, 211 SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev) { 212 llvm_unreachable("DXIL cannot contain GenericDI Nodes"); 213 } 214 void writeDISubrange(const DISubrange *N, SmallVectorImpl<uint64_t> &Record, 215 unsigned Abbrev); 216 void writeDIGenericSubrange(const DIGenericSubrange *N, 217 SmallVectorImpl<uint64_t> &Record, 218 unsigned Abbrev) { 219 llvm_unreachable("DXIL cannot contain DIGenericSubrange Nodes"); 220 } 221 void writeDIEnumerator(const DIEnumerator *N, 222 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 223 void writeDIBasicType(const DIBasicType *N, SmallVectorImpl<uint64_t> &Record, 224 unsigned Abbrev); 225 void writeDIStringType(const DIStringType *N, 226 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) { 227 llvm_unreachable("DXIL cannot contain DIStringType Nodes"); 228 } 229 void writeDIDerivedType(const DIDerivedType *N, 230 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 231 void writeDICompositeType(const DICompositeType *N, 232 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 233 void writeDISubroutineType(const DISubroutineType *N, 234 SmallVectorImpl<uint64_t> &Record, 235 unsigned Abbrev); 236 void writeDIFile(const DIFile *N, SmallVectorImpl<uint64_t> &Record, 237 unsigned Abbrev); 238 void writeDICompileUnit(const DICompileUnit *N, 239 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 240 void writeDISubprogram(const DISubprogram *N, 241 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 242 void writeDILexicalBlock(const DILexicalBlock *N, 243 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 244 void writeDILexicalBlockFile(const DILexicalBlockFile *N, 245 SmallVectorImpl<uint64_t> &Record, 246 unsigned Abbrev); 247 void writeDICommonBlock(const DICommonBlock *N, 248 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) { 249 llvm_unreachable("DXIL cannot contain DICommonBlock Nodes"); 250 } 251 void writeDINamespace(const DINamespace *N, SmallVectorImpl<uint64_t> &Record, 252 unsigned Abbrev); 253 void writeDIMacro(const DIMacro *N, SmallVectorImpl<uint64_t> &Record, 254 unsigned Abbrev) { 255 llvm_unreachable("DXIL cannot contain DIMacro Nodes"); 256 } 257 void writeDIMacroFile(const DIMacroFile *N, SmallVectorImpl<uint64_t> &Record, 258 unsigned Abbrev) { 259 llvm_unreachable("DXIL cannot contain DIMacroFile Nodes"); 260 } 261 void writeDIArgList(const DIArgList *N, SmallVectorImpl<uint64_t> &Record, 262 unsigned Abbrev) { 263 llvm_unreachable("DXIL cannot contain DIArgList Nodes"); 264 } 265 void writeDIModule(const DIModule *N, SmallVectorImpl<uint64_t> &Record, 266 unsigned Abbrev); 267 void writeDITemplateTypeParameter(const DITemplateTypeParameter *N, 268 SmallVectorImpl<uint64_t> &Record, 269 unsigned Abbrev); 270 void writeDITemplateValueParameter(const DITemplateValueParameter *N, 271 SmallVectorImpl<uint64_t> &Record, 272 unsigned Abbrev); 273 void writeDIGlobalVariable(const DIGlobalVariable *N, 274 SmallVectorImpl<uint64_t> &Record, 275 unsigned Abbrev); 276 void writeDILocalVariable(const DILocalVariable *N, 277 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 278 void writeDILabel(const DILabel *N, SmallVectorImpl<uint64_t> &Record, 279 unsigned Abbrev) { 280 llvm_unreachable("DXIL cannot contain DILabel Nodes"); 281 } 282 void writeDIExpression(const DIExpression *N, 283 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 284 void writeDIGlobalVariableExpression(const DIGlobalVariableExpression *N, 285 SmallVectorImpl<uint64_t> &Record, 286 unsigned Abbrev) { 287 llvm_unreachable("DXIL cannot contain GlobalVariableExpression Nodes"); 288 } 289 void writeDIObjCProperty(const DIObjCProperty *N, 290 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 291 void writeDIImportedEntity(const DIImportedEntity *N, 292 SmallVectorImpl<uint64_t> &Record, 293 unsigned Abbrev); 294 unsigned createNamedMetadataAbbrev(); 295 void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record); 296 unsigned createMetadataStringsAbbrev(); 297 void writeMetadataStrings(ArrayRef<const Metadata *> Strings, 298 SmallVectorImpl<uint64_t> &Record); 299 void writeMetadataRecords(ArrayRef<const Metadata *> MDs, 300 SmallVectorImpl<uint64_t> &Record, 301 std::vector<unsigned> *MDAbbrevs = nullptr, 302 std::vector<uint64_t> *IndexPos = nullptr); 303 void writeModuleMetadata(); 304 void writeFunctionMetadata(const Function &F); 305 void writeFunctionMetadataAttachment(const Function &F); 306 void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record, 307 const GlobalObject &GO); 308 void writeModuleMetadataKinds(); 309 void writeOperandBundleTags(); 310 void writeSyncScopeNames(); 311 void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal); 312 void writeModuleConstants(); 313 bool pushValueAndType(const Value *V, unsigned InstID, 314 SmallVectorImpl<unsigned> &Vals); 315 void writeOperandBundles(const CallBase &CB, unsigned InstID); 316 void pushValue(const Value *V, unsigned InstID, 317 SmallVectorImpl<unsigned> &Vals); 318 void pushValueSigned(const Value *V, unsigned InstID, 319 SmallVectorImpl<uint64_t> &Vals); 320 void writeInstruction(const Instruction &I, unsigned InstID, 321 SmallVectorImpl<unsigned> &Vals); 322 void writeFunctionLevelValueSymbolTable(const ValueSymbolTable &VST); 323 void writeGlobalValueSymbolTable( 324 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex); 325 void writeUseList(UseListOrder &&Order); 326 void writeUseListBlock(const Function *F); 327 void writeFunction(const Function &F); 328 void writeBlockInfo(); 329 330 unsigned getEncodedSyncScopeID(SyncScope::ID SSID) { return unsigned(SSID); } 331 332 unsigned getEncodedAlign(MaybeAlign Alignment) { return encode(Alignment); } 333 }; 334 335 } // namespace dxil 336 } // namespace llvm 337 338 using namespace llvm; 339 using namespace llvm::dxil; 340 341 //////////////////////////////////////////////////////////////////////////////// 342 /// Begin dxil::BitcodeWriter Implementation 343 //////////////////////////////////////////////////////////////////////////////// 344 345 dxil::BitcodeWriter::BitcodeWriter(SmallVectorImpl<char> &Buffer, raw_fd_stream *FS) 346 : Buffer(Buffer), Stream(new BitstreamWriter(Buffer, FS, 512)) { 347 // Emit the file header. 348 Stream->Emit((unsigned)'B', 8); 349 Stream->Emit((unsigned)'C', 8); 350 Stream->Emit(0x0, 4); 351 Stream->Emit(0xC, 4); 352 Stream->Emit(0xE, 4); 353 Stream->Emit(0xD, 4); 354 } 355 356 dxil::BitcodeWriter::~BitcodeWriter() { assert(WroteStrtab); } 357 358 /// Write the specified module to the specified output stream. 359 void dxil::WriteDXILToFile(const Module &M, raw_ostream &Out) { 360 SmallVector<char, 0> Buffer; 361 Buffer.reserve(256 * 1024); 362 363 // If this is darwin or another generic macho target, reserve space for the 364 // header. 365 Triple TT(M.getTargetTriple()); 366 if (TT.isOSDarwin() || TT.isOSBinFormatMachO()) 367 Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0); 368 369 BitcodeWriter Writer(Buffer, dyn_cast<raw_fd_stream>(&Out)); 370 Writer.writeModule(M); 371 Writer.writeSymtab(); 372 Writer.writeStrtab(); 373 374 // Write the generated bitstream to "Out". 375 if (!Buffer.empty()) 376 Out.write((char *)&Buffer.front(), Buffer.size()); 377 } 378 379 void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) { 380 Stream->EnterSubblock(Block, 3); 381 382 auto Abbv = std::make_shared<BitCodeAbbrev>(); 383 Abbv->Add(BitCodeAbbrevOp(Record)); 384 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 385 auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv)); 386 387 Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob); 388 389 Stream->ExitBlock(); 390 } 391 392 void BitcodeWriter::writeSymtab() { 393 assert(!WroteStrtab && !WroteSymtab); 394 395 // If any module has module-level inline asm, we will require a registered asm 396 // parser for the target so that we can create an accurate symbol table for 397 // the module. 398 for (Module *M : Mods) { 399 if (M->getModuleInlineAsm().empty()) 400 continue; 401 } 402 403 WroteSymtab = true; 404 SmallVector<char, 0> Symtab; 405 // The irsymtab::build function may be unable to create a symbol table if the 406 // module is malformed (e.g. it contains an invalid alias). Writing a symbol 407 // table is not required for correctness, but we still want to be able to 408 // write malformed modules to bitcode files, so swallow the error. 409 if (Error E = irsymtab::build(Mods, Symtab, StrtabBuilder, Alloc)) { 410 consumeError(std::move(E)); 411 return; 412 } 413 414 writeBlob(bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB, 415 {Symtab.data(), Symtab.size()}); 416 } 417 418 void BitcodeWriter::writeStrtab() { 419 assert(!WroteStrtab); 420 421 std::vector<char> Strtab; 422 StrtabBuilder.finalizeInOrder(); 423 Strtab.resize(StrtabBuilder.getSize()); 424 StrtabBuilder.write((uint8_t *)Strtab.data()); 425 426 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, 427 {Strtab.data(), Strtab.size()}); 428 429 WroteStrtab = true; 430 } 431 432 void BitcodeWriter::copyStrtab(StringRef Strtab) { 433 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab); 434 WroteStrtab = true; 435 } 436 437 void BitcodeWriter::writeModule(const Module &M) { 438 assert(!WroteStrtab); 439 440 // The Mods vector is used by irsymtab::build, which requires non-const 441 // Modules in case it needs to materialize metadata. But the bitcode writer 442 // requires that the module is materialized, so we can cast to non-const here, 443 // after checking that it is in fact materialized. 444 assert(M.isMaterialized()); 445 Mods.push_back(const_cast<Module *>(&M)); 446 447 DXILBitcodeWriter ModuleWriter(M, Buffer, StrtabBuilder, *Stream); 448 ModuleWriter.write(); 449 } 450 451 //////////////////////////////////////////////////////////////////////////////// 452 /// Begin dxil::BitcodeWriterBase Implementation 453 //////////////////////////////////////////////////////////////////////////////// 454 455 unsigned DXILBitcodeWriter::getEncodedCastOpcode(unsigned Opcode) { 456 switch (Opcode) { 457 default: 458 llvm_unreachable("Unknown cast instruction!"); 459 case Instruction::Trunc: 460 return bitc::CAST_TRUNC; 461 case Instruction::ZExt: 462 return bitc::CAST_ZEXT; 463 case Instruction::SExt: 464 return bitc::CAST_SEXT; 465 case Instruction::FPToUI: 466 return bitc::CAST_FPTOUI; 467 case Instruction::FPToSI: 468 return bitc::CAST_FPTOSI; 469 case Instruction::UIToFP: 470 return bitc::CAST_UITOFP; 471 case Instruction::SIToFP: 472 return bitc::CAST_SITOFP; 473 case Instruction::FPTrunc: 474 return bitc::CAST_FPTRUNC; 475 case Instruction::FPExt: 476 return bitc::CAST_FPEXT; 477 case Instruction::PtrToInt: 478 return bitc::CAST_PTRTOINT; 479 case Instruction::IntToPtr: 480 return bitc::CAST_INTTOPTR; 481 case Instruction::BitCast: 482 return bitc::CAST_BITCAST; 483 case Instruction::AddrSpaceCast: 484 return bitc::CAST_ADDRSPACECAST; 485 } 486 } 487 488 unsigned DXILBitcodeWriter::getEncodedUnaryOpcode(unsigned Opcode) { 489 switch (Opcode) { 490 default: 491 llvm_unreachable("Unknown binary instruction!"); 492 case Instruction::FNeg: 493 return bitc::UNOP_FNEG; 494 } 495 } 496 497 unsigned DXILBitcodeWriter::getEncodedBinaryOpcode(unsigned Opcode) { 498 switch (Opcode) { 499 default: 500 llvm_unreachable("Unknown binary instruction!"); 501 case Instruction::Add: 502 case Instruction::FAdd: 503 return bitc::BINOP_ADD; 504 case Instruction::Sub: 505 case Instruction::FSub: 506 return bitc::BINOP_SUB; 507 case Instruction::Mul: 508 case Instruction::FMul: 509 return bitc::BINOP_MUL; 510 case Instruction::UDiv: 511 return bitc::BINOP_UDIV; 512 case Instruction::FDiv: 513 case Instruction::SDiv: 514 return bitc::BINOP_SDIV; 515 case Instruction::URem: 516 return bitc::BINOP_UREM; 517 case Instruction::FRem: 518 case Instruction::SRem: 519 return bitc::BINOP_SREM; 520 case Instruction::Shl: 521 return bitc::BINOP_SHL; 522 case Instruction::LShr: 523 return bitc::BINOP_LSHR; 524 case Instruction::AShr: 525 return bitc::BINOP_ASHR; 526 case Instruction::And: 527 return bitc::BINOP_AND; 528 case Instruction::Or: 529 return bitc::BINOP_OR; 530 case Instruction::Xor: 531 return bitc::BINOP_XOR; 532 } 533 } 534 535 unsigned DXILBitcodeWriter::getEncodedRMWOperation(AtomicRMWInst::BinOp Op) { 536 switch (Op) { 537 default: 538 llvm_unreachable("Unknown RMW operation!"); 539 case AtomicRMWInst::Xchg: 540 return bitc::RMW_XCHG; 541 case AtomicRMWInst::Add: 542 return bitc::RMW_ADD; 543 case AtomicRMWInst::Sub: 544 return bitc::RMW_SUB; 545 case AtomicRMWInst::And: 546 return bitc::RMW_AND; 547 case AtomicRMWInst::Nand: 548 return bitc::RMW_NAND; 549 case AtomicRMWInst::Or: 550 return bitc::RMW_OR; 551 case AtomicRMWInst::Xor: 552 return bitc::RMW_XOR; 553 case AtomicRMWInst::Max: 554 return bitc::RMW_MAX; 555 case AtomicRMWInst::Min: 556 return bitc::RMW_MIN; 557 case AtomicRMWInst::UMax: 558 return bitc::RMW_UMAX; 559 case AtomicRMWInst::UMin: 560 return bitc::RMW_UMIN; 561 case AtomicRMWInst::FAdd: 562 return bitc::RMW_FADD; 563 case AtomicRMWInst::FSub: 564 return bitc::RMW_FSUB; 565 } 566 } 567 568 unsigned DXILBitcodeWriter::getEncodedOrdering(AtomicOrdering Ordering) { 569 switch (Ordering) { 570 case AtomicOrdering::NotAtomic: 571 return bitc::ORDERING_NOTATOMIC; 572 case AtomicOrdering::Unordered: 573 return bitc::ORDERING_UNORDERED; 574 case AtomicOrdering::Monotonic: 575 return bitc::ORDERING_MONOTONIC; 576 case AtomicOrdering::Acquire: 577 return bitc::ORDERING_ACQUIRE; 578 case AtomicOrdering::Release: 579 return bitc::ORDERING_RELEASE; 580 case AtomicOrdering::AcquireRelease: 581 return bitc::ORDERING_ACQREL; 582 case AtomicOrdering::SequentiallyConsistent: 583 return bitc::ORDERING_SEQCST; 584 } 585 llvm_unreachable("Invalid ordering"); 586 } 587 588 void DXILBitcodeWriter::writeStringRecord(BitstreamWriter &Stream, 589 unsigned Code, StringRef Str, 590 unsigned AbbrevToUse) { 591 SmallVector<unsigned, 64> Vals; 592 593 // Code: [strchar x N] 594 for (char C : Str) { 595 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(C)) 596 AbbrevToUse = 0; 597 Vals.push_back(C); 598 } 599 600 // Emit the finished record. 601 Stream.EmitRecord(Code, Vals, AbbrevToUse); 602 } 603 604 uint64_t DXILBitcodeWriter::getAttrKindEncoding(Attribute::AttrKind Kind) { 605 switch (Kind) { 606 case Attribute::Alignment: 607 return bitc::ATTR_KIND_ALIGNMENT; 608 case Attribute::AllocAlign: 609 return bitc::ATTR_KIND_ALLOC_ALIGN; 610 case Attribute::AllocSize: 611 return bitc::ATTR_KIND_ALLOC_SIZE; 612 case Attribute::AlwaysInline: 613 return bitc::ATTR_KIND_ALWAYS_INLINE; 614 case Attribute::ArgMemOnly: 615 return bitc::ATTR_KIND_ARGMEMONLY; 616 case Attribute::Builtin: 617 return bitc::ATTR_KIND_BUILTIN; 618 case Attribute::ByVal: 619 return bitc::ATTR_KIND_BY_VAL; 620 case Attribute::Convergent: 621 return bitc::ATTR_KIND_CONVERGENT; 622 case Attribute::InAlloca: 623 return bitc::ATTR_KIND_IN_ALLOCA; 624 case Attribute::Cold: 625 return bitc::ATTR_KIND_COLD; 626 case Attribute::DisableSanitizerInstrumentation: 627 return bitc::ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION; 628 case Attribute::Hot: 629 return bitc::ATTR_KIND_HOT; 630 case Attribute::ElementType: 631 return bitc::ATTR_KIND_ELEMENTTYPE; 632 case Attribute::InaccessibleMemOnly: 633 return bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY; 634 case Attribute::InaccessibleMemOrArgMemOnly: 635 return bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY; 636 case Attribute::InlineHint: 637 return bitc::ATTR_KIND_INLINE_HINT; 638 case Attribute::InReg: 639 return bitc::ATTR_KIND_IN_REG; 640 case Attribute::JumpTable: 641 return bitc::ATTR_KIND_JUMP_TABLE; 642 case Attribute::MinSize: 643 return bitc::ATTR_KIND_MIN_SIZE; 644 case Attribute::Naked: 645 return bitc::ATTR_KIND_NAKED; 646 case Attribute::Nest: 647 return bitc::ATTR_KIND_NEST; 648 case Attribute::NoAlias: 649 return bitc::ATTR_KIND_NO_ALIAS; 650 case Attribute::NoBuiltin: 651 return bitc::ATTR_KIND_NO_BUILTIN; 652 case Attribute::NoCallback: 653 return bitc::ATTR_KIND_NO_CALLBACK; 654 case Attribute::NoCapture: 655 return bitc::ATTR_KIND_NO_CAPTURE; 656 case Attribute::NoDuplicate: 657 return bitc::ATTR_KIND_NO_DUPLICATE; 658 case Attribute::NoFree: 659 return bitc::ATTR_KIND_NOFREE; 660 case Attribute::NoImplicitFloat: 661 return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT; 662 case Attribute::NoInline: 663 return bitc::ATTR_KIND_NO_INLINE; 664 case Attribute::NoRecurse: 665 return bitc::ATTR_KIND_NO_RECURSE; 666 case Attribute::NoMerge: 667 return bitc::ATTR_KIND_NO_MERGE; 668 case Attribute::NonLazyBind: 669 return bitc::ATTR_KIND_NON_LAZY_BIND; 670 case Attribute::NonNull: 671 return bitc::ATTR_KIND_NON_NULL; 672 case Attribute::Dereferenceable: 673 return bitc::ATTR_KIND_DEREFERENCEABLE; 674 case Attribute::DereferenceableOrNull: 675 return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL; 676 case Attribute::NoRedZone: 677 return bitc::ATTR_KIND_NO_RED_ZONE; 678 case Attribute::NoReturn: 679 return bitc::ATTR_KIND_NO_RETURN; 680 case Attribute::NoSync: 681 return bitc::ATTR_KIND_NOSYNC; 682 case Attribute::NoCfCheck: 683 return bitc::ATTR_KIND_NOCF_CHECK; 684 case Attribute::NoProfile: 685 return bitc::ATTR_KIND_NO_PROFILE; 686 case Attribute::NoUnwind: 687 return bitc::ATTR_KIND_NO_UNWIND; 688 case Attribute::NoSanitizeBounds: 689 return bitc::ATTR_KIND_NO_SANITIZE_BOUNDS; 690 case Attribute::NoSanitizeCoverage: 691 return bitc::ATTR_KIND_NO_SANITIZE_COVERAGE; 692 case Attribute::NullPointerIsValid: 693 return bitc::ATTR_KIND_NULL_POINTER_IS_VALID; 694 case Attribute::OptForFuzzing: 695 return bitc::ATTR_KIND_OPT_FOR_FUZZING; 696 case Attribute::OptimizeForSize: 697 return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE; 698 case Attribute::OptimizeNone: 699 return bitc::ATTR_KIND_OPTIMIZE_NONE; 700 case Attribute::ReadNone: 701 return bitc::ATTR_KIND_READ_NONE; 702 case Attribute::ReadOnly: 703 return bitc::ATTR_KIND_READ_ONLY; 704 case Attribute::Returned: 705 return bitc::ATTR_KIND_RETURNED; 706 case Attribute::ReturnsTwice: 707 return bitc::ATTR_KIND_RETURNS_TWICE; 708 case Attribute::SExt: 709 return bitc::ATTR_KIND_S_EXT; 710 case Attribute::Speculatable: 711 return bitc::ATTR_KIND_SPECULATABLE; 712 case Attribute::StackAlignment: 713 return bitc::ATTR_KIND_STACK_ALIGNMENT; 714 case Attribute::StackProtect: 715 return bitc::ATTR_KIND_STACK_PROTECT; 716 case Attribute::StackProtectReq: 717 return bitc::ATTR_KIND_STACK_PROTECT_REQ; 718 case Attribute::StackProtectStrong: 719 return bitc::ATTR_KIND_STACK_PROTECT_STRONG; 720 case Attribute::SafeStack: 721 return bitc::ATTR_KIND_SAFESTACK; 722 case Attribute::ShadowCallStack: 723 return bitc::ATTR_KIND_SHADOWCALLSTACK; 724 case Attribute::StrictFP: 725 return bitc::ATTR_KIND_STRICT_FP; 726 case Attribute::StructRet: 727 return bitc::ATTR_KIND_STRUCT_RET; 728 case Attribute::SanitizeAddress: 729 return bitc::ATTR_KIND_SANITIZE_ADDRESS; 730 case Attribute::SanitizeHWAddress: 731 return bitc::ATTR_KIND_SANITIZE_HWADDRESS; 732 case Attribute::SanitizeThread: 733 return bitc::ATTR_KIND_SANITIZE_THREAD; 734 case Attribute::SanitizeMemory: 735 return bitc::ATTR_KIND_SANITIZE_MEMORY; 736 case Attribute::SpeculativeLoadHardening: 737 return bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING; 738 case Attribute::SwiftError: 739 return bitc::ATTR_KIND_SWIFT_ERROR; 740 case Attribute::SwiftSelf: 741 return bitc::ATTR_KIND_SWIFT_SELF; 742 case Attribute::SwiftAsync: 743 return bitc::ATTR_KIND_SWIFT_ASYNC; 744 case Attribute::UWTable: 745 return bitc::ATTR_KIND_UW_TABLE; 746 case Attribute::VScaleRange: 747 return bitc::ATTR_KIND_VSCALE_RANGE; 748 case Attribute::WillReturn: 749 return bitc::ATTR_KIND_WILLRETURN; 750 case Attribute::WriteOnly: 751 return bitc::ATTR_KIND_WRITEONLY; 752 case Attribute::ZExt: 753 return bitc::ATTR_KIND_Z_EXT; 754 case Attribute::ImmArg: 755 return bitc::ATTR_KIND_IMMARG; 756 case Attribute::SanitizeMemTag: 757 return bitc::ATTR_KIND_SANITIZE_MEMTAG; 758 case Attribute::Preallocated: 759 return bitc::ATTR_KIND_PREALLOCATED; 760 case Attribute::NoUndef: 761 return bitc::ATTR_KIND_NOUNDEF; 762 case Attribute::ByRef: 763 return bitc::ATTR_KIND_BYREF; 764 case Attribute::MustProgress: 765 return bitc::ATTR_KIND_MUSTPROGRESS; 766 case Attribute::EndAttrKinds: 767 llvm_unreachable("Can not encode end-attribute kinds marker."); 768 case Attribute::None: 769 llvm_unreachable("Can not encode none-attribute."); 770 case Attribute::EmptyKey: 771 case Attribute::TombstoneKey: 772 llvm_unreachable("Trying to encode EmptyKey/TombstoneKey"); 773 } 774 775 llvm_unreachable("Trying to encode unknown attribute"); 776 } 777 778 void DXILBitcodeWriter::emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, 779 uint64_t V) { 780 if ((int64_t)V >= 0) 781 Vals.push_back(V << 1); 782 else 783 Vals.push_back((-V << 1) | 1); 784 } 785 786 void DXILBitcodeWriter::emitWideAPInt(SmallVectorImpl<uint64_t> &Vals, 787 const APInt &A) { 788 // We have an arbitrary precision integer value to write whose 789 // bit width is > 64. However, in canonical unsigned integer 790 // format it is likely that the high bits are going to be zero. 791 // So, we only write the number of active words. 792 unsigned NumWords = A.getActiveWords(); 793 const uint64_t *RawData = A.getRawData(); 794 for (unsigned i = 0; i < NumWords; i++) 795 emitSignedInt64(Vals, RawData[i]); 796 } 797 798 uint64_t DXILBitcodeWriter::getOptimizationFlags(const Value *V) { 799 uint64_t Flags = 0; 800 801 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) { 802 if (OBO->hasNoSignedWrap()) 803 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP; 804 if (OBO->hasNoUnsignedWrap()) 805 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP; 806 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) { 807 if (PEO->isExact()) 808 Flags |= 1 << bitc::PEO_EXACT; 809 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) { 810 if (FPMO->hasAllowReassoc()) 811 Flags |= bitc::AllowReassoc; 812 if (FPMO->hasNoNaNs()) 813 Flags |= bitc::NoNaNs; 814 if (FPMO->hasNoInfs()) 815 Flags |= bitc::NoInfs; 816 if (FPMO->hasNoSignedZeros()) 817 Flags |= bitc::NoSignedZeros; 818 if (FPMO->hasAllowReciprocal()) 819 Flags |= bitc::AllowReciprocal; 820 if (FPMO->hasAllowContract()) 821 Flags |= bitc::AllowContract; 822 if (FPMO->hasApproxFunc()) 823 Flags |= bitc::ApproxFunc; 824 } 825 826 return Flags; 827 } 828 829 unsigned 830 DXILBitcodeWriter::getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) { 831 switch (Linkage) { 832 case GlobalValue::ExternalLinkage: 833 return 0; 834 case GlobalValue::WeakAnyLinkage: 835 return 16; 836 case GlobalValue::AppendingLinkage: 837 return 2; 838 case GlobalValue::InternalLinkage: 839 return 3; 840 case GlobalValue::LinkOnceAnyLinkage: 841 return 18; 842 case GlobalValue::ExternalWeakLinkage: 843 return 7; 844 case GlobalValue::CommonLinkage: 845 return 8; 846 case GlobalValue::PrivateLinkage: 847 return 9; 848 case GlobalValue::WeakODRLinkage: 849 return 17; 850 case GlobalValue::LinkOnceODRLinkage: 851 return 19; 852 case GlobalValue::AvailableExternallyLinkage: 853 return 12; 854 } 855 llvm_unreachable("Invalid linkage"); 856 } 857 858 unsigned DXILBitcodeWriter::getEncodedLinkage(const GlobalValue &GV) { 859 return getEncodedLinkage(GV.getLinkage()); 860 } 861 862 unsigned DXILBitcodeWriter::getEncodedVisibility(const GlobalValue &GV) { 863 switch (GV.getVisibility()) { 864 case GlobalValue::DefaultVisibility: return 0; 865 case GlobalValue::HiddenVisibility: return 1; 866 case GlobalValue::ProtectedVisibility: return 2; 867 } 868 llvm_unreachable("Invalid visibility"); 869 } 870 871 unsigned DXILBitcodeWriter::getEncodedDLLStorageClass(const GlobalValue &GV) { 872 switch (GV.getDLLStorageClass()) { 873 case GlobalValue::DefaultStorageClass: return 0; 874 case GlobalValue::DLLImportStorageClass: return 1; 875 case GlobalValue::DLLExportStorageClass: return 2; 876 } 877 llvm_unreachable("Invalid DLL storage class"); 878 } 879 880 unsigned DXILBitcodeWriter::getEncodedThreadLocalMode(const GlobalValue &GV) { 881 switch (GV.getThreadLocalMode()) { 882 case GlobalVariable::NotThreadLocal: return 0; 883 case GlobalVariable::GeneralDynamicTLSModel: return 1; 884 case GlobalVariable::LocalDynamicTLSModel: return 2; 885 case GlobalVariable::InitialExecTLSModel: return 3; 886 case GlobalVariable::LocalExecTLSModel: return 4; 887 } 888 llvm_unreachable("Invalid TLS model"); 889 } 890 891 unsigned DXILBitcodeWriter::getEncodedComdatSelectionKind(const Comdat &C) { 892 switch (C.getSelectionKind()) { 893 case Comdat::Any: 894 return bitc::COMDAT_SELECTION_KIND_ANY; 895 case Comdat::ExactMatch: 896 return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH; 897 case Comdat::Largest: 898 return bitc::COMDAT_SELECTION_KIND_LARGEST; 899 case Comdat::NoDeduplicate: 900 return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES; 901 case Comdat::SameSize: 902 return bitc::COMDAT_SELECTION_KIND_SAME_SIZE; 903 } 904 llvm_unreachable("Invalid selection kind"); 905 } 906 907 //////////////////////////////////////////////////////////////////////////////// 908 /// Begin DXILBitcodeWriter Implementation 909 //////////////////////////////////////////////////////////////////////////////// 910 911 void DXILBitcodeWriter::writeAttributeGroupTable() { 912 const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps = 913 VE.getAttributeGroups(); 914 if (AttrGrps.empty()) 915 return; 916 917 Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3); 918 919 SmallVector<uint64_t, 64> Record; 920 for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) { 921 unsigned AttrListIndex = Pair.first; 922 AttributeSet AS = Pair.second; 923 Record.push_back(VE.getAttributeGroupID(Pair)); 924 Record.push_back(AttrListIndex); 925 926 for (Attribute Attr : AS) { 927 if (Attr.isEnumAttribute()) { 928 uint64_t Val = getAttrKindEncoding(Attr.getKindAsEnum()); 929 assert(Val <= bitc::ATTR_KIND_ARGMEMONLY && 930 "DXIL does not support attributes above ATTR_KIND_ARGMEMONLY"); 931 Record.push_back(0); 932 Record.push_back(Val); 933 } else if (Attr.isIntAttribute()) { 934 uint64_t Val = getAttrKindEncoding(Attr.getKindAsEnum()); 935 assert(Val <= bitc::ATTR_KIND_ARGMEMONLY && 936 "DXIL does not support attributes above ATTR_KIND_ARGMEMONLY"); 937 Record.push_back(1); 938 Record.push_back(Val); 939 Record.push_back(Attr.getValueAsInt()); 940 } else { 941 StringRef Kind = Attr.getKindAsString(); 942 StringRef Val = Attr.getValueAsString(); 943 944 Record.push_back(Val.empty() ? 3 : 4); 945 Record.append(Kind.begin(), Kind.end()); 946 Record.push_back(0); 947 if (!Val.empty()) { 948 Record.append(Val.begin(), Val.end()); 949 Record.push_back(0); 950 } 951 } 952 } 953 954 Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record); 955 Record.clear(); 956 } 957 958 Stream.ExitBlock(); 959 } 960 961 void DXILBitcodeWriter::writeAttributeTable() { 962 const std::vector<AttributeList> &Attrs = VE.getAttributeLists(); 963 if (Attrs.empty()) 964 return; 965 966 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3); 967 968 SmallVector<uint64_t, 64> Record; 969 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) { 970 AttributeList AL = Attrs[i]; 971 for (unsigned i : AL.indexes()) { 972 AttributeSet AS = AL.getAttributes(i); 973 if (AS.hasAttributes()) 974 Record.push_back(VE.getAttributeGroupID({i, AS})); 975 } 976 977 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record); 978 Record.clear(); 979 } 980 981 Stream.ExitBlock(); 982 } 983 984 /// WriteTypeTable - Write out the type table for a module. 985 void DXILBitcodeWriter::writeTypeTable() { 986 const ValueEnumerator::TypeList &TypeList = VE.getTypes(); 987 988 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */); 989 SmallVector<uint64_t, 64> TypeVals; 990 991 uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies(); 992 993 // Abbrev for TYPE_CODE_POINTER. 994 auto Abbv = std::make_shared<BitCodeAbbrev>(); 995 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER)); 996 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 997 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0 998 unsigned PtrAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 999 1000 // Abbrev for TYPE_CODE_FUNCTION. 1001 Abbv = std::make_shared<BitCodeAbbrev>(); 1002 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION)); 1003 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg 1004 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1005 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 1006 unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 1007 1008 // Abbrev for TYPE_CODE_STRUCT_ANON. 1009 Abbv = std::make_shared<BitCodeAbbrev>(); 1010 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON)); 1011 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked 1012 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1013 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 1014 unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 1015 1016 // Abbrev for TYPE_CODE_STRUCT_NAME. 1017 Abbv = std::make_shared<BitCodeAbbrev>(); 1018 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME)); 1019 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1020 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 1021 unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 1022 1023 // Abbrev for TYPE_CODE_STRUCT_NAMED. 1024 Abbv = std::make_shared<BitCodeAbbrev>(); 1025 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED)); 1026 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked 1027 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1028 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 1029 unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 1030 1031 // Abbrev for TYPE_CODE_ARRAY. 1032 Abbv = std::make_shared<BitCodeAbbrev>(); 1033 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY)); 1034 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size 1035 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 1036 unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 1037 1038 // Emit an entry count so the reader can reserve space. 1039 TypeVals.push_back(TypeList.size()); 1040 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals); 1041 TypeVals.clear(); 1042 1043 // Loop over all of the types, emitting each in turn. 1044 for (Type *T : TypeList) { 1045 int AbbrevToUse = 0; 1046 unsigned Code = 0; 1047 1048 switch (T->getTypeID()) { 1049 case Type::BFloatTyID: 1050 case Type::X86_AMXTyID: 1051 case Type::TokenTyID: 1052 llvm_unreachable("These should never be used!!!"); 1053 break; 1054 case Type::VoidTyID: 1055 Code = bitc::TYPE_CODE_VOID; 1056 break; 1057 case Type::HalfTyID: 1058 Code = bitc::TYPE_CODE_HALF; 1059 break; 1060 case Type::FloatTyID: 1061 Code = bitc::TYPE_CODE_FLOAT; 1062 break; 1063 case Type::DoubleTyID: 1064 Code = bitc::TYPE_CODE_DOUBLE; 1065 break; 1066 case Type::X86_FP80TyID: 1067 Code = bitc::TYPE_CODE_X86_FP80; 1068 break; 1069 case Type::FP128TyID: 1070 Code = bitc::TYPE_CODE_FP128; 1071 break; 1072 case Type::PPC_FP128TyID: 1073 Code = bitc::TYPE_CODE_PPC_FP128; 1074 break; 1075 case Type::LabelTyID: 1076 Code = bitc::TYPE_CODE_LABEL; 1077 break; 1078 case Type::MetadataTyID: 1079 Code = bitc::TYPE_CODE_METADATA; 1080 break; 1081 case Type::X86_MMXTyID: 1082 Code = bitc::TYPE_CODE_X86_MMX; 1083 break; 1084 case Type::IntegerTyID: 1085 // INTEGER: [width] 1086 Code = bitc::TYPE_CODE_INTEGER; 1087 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth()); 1088 break; 1089 case Type::PointerTyID: { 1090 PointerType *PTy = cast<PointerType>(T); 1091 // POINTER: [pointee type, address space] 1092 Code = bitc::TYPE_CODE_POINTER; 1093 TypeVals.push_back(VE.getTypeID(PTy->getNonOpaquePointerElementType())); 1094 unsigned AddressSpace = PTy->getAddressSpace(); 1095 TypeVals.push_back(AddressSpace); 1096 if (AddressSpace == 0) 1097 AbbrevToUse = PtrAbbrev; 1098 break; 1099 } 1100 case Type::FunctionTyID: { 1101 FunctionType *FT = cast<FunctionType>(T); 1102 // FUNCTION: [isvararg, retty, paramty x N] 1103 Code = bitc::TYPE_CODE_FUNCTION; 1104 TypeVals.push_back(FT->isVarArg()); 1105 TypeVals.push_back(VE.getTypeID(FT->getReturnType())); 1106 for (Type *PTy : FT->params()) 1107 TypeVals.push_back(VE.getTypeID(PTy)); 1108 AbbrevToUse = FunctionAbbrev; 1109 break; 1110 } 1111 case Type::StructTyID: { 1112 StructType *ST = cast<StructType>(T); 1113 // STRUCT: [ispacked, eltty x N] 1114 TypeVals.push_back(ST->isPacked()); 1115 // Output all of the element types. 1116 for (Type *ElTy : ST->elements()) 1117 TypeVals.push_back(VE.getTypeID(ElTy)); 1118 1119 if (ST->isLiteral()) { 1120 Code = bitc::TYPE_CODE_STRUCT_ANON; 1121 AbbrevToUse = StructAnonAbbrev; 1122 } else { 1123 if (ST->isOpaque()) { 1124 Code = bitc::TYPE_CODE_OPAQUE; 1125 } else { 1126 Code = bitc::TYPE_CODE_STRUCT_NAMED; 1127 AbbrevToUse = StructNamedAbbrev; 1128 } 1129 1130 // Emit the name if it is present. 1131 if (!ST->getName().empty()) 1132 writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, ST->getName(), 1133 StructNameAbbrev); 1134 } 1135 break; 1136 } 1137 case Type::ArrayTyID: { 1138 ArrayType *AT = cast<ArrayType>(T); 1139 // ARRAY: [numelts, eltty] 1140 Code = bitc::TYPE_CODE_ARRAY; 1141 TypeVals.push_back(AT->getNumElements()); 1142 TypeVals.push_back(VE.getTypeID(AT->getElementType())); 1143 AbbrevToUse = ArrayAbbrev; 1144 break; 1145 } 1146 case Type::FixedVectorTyID: 1147 case Type::ScalableVectorTyID: { 1148 VectorType *VT = cast<VectorType>(T); 1149 // VECTOR [numelts, eltty] 1150 Code = bitc::TYPE_CODE_VECTOR; 1151 TypeVals.push_back(VT->getElementCount().getKnownMinValue()); 1152 TypeVals.push_back(VE.getTypeID(VT->getElementType())); 1153 break; 1154 } 1155 } 1156 1157 // Emit the finished record. 1158 Stream.EmitRecord(Code, TypeVals, AbbrevToUse); 1159 TypeVals.clear(); 1160 } 1161 1162 Stream.ExitBlock(); 1163 } 1164 1165 void DXILBitcodeWriter::writeComdats() { 1166 SmallVector<uint16_t, 64> Vals; 1167 for (const Comdat *C : VE.getComdats()) { 1168 // COMDAT: [selection_kind, name] 1169 Vals.push_back(getEncodedComdatSelectionKind(*C)); 1170 size_t Size = C->getName().size(); 1171 assert(isUInt<16>(Size)); 1172 Vals.push_back(Size); 1173 for (char Chr : C->getName()) 1174 Vals.push_back((unsigned char)Chr); 1175 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0); 1176 Vals.clear(); 1177 } 1178 } 1179 1180 void DXILBitcodeWriter::writeValueSymbolTableForwardDecl() {} 1181 1182 /// Emit top-level description of module, including target triple, inline asm, 1183 /// descriptors for global variables, and function prototype info. 1184 /// Returns the bit offset to backpatch with the location of the real VST. 1185 void DXILBitcodeWriter::writeModuleInfo() { 1186 // Emit various pieces of data attached to a module. 1187 if (!M.getTargetTriple().empty()) 1188 writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(), 1189 0 /*TODO*/); 1190 const std::string &DL = M.getDataLayoutStr(); 1191 if (!DL.empty()) 1192 writeStringRecord(Stream, bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/); 1193 if (!M.getModuleInlineAsm().empty()) 1194 writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(), 1195 0 /*TODO*/); 1196 1197 // Emit information about sections and GC, computing how many there are. Also 1198 // compute the maximum alignment value. 1199 std::map<std::string, unsigned> SectionMap; 1200 std::map<std::string, unsigned> GCMap; 1201 MaybeAlign MaxAlignment; 1202 unsigned MaxGlobalType = 0; 1203 const auto UpdateMaxAlignment = [&MaxAlignment](const MaybeAlign A) { 1204 if (A) 1205 MaxAlignment = !MaxAlignment ? *A : std::max(*MaxAlignment, *A); 1206 }; 1207 for (const GlobalVariable &GV : M.globals()) { 1208 UpdateMaxAlignment(GV.getAlign()); 1209 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType())); 1210 if (GV.hasSection()) { 1211 // Give section names unique ID's. 1212 unsigned &Entry = SectionMap[std::string(GV.getSection())]; 1213 if (!Entry) { 1214 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, 1215 GV.getSection(), 0 /*TODO*/); 1216 Entry = SectionMap.size(); 1217 } 1218 } 1219 } 1220 for (const Function &F : M) { 1221 UpdateMaxAlignment(F.getAlign()); 1222 if (F.hasSection()) { 1223 // Give section names unique ID's. 1224 unsigned &Entry = SectionMap[std::string(F.getSection())]; 1225 if (!Entry) { 1226 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, F.getSection(), 1227 0 /*TODO*/); 1228 Entry = SectionMap.size(); 1229 } 1230 } 1231 if (F.hasGC()) { 1232 // Same for GC names. 1233 unsigned &Entry = GCMap[F.getGC()]; 1234 if (!Entry) { 1235 writeStringRecord(Stream, bitc::MODULE_CODE_GCNAME, F.getGC(), 1236 0 /*TODO*/); 1237 Entry = GCMap.size(); 1238 } 1239 } 1240 } 1241 1242 // Emit abbrev for globals, now that we know # sections and max alignment. 1243 unsigned SimpleGVarAbbrev = 0; 1244 if (!M.global_empty()) { 1245 // Add an abbrev for common globals with no visibility or thread localness. 1246 auto Abbv = std::make_shared<BitCodeAbbrev>(); 1247 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR)); 1248 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1249 Log2_32_Ceil(MaxGlobalType + 1))); 1250 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2 1251 //| explicitType << 1 1252 //| constant 1253 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer. 1254 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage. 1255 if (MaxAlignment == 0) // Alignment. 1256 Abbv->Add(BitCodeAbbrevOp(0)); 1257 else { 1258 unsigned MaxEncAlignment = getEncodedAlign(MaxAlignment); 1259 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1260 Log2_32_Ceil(MaxEncAlignment + 1))); 1261 } 1262 if (SectionMap.empty()) // Section. 1263 Abbv->Add(BitCodeAbbrevOp(0)); 1264 else 1265 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1266 Log2_32_Ceil(SectionMap.size() + 1))); 1267 // Don't bother emitting vis + thread local. 1268 SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 1269 } 1270 1271 // Emit the global variable information. 1272 SmallVector<unsigned, 64> Vals; 1273 for (const GlobalVariable &GV : M.globals()) { 1274 unsigned AbbrevToUse = 0; 1275 1276 // GLOBALVAR: [type, isconst, initid, 1277 // linkage, alignment, section, visibility, threadlocal, 1278 // unnamed_addr, externally_initialized, dllstorageclass, 1279 // comdat] 1280 Vals.push_back(VE.getTypeID(GV.getValueType())); 1281 Vals.push_back( 1282 GV.getType()->getAddressSpace() << 2 | 2 | 1283 (GV.isConstant() ? 1 : 0)); // HLSL Change - bitwise | was used with 1284 // unsigned int and bool 1285 Vals.push_back( 1286 GV.isDeclaration() ? 0 : (VE.getValueID(GV.getInitializer()) + 1)); 1287 Vals.push_back(getEncodedLinkage(GV)); 1288 Vals.push_back(getEncodedAlign(GV.getAlign())); 1289 Vals.push_back(GV.hasSection() ? SectionMap[std::string(GV.getSection())] 1290 : 0); 1291 if (GV.isThreadLocal() || 1292 GV.getVisibility() != GlobalValue::DefaultVisibility || 1293 GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None || 1294 GV.isExternallyInitialized() || 1295 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass || 1296 GV.hasComdat()) { 1297 Vals.push_back(getEncodedVisibility(GV)); 1298 Vals.push_back(getEncodedThreadLocalMode(GV)); 1299 Vals.push_back(GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None); 1300 Vals.push_back(GV.isExternallyInitialized()); 1301 Vals.push_back(getEncodedDLLStorageClass(GV)); 1302 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0); 1303 } else { 1304 AbbrevToUse = SimpleGVarAbbrev; 1305 } 1306 1307 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse); 1308 Vals.clear(); 1309 } 1310 1311 // Emit the function proto information. 1312 for (const Function &F : M) { 1313 // FUNCTION: [type, callingconv, isproto, linkage, paramattrs, alignment, 1314 // section, visibility, gc, unnamed_addr, prologuedata, 1315 // dllstorageclass, comdat, prefixdata, personalityfn] 1316 Vals.push_back(VE.getTypeID(F.getFunctionType())); 1317 Vals.push_back(F.getCallingConv()); 1318 Vals.push_back(F.isDeclaration()); 1319 Vals.push_back(getEncodedLinkage(F)); 1320 Vals.push_back(VE.getAttributeListID(F.getAttributes())); 1321 Vals.push_back(getEncodedAlign(F.getAlign())); 1322 Vals.push_back(F.hasSection() ? SectionMap[std::string(F.getSection())] 1323 : 0); 1324 Vals.push_back(getEncodedVisibility(F)); 1325 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0); 1326 Vals.push_back(F.getUnnamedAddr() != GlobalValue::UnnamedAddr::None); 1327 Vals.push_back( 1328 F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1) : 0); 1329 Vals.push_back(getEncodedDLLStorageClass(F)); 1330 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0); 1331 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1) 1332 : 0); 1333 Vals.push_back( 1334 F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0); 1335 1336 unsigned AbbrevToUse = 0; 1337 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse); 1338 Vals.clear(); 1339 } 1340 1341 // Emit the alias information. 1342 for (const GlobalAlias &A : M.aliases()) { 1343 // ALIAS: [alias type, aliasee val#, linkage, visibility] 1344 Vals.push_back(VE.getTypeID(A.getValueType())); 1345 Vals.push_back(VE.getValueID(A.getAliasee())); 1346 Vals.push_back(getEncodedLinkage(A)); 1347 Vals.push_back(getEncodedVisibility(A)); 1348 Vals.push_back(getEncodedDLLStorageClass(A)); 1349 Vals.push_back(getEncodedThreadLocalMode(A)); 1350 Vals.push_back(A.getUnnamedAddr() != GlobalValue::UnnamedAddr::None); 1351 unsigned AbbrevToUse = 0; 1352 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS_OLD, Vals, AbbrevToUse); 1353 Vals.clear(); 1354 } 1355 } 1356 1357 void DXILBitcodeWriter::writeValueAsMetadata( 1358 const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) { 1359 // Mimic an MDNode with a value as one operand. 1360 Value *V = MD->getValue(); 1361 Record.push_back(VE.getTypeID(V->getType())); 1362 Record.push_back(VE.getValueID(V)); 1363 Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0); 1364 Record.clear(); 1365 } 1366 1367 void DXILBitcodeWriter::writeMDTuple(const MDTuple *N, 1368 SmallVectorImpl<uint64_t> &Record, 1369 unsigned Abbrev) { 1370 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 1371 Metadata *MD = N->getOperand(i); 1372 assert(!(MD && isa<LocalAsMetadata>(MD)) && 1373 "Unexpected function-local metadata"); 1374 Record.push_back(VE.getMetadataOrNullID(MD)); 1375 } 1376 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE 1377 : bitc::METADATA_NODE, 1378 Record, Abbrev); 1379 Record.clear(); 1380 } 1381 1382 void DXILBitcodeWriter::writeDILocation(const DILocation *N, 1383 SmallVectorImpl<uint64_t> &Record, 1384 unsigned &Abbrev) { 1385 if (!Abbrev) 1386 Abbrev = createDILocationAbbrev(); 1387 Record.push_back(N->isDistinct()); 1388 Record.push_back(N->getLine()); 1389 Record.push_back(N->getColumn()); 1390 Record.push_back(VE.getMetadataID(N->getScope())); 1391 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt())); 1392 1393 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev); 1394 Record.clear(); 1395 } 1396 1397 static uint64_t rotateSign(APInt Val) { 1398 int64_t I = Val.getSExtValue(); 1399 uint64_t U = I; 1400 return I < 0 ? ~(U << 1) : U << 1; 1401 } 1402 1403 static uint64_t rotateSign(DISubrange::BoundType Val) { 1404 return rotateSign(Val.get<ConstantInt *>()->getValue()); 1405 } 1406 1407 void DXILBitcodeWriter::writeDISubrange(const DISubrange *N, 1408 SmallVectorImpl<uint64_t> &Record, 1409 unsigned Abbrev) { 1410 Record.push_back(N->isDistinct()); 1411 Record.push_back( 1412 N->getCount().get<ConstantInt *>()->getValue().getSExtValue()); 1413 Record.push_back(rotateSign(N->getLowerBound())); 1414 1415 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev); 1416 Record.clear(); 1417 } 1418 1419 void DXILBitcodeWriter::writeDIEnumerator(const DIEnumerator *N, 1420 SmallVectorImpl<uint64_t> &Record, 1421 unsigned Abbrev) { 1422 Record.push_back(N->isDistinct()); 1423 Record.push_back(rotateSign(N->getValue())); 1424 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1425 1426 Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev); 1427 Record.clear(); 1428 } 1429 1430 void DXILBitcodeWriter::writeDIBasicType(const DIBasicType *N, 1431 SmallVectorImpl<uint64_t> &Record, 1432 unsigned Abbrev) { 1433 Record.push_back(N->isDistinct()); 1434 Record.push_back(N->getTag()); 1435 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1436 Record.push_back(N->getSizeInBits()); 1437 Record.push_back(N->getAlignInBits()); 1438 Record.push_back(N->getEncoding()); 1439 1440 Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev); 1441 Record.clear(); 1442 } 1443 1444 void DXILBitcodeWriter::writeDIDerivedType(const DIDerivedType *N, 1445 SmallVectorImpl<uint64_t> &Record, 1446 unsigned Abbrev) { 1447 Record.push_back(N->isDistinct()); 1448 Record.push_back(N->getTag()); 1449 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1450 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1451 Record.push_back(N->getLine()); 1452 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1453 Record.push_back(VE.getMetadataOrNullID(N->getBaseType())); 1454 Record.push_back(N->getSizeInBits()); 1455 Record.push_back(N->getAlignInBits()); 1456 Record.push_back(N->getOffsetInBits()); 1457 Record.push_back(N->getFlags()); 1458 Record.push_back(VE.getMetadataOrNullID(N->getExtraData())); 1459 1460 Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev); 1461 Record.clear(); 1462 } 1463 1464 void DXILBitcodeWriter::writeDICompositeType(const DICompositeType *N, 1465 SmallVectorImpl<uint64_t> &Record, 1466 unsigned Abbrev) { 1467 Record.push_back(N->isDistinct()); 1468 Record.push_back(N->getTag()); 1469 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1470 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1471 Record.push_back(N->getLine()); 1472 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1473 Record.push_back(VE.getMetadataOrNullID(N->getBaseType())); 1474 Record.push_back(N->getSizeInBits()); 1475 Record.push_back(N->getAlignInBits()); 1476 Record.push_back(N->getOffsetInBits()); 1477 Record.push_back(N->getFlags()); 1478 Record.push_back(VE.getMetadataOrNullID(N->getElements().get())); 1479 Record.push_back(N->getRuntimeLang()); 1480 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder())); 1481 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get())); 1482 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier())); 1483 1484 Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev); 1485 Record.clear(); 1486 } 1487 1488 void DXILBitcodeWriter::writeDISubroutineType(const DISubroutineType *N, 1489 SmallVectorImpl<uint64_t> &Record, 1490 unsigned Abbrev) { 1491 Record.push_back(N->isDistinct()); 1492 Record.push_back(N->getFlags()); 1493 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get())); 1494 1495 Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev); 1496 Record.clear(); 1497 } 1498 1499 void DXILBitcodeWriter::writeDIFile(const DIFile *N, 1500 SmallVectorImpl<uint64_t> &Record, 1501 unsigned Abbrev) { 1502 Record.push_back(N->isDistinct()); 1503 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename())); 1504 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory())); 1505 1506 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev); 1507 Record.clear(); 1508 } 1509 1510 void DXILBitcodeWriter::writeDICompileUnit(const DICompileUnit *N, 1511 SmallVectorImpl<uint64_t> &Record, 1512 unsigned Abbrev) { 1513 Record.push_back(N->isDistinct()); 1514 Record.push_back(N->getSourceLanguage()); 1515 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1516 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer())); 1517 Record.push_back(N->isOptimized()); 1518 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags())); 1519 Record.push_back(N->getRuntimeVersion()); 1520 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename())); 1521 Record.push_back(N->getEmissionKind()); 1522 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get())); 1523 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get())); 1524 Record.push_back(/* subprograms */ 0); 1525 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get())); 1526 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get())); 1527 Record.push_back(N->getDWOId()); 1528 1529 Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev); 1530 Record.clear(); 1531 } 1532 1533 void DXILBitcodeWriter::writeDISubprogram(const DISubprogram *N, 1534 SmallVectorImpl<uint64_t> &Record, 1535 unsigned Abbrev) { 1536 Record.push_back(N->isDistinct()); 1537 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1538 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1539 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName())); 1540 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1541 Record.push_back(N->getLine()); 1542 Record.push_back(VE.getMetadataOrNullID(N->getType())); 1543 Record.push_back(N->isLocalToUnit()); 1544 Record.push_back(N->isDefinition()); 1545 Record.push_back(N->getScopeLine()); 1546 Record.push_back(VE.getMetadataOrNullID(N->getContainingType())); 1547 Record.push_back(N->getVirtuality()); 1548 Record.push_back(N->getVirtualIndex()); 1549 Record.push_back(N->getFlags()); 1550 Record.push_back(N->isOptimized()); 1551 Record.push_back(VE.getMetadataOrNullID(N->getRawUnit())); 1552 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get())); 1553 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration())); 1554 Record.push_back(VE.getMetadataOrNullID(N->getRetainedNodes().get())); 1555 1556 Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev); 1557 Record.clear(); 1558 } 1559 1560 void DXILBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N, 1561 SmallVectorImpl<uint64_t> &Record, 1562 unsigned Abbrev) { 1563 Record.push_back(N->isDistinct()); 1564 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1565 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1566 Record.push_back(N->getLine()); 1567 Record.push_back(N->getColumn()); 1568 1569 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev); 1570 Record.clear(); 1571 } 1572 1573 void DXILBitcodeWriter::writeDILexicalBlockFile( 1574 const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record, 1575 unsigned Abbrev) { 1576 Record.push_back(N->isDistinct()); 1577 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1578 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1579 Record.push_back(N->getDiscriminator()); 1580 1581 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev); 1582 Record.clear(); 1583 } 1584 1585 void DXILBitcodeWriter::writeDINamespace(const DINamespace *N, 1586 SmallVectorImpl<uint64_t> &Record, 1587 unsigned Abbrev) { 1588 Record.push_back(N->isDistinct()); 1589 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1590 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1591 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1592 Record.push_back(/* line number */ 0); 1593 1594 Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev); 1595 Record.clear(); 1596 } 1597 1598 void DXILBitcodeWriter::writeDIModule(const DIModule *N, 1599 SmallVectorImpl<uint64_t> &Record, 1600 unsigned Abbrev) { 1601 Record.push_back(N->isDistinct()); 1602 for (auto &I : N->operands()) 1603 Record.push_back(VE.getMetadataOrNullID(I)); 1604 1605 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev); 1606 Record.clear(); 1607 } 1608 1609 void DXILBitcodeWriter::writeDITemplateTypeParameter( 1610 const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record, 1611 unsigned Abbrev) { 1612 Record.push_back(N->isDistinct()); 1613 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1614 Record.push_back(VE.getMetadataOrNullID(N->getType())); 1615 1616 Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev); 1617 Record.clear(); 1618 } 1619 1620 void DXILBitcodeWriter::writeDITemplateValueParameter( 1621 const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record, 1622 unsigned Abbrev) { 1623 Record.push_back(N->isDistinct()); 1624 Record.push_back(N->getTag()); 1625 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1626 Record.push_back(VE.getMetadataOrNullID(N->getType())); 1627 Record.push_back(VE.getMetadataOrNullID(N->getValue())); 1628 1629 Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev); 1630 Record.clear(); 1631 } 1632 1633 void DXILBitcodeWriter::writeDIGlobalVariable(const DIGlobalVariable *N, 1634 SmallVectorImpl<uint64_t> &Record, 1635 unsigned Abbrev) { 1636 Record.push_back(N->isDistinct()); 1637 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1638 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1639 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName())); 1640 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1641 Record.push_back(N->getLine()); 1642 Record.push_back(VE.getMetadataOrNullID(N->getType())); 1643 Record.push_back(N->isLocalToUnit()); 1644 Record.push_back(N->isDefinition()); 1645 Record.push_back(/* N->getRawVariable() */ 0); 1646 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration())); 1647 1648 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev); 1649 Record.clear(); 1650 } 1651 1652 void DXILBitcodeWriter::writeDILocalVariable(const DILocalVariable *N, 1653 SmallVectorImpl<uint64_t> &Record, 1654 unsigned Abbrev) { 1655 Record.push_back(N->isDistinct()); 1656 Record.push_back(N->getTag()); 1657 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1658 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1659 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1660 Record.push_back(N->getLine()); 1661 Record.push_back(VE.getMetadataOrNullID(N->getType())); 1662 Record.push_back(N->getArg()); 1663 Record.push_back(N->getFlags()); 1664 1665 Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev); 1666 Record.clear(); 1667 } 1668 1669 void DXILBitcodeWriter::writeDIExpression(const DIExpression *N, 1670 SmallVectorImpl<uint64_t> &Record, 1671 unsigned Abbrev) { 1672 Record.reserve(N->getElements().size() + 1); 1673 1674 Record.push_back(N->isDistinct()); 1675 Record.append(N->elements_begin(), N->elements_end()); 1676 1677 Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev); 1678 Record.clear(); 1679 } 1680 1681 void DXILBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N, 1682 SmallVectorImpl<uint64_t> &Record, 1683 unsigned Abbrev) { 1684 llvm_unreachable("DXIL does not support objc!!!"); 1685 } 1686 1687 void DXILBitcodeWriter::writeDIImportedEntity(const DIImportedEntity *N, 1688 SmallVectorImpl<uint64_t> &Record, 1689 unsigned Abbrev) { 1690 Record.push_back(N->isDistinct()); 1691 Record.push_back(N->getTag()); 1692 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1693 Record.push_back(VE.getMetadataOrNullID(N->getEntity())); 1694 Record.push_back(N->getLine()); 1695 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1696 1697 Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev); 1698 Record.clear(); 1699 } 1700 1701 unsigned DXILBitcodeWriter::createDILocationAbbrev() { 1702 // Abbrev for METADATA_LOCATION. 1703 // 1704 // Assume the column is usually under 128, and always output the inlined-at 1705 // location (it's never more expensive than building an array size 1). 1706 std::shared_ptr<BitCodeAbbrev> Abbv = std::make_shared<BitCodeAbbrev>(); 1707 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION)); 1708 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); 1709 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1710 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 1711 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1712 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1713 return Stream.EmitAbbrev(std::move(Abbv)); 1714 } 1715 1716 unsigned DXILBitcodeWriter::createGenericDINodeAbbrev() { 1717 // Abbrev for METADATA_GENERIC_DEBUG. 1718 // 1719 // Assume the column is usually under 128, and always output the inlined-at 1720 // location (it's never more expensive than building an array size 1). 1721 std::shared_ptr<BitCodeAbbrev> Abbv = std::make_shared<BitCodeAbbrev>(); 1722 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG)); 1723 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); 1724 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1725 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); 1726 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1727 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1728 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1729 return Stream.EmitAbbrev(std::move(Abbv)); 1730 } 1731 1732 void DXILBitcodeWriter::writeMetadataRecords(ArrayRef<const Metadata *> MDs, 1733 SmallVectorImpl<uint64_t> &Record, 1734 std::vector<unsigned> *MDAbbrevs, 1735 std::vector<uint64_t> *IndexPos) { 1736 if (MDs.empty()) 1737 return; 1738 1739 // Initialize MDNode abbreviations. 1740 #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0; 1741 #include "llvm/IR/Metadata.def" 1742 1743 for (const Metadata *MD : MDs) { 1744 if (IndexPos) 1745 IndexPos->push_back(Stream.GetCurrentBitNo()); 1746 if (const MDNode *N = dyn_cast<MDNode>(MD)) { 1747 assert(N->isResolved() && "Expected forward references to be resolved"); 1748 1749 switch (N->getMetadataID()) { 1750 default: 1751 llvm_unreachable("Invalid MDNode subclass"); 1752 #define HANDLE_MDNODE_LEAF(CLASS) \ 1753 case Metadata::CLASS##Kind: \ 1754 if (MDAbbrevs) \ 1755 write##CLASS(cast<CLASS>(N), Record, \ 1756 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \ 1757 else \ 1758 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \ 1759 continue; 1760 #include "llvm/IR/Metadata.def" 1761 } 1762 } 1763 writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record); 1764 } 1765 } 1766 1767 unsigned DXILBitcodeWriter::createMetadataStringsAbbrev() { 1768 auto Abbv = std::make_shared<BitCodeAbbrev>(); 1769 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING_OLD)); 1770 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1771 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 1772 return Stream.EmitAbbrev(std::move(Abbv)); 1773 } 1774 1775 void DXILBitcodeWriter::writeMetadataStrings( 1776 ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) { 1777 for (const Metadata *MD : Strings) { 1778 const MDString *MDS = cast<MDString>(MD); 1779 // Code: [strchar x N] 1780 Record.append(MDS->bytes_begin(), MDS->bytes_end()); 1781 1782 // Emit the finished record. 1783 Stream.EmitRecord(bitc::METADATA_STRING_OLD, Record, 1784 createMetadataStringsAbbrev()); 1785 Record.clear(); 1786 } 1787 } 1788 1789 void DXILBitcodeWriter::writeModuleMetadata() { 1790 if (!VE.hasMDs() && M.named_metadata_empty()) 1791 return; 1792 1793 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 5); 1794 1795 // Emit all abbrevs upfront, so that the reader can jump in the middle of the 1796 // block and load any metadata. 1797 std::vector<unsigned> MDAbbrevs; 1798 1799 MDAbbrevs.resize(MetadataAbbrev::LastPlusOne); 1800 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev(); 1801 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] = 1802 createGenericDINodeAbbrev(); 1803 1804 unsigned NameAbbrev = 0; 1805 if (!M.named_metadata_empty()) { 1806 // Abbrev for METADATA_NAME. 1807 std::shared_ptr<BitCodeAbbrev> Abbv = std::make_shared<BitCodeAbbrev>(); 1808 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME)); 1809 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1810 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 1811 NameAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 1812 } 1813 1814 SmallVector<uint64_t, 64> Record; 1815 writeMetadataStrings(VE.getMDStrings(), Record); 1816 1817 std::vector<uint64_t> IndexPos; 1818 IndexPos.reserve(VE.getNonMDStrings().size()); 1819 writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos); 1820 1821 // Write named metadata. 1822 for (const NamedMDNode &NMD : M.named_metadata()) { 1823 // Write name. 1824 StringRef Str = NMD.getName(); 1825 Record.append(Str.bytes_begin(), Str.bytes_end()); 1826 Stream.EmitRecord(bitc::METADATA_NAME, Record, NameAbbrev); 1827 Record.clear(); 1828 1829 // Write named metadata operands. 1830 for (const MDNode *N : NMD.operands()) 1831 Record.push_back(VE.getMetadataID(N)); 1832 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0); 1833 Record.clear(); 1834 } 1835 1836 Stream.ExitBlock(); 1837 } 1838 1839 void DXILBitcodeWriter::writeFunctionMetadata(const Function &F) { 1840 if (!VE.hasMDs()) 1841 return; 1842 1843 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 4); 1844 SmallVector<uint64_t, 64> Record; 1845 writeMetadataStrings(VE.getMDStrings(), Record); 1846 writeMetadataRecords(VE.getNonMDStrings(), Record); 1847 Stream.ExitBlock(); 1848 } 1849 1850 void DXILBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) { 1851 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3); 1852 1853 SmallVector<uint64_t, 64> Record; 1854 1855 // Write metadata attachments 1856 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]] 1857 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 1858 F.getAllMetadata(MDs); 1859 if (!MDs.empty()) { 1860 for (const auto &I : MDs) { 1861 Record.push_back(I.first); 1862 Record.push_back(VE.getMetadataID(I.second)); 1863 } 1864 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0); 1865 Record.clear(); 1866 } 1867 1868 for (const BasicBlock &BB : F) 1869 for (const Instruction &I : BB) { 1870 MDs.clear(); 1871 I.getAllMetadataOtherThanDebugLoc(MDs); 1872 1873 // If no metadata, ignore instruction. 1874 if (MDs.empty()) 1875 continue; 1876 1877 Record.push_back(VE.getInstructionID(&I)); 1878 1879 for (unsigned i = 0, e = MDs.size(); i != e; ++i) { 1880 Record.push_back(MDs[i].first); 1881 Record.push_back(VE.getMetadataID(MDs[i].second)); 1882 } 1883 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0); 1884 Record.clear(); 1885 } 1886 1887 Stream.ExitBlock(); 1888 } 1889 1890 void DXILBitcodeWriter::writeModuleMetadataKinds() { 1891 SmallVector<uint64_t, 64> Record; 1892 1893 // Write metadata kinds 1894 // METADATA_KIND - [n x [id, name]] 1895 SmallVector<StringRef, 8> Names; 1896 M.getMDKindNames(Names); 1897 1898 if (Names.empty()) 1899 return; 1900 1901 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3); 1902 1903 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) { 1904 Record.push_back(MDKindID); 1905 StringRef KName = Names[MDKindID]; 1906 Record.append(KName.begin(), KName.end()); 1907 1908 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0); 1909 Record.clear(); 1910 } 1911 1912 Stream.ExitBlock(); 1913 } 1914 1915 void DXILBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal, 1916 bool isGlobal) { 1917 if (FirstVal == LastVal) 1918 return; 1919 1920 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4); 1921 1922 unsigned AggregateAbbrev = 0; 1923 unsigned String8Abbrev = 0; 1924 unsigned CString7Abbrev = 0; 1925 unsigned CString6Abbrev = 0; 1926 // If this is a constant pool for the module, emit module-specific abbrevs. 1927 if (isGlobal) { 1928 // Abbrev for CST_CODE_AGGREGATE. 1929 auto Abbv = std::make_shared<BitCodeAbbrev>(); 1930 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE)); 1931 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1932 Abbv->Add( 1933 BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal + 1))); 1934 AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 1935 1936 // Abbrev for CST_CODE_STRING. 1937 Abbv = std::make_shared<BitCodeAbbrev>(); 1938 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING)); 1939 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1940 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 1941 String8Abbrev = Stream.EmitAbbrev(std::move(Abbv)); 1942 // Abbrev for CST_CODE_CSTRING. 1943 Abbv = std::make_shared<BitCodeAbbrev>(); 1944 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING)); 1945 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1946 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); 1947 CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv)); 1948 // Abbrev for CST_CODE_CSTRING. 1949 Abbv = std::make_shared<BitCodeAbbrev>(); 1950 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING)); 1951 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1952 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 1953 CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv)); 1954 } 1955 1956 SmallVector<uint64_t, 64> Record; 1957 1958 const ValueEnumerator::ValueList &Vals = VE.getValues(); 1959 Type *LastTy = nullptr; 1960 for (unsigned i = FirstVal; i != LastVal; ++i) { 1961 const Value *V = Vals[i].first; 1962 // If we need to switch types, do so now. 1963 if (V->getType() != LastTy) { 1964 LastTy = V->getType(); 1965 Record.push_back(VE.getTypeID(LastTy)); 1966 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record, 1967 CONSTANTS_SETTYPE_ABBREV); 1968 Record.clear(); 1969 } 1970 1971 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) { 1972 Record.push_back(unsigned(IA->hasSideEffects()) | 1973 unsigned(IA->isAlignStack()) << 1 | 1974 unsigned(IA->getDialect() & 1) << 2); 1975 1976 // Add the asm string. 1977 const std::string &AsmStr = IA->getAsmString(); 1978 Record.push_back(AsmStr.size()); 1979 Record.append(AsmStr.begin(), AsmStr.end()); 1980 1981 // Add the constraint string. 1982 const std::string &ConstraintStr = IA->getConstraintString(); 1983 Record.push_back(ConstraintStr.size()); 1984 Record.append(ConstraintStr.begin(), ConstraintStr.end()); 1985 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record); 1986 Record.clear(); 1987 continue; 1988 } 1989 const Constant *C = cast<Constant>(V); 1990 unsigned Code = -1U; 1991 unsigned AbbrevToUse = 0; 1992 if (C->isNullValue()) { 1993 Code = bitc::CST_CODE_NULL; 1994 } else if (isa<UndefValue>(C)) { 1995 Code = bitc::CST_CODE_UNDEF; 1996 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) { 1997 if (IV->getBitWidth() <= 64) { 1998 uint64_t V = IV->getSExtValue(); 1999 emitSignedInt64(Record, V); 2000 Code = bitc::CST_CODE_INTEGER; 2001 AbbrevToUse = CONSTANTS_INTEGER_ABBREV; 2002 } else { // Wide integers, > 64 bits in size. 2003 // We have an arbitrary precision integer value to write whose 2004 // bit width is > 64. However, in canonical unsigned integer 2005 // format it is likely that the high bits are going to be zero. 2006 // So, we only write the number of active words. 2007 unsigned NWords = IV->getValue().getActiveWords(); 2008 const uint64_t *RawWords = IV->getValue().getRawData(); 2009 for (unsigned i = 0; i != NWords; ++i) { 2010 emitSignedInt64(Record, RawWords[i]); 2011 } 2012 Code = bitc::CST_CODE_WIDE_INTEGER; 2013 } 2014 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) { 2015 Code = bitc::CST_CODE_FLOAT; 2016 Type *Ty = CFP->getType(); 2017 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) { 2018 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue()); 2019 } else if (Ty->isX86_FP80Ty()) { 2020 // api needed to prevent premature destruction 2021 // bits are not in the same order as a normal i80 APInt, compensate. 2022 APInt api = CFP->getValueAPF().bitcastToAPInt(); 2023 const uint64_t *p = api.getRawData(); 2024 Record.push_back((p[1] << 48) | (p[0] >> 16)); 2025 Record.push_back(p[0] & 0xffffLL); 2026 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) { 2027 APInt api = CFP->getValueAPF().bitcastToAPInt(); 2028 const uint64_t *p = api.getRawData(); 2029 Record.push_back(p[0]); 2030 Record.push_back(p[1]); 2031 } else { 2032 assert(0 && "Unknown FP type!"); 2033 } 2034 } else if (isa<ConstantDataSequential>(C) && 2035 cast<ConstantDataSequential>(C)->isString()) { 2036 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C); 2037 // Emit constant strings specially. 2038 unsigned NumElts = Str->getNumElements(); 2039 // If this is a null-terminated string, use the denser CSTRING encoding. 2040 if (Str->isCString()) { 2041 Code = bitc::CST_CODE_CSTRING; 2042 --NumElts; // Don't encode the null, which isn't allowed by char6. 2043 } else { 2044 Code = bitc::CST_CODE_STRING; 2045 AbbrevToUse = String8Abbrev; 2046 } 2047 bool isCStr7 = Code == bitc::CST_CODE_CSTRING; 2048 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING; 2049 for (unsigned i = 0; i != NumElts; ++i) { 2050 unsigned char V = Str->getElementAsInteger(i); 2051 Record.push_back(V); 2052 isCStr7 &= (V & 128) == 0; 2053 if (isCStrChar6) 2054 isCStrChar6 = BitCodeAbbrevOp::isChar6(V); 2055 } 2056 2057 if (isCStrChar6) 2058 AbbrevToUse = CString6Abbrev; 2059 else if (isCStr7) 2060 AbbrevToUse = CString7Abbrev; 2061 } else if (const ConstantDataSequential *CDS = 2062 dyn_cast<ConstantDataSequential>(C)) { 2063 Code = bitc::CST_CODE_DATA; 2064 Type *EltTy = CDS->getType()->getArrayElementType(); 2065 if (isa<IntegerType>(EltTy)) { 2066 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) 2067 Record.push_back(CDS->getElementAsInteger(i)); 2068 } else if (EltTy->isFloatTy()) { 2069 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 2070 union { 2071 float F; 2072 uint32_t I; 2073 }; 2074 F = CDS->getElementAsFloat(i); 2075 Record.push_back(I); 2076 } 2077 } else { 2078 assert(EltTy->isDoubleTy() && "Unknown ConstantData element type"); 2079 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 2080 union { 2081 double F; 2082 uint64_t I; 2083 }; 2084 F = CDS->getElementAsDouble(i); 2085 Record.push_back(I); 2086 } 2087 } 2088 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) || 2089 isa<ConstantVector>(C)) { 2090 Code = bitc::CST_CODE_AGGREGATE; 2091 for (const Value *Op : C->operands()) 2092 Record.push_back(VE.getValueID(Op)); 2093 AbbrevToUse = AggregateAbbrev; 2094 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 2095 switch (CE->getOpcode()) { 2096 default: 2097 if (Instruction::isCast(CE->getOpcode())) { 2098 Code = bitc::CST_CODE_CE_CAST; 2099 Record.push_back(getEncodedCastOpcode(CE->getOpcode())); 2100 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 2101 Record.push_back(VE.getValueID(C->getOperand(0))); 2102 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev; 2103 } else { 2104 assert(CE->getNumOperands() == 2 && "Unknown constant expr!"); 2105 Code = bitc::CST_CODE_CE_BINOP; 2106 Record.push_back(getEncodedBinaryOpcode(CE->getOpcode())); 2107 Record.push_back(VE.getValueID(C->getOperand(0))); 2108 Record.push_back(VE.getValueID(C->getOperand(1))); 2109 uint64_t Flags = getOptimizationFlags(CE); 2110 if (Flags != 0) 2111 Record.push_back(Flags); 2112 } 2113 break; 2114 case Instruction::GetElementPtr: { 2115 Code = bitc::CST_CODE_CE_GEP; 2116 const auto *GO = cast<GEPOperator>(C); 2117 if (GO->isInBounds()) 2118 Code = bitc::CST_CODE_CE_INBOUNDS_GEP; 2119 Record.push_back(VE.getTypeID(GO->getSourceElementType())); 2120 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) { 2121 Record.push_back(VE.getTypeID(C->getOperand(i)->getType())); 2122 Record.push_back(VE.getValueID(C->getOperand(i))); 2123 } 2124 break; 2125 } 2126 case Instruction::Select: 2127 Code = bitc::CST_CODE_CE_SELECT; 2128 Record.push_back(VE.getValueID(C->getOperand(0))); 2129 Record.push_back(VE.getValueID(C->getOperand(1))); 2130 Record.push_back(VE.getValueID(C->getOperand(2))); 2131 break; 2132 case Instruction::ExtractElement: 2133 Code = bitc::CST_CODE_CE_EXTRACTELT; 2134 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 2135 Record.push_back(VE.getValueID(C->getOperand(0))); 2136 Record.push_back(VE.getTypeID(C->getOperand(1)->getType())); 2137 Record.push_back(VE.getValueID(C->getOperand(1))); 2138 break; 2139 case Instruction::InsertElement: 2140 Code = bitc::CST_CODE_CE_INSERTELT; 2141 Record.push_back(VE.getValueID(C->getOperand(0))); 2142 Record.push_back(VE.getValueID(C->getOperand(1))); 2143 Record.push_back(VE.getTypeID(C->getOperand(2)->getType())); 2144 Record.push_back(VE.getValueID(C->getOperand(2))); 2145 break; 2146 case Instruction::ShuffleVector: 2147 // If the return type and argument types are the same, this is a 2148 // standard shufflevector instruction. If the types are different, 2149 // then the shuffle is widening or truncating the input vectors, and 2150 // the argument type must also be encoded. 2151 if (C->getType() == C->getOperand(0)->getType()) { 2152 Code = bitc::CST_CODE_CE_SHUFFLEVEC; 2153 } else { 2154 Code = bitc::CST_CODE_CE_SHUFVEC_EX; 2155 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 2156 } 2157 Record.push_back(VE.getValueID(C->getOperand(0))); 2158 Record.push_back(VE.getValueID(C->getOperand(1))); 2159 Record.push_back(VE.getValueID(C->getOperand(2))); 2160 break; 2161 case Instruction::ICmp: 2162 case Instruction::FCmp: 2163 Code = bitc::CST_CODE_CE_CMP; 2164 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 2165 Record.push_back(VE.getValueID(C->getOperand(0))); 2166 Record.push_back(VE.getValueID(C->getOperand(1))); 2167 Record.push_back(CE->getPredicate()); 2168 break; 2169 } 2170 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) { 2171 Code = bitc::CST_CODE_BLOCKADDRESS; 2172 Record.push_back(VE.getTypeID(BA->getFunction()->getType())); 2173 Record.push_back(VE.getValueID(BA->getFunction())); 2174 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock())); 2175 } else { 2176 #ifndef NDEBUG 2177 C->dump(); 2178 #endif 2179 llvm_unreachable("Unknown constant!"); 2180 } 2181 Stream.EmitRecord(Code, Record, AbbrevToUse); 2182 Record.clear(); 2183 } 2184 2185 Stream.ExitBlock(); 2186 } 2187 2188 void DXILBitcodeWriter::writeModuleConstants() { 2189 const ValueEnumerator::ValueList &Vals = VE.getValues(); 2190 2191 // Find the first constant to emit, which is the first non-globalvalue value. 2192 // We know globalvalues have been emitted by WriteModuleInfo. 2193 for (unsigned i = 0, e = Vals.size(); i != e; ++i) { 2194 if (!isa<GlobalValue>(Vals[i].first)) { 2195 writeConstants(i, Vals.size(), true); 2196 return; 2197 } 2198 } 2199 } 2200 2201 /// pushValueAndType - The file has to encode both the value and type id for 2202 /// many values, because we need to know what type to create for forward 2203 /// references. However, most operands are not forward references, so this type 2204 /// field is not needed. 2205 /// 2206 /// This function adds V's value ID to Vals. If the value ID is higher than the 2207 /// instruction ID, then it is a forward reference, and it also includes the 2208 /// type ID. The value ID that is written is encoded relative to the InstID. 2209 bool DXILBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID, 2210 SmallVectorImpl<unsigned> &Vals) { 2211 unsigned ValID = VE.getValueID(V); 2212 // Make encoding relative to the InstID. 2213 Vals.push_back(InstID - ValID); 2214 if (ValID >= InstID) { 2215 Vals.push_back(VE.getTypeID(V->getType())); 2216 return true; 2217 } 2218 return false; 2219 } 2220 2221 /// pushValue - Like pushValueAndType, but where the type of the value is 2222 /// omitted (perhaps it was already encoded in an earlier operand). 2223 void DXILBitcodeWriter::pushValue(const Value *V, unsigned InstID, 2224 SmallVectorImpl<unsigned> &Vals) { 2225 unsigned ValID = VE.getValueID(V); 2226 Vals.push_back(InstID - ValID); 2227 } 2228 2229 void DXILBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID, 2230 SmallVectorImpl<uint64_t> &Vals) { 2231 unsigned ValID = VE.getValueID(V); 2232 int64_t diff = ((int32_t)InstID - (int32_t)ValID); 2233 emitSignedInt64(Vals, diff); 2234 } 2235 2236 /// WriteInstruction - Emit an instruction 2237 void DXILBitcodeWriter::writeInstruction(const Instruction &I, unsigned InstID, 2238 SmallVectorImpl<unsigned> &Vals) { 2239 unsigned Code = 0; 2240 unsigned AbbrevToUse = 0; 2241 VE.setInstructionID(&I); 2242 switch (I.getOpcode()) { 2243 default: 2244 if (Instruction::isCast(I.getOpcode())) { 2245 Code = bitc::FUNC_CODE_INST_CAST; 2246 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) 2247 AbbrevToUse = (unsigned)FUNCTION_INST_CAST_ABBREV; 2248 Vals.push_back(VE.getTypeID(I.getType())); 2249 Vals.push_back(getEncodedCastOpcode(I.getOpcode())); 2250 } else { 2251 assert(isa<BinaryOperator>(I) && "Unknown instruction!"); 2252 Code = bitc::FUNC_CODE_INST_BINOP; 2253 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) 2254 AbbrevToUse = (unsigned)FUNCTION_INST_BINOP_ABBREV; 2255 pushValue(I.getOperand(1), InstID, Vals); 2256 Vals.push_back(getEncodedBinaryOpcode(I.getOpcode())); 2257 uint64_t Flags = getOptimizationFlags(&I); 2258 if (Flags != 0) { 2259 if (AbbrevToUse == (unsigned)FUNCTION_INST_BINOP_ABBREV) 2260 AbbrevToUse = (unsigned)FUNCTION_INST_BINOP_FLAGS_ABBREV; 2261 Vals.push_back(Flags); 2262 } 2263 } 2264 break; 2265 2266 case Instruction::GetElementPtr: { 2267 Code = bitc::FUNC_CODE_INST_GEP; 2268 AbbrevToUse = (unsigned)FUNCTION_INST_GEP_ABBREV; 2269 auto &GEPInst = cast<GetElementPtrInst>(I); 2270 Vals.push_back(GEPInst.isInBounds()); 2271 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType())); 2272 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) 2273 pushValueAndType(I.getOperand(i), InstID, Vals); 2274 break; 2275 } 2276 case Instruction::ExtractValue: { 2277 Code = bitc::FUNC_CODE_INST_EXTRACTVAL; 2278 pushValueAndType(I.getOperand(0), InstID, Vals); 2279 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I); 2280 Vals.append(EVI->idx_begin(), EVI->idx_end()); 2281 break; 2282 } 2283 case Instruction::InsertValue: { 2284 Code = bitc::FUNC_CODE_INST_INSERTVAL; 2285 pushValueAndType(I.getOperand(0), InstID, Vals); 2286 pushValueAndType(I.getOperand(1), InstID, Vals); 2287 const InsertValueInst *IVI = cast<InsertValueInst>(&I); 2288 Vals.append(IVI->idx_begin(), IVI->idx_end()); 2289 break; 2290 } 2291 case Instruction::Select: 2292 Code = bitc::FUNC_CODE_INST_VSELECT; 2293 pushValueAndType(I.getOperand(1), InstID, Vals); 2294 pushValue(I.getOperand(2), InstID, Vals); 2295 pushValueAndType(I.getOperand(0), InstID, Vals); 2296 break; 2297 case Instruction::ExtractElement: 2298 Code = bitc::FUNC_CODE_INST_EXTRACTELT; 2299 pushValueAndType(I.getOperand(0), InstID, Vals); 2300 pushValueAndType(I.getOperand(1), InstID, Vals); 2301 break; 2302 case Instruction::InsertElement: 2303 Code = bitc::FUNC_CODE_INST_INSERTELT; 2304 pushValueAndType(I.getOperand(0), InstID, Vals); 2305 pushValue(I.getOperand(1), InstID, Vals); 2306 pushValueAndType(I.getOperand(2), InstID, Vals); 2307 break; 2308 case Instruction::ShuffleVector: 2309 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC; 2310 pushValueAndType(I.getOperand(0), InstID, Vals); 2311 pushValue(I.getOperand(1), InstID, Vals); 2312 pushValue(I.getOperand(2), InstID, Vals); 2313 break; 2314 case Instruction::ICmp: 2315 case Instruction::FCmp: { 2316 // compare returning Int1Ty or vector of Int1Ty 2317 Code = bitc::FUNC_CODE_INST_CMP2; 2318 pushValueAndType(I.getOperand(0), InstID, Vals); 2319 pushValue(I.getOperand(1), InstID, Vals); 2320 Vals.push_back(cast<CmpInst>(I).getPredicate()); 2321 uint64_t Flags = getOptimizationFlags(&I); 2322 if (Flags != 0) 2323 Vals.push_back(Flags); 2324 break; 2325 } 2326 2327 case Instruction::Ret: { 2328 Code = bitc::FUNC_CODE_INST_RET; 2329 unsigned NumOperands = I.getNumOperands(); 2330 if (NumOperands == 0) 2331 AbbrevToUse = (unsigned)FUNCTION_INST_RET_VOID_ABBREV; 2332 else if (NumOperands == 1) { 2333 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) 2334 AbbrevToUse = (unsigned)FUNCTION_INST_RET_VAL_ABBREV; 2335 } else { 2336 for (unsigned i = 0, e = NumOperands; i != e; ++i) 2337 pushValueAndType(I.getOperand(i), InstID, Vals); 2338 } 2339 } break; 2340 case Instruction::Br: { 2341 Code = bitc::FUNC_CODE_INST_BR; 2342 const BranchInst &II = cast<BranchInst>(I); 2343 Vals.push_back(VE.getValueID(II.getSuccessor(0))); 2344 if (II.isConditional()) { 2345 Vals.push_back(VE.getValueID(II.getSuccessor(1))); 2346 pushValue(II.getCondition(), InstID, Vals); 2347 } 2348 } break; 2349 case Instruction::Switch: { 2350 Code = bitc::FUNC_CODE_INST_SWITCH; 2351 const SwitchInst &SI = cast<SwitchInst>(I); 2352 Vals.push_back(VE.getTypeID(SI.getCondition()->getType())); 2353 pushValue(SI.getCondition(), InstID, Vals); 2354 Vals.push_back(VE.getValueID(SI.getDefaultDest())); 2355 for (auto Case : SI.cases()) { 2356 Vals.push_back(VE.getValueID(Case.getCaseValue())); 2357 Vals.push_back(VE.getValueID(Case.getCaseSuccessor())); 2358 } 2359 } break; 2360 case Instruction::IndirectBr: 2361 Code = bitc::FUNC_CODE_INST_INDIRECTBR; 2362 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); 2363 // Encode the address operand as relative, but not the basic blocks. 2364 pushValue(I.getOperand(0), InstID, Vals); 2365 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) 2366 Vals.push_back(VE.getValueID(I.getOperand(i))); 2367 break; 2368 2369 case Instruction::Invoke: { 2370 const InvokeInst *II = cast<InvokeInst>(&I); 2371 const Value *Callee = II->getCalledOperand(); 2372 FunctionType *FTy = II->getFunctionType(); 2373 Code = bitc::FUNC_CODE_INST_INVOKE; 2374 2375 Vals.push_back(VE.getAttributeListID(II->getAttributes())); 2376 Vals.push_back(II->getCallingConv() | 1 << 13); 2377 Vals.push_back(VE.getValueID(II->getNormalDest())); 2378 Vals.push_back(VE.getValueID(II->getUnwindDest())); 2379 Vals.push_back(VE.getTypeID(FTy)); 2380 pushValueAndType(Callee, InstID, Vals); 2381 2382 // Emit value #'s for the fixed parameters. 2383 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) 2384 pushValue(I.getOperand(i), InstID, Vals); // fixed param. 2385 2386 // Emit type/value pairs for varargs params. 2387 if (FTy->isVarArg()) { 2388 for (unsigned i = FTy->getNumParams(), e = I.getNumOperands() - 3; i != e; 2389 ++i) 2390 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg 2391 } 2392 break; 2393 } 2394 case Instruction::Resume: 2395 Code = bitc::FUNC_CODE_INST_RESUME; 2396 pushValueAndType(I.getOperand(0), InstID, Vals); 2397 break; 2398 case Instruction::Unreachable: 2399 Code = bitc::FUNC_CODE_INST_UNREACHABLE; 2400 AbbrevToUse = (unsigned)FUNCTION_INST_UNREACHABLE_ABBREV; 2401 break; 2402 2403 case Instruction::PHI: { 2404 const PHINode &PN = cast<PHINode>(I); 2405 Code = bitc::FUNC_CODE_INST_PHI; 2406 // With the newer instruction encoding, forward references could give 2407 // negative valued IDs. This is most common for PHIs, so we use 2408 // signed VBRs. 2409 SmallVector<uint64_t, 128> Vals64; 2410 Vals64.push_back(VE.getTypeID(PN.getType())); 2411 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) { 2412 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64); 2413 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i))); 2414 } 2415 // Emit a Vals64 vector and exit. 2416 Stream.EmitRecord(Code, Vals64, AbbrevToUse); 2417 Vals64.clear(); 2418 return; 2419 } 2420 2421 case Instruction::LandingPad: { 2422 const LandingPadInst &LP = cast<LandingPadInst>(I); 2423 Code = bitc::FUNC_CODE_INST_LANDINGPAD; 2424 Vals.push_back(VE.getTypeID(LP.getType())); 2425 Vals.push_back(LP.isCleanup()); 2426 Vals.push_back(LP.getNumClauses()); 2427 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) { 2428 if (LP.isCatch(I)) 2429 Vals.push_back(LandingPadInst::Catch); 2430 else 2431 Vals.push_back(LandingPadInst::Filter); 2432 pushValueAndType(LP.getClause(I), InstID, Vals); 2433 } 2434 break; 2435 } 2436 2437 case Instruction::Alloca: { 2438 Code = bitc::FUNC_CODE_INST_ALLOCA; 2439 const AllocaInst &AI = cast<AllocaInst>(I); 2440 Vals.push_back(VE.getTypeID(AI.getAllocatedType())); 2441 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); 2442 Vals.push_back(VE.getValueID(I.getOperand(0))); // size. 2443 using APV = AllocaPackedValues; 2444 unsigned Record = 0; 2445 unsigned EncodedAlign = getEncodedAlign(AI.getAlign()); 2446 Bitfield::set<APV::AlignLower>( 2447 Record, EncodedAlign & ((1 << APV::AlignLower::Bits) - 1)); 2448 Bitfield::set<APV::AlignUpper>(Record, 2449 EncodedAlign >> APV::AlignLower::Bits); 2450 Bitfield::set<APV::UsedWithInAlloca>(Record, AI.isUsedWithInAlloca()); 2451 Vals.push_back(Record); 2452 break; 2453 } 2454 2455 case Instruction::Load: 2456 if (cast<LoadInst>(I).isAtomic()) { 2457 Code = bitc::FUNC_CODE_INST_LOADATOMIC; 2458 pushValueAndType(I.getOperand(0), InstID, Vals); 2459 } else { 2460 Code = bitc::FUNC_CODE_INST_LOAD; 2461 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr 2462 AbbrevToUse = (unsigned)FUNCTION_INST_LOAD_ABBREV; 2463 } 2464 Vals.push_back(VE.getTypeID(I.getType())); 2465 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment()) + 1); 2466 Vals.push_back(cast<LoadInst>(I).isVolatile()); 2467 if (cast<LoadInst>(I).isAtomic()) { 2468 Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering())); 2469 Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID())); 2470 } 2471 break; 2472 case Instruction::Store: 2473 if (cast<StoreInst>(I).isAtomic()) 2474 Code = bitc::FUNC_CODE_INST_STOREATOMIC; 2475 else 2476 Code = bitc::FUNC_CODE_INST_STORE; 2477 pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr 2478 pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val 2479 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment()) + 1); 2480 Vals.push_back(cast<StoreInst>(I).isVolatile()); 2481 if (cast<StoreInst>(I).isAtomic()) { 2482 Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering())); 2483 Vals.push_back( 2484 getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID())); 2485 } 2486 break; 2487 case Instruction::AtomicCmpXchg: 2488 Code = bitc::FUNC_CODE_INST_CMPXCHG; 2489 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr 2490 pushValueAndType(I.getOperand(1), InstID, Vals); // cmp. 2491 pushValue(I.getOperand(2), InstID, Vals); // newval. 2492 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile()); 2493 Vals.push_back( 2494 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering())); 2495 Vals.push_back( 2496 getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID())); 2497 Vals.push_back( 2498 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering())); 2499 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak()); 2500 break; 2501 case Instruction::AtomicRMW: 2502 Code = bitc::FUNC_CODE_INST_ATOMICRMW; 2503 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr 2504 pushValue(I.getOperand(1), InstID, Vals); // val. 2505 Vals.push_back( 2506 getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation())); 2507 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile()); 2508 Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering())); 2509 Vals.push_back( 2510 getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID())); 2511 break; 2512 case Instruction::Fence: 2513 Code = bitc::FUNC_CODE_INST_FENCE; 2514 Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering())); 2515 Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID())); 2516 break; 2517 case Instruction::Call: { 2518 const CallInst &CI = cast<CallInst>(I); 2519 FunctionType *FTy = CI.getFunctionType(); 2520 2521 Code = bitc::FUNC_CODE_INST_CALL; 2522 2523 Vals.push_back(VE.getAttributeListID(CI.getAttributes())); 2524 Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall()) | 2525 unsigned(CI.isMustTailCall()) << 14 | 1 << 15); 2526 Vals.push_back(VE.getTypeID(FTy)); 2527 pushValueAndType(CI.getCalledOperand(), InstID, Vals); // Callee 2528 2529 // Emit value #'s for the fixed parameters. 2530 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) { 2531 // Check for labels (can happen with asm labels). 2532 if (FTy->getParamType(i)->isLabelTy()) 2533 Vals.push_back(VE.getValueID(CI.getArgOperand(i))); 2534 else 2535 pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param. 2536 } 2537 2538 // Emit type/value pairs for varargs params. 2539 if (FTy->isVarArg()) { 2540 for (unsigned i = FTy->getNumParams(), e = CI.arg_size(); i != e; ++i) 2541 pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs 2542 } 2543 break; 2544 } 2545 case Instruction::VAArg: 2546 Code = bitc::FUNC_CODE_INST_VAARG; 2547 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty 2548 pushValue(I.getOperand(0), InstID, Vals); // valist. 2549 Vals.push_back(VE.getTypeID(I.getType())); // restype. 2550 break; 2551 } 2552 2553 Stream.EmitRecord(Code, Vals, AbbrevToUse); 2554 Vals.clear(); 2555 } 2556 2557 // Emit names for globals/functions etc. 2558 void DXILBitcodeWriter::writeFunctionLevelValueSymbolTable( 2559 const ValueSymbolTable &VST) { 2560 if (VST.empty()) 2561 return; 2562 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4); 2563 2564 SmallVector<unsigned, 64> NameVals; 2565 2566 // HLSL Change 2567 // Read the named values from a sorted list instead of the original list 2568 // to ensure the binary is the same no matter what values ever existed. 2569 SmallVector<const ValueName *, 16> SortedTable; 2570 2571 for (auto &VI : VST) { 2572 SortedTable.push_back(VI.second->getValueName()); 2573 } 2574 // The keys are unique, so there shouldn't be stability issues. 2575 std::sort(SortedTable.begin(), SortedTable.end(), 2576 [](const ValueName *A, const ValueName *B) { 2577 return A->first() < B->first(); 2578 }); 2579 2580 for (const ValueName *SI : SortedTable) { 2581 auto &Name = *SI; 2582 2583 // Figure out the encoding to use for the name. 2584 bool is7Bit = true; 2585 bool isChar6 = true; 2586 for (const char *C = Name.getKeyData(), *E = C + Name.getKeyLength(); 2587 C != E; ++C) { 2588 if (isChar6) 2589 isChar6 = BitCodeAbbrevOp::isChar6(*C); 2590 if ((unsigned char)*C & 128) { 2591 is7Bit = false; 2592 break; // don't bother scanning the rest. 2593 } 2594 } 2595 2596 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV; 2597 2598 // VST_ENTRY: [valueid, namechar x N] 2599 // VST_BBENTRY: [bbid, namechar x N] 2600 unsigned Code; 2601 if (isa<BasicBlock>(SI->getValue())) { 2602 Code = bitc::VST_CODE_BBENTRY; 2603 if (isChar6) 2604 AbbrevToUse = VST_BBENTRY_6_ABBREV; 2605 } else { 2606 Code = bitc::VST_CODE_ENTRY; 2607 if (isChar6) 2608 AbbrevToUse = VST_ENTRY_6_ABBREV; 2609 else if (is7Bit) 2610 AbbrevToUse = VST_ENTRY_7_ABBREV; 2611 } 2612 2613 NameVals.push_back(VE.getValueID(SI->getValue())); 2614 for (const char *P = Name.getKeyData(), 2615 *E = Name.getKeyData() + Name.getKeyLength(); 2616 P != E; ++P) 2617 NameVals.push_back((unsigned char)*P); 2618 2619 // Emit the finished record. 2620 Stream.EmitRecord(Code, NameVals, AbbrevToUse); 2621 NameVals.clear(); 2622 } 2623 Stream.ExitBlock(); 2624 } 2625 2626 void DXILBitcodeWriter::writeUseList(UseListOrder &&Order) { 2627 assert(Order.Shuffle.size() >= 2 && "Shuffle too small"); 2628 unsigned Code; 2629 if (isa<BasicBlock>(Order.V)) 2630 Code = bitc::USELIST_CODE_BB; 2631 else 2632 Code = bitc::USELIST_CODE_DEFAULT; 2633 2634 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end()); 2635 Record.push_back(VE.getValueID(Order.V)); 2636 Stream.EmitRecord(Code, Record); 2637 } 2638 2639 void DXILBitcodeWriter::writeUseListBlock(const Function *F) { 2640 assert(VE.shouldPreserveUseListOrder() && 2641 "Expected to be preserving use-list order"); 2642 2643 auto hasMore = [&]() { 2644 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F; 2645 }; 2646 if (!hasMore()) 2647 // Nothing to do. 2648 return; 2649 2650 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3); 2651 while (hasMore()) { 2652 writeUseList(std::move(VE.UseListOrders.back())); 2653 VE.UseListOrders.pop_back(); 2654 } 2655 Stream.ExitBlock(); 2656 } 2657 2658 /// Emit a function body to the module stream. 2659 void DXILBitcodeWriter::writeFunction(const Function &F) { 2660 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4); 2661 VE.incorporateFunction(F); 2662 2663 SmallVector<unsigned, 64> Vals; 2664 2665 // Emit the number of basic blocks, so the reader can create them ahead of 2666 // time. 2667 Vals.push_back(VE.getBasicBlocks().size()); 2668 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals); 2669 Vals.clear(); 2670 2671 // If there are function-local constants, emit them now. 2672 unsigned CstStart, CstEnd; 2673 VE.getFunctionConstantRange(CstStart, CstEnd); 2674 writeConstants(CstStart, CstEnd, false); 2675 2676 // If there is function-local metadata, emit it now. 2677 writeFunctionMetadata(F); 2678 2679 // Keep a running idea of what the instruction ID is. 2680 unsigned InstID = CstEnd; 2681 2682 bool NeedsMetadataAttachment = F.hasMetadata(); 2683 2684 DILocation *LastDL = nullptr; 2685 2686 // Finally, emit all the instructions, in order. 2687 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) 2688 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; 2689 ++I) { 2690 writeInstruction(*I, InstID, Vals); 2691 2692 if (!I->getType()->isVoidTy()) 2693 ++InstID; 2694 2695 // If the instruction has metadata, write a metadata attachment later. 2696 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc(); 2697 2698 // If the instruction has a debug location, emit it. 2699 DILocation *DL = I->getDebugLoc(); 2700 if (!DL) 2701 continue; 2702 2703 if (DL == LastDL) { 2704 // Just repeat the same debug loc as last time. 2705 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals); 2706 continue; 2707 } 2708 2709 Vals.push_back(DL->getLine()); 2710 Vals.push_back(DL->getColumn()); 2711 Vals.push_back(VE.getMetadataOrNullID(DL->getScope())); 2712 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt())); 2713 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals); 2714 Vals.clear(); 2715 2716 LastDL = DL; 2717 } 2718 2719 // Emit names for all the instructions etc. 2720 if (auto *Symtab = F.getValueSymbolTable()) 2721 writeFunctionLevelValueSymbolTable(*Symtab); 2722 2723 if (NeedsMetadataAttachment) 2724 writeFunctionMetadataAttachment(F); 2725 if (VE.shouldPreserveUseListOrder()) 2726 writeUseListBlock(&F); 2727 VE.purgeFunction(); 2728 Stream.ExitBlock(); 2729 } 2730 2731 // Emit blockinfo, which defines the standard abbreviations etc. 2732 void DXILBitcodeWriter::writeBlockInfo() { 2733 // We only want to emit block info records for blocks that have multiple 2734 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK. 2735 // Other blocks can define their abbrevs inline. 2736 Stream.EnterBlockInfoBlock(); 2737 2738 { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings. 2739 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2740 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); 2741 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 2742 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2743 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 2744 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, 2745 std::move(Abbv)) != VST_ENTRY_8_ABBREV) 2746 assert(false && "Unexpected abbrev ordering!"); 2747 } 2748 2749 { // 7-bit fixed width VST_ENTRY strings. 2750 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2751 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY)); 2752 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 2753 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2754 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); 2755 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, 2756 std::move(Abbv)) != VST_ENTRY_7_ABBREV) 2757 assert(false && "Unexpected abbrev ordering!"); 2758 } 2759 { // 6-bit char6 VST_ENTRY strings. 2760 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2761 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY)); 2762 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 2763 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2764 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 2765 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, 2766 std::move(Abbv)) != VST_ENTRY_6_ABBREV) 2767 assert(false && "Unexpected abbrev ordering!"); 2768 } 2769 { // 6-bit char6 VST_BBENTRY strings. 2770 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2771 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY)); 2772 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 2773 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2774 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 2775 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, 2776 std::move(Abbv)) != VST_BBENTRY_6_ABBREV) 2777 assert(false && "Unexpected abbrev ordering!"); 2778 } 2779 2780 { // SETTYPE abbrev for CONSTANTS_BLOCK. 2781 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2782 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE)); 2783 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2784 VE.computeBitsRequiredForTypeIndicies())); 2785 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, std::move(Abbv)) != 2786 CONSTANTS_SETTYPE_ABBREV) 2787 assert(false && "Unexpected abbrev ordering!"); 2788 } 2789 2790 { // INTEGER abbrev for CONSTANTS_BLOCK. 2791 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2792 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER)); 2793 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 2794 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, std::move(Abbv)) != 2795 CONSTANTS_INTEGER_ABBREV) 2796 assert(false && "Unexpected abbrev ordering!"); 2797 } 2798 2799 { // CE_CAST abbrev for CONSTANTS_BLOCK. 2800 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2801 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST)); 2802 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc 2803 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid 2804 VE.computeBitsRequiredForTypeIndicies())); 2805 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id 2806 2807 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, std::move(Abbv)) != 2808 CONSTANTS_CE_CAST_Abbrev) 2809 assert(false && "Unexpected abbrev ordering!"); 2810 } 2811 { // NULL abbrev for CONSTANTS_BLOCK. 2812 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2813 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL)); 2814 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, std::move(Abbv)) != 2815 CONSTANTS_NULL_Abbrev) 2816 assert(false && "Unexpected abbrev ordering!"); 2817 } 2818 2819 // FIXME: This should only use space for first class types! 2820 2821 { // INST_LOAD abbrev for FUNCTION_BLOCK. 2822 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2823 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD)); 2824 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr 2825 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty 2826 VE.computeBitsRequiredForTypeIndicies())); 2827 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align 2828 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile 2829 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) != 2830 (unsigned)FUNCTION_INST_LOAD_ABBREV) 2831 assert(false && "Unexpected abbrev ordering!"); 2832 } 2833 { // INST_BINOP abbrev for FUNCTION_BLOCK. 2834 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2835 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP)); 2836 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS 2837 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS 2838 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 2839 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) != 2840 (unsigned)FUNCTION_INST_BINOP_ABBREV) 2841 assert(false && "Unexpected abbrev ordering!"); 2842 } 2843 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK. 2844 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2845 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP)); 2846 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS 2847 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS 2848 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 2849 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags 2850 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) != 2851 (unsigned)FUNCTION_INST_BINOP_FLAGS_ABBREV) 2852 assert(false && "Unexpected abbrev ordering!"); 2853 } 2854 { // INST_CAST abbrev for FUNCTION_BLOCK. 2855 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2856 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST)); 2857 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal 2858 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty 2859 VE.computeBitsRequiredForTypeIndicies())); 2860 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 2861 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) != 2862 (unsigned)FUNCTION_INST_CAST_ABBREV) 2863 assert(false && "Unexpected abbrev ordering!"); 2864 } 2865 2866 { // INST_RET abbrev for FUNCTION_BLOCK. 2867 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2868 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET)); 2869 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) != 2870 (unsigned)FUNCTION_INST_RET_VOID_ABBREV) 2871 assert(false && "Unexpected abbrev ordering!"); 2872 } 2873 { // INST_RET abbrev for FUNCTION_BLOCK. 2874 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2875 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET)); 2876 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID 2877 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) != 2878 (unsigned)FUNCTION_INST_RET_VAL_ABBREV) 2879 assert(false && "Unexpected abbrev ordering!"); 2880 } 2881 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK. 2882 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2883 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE)); 2884 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) != 2885 (unsigned)FUNCTION_INST_UNREACHABLE_ABBREV) 2886 assert(false && "Unexpected abbrev ordering!"); 2887 } 2888 { 2889 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2890 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP)); 2891 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); 2892 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty 2893 Log2_32_Ceil(VE.getTypes().size() + 1))); 2894 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2895 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 2896 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) != 2897 (unsigned)FUNCTION_INST_GEP_ABBREV) 2898 assert(false && "Unexpected abbrev ordering!"); 2899 } 2900 2901 Stream.ExitBlock(); 2902 } 2903 2904 void DXILBitcodeWriter::writeModuleVersion() { 2905 // VERSION: [version#] 2906 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, ArrayRef<unsigned>{1}); 2907 } 2908 2909 /// WriteModule - Emit the specified module to the bitstream. 2910 void DXILBitcodeWriter::write() { 2911 // The identification block is new since llvm-3.7, but the old bitcode reader 2912 // will skip it. 2913 // writeIdentificationBlock(Stream); 2914 2915 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3); 2916 2917 // It is redundant to fully-specify this here, but nice to make it explicit 2918 // so that it is clear the DXIL module version is different. 2919 DXILBitcodeWriter::writeModuleVersion(); 2920 2921 // Emit blockinfo, which defines the standard abbreviations etc. 2922 writeBlockInfo(); 2923 2924 // Emit information about attribute groups. 2925 writeAttributeGroupTable(); 2926 2927 // Emit information about parameter attributes. 2928 writeAttributeTable(); 2929 2930 // Emit information describing all of the types in the module. 2931 writeTypeTable(); 2932 2933 writeComdats(); 2934 2935 // Emit top-level description of module, including target triple, inline asm, 2936 // descriptors for global variables, and function prototype info. 2937 writeModuleInfo(); 2938 2939 // Emit constants. 2940 writeModuleConstants(); 2941 2942 // Emit metadata. 2943 writeModuleMetadataKinds(); 2944 2945 // Emit metadata. 2946 writeModuleMetadata(); 2947 2948 // Emit names for globals/functions etc. 2949 // DXIL uses the same format for module-level value symbol table as for the 2950 // function level table. 2951 writeFunctionLevelValueSymbolTable(M.getValueSymbolTable()); 2952 2953 // Emit module-level use-lists. 2954 if (VE.shouldPreserveUseListOrder()) 2955 writeUseListBlock(nullptr); 2956 2957 // Emit function bodies. 2958 for (const Function &F : M) 2959 if (!F.isDeclaration()) 2960 writeFunction(F); 2961 2962 Stream.ExitBlock(); 2963 } 2964