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