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