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 case Type::DXILPointerTyID: 1053 llvm_unreachable("These should never be used!!!"); 1054 break; 1055 case Type::VoidTyID: 1056 Code = bitc::TYPE_CODE_VOID; 1057 break; 1058 case Type::HalfTyID: 1059 Code = bitc::TYPE_CODE_HALF; 1060 break; 1061 case Type::FloatTyID: 1062 Code = bitc::TYPE_CODE_FLOAT; 1063 break; 1064 case Type::DoubleTyID: 1065 Code = bitc::TYPE_CODE_DOUBLE; 1066 break; 1067 case Type::X86_FP80TyID: 1068 Code = bitc::TYPE_CODE_X86_FP80; 1069 break; 1070 case Type::FP128TyID: 1071 Code = bitc::TYPE_CODE_FP128; 1072 break; 1073 case Type::PPC_FP128TyID: 1074 Code = bitc::TYPE_CODE_PPC_FP128; 1075 break; 1076 case Type::LabelTyID: 1077 Code = bitc::TYPE_CODE_LABEL; 1078 break; 1079 case Type::MetadataTyID: 1080 Code = bitc::TYPE_CODE_METADATA; 1081 break; 1082 case Type::X86_MMXTyID: 1083 Code = bitc::TYPE_CODE_X86_MMX; 1084 break; 1085 case Type::IntegerTyID: 1086 // INTEGER: [width] 1087 Code = bitc::TYPE_CODE_INTEGER; 1088 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth()); 1089 break; 1090 case Type::PointerTyID: { 1091 PointerType *PTy = cast<PointerType>(T); 1092 // POINTER: [pointee type, address space] 1093 Code = bitc::TYPE_CODE_POINTER; 1094 TypeVals.push_back(VE.getTypeID(PTy->getNonOpaquePointerElementType())); 1095 unsigned AddressSpace = PTy->getAddressSpace(); 1096 TypeVals.push_back(AddressSpace); 1097 if (AddressSpace == 0) 1098 AbbrevToUse = PtrAbbrev; 1099 break; 1100 } 1101 case Type::FunctionTyID: { 1102 FunctionType *FT = cast<FunctionType>(T); 1103 // FUNCTION: [isvararg, retty, paramty x N] 1104 Code = bitc::TYPE_CODE_FUNCTION; 1105 TypeVals.push_back(FT->isVarArg()); 1106 TypeVals.push_back(VE.getTypeID(FT->getReturnType())); 1107 for (Type *PTy : FT->params()) 1108 TypeVals.push_back(VE.getTypeID(PTy)); 1109 AbbrevToUse = FunctionAbbrev; 1110 break; 1111 } 1112 case Type::StructTyID: { 1113 StructType *ST = cast<StructType>(T); 1114 // STRUCT: [ispacked, eltty x N] 1115 TypeVals.push_back(ST->isPacked()); 1116 // Output all of the element types. 1117 for (Type *ElTy : ST->elements()) 1118 TypeVals.push_back(VE.getTypeID(ElTy)); 1119 1120 if (ST->isLiteral()) { 1121 Code = bitc::TYPE_CODE_STRUCT_ANON; 1122 AbbrevToUse = StructAnonAbbrev; 1123 } else { 1124 if (ST->isOpaque()) { 1125 Code = bitc::TYPE_CODE_OPAQUE; 1126 } else { 1127 Code = bitc::TYPE_CODE_STRUCT_NAMED; 1128 AbbrevToUse = StructNamedAbbrev; 1129 } 1130 1131 // Emit the name if it is present. 1132 if (!ST->getName().empty()) 1133 writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, ST->getName(), 1134 StructNameAbbrev); 1135 } 1136 break; 1137 } 1138 case Type::ArrayTyID: { 1139 ArrayType *AT = cast<ArrayType>(T); 1140 // ARRAY: [numelts, eltty] 1141 Code = bitc::TYPE_CODE_ARRAY; 1142 TypeVals.push_back(AT->getNumElements()); 1143 TypeVals.push_back(VE.getTypeID(AT->getElementType())); 1144 AbbrevToUse = ArrayAbbrev; 1145 break; 1146 } 1147 case Type::FixedVectorTyID: 1148 case Type::ScalableVectorTyID: { 1149 VectorType *VT = cast<VectorType>(T); 1150 // VECTOR [numelts, eltty] 1151 Code = bitc::TYPE_CODE_VECTOR; 1152 TypeVals.push_back(VT->getElementCount().getKnownMinValue()); 1153 TypeVals.push_back(VE.getTypeID(VT->getElementType())); 1154 break; 1155 } 1156 } 1157 1158 // Emit the finished record. 1159 Stream.EmitRecord(Code, TypeVals, AbbrevToUse); 1160 TypeVals.clear(); 1161 } 1162 1163 Stream.ExitBlock(); 1164 } 1165 1166 void DXILBitcodeWriter::writeComdats() { 1167 SmallVector<uint16_t, 64> Vals; 1168 for (const Comdat *C : VE.getComdats()) { 1169 // COMDAT: [selection_kind, name] 1170 Vals.push_back(getEncodedComdatSelectionKind(*C)); 1171 size_t Size = C->getName().size(); 1172 assert(isUInt<16>(Size)); 1173 Vals.push_back(Size); 1174 for (char Chr : C->getName()) 1175 Vals.push_back((unsigned char)Chr); 1176 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0); 1177 Vals.clear(); 1178 } 1179 } 1180 1181 void DXILBitcodeWriter::writeValueSymbolTableForwardDecl() {} 1182 1183 /// Emit top-level description of module, including target triple, inline asm, 1184 /// descriptors for global variables, and function prototype info. 1185 /// Returns the bit offset to backpatch with the location of the real VST. 1186 void DXILBitcodeWriter::writeModuleInfo() { 1187 // Emit various pieces of data attached to a module. 1188 if (!M.getTargetTriple().empty()) 1189 writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(), 1190 0 /*TODO*/); 1191 const std::string &DL = M.getDataLayoutStr(); 1192 if (!DL.empty()) 1193 writeStringRecord(Stream, bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/); 1194 if (!M.getModuleInlineAsm().empty()) 1195 writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(), 1196 0 /*TODO*/); 1197 1198 // Emit information about sections and GC, computing how many there are. Also 1199 // compute the maximum alignment value. 1200 std::map<std::string, unsigned> SectionMap; 1201 std::map<std::string, unsigned> GCMap; 1202 MaybeAlign MaxAlignment; 1203 unsigned MaxGlobalType = 0; 1204 const auto UpdateMaxAlignment = [&MaxAlignment](const MaybeAlign A) { 1205 if (A) 1206 MaxAlignment = !MaxAlignment ? *A : std::max(*MaxAlignment, *A); 1207 }; 1208 for (const GlobalVariable &GV : M.globals()) { 1209 UpdateMaxAlignment(GV.getAlign()); 1210 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType())); 1211 if (GV.hasSection()) { 1212 // Give section names unique ID's. 1213 unsigned &Entry = SectionMap[std::string(GV.getSection())]; 1214 if (!Entry) { 1215 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, 1216 GV.getSection(), 0 /*TODO*/); 1217 Entry = SectionMap.size(); 1218 } 1219 } 1220 } 1221 for (const Function &F : M) { 1222 UpdateMaxAlignment(F.getAlign()); 1223 if (F.hasSection()) { 1224 // Give section names unique ID's. 1225 unsigned &Entry = SectionMap[std::string(F.getSection())]; 1226 if (!Entry) { 1227 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, F.getSection(), 1228 0 /*TODO*/); 1229 Entry = SectionMap.size(); 1230 } 1231 } 1232 if (F.hasGC()) { 1233 // Same for GC names. 1234 unsigned &Entry = GCMap[F.getGC()]; 1235 if (!Entry) { 1236 writeStringRecord(Stream, bitc::MODULE_CODE_GCNAME, F.getGC(), 1237 0 /*TODO*/); 1238 Entry = GCMap.size(); 1239 } 1240 } 1241 } 1242 1243 // Emit abbrev for globals, now that we know # sections and max alignment. 1244 unsigned SimpleGVarAbbrev = 0; 1245 if (!M.global_empty()) { 1246 // Add an abbrev for common globals with no visibility or thread localness. 1247 auto Abbv = std::make_shared<BitCodeAbbrev>(); 1248 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR)); 1249 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1250 Log2_32_Ceil(MaxGlobalType + 1))); 1251 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2 1252 //| explicitType << 1 1253 //| constant 1254 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer. 1255 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage. 1256 if (MaxAlignment == 0) // Alignment. 1257 Abbv->Add(BitCodeAbbrevOp(0)); 1258 else { 1259 unsigned MaxEncAlignment = getEncodedAlign(MaxAlignment); 1260 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1261 Log2_32_Ceil(MaxEncAlignment + 1))); 1262 } 1263 if (SectionMap.empty()) // Section. 1264 Abbv->Add(BitCodeAbbrevOp(0)); 1265 else 1266 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1267 Log2_32_Ceil(SectionMap.size() + 1))); 1268 // Don't bother emitting vis + thread local. 1269 SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 1270 } 1271 1272 // Emit the global variable information. 1273 SmallVector<unsigned, 64> Vals; 1274 for (const GlobalVariable &GV : M.globals()) { 1275 unsigned AbbrevToUse = 0; 1276 1277 // GLOBALVAR: [type, isconst, initid, 1278 // linkage, alignment, section, visibility, threadlocal, 1279 // unnamed_addr, externally_initialized, dllstorageclass, 1280 // comdat] 1281 Vals.push_back(VE.getTypeID(GV.getValueType())); 1282 Vals.push_back( 1283 GV.getType()->getAddressSpace() << 2 | 2 | 1284 (GV.isConstant() ? 1 : 0)); // HLSL Change - bitwise | was used with 1285 // unsigned int and bool 1286 Vals.push_back( 1287 GV.isDeclaration() ? 0 : (VE.getValueID(GV.getInitializer()) + 1)); 1288 Vals.push_back(getEncodedLinkage(GV)); 1289 Vals.push_back(getEncodedAlign(GV.getAlign())); 1290 Vals.push_back(GV.hasSection() ? SectionMap[std::string(GV.getSection())] 1291 : 0); 1292 if (GV.isThreadLocal() || 1293 GV.getVisibility() != GlobalValue::DefaultVisibility || 1294 GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None || 1295 GV.isExternallyInitialized() || 1296 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass || 1297 GV.hasComdat()) { 1298 Vals.push_back(getEncodedVisibility(GV)); 1299 Vals.push_back(getEncodedThreadLocalMode(GV)); 1300 Vals.push_back(GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None); 1301 Vals.push_back(GV.isExternallyInitialized()); 1302 Vals.push_back(getEncodedDLLStorageClass(GV)); 1303 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0); 1304 } else { 1305 AbbrevToUse = SimpleGVarAbbrev; 1306 } 1307 1308 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse); 1309 Vals.clear(); 1310 } 1311 1312 // Emit the function proto information. 1313 for (const Function &F : M) { 1314 // FUNCTION: [type, callingconv, isproto, linkage, paramattrs, alignment, 1315 // section, visibility, gc, unnamed_addr, prologuedata, 1316 // dllstorageclass, comdat, prefixdata, personalityfn] 1317 Vals.push_back(VE.getTypeID(F.getFunctionType())); 1318 Vals.push_back(F.getCallingConv()); 1319 Vals.push_back(F.isDeclaration()); 1320 Vals.push_back(getEncodedLinkage(F)); 1321 Vals.push_back(VE.getAttributeListID(F.getAttributes())); 1322 Vals.push_back(getEncodedAlign(F.getAlign())); 1323 Vals.push_back(F.hasSection() ? SectionMap[std::string(F.getSection())] 1324 : 0); 1325 Vals.push_back(getEncodedVisibility(F)); 1326 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0); 1327 Vals.push_back(F.getUnnamedAddr() != GlobalValue::UnnamedAddr::None); 1328 Vals.push_back( 1329 F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1) : 0); 1330 Vals.push_back(getEncodedDLLStorageClass(F)); 1331 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0); 1332 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1) 1333 : 0); 1334 Vals.push_back( 1335 F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0); 1336 1337 unsigned AbbrevToUse = 0; 1338 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse); 1339 Vals.clear(); 1340 } 1341 1342 // Emit the alias information. 1343 for (const GlobalAlias &A : M.aliases()) { 1344 // ALIAS: [alias type, aliasee val#, linkage, visibility] 1345 Vals.push_back(VE.getTypeID(A.getValueType())); 1346 Vals.push_back(VE.getValueID(A.getAliasee())); 1347 Vals.push_back(getEncodedLinkage(A)); 1348 Vals.push_back(getEncodedVisibility(A)); 1349 Vals.push_back(getEncodedDLLStorageClass(A)); 1350 Vals.push_back(getEncodedThreadLocalMode(A)); 1351 Vals.push_back(A.getUnnamedAddr() != GlobalValue::UnnamedAddr::None); 1352 unsigned AbbrevToUse = 0; 1353 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS_OLD, Vals, AbbrevToUse); 1354 Vals.clear(); 1355 } 1356 } 1357 1358 void DXILBitcodeWriter::writeValueAsMetadata( 1359 const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) { 1360 // Mimic an MDNode with a value as one operand. 1361 Value *V = MD->getValue(); 1362 Record.push_back(VE.getTypeID(V->getType())); 1363 Record.push_back(VE.getValueID(V)); 1364 Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0); 1365 Record.clear(); 1366 } 1367 1368 void DXILBitcodeWriter::writeMDTuple(const MDTuple *N, 1369 SmallVectorImpl<uint64_t> &Record, 1370 unsigned Abbrev) { 1371 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 1372 Metadata *MD = N->getOperand(i); 1373 assert(!(MD && isa<LocalAsMetadata>(MD)) && 1374 "Unexpected function-local metadata"); 1375 Record.push_back(VE.getMetadataOrNullID(MD)); 1376 } 1377 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE 1378 : bitc::METADATA_NODE, 1379 Record, Abbrev); 1380 Record.clear(); 1381 } 1382 1383 void DXILBitcodeWriter::writeDILocation(const DILocation *N, 1384 SmallVectorImpl<uint64_t> &Record, 1385 unsigned &Abbrev) { 1386 if (!Abbrev) 1387 Abbrev = createDILocationAbbrev(); 1388 Record.push_back(N->isDistinct()); 1389 Record.push_back(N->getLine()); 1390 Record.push_back(N->getColumn()); 1391 Record.push_back(VE.getMetadataID(N->getScope())); 1392 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt())); 1393 1394 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev); 1395 Record.clear(); 1396 } 1397 1398 static uint64_t rotateSign(APInt Val) { 1399 int64_t I = Val.getSExtValue(); 1400 uint64_t U = I; 1401 return I < 0 ? ~(U << 1) : U << 1; 1402 } 1403 1404 static uint64_t rotateSign(DISubrange::BoundType Val) { 1405 return rotateSign(Val.get<ConstantInt *>()->getValue()); 1406 } 1407 1408 void DXILBitcodeWriter::writeDISubrange(const DISubrange *N, 1409 SmallVectorImpl<uint64_t> &Record, 1410 unsigned Abbrev) { 1411 Record.push_back(N->isDistinct()); 1412 Record.push_back( 1413 N->getCount().get<ConstantInt *>()->getValue().getSExtValue()); 1414 Record.push_back(rotateSign(N->getLowerBound())); 1415 1416 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev); 1417 Record.clear(); 1418 } 1419 1420 void DXILBitcodeWriter::writeDIEnumerator(const DIEnumerator *N, 1421 SmallVectorImpl<uint64_t> &Record, 1422 unsigned Abbrev) { 1423 Record.push_back(N->isDistinct()); 1424 Record.push_back(rotateSign(N->getValue())); 1425 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1426 1427 Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev); 1428 Record.clear(); 1429 } 1430 1431 void DXILBitcodeWriter::writeDIBasicType(const DIBasicType *N, 1432 SmallVectorImpl<uint64_t> &Record, 1433 unsigned Abbrev) { 1434 Record.push_back(N->isDistinct()); 1435 Record.push_back(N->getTag()); 1436 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1437 Record.push_back(N->getSizeInBits()); 1438 Record.push_back(N->getAlignInBits()); 1439 Record.push_back(N->getEncoding()); 1440 1441 Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev); 1442 Record.clear(); 1443 } 1444 1445 void DXILBitcodeWriter::writeDIDerivedType(const DIDerivedType *N, 1446 SmallVectorImpl<uint64_t> &Record, 1447 unsigned Abbrev) { 1448 Record.push_back(N->isDistinct()); 1449 Record.push_back(N->getTag()); 1450 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1451 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1452 Record.push_back(N->getLine()); 1453 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1454 Record.push_back(VE.getMetadataOrNullID(N->getBaseType())); 1455 Record.push_back(N->getSizeInBits()); 1456 Record.push_back(N->getAlignInBits()); 1457 Record.push_back(N->getOffsetInBits()); 1458 Record.push_back(N->getFlags()); 1459 Record.push_back(VE.getMetadataOrNullID(N->getExtraData())); 1460 1461 Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev); 1462 Record.clear(); 1463 } 1464 1465 void DXILBitcodeWriter::writeDICompositeType(const DICompositeType *N, 1466 SmallVectorImpl<uint64_t> &Record, 1467 unsigned Abbrev) { 1468 Record.push_back(N->isDistinct()); 1469 Record.push_back(N->getTag()); 1470 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1471 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1472 Record.push_back(N->getLine()); 1473 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1474 Record.push_back(VE.getMetadataOrNullID(N->getBaseType())); 1475 Record.push_back(N->getSizeInBits()); 1476 Record.push_back(N->getAlignInBits()); 1477 Record.push_back(N->getOffsetInBits()); 1478 Record.push_back(N->getFlags()); 1479 Record.push_back(VE.getMetadataOrNullID(N->getElements().get())); 1480 Record.push_back(N->getRuntimeLang()); 1481 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder())); 1482 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get())); 1483 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier())); 1484 1485 Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev); 1486 Record.clear(); 1487 } 1488 1489 void DXILBitcodeWriter::writeDISubroutineType(const DISubroutineType *N, 1490 SmallVectorImpl<uint64_t> &Record, 1491 unsigned Abbrev) { 1492 Record.push_back(N->isDistinct()); 1493 Record.push_back(N->getFlags()); 1494 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get())); 1495 1496 Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev); 1497 Record.clear(); 1498 } 1499 1500 void DXILBitcodeWriter::writeDIFile(const DIFile *N, 1501 SmallVectorImpl<uint64_t> &Record, 1502 unsigned Abbrev) { 1503 Record.push_back(N->isDistinct()); 1504 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename())); 1505 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory())); 1506 1507 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev); 1508 Record.clear(); 1509 } 1510 1511 void DXILBitcodeWriter::writeDICompileUnit(const DICompileUnit *N, 1512 SmallVectorImpl<uint64_t> &Record, 1513 unsigned Abbrev) { 1514 Record.push_back(N->isDistinct()); 1515 Record.push_back(N->getSourceLanguage()); 1516 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1517 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer())); 1518 Record.push_back(N->isOptimized()); 1519 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags())); 1520 Record.push_back(N->getRuntimeVersion()); 1521 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename())); 1522 Record.push_back(N->getEmissionKind()); 1523 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get())); 1524 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get())); 1525 Record.push_back(/* subprograms */ 0); 1526 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get())); 1527 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get())); 1528 Record.push_back(N->getDWOId()); 1529 1530 Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev); 1531 Record.clear(); 1532 } 1533 1534 void DXILBitcodeWriter::writeDISubprogram(const DISubprogram *N, 1535 SmallVectorImpl<uint64_t> &Record, 1536 unsigned Abbrev) { 1537 Record.push_back(N->isDistinct()); 1538 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1539 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1540 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName())); 1541 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1542 Record.push_back(N->getLine()); 1543 Record.push_back(VE.getMetadataOrNullID(N->getType())); 1544 Record.push_back(N->isLocalToUnit()); 1545 Record.push_back(N->isDefinition()); 1546 Record.push_back(N->getScopeLine()); 1547 Record.push_back(VE.getMetadataOrNullID(N->getContainingType())); 1548 Record.push_back(N->getVirtuality()); 1549 Record.push_back(N->getVirtualIndex()); 1550 Record.push_back(N->getFlags()); 1551 Record.push_back(N->isOptimized()); 1552 Record.push_back(VE.getMetadataOrNullID(N->getRawUnit())); 1553 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get())); 1554 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration())); 1555 Record.push_back(VE.getMetadataOrNullID(N->getRetainedNodes().get())); 1556 1557 Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev); 1558 Record.clear(); 1559 } 1560 1561 void DXILBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N, 1562 SmallVectorImpl<uint64_t> &Record, 1563 unsigned Abbrev) { 1564 Record.push_back(N->isDistinct()); 1565 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1566 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1567 Record.push_back(N->getLine()); 1568 Record.push_back(N->getColumn()); 1569 1570 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev); 1571 Record.clear(); 1572 } 1573 1574 void DXILBitcodeWriter::writeDILexicalBlockFile( 1575 const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record, 1576 unsigned Abbrev) { 1577 Record.push_back(N->isDistinct()); 1578 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1579 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1580 Record.push_back(N->getDiscriminator()); 1581 1582 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev); 1583 Record.clear(); 1584 } 1585 1586 void DXILBitcodeWriter::writeDINamespace(const DINamespace *N, 1587 SmallVectorImpl<uint64_t> &Record, 1588 unsigned Abbrev) { 1589 Record.push_back(N->isDistinct()); 1590 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1591 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1592 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1593 Record.push_back(/* line number */ 0); 1594 1595 Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev); 1596 Record.clear(); 1597 } 1598 1599 void DXILBitcodeWriter::writeDIModule(const DIModule *N, 1600 SmallVectorImpl<uint64_t> &Record, 1601 unsigned Abbrev) { 1602 Record.push_back(N->isDistinct()); 1603 for (auto &I : N->operands()) 1604 Record.push_back(VE.getMetadataOrNullID(I)); 1605 1606 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev); 1607 Record.clear(); 1608 } 1609 1610 void DXILBitcodeWriter::writeDITemplateTypeParameter( 1611 const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record, 1612 unsigned Abbrev) { 1613 Record.push_back(N->isDistinct()); 1614 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1615 Record.push_back(VE.getMetadataOrNullID(N->getType())); 1616 1617 Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev); 1618 Record.clear(); 1619 } 1620 1621 void DXILBitcodeWriter::writeDITemplateValueParameter( 1622 const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record, 1623 unsigned Abbrev) { 1624 Record.push_back(N->isDistinct()); 1625 Record.push_back(N->getTag()); 1626 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1627 Record.push_back(VE.getMetadataOrNullID(N->getType())); 1628 Record.push_back(VE.getMetadataOrNullID(N->getValue())); 1629 1630 Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev); 1631 Record.clear(); 1632 } 1633 1634 void DXILBitcodeWriter::writeDIGlobalVariable(const DIGlobalVariable *N, 1635 SmallVectorImpl<uint64_t> &Record, 1636 unsigned Abbrev) { 1637 Record.push_back(N->isDistinct()); 1638 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1639 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1640 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName())); 1641 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1642 Record.push_back(N->getLine()); 1643 Record.push_back(VE.getMetadataOrNullID(N->getType())); 1644 Record.push_back(N->isLocalToUnit()); 1645 Record.push_back(N->isDefinition()); 1646 Record.push_back(/* N->getRawVariable() */ 0); 1647 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration())); 1648 1649 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev); 1650 Record.clear(); 1651 } 1652 1653 void DXILBitcodeWriter::writeDILocalVariable(const DILocalVariable *N, 1654 SmallVectorImpl<uint64_t> &Record, 1655 unsigned Abbrev) { 1656 Record.push_back(N->isDistinct()); 1657 Record.push_back(N->getTag()); 1658 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1659 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1660 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1661 Record.push_back(N->getLine()); 1662 Record.push_back(VE.getMetadataOrNullID(N->getType())); 1663 Record.push_back(N->getArg()); 1664 Record.push_back(N->getFlags()); 1665 1666 Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev); 1667 Record.clear(); 1668 } 1669 1670 void DXILBitcodeWriter::writeDIExpression(const DIExpression *N, 1671 SmallVectorImpl<uint64_t> &Record, 1672 unsigned Abbrev) { 1673 Record.reserve(N->getElements().size() + 1); 1674 1675 Record.push_back(N->isDistinct()); 1676 Record.append(N->elements_begin(), N->elements_end()); 1677 1678 Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev); 1679 Record.clear(); 1680 } 1681 1682 void DXILBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N, 1683 SmallVectorImpl<uint64_t> &Record, 1684 unsigned Abbrev) { 1685 llvm_unreachable("DXIL does not support objc!!!"); 1686 } 1687 1688 void DXILBitcodeWriter::writeDIImportedEntity(const DIImportedEntity *N, 1689 SmallVectorImpl<uint64_t> &Record, 1690 unsigned Abbrev) { 1691 Record.push_back(N->isDistinct()); 1692 Record.push_back(N->getTag()); 1693 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1694 Record.push_back(VE.getMetadataOrNullID(N->getEntity())); 1695 Record.push_back(N->getLine()); 1696 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1697 1698 Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev); 1699 Record.clear(); 1700 } 1701 1702 unsigned DXILBitcodeWriter::createDILocationAbbrev() { 1703 // Abbrev for METADATA_LOCATION. 1704 // 1705 // Assume the column is usually under 128, and always output the inlined-at 1706 // location (it's never more expensive than building an array size 1). 1707 std::shared_ptr<BitCodeAbbrev> Abbv = std::make_shared<BitCodeAbbrev>(); 1708 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION)); 1709 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); 1710 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1711 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 1712 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1713 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1714 return Stream.EmitAbbrev(std::move(Abbv)); 1715 } 1716 1717 unsigned DXILBitcodeWriter::createGenericDINodeAbbrev() { 1718 // Abbrev for METADATA_GENERIC_DEBUG. 1719 // 1720 // Assume the column is usually under 128, and always output the inlined-at 1721 // location (it's never more expensive than building an array size 1). 1722 std::shared_ptr<BitCodeAbbrev> Abbv = std::make_shared<BitCodeAbbrev>(); 1723 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG)); 1724 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); 1725 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1726 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); 1727 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1728 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1729 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1730 return Stream.EmitAbbrev(std::move(Abbv)); 1731 } 1732 1733 void DXILBitcodeWriter::writeMetadataRecords(ArrayRef<const Metadata *> MDs, 1734 SmallVectorImpl<uint64_t> &Record, 1735 std::vector<unsigned> *MDAbbrevs, 1736 std::vector<uint64_t> *IndexPos) { 1737 if (MDs.empty()) 1738 return; 1739 1740 // Initialize MDNode abbreviations. 1741 #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0; 1742 #include "llvm/IR/Metadata.def" 1743 1744 for (const Metadata *MD : MDs) { 1745 if (IndexPos) 1746 IndexPos->push_back(Stream.GetCurrentBitNo()); 1747 if (const MDNode *N = dyn_cast<MDNode>(MD)) { 1748 assert(N->isResolved() && "Expected forward references to be resolved"); 1749 1750 switch (N->getMetadataID()) { 1751 default: 1752 llvm_unreachable("Invalid MDNode subclass"); 1753 #define HANDLE_MDNODE_LEAF(CLASS) \ 1754 case Metadata::CLASS##Kind: \ 1755 if (MDAbbrevs) \ 1756 write##CLASS(cast<CLASS>(N), Record, \ 1757 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \ 1758 else \ 1759 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \ 1760 continue; 1761 #include "llvm/IR/Metadata.def" 1762 } 1763 } 1764 writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record); 1765 } 1766 } 1767 1768 unsigned DXILBitcodeWriter::createMetadataStringsAbbrev() { 1769 auto Abbv = std::make_shared<BitCodeAbbrev>(); 1770 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING_OLD)); 1771 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1772 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 1773 return Stream.EmitAbbrev(std::move(Abbv)); 1774 } 1775 1776 void DXILBitcodeWriter::writeMetadataStrings( 1777 ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) { 1778 for (const Metadata *MD : Strings) { 1779 const MDString *MDS = cast<MDString>(MD); 1780 // Code: [strchar x N] 1781 Record.append(MDS->bytes_begin(), MDS->bytes_end()); 1782 1783 // Emit the finished record. 1784 Stream.EmitRecord(bitc::METADATA_STRING_OLD, Record, 1785 createMetadataStringsAbbrev()); 1786 Record.clear(); 1787 } 1788 } 1789 1790 void DXILBitcodeWriter::writeModuleMetadata() { 1791 if (!VE.hasMDs() && M.named_metadata_empty()) 1792 return; 1793 1794 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 5); 1795 1796 // Emit all abbrevs upfront, so that the reader can jump in the middle of the 1797 // block and load any metadata. 1798 std::vector<unsigned> MDAbbrevs; 1799 1800 MDAbbrevs.resize(MetadataAbbrev::LastPlusOne); 1801 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev(); 1802 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] = 1803 createGenericDINodeAbbrev(); 1804 1805 unsigned NameAbbrev = 0; 1806 if (!M.named_metadata_empty()) { 1807 // Abbrev for METADATA_NAME. 1808 std::shared_ptr<BitCodeAbbrev> Abbv = std::make_shared<BitCodeAbbrev>(); 1809 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME)); 1810 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1811 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 1812 NameAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 1813 } 1814 1815 SmallVector<uint64_t, 64> Record; 1816 writeMetadataStrings(VE.getMDStrings(), Record); 1817 1818 std::vector<uint64_t> IndexPos; 1819 IndexPos.reserve(VE.getNonMDStrings().size()); 1820 writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos); 1821 1822 // Write named metadata. 1823 for (const NamedMDNode &NMD : M.named_metadata()) { 1824 // Write name. 1825 StringRef Str = NMD.getName(); 1826 Record.append(Str.bytes_begin(), Str.bytes_end()); 1827 Stream.EmitRecord(bitc::METADATA_NAME, Record, NameAbbrev); 1828 Record.clear(); 1829 1830 // Write named metadata operands. 1831 for (const MDNode *N : NMD.operands()) 1832 Record.push_back(VE.getMetadataID(N)); 1833 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0); 1834 Record.clear(); 1835 } 1836 1837 Stream.ExitBlock(); 1838 } 1839 1840 void DXILBitcodeWriter::writeFunctionMetadata(const Function &F) { 1841 if (!VE.hasMDs()) 1842 return; 1843 1844 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 4); 1845 SmallVector<uint64_t, 64> Record; 1846 writeMetadataStrings(VE.getMDStrings(), Record); 1847 writeMetadataRecords(VE.getNonMDStrings(), Record); 1848 Stream.ExitBlock(); 1849 } 1850 1851 void DXILBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) { 1852 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3); 1853 1854 SmallVector<uint64_t, 64> Record; 1855 1856 // Write metadata attachments 1857 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]] 1858 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 1859 F.getAllMetadata(MDs); 1860 if (!MDs.empty()) { 1861 for (const auto &I : MDs) { 1862 Record.push_back(I.first); 1863 Record.push_back(VE.getMetadataID(I.second)); 1864 } 1865 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0); 1866 Record.clear(); 1867 } 1868 1869 for (const BasicBlock &BB : F) 1870 for (const Instruction &I : BB) { 1871 MDs.clear(); 1872 I.getAllMetadataOtherThanDebugLoc(MDs); 1873 1874 // If no metadata, ignore instruction. 1875 if (MDs.empty()) 1876 continue; 1877 1878 Record.push_back(VE.getInstructionID(&I)); 1879 1880 for (unsigned i = 0, e = MDs.size(); i != e; ++i) { 1881 Record.push_back(MDs[i].first); 1882 Record.push_back(VE.getMetadataID(MDs[i].second)); 1883 } 1884 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0); 1885 Record.clear(); 1886 } 1887 1888 Stream.ExitBlock(); 1889 } 1890 1891 void DXILBitcodeWriter::writeModuleMetadataKinds() { 1892 SmallVector<uint64_t, 64> Record; 1893 1894 // Write metadata kinds 1895 // METADATA_KIND - [n x [id, name]] 1896 SmallVector<StringRef, 8> Names; 1897 M.getMDKindNames(Names); 1898 1899 if (Names.empty()) 1900 return; 1901 1902 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3); 1903 1904 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) { 1905 Record.push_back(MDKindID); 1906 StringRef KName = Names[MDKindID]; 1907 Record.append(KName.begin(), KName.end()); 1908 1909 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0); 1910 Record.clear(); 1911 } 1912 1913 Stream.ExitBlock(); 1914 } 1915 1916 void DXILBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal, 1917 bool isGlobal) { 1918 if (FirstVal == LastVal) 1919 return; 1920 1921 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4); 1922 1923 unsigned AggregateAbbrev = 0; 1924 unsigned String8Abbrev = 0; 1925 unsigned CString7Abbrev = 0; 1926 unsigned CString6Abbrev = 0; 1927 // If this is a constant pool for the module, emit module-specific abbrevs. 1928 if (isGlobal) { 1929 // Abbrev for CST_CODE_AGGREGATE. 1930 auto Abbv = std::make_shared<BitCodeAbbrev>(); 1931 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE)); 1932 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1933 Abbv->Add( 1934 BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal + 1))); 1935 AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 1936 1937 // Abbrev for CST_CODE_STRING. 1938 Abbv = std::make_shared<BitCodeAbbrev>(); 1939 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING)); 1940 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1941 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 1942 String8Abbrev = Stream.EmitAbbrev(std::move(Abbv)); 1943 // Abbrev for CST_CODE_CSTRING. 1944 Abbv = std::make_shared<BitCodeAbbrev>(); 1945 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING)); 1946 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1947 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); 1948 CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv)); 1949 // Abbrev for CST_CODE_CSTRING. 1950 Abbv = std::make_shared<BitCodeAbbrev>(); 1951 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING)); 1952 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1953 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 1954 CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv)); 1955 } 1956 1957 SmallVector<uint64_t, 64> Record; 1958 1959 const ValueEnumerator::ValueList &Vals = VE.getValues(); 1960 Type *LastTy = nullptr; 1961 for (unsigned i = FirstVal; i != LastVal; ++i) { 1962 const Value *V = Vals[i].first; 1963 // If we need to switch types, do so now. 1964 if (V->getType() != LastTy) { 1965 LastTy = V->getType(); 1966 Record.push_back(VE.getTypeID(LastTy)); 1967 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record, 1968 CONSTANTS_SETTYPE_ABBREV); 1969 Record.clear(); 1970 } 1971 1972 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) { 1973 Record.push_back(unsigned(IA->hasSideEffects()) | 1974 unsigned(IA->isAlignStack()) << 1 | 1975 unsigned(IA->getDialect() & 1) << 2); 1976 1977 // Add the asm string. 1978 const std::string &AsmStr = IA->getAsmString(); 1979 Record.push_back(AsmStr.size()); 1980 Record.append(AsmStr.begin(), AsmStr.end()); 1981 1982 // Add the constraint string. 1983 const std::string &ConstraintStr = IA->getConstraintString(); 1984 Record.push_back(ConstraintStr.size()); 1985 Record.append(ConstraintStr.begin(), ConstraintStr.end()); 1986 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record); 1987 Record.clear(); 1988 continue; 1989 } 1990 const Constant *C = cast<Constant>(V); 1991 unsigned Code = -1U; 1992 unsigned AbbrevToUse = 0; 1993 if (C->isNullValue()) { 1994 Code = bitc::CST_CODE_NULL; 1995 } else if (isa<UndefValue>(C)) { 1996 Code = bitc::CST_CODE_UNDEF; 1997 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) { 1998 if (IV->getBitWidth() <= 64) { 1999 uint64_t V = IV->getSExtValue(); 2000 emitSignedInt64(Record, V); 2001 Code = bitc::CST_CODE_INTEGER; 2002 AbbrevToUse = CONSTANTS_INTEGER_ABBREV; 2003 } else { // Wide integers, > 64 bits in size. 2004 // We have an arbitrary precision integer value to write whose 2005 // bit width is > 64. However, in canonical unsigned integer 2006 // format it is likely that the high bits are going to be zero. 2007 // So, we only write the number of active words. 2008 unsigned NWords = IV->getValue().getActiveWords(); 2009 const uint64_t *RawWords = IV->getValue().getRawData(); 2010 for (unsigned i = 0; i != NWords; ++i) { 2011 emitSignedInt64(Record, RawWords[i]); 2012 } 2013 Code = bitc::CST_CODE_WIDE_INTEGER; 2014 } 2015 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) { 2016 Code = bitc::CST_CODE_FLOAT; 2017 Type *Ty = CFP->getType(); 2018 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) { 2019 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue()); 2020 } else if (Ty->isX86_FP80Ty()) { 2021 // api needed to prevent premature destruction 2022 // bits are not in the same order as a normal i80 APInt, compensate. 2023 APInt api = CFP->getValueAPF().bitcastToAPInt(); 2024 const uint64_t *p = api.getRawData(); 2025 Record.push_back((p[1] << 48) | (p[0] >> 16)); 2026 Record.push_back(p[0] & 0xffffLL); 2027 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) { 2028 APInt api = CFP->getValueAPF().bitcastToAPInt(); 2029 const uint64_t *p = api.getRawData(); 2030 Record.push_back(p[0]); 2031 Record.push_back(p[1]); 2032 } else { 2033 assert(0 && "Unknown FP type!"); 2034 } 2035 } else if (isa<ConstantDataSequential>(C) && 2036 cast<ConstantDataSequential>(C)->isString()) { 2037 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C); 2038 // Emit constant strings specially. 2039 unsigned NumElts = Str->getNumElements(); 2040 // If this is a null-terminated string, use the denser CSTRING encoding. 2041 if (Str->isCString()) { 2042 Code = bitc::CST_CODE_CSTRING; 2043 --NumElts; // Don't encode the null, which isn't allowed by char6. 2044 } else { 2045 Code = bitc::CST_CODE_STRING; 2046 AbbrevToUse = String8Abbrev; 2047 } 2048 bool isCStr7 = Code == bitc::CST_CODE_CSTRING; 2049 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING; 2050 for (unsigned i = 0; i != NumElts; ++i) { 2051 unsigned char V = Str->getElementAsInteger(i); 2052 Record.push_back(V); 2053 isCStr7 &= (V & 128) == 0; 2054 if (isCStrChar6) 2055 isCStrChar6 = BitCodeAbbrevOp::isChar6(V); 2056 } 2057 2058 if (isCStrChar6) 2059 AbbrevToUse = CString6Abbrev; 2060 else if (isCStr7) 2061 AbbrevToUse = CString7Abbrev; 2062 } else if (const ConstantDataSequential *CDS = 2063 dyn_cast<ConstantDataSequential>(C)) { 2064 Code = bitc::CST_CODE_DATA; 2065 Type *EltTy = CDS->getType()->getArrayElementType(); 2066 if (isa<IntegerType>(EltTy)) { 2067 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) 2068 Record.push_back(CDS->getElementAsInteger(i)); 2069 } else if (EltTy->isFloatTy()) { 2070 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 2071 union { 2072 float F; 2073 uint32_t I; 2074 }; 2075 F = CDS->getElementAsFloat(i); 2076 Record.push_back(I); 2077 } 2078 } else { 2079 assert(EltTy->isDoubleTy() && "Unknown ConstantData element type"); 2080 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 2081 union { 2082 double F; 2083 uint64_t I; 2084 }; 2085 F = CDS->getElementAsDouble(i); 2086 Record.push_back(I); 2087 } 2088 } 2089 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) || 2090 isa<ConstantVector>(C)) { 2091 Code = bitc::CST_CODE_AGGREGATE; 2092 for (const Value *Op : C->operands()) 2093 Record.push_back(VE.getValueID(Op)); 2094 AbbrevToUse = AggregateAbbrev; 2095 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 2096 switch (CE->getOpcode()) { 2097 default: 2098 if (Instruction::isCast(CE->getOpcode())) { 2099 Code = bitc::CST_CODE_CE_CAST; 2100 Record.push_back(getEncodedCastOpcode(CE->getOpcode())); 2101 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 2102 Record.push_back(VE.getValueID(C->getOperand(0))); 2103 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev; 2104 } else { 2105 assert(CE->getNumOperands() == 2 && "Unknown constant expr!"); 2106 Code = bitc::CST_CODE_CE_BINOP; 2107 Record.push_back(getEncodedBinaryOpcode(CE->getOpcode())); 2108 Record.push_back(VE.getValueID(C->getOperand(0))); 2109 Record.push_back(VE.getValueID(C->getOperand(1))); 2110 uint64_t Flags = getOptimizationFlags(CE); 2111 if (Flags != 0) 2112 Record.push_back(Flags); 2113 } 2114 break; 2115 case Instruction::GetElementPtr: { 2116 Code = bitc::CST_CODE_CE_GEP; 2117 const auto *GO = cast<GEPOperator>(C); 2118 if (GO->isInBounds()) 2119 Code = bitc::CST_CODE_CE_INBOUNDS_GEP; 2120 Record.push_back(VE.getTypeID(GO->getSourceElementType())); 2121 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) { 2122 Record.push_back(VE.getTypeID(C->getOperand(i)->getType())); 2123 Record.push_back(VE.getValueID(C->getOperand(i))); 2124 } 2125 break; 2126 } 2127 case Instruction::Select: 2128 Code = bitc::CST_CODE_CE_SELECT; 2129 Record.push_back(VE.getValueID(C->getOperand(0))); 2130 Record.push_back(VE.getValueID(C->getOperand(1))); 2131 Record.push_back(VE.getValueID(C->getOperand(2))); 2132 break; 2133 case Instruction::ExtractElement: 2134 Code = bitc::CST_CODE_CE_EXTRACTELT; 2135 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 2136 Record.push_back(VE.getValueID(C->getOperand(0))); 2137 Record.push_back(VE.getTypeID(C->getOperand(1)->getType())); 2138 Record.push_back(VE.getValueID(C->getOperand(1))); 2139 break; 2140 case Instruction::InsertElement: 2141 Code = bitc::CST_CODE_CE_INSERTELT; 2142 Record.push_back(VE.getValueID(C->getOperand(0))); 2143 Record.push_back(VE.getValueID(C->getOperand(1))); 2144 Record.push_back(VE.getTypeID(C->getOperand(2)->getType())); 2145 Record.push_back(VE.getValueID(C->getOperand(2))); 2146 break; 2147 case Instruction::ShuffleVector: 2148 // If the return type and argument types are the same, this is a 2149 // standard shufflevector instruction. If the types are different, 2150 // then the shuffle is widening or truncating the input vectors, and 2151 // the argument type must also be encoded. 2152 if (C->getType() == C->getOperand(0)->getType()) { 2153 Code = bitc::CST_CODE_CE_SHUFFLEVEC; 2154 } else { 2155 Code = bitc::CST_CODE_CE_SHUFVEC_EX; 2156 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 2157 } 2158 Record.push_back(VE.getValueID(C->getOperand(0))); 2159 Record.push_back(VE.getValueID(C->getOperand(1))); 2160 Record.push_back(VE.getValueID(C->getOperand(2))); 2161 break; 2162 case Instruction::ICmp: 2163 case Instruction::FCmp: 2164 Code = bitc::CST_CODE_CE_CMP; 2165 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 2166 Record.push_back(VE.getValueID(C->getOperand(0))); 2167 Record.push_back(VE.getValueID(C->getOperand(1))); 2168 Record.push_back(CE->getPredicate()); 2169 break; 2170 } 2171 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) { 2172 Code = bitc::CST_CODE_BLOCKADDRESS; 2173 Record.push_back(VE.getTypeID(BA->getFunction()->getType())); 2174 Record.push_back(VE.getValueID(BA->getFunction())); 2175 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock())); 2176 } else { 2177 #ifndef NDEBUG 2178 C->dump(); 2179 #endif 2180 llvm_unreachable("Unknown constant!"); 2181 } 2182 Stream.EmitRecord(Code, Record, AbbrevToUse); 2183 Record.clear(); 2184 } 2185 2186 Stream.ExitBlock(); 2187 } 2188 2189 void DXILBitcodeWriter::writeModuleConstants() { 2190 const ValueEnumerator::ValueList &Vals = VE.getValues(); 2191 2192 // Find the first constant to emit, which is the first non-globalvalue value. 2193 // We know globalvalues have been emitted by WriteModuleInfo. 2194 for (unsigned i = 0, e = Vals.size(); i != e; ++i) { 2195 if (!isa<GlobalValue>(Vals[i].first)) { 2196 writeConstants(i, Vals.size(), true); 2197 return; 2198 } 2199 } 2200 } 2201 2202 /// pushValueAndType - The file has to encode both the value and type id for 2203 /// many values, because we need to know what type to create for forward 2204 /// references. However, most operands are not forward references, so this type 2205 /// field is not needed. 2206 /// 2207 /// This function adds V's value ID to Vals. If the value ID is higher than the 2208 /// instruction ID, then it is a forward reference, and it also includes the 2209 /// type ID. The value ID that is written is encoded relative to the InstID. 2210 bool DXILBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID, 2211 SmallVectorImpl<unsigned> &Vals) { 2212 unsigned ValID = VE.getValueID(V); 2213 // Make encoding relative to the InstID. 2214 Vals.push_back(InstID - ValID); 2215 if (ValID >= InstID) { 2216 Vals.push_back(VE.getTypeID(V->getType())); 2217 return true; 2218 } 2219 return false; 2220 } 2221 2222 /// pushValue - Like pushValueAndType, but where the type of the value is 2223 /// omitted (perhaps it was already encoded in an earlier operand). 2224 void DXILBitcodeWriter::pushValue(const Value *V, unsigned InstID, 2225 SmallVectorImpl<unsigned> &Vals) { 2226 unsigned ValID = VE.getValueID(V); 2227 Vals.push_back(InstID - ValID); 2228 } 2229 2230 void DXILBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID, 2231 SmallVectorImpl<uint64_t> &Vals) { 2232 unsigned ValID = VE.getValueID(V); 2233 int64_t diff = ((int32_t)InstID - (int32_t)ValID); 2234 emitSignedInt64(Vals, diff); 2235 } 2236 2237 /// WriteInstruction - Emit an instruction 2238 void DXILBitcodeWriter::writeInstruction(const Instruction &I, unsigned InstID, 2239 SmallVectorImpl<unsigned> &Vals) { 2240 unsigned Code = 0; 2241 unsigned AbbrevToUse = 0; 2242 VE.setInstructionID(&I); 2243 switch (I.getOpcode()) { 2244 default: 2245 if (Instruction::isCast(I.getOpcode())) { 2246 Code = bitc::FUNC_CODE_INST_CAST; 2247 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) 2248 AbbrevToUse = (unsigned)FUNCTION_INST_CAST_ABBREV; 2249 Vals.push_back(VE.getTypeID(I.getType())); 2250 Vals.push_back(getEncodedCastOpcode(I.getOpcode())); 2251 } else { 2252 assert(isa<BinaryOperator>(I) && "Unknown instruction!"); 2253 Code = bitc::FUNC_CODE_INST_BINOP; 2254 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) 2255 AbbrevToUse = (unsigned)FUNCTION_INST_BINOP_ABBREV; 2256 pushValue(I.getOperand(1), InstID, Vals); 2257 Vals.push_back(getEncodedBinaryOpcode(I.getOpcode())); 2258 uint64_t Flags = getOptimizationFlags(&I); 2259 if (Flags != 0) { 2260 if (AbbrevToUse == (unsigned)FUNCTION_INST_BINOP_ABBREV) 2261 AbbrevToUse = (unsigned)FUNCTION_INST_BINOP_FLAGS_ABBREV; 2262 Vals.push_back(Flags); 2263 } 2264 } 2265 break; 2266 2267 case Instruction::GetElementPtr: { 2268 Code = bitc::FUNC_CODE_INST_GEP; 2269 AbbrevToUse = (unsigned)FUNCTION_INST_GEP_ABBREV; 2270 auto &GEPInst = cast<GetElementPtrInst>(I); 2271 Vals.push_back(GEPInst.isInBounds()); 2272 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType())); 2273 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) 2274 pushValueAndType(I.getOperand(i), InstID, Vals); 2275 break; 2276 } 2277 case Instruction::ExtractValue: { 2278 Code = bitc::FUNC_CODE_INST_EXTRACTVAL; 2279 pushValueAndType(I.getOperand(0), InstID, Vals); 2280 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I); 2281 Vals.append(EVI->idx_begin(), EVI->idx_end()); 2282 break; 2283 } 2284 case Instruction::InsertValue: { 2285 Code = bitc::FUNC_CODE_INST_INSERTVAL; 2286 pushValueAndType(I.getOperand(0), InstID, Vals); 2287 pushValueAndType(I.getOperand(1), InstID, Vals); 2288 const InsertValueInst *IVI = cast<InsertValueInst>(&I); 2289 Vals.append(IVI->idx_begin(), IVI->idx_end()); 2290 break; 2291 } 2292 case Instruction::Select: 2293 Code = bitc::FUNC_CODE_INST_VSELECT; 2294 pushValueAndType(I.getOperand(1), InstID, Vals); 2295 pushValue(I.getOperand(2), InstID, Vals); 2296 pushValueAndType(I.getOperand(0), InstID, Vals); 2297 break; 2298 case Instruction::ExtractElement: 2299 Code = bitc::FUNC_CODE_INST_EXTRACTELT; 2300 pushValueAndType(I.getOperand(0), InstID, Vals); 2301 pushValueAndType(I.getOperand(1), InstID, Vals); 2302 break; 2303 case Instruction::InsertElement: 2304 Code = bitc::FUNC_CODE_INST_INSERTELT; 2305 pushValueAndType(I.getOperand(0), InstID, Vals); 2306 pushValue(I.getOperand(1), InstID, Vals); 2307 pushValueAndType(I.getOperand(2), InstID, Vals); 2308 break; 2309 case Instruction::ShuffleVector: 2310 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC; 2311 pushValueAndType(I.getOperand(0), InstID, Vals); 2312 pushValue(I.getOperand(1), InstID, Vals); 2313 pushValue(I.getOperand(2), InstID, Vals); 2314 break; 2315 case Instruction::ICmp: 2316 case Instruction::FCmp: { 2317 // compare returning Int1Ty or vector of Int1Ty 2318 Code = bitc::FUNC_CODE_INST_CMP2; 2319 pushValueAndType(I.getOperand(0), InstID, Vals); 2320 pushValue(I.getOperand(1), InstID, Vals); 2321 Vals.push_back(cast<CmpInst>(I).getPredicate()); 2322 uint64_t Flags = getOptimizationFlags(&I); 2323 if (Flags != 0) 2324 Vals.push_back(Flags); 2325 break; 2326 } 2327 2328 case Instruction::Ret: { 2329 Code = bitc::FUNC_CODE_INST_RET; 2330 unsigned NumOperands = I.getNumOperands(); 2331 if (NumOperands == 0) 2332 AbbrevToUse = (unsigned)FUNCTION_INST_RET_VOID_ABBREV; 2333 else if (NumOperands == 1) { 2334 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) 2335 AbbrevToUse = (unsigned)FUNCTION_INST_RET_VAL_ABBREV; 2336 } else { 2337 for (unsigned i = 0, e = NumOperands; i != e; ++i) 2338 pushValueAndType(I.getOperand(i), InstID, Vals); 2339 } 2340 } break; 2341 case Instruction::Br: { 2342 Code = bitc::FUNC_CODE_INST_BR; 2343 const BranchInst &II = cast<BranchInst>(I); 2344 Vals.push_back(VE.getValueID(II.getSuccessor(0))); 2345 if (II.isConditional()) { 2346 Vals.push_back(VE.getValueID(II.getSuccessor(1))); 2347 pushValue(II.getCondition(), InstID, Vals); 2348 } 2349 } break; 2350 case Instruction::Switch: { 2351 Code = bitc::FUNC_CODE_INST_SWITCH; 2352 const SwitchInst &SI = cast<SwitchInst>(I); 2353 Vals.push_back(VE.getTypeID(SI.getCondition()->getType())); 2354 pushValue(SI.getCondition(), InstID, Vals); 2355 Vals.push_back(VE.getValueID(SI.getDefaultDest())); 2356 for (auto Case : SI.cases()) { 2357 Vals.push_back(VE.getValueID(Case.getCaseValue())); 2358 Vals.push_back(VE.getValueID(Case.getCaseSuccessor())); 2359 } 2360 } break; 2361 case Instruction::IndirectBr: 2362 Code = bitc::FUNC_CODE_INST_INDIRECTBR; 2363 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); 2364 // Encode the address operand as relative, but not the basic blocks. 2365 pushValue(I.getOperand(0), InstID, Vals); 2366 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) 2367 Vals.push_back(VE.getValueID(I.getOperand(i))); 2368 break; 2369 2370 case Instruction::Invoke: { 2371 const InvokeInst *II = cast<InvokeInst>(&I); 2372 const Value *Callee = II->getCalledOperand(); 2373 FunctionType *FTy = II->getFunctionType(); 2374 Code = bitc::FUNC_CODE_INST_INVOKE; 2375 2376 Vals.push_back(VE.getAttributeListID(II->getAttributes())); 2377 Vals.push_back(II->getCallingConv() | 1 << 13); 2378 Vals.push_back(VE.getValueID(II->getNormalDest())); 2379 Vals.push_back(VE.getValueID(II->getUnwindDest())); 2380 Vals.push_back(VE.getTypeID(FTy)); 2381 pushValueAndType(Callee, InstID, Vals); 2382 2383 // Emit value #'s for the fixed parameters. 2384 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) 2385 pushValue(I.getOperand(i), InstID, Vals); // fixed param. 2386 2387 // Emit type/value pairs for varargs params. 2388 if (FTy->isVarArg()) { 2389 for (unsigned i = FTy->getNumParams(), e = I.getNumOperands() - 3; i != e; 2390 ++i) 2391 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg 2392 } 2393 break; 2394 } 2395 case Instruction::Resume: 2396 Code = bitc::FUNC_CODE_INST_RESUME; 2397 pushValueAndType(I.getOperand(0), InstID, Vals); 2398 break; 2399 case Instruction::Unreachable: 2400 Code = bitc::FUNC_CODE_INST_UNREACHABLE; 2401 AbbrevToUse = (unsigned)FUNCTION_INST_UNREACHABLE_ABBREV; 2402 break; 2403 2404 case Instruction::PHI: { 2405 const PHINode &PN = cast<PHINode>(I); 2406 Code = bitc::FUNC_CODE_INST_PHI; 2407 // With the newer instruction encoding, forward references could give 2408 // negative valued IDs. This is most common for PHIs, so we use 2409 // signed VBRs. 2410 SmallVector<uint64_t, 128> Vals64; 2411 Vals64.push_back(VE.getTypeID(PN.getType())); 2412 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) { 2413 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64); 2414 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i))); 2415 } 2416 // Emit a Vals64 vector and exit. 2417 Stream.EmitRecord(Code, Vals64, AbbrevToUse); 2418 Vals64.clear(); 2419 return; 2420 } 2421 2422 case Instruction::LandingPad: { 2423 const LandingPadInst &LP = cast<LandingPadInst>(I); 2424 Code = bitc::FUNC_CODE_INST_LANDINGPAD; 2425 Vals.push_back(VE.getTypeID(LP.getType())); 2426 Vals.push_back(LP.isCleanup()); 2427 Vals.push_back(LP.getNumClauses()); 2428 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) { 2429 if (LP.isCatch(I)) 2430 Vals.push_back(LandingPadInst::Catch); 2431 else 2432 Vals.push_back(LandingPadInst::Filter); 2433 pushValueAndType(LP.getClause(I), InstID, Vals); 2434 } 2435 break; 2436 } 2437 2438 case Instruction::Alloca: { 2439 Code = bitc::FUNC_CODE_INST_ALLOCA; 2440 const AllocaInst &AI = cast<AllocaInst>(I); 2441 Vals.push_back(VE.getTypeID(AI.getAllocatedType())); 2442 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); 2443 Vals.push_back(VE.getValueID(I.getOperand(0))); // size. 2444 using APV = AllocaPackedValues; 2445 unsigned Record = 0; 2446 unsigned EncodedAlign = getEncodedAlign(AI.getAlign()); 2447 Bitfield::set<APV::AlignLower>( 2448 Record, EncodedAlign & ((1 << APV::AlignLower::Bits) - 1)); 2449 Bitfield::set<APV::AlignUpper>(Record, 2450 EncodedAlign >> APV::AlignLower::Bits); 2451 Bitfield::set<APV::UsedWithInAlloca>(Record, AI.isUsedWithInAlloca()); 2452 Vals.push_back(Record); 2453 break; 2454 } 2455 2456 case Instruction::Load: 2457 if (cast<LoadInst>(I).isAtomic()) { 2458 Code = bitc::FUNC_CODE_INST_LOADATOMIC; 2459 pushValueAndType(I.getOperand(0), InstID, Vals); 2460 } else { 2461 Code = bitc::FUNC_CODE_INST_LOAD; 2462 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr 2463 AbbrevToUse = (unsigned)FUNCTION_INST_LOAD_ABBREV; 2464 } 2465 Vals.push_back(VE.getTypeID(I.getType())); 2466 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment()) + 1); 2467 Vals.push_back(cast<LoadInst>(I).isVolatile()); 2468 if (cast<LoadInst>(I).isAtomic()) { 2469 Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering())); 2470 Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID())); 2471 } 2472 break; 2473 case Instruction::Store: 2474 if (cast<StoreInst>(I).isAtomic()) 2475 Code = bitc::FUNC_CODE_INST_STOREATOMIC; 2476 else 2477 Code = bitc::FUNC_CODE_INST_STORE; 2478 pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr 2479 pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val 2480 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment()) + 1); 2481 Vals.push_back(cast<StoreInst>(I).isVolatile()); 2482 if (cast<StoreInst>(I).isAtomic()) { 2483 Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering())); 2484 Vals.push_back( 2485 getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID())); 2486 } 2487 break; 2488 case Instruction::AtomicCmpXchg: 2489 Code = bitc::FUNC_CODE_INST_CMPXCHG; 2490 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr 2491 pushValueAndType(I.getOperand(1), InstID, Vals); // cmp. 2492 pushValue(I.getOperand(2), InstID, Vals); // newval. 2493 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile()); 2494 Vals.push_back( 2495 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering())); 2496 Vals.push_back( 2497 getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID())); 2498 Vals.push_back( 2499 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering())); 2500 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak()); 2501 break; 2502 case Instruction::AtomicRMW: 2503 Code = bitc::FUNC_CODE_INST_ATOMICRMW; 2504 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr 2505 pushValue(I.getOperand(1), InstID, Vals); // val. 2506 Vals.push_back( 2507 getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation())); 2508 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile()); 2509 Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering())); 2510 Vals.push_back( 2511 getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID())); 2512 break; 2513 case Instruction::Fence: 2514 Code = bitc::FUNC_CODE_INST_FENCE; 2515 Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering())); 2516 Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID())); 2517 break; 2518 case Instruction::Call: { 2519 const CallInst &CI = cast<CallInst>(I); 2520 FunctionType *FTy = CI.getFunctionType(); 2521 2522 Code = bitc::FUNC_CODE_INST_CALL; 2523 2524 Vals.push_back(VE.getAttributeListID(CI.getAttributes())); 2525 Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall()) | 2526 unsigned(CI.isMustTailCall()) << 14 | 1 << 15); 2527 Vals.push_back(VE.getTypeID(FTy)); 2528 pushValueAndType(CI.getCalledOperand(), InstID, Vals); // Callee 2529 2530 // Emit value #'s for the fixed parameters. 2531 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) { 2532 // Check for labels (can happen with asm labels). 2533 if (FTy->getParamType(i)->isLabelTy()) 2534 Vals.push_back(VE.getValueID(CI.getArgOperand(i))); 2535 else 2536 pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param. 2537 } 2538 2539 // Emit type/value pairs for varargs params. 2540 if (FTy->isVarArg()) { 2541 for (unsigned i = FTy->getNumParams(), e = CI.arg_size(); i != e; ++i) 2542 pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs 2543 } 2544 break; 2545 } 2546 case Instruction::VAArg: 2547 Code = bitc::FUNC_CODE_INST_VAARG; 2548 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty 2549 pushValue(I.getOperand(0), InstID, Vals); // valist. 2550 Vals.push_back(VE.getTypeID(I.getType())); // restype. 2551 break; 2552 } 2553 2554 Stream.EmitRecord(Code, Vals, AbbrevToUse); 2555 Vals.clear(); 2556 } 2557 2558 // Emit names for globals/functions etc. 2559 void DXILBitcodeWriter::writeFunctionLevelValueSymbolTable( 2560 const ValueSymbolTable &VST) { 2561 if (VST.empty()) 2562 return; 2563 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4); 2564 2565 SmallVector<unsigned, 64> NameVals; 2566 2567 // HLSL Change 2568 // Read the named values from a sorted list instead of the original list 2569 // to ensure the binary is the same no matter what values ever existed. 2570 SmallVector<const ValueName *, 16> SortedTable; 2571 2572 for (auto &VI : VST) { 2573 SortedTable.push_back(VI.second->getValueName()); 2574 } 2575 // The keys are unique, so there shouldn't be stability issues. 2576 std::sort(SortedTable.begin(), SortedTable.end(), 2577 [](const ValueName *A, const ValueName *B) { 2578 return A->first() < B->first(); 2579 }); 2580 2581 for (const ValueName *SI : SortedTable) { 2582 auto &Name = *SI; 2583 2584 // Figure out the encoding to use for the name. 2585 bool is7Bit = true; 2586 bool isChar6 = true; 2587 for (const char *C = Name.getKeyData(), *E = C + Name.getKeyLength(); 2588 C != E; ++C) { 2589 if (isChar6) 2590 isChar6 = BitCodeAbbrevOp::isChar6(*C); 2591 if ((unsigned char)*C & 128) { 2592 is7Bit = false; 2593 break; // don't bother scanning the rest. 2594 } 2595 } 2596 2597 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV; 2598 2599 // VST_ENTRY: [valueid, namechar x N] 2600 // VST_BBENTRY: [bbid, namechar x N] 2601 unsigned Code; 2602 if (isa<BasicBlock>(SI->getValue())) { 2603 Code = bitc::VST_CODE_BBENTRY; 2604 if (isChar6) 2605 AbbrevToUse = VST_BBENTRY_6_ABBREV; 2606 } else { 2607 Code = bitc::VST_CODE_ENTRY; 2608 if (isChar6) 2609 AbbrevToUse = VST_ENTRY_6_ABBREV; 2610 else if (is7Bit) 2611 AbbrevToUse = VST_ENTRY_7_ABBREV; 2612 } 2613 2614 NameVals.push_back(VE.getValueID(SI->getValue())); 2615 for (const char *P = Name.getKeyData(), 2616 *E = Name.getKeyData() + Name.getKeyLength(); 2617 P != E; ++P) 2618 NameVals.push_back((unsigned char)*P); 2619 2620 // Emit the finished record. 2621 Stream.EmitRecord(Code, NameVals, AbbrevToUse); 2622 NameVals.clear(); 2623 } 2624 Stream.ExitBlock(); 2625 } 2626 2627 void DXILBitcodeWriter::writeUseList(UseListOrder &&Order) { 2628 assert(Order.Shuffle.size() >= 2 && "Shuffle too small"); 2629 unsigned Code; 2630 if (isa<BasicBlock>(Order.V)) 2631 Code = bitc::USELIST_CODE_BB; 2632 else 2633 Code = bitc::USELIST_CODE_DEFAULT; 2634 2635 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end()); 2636 Record.push_back(VE.getValueID(Order.V)); 2637 Stream.EmitRecord(Code, Record); 2638 } 2639 2640 void DXILBitcodeWriter::writeUseListBlock(const Function *F) { 2641 assert(VE.shouldPreserveUseListOrder() && 2642 "Expected to be preserving use-list order"); 2643 2644 auto hasMore = [&]() { 2645 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F; 2646 }; 2647 if (!hasMore()) 2648 // Nothing to do. 2649 return; 2650 2651 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3); 2652 while (hasMore()) { 2653 writeUseList(std::move(VE.UseListOrders.back())); 2654 VE.UseListOrders.pop_back(); 2655 } 2656 Stream.ExitBlock(); 2657 } 2658 2659 /// Emit a function body to the module stream. 2660 void DXILBitcodeWriter::writeFunction(const Function &F) { 2661 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4); 2662 VE.incorporateFunction(F); 2663 2664 SmallVector<unsigned, 64> Vals; 2665 2666 // Emit the number of basic blocks, so the reader can create them ahead of 2667 // time. 2668 Vals.push_back(VE.getBasicBlocks().size()); 2669 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals); 2670 Vals.clear(); 2671 2672 // If there are function-local constants, emit them now. 2673 unsigned CstStart, CstEnd; 2674 VE.getFunctionConstantRange(CstStart, CstEnd); 2675 writeConstants(CstStart, CstEnd, false); 2676 2677 // If there is function-local metadata, emit it now. 2678 writeFunctionMetadata(F); 2679 2680 // Keep a running idea of what the instruction ID is. 2681 unsigned InstID = CstEnd; 2682 2683 bool NeedsMetadataAttachment = F.hasMetadata(); 2684 2685 DILocation *LastDL = nullptr; 2686 2687 // Finally, emit all the instructions, in order. 2688 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) 2689 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; 2690 ++I) { 2691 writeInstruction(*I, InstID, Vals); 2692 2693 if (!I->getType()->isVoidTy()) 2694 ++InstID; 2695 2696 // If the instruction has metadata, write a metadata attachment later. 2697 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc(); 2698 2699 // If the instruction has a debug location, emit it. 2700 DILocation *DL = I->getDebugLoc(); 2701 if (!DL) 2702 continue; 2703 2704 if (DL == LastDL) { 2705 // Just repeat the same debug loc as last time. 2706 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals); 2707 continue; 2708 } 2709 2710 Vals.push_back(DL->getLine()); 2711 Vals.push_back(DL->getColumn()); 2712 Vals.push_back(VE.getMetadataOrNullID(DL->getScope())); 2713 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt())); 2714 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals); 2715 Vals.clear(); 2716 2717 LastDL = DL; 2718 } 2719 2720 // Emit names for all the instructions etc. 2721 if (auto *Symtab = F.getValueSymbolTable()) 2722 writeFunctionLevelValueSymbolTable(*Symtab); 2723 2724 if (NeedsMetadataAttachment) 2725 writeFunctionMetadataAttachment(F); 2726 if (VE.shouldPreserveUseListOrder()) 2727 writeUseListBlock(&F); 2728 VE.purgeFunction(); 2729 Stream.ExitBlock(); 2730 } 2731 2732 // Emit blockinfo, which defines the standard abbreviations etc. 2733 void DXILBitcodeWriter::writeBlockInfo() { 2734 // We only want to emit block info records for blocks that have multiple 2735 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK. 2736 // Other blocks can define their abbrevs inline. 2737 Stream.EnterBlockInfoBlock(); 2738 2739 { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings. 2740 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2741 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); 2742 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 2743 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2744 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 2745 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, 2746 std::move(Abbv)) != VST_ENTRY_8_ABBREV) 2747 assert(false && "Unexpected abbrev ordering!"); 2748 } 2749 2750 { // 7-bit fixed width VST_ENTRY strings. 2751 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2752 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY)); 2753 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 2754 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2755 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); 2756 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, 2757 std::move(Abbv)) != VST_ENTRY_7_ABBREV) 2758 assert(false && "Unexpected abbrev ordering!"); 2759 } 2760 { // 6-bit char6 VST_ENTRY strings. 2761 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2762 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY)); 2763 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 2764 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2765 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 2766 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, 2767 std::move(Abbv)) != VST_ENTRY_6_ABBREV) 2768 assert(false && "Unexpected abbrev ordering!"); 2769 } 2770 { // 6-bit char6 VST_BBENTRY strings. 2771 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2772 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY)); 2773 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 2774 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2775 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 2776 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, 2777 std::move(Abbv)) != VST_BBENTRY_6_ABBREV) 2778 assert(false && "Unexpected abbrev ordering!"); 2779 } 2780 2781 { // SETTYPE abbrev for CONSTANTS_BLOCK. 2782 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2783 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE)); 2784 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2785 VE.computeBitsRequiredForTypeIndicies())); 2786 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, std::move(Abbv)) != 2787 CONSTANTS_SETTYPE_ABBREV) 2788 assert(false && "Unexpected abbrev ordering!"); 2789 } 2790 2791 { // INTEGER abbrev for CONSTANTS_BLOCK. 2792 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2793 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER)); 2794 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 2795 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, std::move(Abbv)) != 2796 CONSTANTS_INTEGER_ABBREV) 2797 assert(false && "Unexpected abbrev ordering!"); 2798 } 2799 2800 { // CE_CAST abbrev for CONSTANTS_BLOCK. 2801 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2802 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST)); 2803 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc 2804 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid 2805 VE.computeBitsRequiredForTypeIndicies())); 2806 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id 2807 2808 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, std::move(Abbv)) != 2809 CONSTANTS_CE_CAST_Abbrev) 2810 assert(false && "Unexpected abbrev ordering!"); 2811 } 2812 { // NULL abbrev for CONSTANTS_BLOCK. 2813 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2814 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL)); 2815 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, std::move(Abbv)) != 2816 CONSTANTS_NULL_Abbrev) 2817 assert(false && "Unexpected abbrev ordering!"); 2818 } 2819 2820 // FIXME: This should only use space for first class types! 2821 2822 { // INST_LOAD abbrev for FUNCTION_BLOCK. 2823 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2824 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD)); 2825 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr 2826 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty 2827 VE.computeBitsRequiredForTypeIndicies())); 2828 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align 2829 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile 2830 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) != 2831 (unsigned)FUNCTION_INST_LOAD_ABBREV) 2832 assert(false && "Unexpected abbrev ordering!"); 2833 } 2834 { // INST_BINOP abbrev for FUNCTION_BLOCK. 2835 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2836 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP)); 2837 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS 2838 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS 2839 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 2840 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) != 2841 (unsigned)FUNCTION_INST_BINOP_ABBREV) 2842 assert(false && "Unexpected abbrev ordering!"); 2843 } 2844 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK. 2845 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2846 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP)); 2847 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS 2848 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS 2849 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 2850 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags 2851 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) != 2852 (unsigned)FUNCTION_INST_BINOP_FLAGS_ABBREV) 2853 assert(false && "Unexpected abbrev ordering!"); 2854 } 2855 { // INST_CAST abbrev for FUNCTION_BLOCK. 2856 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2857 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST)); 2858 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal 2859 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty 2860 VE.computeBitsRequiredForTypeIndicies())); 2861 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 2862 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) != 2863 (unsigned)FUNCTION_INST_CAST_ABBREV) 2864 assert(false && "Unexpected abbrev ordering!"); 2865 } 2866 2867 { // INST_RET abbrev for FUNCTION_BLOCK. 2868 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2869 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET)); 2870 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) != 2871 (unsigned)FUNCTION_INST_RET_VOID_ABBREV) 2872 assert(false && "Unexpected abbrev ordering!"); 2873 } 2874 { // INST_RET abbrev for FUNCTION_BLOCK. 2875 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2876 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET)); 2877 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID 2878 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) != 2879 (unsigned)FUNCTION_INST_RET_VAL_ABBREV) 2880 assert(false && "Unexpected abbrev ordering!"); 2881 } 2882 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK. 2883 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2884 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE)); 2885 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) != 2886 (unsigned)FUNCTION_INST_UNREACHABLE_ABBREV) 2887 assert(false && "Unexpected abbrev ordering!"); 2888 } 2889 { 2890 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2891 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP)); 2892 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); 2893 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty 2894 Log2_32_Ceil(VE.getTypes().size() + 1))); 2895 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2896 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 2897 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) != 2898 (unsigned)FUNCTION_INST_GEP_ABBREV) 2899 assert(false && "Unexpected abbrev ordering!"); 2900 } 2901 2902 Stream.ExitBlock(); 2903 } 2904 2905 void DXILBitcodeWriter::writeModuleVersion() { 2906 // VERSION: [version#] 2907 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, ArrayRef<unsigned>{1}); 2908 } 2909 2910 /// WriteModule - Emit the specified module to the bitstream. 2911 void DXILBitcodeWriter::write() { 2912 // The identification block is new since llvm-3.7, but the old bitcode reader 2913 // will skip it. 2914 // writeIdentificationBlock(Stream); 2915 2916 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3); 2917 2918 // It is redundant to fully-specify this here, but nice to make it explicit 2919 // so that it is clear the DXIL module version is different. 2920 DXILBitcodeWriter::writeModuleVersion(); 2921 2922 // Emit blockinfo, which defines the standard abbreviations etc. 2923 writeBlockInfo(); 2924 2925 // Emit information about attribute groups. 2926 writeAttributeGroupTable(); 2927 2928 // Emit information about parameter attributes. 2929 writeAttributeTable(); 2930 2931 // Emit information describing all of the types in the module. 2932 writeTypeTable(); 2933 2934 writeComdats(); 2935 2936 // Emit top-level description of module, including target triple, inline asm, 2937 // descriptors for global variables, and function prototype info. 2938 writeModuleInfo(); 2939 2940 // Emit constants. 2941 writeModuleConstants(); 2942 2943 // Emit metadata. 2944 writeModuleMetadataKinds(); 2945 2946 // Emit metadata. 2947 writeModuleMetadata(); 2948 2949 // Emit names for globals/functions etc. 2950 // DXIL uses the same format for module-level value symbol table as for the 2951 // function level table. 2952 writeFunctionLevelValueSymbolTable(M.getValueSymbolTable()); 2953 2954 // Emit module-level use-lists. 2955 if (VE.shouldPreserveUseListOrder()) 2956 writeUseListBlock(nullptr); 2957 2958 // Emit function bodies. 2959 for (const Function &F : M) 2960 if (!F.isDeclaration()) 2961 writeFunction(F); 2962 2963 Stream.ExitBlock(); 2964 } 2965