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