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