Path: blob/main/contrib/llvm-project/llvm/lib/Target/DirectX/DXILWriter/DXILBitcodeWriter.cpp
35293 views
//===- Bitcode/Writer/DXILBitcodeWriter.cpp - DXIL Bitcode Writer ---------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// Bitcode writer implementation.9//10//===----------------------------------------------------------------------===//1112#include "DXILBitcodeWriter.h"13#include "DXILValueEnumerator.h"14#include "DirectXIRPasses/PointerTypeAnalysis.h"15#include "llvm/ADT/STLExtras.h"16#include "llvm/Bitcode/BitcodeCommon.h"17#include "llvm/Bitcode/BitcodeReader.h"18#include "llvm/Bitcode/LLVMBitCodes.h"19#include "llvm/Bitstream/BitCodes.h"20#include "llvm/Bitstream/BitstreamWriter.h"21#include "llvm/IR/Attributes.h"22#include "llvm/IR/BasicBlock.h"23#include "llvm/IR/Comdat.h"24#include "llvm/IR/Constant.h"25#include "llvm/IR/Constants.h"26#include "llvm/IR/DebugInfoMetadata.h"27#include "llvm/IR/DebugLoc.h"28#include "llvm/IR/DerivedTypes.h"29#include "llvm/IR/Function.h"30#include "llvm/IR/GlobalAlias.h"31#include "llvm/IR/GlobalIFunc.h"32#include "llvm/IR/GlobalObject.h"33#include "llvm/IR/GlobalValue.h"34#include "llvm/IR/GlobalVariable.h"35#include "llvm/IR/InlineAsm.h"36#include "llvm/IR/InstrTypes.h"37#include "llvm/IR/Instruction.h"38#include "llvm/IR/Instructions.h"39#include "llvm/IR/LLVMContext.h"40#include "llvm/IR/Metadata.h"41#include "llvm/IR/Module.h"42#include "llvm/IR/ModuleSummaryIndex.h"43#include "llvm/IR/Operator.h"44#include "llvm/IR/Type.h"45#include "llvm/IR/UseListOrder.h"46#include "llvm/IR/Value.h"47#include "llvm/IR/ValueSymbolTable.h"48#include "llvm/Object/IRSymtab.h"49#include "llvm/Support/ErrorHandling.h"50#include "llvm/Support/ModRef.h"51#include "llvm/Support/SHA1.h"52#include "llvm/TargetParser/Triple.h"5354namespace llvm {55namespace dxil {5657// Generates an enum to use as an index in the Abbrev array of Metadata record.58enum MetadataAbbrev : unsigned {59#define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,60#include "llvm/IR/Metadata.def"61LastPlusOne62};6364class DXILBitcodeWriter {6566/// These are manifest constants used by the bitcode writer. They do not need67/// to be kept in sync with the reader, but need to be consistent within this68/// file.69enum {70// VALUE_SYMTAB_BLOCK abbrev id's.71VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,72VST_ENTRY_7_ABBREV,73VST_ENTRY_6_ABBREV,74VST_BBENTRY_6_ABBREV,7576// CONSTANTS_BLOCK abbrev id's.77CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,78CONSTANTS_INTEGER_ABBREV,79CONSTANTS_CE_CAST_Abbrev,80CONSTANTS_NULL_Abbrev,8182// FUNCTION_BLOCK abbrev id's.83FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,84FUNCTION_INST_BINOP_ABBREV,85FUNCTION_INST_BINOP_FLAGS_ABBREV,86FUNCTION_INST_CAST_ABBREV,87FUNCTION_INST_RET_VOID_ABBREV,88FUNCTION_INST_RET_VAL_ABBREV,89FUNCTION_INST_UNREACHABLE_ABBREV,90FUNCTION_INST_GEP_ABBREV,91};9293// Cache some types94Type *I8Ty;95Type *I8PtrTy;9697/// The stream created and owned by the client.98BitstreamWriter &Stream;99100StringTableBuilder &StrtabBuilder;101102/// The Module to write to bitcode.103const Module &M;104105/// Enumerates ids for all values in the module.106ValueEnumerator VE;107108/// Map that holds the correspondence between GUIDs in the summary index,109/// that came from indirect call profiles, and a value id generated by this110/// class to use in the VST and summary block records.111std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;112113/// Tracks the last value id recorded in the GUIDToValueMap.114unsigned GlobalValueId;115116/// Saves the offset of the VSTOffset record that must eventually be117/// backpatched with the offset of the actual VST.118uint64_t VSTOffsetPlaceholder = 0;119120/// Pointer to the buffer allocated by caller for bitcode writing.121const SmallVectorImpl<char> &Buffer;122123/// The start bit of the identification block.124uint64_t BitcodeStartBit;125126/// This maps values to their typed pointers127PointerTypeMap PointerMap;128129public:130/// Constructs a ModuleBitcodeWriter object for the given Module,131/// writing to the provided \p Buffer.132DXILBitcodeWriter(const Module &M, SmallVectorImpl<char> &Buffer,133StringTableBuilder &StrtabBuilder, BitstreamWriter &Stream)134: I8Ty(Type::getInt8Ty(M.getContext())),135I8PtrTy(TypedPointerType::get(I8Ty, 0)), Stream(Stream),136StrtabBuilder(StrtabBuilder), M(M), VE(M, I8PtrTy), Buffer(Buffer),137BitcodeStartBit(Stream.GetCurrentBitNo()),138PointerMap(PointerTypeAnalysis::run(M)) {139GlobalValueId = VE.getValues().size();140// Enumerate the typed pointers141for (auto El : PointerMap)142VE.EnumerateType(El.second);143}144145/// Emit the current module to the bitstream.146void write();147148static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind);149static void writeStringRecord(BitstreamWriter &Stream, unsigned Code,150StringRef Str, unsigned AbbrevToUse);151static void writeIdentificationBlock(BitstreamWriter &Stream);152static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V);153static void emitWideAPInt(SmallVectorImpl<uint64_t> &Vals, const APInt &A);154155static unsigned getEncodedComdatSelectionKind(const Comdat &C);156static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage);157static unsigned getEncodedLinkage(const GlobalValue &GV);158static unsigned getEncodedVisibility(const GlobalValue &GV);159static unsigned getEncodedThreadLocalMode(const GlobalValue &GV);160static unsigned getEncodedDLLStorageClass(const GlobalValue &GV);161static unsigned getEncodedCastOpcode(unsigned Opcode);162static unsigned getEncodedUnaryOpcode(unsigned Opcode);163static unsigned getEncodedBinaryOpcode(unsigned Opcode);164static unsigned getEncodedRMWOperation(AtomicRMWInst::BinOp Op);165static unsigned getEncodedOrdering(AtomicOrdering Ordering);166static uint64_t getOptimizationFlags(const Value *V);167168private:169void writeModuleVersion();170void writePerModuleGlobalValueSummary();171172void writePerModuleFunctionSummaryRecord(SmallVector<uint64_t, 64> &NameVals,173GlobalValueSummary *Summary,174unsigned ValueID,175unsigned FSCallsAbbrev,176unsigned FSCallsProfileAbbrev,177const Function &F);178void writeModuleLevelReferences(const GlobalVariable &V,179SmallVector<uint64_t, 64> &NameVals,180unsigned FSModRefsAbbrev,181unsigned FSModVTableRefsAbbrev);182183void assignValueId(GlobalValue::GUID ValGUID) {184GUIDToValueIdMap[ValGUID] = ++GlobalValueId;185}186187unsigned getValueId(GlobalValue::GUID ValGUID) {188const auto &VMI = GUIDToValueIdMap.find(ValGUID);189// Expect that any GUID value had a value Id assigned by an190// earlier call to assignValueId.191assert(VMI != GUIDToValueIdMap.end() &&192"GUID does not have assigned value Id");193return VMI->second;194}195196// Helper to get the valueId for the type of value recorded in VI.197unsigned getValueId(ValueInfo VI) {198if (!VI.haveGVs() || !VI.getValue())199return getValueId(VI.getGUID());200return VE.getValueID(VI.getValue());201}202203std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }204205uint64_t bitcodeStartBit() { return BitcodeStartBit; }206207size_t addToStrtab(StringRef Str);208209unsigned createDILocationAbbrev();210unsigned createGenericDINodeAbbrev();211212void writeAttributeGroupTable();213void writeAttributeTable();214void writeTypeTable();215void writeComdats();216void writeValueSymbolTableForwardDecl();217void writeModuleInfo();218void writeValueAsMetadata(const ValueAsMetadata *MD,219SmallVectorImpl<uint64_t> &Record);220void writeMDTuple(const MDTuple *N, SmallVectorImpl<uint64_t> &Record,221unsigned Abbrev);222void writeDILocation(const DILocation *N, SmallVectorImpl<uint64_t> &Record,223unsigned &Abbrev);224void writeGenericDINode(const GenericDINode *N,225SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev) {226llvm_unreachable("DXIL cannot contain GenericDI Nodes");227}228void writeDISubrange(const DISubrange *N, SmallVectorImpl<uint64_t> &Record,229unsigned Abbrev);230void writeDIGenericSubrange(const DIGenericSubrange *N,231SmallVectorImpl<uint64_t> &Record,232unsigned Abbrev) {233llvm_unreachable("DXIL cannot contain DIGenericSubrange Nodes");234}235void writeDIEnumerator(const DIEnumerator *N,236SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);237void writeDIBasicType(const DIBasicType *N, SmallVectorImpl<uint64_t> &Record,238unsigned Abbrev);239void writeDIStringType(const DIStringType *N,240SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {241llvm_unreachable("DXIL cannot contain DIStringType Nodes");242}243void writeDIDerivedType(const DIDerivedType *N,244SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);245void writeDICompositeType(const DICompositeType *N,246SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);247void writeDISubroutineType(const DISubroutineType *N,248SmallVectorImpl<uint64_t> &Record,249unsigned Abbrev);250void writeDIFile(const DIFile *N, SmallVectorImpl<uint64_t> &Record,251unsigned Abbrev);252void writeDICompileUnit(const DICompileUnit *N,253SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);254void writeDISubprogram(const DISubprogram *N,255SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);256void writeDILexicalBlock(const DILexicalBlock *N,257SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);258void writeDILexicalBlockFile(const DILexicalBlockFile *N,259SmallVectorImpl<uint64_t> &Record,260unsigned Abbrev);261void writeDICommonBlock(const DICommonBlock *N,262SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {263llvm_unreachable("DXIL cannot contain DICommonBlock Nodes");264}265void writeDINamespace(const DINamespace *N, SmallVectorImpl<uint64_t> &Record,266unsigned Abbrev);267void writeDIMacro(const DIMacro *N, SmallVectorImpl<uint64_t> &Record,268unsigned Abbrev) {269llvm_unreachable("DXIL cannot contain DIMacro Nodes");270}271void writeDIMacroFile(const DIMacroFile *N, SmallVectorImpl<uint64_t> &Record,272unsigned Abbrev) {273llvm_unreachable("DXIL cannot contain DIMacroFile Nodes");274}275void writeDIArgList(const DIArgList *N, SmallVectorImpl<uint64_t> &Record,276unsigned Abbrev) {277llvm_unreachable("DXIL cannot contain DIArgList Nodes");278}279void writeDIAssignID(const DIAssignID *N, SmallVectorImpl<uint64_t> &Record,280unsigned Abbrev) {281// DIAssignID is experimental feature to track variable location in IR..282// FIXME: translate DIAssignID to debug info DXIL supports.283// See https://github.com/llvm/llvm-project/issues/58989284llvm_unreachable("DXIL cannot contain DIAssignID Nodes");285}286void writeDIModule(const DIModule *N, SmallVectorImpl<uint64_t> &Record,287unsigned Abbrev);288void writeDITemplateTypeParameter(const DITemplateTypeParameter *N,289SmallVectorImpl<uint64_t> &Record,290unsigned Abbrev);291void writeDITemplateValueParameter(const DITemplateValueParameter *N,292SmallVectorImpl<uint64_t> &Record,293unsigned Abbrev);294void writeDIGlobalVariable(const DIGlobalVariable *N,295SmallVectorImpl<uint64_t> &Record,296unsigned Abbrev);297void writeDILocalVariable(const DILocalVariable *N,298SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);299void writeDILabel(const DILabel *N, SmallVectorImpl<uint64_t> &Record,300unsigned Abbrev) {301llvm_unreachable("DXIL cannot contain DILabel Nodes");302}303void writeDIExpression(const DIExpression *N,304SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);305void writeDIGlobalVariableExpression(const DIGlobalVariableExpression *N,306SmallVectorImpl<uint64_t> &Record,307unsigned Abbrev) {308llvm_unreachable("DXIL cannot contain GlobalVariableExpression Nodes");309}310void writeDIObjCProperty(const DIObjCProperty *N,311SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);312void writeDIImportedEntity(const DIImportedEntity *N,313SmallVectorImpl<uint64_t> &Record,314unsigned Abbrev);315unsigned createNamedMetadataAbbrev();316void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);317unsigned createMetadataStringsAbbrev();318void writeMetadataStrings(ArrayRef<const Metadata *> Strings,319SmallVectorImpl<uint64_t> &Record);320void writeMetadataRecords(ArrayRef<const Metadata *> MDs,321SmallVectorImpl<uint64_t> &Record,322std::vector<unsigned> *MDAbbrevs = nullptr,323std::vector<uint64_t> *IndexPos = nullptr);324void writeModuleMetadata();325void writeFunctionMetadata(const Function &F);326void writeFunctionMetadataAttachment(const Function &F);327void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,328const GlobalObject &GO);329void writeModuleMetadataKinds();330void writeOperandBundleTags();331void writeSyncScopeNames();332void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal);333void writeModuleConstants();334bool pushValueAndType(const Value *V, unsigned InstID,335SmallVectorImpl<unsigned> &Vals);336void writeOperandBundles(const CallBase &CB, unsigned InstID);337void pushValue(const Value *V, unsigned InstID,338SmallVectorImpl<unsigned> &Vals);339void pushValueSigned(const Value *V, unsigned InstID,340SmallVectorImpl<uint64_t> &Vals);341void writeInstruction(const Instruction &I, unsigned InstID,342SmallVectorImpl<unsigned> &Vals);343void writeFunctionLevelValueSymbolTable(const ValueSymbolTable &VST);344void writeGlobalValueSymbolTable(345DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);346void writeFunction(const Function &F);347void writeBlockInfo();348349unsigned getEncodedSyncScopeID(SyncScope::ID SSID) { return unsigned(SSID); }350351unsigned getEncodedAlign(MaybeAlign Alignment) { return encode(Alignment); }352353unsigned getTypeID(Type *T, const Value *V = nullptr);354/// getGlobalObjectValueTypeID - returns the element type for a GlobalObject355///356/// GlobalObject types are saved by PointerTypeAnalysis as pointers to the357/// GlobalObject, but in the bitcode writer we need the pointer element type.358unsigned getGlobalObjectValueTypeID(Type *T, const GlobalObject *G);359};360361} // namespace dxil362} // namespace llvm363364using namespace llvm;365using namespace llvm::dxil;366367////////////////////////////////////////////////////////////////////////////////368/// Begin dxil::BitcodeWriter Implementation369////////////////////////////////////////////////////////////////////////////////370371dxil::BitcodeWriter::BitcodeWriter(SmallVectorImpl<char> &Buffer)372: Buffer(Buffer), Stream(new BitstreamWriter(Buffer)) {373// Emit the file header.374Stream->Emit((unsigned)'B', 8);375Stream->Emit((unsigned)'C', 8);376Stream->Emit(0x0, 4);377Stream->Emit(0xC, 4);378Stream->Emit(0xE, 4);379Stream->Emit(0xD, 4);380}381382dxil::BitcodeWriter::~BitcodeWriter() { }383384/// Write the specified module to the specified output stream.385void dxil::WriteDXILToFile(const Module &M, raw_ostream &Out) {386SmallVector<char, 0> Buffer;387Buffer.reserve(256 * 1024);388389// If this is darwin or another generic macho target, reserve space for the390// header.391Triple TT(M.getTargetTriple());392if (TT.isOSDarwin() || TT.isOSBinFormatMachO())393Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);394395BitcodeWriter Writer(Buffer);396Writer.writeModule(M);397398// Write the generated bitstream to "Out".399if (!Buffer.empty())400Out.write((char *)&Buffer.front(), Buffer.size());401}402403void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) {404Stream->EnterSubblock(Block, 3);405406auto Abbv = std::make_shared<BitCodeAbbrev>();407Abbv->Add(BitCodeAbbrevOp(Record));408Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));409auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv));410411Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob);412413Stream->ExitBlock();414}415416void BitcodeWriter::writeModule(const Module &M) {417418// The Mods vector is used by irsymtab::build, which requires non-const419// Modules in case it needs to materialize metadata. But the bitcode writer420// requires that the module is materialized, so we can cast to non-const here,421// after checking that it is in fact materialized.422assert(M.isMaterialized());423Mods.push_back(const_cast<Module *>(&M));424425DXILBitcodeWriter ModuleWriter(M, Buffer, StrtabBuilder, *Stream);426ModuleWriter.write();427}428429////////////////////////////////////////////////////////////////////////////////430/// Begin dxil::BitcodeWriterBase Implementation431////////////////////////////////////////////////////////////////////////////////432433unsigned DXILBitcodeWriter::getEncodedCastOpcode(unsigned Opcode) {434switch (Opcode) {435default:436llvm_unreachable("Unknown cast instruction!");437case Instruction::Trunc:438return bitc::CAST_TRUNC;439case Instruction::ZExt:440return bitc::CAST_ZEXT;441case Instruction::SExt:442return bitc::CAST_SEXT;443case Instruction::FPToUI:444return bitc::CAST_FPTOUI;445case Instruction::FPToSI:446return bitc::CAST_FPTOSI;447case Instruction::UIToFP:448return bitc::CAST_UITOFP;449case Instruction::SIToFP:450return bitc::CAST_SITOFP;451case Instruction::FPTrunc:452return bitc::CAST_FPTRUNC;453case Instruction::FPExt:454return bitc::CAST_FPEXT;455case Instruction::PtrToInt:456return bitc::CAST_PTRTOINT;457case Instruction::IntToPtr:458return bitc::CAST_INTTOPTR;459case Instruction::BitCast:460return bitc::CAST_BITCAST;461case Instruction::AddrSpaceCast:462return bitc::CAST_ADDRSPACECAST;463}464}465466unsigned DXILBitcodeWriter::getEncodedUnaryOpcode(unsigned Opcode) {467switch (Opcode) {468default:469llvm_unreachable("Unknown binary instruction!");470case Instruction::FNeg:471return bitc::UNOP_FNEG;472}473}474475unsigned DXILBitcodeWriter::getEncodedBinaryOpcode(unsigned Opcode) {476switch (Opcode) {477default:478llvm_unreachable("Unknown binary instruction!");479case Instruction::Add:480case Instruction::FAdd:481return bitc::BINOP_ADD;482case Instruction::Sub:483case Instruction::FSub:484return bitc::BINOP_SUB;485case Instruction::Mul:486case Instruction::FMul:487return bitc::BINOP_MUL;488case Instruction::UDiv:489return bitc::BINOP_UDIV;490case Instruction::FDiv:491case Instruction::SDiv:492return bitc::BINOP_SDIV;493case Instruction::URem:494return bitc::BINOP_UREM;495case Instruction::FRem:496case Instruction::SRem:497return bitc::BINOP_SREM;498case Instruction::Shl:499return bitc::BINOP_SHL;500case Instruction::LShr:501return bitc::BINOP_LSHR;502case Instruction::AShr:503return bitc::BINOP_ASHR;504case Instruction::And:505return bitc::BINOP_AND;506case Instruction::Or:507return bitc::BINOP_OR;508case Instruction::Xor:509return bitc::BINOP_XOR;510}511}512513unsigned DXILBitcodeWriter::getTypeID(Type *T, const Value *V) {514if (!T->isPointerTy() &&515// For Constant, always check PointerMap to make sure OpaquePointer in516// things like constant struct/array works.517(!V || !isa<Constant>(V)))518return VE.getTypeID(T);519auto It = PointerMap.find(V);520if (It != PointerMap.end())521return VE.getTypeID(It->second);522// For Constant, return T when cannot find in PointerMap.523// FIXME: support ConstantPointerNull which could map to more than one524// TypedPointerType.525// See https://github.com/llvm/llvm-project/issues/57942.526if (V && isa<Constant>(V) && !isa<ConstantPointerNull>(V))527return VE.getTypeID(T);528return VE.getTypeID(I8PtrTy);529}530531unsigned DXILBitcodeWriter::getGlobalObjectValueTypeID(Type *T,532const GlobalObject *G) {533auto It = PointerMap.find(G);534if (It != PointerMap.end()) {535TypedPointerType *PtrTy = cast<TypedPointerType>(It->second);536return VE.getTypeID(PtrTy->getElementType());537}538return VE.getTypeID(T);539}540541unsigned DXILBitcodeWriter::getEncodedRMWOperation(AtomicRMWInst::BinOp Op) {542switch (Op) {543default:544llvm_unreachable("Unknown RMW operation!");545case AtomicRMWInst::Xchg:546return bitc::RMW_XCHG;547case AtomicRMWInst::Add:548return bitc::RMW_ADD;549case AtomicRMWInst::Sub:550return bitc::RMW_SUB;551case AtomicRMWInst::And:552return bitc::RMW_AND;553case AtomicRMWInst::Nand:554return bitc::RMW_NAND;555case AtomicRMWInst::Or:556return bitc::RMW_OR;557case AtomicRMWInst::Xor:558return bitc::RMW_XOR;559case AtomicRMWInst::Max:560return bitc::RMW_MAX;561case AtomicRMWInst::Min:562return bitc::RMW_MIN;563case AtomicRMWInst::UMax:564return bitc::RMW_UMAX;565case AtomicRMWInst::UMin:566return bitc::RMW_UMIN;567case AtomicRMWInst::FAdd:568return bitc::RMW_FADD;569case AtomicRMWInst::FSub:570return bitc::RMW_FSUB;571case AtomicRMWInst::FMax:572return bitc::RMW_FMAX;573case AtomicRMWInst::FMin:574return bitc::RMW_FMIN;575}576}577578unsigned DXILBitcodeWriter::getEncodedOrdering(AtomicOrdering Ordering) {579switch (Ordering) {580case AtomicOrdering::NotAtomic:581return bitc::ORDERING_NOTATOMIC;582case AtomicOrdering::Unordered:583return bitc::ORDERING_UNORDERED;584case AtomicOrdering::Monotonic:585return bitc::ORDERING_MONOTONIC;586case AtomicOrdering::Acquire:587return bitc::ORDERING_ACQUIRE;588case AtomicOrdering::Release:589return bitc::ORDERING_RELEASE;590case AtomicOrdering::AcquireRelease:591return bitc::ORDERING_ACQREL;592case AtomicOrdering::SequentiallyConsistent:593return bitc::ORDERING_SEQCST;594}595llvm_unreachable("Invalid ordering");596}597598void DXILBitcodeWriter::writeStringRecord(BitstreamWriter &Stream,599unsigned Code, StringRef Str,600unsigned AbbrevToUse) {601SmallVector<unsigned, 64> Vals;602603// Code: [strchar x N]604for (char C : Str) {605if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(C))606AbbrevToUse = 0;607Vals.push_back(C);608}609610// Emit the finished record.611Stream.EmitRecord(Code, Vals, AbbrevToUse);612}613614uint64_t DXILBitcodeWriter::getAttrKindEncoding(Attribute::AttrKind Kind) {615switch (Kind) {616case Attribute::Alignment:617return bitc::ATTR_KIND_ALIGNMENT;618case Attribute::AlwaysInline:619return bitc::ATTR_KIND_ALWAYS_INLINE;620case Attribute::Builtin:621return bitc::ATTR_KIND_BUILTIN;622case Attribute::ByVal:623return bitc::ATTR_KIND_BY_VAL;624case Attribute::Convergent:625return bitc::ATTR_KIND_CONVERGENT;626case Attribute::InAlloca:627return bitc::ATTR_KIND_IN_ALLOCA;628case Attribute::Cold:629return bitc::ATTR_KIND_COLD;630case Attribute::InlineHint:631return bitc::ATTR_KIND_INLINE_HINT;632case Attribute::InReg:633return bitc::ATTR_KIND_IN_REG;634case Attribute::JumpTable:635return bitc::ATTR_KIND_JUMP_TABLE;636case Attribute::MinSize:637return bitc::ATTR_KIND_MIN_SIZE;638case Attribute::Naked:639return bitc::ATTR_KIND_NAKED;640case Attribute::Nest:641return bitc::ATTR_KIND_NEST;642case Attribute::NoAlias:643return bitc::ATTR_KIND_NO_ALIAS;644case Attribute::NoBuiltin:645return bitc::ATTR_KIND_NO_BUILTIN;646case Attribute::NoCapture:647return bitc::ATTR_KIND_NO_CAPTURE;648case Attribute::NoDuplicate:649return bitc::ATTR_KIND_NO_DUPLICATE;650case Attribute::NoImplicitFloat:651return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;652case Attribute::NoInline:653return bitc::ATTR_KIND_NO_INLINE;654case Attribute::NonLazyBind:655return bitc::ATTR_KIND_NON_LAZY_BIND;656case Attribute::NonNull:657return bitc::ATTR_KIND_NON_NULL;658case Attribute::Dereferenceable:659return bitc::ATTR_KIND_DEREFERENCEABLE;660case Attribute::DereferenceableOrNull:661return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL;662case Attribute::NoRedZone:663return bitc::ATTR_KIND_NO_RED_ZONE;664case Attribute::NoReturn:665return bitc::ATTR_KIND_NO_RETURN;666case Attribute::NoUnwind:667return bitc::ATTR_KIND_NO_UNWIND;668case Attribute::OptimizeForSize:669return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;670case Attribute::OptimizeNone:671return bitc::ATTR_KIND_OPTIMIZE_NONE;672case Attribute::ReadNone:673return bitc::ATTR_KIND_READ_NONE;674case Attribute::ReadOnly:675return bitc::ATTR_KIND_READ_ONLY;676case Attribute::Returned:677return bitc::ATTR_KIND_RETURNED;678case Attribute::ReturnsTwice:679return bitc::ATTR_KIND_RETURNS_TWICE;680case Attribute::SExt:681return bitc::ATTR_KIND_S_EXT;682case Attribute::StackAlignment:683return bitc::ATTR_KIND_STACK_ALIGNMENT;684case Attribute::StackProtect:685return bitc::ATTR_KIND_STACK_PROTECT;686case Attribute::StackProtectReq:687return bitc::ATTR_KIND_STACK_PROTECT_REQ;688case Attribute::StackProtectStrong:689return bitc::ATTR_KIND_STACK_PROTECT_STRONG;690case Attribute::SafeStack:691return bitc::ATTR_KIND_SAFESTACK;692case Attribute::StructRet:693return bitc::ATTR_KIND_STRUCT_RET;694case Attribute::SanitizeAddress:695return bitc::ATTR_KIND_SANITIZE_ADDRESS;696case Attribute::SanitizeThread:697return bitc::ATTR_KIND_SANITIZE_THREAD;698case Attribute::SanitizeMemory:699return bitc::ATTR_KIND_SANITIZE_MEMORY;700case Attribute::UWTable:701return bitc::ATTR_KIND_UW_TABLE;702case Attribute::ZExt:703return bitc::ATTR_KIND_Z_EXT;704case Attribute::EndAttrKinds:705llvm_unreachable("Can not encode end-attribute kinds marker.");706case Attribute::None:707llvm_unreachable("Can not encode none-attribute.");708case Attribute::EmptyKey:709case Attribute::TombstoneKey:710llvm_unreachable("Trying to encode EmptyKey/TombstoneKey");711default:712llvm_unreachable("Trying to encode attribute not supported by DXIL. These "713"should be stripped in DXILPrepare");714}715716llvm_unreachable("Trying to encode unknown attribute");717}718719void DXILBitcodeWriter::emitSignedInt64(SmallVectorImpl<uint64_t> &Vals,720uint64_t V) {721if ((int64_t)V >= 0)722Vals.push_back(V << 1);723else724Vals.push_back((-V << 1) | 1);725}726727void DXILBitcodeWriter::emitWideAPInt(SmallVectorImpl<uint64_t> &Vals,728const APInt &A) {729// We have an arbitrary precision integer value to write whose730// bit width is > 64. However, in canonical unsigned integer731// format it is likely that the high bits are going to be zero.732// So, we only write the number of active words.733unsigned NumWords = A.getActiveWords();734const uint64_t *RawData = A.getRawData();735for (unsigned i = 0; i < NumWords; i++)736emitSignedInt64(Vals, RawData[i]);737}738739uint64_t DXILBitcodeWriter::getOptimizationFlags(const Value *V) {740uint64_t Flags = 0;741742if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {743if (OBO->hasNoSignedWrap())744Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;745if (OBO->hasNoUnsignedWrap())746Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;747} else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {748if (PEO->isExact())749Flags |= 1 << bitc::PEO_EXACT;750} else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {751if (FPMO->hasAllowReassoc())752Flags |= bitc::AllowReassoc;753if (FPMO->hasNoNaNs())754Flags |= bitc::NoNaNs;755if (FPMO->hasNoInfs())756Flags |= bitc::NoInfs;757if (FPMO->hasNoSignedZeros())758Flags |= bitc::NoSignedZeros;759if (FPMO->hasAllowReciprocal())760Flags |= bitc::AllowReciprocal;761if (FPMO->hasAllowContract())762Flags |= bitc::AllowContract;763if (FPMO->hasApproxFunc())764Flags |= bitc::ApproxFunc;765}766767return Flags;768}769770unsigned771DXILBitcodeWriter::getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {772switch (Linkage) {773case GlobalValue::ExternalLinkage:774return 0;775case GlobalValue::WeakAnyLinkage:776return 16;777case GlobalValue::AppendingLinkage:778return 2;779case GlobalValue::InternalLinkage:780return 3;781case GlobalValue::LinkOnceAnyLinkage:782return 18;783case GlobalValue::ExternalWeakLinkage:784return 7;785case GlobalValue::CommonLinkage:786return 8;787case GlobalValue::PrivateLinkage:788return 9;789case GlobalValue::WeakODRLinkage:790return 17;791case GlobalValue::LinkOnceODRLinkage:792return 19;793case GlobalValue::AvailableExternallyLinkage:794return 12;795}796llvm_unreachable("Invalid linkage");797}798799unsigned DXILBitcodeWriter::getEncodedLinkage(const GlobalValue &GV) {800return getEncodedLinkage(GV.getLinkage());801}802803unsigned DXILBitcodeWriter::getEncodedVisibility(const GlobalValue &GV) {804switch (GV.getVisibility()) {805case GlobalValue::DefaultVisibility:806return 0;807case GlobalValue::HiddenVisibility:808return 1;809case GlobalValue::ProtectedVisibility:810return 2;811}812llvm_unreachable("Invalid visibility");813}814815unsigned DXILBitcodeWriter::getEncodedDLLStorageClass(const GlobalValue &GV) {816switch (GV.getDLLStorageClass()) {817case GlobalValue::DefaultStorageClass:818return 0;819case GlobalValue::DLLImportStorageClass:820return 1;821case GlobalValue::DLLExportStorageClass:822return 2;823}824llvm_unreachable("Invalid DLL storage class");825}826827unsigned DXILBitcodeWriter::getEncodedThreadLocalMode(const GlobalValue &GV) {828switch (GV.getThreadLocalMode()) {829case GlobalVariable::NotThreadLocal:830return 0;831case GlobalVariable::GeneralDynamicTLSModel:832return 1;833case GlobalVariable::LocalDynamicTLSModel:834return 2;835case GlobalVariable::InitialExecTLSModel:836return 3;837case GlobalVariable::LocalExecTLSModel:838return 4;839}840llvm_unreachable("Invalid TLS model");841}842843unsigned DXILBitcodeWriter::getEncodedComdatSelectionKind(const Comdat &C) {844switch (C.getSelectionKind()) {845case Comdat::Any:846return bitc::COMDAT_SELECTION_KIND_ANY;847case Comdat::ExactMatch:848return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;849case Comdat::Largest:850return bitc::COMDAT_SELECTION_KIND_LARGEST;851case Comdat::NoDeduplicate:852return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;853case Comdat::SameSize:854return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;855}856llvm_unreachable("Invalid selection kind");857}858859////////////////////////////////////////////////////////////////////////////////860/// Begin DXILBitcodeWriter Implementation861////////////////////////////////////////////////////////////////////////////////862863void DXILBitcodeWriter::writeAttributeGroupTable() {864const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =865VE.getAttributeGroups();866if (AttrGrps.empty())867return;868869Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);870871SmallVector<uint64_t, 64> Record;872for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) {873unsigned AttrListIndex = Pair.first;874AttributeSet AS = Pair.second;875Record.push_back(VE.getAttributeGroupID(Pair));876Record.push_back(AttrListIndex);877878for (Attribute Attr : AS) {879if (Attr.isEnumAttribute()) {880uint64_t Val = getAttrKindEncoding(Attr.getKindAsEnum());881assert(Val <= bitc::ATTR_KIND_ARGMEMONLY &&882"DXIL does not support attributes above ATTR_KIND_ARGMEMONLY");883Record.push_back(0);884Record.push_back(Val);885} else if (Attr.isIntAttribute()) {886if (Attr.getKindAsEnum() == Attribute::AttrKind::Memory) {887MemoryEffects ME = Attr.getMemoryEffects();888if (ME.doesNotAccessMemory()) {889Record.push_back(0);890Record.push_back(bitc::ATTR_KIND_READ_NONE);891} else {892if (ME.onlyReadsMemory()) {893Record.push_back(0);894Record.push_back(bitc::ATTR_KIND_READ_ONLY);895}896if (ME.onlyAccessesArgPointees()) {897Record.push_back(0);898Record.push_back(bitc::ATTR_KIND_ARGMEMONLY);899}900}901} else {902uint64_t Val = getAttrKindEncoding(Attr.getKindAsEnum());903assert(Val <= bitc::ATTR_KIND_ARGMEMONLY &&904"DXIL does not support attributes above ATTR_KIND_ARGMEMONLY");905Record.push_back(1);906Record.push_back(Val);907Record.push_back(Attr.getValueAsInt());908}909} else {910StringRef Kind = Attr.getKindAsString();911StringRef Val = Attr.getValueAsString();912913Record.push_back(Val.empty() ? 3 : 4);914Record.append(Kind.begin(), Kind.end());915Record.push_back(0);916if (!Val.empty()) {917Record.append(Val.begin(), Val.end());918Record.push_back(0);919}920}921}922923Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);924Record.clear();925}926927Stream.ExitBlock();928}929930void DXILBitcodeWriter::writeAttributeTable() {931const std::vector<AttributeList> &Attrs = VE.getAttributeLists();932if (Attrs.empty())933return;934935Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);936937SmallVector<uint64_t, 64> Record;938for (AttributeList AL : Attrs) {939for (unsigned i : AL.indexes()) {940AttributeSet AS = AL.getAttributes(i);941if (AS.hasAttributes())942Record.push_back(VE.getAttributeGroupID({i, AS}));943}944945Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);946Record.clear();947}948949Stream.ExitBlock();950}951952/// WriteTypeTable - Write out the type table for a module.953void DXILBitcodeWriter::writeTypeTable() {954const ValueEnumerator::TypeList &TypeList = VE.getTypes();955956Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);957SmallVector<uint64_t, 64> TypeVals;958959uint64_t NumBits = VE.computeBitsRequiredForTypeIndices();960961// Abbrev for TYPE_CODE_POINTER.962auto Abbv = std::make_shared<BitCodeAbbrev>();963Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));964Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));965Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0966unsigned PtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));967968// Abbrev for TYPE_CODE_FUNCTION.969Abbv = std::make_shared<BitCodeAbbrev>();970Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));971Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg972Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));973Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));974unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));975976// Abbrev for TYPE_CODE_STRUCT_ANON.977Abbv = std::make_shared<BitCodeAbbrev>();978Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));979Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked980Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));981Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));982unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));983984// Abbrev for TYPE_CODE_STRUCT_NAME.985Abbv = std::make_shared<BitCodeAbbrev>();986Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));987Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));988Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));989unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));990991// Abbrev for TYPE_CODE_STRUCT_NAMED.992Abbv = std::make_shared<BitCodeAbbrev>();993Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));994Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked995Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));996Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));997unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));998999// Abbrev for TYPE_CODE_ARRAY.1000Abbv = std::make_shared<BitCodeAbbrev>();1001Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));1002Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size1003Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));1004unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));10051006// Emit an entry count so the reader can reserve space.1007TypeVals.push_back(TypeList.size());1008Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);1009TypeVals.clear();10101011// Loop over all of the types, emitting each in turn.1012for (Type *T : TypeList) {1013int AbbrevToUse = 0;1014unsigned Code = 0;10151016switch (T->getTypeID()) {1017case Type::BFloatTyID:1018case Type::X86_AMXTyID:1019case Type::TokenTyID:1020case Type::TargetExtTyID:1021llvm_unreachable("These should never be used!!!");1022break;1023case Type::VoidTyID:1024Code = bitc::TYPE_CODE_VOID;1025break;1026case Type::HalfTyID:1027Code = bitc::TYPE_CODE_HALF;1028break;1029case Type::FloatTyID:1030Code = bitc::TYPE_CODE_FLOAT;1031break;1032case Type::DoubleTyID:1033Code = bitc::TYPE_CODE_DOUBLE;1034break;1035case Type::X86_FP80TyID:1036Code = bitc::TYPE_CODE_X86_FP80;1037break;1038case Type::FP128TyID:1039Code = bitc::TYPE_CODE_FP128;1040break;1041case Type::PPC_FP128TyID:1042Code = bitc::TYPE_CODE_PPC_FP128;1043break;1044case Type::LabelTyID:1045Code = bitc::TYPE_CODE_LABEL;1046break;1047case Type::MetadataTyID:1048Code = bitc::TYPE_CODE_METADATA;1049break;1050case Type::X86_MMXTyID:1051Code = bitc::TYPE_CODE_X86_MMX;1052break;1053case Type::IntegerTyID:1054// INTEGER: [width]1055Code = bitc::TYPE_CODE_INTEGER;1056TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());1057break;1058case Type::TypedPointerTyID: {1059TypedPointerType *PTy = cast<TypedPointerType>(T);1060// POINTER: [pointee type, address space]1061Code = bitc::TYPE_CODE_POINTER;1062TypeVals.push_back(getTypeID(PTy->getElementType()));1063unsigned AddressSpace = PTy->getAddressSpace();1064TypeVals.push_back(AddressSpace);1065if (AddressSpace == 0)1066AbbrevToUse = PtrAbbrev;1067break;1068}1069case Type::PointerTyID: {1070// POINTER: [pointee type, address space]1071// Emitting an empty struct type for the pointer's type allows this to be1072// order-independent. Non-struct types must be emitted in bitcode before1073// they can be referenced.1074TypeVals.push_back(false);1075Code = bitc::TYPE_CODE_OPAQUE;1076writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME,1077"dxilOpaquePtrReservedName", StructNameAbbrev);1078break;1079}1080case Type::FunctionTyID: {1081FunctionType *FT = cast<FunctionType>(T);1082// FUNCTION: [isvararg, retty, paramty x N]1083Code = bitc::TYPE_CODE_FUNCTION;1084TypeVals.push_back(FT->isVarArg());1085TypeVals.push_back(getTypeID(FT->getReturnType()));1086for (Type *PTy : FT->params())1087TypeVals.push_back(getTypeID(PTy));1088AbbrevToUse = FunctionAbbrev;1089break;1090}1091case Type::StructTyID: {1092StructType *ST = cast<StructType>(T);1093// STRUCT: [ispacked, eltty x N]1094TypeVals.push_back(ST->isPacked());1095// Output all of the element types.1096for (Type *ElTy : ST->elements())1097TypeVals.push_back(getTypeID(ElTy));10981099if (ST->isLiteral()) {1100Code = bitc::TYPE_CODE_STRUCT_ANON;1101AbbrevToUse = StructAnonAbbrev;1102} else {1103if (ST->isOpaque()) {1104Code = bitc::TYPE_CODE_OPAQUE;1105} else {1106Code = bitc::TYPE_CODE_STRUCT_NAMED;1107AbbrevToUse = StructNamedAbbrev;1108}11091110// Emit the name if it is present.1111if (!ST->getName().empty())1112writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),1113StructNameAbbrev);1114}1115break;1116}1117case Type::ArrayTyID: {1118ArrayType *AT = cast<ArrayType>(T);1119// ARRAY: [numelts, eltty]1120Code = bitc::TYPE_CODE_ARRAY;1121TypeVals.push_back(AT->getNumElements());1122TypeVals.push_back(getTypeID(AT->getElementType()));1123AbbrevToUse = ArrayAbbrev;1124break;1125}1126case Type::FixedVectorTyID:1127case Type::ScalableVectorTyID: {1128VectorType *VT = cast<VectorType>(T);1129// VECTOR [numelts, eltty]1130Code = bitc::TYPE_CODE_VECTOR;1131TypeVals.push_back(VT->getElementCount().getKnownMinValue());1132TypeVals.push_back(getTypeID(VT->getElementType()));1133break;1134}1135}11361137// Emit the finished record.1138Stream.EmitRecord(Code, TypeVals, AbbrevToUse);1139TypeVals.clear();1140}11411142Stream.ExitBlock();1143}11441145void DXILBitcodeWriter::writeComdats() {1146SmallVector<uint16_t, 64> Vals;1147for (const Comdat *C : VE.getComdats()) {1148// COMDAT: [selection_kind, name]1149Vals.push_back(getEncodedComdatSelectionKind(*C));1150size_t Size = C->getName().size();1151assert(isUInt<16>(Size));1152Vals.push_back(Size);1153for (char Chr : C->getName())1154Vals.push_back((unsigned char)Chr);1155Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);1156Vals.clear();1157}1158}11591160void DXILBitcodeWriter::writeValueSymbolTableForwardDecl() {}11611162/// Emit top-level description of module, including target triple, inline asm,1163/// descriptors for global variables, and function prototype info.1164/// Returns the bit offset to backpatch with the location of the real VST.1165void DXILBitcodeWriter::writeModuleInfo() {1166// Emit various pieces of data attached to a module.1167if (!M.getTargetTriple().empty())1168writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(),11690 /*TODO*/);1170const std::string &DL = M.getDataLayoutStr();1171if (!DL.empty())1172writeStringRecord(Stream, bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/);1173if (!M.getModuleInlineAsm().empty())1174writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(),11750 /*TODO*/);11761177// Emit information about sections and GC, computing how many there are. Also1178// compute the maximum alignment value.1179std::map<std::string, unsigned> SectionMap;1180std::map<std::string, unsigned> GCMap;1181MaybeAlign MaxAlignment;1182unsigned MaxGlobalType = 0;1183const auto UpdateMaxAlignment = [&MaxAlignment](const MaybeAlign A) {1184if (A)1185MaxAlignment = !MaxAlignment ? *A : std::max(*MaxAlignment, *A);1186};1187for (const GlobalVariable &GV : M.globals()) {1188UpdateMaxAlignment(GV.getAlign());1189// Use getGlobalObjectValueTypeID to look up the enumerated type ID for1190// Global Variable types.1191MaxGlobalType = std::max(1192MaxGlobalType, getGlobalObjectValueTypeID(GV.getValueType(), &GV));1193if (GV.hasSection()) {1194// Give section names unique ID's.1195unsigned &Entry = SectionMap[std::string(GV.getSection())];1196if (!Entry) {1197writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME,1198GV.getSection(), 0 /*TODO*/);1199Entry = SectionMap.size();1200}1201}1202}1203for (const Function &F : M) {1204UpdateMaxAlignment(F.getAlign());1205if (F.hasSection()) {1206// Give section names unique ID's.1207unsigned &Entry = SectionMap[std::string(F.getSection())];1208if (!Entry) {1209writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, F.getSection(),12100 /*TODO*/);1211Entry = SectionMap.size();1212}1213}1214if (F.hasGC()) {1215// Same for GC names.1216unsigned &Entry = GCMap[F.getGC()];1217if (!Entry) {1218writeStringRecord(Stream, bitc::MODULE_CODE_GCNAME, F.getGC(),12190 /*TODO*/);1220Entry = GCMap.size();1221}1222}1223}12241225// Emit abbrev for globals, now that we know # sections and max alignment.1226unsigned SimpleGVarAbbrev = 0;1227if (!M.global_empty()) {1228// Add an abbrev for common globals with no visibility or thread1229// localness.1230auto Abbv = std::make_shared<BitCodeAbbrev>();1231Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));1232Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,1233Log2_32_Ceil(MaxGlobalType + 1)));1234Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 21235//| explicitType << 11236//| constant1237Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.1238Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.1239if (!MaxAlignment) // Alignment.1240Abbv->Add(BitCodeAbbrevOp(0));1241else {1242unsigned MaxEncAlignment = getEncodedAlign(MaxAlignment);1243Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,1244Log2_32_Ceil(MaxEncAlignment + 1)));1245}1246if (SectionMap.empty()) // Section.1247Abbv->Add(BitCodeAbbrevOp(0));1248else1249Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,1250Log2_32_Ceil(SectionMap.size() + 1)));1251// Don't bother emitting vis + thread local.1252SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv));1253}12541255// Emit the global variable information.1256SmallVector<unsigned, 64> Vals;1257for (const GlobalVariable &GV : M.globals()) {1258unsigned AbbrevToUse = 0;12591260// GLOBALVAR: [type, isconst, initid,1261// linkage, alignment, section, visibility, threadlocal,1262// unnamed_addr, externally_initialized, dllstorageclass,1263// comdat]1264Vals.push_back(getGlobalObjectValueTypeID(GV.getValueType(), &GV));1265Vals.push_back(1266GV.getType()->getAddressSpace() << 2 | 2 |1267(GV.isConstant() ? 1 : 0)); // HLSL Change - bitwise | was used with1268// unsigned int and bool1269Vals.push_back(1270GV.isDeclaration() ? 0 : (VE.getValueID(GV.getInitializer()) + 1));1271Vals.push_back(getEncodedLinkage(GV));1272Vals.push_back(getEncodedAlign(GV.getAlign()));1273Vals.push_back(GV.hasSection() ? SectionMap[std::string(GV.getSection())]1274: 0);1275if (GV.isThreadLocal() ||1276GV.getVisibility() != GlobalValue::DefaultVisibility ||1277GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||1278GV.isExternallyInitialized() ||1279GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||1280GV.hasComdat()) {1281Vals.push_back(getEncodedVisibility(GV));1282Vals.push_back(getEncodedThreadLocalMode(GV));1283Vals.push_back(GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None);1284Vals.push_back(GV.isExternallyInitialized());1285Vals.push_back(getEncodedDLLStorageClass(GV));1286Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);1287} else {1288AbbrevToUse = SimpleGVarAbbrev;1289}12901291Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);1292Vals.clear();1293}12941295// Emit the function proto information.1296for (const Function &F : M) {1297// FUNCTION: [type, callingconv, isproto, linkage, paramattrs, alignment,1298// section, visibility, gc, unnamed_addr, prologuedata,1299// dllstorageclass, comdat, prefixdata, personalityfn]1300Vals.push_back(getGlobalObjectValueTypeID(F.getFunctionType(), &F));1301Vals.push_back(F.getCallingConv());1302Vals.push_back(F.isDeclaration());1303Vals.push_back(getEncodedLinkage(F));1304Vals.push_back(VE.getAttributeListID(F.getAttributes()));1305Vals.push_back(getEncodedAlign(F.getAlign()));1306Vals.push_back(F.hasSection() ? SectionMap[std::string(F.getSection())]1307: 0);1308Vals.push_back(getEncodedVisibility(F));1309Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);1310Vals.push_back(F.getUnnamedAddr() != GlobalValue::UnnamedAddr::None);1311Vals.push_back(1312F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1) : 0);1313Vals.push_back(getEncodedDLLStorageClass(F));1314Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);1315Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)1316: 0);1317Vals.push_back(1318F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);13191320unsigned AbbrevToUse = 0;1321Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);1322Vals.clear();1323}13241325// Emit the alias information.1326for (const GlobalAlias &A : M.aliases()) {1327// ALIAS: [alias type, aliasee val#, linkage, visibility]1328Vals.push_back(getTypeID(A.getValueType(), &A));1329Vals.push_back(VE.getValueID(A.getAliasee()));1330Vals.push_back(getEncodedLinkage(A));1331Vals.push_back(getEncodedVisibility(A));1332Vals.push_back(getEncodedDLLStorageClass(A));1333Vals.push_back(getEncodedThreadLocalMode(A));1334Vals.push_back(A.getUnnamedAddr() != GlobalValue::UnnamedAddr::None);1335unsigned AbbrevToUse = 0;1336Stream.EmitRecord(bitc::MODULE_CODE_ALIAS_OLD, Vals, AbbrevToUse);1337Vals.clear();1338}1339}13401341void DXILBitcodeWriter::writeValueAsMetadata(1342const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {1343// Mimic an MDNode with a value as one operand.1344Value *V = MD->getValue();1345Type *Ty = V->getType();1346if (Function *F = dyn_cast<Function>(V))1347Ty = TypedPointerType::get(F->getFunctionType(), F->getAddressSpace());1348else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))1349Ty = TypedPointerType::get(GV->getValueType(), GV->getAddressSpace());1350Record.push_back(getTypeID(Ty));1351Record.push_back(VE.getValueID(V));1352Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);1353Record.clear();1354}13551356void DXILBitcodeWriter::writeMDTuple(const MDTuple *N,1357SmallVectorImpl<uint64_t> &Record,1358unsigned Abbrev) {1359for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {1360Metadata *MD = N->getOperand(i);1361assert(!(MD && isa<LocalAsMetadata>(MD)) &&1362"Unexpected function-local metadata");1363Record.push_back(VE.getMetadataOrNullID(MD));1364}1365Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE1366: bitc::METADATA_NODE,1367Record, Abbrev);1368Record.clear();1369}13701371void DXILBitcodeWriter::writeDILocation(const DILocation *N,1372SmallVectorImpl<uint64_t> &Record,1373unsigned &Abbrev) {1374if (!Abbrev)1375Abbrev = createDILocationAbbrev();1376Record.push_back(N->isDistinct());1377Record.push_back(N->getLine());1378Record.push_back(N->getColumn());1379Record.push_back(VE.getMetadataID(N->getScope()));1380Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));13811382Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);1383Record.clear();1384}13851386static uint64_t rotateSign(APInt Val) {1387int64_t I = Val.getSExtValue();1388uint64_t U = I;1389return I < 0 ? ~(U << 1) : U << 1;1390}13911392void DXILBitcodeWriter::writeDISubrange(const DISubrange *N,1393SmallVectorImpl<uint64_t> &Record,1394unsigned Abbrev) {1395Record.push_back(N->isDistinct());13961397// TODO: Do we need to handle DIExpression here? What about cases where Count1398// isn't specified but UpperBound and such are?1399ConstantInt *Count = N->getCount().dyn_cast<ConstantInt *>();1400assert(Count && "Count is missing or not ConstantInt");1401Record.push_back(Count->getValue().getSExtValue());14021403// TODO: Similarly, DIExpression is allowed here now1404DISubrange::BoundType LowerBound = N->getLowerBound();1405assert((LowerBound.isNull() || LowerBound.is<ConstantInt *>()) &&1406"Lower bound provided but not ConstantInt");1407Record.push_back(1408LowerBound ? rotateSign(LowerBound.get<ConstantInt *>()->getValue()) : 0);14091410Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);1411Record.clear();1412}14131414void DXILBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,1415SmallVectorImpl<uint64_t> &Record,1416unsigned Abbrev) {1417Record.push_back(N->isDistinct());1418Record.push_back(rotateSign(N->getValue()));1419Record.push_back(VE.getMetadataOrNullID(N->getRawName()));14201421Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);1422Record.clear();1423}14241425void DXILBitcodeWriter::writeDIBasicType(const DIBasicType *N,1426SmallVectorImpl<uint64_t> &Record,1427unsigned Abbrev) {1428Record.push_back(N->isDistinct());1429Record.push_back(N->getTag());1430Record.push_back(VE.getMetadataOrNullID(N->getRawName()));1431Record.push_back(N->getSizeInBits());1432Record.push_back(N->getAlignInBits());1433Record.push_back(N->getEncoding());14341435Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);1436Record.clear();1437}14381439void DXILBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,1440SmallVectorImpl<uint64_t> &Record,1441unsigned Abbrev) {1442Record.push_back(N->isDistinct());1443Record.push_back(N->getTag());1444Record.push_back(VE.getMetadataOrNullID(N->getRawName()));1445Record.push_back(VE.getMetadataOrNullID(N->getFile()));1446Record.push_back(N->getLine());1447Record.push_back(VE.getMetadataOrNullID(N->getScope()));1448Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));1449Record.push_back(N->getSizeInBits());1450Record.push_back(N->getAlignInBits());1451Record.push_back(N->getOffsetInBits());1452Record.push_back(N->getFlags());1453Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));14541455Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);1456Record.clear();1457}14581459void DXILBitcodeWriter::writeDICompositeType(const DICompositeType *N,1460SmallVectorImpl<uint64_t> &Record,1461unsigned Abbrev) {1462Record.push_back(N->isDistinct());1463Record.push_back(N->getTag());1464Record.push_back(VE.getMetadataOrNullID(N->getRawName()));1465Record.push_back(VE.getMetadataOrNullID(N->getFile()));1466Record.push_back(N->getLine());1467Record.push_back(VE.getMetadataOrNullID(N->getScope()));1468Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));1469Record.push_back(N->getSizeInBits());1470Record.push_back(N->getAlignInBits());1471Record.push_back(N->getOffsetInBits());1472Record.push_back(N->getFlags());1473Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));1474Record.push_back(N->getRuntimeLang());1475Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));1476Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));1477Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));14781479Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);1480Record.clear();1481}14821483void DXILBitcodeWriter::writeDISubroutineType(const DISubroutineType *N,1484SmallVectorImpl<uint64_t> &Record,1485unsigned Abbrev) {1486Record.push_back(N->isDistinct());1487Record.push_back(N->getFlags());1488Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));14891490Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);1491Record.clear();1492}14931494void DXILBitcodeWriter::writeDIFile(const DIFile *N,1495SmallVectorImpl<uint64_t> &Record,1496unsigned Abbrev) {1497Record.push_back(N->isDistinct());1498Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));1499Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));15001501Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);1502Record.clear();1503}15041505void DXILBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,1506SmallVectorImpl<uint64_t> &Record,1507unsigned Abbrev) {1508Record.push_back(N->isDistinct());1509Record.push_back(N->getSourceLanguage());1510Record.push_back(VE.getMetadataOrNullID(N->getFile()));1511Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));1512Record.push_back(N->isOptimized());1513Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));1514Record.push_back(N->getRuntimeVersion());1515Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));1516Record.push_back(N->getEmissionKind());1517Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));1518Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));1519Record.push_back(/* subprograms */ 0);1520Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));1521Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));1522Record.push_back(N->getDWOId());15231524Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);1525Record.clear();1526}15271528void DXILBitcodeWriter::writeDISubprogram(const DISubprogram *N,1529SmallVectorImpl<uint64_t> &Record,1530unsigned Abbrev) {1531Record.push_back(N->isDistinct());1532Record.push_back(VE.getMetadataOrNullID(N->getScope()));1533Record.push_back(VE.getMetadataOrNullID(N->getRawName()));1534Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));1535Record.push_back(VE.getMetadataOrNullID(N->getFile()));1536Record.push_back(N->getLine());1537Record.push_back(VE.getMetadataOrNullID(N->getType()));1538Record.push_back(N->isLocalToUnit());1539Record.push_back(N->isDefinition());1540Record.push_back(N->getScopeLine());1541Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));1542Record.push_back(N->getVirtuality());1543Record.push_back(N->getVirtualIndex());1544Record.push_back(N->getFlags());1545Record.push_back(N->isOptimized());1546Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));1547Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));1548Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));1549Record.push_back(VE.getMetadataOrNullID(N->getRetainedNodes().get()));15501551Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);1552Record.clear();1553}15541555void DXILBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,1556SmallVectorImpl<uint64_t> &Record,1557unsigned Abbrev) {1558Record.push_back(N->isDistinct());1559Record.push_back(VE.getMetadataOrNullID(N->getScope()));1560Record.push_back(VE.getMetadataOrNullID(N->getFile()));1561Record.push_back(N->getLine());1562Record.push_back(N->getColumn());15631564Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);1565Record.clear();1566}15671568void DXILBitcodeWriter::writeDILexicalBlockFile(1569const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record,1570unsigned Abbrev) {1571Record.push_back(N->isDistinct());1572Record.push_back(VE.getMetadataOrNullID(N->getScope()));1573Record.push_back(VE.getMetadataOrNullID(N->getFile()));1574Record.push_back(N->getDiscriminator());15751576Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);1577Record.clear();1578}15791580void DXILBitcodeWriter::writeDINamespace(const DINamespace *N,1581SmallVectorImpl<uint64_t> &Record,1582unsigned Abbrev) {1583Record.push_back(N->isDistinct());1584Record.push_back(VE.getMetadataOrNullID(N->getScope()));1585Record.push_back(VE.getMetadataOrNullID(N->getFile()));1586Record.push_back(VE.getMetadataOrNullID(N->getRawName()));1587Record.push_back(/* line number */ 0);15881589Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);1590Record.clear();1591}15921593void DXILBitcodeWriter::writeDIModule(const DIModule *N,1594SmallVectorImpl<uint64_t> &Record,1595unsigned Abbrev) {1596Record.push_back(N->isDistinct());1597for (auto &I : N->operands())1598Record.push_back(VE.getMetadataOrNullID(I));15991600Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);1601Record.clear();1602}16031604void DXILBitcodeWriter::writeDITemplateTypeParameter(1605const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record,1606unsigned Abbrev) {1607Record.push_back(N->isDistinct());1608Record.push_back(VE.getMetadataOrNullID(N->getRawName()));1609Record.push_back(VE.getMetadataOrNullID(N->getType()));16101611Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);1612Record.clear();1613}16141615void DXILBitcodeWriter::writeDITemplateValueParameter(1616const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record,1617unsigned Abbrev) {1618Record.push_back(N->isDistinct());1619Record.push_back(N->getTag());1620Record.push_back(VE.getMetadataOrNullID(N->getRawName()));1621Record.push_back(VE.getMetadataOrNullID(N->getType()));1622Record.push_back(VE.getMetadataOrNullID(N->getValue()));16231624Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);1625Record.clear();1626}16271628void DXILBitcodeWriter::writeDIGlobalVariable(const DIGlobalVariable *N,1629SmallVectorImpl<uint64_t> &Record,1630unsigned Abbrev) {1631Record.push_back(N->isDistinct());1632Record.push_back(VE.getMetadataOrNullID(N->getScope()));1633Record.push_back(VE.getMetadataOrNullID(N->getRawName()));1634Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));1635Record.push_back(VE.getMetadataOrNullID(N->getFile()));1636Record.push_back(N->getLine());1637Record.push_back(VE.getMetadataOrNullID(N->getType()));1638Record.push_back(N->isLocalToUnit());1639Record.push_back(N->isDefinition());1640Record.push_back(/* N->getRawVariable() */ 0);1641Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));16421643Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);1644Record.clear();1645}16461647void DXILBitcodeWriter::writeDILocalVariable(const DILocalVariable *N,1648SmallVectorImpl<uint64_t> &Record,1649unsigned Abbrev) {1650Record.push_back(N->isDistinct());1651Record.push_back(N->getTag());1652Record.push_back(VE.getMetadataOrNullID(N->getScope()));1653Record.push_back(VE.getMetadataOrNullID(N->getRawName()));1654Record.push_back(VE.getMetadataOrNullID(N->getFile()));1655Record.push_back(N->getLine());1656Record.push_back(VE.getMetadataOrNullID(N->getType()));1657Record.push_back(N->getArg());1658Record.push_back(N->getFlags());16591660Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);1661Record.clear();1662}16631664void DXILBitcodeWriter::writeDIExpression(const DIExpression *N,1665SmallVectorImpl<uint64_t> &Record,1666unsigned Abbrev) {1667Record.reserve(N->getElements().size() + 1);16681669Record.push_back(N->isDistinct());1670Record.append(N->elements_begin(), N->elements_end());16711672Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);1673Record.clear();1674}16751676void DXILBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,1677SmallVectorImpl<uint64_t> &Record,1678unsigned Abbrev) {1679llvm_unreachable("DXIL does not support objc!!!");1680}16811682void DXILBitcodeWriter::writeDIImportedEntity(const DIImportedEntity *N,1683SmallVectorImpl<uint64_t> &Record,1684unsigned Abbrev) {1685Record.push_back(N->isDistinct());1686Record.push_back(N->getTag());1687Record.push_back(VE.getMetadataOrNullID(N->getScope()));1688Record.push_back(VE.getMetadataOrNullID(N->getEntity()));1689Record.push_back(N->getLine());1690Record.push_back(VE.getMetadataOrNullID(N->getRawName()));16911692Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);1693Record.clear();1694}16951696unsigned DXILBitcodeWriter::createDILocationAbbrev() {1697// Abbrev for METADATA_LOCATION.1698//1699// Assume the column is usually under 128, and always output the inlined-at1700// location (it's never more expensive than building an array size 1).1701std::shared_ptr<BitCodeAbbrev> Abbv = std::make_shared<BitCodeAbbrev>();1702Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));1703Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));1704Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));1705Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));1706Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));1707Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));1708return Stream.EmitAbbrev(std::move(Abbv));1709}17101711unsigned DXILBitcodeWriter::createGenericDINodeAbbrev() {1712// Abbrev for METADATA_GENERIC_DEBUG.1713//1714// Assume the column is usually under 128, and always output the inlined-at1715// location (it's never more expensive than building an array size 1).1716std::shared_ptr<BitCodeAbbrev> Abbv = std::make_shared<BitCodeAbbrev>();1717Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));1718Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));1719Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));1720Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));1721Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));1722Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));1723Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));1724return Stream.EmitAbbrev(std::move(Abbv));1725}17261727void DXILBitcodeWriter::writeMetadataRecords(ArrayRef<const Metadata *> MDs,1728SmallVectorImpl<uint64_t> &Record,1729std::vector<unsigned> *MDAbbrevs,1730std::vector<uint64_t> *IndexPos) {1731if (MDs.empty())1732return;17331734// Initialize MDNode abbreviations.1735#define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;1736#include "llvm/IR/Metadata.def"17371738for (const Metadata *MD : MDs) {1739if (IndexPos)1740IndexPos->push_back(Stream.GetCurrentBitNo());1741if (const MDNode *N = dyn_cast<MDNode>(MD)) {1742assert(N->isResolved() && "Expected forward references to be resolved");17431744switch (N->getMetadataID()) {1745default:1746llvm_unreachable("Invalid MDNode subclass");1747#define HANDLE_MDNODE_LEAF(CLASS) \1748case Metadata::CLASS##Kind: \1749if (MDAbbrevs) \1750write##CLASS(cast<CLASS>(N), Record, \1751(*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \1752else \1753write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \1754continue;1755#include "llvm/IR/Metadata.def"1756}1757}1758writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);1759}1760}17611762unsigned DXILBitcodeWriter::createMetadataStringsAbbrev() {1763auto Abbv = std::make_shared<BitCodeAbbrev>();1764Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING_OLD));1765Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));1766Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));1767return Stream.EmitAbbrev(std::move(Abbv));1768}17691770void DXILBitcodeWriter::writeMetadataStrings(1771ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) {1772if (Strings.empty())1773return;17741775unsigned MDSAbbrev = createMetadataStringsAbbrev();17761777for (const Metadata *MD : Strings) {1778const MDString *MDS = cast<MDString>(MD);1779// Code: [strchar x N]1780Record.append(MDS->bytes_begin(), MDS->bytes_end());17811782// Emit the finished record.1783Stream.EmitRecord(bitc::METADATA_STRING_OLD, Record, MDSAbbrev);1784Record.clear();1785}1786}17871788void DXILBitcodeWriter::writeModuleMetadata() {1789if (!VE.hasMDs() && M.named_metadata_empty())1790return;17911792Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 5);17931794// Emit all abbrevs upfront, so that the reader can jump in the middle of the1795// block and load any metadata.1796std::vector<unsigned> MDAbbrevs;17971798MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);1799MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();1800MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =1801createGenericDINodeAbbrev();18021803unsigned NameAbbrev = 0;1804if (!M.named_metadata_empty()) {1805// Abbrev for METADATA_NAME.1806std::shared_ptr<BitCodeAbbrev> Abbv = std::make_shared<BitCodeAbbrev>();1807Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));1808Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));1809Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));1810NameAbbrev = Stream.EmitAbbrev(std::move(Abbv));1811}18121813SmallVector<uint64_t, 64> Record;1814writeMetadataStrings(VE.getMDStrings(), Record);18151816std::vector<uint64_t> IndexPos;1817IndexPos.reserve(VE.getNonMDStrings().size());1818writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);18191820// Write named metadata.1821for (const NamedMDNode &NMD : M.named_metadata()) {1822// Write name.1823StringRef Str = NMD.getName();1824Record.append(Str.bytes_begin(), Str.bytes_end());1825Stream.EmitRecord(bitc::METADATA_NAME, Record, NameAbbrev);1826Record.clear();18271828// Write named metadata operands.1829for (const MDNode *N : NMD.operands())1830Record.push_back(VE.getMetadataID(N));1831Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);1832Record.clear();1833}18341835Stream.ExitBlock();1836}18371838void DXILBitcodeWriter::writeFunctionMetadata(const Function &F) {1839if (!VE.hasMDs())1840return;18411842Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 4);1843SmallVector<uint64_t, 64> Record;1844writeMetadataStrings(VE.getMDStrings(), Record);1845writeMetadataRecords(VE.getNonMDStrings(), Record);1846Stream.ExitBlock();1847}18481849void DXILBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {1850Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);18511852SmallVector<uint64_t, 64> Record;18531854// Write metadata attachments1855// METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]1856SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;1857F.getAllMetadata(MDs);1858if (!MDs.empty()) {1859for (const auto &I : MDs) {1860Record.push_back(I.first);1861Record.push_back(VE.getMetadataID(I.second));1862}1863Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);1864Record.clear();1865}18661867for (const BasicBlock &BB : F)1868for (const Instruction &I : BB) {1869MDs.clear();1870I.getAllMetadataOtherThanDebugLoc(MDs);18711872// If no metadata, ignore instruction.1873if (MDs.empty())1874continue;18751876Record.push_back(VE.getInstructionID(&I));18771878for (unsigned i = 0, e = MDs.size(); i != e; ++i) {1879Record.push_back(MDs[i].first);1880Record.push_back(VE.getMetadataID(MDs[i].second));1881}1882Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);1883Record.clear();1884}18851886Stream.ExitBlock();1887}18881889void DXILBitcodeWriter::writeModuleMetadataKinds() {1890SmallVector<uint64_t, 64> Record;18911892// Write metadata kinds1893// METADATA_KIND - [n x [id, name]]1894SmallVector<StringRef, 8> Names;1895M.getMDKindNames(Names);18961897if (Names.empty())1898return;18991900Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);19011902for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {1903Record.push_back(MDKindID);1904StringRef KName = Names[MDKindID];1905Record.append(KName.begin(), KName.end());19061907Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);1908Record.clear();1909}19101911Stream.ExitBlock();1912}19131914void DXILBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,1915bool isGlobal) {1916if (FirstVal == LastVal)1917return;19181919Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);19201921unsigned AggregateAbbrev = 0;1922unsigned String8Abbrev = 0;1923unsigned CString7Abbrev = 0;1924unsigned CString6Abbrev = 0;1925// If this is a constant pool for the module, emit module-specific abbrevs.1926if (isGlobal) {1927// Abbrev for CST_CODE_AGGREGATE.1928auto Abbv = std::make_shared<BitCodeAbbrev>();1929Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));1930Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));1931Abbv->Add(1932BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal + 1)));1933AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));19341935// Abbrev for CST_CODE_STRING.1936Abbv = std::make_shared<BitCodeAbbrev>();1937Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));1938Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));1939Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));1940String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));1941// Abbrev for CST_CODE_CSTRING.1942Abbv = std::make_shared<BitCodeAbbrev>();1943Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));1944Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));1945Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));1946CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));1947// Abbrev for CST_CODE_CSTRING.1948Abbv = std::make_shared<BitCodeAbbrev>();1949Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));1950Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));1951Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));1952CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));1953}19541955SmallVector<uint64_t, 64> Record;19561957const ValueEnumerator::ValueList &Vals = VE.getValues();1958Type *LastTy = nullptr;1959for (unsigned i = FirstVal; i != LastVal; ++i) {1960const Value *V = Vals[i].first;1961// If we need to switch types, do so now.1962if (V->getType() != LastTy) {1963LastTy = V->getType();1964Record.push_back(getTypeID(LastTy, V));1965Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,1966CONSTANTS_SETTYPE_ABBREV);1967Record.clear();1968}19691970if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {1971Record.push_back(unsigned(IA->hasSideEffects()) |1972unsigned(IA->isAlignStack()) << 1 |1973unsigned(IA->getDialect() & 1) << 2);19741975// Add the asm string.1976const std::string &AsmStr = IA->getAsmString();1977Record.push_back(AsmStr.size());1978Record.append(AsmStr.begin(), AsmStr.end());19791980// Add the constraint string.1981const std::string &ConstraintStr = IA->getConstraintString();1982Record.push_back(ConstraintStr.size());1983Record.append(ConstraintStr.begin(), ConstraintStr.end());1984Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);1985Record.clear();1986continue;1987}1988const Constant *C = cast<Constant>(V);1989unsigned Code = -1U;1990unsigned AbbrevToUse = 0;1991if (C->isNullValue()) {1992Code = bitc::CST_CODE_NULL;1993} else if (isa<UndefValue>(C)) {1994Code = bitc::CST_CODE_UNDEF;1995} else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {1996if (IV->getBitWidth() <= 64) {1997uint64_t V = IV->getSExtValue();1998emitSignedInt64(Record, V);1999Code = bitc::CST_CODE_INTEGER;2000AbbrevToUse = CONSTANTS_INTEGER_ABBREV;2001} else { // Wide integers, > 64 bits in size.2002// We have an arbitrary precision integer value to write whose2003// bit width is > 64. However, in canonical unsigned integer2004// format it is likely that the high bits are going to be zero.2005// So, we only write the number of active words.2006unsigned NWords = IV->getValue().getActiveWords();2007const uint64_t *RawWords = IV->getValue().getRawData();2008for (unsigned i = 0; i != NWords; ++i) {2009emitSignedInt64(Record, RawWords[i]);2010}2011Code = bitc::CST_CODE_WIDE_INTEGER;2012}2013} else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {2014Code = bitc::CST_CODE_FLOAT;2015Type *Ty = CFP->getType();2016if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {2017Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());2018} else if (Ty->isX86_FP80Ty()) {2019// api needed to prevent premature destruction2020// bits are not in the same order as a normal i80 APInt, compensate.2021APInt api = CFP->getValueAPF().bitcastToAPInt();2022const uint64_t *p = api.getRawData();2023Record.push_back((p[1] << 48) | (p[0] >> 16));2024Record.push_back(p[0] & 0xffffLL);2025} else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {2026APInt api = CFP->getValueAPF().bitcastToAPInt();2027const uint64_t *p = api.getRawData();2028Record.push_back(p[0]);2029Record.push_back(p[1]);2030} else {2031assert(0 && "Unknown FP type!");2032}2033} else if (isa<ConstantDataSequential>(C) &&2034cast<ConstantDataSequential>(C)->isString()) {2035const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);2036// Emit constant strings specially.2037unsigned NumElts = Str->getNumElements();2038// If this is a null-terminated string, use the denser CSTRING encoding.2039if (Str->isCString()) {2040Code = bitc::CST_CODE_CSTRING;2041--NumElts; // Don't encode the null, which isn't allowed by char6.2042} else {2043Code = bitc::CST_CODE_STRING;2044AbbrevToUse = String8Abbrev;2045}2046bool isCStr7 = Code == bitc::CST_CODE_CSTRING;2047bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;2048for (unsigned i = 0; i != NumElts; ++i) {2049unsigned char V = Str->getElementAsInteger(i);2050Record.push_back(V);2051isCStr7 &= (V & 128) == 0;2052if (isCStrChar6)2053isCStrChar6 = BitCodeAbbrevOp::isChar6(V);2054}20552056if (isCStrChar6)2057AbbrevToUse = CString6Abbrev;2058else if (isCStr7)2059AbbrevToUse = CString7Abbrev;2060} else if (const ConstantDataSequential *CDS =2061dyn_cast<ConstantDataSequential>(C)) {2062Code = bitc::CST_CODE_DATA;2063Type *EltTy = CDS->getElementType();2064if (isa<IntegerType>(EltTy)) {2065for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)2066Record.push_back(CDS->getElementAsInteger(i));2067} else if (EltTy->isFloatTy()) {2068for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {2069union {2070float F;2071uint32_t I;2072};2073F = CDS->getElementAsFloat(i);2074Record.push_back(I);2075}2076} else {2077assert(EltTy->isDoubleTy() && "Unknown ConstantData element type");2078for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {2079union {2080double F;2081uint64_t I;2082};2083F = CDS->getElementAsDouble(i);2084Record.push_back(I);2085}2086}2087} else if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||2088isa<ConstantVector>(C)) {2089Code = bitc::CST_CODE_AGGREGATE;2090for (const Value *Op : C->operands())2091Record.push_back(VE.getValueID(Op));2092AbbrevToUse = AggregateAbbrev;2093} else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {2094switch (CE->getOpcode()) {2095default:2096if (Instruction::isCast(CE->getOpcode())) {2097Code = bitc::CST_CODE_CE_CAST;2098Record.push_back(getEncodedCastOpcode(CE->getOpcode()));2099Record.push_back(2100getTypeID(C->getOperand(0)->getType(), C->getOperand(0)));2101Record.push_back(VE.getValueID(C->getOperand(0)));2102AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;2103} else {2104assert(CE->getNumOperands() == 2 && "Unknown constant expr!");2105Code = bitc::CST_CODE_CE_BINOP;2106Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));2107Record.push_back(VE.getValueID(C->getOperand(0)));2108Record.push_back(VE.getValueID(C->getOperand(1)));2109uint64_t Flags = getOptimizationFlags(CE);2110if (Flags != 0)2111Record.push_back(Flags);2112}2113break;2114case Instruction::GetElementPtr: {2115Code = bitc::CST_CODE_CE_GEP;2116const auto *GO = cast<GEPOperator>(C);2117if (GO->isInBounds())2118Code = bitc::CST_CODE_CE_INBOUNDS_GEP;2119Record.push_back(getTypeID(GO->getSourceElementType()));2120for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {2121Record.push_back(2122getTypeID(C->getOperand(i)->getType(), C->getOperand(i)));2123Record.push_back(VE.getValueID(C->getOperand(i)));2124}2125break;2126}2127case Instruction::Select:2128Code = bitc::CST_CODE_CE_SELECT;2129Record.push_back(VE.getValueID(C->getOperand(0)));2130Record.push_back(VE.getValueID(C->getOperand(1)));2131Record.push_back(VE.getValueID(C->getOperand(2)));2132break;2133case Instruction::ExtractElement:2134Code = bitc::CST_CODE_CE_EXTRACTELT;2135Record.push_back(getTypeID(C->getOperand(0)->getType()));2136Record.push_back(VE.getValueID(C->getOperand(0)));2137Record.push_back(getTypeID(C->getOperand(1)->getType()));2138Record.push_back(VE.getValueID(C->getOperand(1)));2139break;2140case Instruction::InsertElement:2141Code = bitc::CST_CODE_CE_INSERTELT;2142Record.push_back(VE.getValueID(C->getOperand(0)));2143Record.push_back(VE.getValueID(C->getOperand(1)));2144Record.push_back(getTypeID(C->getOperand(2)->getType()));2145Record.push_back(VE.getValueID(C->getOperand(2)));2146break;2147case Instruction::ShuffleVector:2148// If the return type and argument types are the same, this is a2149// standard shufflevector instruction. If the types are different,2150// then the shuffle is widening or truncating the input vectors, and2151// the argument type must also be encoded.2152if (C->getType() == C->getOperand(0)->getType()) {2153Code = bitc::CST_CODE_CE_SHUFFLEVEC;2154} else {2155Code = bitc::CST_CODE_CE_SHUFVEC_EX;2156Record.push_back(getTypeID(C->getOperand(0)->getType()));2157}2158Record.push_back(VE.getValueID(C->getOperand(0)));2159Record.push_back(VE.getValueID(C->getOperand(1)));2160Record.push_back(VE.getValueID(C->getOperand(2)));2161break;2162}2163} else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {2164Code = bitc::CST_CODE_BLOCKADDRESS;2165Record.push_back(getTypeID(BA->getFunction()->getType()));2166Record.push_back(VE.getValueID(BA->getFunction()));2167Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));2168} else {2169#ifndef NDEBUG2170C->dump();2171#endif2172llvm_unreachable("Unknown constant!");2173}2174Stream.EmitRecord(Code, Record, AbbrevToUse);2175Record.clear();2176}21772178Stream.ExitBlock();2179}21802181void DXILBitcodeWriter::writeModuleConstants() {2182const ValueEnumerator::ValueList &Vals = VE.getValues();21832184// Find the first constant to emit, which is the first non-globalvalue value.2185// We know globalvalues have been emitted by WriteModuleInfo.2186for (unsigned i = 0, e = Vals.size(); i != e; ++i) {2187if (!isa<GlobalValue>(Vals[i].first)) {2188writeConstants(i, Vals.size(), true);2189return;2190}2191}2192}21932194/// pushValueAndType - The file has to encode both the value and type id for2195/// many values, because we need to know what type to create for forward2196/// references. However, most operands are not forward references, so this type2197/// field is not needed.2198///2199/// This function adds V's value ID to Vals. If the value ID is higher than the2200/// instruction ID, then it is a forward reference, and it also includes the2201/// type ID. The value ID that is written is encoded relative to the InstID.2202bool DXILBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,2203SmallVectorImpl<unsigned> &Vals) {2204unsigned ValID = VE.getValueID(V);2205// Make encoding relative to the InstID.2206Vals.push_back(InstID - ValID);2207if (ValID >= InstID) {2208Vals.push_back(getTypeID(V->getType(), V));2209return true;2210}2211return false;2212}22132214/// pushValue - Like pushValueAndType, but where the type of the value is2215/// omitted (perhaps it was already encoded in an earlier operand).2216void DXILBitcodeWriter::pushValue(const Value *V, unsigned InstID,2217SmallVectorImpl<unsigned> &Vals) {2218unsigned ValID = VE.getValueID(V);2219Vals.push_back(InstID - ValID);2220}22212222void DXILBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,2223SmallVectorImpl<uint64_t> &Vals) {2224unsigned ValID = VE.getValueID(V);2225int64_t diff = ((int32_t)InstID - (int32_t)ValID);2226emitSignedInt64(Vals, diff);2227}22282229/// WriteInstruction - Emit an instruction2230void DXILBitcodeWriter::writeInstruction(const Instruction &I, unsigned InstID,2231SmallVectorImpl<unsigned> &Vals) {2232unsigned Code = 0;2233unsigned AbbrevToUse = 0;2234VE.setInstructionID(&I);2235switch (I.getOpcode()) {2236default:2237if (Instruction::isCast(I.getOpcode())) {2238Code = bitc::FUNC_CODE_INST_CAST;2239if (!pushValueAndType(I.getOperand(0), InstID, Vals))2240AbbrevToUse = (unsigned)FUNCTION_INST_CAST_ABBREV;2241Vals.push_back(getTypeID(I.getType(), &I));2242Vals.push_back(getEncodedCastOpcode(I.getOpcode()));2243} else {2244assert(isa<BinaryOperator>(I) && "Unknown instruction!");2245Code = bitc::FUNC_CODE_INST_BINOP;2246if (!pushValueAndType(I.getOperand(0), InstID, Vals))2247AbbrevToUse = (unsigned)FUNCTION_INST_BINOP_ABBREV;2248pushValue(I.getOperand(1), InstID, Vals);2249Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));2250uint64_t Flags = getOptimizationFlags(&I);2251if (Flags != 0) {2252if (AbbrevToUse == (unsigned)FUNCTION_INST_BINOP_ABBREV)2253AbbrevToUse = (unsigned)FUNCTION_INST_BINOP_FLAGS_ABBREV;2254Vals.push_back(Flags);2255}2256}2257break;22582259case Instruction::GetElementPtr: {2260Code = bitc::FUNC_CODE_INST_GEP;2261AbbrevToUse = (unsigned)FUNCTION_INST_GEP_ABBREV;2262auto &GEPInst = cast<GetElementPtrInst>(I);2263Vals.push_back(GEPInst.isInBounds());2264Vals.push_back(getTypeID(GEPInst.getSourceElementType()));2265for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)2266pushValueAndType(I.getOperand(i), InstID, Vals);2267break;2268}2269case Instruction::ExtractValue: {2270Code = bitc::FUNC_CODE_INST_EXTRACTVAL;2271pushValueAndType(I.getOperand(0), InstID, Vals);2272const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);2273Vals.append(EVI->idx_begin(), EVI->idx_end());2274break;2275}2276case Instruction::InsertValue: {2277Code = bitc::FUNC_CODE_INST_INSERTVAL;2278pushValueAndType(I.getOperand(0), InstID, Vals);2279pushValueAndType(I.getOperand(1), InstID, Vals);2280const InsertValueInst *IVI = cast<InsertValueInst>(&I);2281Vals.append(IVI->idx_begin(), IVI->idx_end());2282break;2283}2284case Instruction::Select:2285Code = bitc::FUNC_CODE_INST_VSELECT;2286pushValueAndType(I.getOperand(1), InstID, Vals);2287pushValue(I.getOperand(2), InstID, Vals);2288pushValueAndType(I.getOperand(0), InstID, Vals);2289break;2290case Instruction::ExtractElement:2291Code = bitc::FUNC_CODE_INST_EXTRACTELT;2292pushValueAndType(I.getOperand(0), InstID, Vals);2293pushValueAndType(I.getOperand(1), InstID, Vals);2294break;2295case Instruction::InsertElement:2296Code = bitc::FUNC_CODE_INST_INSERTELT;2297pushValueAndType(I.getOperand(0), InstID, Vals);2298pushValue(I.getOperand(1), InstID, Vals);2299pushValueAndType(I.getOperand(2), InstID, Vals);2300break;2301case Instruction::ShuffleVector:2302Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;2303pushValueAndType(I.getOperand(0), InstID, Vals);2304pushValue(I.getOperand(1), InstID, Vals);2305pushValue(cast<ShuffleVectorInst>(&I)->getShuffleMaskForBitcode(), InstID,2306Vals);2307break;2308case Instruction::ICmp:2309case Instruction::FCmp: {2310// compare returning Int1Ty or vector of Int1Ty2311Code = bitc::FUNC_CODE_INST_CMP2;2312pushValueAndType(I.getOperand(0), InstID, Vals);2313pushValue(I.getOperand(1), InstID, Vals);2314Vals.push_back(cast<CmpInst>(I).getPredicate());2315uint64_t Flags = getOptimizationFlags(&I);2316if (Flags != 0)2317Vals.push_back(Flags);2318break;2319}23202321case Instruction::Ret: {2322Code = bitc::FUNC_CODE_INST_RET;2323unsigned NumOperands = I.getNumOperands();2324if (NumOperands == 0)2325AbbrevToUse = (unsigned)FUNCTION_INST_RET_VOID_ABBREV;2326else if (NumOperands == 1) {2327if (!pushValueAndType(I.getOperand(0), InstID, Vals))2328AbbrevToUse = (unsigned)FUNCTION_INST_RET_VAL_ABBREV;2329} else {2330for (unsigned i = 0, e = NumOperands; i != e; ++i)2331pushValueAndType(I.getOperand(i), InstID, Vals);2332}2333} break;2334case Instruction::Br: {2335Code = bitc::FUNC_CODE_INST_BR;2336const BranchInst &II = cast<BranchInst>(I);2337Vals.push_back(VE.getValueID(II.getSuccessor(0)));2338if (II.isConditional()) {2339Vals.push_back(VE.getValueID(II.getSuccessor(1)));2340pushValue(II.getCondition(), InstID, Vals);2341}2342} break;2343case Instruction::Switch: {2344Code = bitc::FUNC_CODE_INST_SWITCH;2345const SwitchInst &SI = cast<SwitchInst>(I);2346Vals.push_back(getTypeID(SI.getCondition()->getType()));2347pushValue(SI.getCondition(), InstID, Vals);2348Vals.push_back(VE.getValueID(SI.getDefaultDest()));2349for (auto Case : SI.cases()) {2350Vals.push_back(VE.getValueID(Case.getCaseValue()));2351Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));2352}2353} break;2354case Instruction::IndirectBr:2355Code = bitc::FUNC_CODE_INST_INDIRECTBR;2356Vals.push_back(getTypeID(I.getOperand(0)->getType()));2357// Encode the address operand as relative, but not the basic blocks.2358pushValue(I.getOperand(0), InstID, Vals);2359for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)2360Vals.push_back(VE.getValueID(I.getOperand(i)));2361break;23622363case Instruction::Invoke: {2364const InvokeInst *II = cast<InvokeInst>(&I);2365const Value *Callee = II->getCalledOperand();2366FunctionType *FTy = II->getFunctionType();2367Code = bitc::FUNC_CODE_INST_INVOKE;23682369Vals.push_back(VE.getAttributeListID(II->getAttributes()));2370Vals.push_back(II->getCallingConv() | 1 << 13);2371Vals.push_back(VE.getValueID(II->getNormalDest()));2372Vals.push_back(VE.getValueID(II->getUnwindDest()));2373Vals.push_back(getTypeID(FTy));2374pushValueAndType(Callee, InstID, Vals);23752376// Emit value #'s for the fixed parameters.2377for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)2378pushValue(I.getOperand(i), InstID, Vals); // fixed param.23792380// Emit type/value pairs for varargs params.2381if (FTy->isVarArg()) {2382for (unsigned i = FTy->getNumParams(), e = I.getNumOperands() - 3; i != e;2383++i)2384pushValueAndType(I.getOperand(i), InstID, Vals); // vararg2385}2386break;2387}2388case Instruction::Resume:2389Code = bitc::FUNC_CODE_INST_RESUME;2390pushValueAndType(I.getOperand(0), InstID, Vals);2391break;2392case Instruction::Unreachable:2393Code = bitc::FUNC_CODE_INST_UNREACHABLE;2394AbbrevToUse = (unsigned)FUNCTION_INST_UNREACHABLE_ABBREV;2395break;23962397case Instruction::PHI: {2398const PHINode &PN = cast<PHINode>(I);2399Code = bitc::FUNC_CODE_INST_PHI;2400// With the newer instruction encoding, forward references could give2401// negative valued IDs. This is most common for PHIs, so we use2402// signed VBRs.2403SmallVector<uint64_t, 128> Vals64;2404Vals64.push_back(getTypeID(PN.getType()));2405for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {2406pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);2407Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));2408}2409// Emit a Vals64 vector and exit.2410Stream.EmitRecord(Code, Vals64, AbbrevToUse);2411Vals64.clear();2412return;2413}24142415case Instruction::LandingPad: {2416const LandingPadInst &LP = cast<LandingPadInst>(I);2417Code = bitc::FUNC_CODE_INST_LANDINGPAD;2418Vals.push_back(getTypeID(LP.getType()));2419Vals.push_back(LP.isCleanup());2420Vals.push_back(LP.getNumClauses());2421for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {2422if (LP.isCatch(I))2423Vals.push_back(LandingPadInst::Catch);2424else2425Vals.push_back(LandingPadInst::Filter);2426pushValueAndType(LP.getClause(I), InstID, Vals);2427}2428break;2429}24302431case Instruction::Alloca: {2432Code = bitc::FUNC_CODE_INST_ALLOCA;2433const AllocaInst &AI = cast<AllocaInst>(I);2434Vals.push_back(getTypeID(AI.getAllocatedType()));2435Vals.push_back(getTypeID(I.getOperand(0)->getType()));2436Vals.push_back(VE.getValueID(I.getOperand(0))); // size.2437unsigned AlignRecord = Log2_32(AI.getAlign().value()) + 1;2438assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");2439AlignRecord |= AI.isUsedWithInAlloca() << 5;2440AlignRecord |= 1 << 6;2441Vals.push_back(AlignRecord);2442break;2443}24442445case Instruction::Load:2446if (cast<LoadInst>(I).isAtomic()) {2447Code = bitc::FUNC_CODE_INST_LOADATOMIC;2448pushValueAndType(I.getOperand(0), InstID, Vals);2449} else {2450Code = bitc::FUNC_CODE_INST_LOAD;2451if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr2452AbbrevToUse = (unsigned)FUNCTION_INST_LOAD_ABBREV;2453}2454Vals.push_back(getTypeID(I.getType()));2455Vals.push_back(Log2(cast<LoadInst>(I).getAlign()) + 1);2456Vals.push_back(cast<LoadInst>(I).isVolatile());2457if (cast<LoadInst>(I).isAtomic()) {2458Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));2459Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID()));2460}2461break;2462case Instruction::Store:2463if (cast<StoreInst>(I).isAtomic())2464Code = bitc::FUNC_CODE_INST_STOREATOMIC;2465else2466Code = bitc::FUNC_CODE_INST_STORE;2467pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr2468pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val2469Vals.push_back(Log2(cast<StoreInst>(I).getAlign()) + 1);2470Vals.push_back(cast<StoreInst>(I).isVolatile());2471if (cast<StoreInst>(I).isAtomic()) {2472Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));2473Vals.push_back(2474getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID()));2475}2476break;2477case Instruction::AtomicCmpXchg:2478Code = bitc::FUNC_CODE_INST_CMPXCHG;2479pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr2480pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.2481pushValue(I.getOperand(2), InstID, Vals); // newval.2482Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());2483Vals.push_back(2484getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));2485Vals.push_back(2486getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID()));2487Vals.push_back(2488getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));2489Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());2490break;2491case Instruction::AtomicRMW:2492Code = bitc::FUNC_CODE_INST_ATOMICRMW;2493pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr2494pushValue(I.getOperand(1), InstID, Vals); // val.2495Vals.push_back(2496getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));2497Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());2498Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));2499Vals.push_back(2500getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID()));2501break;2502case Instruction::Fence:2503Code = bitc::FUNC_CODE_INST_FENCE;2504Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));2505Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID()));2506break;2507case Instruction::Call: {2508const CallInst &CI = cast<CallInst>(I);2509FunctionType *FTy = CI.getFunctionType();25102511Code = bitc::FUNC_CODE_INST_CALL;25122513Vals.push_back(VE.getAttributeListID(CI.getAttributes()));2514Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall()) |2515unsigned(CI.isMustTailCall()) << 14 | 1 << 15);2516Vals.push_back(getGlobalObjectValueTypeID(FTy, CI.getCalledFunction()));2517pushValueAndType(CI.getCalledOperand(), InstID, Vals); // Callee25182519// Emit value #'s for the fixed parameters.2520for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {2521// Check for labels (can happen with asm labels).2522if (FTy->getParamType(i)->isLabelTy())2523Vals.push_back(VE.getValueID(CI.getArgOperand(i)));2524else2525pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.2526}25272528// Emit type/value pairs for varargs params.2529if (FTy->isVarArg()) {2530for (unsigned i = FTy->getNumParams(), e = CI.arg_size(); i != e; ++i)2531pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs2532}2533break;2534}2535case Instruction::VAArg:2536Code = bitc::FUNC_CODE_INST_VAARG;2537Vals.push_back(getTypeID(I.getOperand(0)->getType())); // valistty2538pushValue(I.getOperand(0), InstID, Vals); // valist.2539Vals.push_back(getTypeID(I.getType())); // restype.2540break;2541}25422543Stream.EmitRecord(Code, Vals, AbbrevToUse);2544Vals.clear();2545}25462547// Emit names for globals/functions etc.2548void DXILBitcodeWriter::writeFunctionLevelValueSymbolTable(2549const ValueSymbolTable &VST) {2550if (VST.empty())2551return;2552Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);25532554SmallVector<unsigned, 64> NameVals;25552556// HLSL Change2557// Read the named values from a sorted list instead of the original list2558// to ensure the binary is the same no matter what values ever existed.2559SmallVector<const ValueName *, 16> SortedTable;25602561for (auto &VI : VST) {2562SortedTable.push_back(VI.second->getValueName());2563}2564// The keys are unique, so there shouldn't be stability issues.2565llvm::sort(SortedTable, [](const ValueName *A, const ValueName *B) {2566return A->first() < B->first();2567});25682569for (const ValueName *SI : SortedTable) {2570auto &Name = *SI;25712572// Figure out the encoding to use for the name.2573bool is7Bit = true;2574bool isChar6 = true;2575for (const char *C = Name.getKeyData(), *E = C + Name.getKeyLength();2576C != E; ++C) {2577if (isChar6)2578isChar6 = BitCodeAbbrevOp::isChar6(*C);2579if ((unsigned char)*C & 128) {2580is7Bit = false;2581break; // don't bother scanning the rest.2582}2583}25842585unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;25862587// VST_ENTRY: [valueid, namechar x N]2588// VST_BBENTRY: [bbid, namechar x N]2589unsigned Code;2590if (isa<BasicBlock>(SI->getValue())) {2591Code = bitc::VST_CODE_BBENTRY;2592if (isChar6)2593AbbrevToUse = VST_BBENTRY_6_ABBREV;2594} else {2595Code = bitc::VST_CODE_ENTRY;2596if (isChar6)2597AbbrevToUse = VST_ENTRY_6_ABBREV;2598else if (is7Bit)2599AbbrevToUse = VST_ENTRY_7_ABBREV;2600}26012602NameVals.push_back(VE.getValueID(SI->getValue()));2603for (const char *P = Name.getKeyData(),2604*E = Name.getKeyData() + Name.getKeyLength();2605P != E; ++P)2606NameVals.push_back((unsigned char)*P);26072608// Emit the finished record.2609Stream.EmitRecord(Code, NameVals, AbbrevToUse);2610NameVals.clear();2611}2612Stream.ExitBlock();2613}26142615/// Emit a function body to the module stream.2616void DXILBitcodeWriter::writeFunction(const Function &F) {2617Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);2618VE.incorporateFunction(F);26192620SmallVector<unsigned, 64> Vals;26212622// Emit the number of basic blocks, so the reader can create them ahead of2623// time.2624Vals.push_back(VE.getBasicBlocks().size());2625Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);2626Vals.clear();26272628// If there are function-local constants, emit them now.2629unsigned CstStart, CstEnd;2630VE.getFunctionConstantRange(CstStart, CstEnd);2631writeConstants(CstStart, CstEnd, false);26322633// If there is function-local metadata, emit it now.2634writeFunctionMetadata(F);26352636// Keep a running idea of what the instruction ID is.2637unsigned InstID = CstEnd;26382639bool NeedsMetadataAttachment = F.hasMetadata();26402641DILocation *LastDL = nullptr;26422643// Finally, emit all the instructions, in order.2644for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)2645for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E;2646++I) {2647writeInstruction(*I, InstID, Vals);26482649if (!I->getType()->isVoidTy())2650++InstID;26512652// If the instruction has metadata, write a metadata attachment later.2653NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();26542655// If the instruction has a debug location, emit it.2656DILocation *DL = I->getDebugLoc();2657if (!DL)2658continue;26592660if (DL == LastDL) {2661// Just repeat the same debug loc as last time.2662Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);2663continue;2664}26652666Vals.push_back(DL->getLine());2667Vals.push_back(DL->getColumn());2668Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));2669Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));2670Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);2671Vals.clear();26722673LastDL = DL;2674}26752676// Emit names for all the instructions etc.2677if (auto *Symtab = F.getValueSymbolTable())2678writeFunctionLevelValueSymbolTable(*Symtab);26792680if (NeedsMetadataAttachment)2681writeFunctionMetadataAttachment(F);26822683VE.purgeFunction();2684Stream.ExitBlock();2685}26862687// Emit blockinfo, which defines the standard abbreviations etc.2688void DXILBitcodeWriter::writeBlockInfo() {2689// We only want to emit block info records for blocks that have multiple2690// instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.2691// Other blocks can define their abbrevs inline.2692Stream.EnterBlockInfoBlock();26932694{ // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.2695auto Abbv = std::make_shared<BitCodeAbbrev>();2696Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));2697Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));2698Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));2699Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));2700if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,2701std::move(Abbv)) != VST_ENTRY_8_ABBREV)2702assert(false && "Unexpected abbrev ordering!");2703}27042705{ // 7-bit fixed width VST_ENTRY strings.2706auto Abbv = std::make_shared<BitCodeAbbrev>();2707Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));2708Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));2709Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));2710Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));2711if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,2712std::move(Abbv)) != VST_ENTRY_7_ABBREV)2713assert(false && "Unexpected abbrev ordering!");2714}2715{ // 6-bit char6 VST_ENTRY strings.2716auto Abbv = std::make_shared<BitCodeAbbrev>();2717Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));2718Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));2719Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));2720Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));2721if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,2722std::move(Abbv)) != VST_ENTRY_6_ABBREV)2723assert(false && "Unexpected abbrev ordering!");2724}2725{ // 6-bit char6 VST_BBENTRY strings.2726auto Abbv = std::make_shared<BitCodeAbbrev>();2727Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));2728Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));2729Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));2730Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));2731if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,2732std::move(Abbv)) != VST_BBENTRY_6_ABBREV)2733assert(false && "Unexpected abbrev ordering!");2734}27352736{ // SETTYPE abbrev for CONSTANTS_BLOCK.2737auto Abbv = std::make_shared<BitCodeAbbrev>();2738Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));2739Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,2740VE.computeBitsRequiredForTypeIndices()));2741if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, std::move(Abbv)) !=2742CONSTANTS_SETTYPE_ABBREV)2743assert(false && "Unexpected abbrev ordering!");2744}27452746{ // INTEGER abbrev for CONSTANTS_BLOCK.2747auto Abbv = std::make_shared<BitCodeAbbrev>();2748Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));2749Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));2750if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, std::move(Abbv)) !=2751CONSTANTS_INTEGER_ABBREV)2752assert(false && "Unexpected abbrev ordering!");2753}27542755{ // CE_CAST abbrev for CONSTANTS_BLOCK.2756auto Abbv = std::make_shared<BitCodeAbbrev>();2757Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));2758Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc2759Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid2760VE.computeBitsRequiredForTypeIndices()));2761Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id27622763if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, std::move(Abbv)) !=2764CONSTANTS_CE_CAST_Abbrev)2765assert(false && "Unexpected abbrev ordering!");2766}2767{ // NULL abbrev for CONSTANTS_BLOCK.2768auto Abbv = std::make_shared<BitCodeAbbrev>();2769Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));2770if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, std::move(Abbv)) !=2771CONSTANTS_NULL_Abbrev)2772assert(false && "Unexpected abbrev ordering!");2773}27742775// FIXME: This should only use space for first class types!27762777{ // INST_LOAD abbrev for FUNCTION_BLOCK.2778auto Abbv = std::make_shared<BitCodeAbbrev>();2779Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));2780Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr2781Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty2782VE.computeBitsRequiredForTypeIndices()));2783Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align2784Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile2785if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) !=2786(unsigned)FUNCTION_INST_LOAD_ABBREV)2787assert(false && "Unexpected abbrev ordering!");2788}2789{ // INST_BINOP abbrev for FUNCTION_BLOCK.2790auto Abbv = std::make_shared<BitCodeAbbrev>();2791Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));2792Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS2793Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS2794Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc2795if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) !=2796(unsigned)FUNCTION_INST_BINOP_ABBREV)2797assert(false && "Unexpected abbrev ordering!");2798}2799{ // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.2800auto Abbv = std::make_shared<BitCodeAbbrev>();2801Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));2802Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS2803Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS2804Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc2805Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags2806if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) !=2807(unsigned)FUNCTION_INST_BINOP_FLAGS_ABBREV)2808assert(false && "Unexpected abbrev ordering!");2809}2810{ // INST_CAST abbrev for FUNCTION_BLOCK.2811auto Abbv = std::make_shared<BitCodeAbbrev>();2812Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));2813Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal2814Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty2815VE.computeBitsRequiredForTypeIndices()));2816Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc2817if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) !=2818(unsigned)FUNCTION_INST_CAST_ABBREV)2819assert(false && "Unexpected abbrev ordering!");2820}28212822{ // INST_RET abbrev for FUNCTION_BLOCK.2823auto Abbv = std::make_shared<BitCodeAbbrev>();2824Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));2825if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) !=2826(unsigned)FUNCTION_INST_RET_VOID_ABBREV)2827assert(false && "Unexpected abbrev ordering!");2828}2829{ // INST_RET abbrev for FUNCTION_BLOCK.2830auto Abbv = std::make_shared<BitCodeAbbrev>();2831Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));2832Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID2833if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) !=2834(unsigned)FUNCTION_INST_RET_VAL_ABBREV)2835assert(false && "Unexpected abbrev ordering!");2836}2837{ // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.2838auto Abbv = std::make_shared<BitCodeAbbrev>();2839Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));2840if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) !=2841(unsigned)FUNCTION_INST_UNREACHABLE_ABBREV)2842assert(false && "Unexpected abbrev ordering!");2843}2844{2845auto Abbv = std::make_shared<BitCodeAbbrev>();2846Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));2847Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));2848Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty2849Log2_32_Ceil(VE.getTypes().size() + 1)));2850Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));2851Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));2852if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) !=2853(unsigned)FUNCTION_INST_GEP_ABBREV)2854assert(false && "Unexpected abbrev ordering!");2855}28562857Stream.ExitBlock();2858}28592860void DXILBitcodeWriter::writeModuleVersion() {2861// VERSION: [version#]2862Stream.EmitRecord(bitc::MODULE_CODE_VERSION, ArrayRef<unsigned>{1});2863}28642865/// WriteModule - Emit the specified module to the bitstream.2866void DXILBitcodeWriter::write() {2867// The identification block is new since llvm-3.7, but the old bitcode reader2868// will skip it.2869// writeIdentificationBlock(Stream);28702871Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);28722873// It is redundant to fully-specify this here, but nice to make it explicit2874// so that it is clear the DXIL module version is different.2875DXILBitcodeWriter::writeModuleVersion();28762877// Emit blockinfo, which defines the standard abbreviations etc.2878writeBlockInfo();28792880// Emit information about attribute groups.2881writeAttributeGroupTable();28822883// Emit information about parameter attributes.2884writeAttributeTable();28852886// Emit information describing all of the types in the module.2887writeTypeTable();28882889writeComdats();28902891// Emit top-level description of module, including target triple, inline asm,2892// descriptors for global variables, and function prototype info.2893writeModuleInfo();28942895// Emit constants.2896writeModuleConstants();28972898// Emit metadata.2899writeModuleMetadataKinds();29002901// Emit metadata.2902writeModuleMetadata();29032904// Emit names for globals/functions etc.2905// DXIL uses the same format for module-level value symbol table as for the2906// function level table.2907writeFunctionLevelValueSymbolTable(M.getValueSymbolTable());29082909// Emit function bodies.2910for (const Function &F : M)2911if (!F.isDeclaration())2912writeFunction(F);29132914Stream.ExitBlock();2915}291629172918