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