1*0b57cec5SDimitry Andric //===- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ------------------===//
2*0b57cec5SDimitry Andric //
3*0b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*0b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5*0b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*0b57cec5SDimitry Andric //
7*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8*0b57cec5SDimitry Andric //
9*0b57cec5SDimitry Andric // Bitcode writer implementation.
10*0b57cec5SDimitry Andric //
11*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
12*0b57cec5SDimitry Andric 
13*0b57cec5SDimitry Andric #include "llvm/Bitcode/BitcodeWriter.h"
14*0b57cec5SDimitry Andric #include "ValueEnumerator.h"
15*0b57cec5SDimitry Andric #include "llvm/ADT/APFloat.h"
16*0b57cec5SDimitry Andric #include "llvm/ADT/APInt.h"
17*0b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
18*0b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
19*0b57cec5SDimitry Andric #include "llvm/ADT/None.h"
20*0b57cec5SDimitry Andric #include "llvm/ADT/Optional.h"
21*0b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
22*0b57cec5SDimitry Andric #include "llvm/ADT/SmallString.h"
23*0b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
24*0b57cec5SDimitry Andric #include "llvm/ADT/StringMap.h"
25*0b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
26*0b57cec5SDimitry Andric #include "llvm/ADT/Triple.h"
27e8d8bef9SDimitry Andric #include "llvm/Bitcode/BitcodeCommon.h"
28480093f4SDimitry Andric #include "llvm/Bitcode/BitcodeReader.h"
29480093f4SDimitry Andric #include "llvm/Bitcode/LLVMBitCodes.h"
30*0b57cec5SDimitry Andric #include "llvm/Bitstream/BitCodes.h"
31*0b57cec5SDimitry Andric #include "llvm/Bitstream/BitstreamWriter.h"
32*0b57cec5SDimitry Andric #include "llvm/Config/llvm-config.h"
33*0b57cec5SDimitry Andric #include "llvm/IR/Attributes.h"
34*0b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
35*0b57cec5SDimitry Andric #include "llvm/IR/Comdat.h"
36*0b57cec5SDimitry Andric #include "llvm/IR/Constant.h"
37*0b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
38*0b57cec5SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
39*0b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h"
40*0b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
41*0b57cec5SDimitry Andric #include "llvm/IR/Function.h"
42*0b57cec5SDimitry Andric #include "llvm/IR/GlobalAlias.h"
43*0b57cec5SDimitry Andric #include "llvm/IR/GlobalIFunc.h"
44*0b57cec5SDimitry Andric #include "llvm/IR/GlobalObject.h"
45*0b57cec5SDimitry Andric #include "llvm/IR/GlobalValue.h"
46*0b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h"
47*0b57cec5SDimitry Andric #include "llvm/IR/InlineAsm.h"
48*0b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h"
49*0b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
50*0b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
51*0b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
52*0b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
53*0b57cec5SDimitry Andric #include "llvm/IR/Module.h"
54*0b57cec5SDimitry Andric #include "llvm/IR/ModuleSummaryIndex.h"
55*0b57cec5SDimitry Andric #include "llvm/IR/Operator.h"
56*0b57cec5SDimitry Andric #include "llvm/IR/Type.h"
57*0b57cec5SDimitry Andric #include "llvm/IR/UseListOrder.h"
58*0b57cec5SDimitry Andric #include "llvm/IR/Value.h"
59*0b57cec5SDimitry Andric #include "llvm/IR/ValueSymbolTable.h"
60*0b57cec5SDimitry Andric #include "llvm/MC/StringTableBuilder.h"
61*0b57cec5SDimitry Andric #include "llvm/Object/IRSymtab.h"
62*0b57cec5SDimitry Andric #include "llvm/Support/AtomicOrdering.h"
63*0b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
64*0b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
65*0b57cec5SDimitry Andric #include "llvm/Support/Endian.h"
66*0b57cec5SDimitry Andric #include "llvm/Support/Error.h"
67*0b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
68*0b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
69*0b57cec5SDimitry Andric #include "llvm/Support/SHA1.h"
70*0b57cec5SDimitry Andric #include "llvm/Support/TargetRegistry.h"
71*0b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
72*0b57cec5SDimitry Andric #include <algorithm>
73*0b57cec5SDimitry Andric #include <cassert>
74*0b57cec5SDimitry Andric #include <cstddef>
75*0b57cec5SDimitry Andric #include <cstdint>
76*0b57cec5SDimitry Andric #include <iterator>
77*0b57cec5SDimitry Andric #include <map>
78*0b57cec5SDimitry Andric #include <memory>
79*0b57cec5SDimitry Andric #include <string>
80*0b57cec5SDimitry Andric #include <utility>
81*0b57cec5SDimitry Andric #include <vector>
82*0b57cec5SDimitry Andric 
83*0b57cec5SDimitry Andric using namespace llvm;
84*0b57cec5SDimitry Andric 
85*0b57cec5SDimitry Andric static cl::opt<unsigned>
86*0b57cec5SDimitry Andric     IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25),
87*0b57cec5SDimitry Andric                    cl::desc("Number of metadatas above which we emit an index "
88*0b57cec5SDimitry Andric                             "to enable lazy-loading"));
89e8d8bef9SDimitry Andric static cl::opt<uint32_t> FlushThreshold(
90e8d8bef9SDimitry Andric     "bitcode-flush-threshold", cl::Hidden, cl::init(512),
91e8d8bef9SDimitry Andric     cl::desc("The threshold (unit M) for flushing LLVM bitcode."));
92*0b57cec5SDimitry Andric 
938bcb0991SDimitry Andric static cl::opt<bool> WriteRelBFToSummary(
94*0b57cec5SDimitry Andric     "write-relbf-to-summary", cl::Hidden, cl::init(false),
95*0b57cec5SDimitry Andric     cl::desc("Write relative block frequency to function summary "));
96*0b57cec5SDimitry Andric 
97*0b57cec5SDimitry Andric extern FunctionSummary::ForceSummaryHotnessType ForceSummaryEdgesCold;
98*0b57cec5SDimitry Andric 
99*0b57cec5SDimitry Andric namespace {
100*0b57cec5SDimitry Andric 
101*0b57cec5SDimitry Andric /// These are manifest constants used by the bitcode writer. They do not need to
102*0b57cec5SDimitry Andric /// be kept in sync with the reader, but need to be consistent within this file.
103*0b57cec5SDimitry Andric enum {
104*0b57cec5SDimitry Andric   // VALUE_SYMTAB_BLOCK abbrev id's.
105*0b57cec5SDimitry Andric   VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
106*0b57cec5SDimitry Andric   VST_ENTRY_7_ABBREV,
107*0b57cec5SDimitry Andric   VST_ENTRY_6_ABBREV,
108*0b57cec5SDimitry Andric   VST_BBENTRY_6_ABBREV,
109*0b57cec5SDimitry Andric 
110*0b57cec5SDimitry Andric   // CONSTANTS_BLOCK abbrev id's.
111*0b57cec5SDimitry Andric   CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
112*0b57cec5SDimitry Andric   CONSTANTS_INTEGER_ABBREV,
113*0b57cec5SDimitry Andric   CONSTANTS_CE_CAST_Abbrev,
114*0b57cec5SDimitry Andric   CONSTANTS_NULL_Abbrev,
115*0b57cec5SDimitry Andric 
116*0b57cec5SDimitry Andric   // FUNCTION_BLOCK abbrev id's.
117*0b57cec5SDimitry Andric   FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
118*0b57cec5SDimitry Andric   FUNCTION_INST_UNOP_ABBREV,
119*0b57cec5SDimitry Andric   FUNCTION_INST_UNOP_FLAGS_ABBREV,
120*0b57cec5SDimitry Andric   FUNCTION_INST_BINOP_ABBREV,
121*0b57cec5SDimitry Andric   FUNCTION_INST_BINOP_FLAGS_ABBREV,
122*0b57cec5SDimitry Andric   FUNCTION_INST_CAST_ABBREV,
123*0b57cec5SDimitry Andric   FUNCTION_INST_RET_VOID_ABBREV,
124*0b57cec5SDimitry Andric   FUNCTION_INST_RET_VAL_ABBREV,
125*0b57cec5SDimitry Andric   FUNCTION_INST_UNREACHABLE_ABBREV,
126*0b57cec5SDimitry Andric   FUNCTION_INST_GEP_ABBREV,
127*0b57cec5SDimitry Andric };
128*0b57cec5SDimitry Andric 
129*0b57cec5SDimitry Andric /// Abstract class to manage the bitcode writing, subclassed for each bitcode
130*0b57cec5SDimitry Andric /// file type.
131*0b57cec5SDimitry Andric class BitcodeWriterBase {
132*0b57cec5SDimitry Andric protected:
133*0b57cec5SDimitry Andric   /// The stream created and owned by the client.
134*0b57cec5SDimitry Andric   BitstreamWriter &Stream;
135*0b57cec5SDimitry Andric 
136*0b57cec5SDimitry Andric   StringTableBuilder &StrtabBuilder;
137*0b57cec5SDimitry Andric 
138*0b57cec5SDimitry Andric public:
139*0b57cec5SDimitry Andric   /// Constructs a BitcodeWriterBase object that writes to the provided
140*0b57cec5SDimitry Andric   /// \p Stream.
141*0b57cec5SDimitry Andric   BitcodeWriterBase(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder)
142*0b57cec5SDimitry Andric       : Stream(Stream), StrtabBuilder(StrtabBuilder) {}
143*0b57cec5SDimitry Andric 
144*0b57cec5SDimitry Andric protected:
145*0b57cec5SDimitry Andric   void writeBitcodeHeader();
146*0b57cec5SDimitry Andric   void writeModuleVersion();
147*0b57cec5SDimitry Andric };
148*0b57cec5SDimitry Andric 
149*0b57cec5SDimitry Andric void BitcodeWriterBase::writeModuleVersion() {
150*0b57cec5SDimitry Andric   // VERSION: [version#]
151*0b57cec5SDimitry Andric   Stream.EmitRecord(bitc::MODULE_CODE_VERSION, ArrayRef<uint64_t>{2});
152*0b57cec5SDimitry Andric }
153*0b57cec5SDimitry Andric 
154*0b57cec5SDimitry Andric /// Base class to manage the module bitcode writing, currently subclassed for
155*0b57cec5SDimitry Andric /// ModuleBitcodeWriter and ThinLinkBitcodeWriter.
156*0b57cec5SDimitry Andric class ModuleBitcodeWriterBase : public BitcodeWriterBase {
157*0b57cec5SDimitry Andric protected:
158*0b57cec5SDimitry Andric   /// The Module to write to bitcode.
159*0b57cec5SDimitry Andric   const Module &M;
160*0b57cec5SDimitry Andric 
161*0b57cec5SDimitry Andric   /// Enumerates ids for all values in the module.
162*0b57cec5SDimitry Andric   ValueEnumerator VE;
163*0b57cec5SDimitry Andric 
164*0b57cec5SDimitry Andric   /// Optional per-module index to write for ThinLTO.
165*0b57cec5SDimitry Andric   const ModuleSummaryIndex *Index;
166*0b57cec5SDimitry Andric 
167*0b57cec5SDimitry Andric   /// Map that holds the correspondence between GUIDs in the summary index,
168*0b57cec5SDimitry Andric   /// that came from indirect call profiles, and a value id generated by this
169*0b57cec5SDimitry Andric   /// class to use in the VST and summary block records.
170*0b57cec5SDimitry Andric   std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
171*0b57cec5SDimitry Andric 
172*0b57cec5SDimitry Andric   /// Tracks the last value id recorded in the GUIDToValueMap.
173*0b57cec5SDimitry Andric   unsigned GlobalValueId;
174*0b57cec5SDimitry Andric 
175*0b57cec5SDimitry Andric   /// Saves the offset of the VSTOffset record that must eventually be
176*0b57cec5SDimitry Andric   /// backpatched with the offset of the actual VST.
177*0b57cec5SDimitry Andric   uint64_t VSTOffsetPlaceholder = 0;
178*0b57cec5SDimitry Andric 
179*0b57cec5SDimitry Andric public:
180*0b57cec5SDimitry Andric   /// Constructs a ModuleBitcodeWriterBase object for the given Module,
181*0b57cec5SDimitry Andric   /// writing to the provided \p Buffer.
182*0b57cec5SDimitry Andric   ModuleBitcodeWriterBase(const Module &M, StringTableBuilder &StrtabBuilder,
183*0b57cec5SDimitry Andric                           BitstreamWriter &Stream,
184*0b57cec5SDimitry Andric                           bool ShouldPreserveUseListOrder,
185*0b57cec5SDimitry Andric                           const ModuleSummaryIndex *Index)
186*0b57cec5SDimitry Andric       : BitcodeWriterBase(Stream, StrtabBuilder), M(M),
187*0b57cec5SDimitry Andric         VE(M, ShouldPreserveUseListOrder), Index(Index) {
188*0b57cec5SDimitry Andric     // Assign ValueIds to any callee values in the index that came from
189*0b57cec5SDimitry Andric     // indirect call profiles and were recorded as a GUID not a Value*
190*0b57cec5SDimitry Andric     // (which would have been assigned an ID by the ValueEnumerator).
191*0b57cec5SDimitry Andric     // The starting ValueId is just after the number of values in the
192*0b57cec5SDimitry Andric     // ValueEnumerator, so that they can be emitted in the VST.
193*0b57cec5SDimitry Andric     GlobalValueId = VE.getValues().size();
194*0b57cec5SDimitry Andric     if (!Index)
195*0b57cec5SDimitry Andric       return;
196*0b57cec5SDimitry Andric     for (const auto &GUIDSummaryLists : *Index)
197*0b57cec5SDimitry Andric       // Examine all summaries for this GUID.
198*0b57cec5SDimitry Andric       for (auto &Summary : GUIDSummaryLists.second.SummaryList)
199*0b57cec5SDimitry Andric         if (auto FS = dyn_cast<FunctionSummary>(Summary.get()))
200*0b57cec5SDimitry Andric           // For each call in the function summary, see if the call
201*0b57cec5SDimitry Andric           // is to a GUID (which means it is for an indirect call,
202*0b57cec5SDimitry Andric           // otherwise we would have a Value for it). If so, synthesize
203*0b57cec5SDimitry Andric           // a value id.
204*0b57cec5SDimitry Andric           for (auto &CallEdge : FS->calls())
205*0b57cec5SDimitry Andric             if (!CallEdge.first.haveGVs() || !CallEdge.first.getValue())
206*0b57cec5SDimitry Andric               assignValueId(CallEdge.first.getGUID());
207*0b57cec5SDimitry Andric   }
208*0b57cec5SDimitry Andric 
209*0b57cec5SDimitry Andric protected:
210*0b57cec5SDimitry Andric   void writePerModuleGlobalValueSummary();
211*0b57cec5SDimitry Andric 
212*0b57cec5SDimitry Andric private:
213*0b57cec5SDimitry Andric   void writePerModuleFunctionSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
214*0b57cec5SDimitry Andric                                            GlobalValueSummary *Summary,
215*0b57cec5SDimitry Andric                                            unsigned ValueID,
216*0b57cec5SDimitry Andric                                            unsigned FSCallsAbbrev,
217*0b57cec5SDimitry Andric                                            unsigned FSCallsProfileAbbrev,
218*0b57cec5SDimitry Andric                                            const Function &F);
219*0b57cec5SDimitry Andric   void writeModuleLevelReferences(const GlobalVariable &V,
220*0b57cec5SDimitry Andric                                   SmallVector<uint64_t, 64> &NameVals,
221*0b57cec5SDimitry Andric                                   unsigned FSModRefsAbbrev,
222*0b57cec5SDimitry Andric                                   unsigned FSModVTableRefsAbbrev);
223*0b57cec5SDimitry Andric 
224*0b57cec5SDimitry Andric   void assignValueId(GlobalValue::GUID ValGUID) {
225*0b57cec5SDimitry Andric     GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
226*0b57cec5SDimitry Andric   }
227*0b57cec5SDimitry Andric 
228*0b57cec5SDimitry Andric   unsigned getValueId(GlobalValue::GUID ValGUID) {
229*0b57cec5SDimitry Andric     const auto &VMI = GUIDToValueIdMap.find(ValGUID);
230*0b57cec5SDimitry Andric     // Expect that any GUID value had a value Id assigned by an
231*0b57cec5SDimitry Andric     // earlier call to assignValueId.
232*0b57cec5SDimitry Andric     assert(VMI != GUIDToValueIdMap.end() &&
233*0b57cec5SDimitry Andric            "GUID does not have assigned value Id");
234*0b57cec5SDimitry Andric     return VMI->second;
235*0b57cec5SDimitry Andric   }
236*0b57cec5SDimitry Andric 
237*0b57cec5SDimitry Andric   // Helper to get the valueId for the type of value recorded in VI.
238*0b57cec5SDimitry Andric   unsigned getValueId(ValueInfo VI) {
239*0b57cec5SDimitry Andric     if (!VI.haveGVs() || !VI.getValue())
240*0b57cec5SDimitry Andric       return getValueId(VI.getGUID());
241*0b57cec5SDimitry Andric     return VE.getValueID(VI.getValue());
242*0b57cec5SDimitry Andric   }
243*0b57cec5SDimitry Andric 
244*0b57cec5SDimitry Andric   std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
245*0b57cec5SDimitry Andric };
246*0b57cec5SDimitry Andric 
247*0b57cec5SDimitry Andric /// Class to manage the bitcode writing for a module.
248*0b57cec5SDimitry Andric class ModuleBitcodeWriter : public ModuleBitcodeWriterBase {
249*0b57cec5SDimitry Andric   /// Pointer to the buffer allocated by caller for bitcode writing.
250*0b57cec5SDimitry Andric   const SmallVectorImpl<char> &Buffer;
251*0b57cec5SDimitry Andric 
252*0b57cec5SDimitry Andric   /// True if a module hash record should be written.
253*0b57cec5SDimitry Andric   bool GenerateHash;
254*0b57cec5SDimitry Andric 
255*0b57cec5SDimitry Andric   /// If non-null, when GenerateHash is true, the resulting hash is written
256*0b57cec5SDimitry Andric   /// into ModHash.
257*0b57cec5SDimitry Andric   ModuleHash *ModHash;
258*0b57cec5SDimitry Andric 
259*0b57cec5SDimitry Andric   SHA1 Hasher;
260*0b57cec5SDimitry Andric 
261*0b57cec5SDimitry Andric   /// The start bit of the identification block.
262*0b57cec5SDimitry Andric   uint64_t BitcodeStartBit;
263*0b57cec5SDimitry Andric 
264*0b57cec5SDimitry Andric public:
265*0b57cec5SDimitry Andric   /// Constructs a ModuleBitcodeWriter object for the given Module,
266*0b57cec5SDimitry Andric   /// writing to the provided \p Buffer.
267*0b57cec5SDimitry Andric   ModuleBitcodeWriter(const Module &M, SmallVectorImpl<char> &Buffer,
268*0b57cec5SDimitry Andric                       StringTableBuilder &StrtabBuilder,
269*0b57cec5SDimitry Andric                       BitstreamWriter &Stream, bool ShouldPreserveUseListOrder,
270*0b57cec5SDimitry Andric                       const ModuleSummaryIndex *Index, bool GenerateHash,
271*0b57cec5SDimitry Andric                       ModuleHash *ModHash = nullptr)
272*0b57cec5SDimitry Andric       : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
273*0b57cec5SDimitry Andric                                 ShouldPreserveUseListOrder, Index),
274*0b57cec5SDimitry Andric         Buffer(Buffer), GenerateHash(GenerateHash), ModHash(ModHash),
275*0b57cec5SDimitry Andric         BitcodeStartBit(Stream.GetCurrentBitNo()) {}
276*0b57cec5SDimitry Andric 
277*0b57cec5SDimitry Andric   /// Emit the current module to the bitstream.
278*0b57cec5SDimitry Andric   void write();
279*0b57cec5SDimitry Andric 
280*0b57cec5SDimitry Andric private:
281*0b57cec5SDimitry Andric   uint64_t bitcodeStartBit() { return BitcodeStartBit; }
282*0b57cec5SDimitry Andric 
283*0b57cec5SDimitry Andric   size_t addToStrtab(StringRef Str);
284*0b57cec5SDimitry Andric 
285*0b57cec5SDimitry Andric   void writeAttributeGroupTable();
286*0b57cec5SDimitry Andric   void writeAttributeTable();
287*0b57cec5SDimitry Andric   void writeTypeTable();
288*0b57cec5SDimitry Andric   void writeComdats();
289*0b57cec5SDimitry Andric   void writeValueSymbolTableForwardDecl();
290*0b57cec5SDimitry Andric   void writeModuleInfo();
291*0b57cec5SDimitry Andric   void writeValueAsMetadata(const ValueAsMetadata *MD,
292*0b57cec5SDimitry Andric                             SmallVectorImpl<uint64_t> &Record);
293*0b57cec5SDimitry Andric   void writeMDTuple(const MDTuple *N, SmallVectorImpl<uint64_t> &Record,
294*0b57cec5SDimitry Andric                     unsigned Abbrev);
295*0b57cec5SDimitry Andric   unsigned createDILocationAbbrev();
296*0b57cec5SDimitry Andric   void writeDILocation(const DILocation *N, SmallVectorImpl<uint64_t> &Record,
297*0b57cec5SDimitry Andric                        unsigned &Abbrev);
298*0b57cec5SDimitry Andric   unsigned createGenericDINodeAbbrev();
299*0b57cec5SDimitry Andric   void writeGenericDINode(const GenericDINode *N,
300*0b57cec5SDimitry Andric                           SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev);
301*0b57cec5SDimitry Andric   void writeDISubrange(const DISubrange *N, SmallVectorImpl<uint64_t> &Record,
302*0b57cec5SDimitry Andric                        unsigned Abbrev);
303e8d8bef9SDimitry Andric   void writeDIGenericSubrange(const DIGenericSubrange *N,
304e8d8bef9SDimitry Andric                               SmallVectorImpl<uint64_t> &Record,
305e8d8bef9SDimitry Andric                               unsigned Abbrev);
306*0b57cec5SDimitry Andric   void writeDIEnumerator(const DIEnumerator *N,
307*0b57cec5SDimitry Andric                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
308*0b57cec5SDimitry Andric   void writeDIBasicType(const DIBasicType *N, SmallVectorImpl<uint64_t> &Record,
309*0b57cec5SDimitry Andric                         unsigned Abbrev);
310e8d8bef9SDimitry Andric   void writeDIStringType(const DIStringType *N,
311e8d8bef9SDimitry Andric                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
312*0b57cec5SDimitry Andric   void writeDIDerivedType(const DIDerivedType *N,
313*0b57cec5SDimitry Andric                           SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
314*0b57cec5SDimitry Andric   void writeDICompositeType(const DICompositeType *N,
315*0b57cec5SDimitry Andric                             SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
316*0b57cec5SDimitry Andric   void writeDISubroutineType(const DISubroutineType *N,
317*0b57cec5SDimitry Andric                              SmallVectorImpl<uint64_t> &Record,
318*0b57cec5SDimitry Andric                              unsigned Abbrev);
319*0b57cec5SDimitry Andric   void writeDIFile(const DIFile *N, SmallVectorImpl<uint64_t> &Record,
320*0b57cec5SDimitry Andric                    unsigned Abbrev);
321*0b57cec5SDimitry Andric   void writeDICompileUnit(const DICompileUnit *N,
322*0b57cec5SDimitry Andric                           SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
323*0b57cec5SDimitry Andric   void writeDISubprogram(const DISubprogram *N,
324*0b57cec5SDimitry Andric                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
325*0b57cec5SDimitry Andric   void writeDILexicalBlock(const DILexicalBlock *N,
326*0b57cec5SDimitry Andric                            SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
327*0b57cec5SDimitry Andric   void writeDILexicalBlockFile(const DILexicalBlockFile *N,
328*0b57cec5SDimitry Andric                                SmallVectorImpl<uint64_t> &Record,
329*0b57cec5SDimitry Andric                                unsigned Abbrev);
330*0b57cec5SDimitry Andric   void writeDICommonBlock(const DICommonBlock *N,
331*0b57cec5SDimitry Andric                           SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
332*0b57cec5SDimitry Andric   void writeDINamespace(const DINamespace *N, SmallVectorImpl<uint64_t> &Record,
333*0b57cec5SDimitry Andric                         unsigned Abbrev);
334*0b57cec5SDimitry Andric   void writeDIMacro(const DIMacro *N, SmallVectorImpl<uint64_t> &Record,
335*0b57cec5SDimitry Andric                     unsigned Abbrev);
336*0b57cec5SDimitry Andric   void writeDIMacroFile(const DIMacroFile *N, SmallVectorImpl<uint64_t> &Record,
337*0b57cec5SDimitry Andric                         unsigned Abbrev);
338*0b57cec5SDimitry Andric   void writeDIModule(const DIModule *N, SmallVectorImpl<uint64_t> &Record,
339*0b57cec5SDimitry Andric                      unsigned Abbrev);
340*0b57cec5SDimitry Andric   void writeDITemplateTypeParameter(const DITemplateTypeParameter *N,
341*0b57cec5SDimitry Andric                                     SmallVectorImpl<uint64_t> &Record,
342*0b57cec5SDimitry Andric                                     unsigned Abbrev);
343*0b57cec5SDimitry Andric   void writeDITemplateValueParameter(const DITemplateValueParameter *N,
344*0b57cec5SDimitry Andric                                      SmallVectorImpl<uint64_t> &Record,
345*0b57cec5SDimitry Andric                                      unsigned Abbrev);
346*0b57cec5SDimitry Andric   void writeDIGlobalVariable(const DIGlobalVariable *N,
347*0b57cec5SDimitry Andric                              SmallVectorImpl<uint64_t> &Record,
348*0b57cec5SDimitry Andric                              unsigned Abbrev);
349*0b57cec5SDimitry Andric   void writeDILocalVariable(const DILocalVariable *N,
350*0b57cec5SDimitry Andric                             SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
351*0b57cec5SDimitry Andric   void writeDILabel(const DILabel *N,
352*0b57cec5SDimitry Andric                     SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
353*0b57cec5SDimitry Andric   void writeDIExpression(const DIExpression *N,
354*0b57cec5SDimitry Andric                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
355*0b57cec5SDimitry Andric   void writeDIGlobalVariableExpression(const DIGlobalVariableExpression *N,
356*0b57cec5SDimitry Andric                                        SmallVectorImpl<uint64_t> &Record,
357*0b57cec5SDimitry Andric                                        unsigned Abbrev);
358*0b57cec5SDimitry Andric   void writeDIObjCProperty(const DIObjCProperty *N,
359*0b57cec5SDimitry Andric                            SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
360*0b57cec5SDimitry Andric   void writeDIImportedEntity(const DIImportedEntity *N,
361*0b57cec5SDimitry Andric                              SmallVectorImpl<uint64_t> &Record,
362*0b57cec5SDimitry Andric                              unsigned Abbrev);
363*0b57cec5SDimitry Andric   unsigned createNamedMetadataAbbrev();
364*0b57cec5SDimitry Andric   void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
365*0b57cec5SDimitry Andric   unsigned createMetadataStringsAbbrev();
366*0b57cec5SDimitry Andric   void writeMetadataStrings(ArrayRef<const Metadata *> Strings,
367*0b57cec5SDimitry Andric                             SmallVectorImpl<uint64_t> &Record);
368*0b57cec5SDimitry Andric   void writeMetadataRecords(ArrayRef<const Metadata *> MDs,
369*0b57cec5SDimitry Andric                             SmallVectorImpl<uint64_t> &Record,
370*0b57cec5SDimitry Andric                             std::vector<unsigned> *MDAbbrevs = nullptr,
371*0b57cec5SDimitry Andric                             std::vector<uint64_t> *IndexPos = nullptr);
372*0b57cec5SDimitry Andric   void writeModuleMetadata();
373*0b57cec5SDimitry Andric   void writeFunctionMetadata(const Function &F);
374*0b57cec5SDimitry Andric   void writeFunctionMetadataAttachment(const Function &F);
375*0b57cec5SDimitry Andric   void writeGlobalVariableMetadataAttachment(const GlobalVariable &GV);
376*0b57cec5SDimitry Andric   void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
377*0b57cec5SDimitry Andric                                     const GlobalObject &GO);
378*0b57cec5SDimitry Andric   void writeModuleMetadataKinds();
379*0b57cec5SDimitry Andric   void writeOperandBundleTags();
380*0b57cec5SDimitry Andric   void writeSyncScopeNames();
381*0b57cec5SDimitry Andric   void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal);
382*0b57cec5SDimitry Andric   void writeModuleConstants();
383*0b57cec5SDimitry Andric   bool pushValueAndType(const Value *V, unsigned InstID,
384*0b57cec5SDimitry Andric                         SmallVectorImpl<unsigned> &Vals);
3855ffd83dbSDimitry Andric   void writeOperandBundles(const CallBase &CB, unsigned InstID);
386*0b57cec5SDimitry Andric   void pushValue(const Value *V, unsigned InstID,
387*0b57cec5SDimitry Andric                  SmallVectorImpl<unsigned> &Vals);
388*0b57cec5SDimitry Andric   void pushValueSigned(const Value *V, unsigned InstID,
389*0b57cec5SDimitry Andric                        SmallVectorImpl<uint64_t> &Vals);
390*0b57cec5SDimitry Andric   void writeInstruction(const Instruction &I, unsigned InstID,
391*0b57cec5SDimitry Andric                         SmallVectorImpl<unsigned> &Vals);
392*0b57cec5SDimitry Andric   void writeFunctionLevelValueSymbolTable(const ValueSymbolTable &VST);
393*0b57cec5SDimitry Andric   void writeGlobalValueSymbolTable(
394*0b57cec5SDimitry Andric       DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
395*0b57cec5SDimitry Andric   void writeUseList(UseListOrder &&Order);
396*0b57cec5SDimitry Andric   void writeUseListBlock(const Function *F);
397*0b57cec5SDimitry Andric   void
398*0b57cec5SDimitry Andric   writeFunction(const Function &F,
399*0b57cec5SDimitry Andric                 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
400*0b57cec5SDimitry Andric   void writeBlockInfo();
401*0b57cec5SDimitry Andric   void writeModuleHash(size_t BlockStartPos);
402*0b57cec5SDimitry Andric 
403*0b57cec5SDimitry Andric   unsigned getEncodedSyncScopeID(SyncScope::ID SSID) {
404*0b57cec5SDimitry Andric     return unsigned(SSID);
405*0b57cec5SDimitry Andric   }
406e8d8bef9SDimitry Andric 
407e8d8bef9SDimitry Andric   unsigned getEncodedAlign(MaybeAlign Alignment) { return encode(Alignment); }
408*0b57cec5SDimitry Andric };
409*0b57cec5SDimitry Andric 
410*0b57cec5SDimitry Andric /// Class to manage the bitcode writing for a combined index.
411*0b57cec5SDimitry Andric class IndexBitcodeWriter : public BitcodeWriterBase {
412*0b57cec5SDimitry Andric   /// The combined index to write to bitcode.
413*0b57cec5SDimitry Andric   const ModuleSummaryIndex &Index;
414*0b57cec5SDimitry Andric 
415*0b57cec5SDimitry Andric   /// When writing a subset of the index for distributed backends, client
416*0b57cec5SDimitry Andric   /// provides a map of modules to the corresponding GUIDs/summaries to write.
417*0b57cec5SDimitry Andric   const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex;
418*0b57cec5SDimitry Andric 
419*0b57cec5SDimitry Andric   /// Map that holds the correspondence between the GUID used in the combined
420*0b57cec5SDimitry Andric   /// index and a value id generated by this class to use in references.
421*0b57cec5SDimitry Andric   std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
422*0b57cec5SDimitry Andric 
423*0b57cec5SDimitry Andric   /// Tracks the last value id recorded in the GUIDToValueMap.
424*0b57cec5SDimitry Andric   unsigned GlobalValueId = 0;
425*0b57cec5SDimitry Andric 
426*0b57cec5SDimitry Andric public:
427*0b57cec5SDimitry Andric   /// Constructs a IndexBitcodeWriter object for the given combined index,
428*0b57cec5SDimitry Andric   /// writing to the provided \p Buffer. When writing a subset of the index
429*0b57cec5SDimitry Andric   /// for a distributed backend, provide a \p ModuleToSummariesForIndex map.
430*0b57cec5SDimitry Andric   IndexBitcodeWriter(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder,
431*0b57cec5SDimitry Andric                      const ModuleSummaryIndex &Index,
432*0b57cec5SDimitry Andric                      const std::map<std::string, GVSummaryMapTy>
433*0b57cec5SDimitry Andric                          *ModuleToSummariesForIndex = nullptr)
434*0b57cec5SDimitry Andric       : BitcodeWriterBase(Stream, StrtabBuilder), Index(Index),
435*0b57cec5SDimitry Andric         ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
436*0b57cec5SDimitry Andric     // Assign unique value ids to all summaries to be written, for use
437*0b57cec5SDimitry Andric     // in writing out the call graph edges. Save the mapping from GUID
438*0b57cec5SDimitry Andric     // to the new global value id to use when writing those edges, which
439*0b57cec5SDimitry Andric     // are currently saved in the index in terms of GUID.
440*0b57cec5SDimitry Andric     forEachSummary([&](GVInfo I, bool) {
441*0b57cec5SDimitry Andric       GUIDToValueIdMap[I.first] = ++GlobalValueId;
442*0b57cec5SDimitry Andric     });
443*0b57cec5SDimitry Andric   }
444*0b57cec5SDimitry Andric 
445*0b57cec5SDimitry Andric   /// The below iterator returns the GUID and associated summary.
446*0b57cec5SDimitry Andric   using GVInfo = std::pair<GlobalValue::GUID, GlobalValueSummary *>;
447*0b57cec5SDimitry Andric 
448*0b57cec5SDimitry Andric   /// Calls the callback for each value GUID and summary to be written to
449*0b57cec5SDimitry Andric   /// bitcode. This hides the details of whether they are being pulled from the
450*0b57cec5SDimitry Andric   /// entire index or just those in a provided ModuleToSummariesForIndex map.
451*0b57cec5SDimitry Andric   template<typename Functor>
452*0b57cec5SDimitry Andric   void forEachSummary(Functor Callback) {
453*0b57cec5SDimitry Andric     if (ModuleToSummariesForIndex) {
454*0b57cec5SDimitry Andric       for (auto &M : *ModuleToSummariesForIndex)
455*0b57cec5SDimitry Andric         for (auto &Summary : M.second) {
456*0b57cec5SDimitry Andric           Callback(Summary, false);
457*0b57cec5SDimitry Andric           // Ensure aliasee is handled, e.g. for assigning a valueId,
458*0b57cec5SDimitry Andric           // even if we are not importing the aliasee directly (the
459*0b57cec5SDimitry Andric           // imported alias will contain a copy of aliasee).
460*0b57cec5SDimitry Andric           if (auto *AS = dyn_cast<AliasSummary>(Summary.getSecond()))
461*0b57cec5SDimitry Andric             Callback({AS->getAliaseeGUID(), &AS->getAliasee()}, true);
462*0b57cec5SDimitry Andric         }
463*0b57cec5SDimitry Andric     } else {
464*0b57cec5SDimitry Andric       for (auto &Summaries : Index)
465*0b57cec5SDimitry Andric         for (auto &Summary : Summaries.second.SummaryList)
466*0b57cec5SDimitry Andric           Callback({Summaries.first, Summary.get()}, false);
467*0b57cec5SDimitry Andric     }
468*0b57cec5SDimitry Andric   }
469*0b57cec5SDimitry Andric 
470*0b57cec5SDimitry Andric   /// Calls the callback for each entry in the modulePaths StringMap that
471*0b57cec5SDimitry Andric   /// should be written to the module path string table. This hides the details
472*0b57cec5SDimitry Andric   /// of whether they are being pulled from the entire index or just those in a
473*0b57cec5SDimitry Andric   /// provided ModuleToSummariesForIndex map.
474*0b57cec5SDimitry Andric   template <typename Functor> void forEachModule(Functor Callback) {
475*0b57cec5SDimitry Andric     if (ModuleToSummariesForIndex) {
476*0b57cec5SDimitry Andric       for (const auto &M : *ModuleToSummariesForIndex) {
477*0b57cec5SDimitry Andric         const auto &MPI = Index.modulePaths().find(M.first);
478*0b57cec5SDimitry Andric         if (MPI == Index.modulePaths().end()) {
479*0b57cec5SDimitry Andric           // This should only happen if the bitcode file was empty, in which
480*0b57cec5SDimitry Andric           // case we shouldn't be importing (the ModuleToSummariesForIndex
481*0b57cec5SDimitry Andric           // would only include the module we are writing and index for).
482*0b57cec5SDimitry Andric           assert(ModuleToSummariesForIndex->size() == 1);
483*0b57cec5SDimitry Andric           continue;
484*0b57cec5SDimitry Andric         }
485*0b57cec5SDimitry Andric         Callback(*MPI);
486*0b57cec5SDimitry Andric       }
487*0b57cec5SDimitry Andric     } else {
488*0b57cec5SDimitry Andric       for (const auto &MPSE : Index.modulePaths())
489*0b57cec5SDimitry Andric         Callback(MPSE);
490*0b57cec5SDimitry Andric     }
491*0b57cec5SDimitry Andric   }
492*0b57cec5SDimitry Andric 
493*0b57cec5SDimitry Andric   /// Main entry point for writing a combined index to bitcode.
494*0b57cec5SDimitry Andric   void write();
495*0b57cec5SDimitry Andric 
496*0b57cec5SDimitry Andric private:
497*0b57cec5SDimitry Andric   void writeModStrings();
498*0b57cec5SDimitry Andric   void writeCombinedGlobalValueSummary();
499*0b57cec5SDimitry Andric 
500*0b57cec5SDimitry Andric   Optional<unsigned> getValueId(GlobalValue::GUID ValGUID) {
501*0b57cec5SDimitry Andric     auto VMI = GUIDToValueIdMap.find(ValGUID);
502*0b57cec5SDimitry Andric     if (VMI == GUIDToValueIdMap.end())
503*0b57cec5SDimitry Andric       return None;
504*0b57cec5SDimitry Andric     return VMI->second;
505*0b57cec5SDimitry Andric   }
506*0b57cec5SDimitry Andric 
507*0b57cec5SDimitry Andric   std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
508*0b57cec5SDimitry Andric };
509*0b57cec5SDimitry Andric 
510*0b57cec5SDimitry Andric } // end anonymous namespace
511*0b57cec5SDimitry Andric 
512*0b57cec5SDimitry Andric static unsigned getEncodedCastOpcode(unsigned Opcode) {
513*0b57cec5SDimitry Andric   switch (Opcode) {
514*0b57cec5SDimitry Andric   default: llvm_unreachable("Unknown cast instruction!");
515*0b57cec5SDimitry Andric   case Instruction::Trunc   : return bitc::CAST_TRUNC;
516*0b57cec5SDimitry Andric   case Instruction::ZExt    : return bitc::CAST_ZEXT;
517*0b57cec5SDimitry Andric   case Instruction::SExt    : return bitc::CAST_SEXT;
518*0b57cec5SDimitry Andric   case Instruction::FPToUI  : return bitc::CAST_FPTOUI;
519*0b57cec5SDimitry Andric   case Instruction::FPToSI  : return bitc::CAST_FPTOSI;
520*0b57cec5SDimitry Andric   case Instruction::UIToFP  : return bitc::CAST_UITOFP;
521*0b57cec5SDimitry Andric   case Instruction::SIToFP  : return bitc::CAST_SITOFP;
522*0b57cec5SDimitry Andric   case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
523*0b57cec5SDimitry Andric   case Instruction::FPExt   : return bitc::CAST_FPEXT;
524*0b57cec5SDimitry Andric   case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
525*0b57cec5SDimitry Andric   case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
526*0b57cec5SDimitry Andric   case Instruction::BitCast : return bitc::CAST_BITCAST;
527*0b57cec5SDimitry Andric   case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
528*0b57cec5SDimitry Andric   }
529*0b57cec5SDimitry Andric }
530*0b57cec5SDimitry Andric 
531*0b57cec5SDimitry Andric static unsigned getEncodedUnaryOpcode(unsigned Opcode) {
532*0b57cec5SDimitry Andric   switch (Opcode) {
533*0b57cec5SDimitry Andric   default: llvm_unreachable("Unknown binary instruction!");
5348bcb0991SDimitry Andric   case Instruction::FNeg: return bitc::UNOP_FNEG;
535*0b57cec5SDimitry Andric   }
536*0b57cec5SDimitry Andric }
537*0b57cec5SDimitry Andric 
538*0b57cec5SDimitry Andric static unsigned getEncodedBinaryOpcode(unsigned Opcode) {
539*0b57cec5SDimitry Andric   switch (Opcode) {
540*0b57cec5SDimitry Andric   default: llvm_unreachable("Unknown binary instruction!");
541*0b57cec5SDimitry Andric   case Instruction::Add:
542*0b57cec5SDimitry Andric   case Instruction::FAdd: return bitc::BINOP_ADD;
543*0b57cec5SDimitry Andric   case Instruction::Sub:
544*0b57cec5SDimitry Andric   case Instruction::FSub: return bitc::BINOP_SUB;
545*0b57cec5SDimitry Andric   case Instruction::Mul:
546*0b57cec5SDimitry Andric   case Instruction::FMul: return bitc::BINOP_MUL;
547*0b57cec5SDimitry Andric   case Instruction::UDiv: return bitc::BINOP_UDIV;
548*0b57cec5SDimitry Andric   case Instruction::FDiv:
549*0b57cec5SDimitry Andric   case Instruction::SDiv: return bitc::BINOP_SDIV;
550*0b57cec5SDimitry Andric   case Instruction::URem: return bitc::BINOP_UREM;
551*0b57cec5SDimitry Andric   case Instruction::FRem:
552*0b57cec5SDimitry Andric   case Instruction::SRem: return bitc::BINOP_SREM;
553*0b57cec5SDimitry Andric   case Instruction::Shl:  return bitc::BINOP_SHL;
554*0b57cec5SDimitry Andric   case Instruction::LShr: return bitc::BINOP_LSHR;
555*0b57cec5SDimitry Andric   case Instruction::AShr: return bitc::BINOP_ASHR;
556*0b57cec5SDimitry Andric   case Instruction::And:  return bitc::BINOP_AND;
557*0b57cec5SDimitry Andric   case Instruction::Or:   return bitc::BINOP_OR;
558*0b57cec5SDimitry Andric   case Instruction::Xor:  return bitc::BINOP_XOR;
559*0b57cec5SDimitry Andric   }
560*0b57cec5SDimitry Andric }
561*0b57cec5SDimitry Andric 
562*0b57cec5SDimitry Andric static unsigned getEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
563*0b57cec5SDimitry Andric   switch (Op) {
564*0b57cec5SDimitry Andric   default: llvm_unreachable("Unknown RMW operation!");
565*0b57cec5SDimitry Andric   case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
566*0b57cec5SDimitry Andric   case AtomicRMWInst::Add: return bitc::RMW_ADD;
567*0b57cec5SDimitry Andric   case AtomicRMWInst::Sub: return bitc::RMW_SUB;
568*0b57cec5SDimitry Andric   case AtomicRMWInst::And: return bitc::RMW_AND;
569*0b57cec5SDimitry Andric   case AtomicRMWInst::Nand: return bitc::RMW_NAND;
570*0b57cec5SDimitry Andric   case AtomicRMWInst::Or: return bitc::RMW_OR;
571*0b57cec5SDimitry Andric   case AtomicRMWInst::Xor: return bitc::RMW_XOR;
572*0b57cec5SDimitry Andric   case AtomicRMWInst::Max: return bitc::RMW_MAX;
573*0b57cec5SDimitry Andric   case AtomicRMWInst::Min: return bitc::RMW_MIN;
574*0b57cec5SDimitry Andric   case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
575*0b57cec5SDimitry Andric   case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
576*0b57cec5SDimitry Andric   case AtomicRMWInst::FAdd: return bitc::RMW_FADD;
577*0b57cec5SDimitry Andric   case AtomicRMWInst::FSub: return bitc::RMW_FSUB;
578*0b57cec5SDimitry Andric   }
579*0b57cec5SDimitry Andric }
580*0b57cec5SDimitry Andric 
581*0b57cec5SDimitry Andric static unsigned getEncodedOrdering(AtomicOrdering Ordering) {
582*0b57cec5SDimitry Andric   switch (Ordering) {
583*0b57cec5SDimitry Andric   case AtomicOrdering::NotAtomic: return bitc::ORDERING_NOTATOMIC;
584*0b57cec5SDimitry Andric   case AtomicOrdering::Unordered: return bitc::ORDERING_UNORDERED;
585*0b57cec5SDimitry Andric   case AtomicOrdering::Monotonic: return bitc::ORDERING_MONOTONIC;
586*0b57cec5SDimitry Andric   case AtomicOrdering::Acquire: return bitc::ORDERING_ACQUIRE;
587*0b57cec5SDimitry Andric   case AtomicOrdering::Release: return bitc::ORDERING_RELEASE;
588*0b57cec5SDimitry Andric   case AtomicOrdering::AcquireRelease: return bitc::ORDERING_ACQREL;
589*0b57cec5SDimitry Andric   case AtomicOrdering::SequentiallyConsistent: return bitc::ORDERING_SEQCST;
590*0b57cec5SDimitry Andric   }
591*0b57cec5SDimitry Andric   llvm_unreachable("Invalid ordering");
592*0b57cec5SDimitry Andric }
593*0b57cec5SDimitry Andric 
594*0b57cec5SDimitry Andric static void writeStringRecord(BitstreamWriter &Stream, unsigned Code,
595*0b57cec5SDimitry Andric                               StringRef Str, unsigned AbbrevToUse) {
596*0b57cec5SDimitry Andric   SmallVector<unsigned, 64> Vals;
597*0b57cec5SDimitry Andric 
598*0b57cec5SDimitry Andric   // Code: [strchar x N]
599*0b57cec5SDimitry Andric   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
600*0b57cec5SDimitry Andric     if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
601*0b57cec5SDimitry Andric       AbbrevToUse = 0;
602*0b57cec5SDimitry Andric     Vals.push_back(Str[i]);
603*0b57cec5SDimitry Andric   }
604*0b57cec5SDimitry Andric 
605*0b57cec5SDimitry Andric   // Emit the finished record.
606*0b57cec5SDimitry Andric   Stream.EmitRecord(Code, Vals, AbbrevToUse);
607*0b57cec5SDimitry Andric }
608*0b57cec5SDimitry Andric 
609*0b57cec5SDimitry Andric static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
610*0b57cec5SDimitry Andric   switch (Kind) {
611*0b57cec5SDimitry Andric   case Attribute::Alignment:
612*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_ALIGNMENT;
613*0b57cec5SDimitry Andric   case Attribute::AllocSize:
614*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_ALLOC_SIZE;
615*0b57cec5SDimitry Andric   case Attribute::AlwaysInline:
616*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_ALWAYS_INLINE;
617*0b57cec5SDimitry Andric   case Attribute::ArgMemOnly:
618*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_ARGMEMONLY;
619*0b57cec5SDimitry Andric   case Attribute::Builtin:
620*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_BUILTIN;
621*0b57cec5SDimitry Andric   case Attribute::ByVal:
622*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_BY_VAL;
623*0b57cec5SDimitry Andric   case Attribute::Convergent:
624*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_CONVERGENT;
625*0b57cec5SDimitry Andric   case Attribute::InAlloca:
626*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_IN_ALLOCA;
627*0b57cec5SDimitry Andric   case Attribute::Cold:
628*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_COLD;
629e8d8bef9SDimitry Andric   case Attribute::Hot:
630e8d8bef9SDimitry Andric     return bitc::ATTR_KIND_HOT;
631*0b57cec5SDimitry Andric   case Attribute::InaccessibleMemOnly:
632*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY;
633*0b57cec5SDimitry Andric   case Attribute::InaccessibleMemOrArgMemOnly:
634*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY;
635*0b57cec5SDimitry Andric   case Attribute::InlineHint:
636*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_INLINE_HINT;
637*0b57cec5SDimitry Andric   case Attribute::InReg:
638*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_IN_REG;
639*0b57cec5SDimitry Andric   case Attribute::JumpTable:
640*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_JUMP_TABLE;
641*0b57cec5SDimitry Andric   case Attribute::MinSize:
642*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_MIN_SIZE;
643*0b57cec5SDimitry Andric   case Attribute::Naked:
644*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_NAKED;
645*0b57cec5SDimitry Andric   case Attribute::Nest:
646*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_NEST;
647*0b57cec5SDimitry Andric   case Attribute::NoAlias:
648*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_NO_ALIAS;
649*0b57cec5SDimitry Andric   case Attribute::NoBuiltin:
650*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_NO_BUILTIN;
651e8d8bef9SDimitry Andric   case Attribute::NoCallback:
652e8d8bef9SDimitry Andric     return bitc::ATTR_KIND_NO_CALLBACK;
653*0b57cec5SDimitry Andric   case Attribute::NoCapture:
654*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_NO_CAPTURE;
655*0b57cec5SDimitry Andric   case Attribute::NoDuplicate:
656*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_NO_DUPLICATE;
657*0b57cec5SDimitry Andric   case Attribute::NoFree:
658*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_NOFREE;
659*0b57cec5SDimitry Andric   case Attribute::NoImplicitFloat:
660*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
661*0b57cec5SDimitry Andric   case Attribute::NoInline:
662*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_NO_INLINE;
663*0b57cec5SDimitry Andric   case Attribute::NoRecurse:
664*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_NO_RECURSE;
6655ffd83dbSDimitry Andric   case Attribute::NoMerge:
6665ffd83dbSDimitry Andric     return bitc::ATTR_KIND_NO_MERGE;
667*0b57cec5SDimitry Andric   case Attribute::NonLazyBind:
668*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_NON_LAZY_BIND;
669*0b57cec5SDimitry Andric   case Attribute::NonNull:
670*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_NON_NULL;
671*0b57cec5SDimitry Andric   case Attribute::Dereferenceable:
672*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_DEREFERENCEABLE;
673*0b57cec5SDimitry Andric   case Attribute::DereferenceableOrNull:
674*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL;
675*0b57cec5SDimitry Andric   case Attribute::NoRedZone:
676*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_NO_RED_ZONE;
677*0b57cec5SDimitry Andric   case Attribute::NoReturn:
678*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_NO_RETURN;
679*0b57cec5SDimitry Andric   case Attribute::NoSync:
680*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_NOSYNC;
681*0b57cec5SDimitry Andric   case Attribute::NoCfCheck:
682*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_NOCF_CHECK;
683e8d8bef9SDimitry Andric   case Attribute::NoProfile:
684e8d8bef9SDimitry Andric     return bitc::ATTR_KIND_NO_PROFILE;
685*0b57cec5SDimitry Andric   case Attribute::NoUnwind:
686*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_NO_UNWIND;
6875ffd83dbSDimitry Andric   case Attribute::NullPointerIsValid:
6885ffd83dbSDimitry Andric     return bitc::ATTR_KIND_NULL_POINTER_IS_VALID;
689*0b57cec5SDimitry Andric   case Attribute::OptForFuzzing:
690*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_OPT_FOR_FUZZING;
691*0b57cec5SDimitry Andric   case Attribute::OptimizeForSize:
692*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
693*0b57cec5SDimitry Andric   case Attribute::OptimizeNone:
694*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_OPTIMIZE_NONE;
695*0b57cec5SDimitry Andric   case Attribute::ReadNone:
696*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_READ_NONE;
697*0b57cec5SDimitry Andric   case Attribute::ReadOnly:
698*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_READ_ONLY;
699*0b57cec5SDimitry Andric   case Attribute::Returned:
700*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_RETURNED;
701*0b57cec5SDimitry Andric   case Attribute::ReturnsTwice:
702*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_RETURNS_TWICE;
703*0b57cec5SDimitry Andric   case Attribute::SExt:
704*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_S_EXT;
705*0b57cec5SDimitry Andric   case Attribute::Speculatable:
706*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_SPECULATABLE;
707*0b57cec5SDimitry Andric   case Attribute::StackAlignment:
708*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_STACK_ALIGNMENT;
709*0b57cec5SDimitry Andric   case Attribute::StackProtect:
710*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_STACK_PROTECT;
711*0b57cec5SDimitry Andric   case Attribute::StackProtectReq:
712*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_STACK_PROTECT_REQ;
713*0b57cec5SDimitry Andric   case Attribute::StackProtectStrong:
714*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
715*0b57cec5SDimitry Andric   case Attribute::SafeStack:
716*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_SAFESTACK;
717*0b57cec5SDimitry Andric   case Attribute::ShadowCallStack:
718*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_SHADOWCALLSTACK;
719*0b57cec5SDimitry Andric   case Attribute::StrictFP:
720*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_STRICT_FP;
721*0b57cec5SDimitry Andric   case Attribute::StructRet:
722*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_STRUCT_RET;
723*0b57cec5SDimitry Andric   case Attribute::SanitizeAddress:
724*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_SANITIZE_ADDRESS;
725*0b57cec5SDimitry Andric   case Attribute::SanitizeHWAddress:
726*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_SANITIZE_HWADDRESS;
727*0b57cec5SDimitry Andric   case Attribute::SanitizeThread:
728*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_SANITIZE_THREAD;
729*0b57cec5SDimitry Andric   case Attribute::SanitizeMemory:
730*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_SANITIZE_MEMORY;
731*0b57cec5SDimitry Andric   case Attribute::SpeculativeLoadHardening:
732*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING;
733*0b57cec5SDimitry Andric   case Attribute::SwiftError:
734*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_SWIFT_ERROR;
735*0b57cec5SDimitry Andric   case Attribute::SwiftSelf:
736*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_SWIFT_SELF;
737*0b57cec5SDimitry Andric   case Attribute::UWTable:
738*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_UW_TABLE;
739*0b57cec5SDimitry Andric   case Attribute::WillReturn:
740*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_WILLRETURN;
741*0b57cec5SDimitry Andric   case Attribute::WriteOnly:
742*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_WRITEONLY;
743*0b57cec5SDimitry Andric   case Attribute::ZExt:
744*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_Z_EXT;
745*0b57cec5SDimitry Andric   case Attribute::ImmArg:
746*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_IMMARG;
747*0b57cec5SDimitry Andric   case Attribute::SanitizeMemTag:
748*0b57cec5SDimitry Andric     return bitc::ATTR_KIND_SANITIZE_MEMTAG;
7495ffd83dbSDimitry Andric   case Attribute::Preallocated:
7505ffd83dbSDimitry Andric     return bitc::ATTR_KIND_PREALLOCATED;
7515ffd83dbSDimitry Andric   case Attribute::NoUndef:
7525ffd83dbSDimitry Andric     return bitc::ATTR_KIND_NOUNDEF;
753e8d8bef9SDimitry Andric   case Attribute::ByRef:
754e8d8bef9SDimitry Andric     return bitc::ATTR_KIND_BYREF;
755e8d8bef9SDimitry Andric   case Attribute::MustProgress:
756e8d8bef9SDimitry Andric     return bitc::ATTR_KIND_MUSTPROGRESS;
757*0b57cec5SDimitry Andric   case Attribute::EndAttrKinds:
758*0b57cec5SDimitry Andric     llvm_unreachable("Can not encode end-attribute kinds marker.");
759*0b57cec5SDimitry Andric   case Attribute::None:
760*0b57cec5SDimitry Andric     llvm_unreachable("Can not encode none-attribute.");
7615ffd83dbSDimitry Andric   case Attribute::EmptyKey:
7625ffd83dbSDimitry Andric   case Attribute::TombstoneKey:
7635ffd83dbSDimitry Andric     llvm_unreachable("Trying to encode EmptyKey/TombstoneKey");
764*0b57cec5SDimitry Andric   }
765*0b57cec5SDimitry Andric 
766*0b57cec5SDimitry Andric   llvm_unreachable("Trying to encode unknown attribute");
767*0b57cec5SDimitry Andric }
768*0b57cec5SDimitry Andric 
769*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeAttributeGroupTable() {
770*0b57cec5SDimitry Andric   const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
771*0b57cec5SDimitry Andric       VE.getAttributeGroups();
772*0b57cec5SDimitry Andric   if (AttrGrps.empty()) return;
773*0b57cec5SDimitry Andric 
774*0b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
775*0b57cec5SDimitry Andric 
776*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
777*0b57cec5SDimitry Andric   for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) {
778*0b57cec5SDimitry Andric     unsigned AttrListIndex = Pair.first;
779*0b57cec5SDimitry Andric     AttributeSet AS = Pair.second;
780*0b57cec5SDimitry Andric     Record.push_back(VE.getAttributeGroupID(Pair));
781*0b57cec5SDimitry Andric     Record.push_back(AttrListIndex);
782*0b57cec5SDimitry Andric 
783*0b57cec5SDimitry Andric     for (Attribute Attr : AS) {
784*0b57cec5SDimitry Andric       if (Attr.isEnumAttribute()) {
785*0b57cec5SDimitry Andric         Record.push_back(0);
786*0b57cec5SDimitry Andric         Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
787*0b57cec5SDimitry Andric       } else if (Attr.isIntAttribute()) {
788*0b57cec5SDimitry Andric         Record.push_back(1);
789*0b57cec5SDimitry Andric         Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
790*0b57cec5SDimitry Andric         Record.push_back(Attr.getValueAsInt());
791*0b57cec5SDimitry Andric       } else if (Attr.isStringAttribute()) {
792*0b57cec5SDimitry Andric         StringRef Kind = Attr.getKindAsString();
793*0b57cec5SDimitry Andric         StringRef Val = Attr.getValueAsString();
794*0b57cec5SDimitry Andric 
795*0b57cec5SDimitry Andric         Record.push_back(Val.empty() ? 3 : 4);
796*0b57cec5SDimitry Andric         Record.append(Kind.begin(), Kind.end());
797*0b57cec5SDimitry Andric         Record.push_back(0);
798*0b57cec5SDimitry Andric         if (!Val.empty()) {
799*0b57cec5SDimitry Andric           Record.append(Val.begin(), Val.end());
800*0b57cec5SDimitry Andric           Record.push_back(0);
801*0b57cec5SDimitry Andric         }
802*0b57cec5SDimitry Andric       } else {
803*0b57cec5SDimitry Andric         assert(Attr.isTypeAttribute());
804*0b57cec5SDimitry Andric         Type *Ty = Attr.getValueAsType();
805*0b57cec5SDimitry Andric         Record.push_back(Ty ? 6 : 5);
806*0b57cec5SDimitry Andric         Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
807*0b57cec5SDimitry Andric         if (Ty)
808*0b57cec5SDimitry Andric           Record.push_back(VE.getTypeID(Attr.getValueAsType()));
809*0b57cec5SDimitry Andric       }
810*0b57cec5SDimitry Andric     }
811*0b57cec5SDimitry Andric 
812*0b57cec5SDimitry Andric     Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
813*0b57cec5SDimitry Andric     Record.clear();
814*0b57cec5SDimitry Andric   }
815*0b57cec5SDimitry Andric 
816*0b57cec5SDimitry Andric   Stream.ExitBlock();
817*0b57cec5SDimitry Andric }
818*0b57cec5SDimitry Andric 
819*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeAttributeTable() {
820*0b57cec5SDimitry Andric   const std::vector<AttributeList> &Attrs = VE.getAttributeLists();
821*0b57cec5SDimitry Andric   if (Attrs.empty()) return;
822*0b57cec5SDimitry Andric 
823*0b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
824*0b57cec5SDimitry Andric 
825*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
826*0b57cec5SDimitry Andric   for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
827*0b57cec5SDimitry Andric     AttributeList AL = Attrs[i];
828*0b57cec5SDimitry Andric     for (unsigned i = AL.index_begin(), e = AL.index_end(); i != e; ++i) {
829*0b57cec5SDimitry Andric       AttributeSet AS = AL.getAttributes(i);
830*0b57cec5SDimitry Andric       if (AS.hasAttributes())
831*0b57cec5SDimitry Andric         Record.push_back(VE.getAttributeGroupID({i, AS}));
832*0b57cec5SDimitry Andric     }
833*0b57cec5SDimitry Andric 
834*0b57cec5SDimitry Andric     Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
835*0b57cec5SDimitry Andric     Record.clear();
836*0b57cec5SDimitry Andric   }
837*0b57cec5SDimitry Andric 
838*0b57cec5SDimitry Andric   Stream.ExitBlock();
839*0b57cec5SDimitry Andric }
840*0b57cec5SDimitry Andric 
841*0b57cec5SDimitry Andric /// WriteTypeTable - Write out the type table for a module.
842*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeTypeTable() {
843*0b57cec5SDimitry Andric   const ValueEnumerator::TypeList &TypeList = VE.getTypes();
844*0b57cec5SDimitry Andric 
845*0b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
846*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> TypeVals;
847*0b57cec5SDimitry Andric 
848*0b57cec5SDimitry Andric   uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies();
849*0b57cec5SDimitry Andric 
850*0b57cec5SDimitry Andric   // Abbrev for TYPE_CODE_POINTER.
851*0b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
852*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
853*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
854*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(0));  // Addrspace = 0
855*0b57cec5SDimitry Andric   unsigned PtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
856*0b57cec5SDimitry Andric 
857*0b57cec5SDimitry Andric   // Abbrev for TYPE_CODE_FUNCTION.
858*0b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
859*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
860*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // isvararg
861*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
862*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
863*0b57cec5SDimitry Andric   unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));
864*0b57cec5SDimitry Andric 
865*0b57cec5SDimitry Andric   // Abbrev for TYPE_CODE_STRUCT_ANON.
866*0b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
867*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
868*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
869*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
870*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
871*0b57cec5SDimitry Andric   unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));
872*0b57cec5SDimitry Andric 
873*0b57cec5SDimitry Andric   // Abbrev for TYPE_CODE_STRUCT_NAME.
874*0b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
875*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
876*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
877*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
878*0b57cec5SDimitry Andric   unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
879*0b57cec5SDimitry Andric 
880*0b57cec5SDimitry Andric   // Abbrev for TYPE_CODE_STRUCT_NAMED.
881*0b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
882*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
883*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
884*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
885*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
886*0b57cec5SDimitry Andric   unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));
887*0b57cec5SDimitry Andric 
888*0b57cec5SDimitry Andric   // Abbrev for TYPE_CODE_ARRAY.
889*0b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
890*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
891*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // size
892*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
893*0b57cec5SDimitry Andric   unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));
894*0b57cec5SDimitry Andric 
895*0b57cec5SDimitry Andric   // Emit an entry count so the reader can reserve space.
896*0b57cec5SDimitry Andric   TypeVals.push_back(TypeList.size());
897*0b57cec5SDimitry Andric   Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
898*0b57cec5SDimitry Andric   TypeVals.clear();
899*0b57cec5SDimitry Andric 
900*0b57cec5SDimitry Andric   // Loop over all of the types, emitting each in turn.
901*0b57cec5SDimitry Andric   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
902*0b57cec5SDimitry Andric     Type *T = TypeList[i];
903*0b57cec5SDimitry Andric     int AbbrevToUse = 0;
904*0b57cec5SDimitry Andric     unsigned Code = 0;
905*0b57cec5SDimitry Andric 
906*0b57cec5SDimitry Andric     switch (T->getTypeID()) {
907*0b57cec5SDimitry Andric     case Type::VoidTyID:      Code = bitc::TYPE_CODE_VOID;      break;
908*0b57cec5SDimitry Andric     case Type::HalfTyID:      Code = bitc::TYPE_CODE_HALF;      break;
9095ffd83dbSDimitry Andric     case Type::BFloatTyID:    Code = bitc::TYPE_CODE_BFLOAT;    break;
910*0b57cec5SDimitry Andric     case Type::FloatTyID:     Code = bitc::TYPE_CODE_FLOAT;     break;
911*0b57cec5SDimitry Andric     case Type::DoubleTyID:    Code = bitc::TYPE_CODE_DOUBLE;    break;
912*0b57cec5SDimitry Andric     case Type::X86_FP80TyID:  Code = bitc::TYPE_CODE_X86_FP80;  break;
913*0b57cec5SDimitry Andric     case Type::FP128TyID:     Code = bitc::TYPE_CODE_FP128;     break;
914*0b57cec5SDimitry Andric     case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
915*0b57cec5SDimitry Andric     case Type::LabelTyID:     Code = bitc::TYPE_CODE_LABEL;     break;
916*0b57cec5SDimitry Andric     case Type::MetadataTyID:  Code = bitc::TYPE_CODE_METADATA;  break;
917*0b57cec5SDimitry Andric     case Type::X86_MMXTyID:   Code = bitc::TYPE_CODE_X86_MMX;   break;
918e8d8bef9SDimitry Andric     case Type::X86_AMXTyID:   Code = bitc::TYPE_CODE_X86_AMX;   break;
919*0b57cec5SDimitry Andric     case Type::TokenTyID:     Code = bitc::TYPE_CODE_TOKEN;     break;
920*0b57cec5SDimitry Andric     case Type::IntegerTyID:
921*0b57cec5SDimitry Andric       // INTEGER: [width]
922*0b57cec5SDimitry Andric       Code = bitc::TYPE_CODE_INTEGER;
923*0b57cec5SDimitry Andric       TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
924*0b57cec5SDimitry Andric       break;
925*0b57cec5SDimitry Andric     case Type::PointerTyID: {
926*0b57cec5SDimitry Andric       PointerType *PTy = cast<PointerType>(T);
927*0b57cec5SDimitry Andric       // POINTER: [pointee type, address space]
928*0b57cec5SDimitry Andric       Code = bitc::TYPE_CODE_POINTER;
929*0b57cec5SDimitry Andric       TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
930*0b57cec5SDimitry Andric       unsigned AddressSpace = PTy->getAddressSpace();
931*0b57cec5SDimitry Andric       TypeVals.push_back(AddressSpace);
932*0b57cec5SDimitry Andric       if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
933*0b57cec5SDimitry Andric       break;
934*0b57cec5SDimitry Andric     }
935*0b57cec5SDimitry Andric     case Type::FunctionTyID: {
936*0b57cec5SDimitry Andric       FunctionType *FT = cast<FunctionType>(T);
937*0b57cec5SDimitry Andric       // FUNCTION: [isvararg, retty, paramty x N]
938*0b57cec5SDimitry Andric       Code = bitc::TYPE_CODE_FUNCTION;
939*0b57cec5SDimitry Andric       TypeVals.push_back(FT->isVarArg());
940*0b57cec5SDimitry Andric       TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
941*0b57cec5SDimitry Andric       for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
942*0b57cec5SDimitry Andric         TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
943*0b57cec5SDimitry Andric       AbbrevToUse = FunctionAbbrev;
944*0b57cec5SDimitry Andric       break;
945*0b57cec5SDimitry Andric     }
946*0b57cec5SDimitry Andric     case Type::StructTyID: {
947*0b57cec5SDimitry Andric       StructType *ST = cast<StructType>(T);
948*0b57cec5SDimitry Andric       // STRUCT: [ispacked, eltty x N]
949*0b57cec5SDimitry Andric       TypeVals.push_back(ST->isPacked());
950*0b57cec5SDimitry Andric       // Output all of the element types.
951*0b57cec5SDimitry Andric       for (StructType::element_iterator I = ST->element_begin(),
952*0b57cec5SDimitry Andric            E = ST->element_end(); I != E; ++I)
953*0b57cec5SDimitry Andric         TypeVals.push_back(VE.getTypeID(*I));
954*0b57cec5SDimitry Andric 
955*0b57cec5SDimitry Andric       if (ST->isLiteral()) {
956*0b57cec5SDimitry Andric         Code = bitc::TYPE_CODE_STRUCT_ANON;
957*0b57cec5SDimitry Andric         AbbrevToUse = StructAnonAbbrev;
958*0b57cec5SDimitry Andric       } else {
959*0b57cec5SDimitry Andric         if (ST->isOpaque()) {
960*0b57cec5SDimitry Andric           Code = bitc::TYPE_CODE_OPAQUE;
961*0b57cec5SDimitry Andric         } else {
962*0b57cec5SDimitry Andric           Code = bitc::TYPE_CODE_STRUCT_NAMED;
963*0b57cec5SDimitry Andric           AbbrevToUse = StructNamedAbbrev;
964*0b57cec5SDimitry Andric         }
965*0b57cec5SDimitry Andric 
966*0b57cec5SDimitry Andric         // Emit the name if it is present.
967*0b57cec5SDimitry Andric         if (!ST->getName().empty())
968*0b57cec5SDimitry Andric           writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
969*0b57cec5SDimitry Andric                             StructNameAbbrev);
970*0b57cec5SDimitry Andric       }
971*0b57cec5SDimitry Andric       break;
972*0b57cec5SDimitry Andric     }
973*0b57cec5SDimitry Andric     case Type::ArrayTyID: {
974*0b57cec5SDimitry Andric       ArrayType *AT = cast<ArrayType>(T);
975*0b57cec5SDimitry Andric       // ARRAY: [numelts, eltty]
976*0b57cec5SDimitry Andric       Code = bitc::TYPE_CODE_ARRAY;
977*0b57cec5SDimitry Andric       TypeVals.push_back(AT->getNumElements());
978*0b57cec5SDimitry Andric       TypeVals.push_back(VE.getTypeID(AT->getElementType()));
979*0b57cec5SDimitry Andric       AbbrevToUse = ArrayAbbrev;
980*0b57cec5SDimitry Andric       break;
981*0b57cec5SDimitry Andric     }
9825ffd83dbSDimitry Andric     case Type::FixedVectorTyID:
9835ffd83dbSDimitry Andric     case Type::ScalableVectorTyID: {
984*0b57cec5SDimitry Andric       VectorType *VT = cast<VectorType>(T);
985*0b57cec5SDimitry Andric       // VECTOR [numelts, eltty] or
986*0b57cec5SDimitry Andric       //        [numelts, eltty, scalable]
987*0b57cec5SDimitry Andric       Code = bitc::TYPE_CODE_VECTOR;
988e8d8bef9SDimitry Andric       TypeVals.push_back(VT->getElementCount().getKnownMinValue());
989*0b57cec5SDimitry Andric       TypeVals.push_back(VE.getTypeID(VT->getElementType()));
9905ffd83dbSDimitry Andric       if (isa<ScalableVectorType>(VT))
9915ffd83dbSDimitry Andric         TypeVals.push_back(true);
992*0b57cec5SDimitry Andric       break;
993*0b57cec5SDimitry Andric     }
994*0b57cec5SDimitry Andric     }
995*0b57cec5SDimitry Andric 
996*0b57cec5SDimitry Andric     // Emit the finished record.
997*0b57cec5SDimitry Andric     Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
998*0b57cec5SDimitry Andric     TypeVals.clear();
999*0b57cec5SDimitry Andric   }
1000*0b57cec5SDimitry Andric 
1001*0b57cec5SDimitry Andric   Stream.ExitBlock();
1002*0b57cec5SDimitry Andric }
1003*0b57cec5SDimitry Andric 
1004*0b57cec5SDimitry Andric static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {
1005*0b57cec5SDimitry Andric   switch (Linkage) {
1006*0b57cec5SDimitry Andric   case GlobalValue::ExternalLinkage:
1007*0b57cec5SDimitry Andric     return 0;
1008*0b57cec5SDimitry Andric   case GlobalValue::WeakAnyLinkage:
1009*0b57cec5SDimitry Andric     return 16;
1010*0b57cec5SDimitry Andric   case GlobalValue::AppendingLinkage:
1011*0b57cec5SDimitry Andric     return 2;
1012*0b57cec5SDimitry Andric   case GlobalValue::InternalLinkage:
1013*0b57cec5SDimitry Andric     return 3;
1014*0b57cec5SDimitry Andric   case GlobalValue::LinkOnceAnyLinkage:
1015*0b57cec5SDimitry Andric     return 18;
1016*0b57cec5SDimitry Andric   case GlobalValue::ExternalWeakLinkage:
1017*0b57cec5SDimitry Andric     return 7;
1018*0b57cec5SDimitry Andric   case GlobalValue::CommonLinkage:
1019*0b57cec5SDimitry Andric     return 8;
1020*0b57cec5SDimitry Andric   case GlobalValue::PrivateLinkage:
1021*0b57cec5SDimitry Andric     return 9;
1022*0b57cec5SDimitry Andric   case GlobalValue::WeakODRLinkage:
1023*0b57cec5SDimitry Andric     return 17;
1024*0b57cec5SDimitry Andric   case GlobalValue::LinkOnceODRLinkage:
1025*0b57cec5SDimitry Andric     return 19;
1026*0b57cec5SDimitry Andric   case GlobalValue::AvailableExternallyLinkage:
1027*0b57cec5SDimitry Andric     return 12;
1028*0b57cec5SDimitry Andric   }
1029*0b57cec5SDimitry Andric   llvm_unreachable("Invalid linkage");
1030*0b57cec5SDimitry Andric }
1031*0b57cec5SDimitry Andric 
1032*0b57cec5SDimitry Andric static unsigned getEncodedLinkage(const GlobalValue &GV) {
1033*0b57cec5SDimitry Andric   return getEncodedLinkage(GV.getLinkage());
1034*0b57cec5SDimitry Andric }
1035*0b57cec5SDimitry Andric 
1036*0b57cec5SDimitry Andric static uint64_t getEncodedFFlags(FunctionSummary::FFlags Flags) {
1037*0b57cec5SDimitry Andric   uint64_t RawFlags = 0;
1038*0b57cec5SDimitry Andric   RawFlags |= Flags.ReadNone;
1039*0b57cec5SDimitry Andric   RawFlags |= (Flags.ReadOnly << 1);
1040*0b57cec5SDimitry Andric   RawFlags |= (Flags.NoRecurse << 2);
1041*0b57cec5SDimitry Andric   RawFlags |= (Flags.ReturnDoesNotAlias << 3);
1042*0b57cec5SDimitry Andric   RawFlags |= (Flags.NoInline << 4);
1043480093f4SDimitry Andric   RawFlags |= (Flags.AlwaysInline << 5);
1044*0b57cec5SDimitry Andric   return RawFlags;
1045*0b57cec5SDimitry Andric }
1046*0b57cec5SDimitry Andric 
1047*0b57cec5SDimitry Andric // Decode the flags for GlobalValue in the summary
1048*0b57cec5SDimitry Andric static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags) {
1049*0b57cec5SDimitry Andric   uint64_t RawFlags = 0;
1050*0b57cec5SDimitry Andric 
1051*0b57cec5SDimitry Andric   RawFlags |= Flags.NotEligibleToImport; // bool
1052*0b57cec5SDimitry Andric   RawFlags |= (Flags.Live << 1);
1053*0b57cec5SDimitry Andric   RawFlags |= (Flags.DSOLocal << 2);
1054*0b57cec5SDimitry Andric   RawFlags |= (Flags.CanAutoHide << 3);
1055*0b57cec5SDimitry Andric 
1056*0b57cec5SDimitry Andric   // Linkage don't need to be remapped at that time for the summary. Any future
1057*0b57cec5SDimitry Andric   // change to the getEncodedLinkage() function will need to be taken into
1058*0b57cec5SDimitry Andric   // account here as well.
1059*0b57cec5SDimitry Andric   RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits
1060*0b57cec5SDimitry Andric 
1061*0b57cec5SDimitry Andric   return RawFlags;
1062*0b57cec5SDimitry Andric }
1063*0b57cec5SDimitry Andric 
1064*0b57cec5SDimitry Andric static uint64_t getEncodedGVarFlags(GlobalVarSummary::GVarFlags Flags) {
10655ffd83dbSDimitry Andric   uint64_t RawFlags = Flags.MaybeReadOnly | (Flags.MaybeWriteOnly << 1) |
10665ffd83dbSDimitry Andric                       (Flags.Constant << 2) | Flags.VCallVisibility << 3;
1067*0b57cec5SDimitry Andric   return RawFlags;
1068*0b57cec5SDimitry Andric }
1069*0b57cec5SDimitry Andric 
1070*0b57cec5SDimitry Andric static unsigned getEncodedVisibility(const GlobalValue &GV) {
1071*0b57cec5SDimitry Andric   switch (GV.getVisibility()) {
1072*0b57cec5SDimitry Andric   case GlobalValue::DefaultVisibility:   return 0;
1073*0b57cec5SDimitry Andric   case GlobalValue::HiddenVisibility:    return 1;
1074*0b57cec5SDimitry Andric   case GlobalValue::ProtectedVisibility: return 2;
1075*0b57cec5SDimitry Andric   }
1076*0b57cec5SDimitry Andric   llvm_unreachable("Invalid visibility");
1077*0b57cec5SDimitry Andric }
1078*0b57cec5SDimitry Andric 
1079*0b57cec5SDimitry Andric static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
1080*0b57cec5SDimitry Andric   switch (GV.getDLLStorageClass()) {
1081*0b57cec5SDimitry Andric   case GlobalValue::DefaultStorageClass:   return 0;
1082*0b57cec5SDimitry Andric   case GlobalValue::DLLImportStorageClass: return 1;
1083*0b57cec5SDimitry Andric   case GlobalValue::DLLExportStorageClass: return 2;
1084*0b57cec5SDimitry Andric   }
1085*0b57cec5SDimitry Andric   llvm_unreachable("Invalid DLL storage class");
1086*0b57cec5SDimitry Andric }
1087*0b57cec5SDimitry Andric 
1088*0b57cec5SDimitry Andric static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
1089*0b57cec5SDimitry Andric   switch (GV.getThreadLocalMode()) {
1090*0b57cec5SDimitry Andric     case GlobalVariable::NotThreadLocal:         return 0;
1091*0b57cec5SDimitry Andric     case GlobalVariable::GeneralDynamicTLSModel: return 1;
1092*0b57cec5SDimitry Andric     case GlobalVariable::LocalDynamicTLSModel:   return 2;
1093*0b57cec5SDimitry Andric     case GlobalVariable::InitialExecTLSModel:    return 3;
1094*0b57cec5SDimitry Andric     case GlobalVariable::LocalExecTLSModel:      return 4;
1095*0b57cec5SDimitry Andric   }
1096*0b57cec5SDimitry Andric   llvm_unreachable("Invalid TLS model");
1097*0b57cec5SDimitry Andric }
1098*0b57cec5SDimitry Andric 
1099*0b57cec5SDimitry Andric static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
1100*0b57cec5SDimitry Andric   switch (C.getSelectionKind()) {
1101*0b57cec5SDimitry Andric   case Comdat::Any:
1102*0b57cec5SDimitry Andric     return bitc::COMDAT_SELECTION_KIND_ANY;
1103*0b57cec5SDimitry Andric   case Comdat::ExactMatch:
1104*0b57cec5SDimitry Andric     return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
1105*0b57cec5SDimitry Andric   case Comdat::Largest:
1106*0b57cec5SDimitry Andric     return bitc::COMDAT_SELECTION_KIND_LARGEST;
1107*0b57cec5SDimitry Andric   case Comdat::NoDuplicates:
1108*0b57cec5SDimitry Andric     return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
1109*0b57cec5SDimitry Andric   case Comdat::SameSize:
1110*0b57cec5SDimitry Andric     return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
1111*0b57cec5SDimitry Andric   }
1112*0b57cec5SDimitry Andric   llvm_unreachable("Invalid selection kind");
1113*0b57cec5SDimitry Andric }
1114*0b57cec5SDimitry Andric 
1115*0b57cec5SDimitry Andric static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) {
1116*0b57cec5SDimitry Andric   switch (GV.getUnnamedAddr()) {
1117*0b57cec5SDimitry Andric   case GlobalValue::UnnamedAddr::None:   return 0;
1118*0b57cec5SDimitry Andric   case GlobalValue::UnnamedAddr::Local:  return 2;
1119*0b57cec5SDimitry Andric   case GlobalValue::UnnamedAddr::Global: return 1;
1120*0b57cec5SDimitry Andric   }
1121*0b57cec5SDimitry Andric   llvm_unreachable("Invalid unnamed_addr");
1122*0b57cec5SDimitry Andric }
1123*0b57cec5SDimitry Andric 
1124*0b57cec5SDimitry Andric size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) {
1125*0b57cec5SDimitry Andric   if (GenerateHash)
1126*0b57cec5SDimitry Andric     Hasher.update(Str);
1127*0b57cec5SDimitry Andric   return StrtabBuilder.add(Str);
1128*0b57cec5SDimitry Andric }
1129*0b57cec5SDimitry Andric 
1130*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeComdats() {
1131*0b57cec5SDimitry Andric   SmallVector<unsigned, 64> Vals;
1132*0b57cec5SDimitry Andric   for (const Comdat *C : VE.getComdats()) {
1133*0b57cec5SDimitry Andric     // COMDAT: [strtab offset, strtab size, selection_kind]
1134*0b57cec5SDimitry Andric     Vals.push_back(addToStrtab(C->getName()));
1135*0b57cec5SDimitry Andric     Vals.push_back(C->getName().size());
1136*0b57cec5SDimitry Andric     Vals.push_back(getEncodedComdatSelectionKind(*C));
1137*0b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
1138*0b57cec5SDimitry Andric     Vals.clear();
1139*0b57cec5SDimitry Andric   }
1140*0b57cec5SDimitry Andric }
1141*0b57cec5SDimitry Andric 
1142*0b57cec5SDimitry Andric /// Write a record that will eventually hold the word offset of the
1143*0b57cec5SDimitry Andric /// module-level VST. For now the offset is 0, which will be backpatched
1144*0b57cec5SDimitry Andric /// after the real VST is written. Saves the bit offset to backpatch.
1145*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
1146*0b57cec5SDimitry Andric   // Write a placeholder value in for the offset of the real VST,
1147*0b57cec5SDimitry Andric   // which is written after the function blocks so that it can include
1148*0b57cec5SDimitry Andric   // the offset of each function. The placeholder offset will be
1149*0b57cec5SDimitry Andric   // updated when the real VST is written.
1150*0b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
1151*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET));
1152*0b57cec5SDimitry Andric   // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
1153*0b57cec5SDimitry Andric   // hold the real VST offset. Must use fixed instead of VBR as we don't
1154*0b57cec5SDimitry Andric   // know how many VBR chunks to reserve ahead of time.
1155*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1156*0b57cec5SDimitry Andric   unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1157*0b57cec5SDimitry Andric 
1158*0b57cec5SDimitry Andric   // Emit the placeholder
1159*0b57cec5SDimitry Andric   uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0};
1160*0b57cec5SDimitry Andric   Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
1161*0b57cec5SDimitry Andric 
1162*0b57cec5SDimitry Andric   // Compute and save the bit offset to the placeholder, which will be
1163*0b57cec5SDimitry Andric   // patched when the real VST is written. We can simply subtract the 32-bit
1164*0b57cec5SDimitry Andric   // fixed size from the current bit number to get the location to backpatch.
1165*0b57cec5SDimitry Andric   VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32;
1166*0b57cec5SDimitry Andric }
1167*0b57cec5SDimitry Andric 
1168*0b57cec5SDimitry Andric enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 };
1169*0b57cec5SDimitry Andric 
1170*0b57cec5SDimitry Andric /// Determine the encoding to use for the given string name and length.
1171*0b57cec5SDimitry Andric static StringEncoding getStringEncoding(StringRef Str) {
1172*0b57cec5SDimitry Andric   bool isChar6 = true;
1173*0b57cec5SDimitry Andric   for (char C : Str) {
1174*0b57cec5SDimitry Andric     if (isChar6)
1175*0b57cec5SDimitry Andric       isChar6 = BitCodeAbbrevOp::isChar6(C);
1176*0b57cec5SDimitry Andric     if ((unsigned char)C & 128)
1177*0b57cec5SDimitry Andric       // don't bother scanning the rest.
1178*0b57cec5SDimitry Andric       return SE_Fixed8;
1179*0b57cec5SDimitry Andric   }
1180*0b57cec5SDimitry Andric   if (isChar6)
1181*0b57cec5SDimitry Andric     return SE_Char6;
1182*0b57cec5SDimitry Andric   return SE_Fixed7;
1183*0b57cec5SDimitry Andric }
1184*0b57cec5SDimitry Andric 
1185*0b57cec5SDimitry Andric /// Emit top-level description of module, including target triple, inline asm,
1186*0b57cec5SDimitry Andric /// descriptors for global variables, and function prototype info.
1187*0b57cec5SDimitry Andric /// Returns the bit offset to backpatch with the location of the real VST.
1188*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeModuleInfo() {
1189*0b57cec5SDimitry Andric   // Emit various pieces of data attached to a module.
1190*0b57cec5SDimitry Andric   if (!M.getTargetTriple().empty())
1191*0b57cec5SDimitry Andric     writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(),
1192*0b57cec5SDimitry Andric                       0 /*TODO*/);
1193*0b57cec5SDimitry Andric   const std::string &DL = M.getDataLayoutStr();
1194*0b57cec5SDimitry Andric   if (!DL.empty())
1195*0b57cec5SDimitry Andric     writeStringRecord(Stream, bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/);
1196*0b57cec5SDimitry Andric   if (!M.getModuleInlineAsm().empty())
1197*0b57cec5SDimitry Andric     writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(),
1198*0b57cec5SDimitry Andric                       0 /*TODO*/);
1199*0b57cec5SDimitry Andric 
1200*0b57cec5SDimitry Andric   // Emit information about sections and GC, computing how many there are. Also
1201*0b57cec5SDimitry Andric   // compute the maximum alignment value.
1202*0b57cec5SDimitry Andric   std::map<std::string, unsigned> SectionMap;
1203*0b57cec5SDimitry Andric   std::map<std::string, unsigned> GCMap;
1204e8d8bef9SDimitry Andric   MaybeAlign MaxAlignment;
1205*0b57cec5SDimitry Andric   unsigned MaxGlobalType = 0;
1206e8d8bef9SDimitry Andric   const auto UpdateMaxAlignment = [&MaxAlignment](const MaybeAlign A) {
1207e8d8bef9SDimitry Andric     if (A)
1208e8d8bef9SDimitry Andric       MaxAlignment = !MaxAlignment ? *A : std::max(*MaxAlignment, *A);
1209e8d8bef9SDimitry Andric   };
12105ffd83dbSDimitry Andric   for (const GlobalVariable &GV : M.globals()) {
1211e8d8bef9SDimitry Andric     UpdateMaxAlignment(GV.getAlign());
1212*0b57cec5SDimitry Andric     MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
1213*0b57cec5SDimitry Andric     if (GV.hasSection()) {
1214*0b57cec5SDimitry Andric       // Give section names unique ID's.
12155ffd83dbSDimitry Andric       unsigned &Entry = SectionMap[std::string(GV.getSection())];
1216*0b57cec5SDimitry Andric       if (!Entry) {
1217*0b57cec5SDimitry Andric         writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
1218*0b57cec5SDimitry Andric                           0 /*TODO*/);
1219*0b57cec5SDimitry Andric         Entry = SectionMap.size();
1220*0b57cec5SDimitry Andric       }
1221*0b57cec5SDimitry Andric     }
1222*0b57cec5SDimitry Andric   }
1223*0b57cec5SDimitry Andric   for (const Function &F : M) {
1224e8d8bef9SDimitry Andric     UpdateMaxAlignment(F.getAlign());
1225*0b57cec5SDimitry Andric     if (F.hasSection()) {
1226*0b57cec5SDimitry Andric       // Give section names unique ID's.
12275ffd83dbSDimitry Andric       unsigned &Entry = SectionMap[std::string(F.getSection())];
1228*0b57cec5SDimitry Andric       if (!Entry) {
1229*0b57cec5SDimitry Andric         writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
1230*0b57cec5SDimitry Andric                           0 /*TODO*/);
1231*0b57cec5SDimitry Andric         Entry = SectionMap.size();
1232*0b57cec5SDimitry Andric       }
1233*0b57cec5SDimitry Andric     }
1234*0b57cec5SDimitry Andric     if (F.hasGC()) {
1235*0b57cec5SDimitry Andric       // Same for GC names.
1236*0b57cec5SDimitry Andric       unsigned &Entry = GCMap[F.getGC()];
1237*0b57cec5SDimitry Andric       if (!Entry) {
1238*0b57cec5SDimitry Andric         writeStringRecord(Stream, bitc::MODULE_CODE_GCNAME, F.getGC(),
1239*0b57cec5SDimitry Andric                           0 /*TODO*/);
1240*0b57cec5SDimitry Andric         Entry = GCMap.size();
1241*0b57cec5SDimitry Andric       }
1242*0b57cec5SDimitry Andric     }
1243*0b57cec5SDimitry Andric   }
1244*0b57cec5SDimitry Andric 
1245*0b57cec5SDimitry Andric   // Emit abbrev for globals, now that we know # sections and max alignment.
1246*0b57cec5SDimitry Andric   unsigned SimpleGVarAbbrev = 0;
1247*0b57cec5SDimitry Andric   if (!M.global_empty()) {
1248*0b57cec5SDimitry Andric     // Add an abbrev for common globals with no visibility or thread localness.
1249*0b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
1250*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
1251*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1252*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1253*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1254*0b57cec5SDimitry Andric                               Log2_32_Ceil(MaxGlobalType+1)));
1255*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // AddrSpace << 2
1256*0b57cec5SDimitry Andric                                                            //| explicitType << 1
1257*0b57cec5SDimitry Andric                                                            //| constant
1258*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // Initializer.
1259*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
1260e8d8bef9SDimitry Andric     if (!MaxAlignment)                                     // Alignment.
1261*0b57cec5SDimitry Andric       Abbv->Add(BitCodeAbbrevOp(0));
1262*0b57cec5SDimitry Andric     else {
1263e8d8bef9SDimitry Andric       unsigned MaxEncAlignment = getEncodedAlign(MaxAlignment);
1264*0b57cec5SDimitry Andric       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1265*0b57cec5SDimitry Andric                                Log2_32_Ceil(MaxEncAlignment+1)));
1266*0b57cec5SDimitry Andric     }
1267*0b57cec5SDimitry Andric     if (SectionMap.empty())                                    // Section.
1268*0b57cec5SDimitry Andric       Abbv->Add(BitCodeAbbrevOp(0));
1269*0b57cec5SDimitry Andric     else
1270*0b57cec5SDimitry Andric       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1271*0b57cec5SDimitry Andric                                Log2_32_Ceil(SectionMap.size()+1)));
1272*0b57cec5SDimitry Andric     // Don't bother emitting vis + thread local.
1273*0b57cec5SDimitry Andric     SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1274*0b57cec5SDimitry Andric   }
1275*0b57cec5SDimitry Andric 
1276*0b57cec5SDimitry Andric   SmallVector<unsigned, 64> Vals;
1277*0b57cec5SDimitry Andric   // Emit the module's source file name.
1278*0b57cec5SDimitry Andric   {
1279*0b57cec5SDimitry Andric     StringEncoding Bits = getStringEncoding(M.getSourceFileName());
1280*0b57cec5SDimitry Andric     BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
1281*0b57cec5SDimitry Andric     if (Bits == SE_Char6)
1282*0b57cec5SDimitry Andric       AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
1283*0b57cec5SDimitry Andric     else if (Bits == SE_Fixed7)
1284*0b57cec5SDimitry Andric       AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
1285*0b57cec5SDimitry Andric 
1286*0b57cec5SDimitry Andric     // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
1287*0b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
1288*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
1289*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1290*0b57cec5SDimitry Andric     Abbv->Add(AbbrevOpToUse);
1291*0b57cec5SDimitry Andric     unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1292*0b57cec5SDimitry Andric 
1293*0b57cec5SDimitry Andric     for (const auto P : M.getSourceFileName())
1294*0b57cec5SDimitry Andric       Vals.push_back((unsigned char)P);
1295*0b57cec5SDimitry Andric 
1296*0b57cec5SDimitry Andric     // Emit the finished record.
1297*0b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
1298*0b57cec5SDimitry Andric     Vals.clear();
1299*0b57cec5SDimitry Andric   }
1300*0b57cec5SDimitry Andric 
1301*0b57cec5SDimitry Andric   // Emit the global variable information.
1302*0b57cec5SDimitry Andric   for (const GlobalVariable &GV : M.globals()) {
1303*0b57cec5SDimitry Andric     unsigned AbbrevToUse = 0;
1304*0b57cec5SDimitry Andric 
1305*0b57cec5SDimitry Andric     // GLOBALVAR: [strtab offset, strtab size, type, isconst, initid,
1306*0b57cec5SDimitry Andric     //             linkage, alignment, section, visibility, threadlocal,
1307*0b57cec5SDimitry Andric     //             unnamed_addr, externally_initialized, dllstorageclass,
1308*0b57cec5SDimitry Andric     //             comdat, attributes, DSO_Local]
1309*0b57cec5SDimitry Andric     Vals.push_back(addToStrtab(GV.getName()));
1310*0b57cec5SDimitry Andric     Vals.push_back(GV.getName().size());
1311*0b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(GV.getValueType()));
1312*0b57cec5SDimitry Andric     Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
1313*0b57cec5SDimitry Andric     Vals.push_back(GV.isDeclaration() ? 0 :
1314*0b57cec5SDimitry Andric                    (VE.getValueID(GV.getInitializer()) + 1));
1315*0b57cec5SDimitry Andric     Vals.push_back(getEncodedLinkage(GV));
1316e8d8bef9SDimitry Andric     Vals.push_back(getEncodedAlign(GV.getAlign()));
13175ffd83dbSDimitry Andric     Vals.push_back(GV.hasSection() ? SectionMap[std::string(GV.getSection())]
13185ffd83dbSDimitry Andric                                    : 0);
1319*0b57cec5SDimitry Andric     if (GV.isThreadLocal() ||
1320*0b57cec5SDimitry Andric         GV.getVisibility() != GlobalValue::DefaultVisibility ||
1321*0b57cec5SDimitry Andric         GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1322*0b57cec5SDimitry Andric         GV.isExternallyInitialized() ||
1323*0b57cec5SDimitry Andric         GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
1324*0b57cec5SDimitry Andric         GV.hasComdat() ||
1325*0b57cec5SDimitry Andric         GV.hasAttributes() ||
1326*0b57cec5SDimitry Andric         GV.isDSOLocal() ||
1327*0b57cec5SDimitry Andric         GV.hasPartition()) {
1328*0b57cec5SDimitry Andric       Vals.push_back(getEncodedVisibility(GV));
1329*0b57cec5SDimitry Andric       Vals.push_back(getEncodedThreadLocalMode(GV));
1330*0b57cec5SDimitry Andric       Vals.push_back(getEncodedUnnamedAddr(GV));
1331*0b57cec5SDimitry Andric       Vals.push_back(GV.isExternallyInitialized());
1332*0b57cec5SDimitry Andric       Vals.push_back(getEncodedDLLStorageClass(GV));
1333*0b57cec5SDimitry Andric       Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
1334*0b57cec5SDimitry Andric 
1335*0b57cec5SDimitry Andric       auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
1336*0b57cec5SDimitry Andric       Vals.push_back(VE.getAttributeListID(AL));
1337*0b57cec5SDimitry Andric 
1338*0b57cec5SDimitry Andric       Vals.push_back(GV.isDSOLocal());
1339*0b57cec5SDimitry Andric       Vals.push_back(addToStrtab(GV.getPartition()));
1340*0b57cec5SDimitry Andric       Vals.push_back(GV.getPartition().size());
1341*0b57cec5SDimitry Andric     } else {
1342*0b57cec5SDimitry Andric       AbbrevToUse = SimpleGVarAbbrev;
1343*0b57cec5SDimitry Andric     }
1344*0b57cec5SDimitry Andric 
1345*0b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
1346*0b57cec5SDimitry Andric     Vals.clear();
1347*0b57cec5SDimitry Andric   }
1348*0b57cec5SDimitry Andric 
1349*0b57cec5SDimitry Andric   // Emit the function proto information.
1350*0b57cec5SDimitry Andric   for (const Function &F : M) {
1351*0b57cec5SDimitry Andric     // FUNCTION:  [strtab offset, strtab size, type, callingconv, isproto,
1352*0b57cec5SDimitry Andric     //             linkage, paramattrs, alignment, section, visibility, gc,
1353*0b57cec5SDimitry Andric     //             unnamed_addr, prologuedata, dllstorageclass, comdat,
1354*0b57cec5SDimitry Andric     //             prefixdata, personalityfn, DSO_Local, addrspace]
1355*0b57cec5SDimitry Andric     Vals.push_back(addToStrtab(F.getName()));
1356*0b57cec5SDimitry Andric     Vals.push_back(F.getName().size());
1357*0b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(F.getFunctionType()));
1358*0b57cec5SDimitry Andric     Vals.push_back(F.getCallingConv());
1359*0b57cec5SDimitry Andric     Vals.push_back(F.isDeclaration());
1360*0b57cec5SDimitry Andric     Vals.push_back(getEncodedLinkage(F));
1361*0b57cec5SDimitry Andric     Vals.push_back(VE.getAttributeListID(F.getAttributes()));
1362e8d8bef9SDimitry Andric     Vals.push_back(getEncodedAlign(F.getAlign()));
13635ffd83dbSDimitry Andric     Vals.push_back(F.hasSection() ? SectionMap[std::string(F.getSection())]
13645ffd83dbSDimitry Andric                                   : 0);
1365*0b57cec5SDimitry Andric     Vals.push_back(getEncodedVisibility(F));
1366*0b57cec5SDimitry Andric     Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
1367*0b57cec5SDimitry Andric     Vals.push_back(getEncodedUnnamedAddr(F));
1368*0b57cec5SDimitry Andric     Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
1369*0b57cec5SDimitry Andric                                        : 0);
1370*0b57cec5SDimitry Andric     Vals.push_back(getEncodedDLLStorageClass(F));
1371*0b57cec5SDimitry Andric     Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
1372*0b57cec5SDimitry Andric     Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
1373*0b57cec5SDimitry Andric                                      : 0);
1374*0b57cec5SDimitry Andric     Vals.push_back(
1375*0b57cec5SDimitry Andric         F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
1376*0b57cec5SDimitry Andric 
1377*0b57cec5SDimitry Andric     Vals.push_back(F.isDSOLocal());
1378*0b57cec5SDimitry Andric     Vals.push_back(F.getAddressSpace());
1379*0b57cec5SDimitry Andric     Vals.push_back(addToStrtab(F.getPartition()));
1380*0b57cec5SDimitry Andric     Vals.push_back(F.getPartition().size());
1381*0b57cec5SDimitry Andric 
1382*0b57cec5SDimitry Andric     unsigned AbbrevToUse = 0;
1383*0b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
1384*0b57cec5SDimitry Andric     Vals.clear();
1385*0b57cec5SDimitry Andric   }
1386*0b57cec5SDimitry Andric 
1387*0b57cec5SDimitry Andric   // Emit the alias information.
1388*0b57cec5SDimitry Andric   for (const GlobalAlias &A : M.aliases()) {
1389*0b57cec5SDimitry Andric     // ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage,
1390*0b57cec5SDimitry Andric     //         visibility, dllstorageclass, threadlocal, unnamed_addr,
1391*0b57cec5SDimitry Andric     //         DSO_Local]
1392*0b57cec5SDimitry Andric     Vals.push_back(addToStrtab(A.getName()));
1393*0b57cec5SDimitry Andric     Vals.push_back(A.getName().size());
1394*0b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(A.getValueType()));
1395*0b57cec5SDimitry Andric     Vals.push_back(A.getType()->getAddressSpace());
1396*0b57cec5SDimitry Andric     Vals.push_back(VE.getValueID(A.getAliasee()));
1397*0b57cec5SDimitry Andric     Vals.push_back(getEncodedLinkage(A));
1398*0b57cec5SDimitry Andric     Vals.push_back(getEncodedVisibility(A));
1399*0b57cec5SDimitry Andric     Vals.push_back(getEncodedDLLStorageClass(A));
1400*0b57cec5SDimitry Andric     Vals.push_back(getEncodedThreadLocalMode(A));
1401*0b57cec5SDimitry Andric     Vals.push_back(getEncodedUnnamedAddr(A));
1402*0b57cec5SDimitry Andric     Vals.push_back(A.isDSOLocal());
1403*0b57cec5SDimitry Andric     Vals.push_back(addToStrtab(A.getPartition()));
1404*0b57cec5SDimitry Andric     Vals.push_back(A.getPartition().size());
1405*0b57cec5SDimitry Andric 
1406*0b57cec5SDimitry Andric     unsigned AbbrevToUse = 0;
1407*0b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
1408*0b57cec5SDimitry Andric     Vals.clear();
1409*0b57cec5SDimitry Andric   }
1410*0b57cec5SDimitry Andric 
1411*0b57cec5SDimitry Andric   // Emit the ifunc information.
1412*0b57cec5SDimitry Andric   for (const GlobalIFunc &I : M.ifuncs()) {
1413*0b57cec5SDimitry Andric     // IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver
1414*0b57cec5SDimitry Andric     //         val#, linkage, visibility, DSO_Local]
1415*0b57cec5SDimitry Andric     Vals.push_back(addToStrtab(I.getName()));
1416*0b57cec5SDimitry Andric     Vals.push_back(I.getName().size());
1417*0b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(I.getValueType()));
1418*0b57cec5SDimitry Andric     Vals.push_back(I.getType()->getAddressSpace());
1419*0b57cec5SDimitry Andric     Vals.push_back(VE.getValueID(I.getResolver()));
1420*0b57cec5SDimitry Andric     Vals.push_back(getEncodedLinkage(I));
1421*0b57cec5SDimitry Andric     Vals.push_back(getEncodedVisibility(I));
1422*0b57cec5SDimitry Andric     Vals.push_back(I.isDSOLocal());
1423*0b57cec5SDimitry Andric     Vals.push_back(addToStrtab(I.getPartition()));
1424*0b57cec5SDimitry Andric     Vals.push_back(I.getPartition().size());
1425*0b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
1426*0b57cec5SDimitry Andric     Vals.clear();
1427*0b57cec5SDimitry Andric   }
1428*0b57cec5SDimitry Andric 
1429*0b57cec5SDimitry Andric   writeValueSymbolTableForwardDecl();
1430*0b57cec5SDimitry Andric }
1431*0b57cec5SDimitry Andric 
1432*0b57cec5SDimitry Andric static uint64_t getOptimizationFlags(const Value *V) {
1433*0b57cec5SDimitry Andric   uint64_t Flags = 0;
1434*0b57cec5SDimitry Andric 
1435*0b57cec5SDimitry Andric   if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
1436*0b57cec5SDimitry Andric     if (OBO->hasNoSignedWrap())
1437*0b57cec5SDimitry Andric       Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
1438*0b57cec5SDimitry Andric     if (OBO->hasNoUnsignedWrap())
1439*0b57cec5SDimitry Andric       Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
1440*0b57cec5SDimitry Andric   } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
1441*0b57cec5SDimitry Andric     if (PEO->isExact())
1442*0b57cec5SDimitry Andric       Flags |= 1 << bitc::PEO_EXACT;
1443*0b57cec5SDimitry Andric   } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
1444*0b57cec5SDimitry Andric     if (FPMO->hasAllowReassoc())
1445*0b57cec5SDimitry Andric       Flags |= bitc::AllowReassoc;
1446*0b57cec5SDimitry Andric     if (FPMO->hasNoNaNs())
1447*0b57cec5SDimitry Andric       Flags |= bitc::NoNaNs;
1448*0b57cec5SDimitry Andric     if (FPMO->hasNoInfs())
1449*0b57cec5SDimitry Andric       Flags |= bitc::NoInfs;
1450*0b57cec5SDimitry Andric     if (FPMO->hasNoSignedZeros())
1451*0b57cec5SDimitry Andric       Flags |= bitc::NoSignedZeros;
1452*0b57cec5SDimitry Andric     if (FPMO->hasAllowReciprocal())
1453*0b57cec5SDimitry Andric       Flags |= bitc::AllowReciprocal;
1454*0b57cec5SDimitry Andric     if (FPMO->hasAllowContract())
1455*0b57cec5SDimitry Andric       Flags |= bitc::AllowContract;
1456*0b57cec5SDimitry Andric     if (FPMO->hasApproxFunc())
1457*0b57cec5SDimitry Andric       Flags |= bitc::ApproxFunc;
1458*0b57cec5SDimitry Andric   }
1459*0b57cec5SDimitry Andric 
1460*0b57cec5SDimitry Andric   return Flags;
1461*0b57cec5SDimitry Andric }
1462*0b57cec5SDimitry Andric 
1463*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeValueAsMetadata(
1464*0b57cec5SDimitry Andric     const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
1465*0b57cec5SDimitry Andric   // Mimic an MDNode with a value as one operand.
1466*0b57cec5SDimitry Andric   Value *V = MD->getValue();
1467*0b57cec5SDimitry Andric   Record.push_back(VE.getTypeID(V->getType()));
1468*0b57cec5SDimitry Andric   Record.push_back(VE.getValueID(V));
1469*0b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
1470*0b57cec5SDimitry Andric   Record.clear();
1471*0b57cec5SDimitry Andric }
1472*0b57cec5SDimitry Andric 
1473*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N,
1474*0b57cec5SDimitry Andric                                        SmallVectorImpl<uint64_t> &Record,
1475*0b57cec5SDimitry Andric                                        unsigned Abbrev) {
1476*0b57cec5SDimitry Andric   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1477*0b57cec5SDimitry Andric     Metadata *MD = N->getOperand(i);
1478*0b57cec5SDimitry Andric     assert(!(MD && isa<LocalAsMetadata>(MD)) &&
1479*0b57cec5SDimitry Andric            "Unexpected function-local metadata");
1480*0b57cec5SDimitry Andric     Record.push_back(VE.getMetadataOrNullID(MD));
1481*0b57cec5SDimitry Andric   }
1482*0b57cec5SDimitry Andric   Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
1483*0b57cec5SDimitry Andric                                     : bitc::METADATA_NODE,
1484*0b57cec5SDimitry Andric                     Record, Abbrev);
1485*0b57cec5SDimitry Andric   Record.clear();
1486*0b57cec5SDimitry Andric }
1487*0b57cec5SDimitry Andric 
1488*0b57cec5SDimitry Andric unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
1489*0b57cec5SDimitry Andric   // Assume the column is usually under 128, and always output the inlined-at
1490*0b57cec5SDimitry Andric   // location (it's never more expensive than building an array size 1).
1491*0b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
1492*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
1493*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1494*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1495*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1496*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1497*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1498*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1499*0b57cec5SDimitry Andric   return Stream.EmitAbbrev(std::move(Abbv));
1500*0b57cec5SDimitry Andric }
1501*0b57cec5SDimitry Andric 
1502*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDILocation(const DILocation *N,
1503*0b57cec5SDimitry Andric                                           SmallVectorImpl<uint64_t> &Record,
1504*0b57cec5SDimitry Andric                                           unsigned &Abbrev) {
1505*0b57cec5SDimitry Andric   if (!Abbrev)
1506*0b57cec5SDimitry Andric     Abbrev = createDILocationAbbrev();
1507*0b57cec5SDimitry Andric 
1508*0b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
1509*0b57cec5SDimitry Andric   Record.push_back(N->getLine());
1510*0b57cec5SDimitry Andric   Record.push_back(N->getColumn());
1511*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataID(N->getScope()));
1512*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
1513*0b57cec5SDimitry Andric   Record.push_back(N->isImplicitCode());
1514*0b57cec5SDimitry Andric 
1515*0b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
1516*0b57cec5SDimitry Andric   Record.clear();
1517*0b57cec5SDimitry Andric }
1518*0b57cec5SDimitry Andric 
1519*0b57cec5SDimitry Andric unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
1520*0b57cec5SDimitry Andric   // Assume the column is usually under 128, and always output the inlined-at
1521*0b57cec5SDimitry Andric   // location (it's never more expensive than building an array size 1).
1522*0b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
1523*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
1524*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1525*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1526*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1527*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1528*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1529*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1530*0b57cec5SDimitry Andric   return Stream.EmitAbbrev(std::move(Abbv));
1531*0b57cec5SDimitry Andric }
1532*0b57cec5SDimitry Andric 
1533*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N,
1534*0b57cec5SDimitry Andric                                              SmallVectorImpl<uint64_t> &Record,
1535*0b57cec5SDimitry Andric                                              unsigned &Abbrev) {
1536*0b57cec5SDimitry Andric   if (!Abbrev)
1537*0b57cec5SDimitry Andric     Abbrev = createGenericDINodeAbbrev();
1538*0b57cec5SDimitry Andric 
1539*0b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
1540*0b57cec5SDimitry Andric   Record.push_back(N->getTag());
1541*0b57cec5SDimitry Andric   Record.push_back(0); // Per-tag version field; unused for now.
1542*0b57cec5SDimitry Andric 
1543*0b57cec5SDimitry Andric   for (auto &I : N->operands())
1544*0b57cec5SDimitry Andric     Record.push_back(VE.getMetadataOrNullID(I));
1545*0b57cec5SDimitry Andric 
1546*0b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
1547*0b57cec5SDimitry Andric   Record.clear();
1548*0b57cec5SDimitry Andric }
1549*0b57cec5SDimitry Andric 
1550*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N,
1551*0b57cec5SDimitry Andric                                           SmallVectorImpl<uint64_t> &Record,
1552*0b57cec5SDimitry Andric                                           unsigned Abbrev) {
15535ffd83dbSDimitry Andric   const uint64_t Version = 2 << 1;
1554*0b57cec5SDimitry Andric   Record.push_back((uint64_t)N->isDistinct() | Version);
1555*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
15565ffd83dbSDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
15575ffd83dbSDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
15585ffd83dbSDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
1559*0b57cec5SDimitry Andric 
1560*0b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
1561*0b57cec5SDimitry Andric   Record.clear();
1562*0b57cec5SDimitry Andric }
1563*0b57cec5SDimitry Andric 
1564e8d8bef9SDimitry Andric void ModuleBitcodeWriter::writeDIGenericSubrange(
1565e8d8bef9SDimitry Andric     const DIGenericSubrange *N, SmallVectorImpl<uint64_t> &Record,
1566e8d8bef9SDimitry Andric     unsigned Abbrev) {
1567e8d8bef9SDimitry Andric   Record.push_back((uint64_t)N->isDistinct());
1568e8d8bef9SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
1569e8d8bef9SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
1570e8d8bef9SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
1571e8d8bef9SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
1572e8d8bef9SDimitry Andric 
1573e8d8bef9SDimitry Andric   Stream.EmitRecord(bitc::METADATA_GENERIC_SUBRANGE, Record, Abbrev);
1574e8d8bef9SDimitry Andric   Record.clear();
1575e8d8bef9SDimitry Andric }
1576e8d8bef9SDimitry Andric 
15775ffd83dbSDimitry Andric static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
15785ffd83dbSDimitry Andric   if ((int64_t)V >= 0)
15795ffd83dbSDimitry Andric     Vals.push_back(V << 1);
15805ffd83dbSDimitry Andric   else
15815ffd83dbSDimitry Andric     Vals.push_back((-V << 1) | 1);
15825ffd83dbSDimitry Andric }
15835ffd83dbSDimitry Andric 
15845ffd83dbSDimitry Andric static void emitWideAPInt(SmallVectorImpl<uint64_t> &Vals, const APInt &A) {
15855ffd83dbSDimitry Andric   // We have an arbitrary precision integer value to write whose
15865ffd83dbSDimitry Andric   // bit width is > 64. However, in canonical unsigned integer
15875ffd83dbSDimitry Andric   // format it is likely that the high bits are going to be zero.
15885ffd83dbSDimitry Andric   // So, we only write the number of active words.
15895ffd83dbSDimitry Andric   unsigned NumWords = A.getActiveWords();
15905ffd83dbSDimitry Andric   const uint64_t *RawData = A.getRawData();
15915ffd83dbSDimitry Andric   for (unsigned i = 0; i < NumWords; i++)
15925ffd83dbSDimitry Andric     emitSignedInt64(Vals, RawData[i]);
15935ffd83dbSDimitry Andric }
15945ffd83dbSDimitry Andric 
1595*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,
1596*0b57cec5SDimitry Andric                                             SmallVectorImpl<uint64_t> &Record,
1597*0b57cec5SDimitry Andric                                             unsigned Abbrev) {
15985ffd83dbSDimitry Andric   const uint64_t IsBigInt = 1 << 2;
15995ffd83dbSDimitry Andric   Record.push_back(IsBigInt | (N->isUnsigned() << 1) | N->isDistinct());
16005ffd83dbSDimitry Andric   Record.push_back(N->getValue().getBitWidth());
1601*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
16025ffd83dbSDimitry Andric   emitWideAPInt(Record, N->getValue());
1603*0b57cec5SDimitry Andric 
1604*0b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
1605*0b57cec5SDimitry Andric   Record.clear();
1606*0b57cec5SDimitry Andric }
1607*0b57cec5SDimitry Andric 
1608*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N,
1609*0b57cec5SDimitry Andric                                            SmallVectorImpl<uint64_t> &Record,
1610*0b57cec5SDimitry Andric                                            unsigned Abbrev) {
1611*0b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
1612*0b57cec5SDimitry Andric   Record.push_back(N->getTag());
1613*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1614*0b57cec5SDimitry Andric   Record.push_back(N->getSizeInBits());
1615*0b57cec5SDimitry Andric   Record.push_back(N->getAlignInBits());
1616*0b57cec5SDimitry Andric   Record.push_back(N->getEncoding());
1617*0b57cec5SDimitry Andric   Record.push_back(N->getFlags());
1618*0b57cec5SDimitry Andric 
1619*0b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
1620*0b57cec5SDimitry Andric   Record.clear();
1621*0b57cec5SDimitry Andric }
1622*0b57cec5SDimitry Andric 
1623e8d8bef9SDimitry Andric void ModuleBitcodeWriter::writeDIStringType(const DIStringType *N,
1624e8d8bef9SDimitry Andric                                             SmallVectorImpl<uint64_t> &Record,
1625e8d8bef9SDimitry Andric                                             unsigned Abbrev) {
1626e8d8bef9SDimitry Andric   Record.push_back(N->isDistinct());
1627e8d8bef9SDimitry Andric   Record.push_back(N->getTag());
1628e8d8bef9SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1629e8d8bef9SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getStringLength()));
1630e8d8bef9SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getStringLengthExp()));
1631e8d8bef9SDimitry Andric   Record.push_back(N->getSizeInBits());
1632e8d8bef9SDimitry Andric   Record.push_back(N->getAlignInBits());
1633e8d8bef9SDimitry Andric   Record.push_back(N->getEncoding());
1634e8d8bef9SDimitry Andric 
1635e8d8bef9SDimitry Andric   Stream.EmitRecord(bitc::METADATA_STRING_TYPE, Record, Abbrev);
1636e8d8bef9SDimitry Andric   Record.clear();
1637e8d8bef9SDimitry Andric }
1638e8d8bef9SDimitry Andric 
1639*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,
1640*0b57cec5SDimitry Andric                                              SmallVectorImpl<uint64_t> &Record,
1641*0b57cec5SDimitry Andric                                              unsigned Abbrev) {
1642*0b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
1643*0b57cec5SDimitry Andric   Record.push_back(N->getTag());
1644*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1645*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1646*0b57cec5SDimitry Andric   Record.push_back(N->getLine());
1647*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1648*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1649*0b57cec5SDimitry Andric   Record.push_back(N->getSizeInBits());
1650*0b57cec5SDimitry Andric   Record.push_back(N->getAlignInBits());
1651*0b57cec5SDimitry Andric   Record.push_back(N->getOffsetInBits());
1652*0b57cec5SDimitry Andric   Record.push_back(N->getFlags());
1653*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
1654*0b57cec5SDimitry Andric 
1655*0b57cec5SDimitry Andric   // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
1656*0b57cec5SDimitry Andric   // that there is no DWARF address space associated with DIDerivedType.
1657*0b57cec5SDimitry Andric   if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
1658*0b57cec5SDimitry Andric     Record.push_back(*DWARFAddressSpace + 1);
1659*0b57cec5SDimitry Andric   else
1660*0b57cec5SDimitry Andric     Record.push_back(0);
1661*0b57cec5SDimitry Andric 
1662*0b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
1663*0b57cec5SDimitry Andric   Record.clear();
1664*0b57cec5SDimitry Andric }
1665*0b57cec5SDimitry Andric 
1666*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDICompositeType(
1667*0b57cec5SDimitry Andric     const DICompositeType *N, SmallVectorImpl<uint64_t> &Record,
1668*0b57cec5SDimitry Andric     unsigned Abbrev) {
1669*0b57cec5SDimitry Andric   const unsigned IsNotUsedInOldTypeRef = 0x2;
1670*0b57cec5SDimitry Andric   Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct());
1671*0b57cec5SDimitry Andric   Record.push_back(N->getTag());
1672*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1673*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1674*0b57cec5SDimitry Andric   Record.push_back(N->getLine());
1675*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1676*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1677*0b57cec5SDimitry Andric   Record.push_back(N->getSizeInBits());
1678*0b57cec5SDimitry Andric   Record.push_back(N->getAlignInBits());
1679*0b57cec5SDimitry Andric   Record.push_back(N->getOffsetInBits());
1680*0b57cec5SDimitry Andric   Record.push_back(N->getFlags());
1681*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1682*0b57cec5SDimitry Andric   Record.push_back(N->getRuntimeLang());
1683*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
1684*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1685*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
1686*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getDiscriminator()));
16875ffd83dbSDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawDataLocation()));
1688e8d8bef9SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawAssociated()));
1689e8d8bef9SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawAllocated()));
1690e8d8bef9SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawRank()));
1691*0b57cec5SDimitry Andric 
1692*0b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
1693*0b57cec5SDimitry Andric   Record.clear();
1694*0b57cec5SDimitry Andric }
1695*0b57cec5SDimitry Andric 
1696*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDISubroutineType(
1697*0b57cec5SDimitry Andric     const DISubroutineType *N, SmallVectorImpl<uint64_t> &Record,
1698*0b57cec5SDimitry Andric     unsigned Abbrev) {
1699*0b57cec5SDimitry Andric   const unsigned HasNoOldTypeRefs = 0x2;
1700*0b57cec5SDimitry Andric   Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
1701*0b57cec5SDimitry Andric   Record.push_back(N->getFlags());
1702*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
1703*0b57cec5SDimitry Andric   Record.push_back(N->getCC());
1704*0b57cec5SDimitry Andric 
1705*0b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
1706*0b57cec5SDimitry Andric   Record.clear();
1707*0b57cec5SDimitry Andric }
1708*0b57cec5SDimitry Andric 
1709*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIFile(const DIFile *N,
1710*0b57cec5SDimitry Andric                                       SmallVectorImpl<uint64_t> &Record,
1711*0b57cec5SDimitry Andric                                       unsigned Abbrev) {
1712*0b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
1713*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
1714*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
1715*0b57cec5SDimitry Andric   if (N->getRawChecksum()) {
1716*0b57cec5SDimitry Andric     Record.push_back(N->getRawChecksum()->Kind);
1717*0b57cec5SDimitry Andric     Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()->Value));
1718*0b57cec5SDimitry Andric   } else {
1719*0b57cec5SDimitry Andric     // Maintain backwards compatibility with the old internal representation of
1720*0b57cec5SDimitry Andric     // CSK_None in ChecksumKind by writing nulls here when Checksum is None.
1721*0b57cec5SDimitry Andric     Record.push_back(0);
1722*0b57cec5SDimitry Andric     Record.push_back(VE.getMetadataOrNullID(nullptr));
1723*0b57cec5SDimitry Andric   }
1724*0b57cec5SDimitry Andric   auto Source = N->getRawSource();
1725*0b57cec5SDimitry Andric   if (Source)
1726*0b57cec5SDimitry Andric     Record.push_back(VE.getMetadataOrNullID(*Source));
1727*0b57cec5SDimitry Andric 
1728*0b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
1729*0b57cec5SDimitry Andric   Record.clear();
1730*0b57cec5SDimitry Andric }
1731*0b57cec5SDimitry Andric 
1732*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
1733*0b57cec5SDimitry Andric                                              SmallVectorImpl<uint64_t> &Record,
1734*0b57cec5SDimitry Andric                                              unsigned Abbrev) {
1735*0b57cec5SDimitry Andric   assert(N->isDistinct() && "Expected distinct compile units");
1736*0b57cec5SDimitry Andric   Record.push_back(/* IsDistinct */ true);
1737*0b57cec5SDimitry Andric   Record.push_back(N->getSourceLanguage());
1738*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1739*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
1740*0b57cec5SDimitry Andric   Record.push_back(N->isOptimized());
1741*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
1742*0b57cec5SDimitry Andric   Record.push_back(N->getRuntimeVersion());
1743*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
1744*0b57cec5SDimitry Andric   Record.push_back(N->getEmissionKind());
1745*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
1746*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
1747*0b57cec5SDimitry Andric   Record.push_back(/* subprograms */ 0);
1748*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
1749*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
1750*0b57cec5SDimitry Andric   Record.push_back(N->getDWOId());
1751*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
1752*0b57cec5SDimitry Andric   Record.push_back(N->getSplitDebugInlining());
1753*0b57cec5SDimitry Andric   Record.push_back(N->getDebugInfoForProfiling());
1754*0b57cec5SDimitry Andric   Record.push_back((unsigned)N->getNameTableKind());
17555ffd83dbSDimitry Andric   Record.push_back(N->getRangesBaseAddress());
17565ffd83dbSDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawSysRoot()));
17575ffd83dbSDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawSDK()));
1758*0b57cec5SDimitry Andric 
1759*0b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
1760*0b57cec5SDimitry Andric   Record.clear();
1761*0b57cec5SDimitry Andric }
1762*0b57cec5SDimitry Andric 
1763*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,
1764*0b57cec5SDimitry Andric                                             SmallVectorImpl<uint64_t> &Record,
1765*0b57cec5SDimitry Andric                                             unsigned Abbrev) {
1766*0b57cec5SDimitry Andric   const uint64_t HasUnitFlag = 1 << 1;
1767*0b57cec5SDimitry Andric   const uint64_t HasSPFlagsFlag = 1 << 2;
1768*0b57cec5SDimitry Andric   Record.push_back(uint64_t(N->isDistinct()) | HasUnitFlag | HasSPFlagsFlag);
1769*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1770*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1771*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1772*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1773*0b57cec5SDimitry Andric   Record.push_back(N->getLine());
1774*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1775*0b57cec5SDimitry Andric   Record.push_back(N->getScopeLine());
1776*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
1777*0b57cec5SDimitry Andric   Record.push_back(N->getSPFlags());
1778*0b57cec5SDimitry Andric   Record.push_back(N->getVirtualIndex());
1779*0b57cec5SDimitry Andric   Record.push_back(N->getFlags());
1780*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
1781*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1782*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
1783*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRetainedNodes().get()));
1784*0b57cec5SDimitry Andric   Record.push_back(N->getThisAdjustment());
1785*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get()));
1786*0b57cec5SDimitry Andric 
1787*0b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
1788*0b57cec5SDimitry Andric   Record.clear();
1789*0b57cec5SDimitry Andric }
1790*0b57cec5SDimitry Andric 
1791*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
1792*0b57cec5SDimitry Andric                                               SmallVectorImpl<uint64_t> &Record,
1793*0b57cec5SDimitry Andric                                               unsigned Abbrev) {
1794*0b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
1795*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1796*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1797*0b57cec5SDimitry Andric   Record.push_back(N->getLine());
1798*0b57cec5SDimitry Andric   Record.push_back(N->getColumn());
1799*0b57cec5SDimitry Andric 
1800*0b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
1801*0b57cec5SDimitry Andric   Record.clear();
1802*0b57cec5SDimitry Andric }
1803*0b57cec5SDimitry Andric 
1804*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDILexicalBlockFile(
1805*0b57cec5SDimitry Andric     const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record,
1806*0b57cec5SDimitry Andric     unsigned Abbrev) {
1807*0b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
1808*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1809*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1810*0b57cec5SDimitry Andric   Record.push_back(N->getDiscriminator());
1811*0b57cec5SDimitry Andric 
1812*0b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
1813*0b57cec5SDimitry Andric   Record.clear();
1814*0b57cec5SDimitry Andric }
1815*0b57cec5SDimitry Andric 
1816*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDICommonBlock(const DICommonBlock *N,
1817*0b57cec5SDimitry Andric                                              SmallVectorImpl<uint64_t> &Record,
1818*0b57cec5SDimitry Andric                                              unsigned Abbrev) {
1819*0b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
1820*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1821*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getDecl()));
1822*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1823*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1824*0b57cec5SDimitry Andric   Record.push_back(N->getLineNo());
1825*0b57cec5SDimitry Andric 
1826*0b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_COMMON_BLOCK, Record, Abbrev);
1827*0b57cec5SDimitry Andric   Record.clear();
1828*0b57cec5SDimitry Andric }
1829*0b57cec5SDimitry Andric 
1830*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,
1831*0b57cec5SDimitry Andric                                            SmallVectorImpl<uint64_t> &Record,
1832*0b57cec5SDimitry Andric                                            unsigned Abbrev) {
1833*0b57cec5SDimitry Andric   Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
1834*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1835*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1836*0b57cec5SDimitry Andric 
1837*0b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
1838*0b57cec5SDimitry Andric   Record.clear();
1839*0b57cec5SDimitry Andric }
1840*0b57cec5SDimitry Andric 
1841*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,
1842*0b57cec5SDimitry Andric                                        SmallVectorImpl<uint64_t> &Record,
1843*0b57cec5SDimitry Andric                                        unsigned Abbrev) {
1844*0b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
1845*0b57cec5SDimitry Andric   Record.push_back(N->getMacinfoType());
1846*0b57cec5SDimitry Andric   Record.push_back(N->getLine());
1847*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1848*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
1849*0b57cec5SDimitry Andric 
1850*0b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
1851*0b57cec5SDimitry Andric   Record.clear();
1852*0b57cec5SDimitry Andric }
1853*0b57cec5SDimitry Andric 
1854*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,
1855*0b57cec5SDimitry Andric                                            SmallVectorImpl<uint64_t> &Record,
1856*0b57cec5SDimitry Andric                                            unsigned Abbrev) {
1857*0b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
1858*0b57cec5SDimitry Andric   Record.push_back(N->getMacinfoType());
1859*0b57cec5SDimitry Andric   Record.push_back(N->getLine());
1860*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1861*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1862*0b57cec5SDimitry Andric 
1863*0b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
1864*0b57cec5SDimitry Andric   Record.clear();
1865*0b57cec5SDimitry Andric }
1866*0b57cec5SDimitry Andric 
1867*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIModule(const DIModule *N,
1868*0b57cec5SDimitry Andric                                         SmallVectorImpl<uint64_t> &Record,
1869*0b57cec5SDimitry Andric                                         unsigned Abbrev) {
1870*0b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
1871*0b57cec5SDimitry Andric   for (auto &I : N->operands())
1872*0b57cec5SDimitry Andric     Record.push_back(VE.getMetadataOrNullID(I));
18735ffd83dbSDimitry Andric   Record.push_back(N->getLineNo());
1874e8d8bef9SDimitry Andric   Record.push_back(N->getIsDecl());
1875*0b57cec5SDimitry Andric 
1876*0b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
1877*0b57cec5SDimitry Andric   Record.clear();
1878*0b57cec5SDimitry Andric }
1879*0b57cec5SDimitry Andric 
1880*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDITemplateTypeParameter(
1881*0b57cec5SDimitry Andric     const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record,
1882*0b57cec5SDimitry Andric     unsigned Abbrev) {
1883*0b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
1884*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1885*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getType()));
18865ffd83dbSDimitry Andric   Record.push_back(N->isDefault());
1887*0b57cec5SDimitry Andric 
1888*0b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
1889*0b57cec5SDimitry Andric   Record.clear();
1890*0b57cec5SDimitry Andric }
1891*0b57cec5SDimitry Andric 
1892*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDITemplateValueParameter(
1893*0b57cec5SDimitry Andric     const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record,
1894*0b57cec5SDimitry Andric     unsigned Abbrev) {
1895*0b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
1896*0b57cec5SDimitry Andric   Record.push_back(N->getTag());
1897*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1898*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getType()));
18995ffd83dbSDimitry Andric   Record.push_back(N->isDefault());
1900*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getValue()));
1901*0b57cec5SDimitry Andric 
1902*0b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
1903*0b57cec5SDimitry Andric   Record.clear();
1904*0b57cec5SDimitry Andric }
1905*0b57cec5SDimitry Andric 
1906*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIGlobalVariable(
1907*0b57cec5SDimitry Andric     const DIGlobalVariable *N, SmallVectorImpl<uint64_t> &Record,
1908*0b57cec5SDimitry Andric     unsigned Abbrev) {
1909*0b57cec5SDimitry Andric   const uint64_t Version = 2 << 1;
1910*0b57cec5SDimitry Andric   Record.push_back((uint64_t)N->isDistinct() | Version);
1911*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1912*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1913*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1914*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1915*0b57cec5SDimitry Andric   Record.push_back(N->getLine());
1916*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1917*0b57cec5SDimitry Andric   Record.push_back(N->isLocalToUnit());
1918*0b57cec5SDimitry Andric   Record.push_back(N->isDefinition());
1919*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
1920*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams()));
1921*0b57cec5SDimitry Andric   Record.push_back(N->getAlignInBits());
1922*0b57cec5SDimitry Andric 
1923*0b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
1924*0b57cec5SDimitry Andric   Record.clear();
1925*0b57cec5SDimitry Andric }
1926*0b57cec5SDimitry Andric 
1927*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDILocalVariable(
1928*0b57cec5SDimitry Andric     const DILocalVariable *N, SmallVectorImpl<uint64_t> &Record,
1929*0b57cec5SDimitry Andric     unsigned Abbrev) {
1930*0b57cec5SDimitry Andric   // In order to support all possible bitcode formats in BitcodeReader we need
1931*0b57cec5SDimitry Andric   // to distinguish the following cases:
1932*0b57cec5SDimitry Andric   // 1) Record has no artificial tag (Record[1]),
1933*0b57cec5SDimitry Andric   //   has no obsolete inlinedAt field (Record[9]).
1934*0b57cec5SDimitry Andric   //   In this case Record size will be 8, HasAlignment flag is false.
1935*0b57cec5SDimitry Andric   // 2) Record has artificial tag (Record[1]),
1936*0b57cec5SDimitry Andric   //   has no obsolete inlignedAt field (Record[9]).
1937*0b57cec5SDimitry Andric   //   In this case Record size will be 9, HasAlignment flag is false.
1938*0b57cec5SDimitry Andric   // 3) Record has both artificial tag (Record[1]) and
1939*0b57cec5SDimitry Andric   //   obsolete inlignedAt field (Record[9]).
1940*0b57cec5SDimitry Andric   //   In this case Record size will be 10, HasAlignment flag is false.
1941*0b57cec5SDimitry Andric   // 4) Record has neither artificial tag, nor inlignedAt field, but
1942*0b57cec5SDimitry Andric   //   HasAlignment flag is true and Record[8] contains alignment value.
1943*0b57cec5SDimitry Andric   const uint64_t HasAlignmentFlag = 1 << 1;
1944*0b57cec5SDimitry Andric   Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
1945*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1946*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1947*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1948*0b57cec5SDimitry Andric   Record.push_back(N->getLine());
1949*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1950*0b57cec5SDimitry Andric   Record.push_back(N->getArg());
1951*0b57cec5SDimitry Andric   Record.push_back(N->getFlags());
1952*0b57cec5SDimitry Andric   Record.push_back(N->getAlignInBits());
1953*0b57cec5SDimitry Andric 
1954*0b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
1955*0b57cec5SDimitry Andric   Record.clear();
1956*0b57cec5SDimitry Andric }
1957*0b57cec5SDimitry Andric 
1958*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDILabel(
1959*0b57cec5SDimitry Andric     const DILabel *N, SmallVectorImpl<uint64_t> &Record,
1960*0b57cec5SDimitry Andric     unsigned Abbrev) {
1961*0b57cec5SDimitry Andric   Record.push_back((uint64_t)N->isDistinct());
1962*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1963*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1964*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1965*0b57cec5SDimitry Andric   Record.push_back(N->getLine());
1966*0b57cec5SDimitry Andric 
1967*0b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_LABEL, Record, Abbrev);
1968*0b57cec5SDimitry Andric   Record.clear();
1969*0b57cec5SDimitry Andric }
1970*0b57cec5SDimitry Andric 
1971*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,
1972*0b57cec5SDimitry Andric                                             SmallVectorImpl<uint64_t> &Record,
1973*0b57cec5SDimitry Andric                                             unsigned Abbrev) {
1974*0b57cec5SDimitry Andric   Record.reserve(N->getElements().size() + 1);
1975*0b57cec5SDimitry Andric   const uint64_t Version = 3 << 1;
1976*0b57cec5SDimitry Andric   Record.push_back((uint64_t)N->isDistinct() | Version);
1977*0b57cec5SDimitry Andric   Record.append(N->elements_begin(), N->elements_end());
1978*0b57cec5SDimitry Andric 
1979*0b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
1980*0b57cec5SDimitry Andric   Record.clear();
1981*0b57cec5SDimitry Andric }
1982*0b57cec5SDimitry Andric 
1983*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
1984*0b57cec5SDimitry Andric     const DIGlobalVariableExpression *N, SmallVectorImpl<uint64_t> &Record,
1985*0b57cec5SDimitry Andric     unsigned Abbrev) {
1986*0b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
1987*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
1988*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
1989*0b57cec5SDimitry Andric 
1990*0b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR, Record, Abbrev);
1991*0b57cec5SDimitry Andric   Record.clear();
1992*0b57cec5SDimitry Andric }
1993*0b57cec5SDimitry Andric 
1994*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
1995*0b57cec5SDimitry Andric                                               SmallVectorImpl<uint64_t> &Record,
1996*0b57cec5SDimitry Andric                                               unsigned Abbrev) {
1997*0b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
1998*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1999*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2000*0b57cec5SDimitry Andric   Record.push_back(N->getLine());
2001*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
2002*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
2003*0b57cec5SDimitry Andric   Record.push_back(N->getAttributes());
2004*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getType()));
2005*0b57cec5SDimitry Andric 
2006*0b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
2007*0b57cec5SDimitry Andric   Record.clear();
2008*0b57cec5SDimitry Andric }
2009*0b57cec5SDimitry Andric 
2010*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIImportedEntity(
2011*0b57cec5SDimitry Andric     const DIImportedEntity *N, SmallVectorImpl<uint64_t> &Record,
2012*0b57cec5SDimitry Andric     unsigned Abbrev) {
2013*0b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
2014*0b57cec5SDimitry Andric   Record.push_back(N->getTag());
2015*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2016*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
2017*0b57cec5SDimitry Andric   Record.push_back(N->getLine());
2018*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2019*0b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawFile()));
2020*0b57cec5SDimitry Andric 
2021*0b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
2022*0b57cec5SDimitry Andric   Record.clear();
2023*0b57cec5SDimitry Andric }
2024*0b57cec5SDimitry Andric 
2025*0b57cec5SDimitry Andric unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
2026*0b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
2027*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
2028*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2029*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2030*0b57cec5SDimitry Andric   return Stream.EmitAbbrev(std::move(Abbv));
2031*0b57cec5SDimitry Andric }
2032*0b57cec5SDimitry Andric 
2033*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeNamedMetadata(
2034*0b57cec5SDimitry Andric     SmallVectorImpl<uint64_t> &Record) {
2035*0b57cec5SDimitry Andric   if (M.named_metadata_empty())
2036*0b57cec5SDimitry Andric     return;
2037*0b57cec5SDimitry Andric 
2038*0b57cec5SDimitry Andric   unsigned Abbrev = createNamedMetadataAbbrev();
2039*0b57cec5SDimitry Andric   for (const NamedMDNode &NMD : M.named_metadata()) {
2040*0b57cec5SDimitry Andric     // Write name.
2041*0b57cec5SDimitry Andric     StringRef Str = NMD.getName();
2042*0b57cec5SDimitry Andric     Record.append(Str.bytes_begin(), Str.bytes_end());
2043*0b57cec5SDimitry Andric     Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
2044*0b57cec5SDimitry Andric     Record.clear();
2045*0b57cec5SDimitry Andric 
2046*0b57cec5SDimitry Andric     // Write named metadata operands.
2047*0b57cec5SDimitry Andric     for (const MDNode *N : NMD.operands())
2048*0b57cec5SDimitry Andric       Record.push_back(VE.getMetadataID(N));
2049*0b57cec5SDimitry Andric     Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
2050*0b57cec5SDimitry Andric     Record.clear();
2051*0b57cec5SDimitry Andric   }
2052*0b57cec5SDimitry Andric }
2053*0b57cec5SDimitry Andric 
2054*0b57cec5SDimitry Andric unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
2055*0b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
2056*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS));
2057*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
2058*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
2059*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2060*0b57cec5SDimitry Andric   return Stream.EmitAbbrev(std::move(Abbv));
2061*0b57cec5SDimitry Andric }
2062*0b57cec5SDimitry Andric 
2063*0b57cec5SDimitry Andric /// Write out a record for MDString.
2064*0b57cec5SDimitry Andric ///
2065*0b57cec5SDimitry Andric /// All the metadata strings in a metadata block are emitted in a single
2066*0b57cec5SDimitry Andric /// record.  The sizes and strings themselves are shoved into a blob.
2067*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeMetadataStrings(
2068*0b57cec5SDimitry Andric     ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) {
2069*0b57cec5SDimitry Andric   if (Strings.empty())
2070*0b57cec5SDimitry Andric     return;
2071*0b57cec5SDimitry Andric 
2072*0b57cec5SDimitry Andric   // Start the record with the number of strings.
2073*0b57cec5SDimitry Andric   Record.push_back(bitc::METADATA_STRINGS);
2074*0b57cec5SDimitry Andric   Record.push_back(Strings.size());
2075*0b57cec5SDimitry Andric 
2076*0b57cec5SDimitry Andric   // Emit the sizes of the strings in the blob.
2077*0b57cec5SDimitry Andric   SmallString<256> Blob;
2078*0b57cec5SDimitry Andric   {
2079*0b57cec5SDimitry Andric     BitstreamWriter W(Blob);
2080*0b57cec5SDimitry Andric     for (const Metadata *MD : Strings)
2081*0b57cec5SDimitry Andric       W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
2082*0b57cec5SDimitry Andric     W.FlushToWord();
2083*0b57cec5SDimitry Andric   }
2084*0b57cec5SDimitry Andric 
2085*0b57cec5SDimitry Andric   // Add the offset to the strings to the record.
2086*0b57cec5SDimitry Andric   Record.push_back(Blob.size());
2087*0b57cec5SDimitry Andric 
2088*0b57cec5SDimitry Andric   // Add the strings to the blob.
2089*0b57cec5SDimitry Andric   for (const Metadata *MD : Strings)
2090*0b57cec5SDimitry Andric     Blob.append(cast<MDString>(MD)->getString());
2091*0b57cec5SDimitry Andric 
2092*0b57cec5SDimitry Andric   // Emit the final record.
2093*0b57cec5SDimitry Andric   Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
2094*0b57cec5SDimitry Andric   Record.clear();
2095*0b57cec5SDimitry Andric }
2096*0b57cec5SDimitry Andric 
2097*0b57cec5SDimitry Andric // Generates an enum to use as an index in the Abbrev array of Metadata record.
2098*0b57cec5SDimitry Andric enum MetadataAbbrev : unsigned {
2099*0b57cec5SDimitry Andric #define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
2100*0b57cec5SDimitry Andric #include "llvm/IR/Metadata.def"
2101*0b57cec5SDimitry Andric   LastPlusOne
2102*0b57cec5SDimitry Andric };
2103*0b57cec5SDimitry Andric 
2104*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeMetadataRecords(
2105*0b57cec5SDimitry Andric     ArrayRef<const Metadata *> MDs, SmallVectorImpl<uint64_t> &Record,
2106*0b57cec5SDimitry Andric     std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
2107*0b57cec5SDimitry Andric   if (MDs.empty())
2108*0b57cec5SDimitry Andric     return;
2109*0b57cec5SDimitry Andric 
2110*0b57cec5SDimitry Andric   // Initialize MDNode abbreviations.
2111*0b57cec5SDimitry Andric #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
2112*0b57cec5SDimitry Andric #include "llvm/IR/Metadata.def"
2113*0b57cec5SDimitry Andric 
2114*0b57cec5SDimitry Andric   for (const Metadata *MD : MDs) {
2115*0b57cec5SDimitry Andric     if (IndexPos)
2116*0b57cec5SDimitry Andric       IndexPos->push_back(Stream.GetCurrentBitNo());
2117*0b57cec5SDimitry Andric     if (const MDNode *N = dyn_cast<MDNode>(MD)) {
2118*0b57cec5SDimitry Andric       assert(N->isResolved() && "Expected forward references to be resolved");
2119*0b57cec5SDimitry Andric 
2120*0b57cec5SDimitry Andric       switch (N->getMetadataID()) {
2121*0b57cec5SDimitry Andric       default:
2122*0b57cec5SDimitry Andric         llvm_unreachable("Invalid MDNode subclass");
2123*0b57cec5SDimitry Andric #define HANDLE_MDNODE_LEAF(CLASS)                                              \
2124*0b57cec5SDimitry Andric   case Metadata::CLASS##Kind:                                                  \
2125*0b57cec5SDimitry Andric     if (MDAbbrevs)                                                             \
2126*0b57cec5SDimitry Andric       write##CLASS(cast<CLASS>(N), Record,                                     \
2127*0b57cec5SDimitry Andric                    (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]);             \
2128*0b57cec5SDimitry Andric     else                                                                       \
2129*0b57cec5SDimitry Andric       write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev);                     \
2130*0b57cec5SDimitry Andric     continue;
2131*0b57cec5SDimitry Andric #include "llvm/IR/Metadata.def"
2132*0b57cec5SDimitry Andric       }
2133*0b57cec5SDimitry Andric     }
2134*0b57cec5SDimitry Andric     writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
2135*0b57cec5SDimitry Andric   }
2136*0b57cec5SDimitry Andric }
2137*0b57cec5SDimitry Andric 
2138*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeModuleMetadata() {
2139*0b57cec5SDimitry Andric   if (!VE.hasMDs() && M.named_metadata_empty())
2140*0b57cec5SDimitry Andric     return;
2141*0b57cec5SDimitry Andric 
2142*0b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 4);
2143*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
2144*0b57cec5SDimitry Andric 
2145*0b57cec5SDimitry Andric   // Emit all abbrevs upfront, so that the reader can jump in the middle of the
2146*0b57cec5SDimitry Andric   // block and load any metadata.
2147*0b57cec5SDimitry Andric   std::vector<unsigned> MDAbbrevs;
2148*0b57cec5SDimitry Andric 
2149*0b57cec5SDimitry Andric   MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
2150*0b57cec5SDimitry Andric   MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
2151*0b57cec5SDimitry Andric   MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
2152*0b57cec5SDimitry Andric       createGenericDINodeAbbrev();
2153*0b57cec5SDimitry Andric 
2154*0b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
2155*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX_OFFSET));
2156*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2157*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2158*0b57cec5SDimitry Andric   unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2159*0b57cec5SDimitry Andric 
2160*0b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
2161*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX));
2162*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2163*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2164*0b57cec5SDimitry Andric   unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2165*0b57cec5SDimitry Andric 
2166*0b57cec5SDimitry Andric   // Emit MDStrings together upfront.
2167*0b57cec5SDimitry Andric   writeMetadataStrings(VE.getMDStrings(), Record);
2168*0b57cec5SDimitry Andric 
2169*0b57cec5SDimitry Andric   // We only emit an index for the metadata record if we have more than a given
2170*0b57cec5SDimitry Andric   // (naive) threshold of metadatas, otherwise it is not worth it.
2171*0b57cec5SDimitry Andric   if (VE.getNonMDStrings().size() > IndexThreshold) {
2172*0b57cec5SDimitry Andric     // Write a placeholder value in for the offset of the metadata index,
2173*0b57cec5SDimitry Andric     // which is written after the records, so that it can include
2174*0b57cec5SDimitry Andric     // the offset of each entry. The placeholder offset will be
2175*0b57cec5SDimitry Andric     // updated after all records are emitted.
2176*0b57cec5SDimitry Andric     uint64_t Vals[] = {0, 0};
2177*0b57cec5SDimitry Andric     Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
2178*0b57cec5SDimitry Andric   }
2179*0b57cec5SDimitry Andric 
2180*0b57cec5SDimitry Andric   // Compute and save the bit offset to the current position, which will be
2181*0b57cec5SDimitry Andric   // patched when we emit the index later. We can simply subtract the 64-bit
2182*0b57cec5SDimitry Andric   // fixed size from the current bit number to get the location to backpatch.
2183*0b57cec5SDimitry Andric   uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
2184*0b57cec5SDimitry Andric 
2185*0b57cec5SDimitry Andric   // This index will contain the bitpos for each individual record.
2186*0b57cec5SDimitry Andric   std::vector<uint64_t> IndexPos;
2187*0b57cec5SDimitry Andric   IndexPos.reserve(VE.getNonMDStrings().size());
2188*0b57cec5SDimitry Andric 
2189*0b57cec5SDimitry Andric   // Write all the records
2190*0b57cec5SDimitry Andric   writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
2191*0b57cec5SDimitry Andric 
2192*0b57cec5SDimitry Andric   if (VE.getNonMDStrings().size() > IndexThreshold) {
2193*0b57cec5SDimitry Andric     // Now that we have emitted all the records we will emit the index. But
2194*0b57cec5SDimitry Andric     // first
2195*0b57cec5SDimitry Andric     // backpatch the forward reference so that the reader can skip the records
2196*0b57cec5SDimitry Andric     // efficiently.
2197*0b57cec5SDimitry Andric     Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
2198*0b57cec5SDimitry Andric                            Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
2199*0b57cec5SDimitry Andric 
2200*0b57cec5SDimitry Andric     // Delta encode the index.
2201*0b57cec5SDimitry Andric     uint64_t PreviousValue = IndexOffsetRecordBitPos;
2202*0b57cec5SDimitry Andric     for (auto &Elt : IndexPos) {
2203*0b57cec5SDimitry Andric       auto EltDelta = Elt - PreviousValue;
2204*0b57cec5SDimitry Andric       PreviousValue = Elt;
2205*0b57cec5SDimitry Andric       Elt = EltDelta;
2206*0b57cec5SDimitry Andric     }
2207*0b57cec5SDimitry Andric     // Emit the index record.
2208*0b57cec5SDimitry Andric     Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
2209*0b57cec5SDimitry Andric     IndexPos.clear();
2210*0b57cec5SDimitry Andric   }
2211*0b57cec5SDimitry Andric 
2212*0b57cec5SDimitry Andric   // Write the named metadata now.
2213*0b57cec5SDimitry Andric   writeNamedMetadata(Record);
2214*0b57cec5SDimitry Andric 
2215*0b57cec5SDimitry Andric   auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
2216*0b57cec5SDimitry Andric     SmallVector<uint64_t, 4> Record;
2217*0b57cec5SDimitry Andric     Record.push_back(VE.getValueID(&GO));
2218*0b57cec5SDimitry Andric     pushGlobalMetadataAttachment(Record, GO);
2219*0b57cec5SDimitry Andric     Stream.EmitRecord(bitc::METADATA_GLOBAL_DECL_ATTACHMENT, Record);
2220*0b57cec5SDimitry Andric   };
2221*0b57cec5SDimitry Andric   for (const Function &F : M)
2222*0b57cec5SDimitry Andric     if (F.isDeclaration() && F.hasMetadata())
2223*0b57cec5SDimitry Andric       AddDeclAttachedMetadata(F);
2224*0b57cec5SDimitry Andric   // FIXME: Only store metadata for declarations here, and move data for global
2225*0b57cec5SDimitry Andric   // variable definitions to a separate block (PR28134).
2226*0b57cec5SDimitry Andric   for (const GlobalVariable &GV : M.globals())
2227*0b57cec5SDimitry Andric     if (GV.hasMetadata())
2228*0b57cec5SDimitry Andric       AddDeclAttachedMetadata(GV);
2229*0b57cec5SDimitry Andric 
2230*0b57cec5SDimitry Andric   Stream.ExitBlock();
2231*0b57cec5SDimitry Andric }
2232*0b57cec5SDimitry Andric 
2233*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
2234*0b57cec5SDimitry Andric   if (!VE.hasMDs())
2235*0b57cec5SDimitry Andric     return;
2236*0b57cec5SDimitry Andric 
2237*0b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
2238*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
2239*0b57cec5SDimitry Andric   writeMetadataStrings(VE.getMDStrings(), Record);
2240*0b57cec5SDimitry Andric   writeMetadataRecords(VE.getNonMDStrings(), Record);
2241*0b57cec5SDimitry Andric   Stream.ExitBlock();
2242*0b57cec5SDimitry Andric }
2243*0b57cec5SDimitry Andric 
2244*0b57cec5SDimitry Andric void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
2245*0b57cec5SDimitry Andric     SmallVectorImpl<uint64_t> &Record, const GlobalObject &GO) {
2246*0b57cec5SDimitry Andric   // [n x [id, mdnode]]
2247*0b57cec5SDimitry Andric   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2248*0b57cec5SDimitry Andric   GO.getAllMetadata(MDs);
2249*0b57cec5SDimitry Andric   for (const auto &I : MDs) {
2250*0b57cec5SDimitry Andric     Record.push_back(I.first);
2251*0b57cec5SDimitry Andric     Record.push_back(VE.getMetadataID(I.second));
2252*0b57cec5SDimitry Andric   }
2253*0b57cec5SDimitry Andric }
2254*0b57cec5SDimitry Andric 
2255*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
2256*0b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
2257*0b57cec5SDimitry Andric 
2258*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
2259*0b57cec5SDimitry Andric 
2260*0b57cec5SDimitry Andric   if (F.hasMetadata()) {
2261*0b57cec5SDimitry Andric     pushGlobalMetadataAttachment(Record, F);
2262*0b57cec5SDimitry Andric     Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
2263*0b57cec5SDimitry Andric     Record.clear();
2264*0b57cec5SDimitry Andric   }
2265*0b57cec5SDimitry Andric 
2266*0b57cec5SDimitry Andric   // Write metadata attachments
2267*0b57cec5SDimitry Andric   // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
2268*0b57cec5SDimitry Andric   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2269*0b57cec5SDimitry Andric   for (const BasicBlock &BB : F)
2270*0b57cec5SDimitry Andric     for (const Instruction &I : BB) {
2271*0b57cec5SDimitry Andric       MDs.clear();
2272*0b57cec5SDimitry Andric       I.getAllMetadataOtherThanDebugLoc(MDs);
2273*0b57cec5SDimitry Andric 
2274*0b57cec5SDimitry Andric       // If no metadata, ignore instruction.
2275*0b57cec5SDimitry Andric       if (MDs.empty()) continue;
2276*0b57cec5SDimitry Andric 
2277*0b57cec5SDimitry Andric       Record.push_back(VE.getInstructionID(&I));
2278*0b57cec5SDimitry Andric 
2279*0b57cec5SDimitry Andric       for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
2280*0b57cec5SDimitry Andric         Record.push_back(MDs[i].first);
2281*0b57cec5SDimitry Andric         Record.push_back(VE.getMetadataID(MDs[i].second));
2282*0b57cec5SDimitry Andric       }
2283*0b57cec5SDimitry Andric       Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
2284*0b57cec5SDimitry Andric       Record.clear();
2285*0b57cec5SDimitry Andric     }
2286*0b57cec5SDimitry Andric 
2287*0b57cec5SDimitry Andric   Stream.ExitBlock();
2288*0b57cec5SDimitry Andric }
2289*0b57cec5SDimitry Andric 
2290*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeModuleMetadataKinds() {
2291*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
2292*0b57cec5SDimitry Andric 
2293*0b57cec5SDimitry Andric   // Write metadata kinds
2294*0b57cec5SDimitry Andric   // METADATA_KIND - [n x [id, name]]
2295*0b57cec5SDimitry Andric   SmallVector<StringRef, 8> Names;
2296*0b57cec5SDimitry Andric   M.getMDKindNames(Names);
2297*0b57cec5SDimitry Andric 
2298*0b57cec5SDimitry Andric   if (Names.empty()) return;
2299*0b57cec5SDimitry Andric 
2300*0b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3);
2301*0b57cec5SDimitry Andric 
2302*0b57cec5SDimitry Andric   for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
2303*0b57cec5SDimitry Andric     Record.push_back(MDKindID);
2304*0b57cec5SDimitry Andric     StringRef KName = Names[MDKindID];
2305*0b57cec5SDimitry Andric     Record.append(KName.begin(), KName.end());
2306*0b57cec5SDimitry Andric 
2307*0b57cec5SDimitry Andric     Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
2308*0b57cec5SDimitry Andric     Record.clear();
2309*0b57cec5SDimitry Andric   }
2310*0b57cec5SDimitry Andric 
2311*0b57cec5SDimitry Andric   Stream.ExitBlock();
2312*0b57cec5SDimitry Andric }
2313*0b57cec5SDimitry Andric 
2314*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeOperandBundleTags() {
2315*0b57cec5SDimitry Andric   // Write metadata kinds
2316*0b57cec5SDimitry Andric   //
2317*0b57cec5SDimitry Andric   // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
2318*0b57cec5SDimitry Andric   //
2319*0b57cec5SDimitry Andric   // OPERAND_BUNDLE_TAG - [strchr x N]
2320*0b57cec5SDimitry Andric 
2321*0b57cec5SDimitry Andric   SmallVector<StringRef, 8> Tags;
2322*0b57cec5SDimitry Andric   M.getOperandBundleTags(Tags);
2323*0b57cec5SDimitry Andric 
2324*0b57cec5SDimitry Andric   if (Tags.empty())
2325*0b57cec5SDimitry Andric     return;
2326*0b57cec5SDimitry Andric 
2327*0b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3);
2328*0b57cec5SDimitry Andric 
2329*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
2330*0b57cec5SDimitry Andric 
2331*0b57cec5SDimitry Andric   for (auto Tag : Tags) {
2332*0b57cec5SDimitry Andric     Record.append(Tag.begin(), Tag.end());
2333*0b57cec5SDimitry Andric 
2334*0b57cec5SDimitry Andric     Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
2335*0b57cec5SDimitry Andric     Record.clear();
2336*0b57cec5SDimitry Andric   }
2337*0b57cec5SDimitry Andric 
2338*0b57cec5SDimitry Andric   Stream.ExitBlock();
2339*0b57cec5SDimitry Andric }
2340*0b57cec5SDimitry Andric 
2341*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeSyncScopeNames() {
2342*0b57cec5SDimitry Andric   SmallVector<StringRef, 8> SSNs;
2343*0b57cec5SDimitry Andric   M.getContext().getSyncScopeNames(SSNs);
2344*0b57cec5SDimitry Andric   if (SSNs.empty())
2345*0b57cec5SDimitry Andric     return;
2346*0b57cec5SDimitry Andric 
2347*0b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID, 2);
2348*0b57cec5SDimitry Andric 
2349*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
2350*0b57cec5SDimitry Andric   for (auto SSN : SSNs) {
2351*0b57cec5SDimitry Andric     Record.append(SSN.begin(), SSN.end());
2352*0b57cec5SDimitry Andric     Stream.EmitRecord(bitc::SYNC_SCOPE_NAME, Record, 0);
2353*0b57cec5SDimitry Andric     Record.clear();
2354*0b57cec5SDimitry Andric   }
2355*0b57cec5SDimitry Andric 
2356*0b57cec5SDimitry Andric   Stream.ExitBlock();
2357*0b57cec5SDimitry Andric }
2358*0b57cec5SDimitry Andric 
2359*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
2360*0b57cec5SDimitry Andric                                          bool isGlobal) {
2361*0b57cec5SDimitry Andric   if (FirstVal == LastVal) return;
2362*0b57cec5SDimitry Andric 
2363*0b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
2364*0b57cec5SDimitry Andric 
2365*0b57cec5SDimitry Andric   unsigned AggregateAbbrev = 0;
2366*0b57cec5SDimitry Andric   unsigned String8Abbrev = 0;
2367*0b57cec5SDimitry Andric   unsigned CString7Abbrev = 0;
2368*0b57cec5SDimitry Andric   unsigned CString6Abbrev = 0;
2369*0b57cec5SDimitry Andric   // If this is a constant pool for the module, emit module-specific abbrevs.
2370*0b57cec5SDimitry Andric   if (isGlobal) {
2371*0b57cec5SDimitry Andric     // Abbrev for CST_CODE_AGGREGATE.
2372*0b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
2373*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
2374*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2375*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
2376*0b57cec5SDimitry Andric     AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2377*0b57cec5SDimitry Andric 
2378*0b57cec5SDimitry Andric     // Abbrev for CST_CODE_STRING.
2379*0b57cec5SDimitry Andric     Abbv = std::make_shared<BitCodeAbbrev>();
2380*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
2381*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2382*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2383*0b57cec5SDimitry Andric     String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2384*0b57cec5SDimitry Andric     // Abbrev for CST_CODE_CSTRING.
2385*0b57cec5SDimitry Andric     Abbv = std::make_shared<BitCodeAbbrev>();
2386*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2387*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2388*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2389*0b57cec5SDimitry Andric     CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2390*0b57cec5SDimitry Andric     // Abbrev for CST_CODE_CSTRING.
2391*0b57cec5SDimitry Andric     Abbv = std::make_shared<BitCodeAbbrev>();
2392*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2393*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2394*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2395*0b57cec5SDimitry Andric     CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2396*0b57cec5SDimitry Andric   }
2397*0b57cec5SDimitry Andric 
2398*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
2399*0b57cec5SDimitry Andric 
2400*0b57cec5SDimitry Andric   const ValueEnumerator::ValueList &Vals = VE.getValues();
2401*0b57cec5SDimitry Andric   Type *LastTy = nullptr;
2402*0b57cec5SDimitry Andric   for (unsigned i = FirstVal; i != LastVal; ++i) {
2403*0b57cec5SDimitry Andric     const Value *V = Vals[i].first;
2404*0b57cec5SDimitry Andric     // If we need to switch types, do so now.
2405*0b57cec5SDimitry Andric     if (V->getType() != LastTy) {
2406*0b57cec5SDimitry Andric       LastTy = V->getType();
2407*0b57cec5SDimitry Andric       Record.push_back(VE.getTypeID(LastTy));
2408*0b57cec5SDimitry Andric       Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
2409*0b57cec5SDimitry Andric                         CONSTANTS_SETTYPE_ABBREV);
2410*0b57cec5SDimitry Andric       Record.clear();
2411*0b57cec5SDimitry Andric     }
2412*0b57cec5SDimitry Andric 
2413*0b57cec5SDimitry Andric     if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
2414*0b57cec5SDimitry Andric       Record.push_back(unsigned(IA->hasSideEffects()) |
2415*0b57cec5SDimitry Andric                        unsigned(IA->isAlignStack()) << 1 |
2416*0b57cec5SDimitry Andric                        unsigned(IA->getDialect()&1) << 2);
2417*0b57cec5SDimitry Andric 
2418*0b57cec5SDimitry Andric       // Add the asm string.
2419*0b57cec5SDimitry Andric       const std::string &AsmStr = IA->getAsmString();
2420*0b57cec5SDimitry Andric       Record.push_back(AsmStr.size());
2421*0b57cec5SDimitry Andric       Record.append(AsmStr.begin(), AsmStr.end());
2422*0b57cec5SDimitry Andric 
2423*0b57cec5SDimitry Andric       // Add the constraint string.
2424*0b57cec5SDimitry Andric       const std::string &ConstraintStr = IA->getConstraintString();
2425*0b57cec5SDimitry Andric       Record.push_back(ConstraintStr.size());
2426*0b57cec5SDimitry Andric       Record.append(ConstraintStr.begin(), ConstraintStr.end());
2427*0b57cec5SDimitry Andric       Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
2428*0b57cec5SDimitry Andric       Record.clear();
2429*0b57cec5SDimitry Andric       continue;
2430*0b57cec5SDimitry Andric     }
2431*0b57cec5SDimitry Andric     const Constant *C = cast<Constant>(V);
2432*0b57cec5SDimitry Andric     unsigned Code = -1U;
2433*0b57cec5SDimitry Andric     unsigned AbbrevToUse = 0;
2434*0b57cec5SDimitry Andric     if (C->isNullValue()) {
2435*0b57cec5SDimitry Andric       Code = bitc::CST_CODE_NULL;
2436e8d8bef9SDimitry Andric     } else if (isa<PoisonValue>(C)) {
2437e8d8bef9SDimitry Andric       Code = bitc::CST_CODE_POISON;
2438*0b57cec5SDimitry Andric     } else if (isa<UndefValue>(C)) {
2439*0b57cec5SDimitry Andric       Code = bitc::CST_CODE_UNDEF;
2440*0b57cec5SDimitry Andric     } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
2441*0b57cec5SDimitry Andric       if (IV->getBitWidth() <= 64) {
2442*0b57cec5SDimitry Andric         uint64_t V = IV->getSExtValue();
2443*0b57cec5SDimitry Andric         emitSignedInt64(Record, V);
2444*0b57cec5SDimitry Andric         Code = bitc::CST_CODE_INTEGER;
2445*0b57cec5SDimitry Andric         AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
2446*0b57cec5SDimitry Andric       } else {                             // Wide integers, > 64 bits in size.
24475ffd83dbSDimitry Andric         emitWideAPInt(Record, IV->getValue());
2448*0b57cec5SDimitry Andric         Code = bitc::CST_CODE_WIDE_INTEGER;
2449*0b57cec5SDimitry Andric       }
2450*0b57cec5SDimitry Andric     } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
2451*0b57cec5SDimitry Andric       Code = bitc::CST_CODE_FLOAT;
2452*0b57cec5SDimitry Andric       Type *Ty = CFP->getType();
24535ffd83dbSDimitry Andric       if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() ||
24545ffd83dbSDimitry Andric           Ty->isDoubleTy()) {
2455*0b57cec5SDimitry Andric         Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
2456*0b57cec5SDimitry Andric       } else if (Ty->isX86_FP80Ty()) {
2457*0b57cec5SDimitry Andric         // api needed to prevent premature destruction
2458*0b57cec5SDimitry Andric         // bits are not in the same order as a normal i80 APInt, compensate.
2459*0b57cec5SDimitry Andric         APInt api = CFP->getValueAPF().bitcastToAPInt();
2460*0b57cec5SDimitry Andric         const uint64_t *p = api.getRawData();
2461*0b57cec5SDimitry Andric         Record.push_back((p[1] << 48) | (p[0] >> 16));
2462*0b57cec5SDimitry Andric         Record.push_back(p[0] & 0xffffLL);
2463*0b57cec5SDimitry Andric       } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
2464*0b57cec5SDimitry Andric         APInt api = CFP->getValueAPF().bitcastToAPInt();
2465*0b57cec5SDimitry Andric         const uint64_t *p = api.getRawData();
2466*0b57cec5SDimitry Andric         Record.push_back(p[0]);
2467*0b57cec5SDimitry Andric         Record.push_back(p[1]);
2468*0b57cec5SDimitry Andric       } else {
2469*0b57cec5SDimitry Andric         assert(0 && "Unknown FP type!");
2470*0b57cec5SDimitry Andric       }
2471*0b57cec5SDimitry Andric     } else if (isa<ConstantDataSequential>(C) &&
2472*0b57cec5SDimitry Andric                cast<ConstantDataSequential>(C)->isString()) {
2473*0b57cec5SDimitry Andric       const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
2474*0b57cec5SDimitry Andric       // Emit constant strings specially.
2475*0b57cec5SDimitry Andric       unsigned NumElts = Str->getNumElements();
2476*0b57cec5SDimitry Andric       // If this is a null-terminated string, use the denser CSTRING encoding.
2477*0b57cec5SDimitry Andric       if (Str->isCString()) {
2478*0b57cec5SDimitry Andric         Code = bitc::CST_CODE_CSTRING;
2479*0b57cec5SDimitry Andric         --NumElts;  // Don't encode the null, which isn't allowed by char6.
2480*0b57cec5SDimitry Andric       } else {
2481*0b57cec5SDimitry Andric         Code = bitc::CST_CODE_STRING;
2482*0b57cec5SDimitry Andric         AbbrevToUse = String8Abbrev;
2483*0b57cec5SDimitry Andric       }
2484*0b57cec5SDimitry Andric       bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
2485*0b57cec5SDimitry Andric       bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
2486*0b57cec5SDimitry Andric       for (unsigned i = 0; i != NumElts; ++i) {
2487*0b57cec5SDimitry Andric         unsigned char V = Str->getElementAsInteger(i);
2488*0b57cec5SDimitry Andric         Record.push_back(V);
2489*0b57cec5SDimitry Andric         isCStr7 &= (V & 128) == 0;
2490*0b57cec5SDimitry Andric         if (isCStrChar6)
2491*0b57cec5SDimitry Andric           isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
2492*0b57cec5SDimitry Andric       }
2493*0b57cec5SDimitry Andric 
2494*0b57cec5SDimitry Andric       if (isCStrChar6)
2495*0b57cec5SDimitry Andric         AbbrevToUse = CString6Abbrev;
2496*0b57cec5SDimitry Andric       else if (isCStr7)
2497*0b57cec5SDimitry Andric         AbbrevToUse = CString7Abbrev;
2498*0b57cec5SDimitry Andric     } else if (const ConstantDataSequential *CDS =
2499*0b57cec5SDimitry Andric                   dyn_cast<ConstantDataSequential>(C)) {
2500*0b57cec5SDimitry Andric       Code = bitc::CST_CODE_DATA;
25015ffd83dbSDimitry Andric       Type *EltTy = CDS->getElementType();
2502*0b57cec5SDimitry Andric       if (isa<IntegerType>(EltTy)) {
2503*0b57cec5SDimitry Andric         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2504*0b57cec5SDimitry Andric           Record.push_back(CDS->getElementAsInteger(i));
2505*0b57cec5SDimitry Andric       } else {
2506*0b57cec5SDimitry Andric         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2507*0b57cec5SDimitry Andric           Record.push_back(
2508*0b57cec5SDimitry Andric               CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
2509*0b57cec5SDimitry Andric       }
2510*0b57cec5SDimitry Andric     } else if (isa<ConstantAggregate>(C)) {
2511*0b57cec5SDimitry Andric       Code = bitc::CST_CODE_AGGREGATE;
2512*0b57cec5SDimitry Andric       for (const Value *Op : C->operands())
2513*0b57cec5SDimitry Andric         Record.push_back(VE.getValueID(Op));
2514*0b57cec5SDimitry Andric       AbbrevToUse = AggregateAbbrev;
2515*0b57cec5SDimitry Andric     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2516*0b57cec5SDimitry Andric       switch (CE->getOpcode()) {
2517*0b57cec5SDimitry Andric       default:
2518*0b57cec5SDimitry Andric         if (Instruction::isCast(CE->getOpcode())) {
2519*0b57cec5SDimitry Andric           Code = bitc::CST_CODE_CE_CAST;
2520*0b57cec5SDimitry Andric           Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
2521*0b57cec5SDimitry Andric           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2522*0b57cec5SDimitry Andric           Record.push_back(VE.getValueID(C->getOperand(0)));
2523*0b57cec5SDimitry Andric           AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
2524*0b57cec5SDimitry Andric         } else {
2525*0b57cec5SDimitry Andric           assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
2526*0b57cec5SDimitry Andric           Code = bitc::CST_CODE_CE_BINOP;
2527*0b57cec5SDimitry Andric           Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
2528*0b57cec5SDimitry Andric           Record.push_back(VE.getValueID(C->getOperand(0)));
2529*0b57cec5SDimitry Andric           Record.push_back(VE.getValueID(C->getOperand(1)));
2530*0b57cec5SDimitry Andric           uint64_t Flags = getOptimizationFlags(CE);
2531*0b57cec5SDimitry Andric           if (Flags != 0)
2532*0b57cec5SDimitry Andric             Record.push_back(Flags);
2533*0b57cec5SDimitry Andric         }
2534*0b57cec5SDimitry Andric         break;
2535*0b57cec5SDimitry Andric       case Instruction::FNeg: {
2536*0b57cec5SDimitry Andric         assert(CE->getNumOperands() == 1 && "Unknown constant expr!");
2537*0b57cec5SDimitry Andric         Code = bitc::CST_CODE_CE_UNOP;
2538*0b57cec5SDimitry Andric         Record.push_back(getEncodedUnaryOpcode(CE->getOpcode()));
2539*0b57cec5SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(0)));
2540*0b57cec5SDimitry Andric         uint64_t Flags = getOptimizationFlags(CE);
2541*0b57cec5SDimitry Andric         if (Flags != 0)
2542*0b57cec5SDimitry Andric           Record.push_back(Flags);
2543*0b57cec5SDimitry Andric         break;
2544*0b57cec5SDimitry Andric       }
2545*0b57cec5SDimitry Andric       case Instruction::GetElementPtr: {
2546*0b57cec5SDimitry Andric         Code = bitc::CST_CODE_CE_GEP;
2547*0b57cec5SDimitry Andric         const auto *GO = cast<GEPOperator>(C);
2548*0b57cec5SDimitry Andric         Record.push_back(VE.getTypeID(GO->getSourceElementType()));
2549*0b57cec5SDimitry Andric         if (Optional<unsigned> Idx = GO->getInRangeIndex()) {
2550*0b57cec5SDimitry Andric           Code = bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX;
2551*0b57cec5SDimitry Andric           Record.push_back((*Idx << 1) | GO->isInBounds());
2552*0b57cec5SDimitry Andric         } else if (GO->isInBounds())
2553*0b57cec5SDimitry Andric           Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
2554*0b57cec5SDimitry Andric         for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
2555*0b57cec5SDimitry Andric           Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
2556*0b57cec5SDimitry Andric           Record.push_back(VE.getValueID(C->getOperand(i)));
2557*0b57cec5SDimitry Andric         }
2558*0b57cec5SDimitry Andric         break;
2559*0b57cec5SDimitry Andric       }
2560*0b57cec5SDimitry Andric       case Instruction::Select:
2561*0b57cec5SDimitry Andric         Code = bitc::CST_CODE_CE_SELECT;
2562*0b57cec5SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(0)));
2563*0b57cec5SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(1)));
2564*0b57cec5SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(2)));
2565*0b57cec5SDimitry Andric         break;
2566*0b57cec5SDimitry Andric       case Instruction::ExtractElement:
2567*0b57cec5SDimitry Andric         Code = bitc::CST_CODE_CE_EXTRACTELT;
2568*0b57cec5SDimitry Andric         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2569*0b57cec5SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(0)));
2570*0b57cec5SDimitry Andric         Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
2571*0b57cec5SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(1)));
2572*0b57cec5SDimitry Andric         break;
2573*0b57cec5SDimitry Andric       case Instruction::InsertElement:
2574*0b57cec5SDimitry Andric         Code = bitc::CST_CODE_CE_INSERTELT;
2575*0b57cec5SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(0)));
2576*0b57cec5SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(1)));
2577*0b57cec5SDimitry Andric         Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
2578*0b57cec5SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(2)));
2579*0b57cec5SDimitry Andric         break;
2580*0b57cec5SDimitry Andric       case Instruction::ShuffleVector:
2581*0b57cec5SDimitry Andric         // If the return type and argument types are the same, this is a
2582*0b57cec5SDimitry Andric         // standard shufflevector instruction.  If the types are different,
2583*0b57cec5SDimitry Andric         // then the shuffle is widening or truncating the input vectors, and
2584*0b57cec5SDimitry Andric         // the argument type must also be encoded.
2585*0b57cec5SDimitry Andric         if (C->getType() == C->getOperand(0)->getType()) {
2586*0b57cec5SDimitry Andric           Code = bitc::CST_CODE_CE_SHUFFLEVEC;
2587*0b57cec5SDimitry Andric         } else {
2588*0b57cec5SDimitry Andric           Code = bitc::CST_CODE_CE_SHUFVEC_EX;
2589*0b57cec5SDimitry Andric           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2590*0b57cec5SDimitry Andric         }
2591*0b57cec5SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(0)));
2592*0b57cec5SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(1)));
25935ffd83dbSDimitry Andric         Record.push_back(VE.getValueID(CE->getShuffleMaskForBitcode()));
2594*0b57cec5SDimitry Andric         break;
2595*0b57cec5SDimitry Andric       case Instruction::ICmp:
2596*0b57cec5SDimitry Andric       case Instruction::FCmp:
2597*0b57cec5SDimitry Andric         Code = bitc::CST_CODE_CE_CMP;
2598*0b57cec5SDimitry Andric         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2599*0b57cec5SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(0)));
2600*0b57cec5SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(1)));
2601*0b57cec5SDimitry Andric         Record.push_back(CE->getPredicate());
2602*0b57cec5SDimitry Andric         break;
2603*0b57cec5SDimitry Andric       }
2604*0b57cec5SDimitry Andric     } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
2605*0b57cec5SDimitry Andric       Code = bitc::CST_CODE_BLOCKADDRESS;
2606*0b57cec5SDimitry Andric       Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
2607*0b57cec5SDimitry Andric       Record.push_back(VE.getValueID(BA->getFunction()));
2608*0b57cec5SDimitry Andric       Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
2609*0b57cec5SDimitry Andric     } else {
2610*0b57cec5SDimitry Andric #ifndef NDEBUG
2611*0b57cec5SDimitry Andric       C->dump();
2612*0b57cec5SDimitry Andric #endif
2613*0b57cec5SDimitry Andric       llvm_unreachable("Unknown constant!");
2614*0b57cec5SDimitry Andric     }
2615*0b57cec5SDimitry Andric     Stream.EmitRecord(Code, Record, AbbrevToUse);
2616*0b57cec5SDimitry Andric     Record.clear();
2617*0b57cec5SDimitry Andric   }
2618*0b57cec5SDimitry Andric 
2619*0b57cec5SDimitry Andric   Stream.ExitBlock();
2620*0b57cec5SDimitry Andric }
2621*0b57cec5SDimitry Andric 
2622*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeModuleConstants() {
2623*0b57cec5SDimitry Andric   const ValueEnumerator::ValueList &Vals = VE.getValues();
2624*0b57cec5SDimitry Andric 
2625*0b57cec5SDimitry Andric   // Find the first constant to emit, which is the first non-globalvalue value.
2626*0b57cec5SDimitry Andric   // We know globalvalues have been emitted by WriteModuleInfo.
2627*0b57cec5SDimitry Andric   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
2628*0b57cec5SDimitry Andric     if (!isa<GlobalValue>(Vals[i].first)) {
2629*0b57cec5SDimitry Andric       writeConstants(i, Vals.size(), true);
2630*0b57cec5SDimitry Andric       return;
2631*0b57cec5SDimitry Andric     }
2632*0b57cec5SDimitry Andric   }
2633*0b57cec5SDimitry Andric }
2634*0b57cec5SDimitry Andric 
2635*0b57cec5SDimitry Andric /// pushValueAndType - The file has to encode both the value and type id for
2636*0b57cec5SDimitry Andric /// many values, because we need to know what type to create for forward
2637*0b57cec5SDimitry Andric /// references.  However, most operands are not forward references, so this type
2638*0b57cec5SDimitry Andric /// field is not needed.
2639*0b57cec5SDimitry Andric ///
2640*0b57cec5SDimitry Andric /// This function adds V's value ID to Vals.  If the value ID is higher than the
2641*0b57cec5SDimitry Andric /// instruction ID, then it is a forward reference, and it also includes the
2642*0b57cec5SDimitry Andric /// type ID.  The value ID that is written is encoded relative to the InstID.
2643*0b57cec5SDimitry Andric bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
2644*0b57cec5SDimitry Andric                                            SmallVectorImpl<unsigned> &Vals) {
2645*0b57cec5SDimitry Andric   unsigned ValID = VE.getValueID(V);
2646*0b57cec5SDimitry Andric   // Make encoding relative to the InstID.
2647*0b57cec5SDimitry Andric   Vals.push_back(InstID - ValID);
2648*0b57cec5SDimitry Andric   if (ValID >= InstID) {
2649*0b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(V->getType()));
2650*0b57cec5SDimitry Andric     return true;
2651*0b57cec5SDimitry Andric   }
2652*0b57cec5SDimitry Andric   return false;
2653*0b57cec5SDimitry Andric }
2654*0b57cec5SDimitry Andric 
26555ffd83dbSDimitry Andric void ModuleBitcodeWriter::writeOperandBundles(const CallBase &CS,
2656*0b57cec5SDimitry Andric                                               unsigned InstID) {
2657*0b57cec5SDimitry Andric   SmallVector<unsigned, 64> Record;
26585ffd83dbSDimitry Andric   LLVMContext &C = CS.getContext();
2659*0b57cec5SDimitry Andric 
2660*0b57cec5SDimitry Andric   for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
2661*0b57cec5SDimitry Andric     const auto &Bundle = CS.getOperandBundleAt(i);
2662*0b57cec5SDimitry Andric     Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
2663*0b57cec5SDimitry Andric 
2664*0b57cec5SDimitry Andric     for (auto &Input : Bundle.Inputs)
2665*0b57cec5SDimitry Andric       pushValueAndType(Input, InstID, Record);
2666*0b57cec5SDimitry Andric 
2667*0b57cec5SDimitry Andric     Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record);
2668*0b57cec5SDimitry Andric     Record.clear();
2669*0b57cec5SDimitry Andric   }
2670*0b57cec5SDimitry Andric }
2671*0b57cec5SDimitry Andric 
2672*0b57cec5SDimitry Andric /// pushValue - Like pushValueAndType, but where the type of the value is
2673*0b57cec5SDimitry Andric /// omitted (perhaps it was already encoded in an earlier operand).
2674*0b57cec5SDimitry Andric void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
2675*0b57cec5SDimitry Andric                                     SmallVectorImpl<unsigned> &Vals) {
2676*0b57cec5SDimitry Andric   unsigned ValID = VE.getValueID(V);
2677*0b57cec5SDimitry Andric   Vals.push_back(InstID - ValID);
2678*0b57cec5SDimitry Andric }
2679*0b57cec5SDimitry Andric 
2680*0b57cec5SDimitry Andric void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
2681*0b57cec5SDimitry Andric                                           SmallVectorImpl<uint64_t> &Vals) {
2682*0b57cec5SDimitry Andric   unsigned ValID = VE.getValueID(V);
2683*0b57cec5SDimitry Andric   int64_t diff = ((int32_t)InstID - (int32_t)ValID);
2684*0b57cec5SDimitry Andric   emitSignedInt64(Vals, diff);
2685*0b57cec5SDimitry Andric }
2686*0b57cec5SDimitry Andric 
2687*0b57cec5SDimitry Andric /// WriteInstruction - Emit an instruction to the specified stream.
2688*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
2689*0b57cec5SDimitry Andric                                            unsigned InstID,
2690*0b57cec5SDimitry Andric                                            SmallVectorImpl<unsigned> &Vals) {
2691*0b57cec5SDimitry Andric   unsigned Code = 0;
2692*0b57cec5SDimitry Andric   unsigned AbbrevToUse = 0;
2693*0b57cec5SDimitry Andric   VE.setInstructionID(&I);
2694*0b57cec5SDimitry Andric   switch (I.getOpcode()) {
2695*0b57cec5SDimitry Andric   default:
2696*0b57cec5SDimitry Andric     if (Instruction::isCast(I.getOpcode())) {
2697*0b57cec5SDimitry Andric       Code = bitc::FUNC_CODE_INST_CAST;
2698*0b57cec5SDimitry Andric       if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2699*0b57cec5SDimitry Andric         AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
2700*0b57cec5SDimitry Andric       Vals.push_back(VE.getTypeID(I.getType()));
2701*0b57cec5SDimitry Andric       Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
2702*0b57cec5SDimitry Andric     } else {
2703*0b57cec5SDimitry Andric       assert(isa<BinaryOperator>(I) && "Unknown instruction!");
2704*0b57cec5SDimitry Andric       Code = bitc::FUNC_CODE_INST_BINOP;
2705*0b57cec5SDimitry Andric       if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2706*0b57cec5SDimitry Andric         AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
2707*0b57cec5SDimitry Andric       pushValue(I.getOperand(1), InstID, Vals);
2708*0b57cec5SDimitry Andric       Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
2709*0b57cec5SDimitry Andric       uint64_t Flags = getOptimizationFlags(&I);
2710*0b57cec5SDimitry Andric       if (Flags != 0) {
2711*0b57cec5SDimitry Andric         if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
2712*0b57cec5SDimitry Andric           AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
2713*0b57cec5SDimitry Andric         Vals.push_back(Flags);
2714*0b57cec5SDimitry Andric       }
2715*0b57cec5SDimitry Andric     }
2716*0b57cec5SDimitry Andric     break;
2717*0b57cec5SDimitry Andric   case Instruction::FNeg: {
2718*0b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_UNOP;
2719*0b57cec5SDimitry Andric     if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2720*0b57cec5SDimitry Andric       AbbrevToUse = FUNCTION_INST_UNOP_ABBREV;
2721*0b57cec5SDimitry Andric     Vals.push_back(getEncodedUnaryOpcode(I.getOpcode()));
2722*0b57cec5SDimitry Andric     uint64_t Flags = getOptimizationFlags(&I);
2723*0b57cec5SDimitry Andric     if (Flags != 0) {
2724*0b57cec5SDimitry Andric       if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV)
2725*0b57cec5SDimitry Andric         AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV;
2726*0b57cec5SDimitry Andric       Vals.push_back(Flags);
2727*0b57cec5SDimitry Andric     }
2728*0b57cec5SDimitry Andric     break;
2729*0b57cec5SDimitry Andric   }
2730*0b57cec5SDimitry Andric   case Instruction::GetElementPtr: {
2731*0b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_GEP;
2732*0b57cec5SDimitry Andric     AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
2733*0b57cec5SDimitry Andric     auto &GEPInst = cast<GetElementPtrInst>(I);
2734*0b57cec5SDimitry Andric     Vals.push_back(GEPInst.isInBounds());
2735*0b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
2736*0b57cec5SDimitry Andric     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
2737*0b57cec5SDimitry Andric       pushValueAndType(I.getOperand(i), InstID, Vals);
2738*0b57cec5SDimitry Andric     break;
2739*0b57cec5SDimitry Andric   }
2740*0b57cec5SDimitry Andric   case Instruction::ExtractValue: {
2741*0b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
2742*0b57cec5SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals);
2743*0b57cec5SDimitry Andric     const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
2744*0b57cec5SDimitry Andric     Vals.append(EVI->idx_begin(), EVI->idx_end());
2745*0b57cec5SDimitry Andric     break;
2746*0b57cec5SDimitry Andric   }
2747*0b57cec5SDimitry Andric   case Instruction::InsertValue: {
2748*0b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_INSERTVAL;
2749*0b57cec5SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals);
2750*0b57cec5SDimitry Andric     pushValueAndType(I.getOperand(1), InstID, Vals);
2751*0b57cec5SDimitry Andric     const InsertValueInst *IVI = cast<InsertValueInst>(&I);
2752*0b57cec5SDimitry Andric     Vals.append(IVI->idx_begin(), IVI->idx_end());
2753*0b57cec5SDimitry Andric     break;
2754*0b57cec5SDimitry Andric   }
2755*0b57cec5SDimitry Andric   case Instruction::Select: {
2756*0b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_VSELECT;
2757*0b57cec5SDimitry Andric     pushValueAndType(I.getOperand(1), InstID, Vals);
2758*0b57cec5SDimitry Andric     pushValue(I.getOperand(2), InstID, Vals);
2759*0b57cec5SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals);
2760*0b57cec5SDimitry Andric     uint64_t Flags = getOptimizationFlags(&I);
2761*0b57cec5SDimitry Andric     if (Flags != 0)
2762*0b57cec5SDimitry Andric       Vals.push_back(Flags);
2763*0b57cec5SDimitry Andric     break;
2764*0b57cec5SDimitry Andric   }
2765*0b57cec5SDimitry Andric   case Instruction::ExtractElement:
2766*0b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_EXTRACTELT;
2767*0b57cec5SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals);
2768*0b57cec5SDimitry Andric     pushValueAndType(I.getOperand(1), InstID, Vals);
2769*0b57cec5SDimitry Andric     break;
2770*0b57cec5SDimitry Andric   case Instruction::InsertElement:
2771*0b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_INSERTELT;
2772*0b57cec5SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals);
2773*0b57cec5SDimitry Andric     pushValue(I.getOperand(1), InstID, Vals);
2774*0b57cec5SDimitry Andric     pushValueAndType(I.getOperand(2), InstID, Vals);
2775*0b57cec5SDimitry Andric     break;
2776*0b57cec5SDimitry Andric   case Instruction::ShuffleVector:
2777*0b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
2778*0b57cec5SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals);
2779*0b57cec5SDimitry Andric     pushValue(I.getOperand(1), InstID, Vals);
27805ffd83dbSDimitry Andric     pushValue(cast<ShuffleVectorInst>(I).getShuffleMaskForBitcode(), InstID,
27815ffd83dbSDimitry Andric               Vals);
2782*0b57cec5SDimitry Andric     break;
2783*0b57cec5SDimitry Andric   case Instruction::ICmp:
2784*0b57cec5SDimitry Andric   case Instruction::FCmp: {
2785*0b57cec5SDimitry Andric     // compare returning Int1Ty or vector of Int1Ty
2786*0b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_CMP2;
2787*0b57cec5SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals);
2788*0b57cec5SDimitry Andric     pushValue(I.getOperand(1), InstID, Vals);
2789*0b57cec5SDimitry Andric     Vals.push_back(cast<CmpInst>(I).getPredicate());
2790*0b57cec5SDimitry Andric     uint64_t Flags = getOptimizationFlags(&I);
2791*0b57cec5SDimitry Andric     if (Flags != 0)
2792*0b57cec5SDimitry Andric       Vals.push_back(Flags);
2793*0b57cec5SDimitry Andric     break;
2794*0b57cec5SDimitry Andric   }
2795*0b57cec5SDimitry Andric 
2796*0b57cec5SDimitry Andric   case Instruction::Ret:
2797*0b57cec5SDimitry Andric     {
2798*0b57cec5SDimitry Andric       Code = bitc::FUNC_CODE_INST_RET;
2799*0b57cec5SDimitry Andric       unsigned NumOperands = I.getNumOperands();
2800*0b57cec5SDimitry Andric       if (NumOperands == 0)
2801*0b57cec5SDimitry Andric         AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
2802*0b57cec5SDimitry Andric       else if (NumOperands == 1) {
2803*0b57cec5SDimitry Andric         if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2804*0b57cec5SDimitry Andric           AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
2805*0b57cec5SDimitry Andric       } else {
2806*0b57cec5SDimitry Andric         for (unsigned i = 0, e = NumOperands; i != e; ++i)
2807*0b57cec5SDimitry Andric           pushValueAndType(I.getOperand(i), InstID, Vals);
2808*0b57cec5SDimitry Andric       }
2809*0b57cec5SDimitry Andric     }
2810*0b57cec5SDimitry Andric     break;
2811*0b57cec5SDimitry Andric   case Instruction::Br:
2812*0b57cec5SDimitry Andric     {
2813*0b57cec5SDimitry Andric       Code = bitc::FUNC_CODE_INST_BR;
2814*0b57cec5SDimitry Andric       const BranchInst &II = cast<BranchInst>(I);
2815*0b57cec5SDimitry Andric       Vals.push_back(VE.getValueID(II.getSuccessor(0)));
2816*0b57cec5SDimitry Andric       if (II.isConditional()) {
2817*0b57cec5SDimitry Andric         Vals.push_back(VE.getValueID(II.getSuccessor(1)));
2818*0b57cec5SDimitry Andric         pushValue(II.getCondition(), InstID, Vals);
2819*0b57cec5SDimitry Andric       }
2820*0b57cec5SDimitry Andric     }
2821*0b57cec5SDimitry Andric     break;
2822*0b57cec5SDimitry Andric   case Instruction::Switch:
2823*0b57cec5SDimitry Andric     {
2824*0b57cec5SDimitry Andric       Code = bitc::FUNC_CODE_INST_SWITCH;
2825*0b57cec5SDimitry Andric       const SwitchInst &SI = cast<SwitchInst>(I);
2826*0b57cec5SDimitry Andric       Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
2827*0b57cec5SDimitry Andric       pushValue(SI.getCondition(), InstID, Vals);
2828*0b57cec5SDimitry Andric       Vals.push_back(VE.getValueID(SI.getDefaultDest()));
2829*0b57cec5SDimitry Andric       for (auto Case : SI.cases()) {
2830*0b57cec5SDimitry Andric         Vals.push_back(VE.getValueID(Case.getCaseValue()));
2831*0b57cec5SDimitry Andric         Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
2832*0b57cec5SDimitry Andric       }
2833*0b57cec5SDimitry Andric     }
2834*0b57cec5SDimitry Andric     break;
2835*0b57cec5SDimitry Andric   case Instruction::IndirectBr:
2836*0b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_INDIRECTBR;
2837*0b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
2838*0b57cec5SDimitry Andric     // Encode the address operand as relative, but not the basic blocks.
2839*0b57cec5SDimitry Andric     pushValue(I.getOperand(0), InstID, Vals);
2840*0b57cec5SDimitry Andric     for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
2841*0b57cec5SDimitry Andric       Vals.push_back(VE.getValueID(I.getOperand(i)));
2842*0b57cec5SDimitry Andric     break;
2843*0b57cec5SDimitry Andric 
2844*0b57cec5SDimitry Andric   case Instruction::Invoke: {
2845*0b57cec5SDimitry Andric     const InvokeInst *II = cast<InvokeInst>(&I);
28465ffd83dbSDimitry Andric     const Value *Callee = II->getCalledOperand();
2847*0b57cec5SDimitry Andric     FunctionType *FTy = II->getFunctionType();
2848*0b57cec5SDimitry Andric 
2849*0b57cec5SDimitry Andric     if (II->hasOperandBundles())
28505ffd83dbSDimitry Andric       writeOperandBundles(*II, InstID);
2851*0b57cec5SDimitry Andric 
2852*0b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_INVOKE;
2853*0b57cec5SDimitry Andric 
2854*0b57cec5SDimitry Andric     Vals.push_back(VE.getAttributeListID(II->getAttributes()));
2855*0b57cec5SDimitry Andric     Vals.push_back(II->getCallingConv() | 1 << 13);
2856*0b57cec5SDimitry Andric     Vals.push_back(VE.getValueID(II->getNormalDest()));
2857*0b57cec5SDimitry Andric     Vals.push_back(VE.getValueID(II->getUnwindDest()));
2858*0b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(FTy));
2859*0b57cec5SDimitry Andric     pushValueAndType(Callee, InstID, Vals);
2860*0b57cec5SDimitry Andric 
2861*0b57cec5SDimitry Andric     // Emit value #'s for the fixed parameters.
2862*0b57cec5SDimitry Andric     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2863*0b57cec5SDimitry Andric       pushValue(I.getOperand(i), InstID, Vals); // fixed param.
2864*0b57cec5SDimitry Andric 
2865*0b57cec5SDimitry Andric     // Emit type/value pairs for varargs params.
2866*0b57cec5SDimitry Andric     if (FTy->isVarArg()) {
2867*0b57cec5SDimitry Andric       for (unsigned i = FTy->getNumParams(), e = II->getNumArgOperands();
2868*0b57cec5SDimitry Andric            i != e; ++i)
2869*0b57cec5SDimitry Andric         pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
2870*0b57cec5SDimitry Andric     }
2871*0b57cec5SDimitry Andric     break;
2872*0b57cec5SDimitry Andric   }
2873*0b57cec5SDimitry Andric   case Instruction::Resume:
2874*0b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_RESUME;
2875*0b57cec5SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals);
2876*0b57cec5SDimitry Andric     break;
2877*0b57cec5SDimitry Andric   case Instruction::CleanupRet: {
2878*0b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_CLEANUPRET;
2879*0b57cec5SDimitry Andric     const auto &CRI = cast<CleanupReturnInst>(I);
2880*0b57cec5SDimitry Andric     pushValue(CRI.getCleanupPad(), InstID, Vals);
2881*0b57cec5SDimitry Andric     if (CRI.hasUnwindDest())
2882*0b57cec5SDimitry Andric       Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
2883*0b57cec5SDimitry Andric     break;
2884*0b57cec5SDimitry Andric   }
2885*0b57cec5SDimitry Andric   case Instruction::CatchRet: {
2886*0b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_CATCHRET;
2887*0b57cec5SDimitry Andric     const auto &CRI = cast<CatchReturnInst>(I);
2888*0b57cec5SDimitry Andric     pushValue(CRI.getCatchPad(), InstID, Vals);
2889*0b57cec5SDimitry Andric     Vals.push_back(VE.getValueID(CRI.getSuccessor()));
2890*0b57cec5SDimitry Andric     break;
2891*0b57cec5SDimitry Andric   }
2892*0b57cec5SDimitry Andric   case Instruction::CleanupPad:
2893*0b57cec5SDimitry Andric   case Instruction::CatchPad: {
2894*0b57cec5SDimitry Andric     const auto &FuncletPad = cast<FuncletPadInst>(I);
2895*0b57cec5SDimitry Andric     Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
2896*0b57cec5SDimitry Andric                                          : bitc::FUNC_CODE_INST_CLEANUPPAD;
2897*0b57cec5SDimitry Andric     pushValue(FuncletPad.getParentPad(), InstID, Vals);
2898*0b57cec5SDimitry Andric 
2899*0b57cec5SDimitry Andric     unsigned NumArgOperands = FuncletPad.getNumArgOperands();
2900*0b57cec5SDimitry Andric     Vals.push_back(NumArgOperands);
2901*0b57cec5SDimitry Andric     for (unsigned Op = 0; Op != NumArgOperands; ++Op)
2902*0b57cec5SDimitry Andric       pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
2903*0b57cec5SDimitry Andric     break;
2904*0b57cec5SDimitry Andric   }
2905*0b57cec5SDimitry Andric   case Instruction::CatchSwitch: {
2906*0b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_CATCHSWITCH;
2907*0b57cec5SDimitry Andric     const auto &CatchSwitch = cast<CatchSwitchInst>(I);
2908*0b57cec5SDimitry Andric 
2909*0b57cec5SDimitry Andric     pushValue(CatchSwitch.getParentPad(), InstID, Vals);
2910*0b57cec5SDimitry Andric 
2911*0b57cec5SDimitry Andric     unsigned NumHandlers = CatchSwitch.getNumHandlers();
2912*0b57cec5SDimitry Andric     Vals.push_back(NumHandlers);
2913*0b57cec5SDimitry Andric     for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
2914*0b57cec5SDimitry Andric       Vals.push_back(VE.getValueID(CatchPadBB));
2915*0b57cec5SDimitry Andric 
2916*0b57cec5SDimitry Andric     if (CatchSwitch.hasUnwindDest())
2917*0b57cec5SDimitry Andric       Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
2918*0b57cec5SDimitry Andric     break;
2919*0b57cec5SDimitry Andric   }
2920*0b57cec5SDimitry Andric   case Instruction::CallBr: {
2921*0b57cec5SDimitry Andric     const CallBrInst *CBI = cast<CallBrInst>(&I);
29225ffd83dbSDimitry Andric     const Value *Callee = CBI->getCalledOperand();
2923*0b57cec5SDimitry Andric     FunctionType *FTy = CBI->getFunctionType();
2924*0b57cec5SDimitry Andric 
2925*0b57cec5SDimitry Andric     if (CBI->hasOperandBundles())
29265ffd83dbSDimitry Andric       writeOperandBundles(*CBI, InstID);
2927*0b57cec5SDimitry Andric 
2928*0b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_CALLBR;
2929*0b57cec5SDimitry Andric 
2930*0b57cec5SDimitry Andric     Vals.push_back(VE.getAttributeListID(CBI->getAttributes()));
2931*0b57cec5SDimitry Andric 
2932*0b57cec5SDimitry Andric     Vals.push_back(CBI->getCallingConv() << bitc::CALL_CCONV |
2933*0b57cec5SDimitry Andric                    1 << bitc::CALL_EXPLICIT_TYPE);
2934*0b57cec5SDimitry Andric 
2935*0b57cec5SDimitry Andric     Vals.push_back(VE.getValueID(CBI->getDefaultDest()));
2936*0b57cec5SDimitry Andric     Vals.push_back(CBI->getNumIndirectDests());
2937*0b57cec5SDimitry Andric     for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i)
2938*0b57cec5SDimitry Andric       Vals.push_back(VE.getValueID(CBI->getIndirectDest(i)));
2939*0b57cec5SDimitry Andric 
2940*0b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(FTy));
2941*0b57cec5SDimitry Andric     pushValueAndType(Callee, InstID, Vals);
2942*0b57cec5SDimitry Andric 
2943*0b57cec5SDimitry Andric     // Emit value #'s for the fixed parameters.
2944*0b57cec5SDimitry Andric     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2945*0b57cec5SDimitry Andric       pushValue(I.getOperand(i), InstID, Vals); // fixed param.
2946*0b57cec5SDimitry Andric 
2947*0b57cec5SDimitry Andric     // Emit type/value pairs for varargs params.
2948*0b57cec5SDimitry Andric     if (FTy->isVarArg()) {
2949*0b57cec5SDimitry Andric       for (unsigned i = FTy->getNumParams(), e = CBI->getNumArgOperands();
2950*0b57cec5SDimitry Andric            i != e; ++i)
2951*0b57cec5SDimitry Andric         pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
2952*0b57cec5SDimitry Andric     }
2953*0b57cec5SDimitry Andric     break;
2954*0b57cec5SDimitry Andric   }
2955*0b57cec5SDimitry Andric   case Instruction::Unreachable:
2956*0b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_UNREACHABLE;
2957*0b57cec5SDimitry Andric     AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
2958*0b57cec5SDimitry Andric     break;
2959*0b57cec5SDimitry Andric 
2960*0b57cec5SDimitry Andric   case Instruction::PHI: {
2961*0b57cec5SDimitry Andric     const PHINode &PN = cast<PHINode>(I);
2962*0b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_PHI;
2963*0b57cec5SDimitry Andric     // With the newer instruction encoding, forward references could give
2964*0b57cec5SDimitry Andric     // negative valued IDs.  This is most common for PHIs, so we use
2965*0b57cec5SDimitry Andric     // signed VBRs.
2966*0b57cec5SDimitry Andric     SmallVector<uint64_t, 128> Vals64;
2967*0b57cec5SDimitry Andric     Vals64.push_back(VE.getTypeID(PN.getType()));
2968*0b57cec5SDimitry Andric     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
2969*0b57cec5SDimitry Andric       pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
2970*0b57cec5SDimitry Andric       Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
2971*0b57cec5SDimitry Andric     }
29728bcb0991SDimitry Andric 
29738bcb0991SDimitry Andric     uint64_t Flags = getOptimizationFlags(&I);
29748bcb0991SDimitry Andric     if (Flags != 0)
29758bcb0991SDimitry Andric       Vals64.push_back(Flags);
29768bcb0991SDimitry Andric 
2977*0b57cec5SDimitry Andric     // Emit a Vals64 vector and exit.
2978*0b57cec5SDimitry Andric     Stream.EmitRecord(Code, Vals64, AbbrevToUse);
2979*0b57cec5SDimitry Andric     Vals64.clear();
2980*0b57cec5SDimitry Andric     return;
2981*0b57cec5SDimitry Andric   }
2982*0b57cec5SDimitry Andric 
2983*0b57cec5SDimitry Andric   case Instruction::LandingPad: {
2984*0b57cec5SDimitry Andric     const LandingPadInst &LP = cast<LandingPadInst>(I);
2985*0b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_LANDINGPAD;
2986*0b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(LP.getType()));
2987*0b57cec5SDimitry Andric     Vals.push_back(LP.isCleanup());
2988*0b57cec5SDimitry Andric     Vals.push_back(LP.getNumClauses());
2989*0b57cec5SDimitry Andric     for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
2990*0b57cec5SDimitry Andric       if (LP.isCatch(I))
2991*0b57cec5SDimitry Andric         Vals.push_back(LandingPadInst::Catch);
2992*0b57cec5SDimitry Andric       else
2993*0b57cec5SDimitry Andric         Vals.push_back(LandingPadInst::Filter);
2994*0b57cec5SDimitry Andric       pushValueAndType(LP.getClause(I), InstID, Vals);
2995*0b57cec5SDimitry Andric     }
2996*0b57cec5SDimitry Andric     break;
2997*0b57cec5SDimitry Andric   }
2998*0b57cec5SDimitry Andric 
2999*0b57cec5SDimitry Andric   case Instruction::Alloca: {
3000*0b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_ALLOCA;
3001*0b57cec5SDimitry Andric     const AllocaInst &AI = cast<AllocaInst>(I);
3002*0b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
3003*0b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
3004*0b57cec5SDimitry Andric     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
3005e8d8bef9SDimitry Andric     using APV = AllocaPackedValues;
3006e8d8bef9SDimitry Andric     unsigned Record = 0;
3007e8d8bef9SDimitry Andric     Bitfield::set<APV::Align>(Record, getEncodedAlign(AI.getAlign()));
3008e8d8bef9SDimitry Andric     Bitfield::set<APV::UsedWithInAlloca>(Record, AI.isUsedWithInAlloca());
3009e8d8bef9SDimitry Andric     Bitfield::set<APV::ExplicitType>(Record, true);
3010e8d8bef9SDimitry Andric     Bitfield::set<APV::SwiftError>(Record, AI.isSwiftError());
3011e8d8bef9SDimitry Andric     Vals.push_back(Record);
3012*0b57cec5SDimitry Andric     break;
3013*0b57cec5SDimitry Andric   }
3014*0b57cec5SDimitry Andric 
3015*0b57cec5SDimitry Andric   case Instruction::Load:
3016*0b57cec5SDimitry Andric     if (cast<LoadInst>(I).isAtomic()) {
3017*0b57cec5SDimitry Andric       Code = bitc::FUNC_CODE_INST_LOADATOMIC;
3018*0b57cec5SDimitry Andric       pushValueAndType(I.getOperand(0), InstID, Vals);
3019*0b57cec5SDimitry Andric     } else {
3020*0b57cec5SDimitry Andric       Code = bitc::FUNC_CODE_INST_LOAD;
3021*0b57cec5SDimitry Andric       if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
3022*0b57cec5SDimitry Andric         AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
3023*0b57cec5SDimitry Andric     }
3024*0b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(I.getType()));
3025e8d8bef9SDimitry Andric     Vals.push_back(getEncodedAlign(cast<LoadInst>(I).getAlign()));
3026*0b57cec5SDimitry Andric     Vals.push_back(cast<LoadInst>(I).isVolatile());
3027*0b57cec5SDimitry Andric     if (cast<LoadInst>(I).isAtomic()) {
3028*0b57cec5SDimitry Andric       Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
3029*0b57cec5SDimitry Andric       Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID()));
3030*0b57cec5SDimitry Andric     }
3031*0b57cec5SDimitry Andric     break;
3032*0b57cec5SDimitry Andric   case Instruction::Store:
3033*0b57cec5SDimitry Andric     if (cast<StoreInst>(I).isAtomic())
3034*0b57cec5SDimitry Andric       Code = bitc::FUNC_CODE_INST_STOREATOMIC;
3035*0b57cec5SDimitry Andric     else
3036*0b57cec5SDimitry Andric       Code = bitc::FUNC_CODE_INST_STORE;
3037*0b57cec5SDimitry Andric     pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr
3038*0b57cec5SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val
3039e8d8bef9SDimitry Andric     Vals.push_back(getEncodedAlign(cast<StoreInst>(I).getAlign()));
3040*0b57cec5SDimitry Andric     Vals.push_back(cast<StoreInst>(I).isVolatile());
3041*0b57cec5SDimitry Andric     if (cast<StoreInst>(I).isAtomic()) {
3042*0b57cec5SDimitry Andric       Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
3043*0b57cec5SDimitry Andric       Vals.push_back(
3044*0b57cec5SDimitry Andric           getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID()));
3045*0b57cec5SDimitry Andric     }
3046*0b57cec5SDimitry Andric     break;
3047*0b57cec5SDimitry Andric   case Instruction::AtomicCmpXchg:
3048*0b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_CMPXCHG;
3049*0b57cec5SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
3050*0b57cec5SDimitry Andric     pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
3051*0b57cec5SDimitry Andric     pushValue(I.getOperand(2), InstID, Vals);        // newval.
3052*0b57cec5SDimitry Andric     Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
3053*0b57cec5SDimitry Andric     Vals.push_back(
3054*0b57cec5SDimitry Andric         getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
3055*0b57cec5SDimitry Andric     Vals.push_back(
3056*0b57cec5SDimitry Andric         getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID()));
3057*0b57cec5SDimitry Andric     Vals.push_back(
3058*0b57cec5SDimitry Andric         getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
3059*0b57cec5SDimitry Andric     Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
3060*0b57cec5SDimitry Andric     break;
3061*0b57cec5SDimitry Andric   case Instruction::AtomicRMW:
3062*0b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_ATOMICRMW;
3063*0b57cec5SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
3064*0b57cec5SDimitry Andric     pushValue(I.getOperand(1), InstID, Vals);        // val.
3065*0b57cec5SDimitry Andric     Vals.push_back(
3066*0b57cec5SDimitry Andric         getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
3067*0b57cec5SDimitry Andric     Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
3068*0b57cec5SDimitry Andric     Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
3069*0b57cec5SDimitry Andric     Vals.push_back(
3070*0b57cec5SDimitry Andric         getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID()));
3071*0b57cec5SDimitry Andric     break;
3072*0b57cec5SDimitry Andric   case Instruction::Fence:
3073*0b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_FENCE;
3074*0b57cec5SDimitry Andric     Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
3075*0b57cec5SDimitry Andric     Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID()));
3076*0b57cec5SDimitry Andric     break;
3077*0b57cec5SDimitry Andric   case Instruction::Call: {
3078*0b57cec5SDimitry Andric     const CallInst &CI = cast<CallInst>(I);
3079*0b57cec5SDimitry Andric     FunctionType *FTy = CI.getFunctionType();
3080*0b57cec5SDimitry Andric 
3081*0b57cec5SDimitry Andric     if (CI.hasOperandBundles())
30825ffd83dbSDimitry Andric       writeOperandBundles(CI, InstID);
3083*0b57cec5SDimitry Andric 
3084*0b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_CALL;
3085*0b57cec5SDimitry Andric 
3086*0b57cec5SDimitry Andric     Vals.push_back(VE.getAttributeListID(CI.getAttributes()));
3087*0b57cec5SDimitry Andric 
3088*0b57cec5SDimitry Andric     unsigned Flags = getOptimizationFlags(&I);
3089*0b57cec5SDimitry Andric     Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |
3090*0b57cec5SDimitry Andric                    unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
3091*0b57cec5SDimitry Andric                    unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
3092*0b57cec5SDimitry Andric                    1 << bitc::CALL_EXPLICIT_TYPE |
3093*0b57cec5SDimitry Andric                    unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
3094*0b57cec5SDimitry Andric                    unsigned(Flags != 0) << bitc::CALL_FMF);
3095*0b57cec5SDimitry Andric     if (Flags != 0)
3096*0b57cec5SDimitry Andric       Vals.push_back(Flags);
3097*0b57cec5SDimitry Andric 
3098*0b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(FTy));
30995ffd83dbSDimitry Andric     pushValueAndType(CI.getCalledOperand(), InstID, Vals); // Callee
3100*0b57cec5SDimitry Andric 
3101*0b57cec5SDimitry Andric     // Emit value #'s for the fixed parameters.
3102*0b57cec5SDimitry Andric     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3103*0b57cec5SDimitry Andric       // Check for labels (can happen with asm labels).
3104*0b57cec5SDimitry Andric       if (FTy->getParamType(i)->isLabelTy())
3105*0b57cec5SDimitry Andric         Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
3106*0b57cec5SDimitry Andric       else
3107*0b57cec5SDimitry Andric         pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
3108*0b57cec5SDimitry Andric     }
3109*0b57cec5SDimitry Andric 
3110*0b57cec5SDimitry Andric     // Emit type/value pairs for varargs params.
3111*0b57cec5SDimitry Andric     if (FTy->isVarArg()) {
3112*0b57cec5SDimitry Andric       for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
3113*0b57cec5SDimitry Andric            i != e; ++i)
3114*0b57cec5SDimitry Andric         pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
3115*0b57cec5SDimitry Andric     }
3116*0b57cec5SDimitry Andric     break;
3117*0b57cec5SDimitry Andric   }
3118*0b57cec5SDimitry Andric   case Instruction::VAArg:
3119*0b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_VAARG;
3120*0b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));   // valistty
3121*0b57cec5SDimitry Andric     pushValue(I.getOperand(0), InstID, Vals);                   // valist.
3122*0b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(I.getType())); // restype.
3123*0b57cec5SDimitry Andric     break;
3124480093f4SDimitry Andric   case Instruction::Freeze:
3125480093f4SDimitry Andric     Code = bitc::FUNC_CODE_INST_FREEZE;
3126480093f4SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals);
3127480093f4SDimitry Andric     break;
3128*0b57cec5SDimitry Andric   }
3129*0b57cec5SDimitry Andric 
3130*0b57cec5SDimitry Andric   Stream.EmitRecord(Code, Vals, AbbrevToUse);
3131*0b57cec5SDimitry Andric   Vals.clear();
3132*0b57cec5SDimitry Andric }
3133*0b57cec5SDimitry Andric 
3134*0b57cec5SDimitry Andric /// Write a GlobalValue VST to the module. The purpose of this data structure is
3135*0b57cec5SDimitry Andric /// to allow clients to efficiently find the function body.
3136*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
3137*0b57cec5SDimitry Andric   DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3138*0b57cec5SDimitry Andric   // Get the offset of the VST we are writing, and backpatch it into
3139*0b57cec5SDimitry Andric   // the VST forward declaration record.
3140*0b57cec5SDimitry Andric   uint64_t VSTOffset = Stream.GetCurrentBitNo();
3141*0b57cec5SDimitry Andric   // The BitcodeStartBit was the stream offset of the identification block.
3142*0b57cec5SDimitry Andric   VSTOffset -= bitcodeStartBit();
3143*0b57cec5SDimitry Andric   assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
3144*0b57cec5SDimitry Andric   // Note that we add 1 here because the offset is relative to one word
3145*0b57cec5SDimitry Andric   // before the start of the identification block, which was historically
3146*0b57cec5SDimitry Andric   // always the start of the regular bitcode header.
3147*0b57cec5SDimitry Andric   Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
3148*0b57cec5SDimitry Andric 
3149*0b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
3150*0b57cec5SDimitry Andric 
3151*0b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
3152*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
3153*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3154*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
3155*0b57cec5SDimitry Andric   unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3156*0b57cec5SDimitry Andric 
3157*0b57cec5SDimitry Andric   for (const Function &F : M) {
3158*0b57cec5SDimitry Andric     uint64_t Record[2];
3159*0b57cec5SDimitry Andric 
3160*0b57cec5SDimitry Andric     if (F.isDeclaration())
3161*0b57cec5SDimitry Andric       continue;
3162*0b57cec5SDimitry Andric 
3163*0b57cec5SDimitry Andric     Record[0] = VE.getValueID(&F);
3164*0b57cec5SDimitry Andric 
3165*0b57cec5SDimitry Andric     // Save the word offset of the function (from the start of the
3166*0b57cec5SDimitry Andric     // actual bitcode written to the stream).
3167*0b57cec5SDimitry Andric     uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit();
3168*0b57cec5SDimitry Andric     assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
3169*0b57cec5SDimitry Andric     // Note that we add 1 here because the offset is relative to one word
3170*0b57cec5SDimitry Andric     // before the start of the identification block, which was historically
3171*0b57cec5SDimitry Andric     // always the start of the regular bitcode header.
3172*0b57cec5SDimitry Andric     Record[1] = BitcodeIndex / 32 + 1;
3173*0b57cec5SDimitry Andric 
3174*0b57cec5SDimitry Andric     Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev);
3175*0b57cec5SDimitry Andric   }
3176*0b57cec5SDimitry Andric 
3177*0b57cec5SDimitry Andric   Stream.ExitBlock();
3178*0b57cec5SDimitry Andric }
3179*0b57cec5SDimitry Andric 
3180*0b57cec5SDimitry Andric /// Emit names for arguments, instructions and basic blocks in a function.
3181*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
3182*0b57cec5SDimitry Andric     const ValueSymbolTable &VST) {
3183*0b57cec5SDimitry Andric   if (VST.empty())
3184*0b57cec5SDimitry Andric     return;
3185*0b57cec5SDimitry Andric 
3186*0b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
3187*0b57cec5SDimitry Andric 
3188*0b57cec5SDimitry Andric   // FIXME: Set up the abbrev, we know how many values there are!
3189*0b57cec5SDimitry Andric   // FIXME: We know if the type names can use 7-bit ascii.
3190*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> NameVals;
3191*0b57cec5SDimitry Andric 
3192*0b57cec5SDimitry Andric   for (const ValueName &Name : VST) {
3193*0b57cec5SDimitry Andric     // Figure out the encoding to use for the name.
3194*0b57cec5SDimitry Andric     StringEncoding Bits = getStringEncoding(Name.getKey());
3195*0b57cec5SDimitry Andric 
3196*0b57cec5SDimitry Andric     unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
3197*0b57cec5SDimitry Andric     NameVals.push_back(VE.getValueID(Name.getValue()));
3198*0b57cec5SDimitry Andric 
3199*0b57cec5SDimitry Andric     // VST_CODE_ENTRY:   [valueid, namechar x N]
3200*0b57cec5SDimitry Andric     // VST_CODE_BBENTRY: [bbid, namechar x N]
3201*0b57cec5SDimitry Andric     unsigned Code;
3202*0b57cec5SDimitry Andric     if (isa<BasicBlock>(Name.getValue())) {
3203*0b57cec5SDimitry Andric       Code = bitc::VST_CODE_BBENTRY;
3204*0b57cec5SDimitry Andric       if (Bits == SE_Char6)
3205*0b57cec5SDimitry Andric         AbbrevToUse = VST_BBENTRY_6_ABBREV;
3206*0b57cec5SDimitry Andric     } else {
3207*0b57cec5SDimitry Andric       Code = bitc::VST_CODE_ENTRY;
3208*0b57cec5SDimitry Andric       if (Bits == SE_Char6)
3209*0b57cec5SDimitry Andric         AbbrevToUse = VST_ENTRY_6_ABBREV;
3210*0b57cec5SDimitry Andric       else if (Bits == SE_Fixed7)
3211*0b57cec5SDimitry Andric         AbbrevToUse = VST_ENTRY_7_ABBREV;
3212*0b57cec5SDimitry Andric     }
3213*0b57cec5SDimitry Andric 
3214*0b57cec5SDimitry Andric     for (const auto P : Name.getKey())
3215*0b57cec5SDimitry Andric       NameVals.push_back((unsigned char)P);
3216*0b57cec5SDimitry Andric 
3217*0b57cec5SDimitry Andric     // Emit the finished record.
3218*0b57cec5SDimitry Andric     Stream.EmitRecord(Code, NameVals, AbbrevToUse);
3219*0b57cec5SDimitry Andric     NameVals.clear();
3220*0b57cec5SDimitry Andric   }
3221*0b57cec5SDimitry Andric 
3222*0b57cec5SDimitry Andric   Stream.ExitBlock();
3223*0b57cec5SDimitry Andric }
3224*0b57cec5SDimitry Andric 
3225*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
3226*0b57cec5SDimitry Andric   assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
3227*0b57cec5SDimitry Andric   unsigned Code;
3228*0b57cec5SDimitry Andric   if (isa<BasicBlock>(Order.V))
3229*0b57cec5SDimitry Andric     Code = bitc::USELIST_CODE_BB;
3230*0b57cec5SDimitry Andric   else
3231*0b57cec5SDimitry Andric     Code = bitc::USELIST_CODE_DEFAULT;
3232*0b57cec5SDimitry Andric 
3233*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
3234*0b57cec5SDimitry Andric   Record.push_back(VE.getValueID(Order.V));
3235*0b57cec5SDimitry Andric   Stream.EmitRecord(Code, Record);
3236*0b57cec5SDimitry Andric }
3237*0b57cec5SDimitry Andric 
3238*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
3239*0b57cec5SDimitry Andric   assert(VE.shouldPreserveUseListOrder() &&
3240*0b57cec5SDimitry Andric          "Expected to be preserving use-list order");
3241*0b57cec5SDimitry Andric 
3242*0b57cec5SDimitry Andric   auto hasMore = [&]() {
3243*0b57cec5SDimitry Andric     return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
3244*0b57cec5SDimitry Andric   };
3245*0b57cec5SDimitry Andric   if (!hasMore())
3246*0b57cec5SDimitry Andric     // Nothing to do.
3247*0b57cec5SDimitry Andric     return;
3248*0b57cec5SDimitry Andric 
3249*0b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
3250*0b57cec5SDimitry Andric   while (hasMore()) {
3251*0b57cec5SDimitry Andric     writeUseList(std::move(VE.UseListOrders.back()));
3252*0b57cec5SDimitry Andric     VE.UseListOrders.pop_back();
3253*0b57cec5SDimitry Andric   }
3254*0b57cec5SDimitry Andric   Stream.ExitBlock();
3255*0b57cec5SDimitry Andric }
3256*0b57cec5SDimitry Andric 
3257*0b57cec5SDimitry Andric /// Emit a function body to the module stream.
3258*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeFunction(
3259*0b57cec5SDimitry Andric     const Function &F,
3260*0b57cec5SDimitry Andric     DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3261*0b57cec5SDimitry Andric   // Save the bitcode index of the start of this function block for recording
3262*0b57cec5SDimitry Andric   // in the VST.
3263*0b57cec5SDimitry Andric   FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
3264*0b57cec5SDimitry Andric 
3265*0b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
3266*0b57cec5SDimitry Andric   VE.incorporateFunction(F);
3267*0b57cec5SDimitry Andric 
3268*0b57cec5SDimitry Andric   SmallVector<unsigned, 64> Vals;
3269*0b57cec5SDimitry Andric 
3270*0b57cec5SDimitry Andric   // Emit the number of basic blocks, so the reader can create them ahead of
3271*0b57cec5SDimitry Andric   // time.
3272*0b57cec5SDimitry Andric   Vals.push_back(VE.getBasicBlocks().size());
3273*0b57cec5SDimitry Andric   Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
3274*0b57cec5SDimitry Andric   Vals.clear();
3275*0b57cec5SDimitry Andric 
3276*0b57cec5SDimitry Andric   // If there are function-local constants, emit them now.
3277*0b57cec5SDimitry Andric   unsigned CstStart, CstEnd;
3278*0b57cec5SDimitry Andric   VE.getFunctionConstantRange(CstStart, CstEnd);
3279*0b57cec5SDimitry Andric   writeConstants(CstStart, CstEnd, false);
3280*0b57cec5SDimitry Andric 
3281*0b57cec5SDimitry Andric   // If there is function-local metadata, emit it now.
3282*0b57cec5SDimitry Andric   writeFunctionMetadata(F);
3283*0b57cec5SDimitry Andric 
3284*0b57cec5SDimitry Andric   // Keep a running idea of what the instruction ID is.
3285*0b57cec5SDimitry Andric   unsigned InstID = CstEnd;
3286*0b57cec5SDimitry Andric 
3287*0b57cec5SDimitry Andric   bool NeedsMetadataAttachment = F.hasMetadata();
3288*0b57cec5SDimitry Andric 
3289*0b57cec5SDimitry Andric   DILocation *LastDL = nullptr;
3290*0b57cec5SDimitry Andric   // Finally, emit all the instructions, in order.
3291*0b57cec5SDimitry Andric   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
3292*0b57cec5SDimitry Andric     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
3293*0b57cec5SDimitry Andric          I != E; ++I) {
3294*0b57cec5SDimitry Andric       writeInstruction(*I, InstID, Vals);
3295*0b57cec5SDimitry Andric 
3296*0b57cec5SDimitry Andric       if (!I->getType()->isVoidTy())
3297*0b57cec5SDimitry Andric         ++InstID;
3298*0b57cec5SDimitry Andric 
3299*0b57cec5SDimitry Andric       // If the instruction has metadata, write a metadata attachment later.
3300*0b57cec5SDimitry Andric       NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
3301*0b57cec5SDimitry Andric 
3302*0b57cec5SDimitry Andric       // If the instruction has a debug location, emit it.
3303*0b57cec5SDimitry Andric       DILocation *DL = I->getDebugLoc();
3304*0b57cec5SDimitry Andric       if (!DL)
3305*0b57cec5SDimitry Andric         continue;
3306*0b57cec5SDimitry Andric 
3307*0b57cec5SDimitry Andric       if (DL == LastDL) {
3308*0b57cec5SDimitry Andric         // Just repeat the same debug loc as last time.
3309*0b57cec5SDimitry Andric         Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
3310*0b57cec5SDimitry Andric         continue;
3311*0b57cec5SDimitry Andric       }
3312*0b57cec5SDimitry Andric 
3313*0b57cec5SDimitry Andric       Vals.push_back(DL->getLine());
3314*0b57cec5SDimitry Andric       Vals.push_back(DL->getColumn());
3315*0b57cec5SDimitry Andric       Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
3316*0b57cec5SDimitry Andric       Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
3317*0b57cec5SDimitry Andric       Vals.push_back(DL->isImplicitCode());
3318*0b57cec5SDimitry Andric       Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
3319*0b57cec5SDimitry Andric       Vals.clear();
3320*0b57cec5SDimitry Andric 
3321*0b57cec5SDimitry Andric       LastDL = DL;
3322*0b57cec5SDimitry Andric     }
3323*0b57cec5SDimitry Andric 
3324*0b57cec5SDimitry Andric   // Emit names for all the instructions etc.
3325*0b57cec5SDimitry Andric   if (auto *Symtab = F.getValueSymbolTable())
3326*0b57cec5SDimitry Andric     writeFunctionLevelValueSymbolTable(*Symtab);
3327*0b57cec5SDimitry Andric 
3328*0b57cec5SDimitry Andric   if (NeedsMetadataAttachment)
3329*0b57cec5SDimitry Andric     writeFunctionMetadataAttachment(F);
3330*0b57cec5SDimitry Andric   if (VE.shouldPreserveUseListOrder())
3331*0b57cec5SDimitry Andric     writeUseListBlock(&F);
3332*0b57cec5SDimitry Andric   VE.purgeFunction();
3333*0b57cec5SDimitry Andric   Stream.ExitBlock();
3334*0b57cec5SDimitry Andric }
3335*0b57cec5SDimitry Andric 
3336*0b57cec5SDimitry Andric // Emit blockinfo, which defines the standard abbreviations etc.
3337*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeBlockInfo() {
3338*0b57cec5SDimitry Andric   // We only want to emit block info records for blocks that have multiple
3339*0b57cec5SDimitry Andric   // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
3340*0b57cec5SDimitry Andric   // Other blocks can define their abbrevs inline.
3341*0b57cec5SDimitry Andric   Stream.EnterBlockInfoBlock();
3342*0b57cec5SDimitry Andric 
3343*0b57cec5SDimitry Andric   { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
3344*0b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
3345*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
3346*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3347*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3348*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
3349*0b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3350*0b57cec5SDimitry Andric         VST_ENTRY_8_ABBREV)
3351*0b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
3352*0b57cec5SDimitry Andric   }
3353*0b57cec5SDimitry Andric 
3354*0b57cec5SDimitry Andric   { // 7-bit fixed width VST_CODE_ENTRY strings.
3355*0b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
3356*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
3357*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3358*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3359*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
3360*0b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3361*0b57cec5SDimitry Andric         VST_ENTRY_7_ABBREV)
3362*0b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
3363*0b57cec5SDimitry Andric   }
3364*0b57cec5SDimitry Andric   { // 6-bit char6 VST_CODE_ENTRY strings.
3365*0b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
3366*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
3367*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3368*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3369*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3370*0b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3371*0b57cec5SDimitry Andric         VST_ENTRY_6_ABBREV)
3372*0b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
3373*0b57cec5SDimitry Andric   }
3374*0b57cec5SDimitry Andric   { // 6-bit char6 VST_CODE_BBENTRY strings.
3375*0b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
3376*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
3377*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3378*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3379*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3380*0b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3381*0b57cec5SDimitry Andric         VST_BBENTRY_6_ABBREV)
3382*0b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
3383*0b57cec5SDimitry Andric   }
3384*0b57cec5SDimitry Andric 
3385*0b57cec5SDimitry Andric   { // SETTYPE abbrev for CONSTANTS_BLOCK.
3386*0b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
3387*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
3388*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
3389*0b57cec5SDimitry Andric                               VE.computeBitsRequiredForTypeIndicies()));
3390*0b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3391*0b57cec5SDimitry Andric         CONSTANTS_SETTYPE_ABBREV)
3392*0b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
3393*0b57cec5SDimitry Andric   }
3394*0b57cec5SDimitry Andric 
3395*0b57cec5SDimitry Andric   { // INTEGER abbrev for CONSTANTS_BLOCK.
3396*0b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
3397*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
3398*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3399*0b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3400*0b57cec5SDimitry Andric         CONSTANTS_INTEGER_ABBREV)
3401*0b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
3402*0b57cec5SDimitry Andric   }
3403*0b57cec5SDimitry Andric 
3404*0b57cec5SDimitry Andric   { // CE_CAST abbrev for CONSTANTS_BLOCK.
3405*0b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
3406*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
3407*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // cast opc
3408*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // typeid
3409*0b57cec5SDimitry Andric                               VE.computeBitsRequiredForTypeIndicies()));
3410*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));    // value id
3411*0b57cec5SDimitry Andric 
3412*0b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3413*0b57cec5SDimitry Andric         CONSTANTS_CE_CAST_Abbrev)
3414*0b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
3415*0b57cec5SDimitry Andric   }
3416*0b57cec5SDimitry Andric   { // NULL abbrev for CONSTANTS_BLOCK.
3417*0b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
3418*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
3419*0b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3420*0b57cec5SDimitry Andric         CONSTANTS_NULL_Abbrev)
3421*0b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
3422*0b57cec5SDimitry Andric   }
3423*0b57cec5SDimitry Andric 
3424*0b57cec5SDimitry Andric   // FIXME: This should only use space for first class types!
3425*0b57cec5SDimitry Andric 
3426*0b57cec5SDimitry Andric   { // INST_LOAD abbrev for FUNCTION_BLOCK.
3427*0b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
3428*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
3429*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
3430*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,    // dest ty
3431*0b57cec5SDimitry Andric                               VE.computeBitsRequiredForTypeIndicies()));
3432*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
3433*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
3434*0b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3435*0b57cec5SDimitry Andric         FUNCTION_INST_LOAD_ABBREV)
3436*0b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
3437*0b57cec5SDimitry Andric   }
3438*0b57cec5SDimitry Andric   { // INST_UNOP abbrev for FUNCTION_BLOCK.
3439*0b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
3440*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP));
3441*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3442*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3443*0b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3444*0b57cec5SDimitry Andric         FUNCTION_INST_UNOP_ABBREV)
3445*0b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
3446*0b57cec5SDimitry Andric   }
3447*0b57cec5SDimitry Andric   { // INST_UNOP_FLAGS abbrev for FUNCTION_BLOCK.
3448*0b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
3449*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP));
3450*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3451*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3452*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
3453*0b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3454*0b57cec5SDimitry Andric         FUNCTION_INST_UNOP_FLAGS_ABBREV)
3455*0b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
3456*0b57cec5SDimitry Andric   }
3457*0b57cec5SDimitry Andric   { // INST_BINOP abbrev for FUNCTION_BLOCK.
3458*0b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
3459*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3460*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3461*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3462*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3463*0b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3464*0b57cec5SDimitry Andric         FUNCTION_INST_BINOP_ABBREV)
3465*0b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
3466*0b57cec5SDimitry Andric   }
3467*0b57cec5SDimitry Andric   { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
3468*0b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
3469*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3470*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3471*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3472*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3473*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
3474*0b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3475*0b57cec5SDimitry Andric         FUNCTION_INST_BINOP_FLAGS_ABBREV)
3476*0b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
3477*0b57cec5SDimitry Andric   }
3478*0b57cec5SDimitry Andric   { // INST_CAST abbrev for FUNCTION_BLOCK.
3479*0b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
3480*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
3481*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));    // OpVal
3482*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // dest ty
3483*0b57cec5SDimitry Andric                               VE.computeBitsRequiredForTypeIndicies()));
3484*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // opc
3485*0b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3486*0b57cec5SDimitry Andric         FUNCTION_INST_CAST_ABBREV)
3487*0b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
3488*0b57cec5SDimitry Andric   }
3489*0b57cec5SDimitry Andric 
3490*0b57cec5SDimitry Andric   { // INST_RET abbrev for FUNCTION_BLOCK.
3491*0b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
3492*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
3493*0b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3494*0b57cec5SDimitry Andric         FUNCTION_INST_RET_VOID_ABBREV)
3495*0b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
3496*0b57cec5SDimitry Andric   }
3497*0b57cec5SDimitry Andric   { // INST_RET abbrev for FUNCTION_BLOCK.
3498*0b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
3499*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
3500*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
3501*0b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3502*0b57cec5SDimitry Andric         FUNCTION_INST_RET_VAL_ABBREV)
3503*0b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
3504*0b57cec5SDimitry Andric   }
3505*0b57cec5SDimitry Andric   { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
3506*0b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
3507*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
3508*0b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3509*0b57cec5SDimitry Andric         FUNCTION_INST_UNREACHABLE_ABBREV)
3510*0b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
3511*0b57cec5SDimitry Andric   }
3512*0b57cec5SDimitry Andric   {
3513*0b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
3514*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
3515*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
3516*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3517*0b57cec5SDimitry Andric                               Log2_32_Ceil(VE.getTypes().size() + 1)));
3518*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3519*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
3520*0b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3521*0b57cec5SDimitry Andric         FUNCTION_INST_GEP_ABBREV)
3522*0b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
3523*0b57cec5SDimitry Andric   }
3524*0b57cec5SDimitry Andric 
3525*0b57cec5SDimitry Andric   Stream.ExitBlock();
3526*0b57cec5SDimitry Andric }
3527*0b57cec5SDimitry Andric 
3528*0b57cec5SDimitry Andric /// Write the module path strings, currently only used when generating
3529*0b57cec5SDimitry Andric /// a combined index file.
3530*0b57cec5SDimitry Andric void IndexBitcodeWriter::writeModStrings() {
3531*0b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);
3532*0b57cec5SDimitry Andric 
3533*0b57cec5SDimitry Andric   // TODO: See which abbrev sizes we actually need to emit
3534*0b57cec5SDimitry Andric 
3535*0b57cec5SDimitry Andric   // 8-bit fixed-width MST_ENTRY strings.
3536*0b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
3537*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3538*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3539*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3540*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
3541*0b57cec5SDimitry Andric   unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
3542*0b57cec5SDimitry Andric 
3543*0b57cec5SDimitry Andric   // 7-bit fixed width MST_ENTRY strings.
3544*0b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
3545*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3546*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3547*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3548*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
3549*0b57cec5SDimitry Andric   unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
3550*0b57cec5SDimitry Andric 
3551*0b57cec5SDimitry Andric   // 6-bit char6 MST_ENTRY strings.
3552*0b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
3553*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3554*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3555*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3556*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3557*0b57cec5SDimitry Andric   unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
3558*0b57cec5SDimitry Andric 
3559*0b57cec5SDimitry Andric   // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
3560*0b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
3561*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH));
3562*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3563*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3564*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3565*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3566*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3567*0b57cec5SDimitry Andric   unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
3568*0b57cec5SDimitry Andric 
3569*0b57cec5SDimitry Andric   SmallVector<unsigned, 64> Vals;
3570*0b57cec5SDimitry Andric   forEachModule(
3571*0b57cec5SDimitry Andric       [&](const StringMapEntry<std::pair<uint64_t, ModuleHash>> &MPSE) {
3572*0b57cec5SDimitry Andric         StringRef Key = MPSE.getKey();
3573*0b57cec5SDimitry Andric         const auto &Value = MPSE.getValue();
3574*0b57cec5SDimitry Andric         StringEncoding Bits = getStringEncoding(Key);
3575*0b57cec5SDimitry Andric         unsigned AbbrevToUse = Abbrev8Bit;
3576*0b57cec5SDimitry Andric         if (Bits == SE_Char6)
3577*0b57cec5SDimitry Andric           AbbrevToUse = Abbrev6Bit;
3578*0b57cec5SDimitry Andric         else if (Bits == SE_Fixed7)
3579*0b57cec5SDimitry Andric           AbbrevToUse = Abbrev7Bit;
3580*0b57cec5SDimitry Andric 
3581*0b57cec5SDimitry Andric         Vals.push_back(Value.first);
3582*0b57cec5SDimitry Andric         Vals.append(Key.begin(), Key.end());
3583*0b57cec5SDimitry Andric 
3584*0b57cec5SDimitry Andric         // Emit the finished record.
3585*0b57cec5SDimitry Andric         Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
3586*0b57cec5SDimitry Andric 
3587*0b57cec5SDimitry Andric         // Emit an optional hash for the module now
3588*0b57cec5SDimitry Andric         const auto &Hash = Value.second;
3589*0b57cec5SDimitry Andric         if (llvm::any_of(Hash, [](uint32_t H) { return H; })) {
3590*0b57cec5SDimitry Andric           Vals.assign(Hash.begin(), Hash.end());
3591*0b57cec5SDimitry Andric           // Emit the hash record.
3592*0b57cec5SDimitry Andric           Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
3593*0b57cec5SDimitry Andric         }
3594*0b57cec5SDimitry Andric 
3595*0b57cec5SDimitry Andric         Vals.clear();
3596*0b57cec5SDimitry Andric       });
3597*0b57cec5SDimitry Andric   Stream.ExitBlock();
3598*0b57cec5SDimitry Andric }
3599*0b57cec5SDimitry Andric 
3600*0b57cec5SDimitry Andric /// Write the function type metadata related records that need to appear before
3601*0b57cec5SDimitry Andric /// a function summary entry (whether per-module or combined).
3602e8d8bef9SDimitry Andric template <typename Fn>
3603*0b57cec5SDimitry Andric static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream,
3604e8d8bef9SDimitry Andric                                              FunctionSummary *FS,
3605e8d8bef9SDimitry Andric                                              Fn GetValueID) {
3606*0b57cec5SDimitry Andric   if (!FS->type_tests().empty())
3607*0b57cec5SDimitry Andric     Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
3608*0b57cec5SDimitry Andric 
3609*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
3610*0b57cec5SDimitry Andric 
3611*0b57cec5SDimitry Andric   auto WriteVFuncIdVec = [&](uint64_t Ty,
3612*0b57cec5SDimitry Andric                              ArrayRef<FunctionSummary::VFuncId> VFs) {
3613*0b57cec5SDimitry Andric     if (VFs.empty())
3614*0b57cec5SDimitry Andric       return;
3615*0b57cec5SDimitry Andric     Record.clear();
3616*0b57cec5SDimitry Andric     for (auto &VF : VFs) {
3617*0b57cec5SDimitry Andric       Record.push_back(VF.GUID);
3618*0b57cec5SDimitry Andric       Record.push_back(VF.Offset);
3619*0b57cec5SDimitry Andric     }
3620*0b57cec5SDimitry Andric     Stream.EmitRecord(Ty, Record);
3621*0b57cec5SDimitry Andric   };
3622*0b57cec5SDimitry Andric 
3623*0b57cec5SDimitry Andric   WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
3624*0b57cec5SDimitry Andric                   FS->type_test_assume_vcalls());
3625*0b57cec5SDimitry Andric   WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
3626*0b57cec5SDimitry Andric                   FS->type_checked_load_vcalls());
3627*0b57cec5SDimitry Andric 
3628*0b57cec5SDimitry Andric   auto WriteConstVCallVec = [&](uint64_t Ty,
3629*0b57cec5SDimitry Andric                                 ArrayRef<FunctionSummary::ConstVCall> VCs) {
3630*0b57cec5SDimitry Andric     for (auto &VC : VCs) {
3631*0b57cec5SDimitry Andric       Record.clear();
3632*0b57cec5SDimitry Andric       Record.push_back(VC.VFunc.GUID);
3633*0b57cec5SDimitry Andric       Record.push_back(VC.VFunc.Offset);
3634e8d8bef9SDimitry Andric       llvm::append_range(Record, VC.Args);
3635*0b57cec5SDimitry Andric       Stream.EmitRecord(Ty, Record);
3636*0b57cec5SDimitry Andric     }
3637*0b57cec5SDimitry Andric   };
3638*0b57cec5SDimitry Andric 
3639*0b57cec5SDimitry Andric   WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
3640*0b57cec5SDimitry Andric                      FS->type_test_assume_const_vcalls());
3641*0b57cec5SDimitry Andric   WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
3642*0b57cec5SDimitry Andric                      FS->type_checked_load_const_vcalls());
36435ffd83dbSDimitry Andric 
36445ffd83dbSDimitry Andric   auto WriteRange = [&](ConstantRange Range) {
36455ffd83dbSDimitry Andric     Range = Range.sextOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
36465ffd83dbSDimitry Andric     assert(Range.getLower().getNumWords() == 1);
36475ffd83dbSDimitry Andric     assert(Range.getUpper().getNumWords() == 1);
36485ffd83dbSDimitry Andric     emitSignedInt64(Record, *Range.getLower().getRawData());
36495ffd83dbSDimitry Andric     emitSignedInt64(Record, *Range.getUpper().getRawData());
36505ffd83dbSDimitry Andric   };
36515ffd83dbSDimitry Andric 
36525ffd83dbSDimitry Andric   if (!FS->paramAccesses().empty()) {
36535ffd83dbSDimitry Andric     Record.clear();
36545ffd83dbSDimitry Andric     for (auto &Arg : FS->paramAccesses()) {
3655e8d8bef9SDimitry Andric       size_t UndoSize = Record.size();
36565ffd83dbSDimitry Andric       Record.push_back(Arg.ParamNo);
36575ffd83dbSDimitry Andric       WriteRange(Arg.Use);
36585ffd83dbSDimitry Andric       Record.push_back(Arg.Calls.size());
36595ffd83dbSDimitry Andric       for (auto &Call : Arg.Calls) {
36605ffd83dbSDimitry Andric         Record.push_back(Call.ParamNo);
3661e8d8bef9SDimitry Andric         Optional<unsigned> ValueID = GetValueID(Call.Callee);
3662e8d8bef9SDimitry Andric         if (!ValueID) {
3663e8d8bef9SDimitry Andric           // If ValueID is unknown we can't drop just this call, we must drop
3664e8d8bef9SDimitry Andric           // entire parameter.
3665e8d8bef9SDimitry Andric           Record.resize(UndoSize);
3666e8d8bef9SDimitry Andric           break;
3667e8d8bef9SDimitry Andric         }
3668e8d8bef9SDimitry Andric         Record.push_back(*ValueID);
36695ffd83dbSDimitry Andric         WriteRange(Call.Offsets);
36705ffd83dbSDimitry Andric       }
36715ffd83dbSDimitry Andric     }
3672e8d8bef9SDimitry Andric     if (!Record.empty())
36735ffd83dbSDimitry Andric       Stream.EmitRecord(bitc::FS_PARAM_ACCESS, Record);
36745ffd83dbSDimitry Andric   }
3675*0b57cec5SDimitry Andric }
3676*0b57cec5SDimitry Andric 
3677*0b57cec5SDimitry Andric /// Collect type IDs from type tests used by function.
3678*0b57cec5SDimitry Andric static void
3679*0b57cec5SDimitry Andric getReferencedTypeIds(FunctionSummary *FS,
3680*0b57cec5SDimitry Andric                      std::set<GlobalValue::GUID> &ReferencedTypeIds) {
3681*0b57cec5SDimitry Andric   if (!FS->type_tests().empty())
3682*0b57cec5SDimitry Andric     for (auto &TT : FS->type_tests())
3683*0b57cec5SDimitry Andric       ReferencedTypeIds.insert(TT);
3684*0b57cec5SDimitry Andric 
3685*0b57cec5SDimitry Andric   auto GetReferencedTypesFromVFuncIdVec =
3686*0b57cec5SDimitry Andric       [&](ArrayRef<FunctionSummary::VFuncId> VFs) {
3687*0b57cec5SDimitry Andric         for (auto &VF : VFs)
3688*0b57cec5SDimitry Andric           ReferencedTypeIds.insert(VF.GUID);
3689*0b57cec5SDimitry Andric       };
3690*0b57cec5SDimitry Andric 
3691*0b57cec5SDimitry Andric   GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls());
3692*0b57cec5SDimitry Andric   GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls());
3693*0b57cec5SDimitry Andric 
3694*0b57cec5SDimitry Andric   auto GetReferencedTypesFromConstVCallVec =
3695*0b57cec5SDimitry Andric       [&](ArrayRef<FunctionSummary::ConstVCall> VCs) {
3696*0b57cec5SDimitry Andric         for (auto &VC : VCs)
3697*0b57cec5SDimitry Andric           ReferencedTypeIds.insert(VC.VFunc.GUID);
3698*0b57cec5SDimitry Andric       };
3699*0b57cec5SDimitry Andric 
3700*0b57cec5SDimitry Andric   GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls());
3701*0b57cec5SDimitry Andric   GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls());
3702*0b57cec5SDimitry Andric }
3703*0b57cec5SDimitry Andric 
3704*0b57cec5SDimitry Andric static void writeWholeProgramDevirtResolutionByArg(
3705*0b57cec5SDimitry Andric     SmallVector<uint64_t, 64> &NameVals, const std::vector<uint64_t> &args,
3706*0b57cec5SDimitry Andric     const WholeProgramDevirtResolution::ByArg &ByArg) {
3707*0b57cec5SDimitry Andric   NameVals.push_back(args.size());
3708e8d8bef9SDimitry Andric   llvm::append_range(NameVals, args);
3709*0b57cec5SDimitry Andric 
3710*0b57cec5SDimitry Andric   NameVals.push_back(ByArg.TheKind);
3711*0b57cec5SDimitry Andric   NameVals.push_back(ByArg.Info);
3712*0b57cec5SDimitry Andric   NameVals.push_back(ByArg.Byte);
3713*0b57cec5SDimitry Andric   NameVals.push_back(ByArg.Bit);
3714*0b57cec5SDimitry Andric }
3715*0b57cec5SDimitry Andric 
3716*0b57cec5SDimitry Andric static void writeWholeProgramDevirtResolution(
3717*0b57cec5SDimitry Andric     SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
3718*0b57cec5SDimitry Andric     uint64_t Id, const WholeProgramDevirtResolution &Wpd) {
3719*0b57cec5SDimitry Andric   NameVals.push_back(Id);
3720*0b57cec5SDimitry Andric 
3721*0b57cec5SDimitry Andric   NameVals.push_back(Wpd.TheKind);
3722*0b57cec5SDimitry Andric   NameVals.push_back(StrtabBuilder.add(Wpd.SingleImplName));
3723*0b57cec5SDimitry Andric   NameVals.push_back(Wpd.SingleImplName.size());
3724*0b57cec5SDimitry Andric 
3725*0b57cec5SDimitry Andric   NameVals.push_back(Wpd.ResByArg.size());
3726*0b57cec5SDimitry Andric   for (auto &A : Wpd.ResByArg)
3727*0b57cec5SDimitry Andric     writeWholeProgramDevirtResolutionByArg(NameVals, A.first, A.second);
3728*0b57cec5SDimitry Andric }
3729*0b57cec5SDimitry Andric 
3730*0b57cec5SDimitry Andric static void writeTypeIdSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
3731*0b57cec5SDimitry Andric                                      StringTableBuilder &StrtabBuilder,
3732*0b57cec5SDimitry Andric                                      const std::string &Id,
3733*0b57cec5SDimitry Andric                                      const TypeIdSummary &Summary) {
3734*0b57cec5SDimitry Andric   NameVals.push_back(StrtabBuilder.add(Id));
3735*0b57cec5SDimitry Andric   NameVals.push_back(Id.size());
3736*0b57cec5SDimitry Andric 
3737*0b57cec5SDimitry Andric   NameVals.push_back(Summary.TTRes.TheKind);
3738*0b57cec5SDimitry Andric   NameVals.push_back(Summary.TTRes.SizeM1BitWidth);
3739*0b57cec5SDimitry Andric   NameVals.push_back(Summary.TTRes.AlignLog2);
3740*0b57cec5SDimitry Andric   NameVals.push_back(Summary.TTRes.SizeM1);
3741*0b57cec5SDimitry Andric   NameVals.push_back(Summary.TTRes.BitMask);
3742*0b57cec5SDimitry Andric   NameVals.push_back(Summary.TTRes.InlineBits);
3743*0b57cec5SDimitry Andric 
3744*0b57cec5SDimitry Andric   for (auto &W : Summary.WPDRes)
3745*0b57cec5SDimitry Andric     writeWholeProgramDevirtResolution(NameVals, StrtabBuilder, W.first,
3746*0b57cec5SDimitry Andric                                       W.second);
3747*0b57cec5SDimitry Andric }
3748*0b57cec5SDimitry Andric 
3749*0b57cec5SDimitry Andric static void writeTypeIdCompatibleVtableSummaryRecord(
3750*0b57cec5SDimitry Andric     SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
3751*0b57cec5SDimitry Andric     const std::string &Id, const TypeIdCompatibleVtableInfo &Summary,
3752*0b57cec5SDimitry Andric     ValueEnumerator &VE) {
3753*0b57cec5SDimitry Andric   NameVals.push_back(StrtabBuilder.add(Id));
3754*0b57cec5SDimitry Andric   NameVals.push_back(Id.size());
3755*0b57cec5SDimitry Andric 
3756*0b57cec5SDimitry Andric   for (auto &P : Summary) {
3757*0b57cec5SDimitry Andric     NameVals.push_back(P.AddressPointOffset);
3758*0b57cec5SDimitry Andric     NameVals.push_back(VE.getValueID(P.VTableVI.getValue()));
3759*0b57cec5SDimitry Andric   }
3760*0b57cec5SDimitry Andric }
3761*0b57cec5SDimitry Andric 
3762*0b57cec5SDimitry Andric // Helper to emit a single function summary record.
3763*0b57cec5SDimitry Andric void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
3764*0b57cec5SDimitry Andric     SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
3765*0b57cec5SDimitry Andric     unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
3766*0b57cec5SDimitry Andric     const Function &F) {
3767*0b57cec5SDimitry Andric   NameVals.push_back(ValueID);
3768*0b57cec5SDimitry Andric 
3769*0b57cec5SDimitry Andric   FunctionSummary *FS = cast<FunctionSummary>(Summary);
3770e8d8bef9SDimitry Andric 
3771e8d8bef9SDimitry Andric   writeFunctionTypeMetadataRecords(
3772e8d8bef9SDimitry Andric       Stream, FS, [&](const ValueInfo &VI) -> Optional<unsigned> {
3773e8d8bef9SDimitry Andric         return {VE.getValueID(VI.getValue())};
3774e8d8bef9SDimitry Andric       });
3775*0b57cec5SDimitry Andric 
3776*0b57cec5SDimitry Andric   auto SpecialRefCnts = FS->specialRefCounts();
3777*0b57cec5SDimitry Andric   NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
3778*0b57cec5SDimitry Andric   NameVals.push_back(FS->instCount());
3779*0b57cec5SDimitry Andric   NameVals.push_back(getEncodedFFlags(FS->fflags()));
3780*0b57cec5SDimitry Andric   NameVals.push_back(FS->refs().size());
3781*0b57cec5SDimitry Andric   NameVals.push_back(SpecialRefCnts.first);  // rorefcnt
3782*0b57cec5SDimitry Andric   NameVals.push_back(SpecialRefCnts.second); // worefcnt
3783*0b57cec5SDimitry Andric 
3784*0b57cec5SDimitry Andric   for (auto &RI : FS->refs())
3785*0b57cec5SDimitry Andric     NameVals.push_back(VE.getValueID(RI.getValue()));
3786*0b57cec5SDimitry Andric 
3787*0b57cec5SDimitry Andric   bool HasProfileData =
3788*0b57cec5SDimitry Andric       F.hasProfileData() || ForceSummaryEdgesCold != FunctionSummary::FSHT_None;
3789*0b57cec5SDimitry Andric   for (auto &ECI : FS->calls()) {
3790*0b57cec5SDimitry Andric     NameVals.push_back(getValueId(ECI.first));
3791*0b57cec5SDimitry Andric     if (HasProfileData)
3792*0b57cec5SDimitry Andric       NameVals.push_back(static_cast<uint8_t>(ECI.second.Hotness));
3793*0b57cec5SDimitry Andric     else if (WriteRelBFToSummary)
3794*0b57cec5SDimitry Andric       NameVals.push_back(ECI.second.RelBlockFreq);
3795*0b57cec5SDimitry Andric   }
3796*0b57cec5SDimitry Andric 
3797*0b57cec5SDimitry Andric   unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3798*0b57cec5SDimitry Andric   unsigned Code =
3799*0b57cec5SDimitry Andric       (HasProfileData ? bitc::FS_PERMODULE_PROFILE
3800*0b57cec5SDimitry Andric                       : (WriteRelBFToSummary ? bitc::FS_PERMODULE_RELBF
3801*0b57cec5SDimitry Andric                                              : bitc::FS_PERMODULE));
3802*0b57cec5SDimitry Andric 
3803*0b57cec5SDimitry Andric   // Emit the finished record.
3804*0b57cec5SDimitry Andric   Stream.EmitRecord(Code, NameVals, FSAbbrev);
3805*0b57cec5SDimitry Andric   NameVals.clear();
3806*0b57cec5SDimitry Andric }
3807*0b57cec5SDimitry Andric 
3808*0b57cec5SDimitry Andric // Collect the global value references in the given variable's initializer,
3809*0b57cec5SDimitry Andric // and emit them in a summary record.
3810*0b57cec5SDimitry Andric void ModuleBitcodeWriterBase::writeModuleLevelReferences(
3811*0b57cec5SDimitry Andric     const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
3812*0b57cec5SDimitry Andric     unsigned FSModRefsAbbrev, unsigned FSModVTableRefsAbbrev) {
3813*0b57cec5SDimitry Andric   auto VI = Index->getValueInfo(V.getGUID());
3814*0b57cec5SDimitry Andric   if (!VI || VI.getSummaryList().empty()) {
3815*0b57cec5SDimitry Andric     // Only declarations should not have a summary (a declaration might however
3816*0b57cec5SDimitry Andric     // have a summary if the def was in module level asm).
3817*0b57cec5SDimitry Andric     assert(V.isDeclaration());
3818*0b57cec5SDimitry Andric     return;
3819*0b57cec5SDimitry Andric   }
3820*0b57cec5SDimitry Andric   auto *Summary = VI.getSummaryList()[0].get();
3821*0b57cec5SDimitry Andric   NameVals.push_back(VE.getValueID(&V));
3822*0b57cec5SDimitry Andric   GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
3823*0b57cec5SDimitry Andric   NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
3824*0b57cec5SDimitry Andric   NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
3825*0b57cec5SDimitry Andric 
3826*0b57cec5SDimitry Andric   auto VTableFuncs = VS->vTableFuncs();
3827*0b57cec5SDimitry Andric   if (!VTableFuncs.empty())
3828*0b57cec5SDimitry Andric     NameVals.push_back(VS->refs().size());
3829*0b57cec5SDimitry Andric 
3830*0b57cec5SDimitry Andric   unsigned SizeBeforeRefs = NameVals.size();
3831*0b57cec5SDimitry Andric   for (auto &RI : VS->refs())
3832*0b57cec5SDimitry Andric     NameVals.push_back(VE.getValueID(RI.getValue()));
3833*0b57cec5SDimitry Andric   // Sort the refs for determinism output, the vector returned by FS->refs() has
3834*0b57cec5SDimitry Andric   // been initialized from a DenseSet.
3835e8d8bef9SDimitry Andric   llvm::sort(drop_begin(NameVals, SizeBeforeRefs));
3836*0b57cec5SDimitry Andric 
3837*0b57cec5SDimitry Andric   if (VTableFuncs.empty())
3838*0b57cec5SDimitry Andric     Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals,
3839*0b57cec5SDimitry Andric                       FSModRefsAbbrev);
3840*0b57cec5SDimitry Andric   else {
3841*0b57cec5SDimitry Andric     // VTableFuncs pairs should already be sorted by offset.
3842*0b57cec5SDimitry Andric     for (auto &P : VTableFuncs) {
3843*0b57cec5SDimitry Andric       NameVals.push_back(VE.getValueID(P.FuncVI.getValue()));
3844*0b57cec5SDimitry Andric       NameVals.push_back(P.VTableOffset);
3845*0b57cec5SDimitry Andric     }
3846*0b57cec5SDimitry Andric 
3847*0b57cec5SDimitry Andric     Stream.EmitRecord(bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS, NameVals,
3848*0b57cec5SDimitry Andric                       FSModVTableRefsAbbrev);
3849*0b57cec5SDimitry Andric   }
3850*0b57cec5SDimitry Andric   NameVals.clear();
3851*0b57cec5SDimitry Andric }
3852*0b57cec5SDimitry Andric 
3853*0b57cec5SDimitry Andric /// Emit the per-module summary section alongside the rest of
3854*0b57cec5SDimitry Andric /// the module's bitcode.
3855*0b57cec5SDimitry Andric void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
3856*0b57cec5SDimitry Andric   // By default we compile with ThinLTO if the module has a summary, but the
3857*0b57cec5SDimitry Andric   // client can request full LTO with a module flag.
3858*0b57cec5SDimitry Andric   bool IsThinLTO = true;
3859*0b57cec5SDimitry Andric   if (auto *MD =
3860*0b57cec5SDimitry Andric           mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
3861*0b57cec5SDimitry Andric     IsThinLTO = MD->getZExtValue();
3862*0b57cec5SDimitry Andric   Stream.EnterSubblock(IsThinLTO ? bitc::GLOBALVAL_SUMMARY_BLOCK_ID
3863*0b57cec5SDimitry Andric                                  : bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID,
3864*0b57cec5SDimitry Andric                        4);
3865*0b57cec5SDimitry Andric 
3866480093f4SDimitry Andric   Stream.EmitRecord(
3867480093f4SDimitry Andric       bitc::FS_VERSION,
3868480093f4SDimitry Andric       ArrayRef<uint64_t>{ModuleSummaryIndex::BitcodeSummaryVersion});
3869*0b57cec5SDimitry Andric 
3870*0b57cec5SDimitry Andric   // Write the index flags.
3871*0b57cec5SDimitry Andric   uint64_t Flags = 0;
3872*0b57cec5SDimitry Andric   // Bits 1-3 are set only in the combined index, skip them.
3873*0b57cec5SDimitry Andric   if (Index->enableSplitLTOUnit())
3874*0b57cec5SDimitry Andric     Flags |= 0x8;
3875*0b57cec5SDimitry Andric   Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Flags});
3876*0b57cec5SDimitry Andric 
3877*0b57cec5SDimitry Andric   if (Index->begin() == Index->end()) {
3878*0b57cec5SDimitry Andric     Stream.ExitBlock();
3879*0b57cec5SDimitry Andric     return;
3880*0b57cec5SDimitry Andric   }
3881*0b57cec5SDimitry Andric 
3882*0b57cec5SDimitry Andric   for (const auto &GVI : valueIds()) {
3883*0b57cec5SDimitry Andric     Stream.EmitRecord(bitc::FS_VALUE_GUID,
3884*0b57cec5SDimitry Andric                       ArrayRef<uint64_t>{GVI.second, GVI.first});
3885*0b57cec5SDimitry Andric   }
3886*0b57cec5SDimitry Andric 
3887*0b57cec5SDimitry Andric   // Abbrev for FS_PERMODULE_PROFILE.
3888*0b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
3889*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));
3890*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3891*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
3892*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
3893*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // fflags
3894*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
3895*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // rorefcnt
3896*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // worefcnt
3897*0b57cec5SDimitry Andric   // numrefs x valueid, n x (valueid, hotness)
3898*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3899*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3900*0b57cec5SDimitry Andric   unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3901*0b57cec5SDimitry Andric 
3902*0b57cec5SDimitry Andric   // Abbrev for FS_PERMODULE or FS_PERMODULE_RELBF.
3903*0b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
3904*0b57cec5SDimitry Andric   if (WriteRelBFToSummary)
3905*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_RELBF));
3906*0b57cec5SDimitry Andric   else
3907*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE));
3908*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3909*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
3910*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
3911*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // fflags
3912*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
3913*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // rorefcnt
3914*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // worefcnt
3915*0b57cec5SDimitry Andric   // numrefs x valueid, n x (valueid [, rel_block_freq])
3916*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3917*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3918*0b57cec5SDimitry Andric   unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3919*0b57cec5SDimitry Andric 
3920*0b57cec5SDimitry Andric   // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
3921*0b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
3922*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));
3923*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3924*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3925*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));  // valueids
3926*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3927*0b57cec5SDimitry Andric   unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3928*0b57cec5SDimitry Andric 
3929*0b57cec5SDimitry Andric   // Abbrev for FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS.
3930*0b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
3931*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS));
3932*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3933*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3934*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3935*0b57cec5SDimitry Andric   // numrefs x valueid, n x (valueid , offset)
3936*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3937*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3938*0b57cec5SDimitry Andric   unsigned FSModVTableRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3939*0b57cec5SDimitry Andric 
3940*0b57cec5SDimitry Andric   // Abbrev for FS_ALIAS.
3941*0b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
3942*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
3943*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3944*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
3945*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3946*0b57cec5SDimitry Andric   unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3947*0b57cec5SDimitry Andric 
3948*0b57cec5SDimitry Andric   // Abbrev for FS_TYPE_ID_METADATA
3949*0b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
3950*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::FS_TYPE_ID_METADATA));
3951*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid strtab index
3952*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid length
3953*0b57cec5SDimitry Andric   // n x (valueid , offset)
3954*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3955*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3956*0b57cec5SDimitry Andric   unsigned TypeIdCompatibleVtableAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3957*0b57cec5SDimitry Andric 
3958*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> NameVals;
3959*0b57cec5SDimitry Andric   // Iterate over the list of functions instead of the Index to
3960*0b57cec5SDimitry Andric   // ensure the ordering is stable.
3961*0b57cec5SDimitry Andric   for (const Function &F : M) {
3962*0b57cec5SDimitry Andric     // Summary emission does not support anonymous functions, they have to
3963*0b57cec5SDimitry Andric     // renamed using the anonymous function renaming pass.
3964*0b57cec5SDimitry Andric     if (!F.hasName())
3965*0b57cec5SDimitry Andric       report_fatal_error("Unexpected anonymous function when writing summary");
3966*0b57cec5SDimitry Andric 
3967*0b57cec5SDimitry Andric     ValueInfo VI = Index->getValueInfo(F.getGUID());
3968*0b57cec5SDimitry Andric     if (!VI || VI.getSummaryList().empty()) {
3969*0b57cec5SDimitry Andric       // Only declarations should not have a summary (a declaration might
3970*0b57cec5SDimitry Andric       // however have a summary if the def was in module level asm).
3971*0b57cec5SDimitry Andric       assert(F.isDeclaration());
3972*0b57cec5SDimitry Andric       continue;
3973*0b57cec5SDimitry Andric     }
3974*0b57cec5SDimitry Andric     auto *Summary = VI.getSummaryList()[0].get();
3975*0b57cec5SDimitry Andric     writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.getValueID(&F),
3976*0b57cec5SDimitry Andric                                         FSCallsAbbrev, FSCallsProfileAbbrev, F);
3977*0b57cec5SDimitry Andric   }
3978*0b57cec5SDimitry Andric 
3979*0b57cec5SDimitry Andric   // Capture references from GlobalVariable initializers, which are outside
3980*0b57cec5SDimitry Andric   // of a function scope.
3981*0b57cec5SDimitry Andric   for (const GlobalVariable &G : M.globals())
3982*0b57cec5SDimitry Andric     writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev,
3983*0b57cec5SDimitry Andric                                FSModVTableRefsAbbrev);
3984*0b57cec5SDimitry Andric 
3985*0b57cec5SDimitry Andric   for (const GlobalAlias &A : M.aliases()) {
3986*0b57cec5SDimitry Andric     auto *Aliasee = A.getBaseObject();
3987*0b57cec5SDimitry Andric     if (!Aliasee->hasName())
3988*0b57cec5SDimitry Andric       // Nameless function don't have an entry in the summary, skip it.
3989*0b57cec5SDimitry Andric       continue;
3990*0b57cec5SDimitry Andric     auto AliasId = VE.getValueID(&A);
3991*0b57cec5SDimitry Andric     auto AliaseeId = VE.getValueID(Aliasee);
3992*0b57cec5SDimitry Andric     NameVals.push_back(AliasId);
3993*0b57cec5SDimitry Andric     auto *Summary = Index->getGlobalValueSummary(A);
3994*0b57cec5SDimitry Andric     AliasSummary *AS = cast<AliasSummary>(Summary);
3995*0b57cec5SDimitry Andric     NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
3996*0b57cec5SDimitry Andric     NameVals.push_back(AliaseeId);
3997*0b57cec5SDimitry Andric     Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
3998*0b57cec5SDimitry Andric     NameVals.clear();
3999*0b57cec5SDimitry Andric   }
4000*0b57cec5SDimitry Andric 
4001*0b57cec5SDimitry Andric   for (auto &S : Index->typeIdCompatibleVtableMap()) {
4002*0b57cec5SDimitry Andric     writeTypeIdCompatibleVtableSummaryRecord(NameVals, StrtabBuilder, S.first,
4003*0b57cec5SDimitry Andric                                              S.second, VE);
4004*0b57cec5SDimitry Andric     Stream.EmitRecord(bitc::FS_TYPE_ID_METADATA, NameVals,
4005*0b57cec5SDimitry Andric                       TypeIdCompatibleVtableAbbrev);
4006*0b57cec5SDimitry Andric     NameVals.clear();
4007*0b57cec5SDimitry Andric   }
4008*0b57cec5SDimitry Andric 
40095ffd83dbSDimitry Andric   Stream.EmitRecord(bitc::FS_BLOCK_COUNT,
40105ffd83dbSDimitry Andric                     ArrayRef<uint64_t>{Index->getBlockCount()});
40115ffd83dbSDimitry Andric 
4012*0b57cec5SDimitry Andric   Stream.ExitBlock();
4013*0b57cec5SDimitry Andric }
4014*0b57cec5SDimitry Andric 
4015*0b57cec5SDimitry Andric /// Emit the combined summary section into the combined index file.
4016*0b57cec5SDimitry Andric void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
4017*0b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3);
4018480093f4SDimitry Andric   Stream.EmitRecord(
4019480093f4SDimitry Andric       bitc::FS_VERSION,
4020480093f4SDimitry Andric       ArrayRef<uint64_t>{ModuleSummaryIndex::BitcodeSummaryVersion});
4021*0b57cec5SDimitry Andric 
4022*0b57cec5SDimitry Andric   // Write the index flags.
40235ffd83dbSDimitry Andric   Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Index.getFlags()});
4024*0b57cec5SDimitry Andric 
4025*0b57cec5SDimitry Andric   for (const auto &GVI : valueIds()) {
4026*0b57cec5SDimitry Andric     Stream.EmitRecord(bitc::FS_VALUE_GUID,
4027*0b57cec5SDimitry Andric                       ArrayRef<uint64_t>{GVI.second, GVI.first});
4028*0b57cec5SDimitry Andric   }
4029*0b57cec5SDimitry Andric 
4030*0b57cec5SDimitry Andric   // Abbrev for FS_COMBINED.
4031*0b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
4032*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED));
4033*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
4034*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
4035*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
4036*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
4037*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // fflags
4038*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // entrycount
4039*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
4040*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // rorefcnt
4041*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // worefcnt
4042*0b57cec5SDimitry Andric   // numrefs x valueid, n x (valueid)
4043*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4044*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4045*0b57cec5SDimitry Andric   unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4046*0b57cec5SDimitry Andric 
4047*0b57cec5SDimitry Andric   // Abbrev for FS_COMBINED_PROFILE.
4048*0b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
4049*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));
4050*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
4051*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
4052*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
4053*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
4054*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // fflags
4055*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // entrycount
4056*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
4057*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // rorefcnt
4058*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // worefcnt
4059*0b57cec5SDimitry Andric   // numrefs x valueid, n x (valueid, hotness)
4060*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4061*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4062*0b57cec5SDimitry Andric   unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4063*0b57cec5SDimitry Andric 
4064*0b57cec5SDimitry Andric   // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
4065*0b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
4066*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));
4067*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
4068*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
4069*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
4070*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));    // valueids
4071*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4072*0b57cec5SDimitry Andric   unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4073*0b57cec5SDimitry Andric 
4074*0b57cec5SDimitry Andric   // Abbrev for FS_COMBINED_ALIAS.
4075*0b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
4076*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS));
4077*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
4078*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
4079*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
4080*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
4081*0b57cec5SDimitry Andric   unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4082*0b57cec5SDimitry Andric 
4083*0b57cec5SDimitry Andric   // The aliases are emitted as a post-pass, and will point to the value
4084*0b57cec5SDimitry Andric   // id of the aliasee. Save them in a vector for post-processing.
4085*0b57cec5SDimitry Andric   SmallVector<AliasSummary *, 64> Aliases;
4086*0b57cec5SDimitry Andric 
4087*0b57cec5SDimitry Andric   // Save the value id for each summary for alias emission.
4088*0b57cec5SDimitry Andric   DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
4089*0b57cec5SDimitry Andric 
4090*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> NameVals;
4091*0b57cec5SDimitry Andric 
4092*0b57cec5SDimitry Andric   // Set that will be populated during call to writeFunctionTypeMetadataRecords
4093*0b57cec5SDimitry Andric   // with the type ids referenced by this index file.
4094*0b57cec5SDimitry Andric   std::set<GlobalValue::GUID> ReferencedTypeIds;
4095*0b57cec5SDimitry Andric 
4096*0b57cec5SDimitry Andric   // For local linkage, we also emit the original name separately
4097*0b57cec5SDimitry Andric   // immediately after the record.
4098*0b57cec5SDimitry Andric   auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
4099*0b57cec5SDimitry Andric     if (!GlobalValue::isLocalLinkage(S.linkage()))
4100*0b57cec5SDimitry Andric       return;
4101*0b57cec5SDimitry Andric     NameVals.push_back(S.getOriginalName());
4102*0b57cec5SDimitry Andric     Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals);
4103*0b57cec5SDimitry Andric     NameVals.clear();
4104*0b57cec5SDimitry Andric   };
4105*0b57cec5SDimitry Andric 
4106*0b57cec5SDimitry Andric   std::set<GlobalValue::GUID> DefOrUseGUIDs;
4107*0b57cec5SDimitry Andric   forEachSummary([&](GVInfo I, bool IsAliasee) {
4108*0b57cec5SDimitry Andric     GlobalValueSummary *S = I.second;
4109*0b57cec5SDimitry Andric     assert(S);
4110*0b57cec5SDimitry Andric     DefOrUseGUIDs.insert(I.first);
4111*0b57cec5SDimitry Andric     for (const ValueInfo &VI : S->refs())
4112*0b57cec5SDimitry Andric       DefOrUseGUIDs.insert(VI.getGUID());
4113*0b57cec5SDimitry Andric 
4114*0b57cec5SDimitry Andric     auto ValueId = getValueId(I.first);
4115*0b57cec5SDimitry Andric     assert(ValueId);
4116*0b57cec5SDimitry Andric     SummaryToValueIdMap[S] = *ValueId;
4117*0b57cec5SDimitry Andric 
4118*0b57cec5SDimitry Andric     // If this is invoked for an aliasee, we want to record the above
4119*0b57cec5SDimitry Andric     // mapping, but then not emit a summary entry (if the aliasee is
4120*0b57cec5SDimitry Andric     // to be imported, we will invoke this separately with IsAliasee=false).
4121*0b57cec5SDimitry Andric     if (IsAliasee)
4122*0b57cec5SDimitry Andric       return;
4123*0b57cec5SDimitry Andric 
4124*0b57cec5SDimitry Andric     if (auto *AS = dyn_cast<AliasSummary>(S)) {
4125*0b57cec5SDimitry Andric       // Will process aliases as a post-pass because the reader wants all
4126*0b57cec5SDimitry Andric       // global to be loaded first.
4127*0b57cec5SDimitry Andric       Aliases.push_back(AS);
4128*0b57cec5SDimitry Andric       return;
4129*0b57cec5SDimitry Andric     }
4130*0b57cec5SDimitry Andric 
4131*0b57cec5SDimitry Andric     if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
4132*0b57cec5SDimitry Andric       NameVals.push_back(*ValueId);
4133*0b57cec5SDimitry Andric       NameVals.push_back(Index.getModuleId(VS->modulePath()));
4134*0b57cec5SDimitry Andric       NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
4135*0b57cec5SDimitry Andric       NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
4136*0b57cec5SDimitry Andric       for (auto &RI : VS->refs()) {
4137*0b57cec5SDimitry Andric         auto RefValueId = getValueId(RI.getGUID());
4138*0b57cec5SDimitry Andric         if (!RefValueId)
4139*0b57cec5SDimitry Andric           continue;
4140*0b57cec5SDimitry Andric         NameVals.push_back(*RefValueId);
4141*0b57cec5SDimitry Andric       }
4142*0b57cec5SDimitry Andric 
4143*0b57cec5SDimitry Andric       // Emit the finished record.
4144*0b57cec5SDimitry Andric       Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals,
4145*0b57cec5SDimitry Andric                         FSModRefsAbbrev);
4146*0b57cec5SDimitry Andric       NameVals.clear();
4147*0b57cec5SDimitry Andric       MaybeEmitOriginalName(*S);
4148*0b57cec5SDimitry Andric       return;
4149*0b57cec5SDimitry Andric     }
4150*0b57cec5SDimitry Andric 
4151e8d8bef9SDimitry Andric     auto GetValueId = [&](const ValueInfo &VI) -> Optional<unsigned> {
4152e8d8bef9SDimitry Andric       GlobalValue::GUID GUID = VI.getGUID();
4153e8d8bef9SDimitry Andric       Optional<unsigned> CallValueId = getValueId(GUID);
4154e8d8bef9SDimitry Andric       if (CallValueId)
4155e8d8bef9SDimitry Andric         return CallValueId;
4156e8d8bef9SDimitry Andric       // For SamplePGO, the indirect call targets for local functions will
4157e8d8bef9SDimitry Andric       // have its original name annotated in profile. We try to find the
4158e8d8bef9SDimitry Andric       // corresponding PGOFuncName as the GUID.
4159e8d8bef9SDimitry Andric       GUID = Index.getGUIDFromOriginalID(GUID);
4160e8d8bef9SDimitry Andric       if (!GUID)
4161e8d8bef9SDimitry Andric         return None;
4162e8d8bef9SDimitry Andric       CallValueId = getValueId(GUID);
4163e8d8bef9SDimitry Andric       if (!CallValueId)
4164e8d8bef9SDimitry Andric         return None;
4165e8d8bef9SDimitry Andric       // The mapping from OriginalId to GUID may return a GUID
4166e8d8bef9SDimitry Andric       // that corresponds to a static variable. Filter it out here.
4167e8d8bef9SDimitry Andric       // This can happen when
4168e8d8bef9SDimitry Andric       // 1) There is a call to a library function which does not have
4169e8d8bef9SDimitry Andric       // a CallValidId;
4170e8d8bef9SDimitry Andric       // 2) There is a static variable with the  OriginalGUID identical
4171e8d8bef9SDimitry Andric       // to the GUID of the library function in 1);
4172e8d8bef9SDimitry Andric       // When this happens, the logic for SamplePGO kicks in and
4173e8d8bef9SDimitry Andric       // the static variable in 2) will be found, which needs to be
4174e8d8bef9SDimitry Andric       // filtered out.
4175e8d8bef9SDimitry Andric       auto *GVSum = Index.getGlobalValueSummary(GUID, false);
4176e8d8bef9SDimitry Andric       if (GVSum && GVSum->getSummaryKind() == GlobalValueSummary::GlobalVarKind)
4177e8d8bef9SDimitry Andric         return None;
4178e8d8bef9SDimitry Andric       return CallValueId;
4179e8d8bef9SDimitry Andric     };
4180e8d8bef9SDimitry Andric 
4181*0b57cec5SDimitry Andric     auto *FS = cast<FunctionSummary>(S);
4182e8d8bef9SDimitry Andric     writeFunctionTypeMetadataRecords(Stream, FS, GetValueId);
4183*0b57cec5SDimitry Andric     getReferencedTypeIds(FS, ReferencedTypeIds);
4184*0b57cec5SDimitry Andric 
4185*0b57cec5SDimitry Andric     NameVals.push_back(*ValueId);
4186*0b57cec5SDimitry Andric     NameVals.push_back(Index.getModuleId(FS->modulePath()));
4187*0b57cec5SDimitry Andric     NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
4188*0b57cec5SDimitry Andric     NameVals.push_back(FS->instCount());
4189*0b57cec5SDimitry Andric     NameVals.push_back(getEncodedFFlags(FS->fflags()));
4190*0b57cec5SDimitry Andric     NameVals.push_back(FS->entryCount());
4191*0b57cec5SDimitry Andric 
4192*0b57cec5SDimitry Andric     // Fill in below
4193*0b57cec5SDimitry Andric     NameVals.push_back(0); // numrefs
4194*0b57cec5SDimitry Andric     NameVals.push_back(0); // rorefcnt
4195*0b57cec5SDimitry Andric     NameVals.push_back(0); // worefcnt
4196*0b57cec5SDimitry Andric 
4197*0b57cec5SDimitry Andric     unsigned Count = 0, RORefCnt = 0, WORefCnt = 0;
4198*0b57cec5SDimitry Andric     for (auto &RI : FS->refs()) {
4199*0b57cec5SDimitry Andric       auto RefValueId = getValueId(RI.getGUID());
4200*0b57cec5SDimitry Andric       if (!RefValueId)
4201*0b57cec5SDimitry Andric         continue;
4202*0b57cec5SDimitry Andric       NameVals.push_back(*RefValueId);
4203*0b57cec5SDimitry Andric       if (RI.isReadOnly())
4204*0b57cec5SDimitry Andric         RORefCnt++;
4205*0b57cec5SDimitry Andric       else if (RI.isWriteOnly())
4206*0b57cec5SDimitry Andric         WORefCnt++;
4207*0b57cec5SDimitry Andric       Count++;
4208*0b57cec5SDimitry Andric     }
4209*0b57cec5SDimitry Andric     NameVals[6] = Count;
4210*0b57cec5SDimitry Andric     NameVals[7] = RORefCnt;
4211*0b57cec5SDimitry Andric     NameVals[8] = WORefCnt;
4212*0b57cec5SDimitry Andric 
4213*0b57cec5SDimitry Andric     bool HasProfileData = false;
4214*0b57cec5SDimitry Andric     for (auto &EI : FS->calls()) {
4215*0b57cec5SDimitry Andric       HasProfileData |=
4216*0b57cec5SDimitry Andric           EI.second.getHotness() != CalleeInfo::HotnessType::Unknown;
4217*0b57cec5SDimitry Andric       if (HasProfileData)
4218*0b57cec5SDimitry Andric         break;
4219*0b57cec5SDimitry Andric     }
4220*0b57cec5SDimitry Andric 
4221*0b57cec5SDimitry Andric     for (auto &EI : FS->calls()) {
4222*0b57cec5SDimitry Andric       // If this GUID doesn't have a value id, it doesn't have a function
4223*0b57cec5SDimitry Andric       // summary and we don't need to record any calls to it.
4224e8d8bef9SDimitry Andric       Optional<unsigned> CallValueId = GetValueId(EI.first);
4225*0b57cec5SDimitry Andric       if (!CallValueId)
4226*0b57cec5SDimitry Andric         continue;
4227*0b57cec5SDimitry Andric       NameVals.push_back(*CallValueId);
4228*0b57cec5SDimitry Andric       if (HasProfileData)
4229*0b57cec5SDimitry Andric         NameVals.push_back(static_cast<uint8_t>(EI.second.Hotness));
4230*0b57cec5SDimitry Andric     }
4231*0b57cec5SDimitry Andric 
4232*0b57cec5SDimitry Andric     unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
4233*0b57cec5SDimitry Andric     unsigned Code =
4234*0b57cec5SDimitry Andric         (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED);
4235*0b57cec5SDimitry Andric 
4236*0b57cec5SDimitry Andric     // Emit the finished record.
4237*0b57cec5SDimitry Andric     Stream.EmitRecord(Code, NameVals, FSAbbrev);
4238*0b57cec5SDimitry Andric     NameVals.clear();
4239*0b57cec5SDimitry Andric     MaybeEmitOriginalName(*S);
4240*0b57cec5SDimitry Andric   });
4241*0b57cec5SDimitry Andric 
4242*0b57cec5SDimitry Andric   for (auto *AS : Aliases) {
4243*0b57cec5SDimitry Andric     auto AliasValueId = SummaryToValueIdMap[AS];
4244*0b57cec5SDimitry Andric     assert(AliasValueId);
4245*0b57cec5SDimitry Andric     NameVals.push_back(AliasValueId);
4246*0b57cec5SDimitry Andric     NameVals.push_back(Index.getModuleId(AS->modulePath()));
4247*0b57cec5SDimitry Andric     NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
4248*0b57cec5SDimitry Andric     auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()];
4249*0b57cec5SDimitry Andric     assert(AliaseeValueId);
4250*0b57cec5SDimitry Andric     NameVals.push_back(AliaseeValueId);
4251*0b57cec5SDimitry Andric 
4252*0b57cec5SDimitry Andric     // Emit the finished record.
4253*0b57cec5SDimitry Andric     Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
4254*0b57cec5SDimitry Andric     NameVals.clear();
4255*0b57cec5SDimitry Andric     MaybeEmitOriginalName(*AS);
4256*0b57cec5SDimitry Andric 
4257*0b57cec5SDimitry Andric     if (auto *FS = dyn_cast<FunctionSummary>(&AS->getAliasee()))
4258*0b57cec5SDimitry Andric       getReferencedTypeIds(FS, ReferencedTypeIds);
4259*0b57cec5SDimitry Andric   }
4260*0b57cec5SDimitry Andric 
4261*0b57cec5SDimitry Andric   if (!Index.cfiFunctionDefs().empty()) {
4262*0b57cec5SDimitry Andric     for (auto &S : Index.cfiFunctionDefs()) {
4263*0b57cec5SDimitry Andric       if (DefOrUseGUIDs.count(
4264*0b57cec5SDimitry Andric               GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(S)))) {
4265*0b57cec5SDimitry Andric         NameVals.push_back(StrtabBuilder.add(S));
4266*0b57cec5SDimitry Andric         NameVals.push_back(S.size());
4267*0b57cec5SDimitry Andric       }
4268*0b57cec5SDimitry Andric     }
4269*0b57cec5SDimitry Andric     if (!NameVals.empty()) {
4270*0b57cec5SDimitry Andric       Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DEFS, NameVals);
4271*0b57cec5SDimitry Andric       NameVals.clear();
4272*0b57cec5SDimitry Andric     }
4273*0b57cec5SDimitry Andric   }
4274*0b57cec5SDimitry Andric 
4275*0b57cec5SDimitry Andric   if (!Index.cfiFunctionDecls().empty()) {
4276*0b57cec5SDimitry Andric     for (auto &S : Index.cfiFunctionDecls()) {
4277*0b57cec5SDimitry Andric       if (DefOrUseGUIDs.count(
4278*0b57cec5SDimitry Andric               GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(S)))) {
4279*0b57cec5SDimitry Andric         NameVals.push_back(StrtabBuilder.add(S));
4280*0b57cec5SDimitry Andric         NameVals.push_back(S.size());
4281*0b57cec5SDimitry Andric       }
4282*0b57cec5SDimitry Andric     }
4283*0b57cec5SDimitry Andric     if (!NameVals.empty()) {
4284*0b57cec5SDimitry Andric       Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DECLS, NameVals);
4285*0b57cec5SDimitry Andric       NameVals.clear();
4286*0b57cec5SDimitry Andric     }
4287*0b57cec5SDimitry Andric   }
4288*0b57cec5SDimitry Andric 
4289*0b57cec5SDimitry Andric   // Walk the GUIDs that were referenced, and write the
4290*0b57cec5SDimitry Andric   // corresponding type id records.
4291*0b57cec5SDimitry Andric   for (auto &T : ReferencedTypeIds) {
4292*0b57cec5SDimitry Andric     auto TidIter = Index.typeIds().equal_range(T);
4293*0b57cec5SDimitry Andric     for (auto It = TidIter.first; It != TidIter.second; ++It) {
4294*0b57cec5SDimitry Andric       writeTypeIdSummaryRecord(NameVals, StrtabBuilder, It->second.first,
4295*0b57cec5SDimitry Andric                                It->second.second);
4296*0b57cec5SDimitry Andric       Stream.EmitRecord(bitc::FS_TYPE_ID, NameVals);
4297*0b57cec5SDimitry Andric       NameVals.clear();
4298*0b57cec5SDimitry Andric     }
4299*0b57cec5SDimitry Andric   }
4300*0b57cec5SDimitry Andric 
43015ffd83dbSDimitry Andric   Stream.EmitRecord(bitc::FS_BLOCK_COUNT,
43025ffd83dbSDimitry Andric                     ArrayRef<uint64_t>{Index.getBlockCount()});
43035ffd83dbSDimitry Andric 
4304*0b57cec5SDimitry Andric   Stream.ExitBlock();
4305*0b57cec5SDimitry Andric }
4306*0b57cec5SDimitry Andric 
4307*0b57cec5SDimitry Andric /// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
4308*0b57cec5SDimitry Andric /// current llvm version, and a record for the epoch number.
4309*0b57cec5SDimitry Andric static void writeIdentificationBlock(BitstreamWriter &Stream) {
4310*0b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);
4311*0b57cec5SDimitry Andric 
4312*0b57cec5SDimitry Andric   // Write the "user readable" string identifying the bitcode producer
4313*0b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
4314*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING));
4315*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4316*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
4317*0b57cec5SDimitry Andric   auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4318*0b57cec5SDimitry Andric   writeStringRecord(Stream, bitc::IDENTIFICATION_CODE_STRING,
4319*0b57cec5SDimitry Andric                     "LLVM" LLVM_VERSION_STRING, StringAbbrev);
4320*0b57cec5SDimitry Andric 
4321*0b57cec5SDimitry Andric   // Write the epoch version
4322*0b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
4323*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH));
4324*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4325*0b57cec5SDimitry Andric   auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));
43265ffd83dbSDimitry Andric   constexpr std::array<unsigned, 1> Vals = {{bitc::BITCODE_CURRENT_EPOCH}};
4327*0b57cec5SDimitry Andric   Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
4328*0b57cec5SDimitry Andric   Stream.ExitBlock();
4329*0b57cec5SDimitry Andric }
4330*0b57cec5SDimitry Andric 
4331*0b57cec5SDimitry Andric void ModuleBitcodeWriter::writeModuleHash(size_t BlockStartPos) {
4332*0b57cec5SDimitry Andric   // Emit the module's hash.
4333*0b57cec5SDimitry Andric   // MODULE_CODE_HASH: [5*i32]
4334*0b57cec5SDimitry Andric   if (GenerateHash) {
4335*0b57cec5SDimitry Andric     uint32_t Vals[5];
4336*0b57cec5SDimitry Andric     Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&(Buffer)[BlockStartPos],
4337*0b57cec5SDimitry Andric                                     Buffer.size() - BlockStartPos));
4338*0b57cec5SDimitry Andric     StringRef Hash = Hasher.result();
4339*0b57cec5SDimitry Andric     for (int Pos = 0; Pos < 20; Pos += 4) {
4340*0b57cec5SDimitry Andric       Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);
4341*0b57cec5SDimitry Andric     }
4342*0b57cec5SDimitry Andric 
4343*0b57cec5SDimitry Andric     // Emit the finished record.
4344*0b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
4345*0b57cec5SDimitry Andric 
4346*0b57cec5SDimitry Andric     if (ModHash)
4347*0b57cec5SDimitry Andric       // Save the written hash value.
4348*0b57cec5SDimitry Andric       llvm::copy(Vals, std::begin(*ModHash));
4349*0b57cec5SDimitry Andric   }
4350*0b57cec5SDimitry Andric }
4351*0b57cec5SDimitry Andric 
4352*0b57cec5SDimitry Andric void ModuleBitcodeWriter::write() {
4353*0b57cec5SDimitry Andric   writeIdentificationBlock(Stream);
4354*0b57cec5SDimitry Andric 
4355*0b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
4356*0b57cec5SDimitry Andric   size_t BlockStartPos = Buffer.size();
4357*0b57cec5SDimitry Andric 
4358*0b57cec5SDimitry Andric   writeModuleVersion();
4359*0b57cec5SDimitry Andric 
4360*0b57cec5SDimitry Andric   // Emit blockinfo, which defines the standard abbreviations etc.
4361*0b57cec5SDimitry Andric   writeBlockInfo();
4362*0b57cec5SDimitry Andric 
4363*0b57cec5SDimitry Andric   // Emit information describing all of the types in the module.
4364*0b57cec5SDimitry Andric   writeTypeTable();
4365*0b57cec5SDimitry Andric 
4366*0b57cec5SDimitry Andric   // Emit information about attribute groups.
4367*0b57cec5SDimitry Andric   writeAttributeGroupTable();
4368*0b57cec5SDimitry Andric 
4369*0b57cec5SDimitry Andric   // Emit information about parameter attributes.
4370*0b57cec5SDimitry Andric   writeAttributeTable();
4371*0b57cec5SDimitry Andric 
4372*0b57cec5SDimitry Andric   writeComdats();
4373*0b57cec5SDimitry Andric 
4374*0b57cec5SDimitry Andric   // Emit top-level description of module, including target triple, inline asm,
4375*0b57cec5SDimitry Andric   // descriptors for global variables, and function prototype info.
4376*0b57cec5SDimitry Andric   writeModuleInfo();
4377*0b57cec5SDimitry Andric 
4378*0b57cec5SDimitry Andric   // Emit constants.
4379*0b57cec5SDimitry Andric   writeModuleConstants();
4380*0b57cec5SDimitry Andric 
4381*0b57cec5SDimitry Andric   // Emit metadata kind names.
4382*0b57cec5SDimitry Andric   writeModuleMetadataKinds();
4383*0b57cec5SDimitry Andric 
4384*0b57cec5SDimitry Andric   // Emit metadata.
4385*0b57cec5SDimitry Andric   writeModuleMetadata();
4386*0b57cec5SDimitry Andric 
4387*0b57cec5SDimitry Andric   // Emit module-level use-lists.
4388*0b57cec5SDimitry Andric   if (VE.shouldPreserveUseListOrder())
4389*0b57cec5SDimitry Andric     writeUseListBlock(nullptr);
4390*0b57cec5SDimitry Andric 
4391*0b57cec5SDimitry Andric   writeOperandBundleTags();
4392*0b57cec5SDimitry Andric   writeSyncScopeNames();
4393*0b57cec5SDimitry Andric 
4394*0b57cec5SDimitry Andric   // Emit function bodies.
4395*0b57cec5SDimitry Andric   DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
4396*0b57cec5SDimitry Andric   for (Module::const_iterator F = M.begin(), E = M.end(); F != E; ++F)
4397*0b57cec5SDimitry Andric     if (!F->isDeclaration())
4398*0b57cec5SDimitry Andric       writeFunction(*F, FunctionToBitcodeIndex);
4399*0b57cec5SDimitry Andric 
4400*0b57cec5SDimitry Andric   // Need to write after the above call to WriteFunction which populates
4401*0b57cec5SDimitry Andric   // the summary information in the index.
4402*0b57cec5SDimitry Andric   if (Index)
4403*0b57cec5SDimitry Andric     writePerModuleGlobalValueSummary();
4404*0b57cec5SDimitry Andric 
4405*0b57cec5SDimitry Andric   writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
4406*0b57cec5SDimitry Andric 
4407*0b57cec5SDimitry Andric   writeModuleHash(BlockStartPos);
4408*0b57cec5SDimitry Andric 
4409*0b57cec5SDimitry Andric   Stream.ExitBlock();
4410*0b57cec5SDimitry Andric }
4411*0b57cec5SDimitry Andric 
4412*0b57cec5SDimitry Andric static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
4413*0b57cec5SDimitry Andric                                uint32_t &Position) {
4414*0b57cec5SDimitry Andric   support::endian::write32le(&Buffer[Position], Value);
4415*0b57cec5SDimitry Andric   Position += 4;
4416*0b57cec5SDimitry Andric }
4417*0b57cec5SDimitry Andric 
4418*0b57cec5SDimitry Andric /// If generating a bc file on darwin, we have to emit a
4419*0b57cec5SDimitry Andric /// header and trailer to make it compatible with the system archiver.  To do
4420*0b57cec5SDimitry Andric /// this we emit the following header, and then emit a trailer that pads the
4421*0b57cec5SDimitry Andric /// file out to be a multiple of 16 bytes.
4422*0b57cec5SDimitry Andric ///
4423*0b57cec5SDimitry Andric /// struct bc_header {
4424*0b57cec5SDimitry Andric ///   uint32_t Magic;         // 0x0B17C0DE
4425*0b57cec5SDimitry Andric ///   uint32_t Version;       // Version, currently always 0.
4426*0b57cec5SDimitry Andric ///   uint32_t BitcodeOffset; // Offset to traditional bitcode file.
4427*0b57cec5SDimitry Andric ///   uint32_t BitcodeSize;   // Size of traditional bitcode file.
4428*0b57cec5SDimitry Andric ///   uint32_t CPUType;       // CPU specifier.
4429*0b57cec5SDimitry Andric ///   ... potentially more later ...
4430*0b57cec5SDimitry Andric /// };
4431*0b57cec5SDimitry Andric static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
4432*0b57cec5SDimitry Andric                                          const Triple &TT) {
4433*0b57cec5SDimitry Andric   unsigned CPUType = ~0U;
4434*0b57cec5SDimitry Andric 
4435*0b57cec5SDimitry Andric   // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
4436*0b57cec5SDimitry Andric   // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
4437*0b57cec5SDimitry Andric   // number from /usr/include/mach/machine.h.  It is ok to reproduce the
4438*0b57cec5SDimitry Andric   // specific constants here because they are implicitly part of the Darwin ABI.
4439*0b57cec5SDimitry Andric   enum {
4440*0b57cec5SDimitry Andric     DARWIN_CPU_ARCH_ABI64      = 0x01000000,
4441*0b57cec5SDimitry Andric     DARWIN_CPU_TYPE_X86        = 7,
4442*0b57cec5SDimitry Andric     DARWIN_CPU_TYPE_ARM        = 12,
4443*0b57cec5SDimitry Andric     DARWIN_CPU_TYPE_POWERPC    = 18
4444*0b57cec5SDimitry Andric   };
4445*0b57cec5SDimitry Andric 
4446*0b57cec5SDimitry Andric   Triple::ArchType Arch = TT.getArch();
4447*0b57cec5SDimitry Andric   if (Arch == Triple::x86_64)
4448*0b57cec5SDimitry Andric     CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
4449*0b57cec5SDimitry Andric   else if (Arch == Triple::x86)
4450*0b57cec5SDimitry Andric     CPUType = DARWIN_CPU_TYPE_X86;
4451*0b57cec5SDimitry Andric   else if (Arch == Triple::ppc)
4452*0b57cec5SDimitry Andric     CPUType = DARWIN_CPU_TYPE_POWERPC;
4453*0b57cec5SDimitry Andric   else if (Arch == Triple::ppc64)
4454*0b57cec5SDimitry Andric     CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
4455*0b57cec5SDimitry Andric   else if (Arch == Triple::arm || Arch == Triple::thumb)
4456*0b57cec5SDimitry Andric     CPUType = DARWIN_CPU_TYPE_ARM;
4457*0b57cec5SDimitry Andric 
4458*0b57cec5SDimitry Andric   // Traditional Bitcode starts after header.
4459*0b57cec5SDimitry Andric   assert(Buffer.size() >= BWH_HeaderSize &&
4460*0b57cec5SDimitry Andric          "Expected header size to be reserved");
4461*0b57cec5SDimitry Andric   unsigned BCOffset = BWH_HeaderSize;
4462*0b57cec5SDimitry Andric   unsigned BCSize = Buffer.size() - BWH_HeaderSize;
4463*0b57cec5SDimitry Andric 
4464*0b57cec5SDimitry Andric   // Write the magic and version.
4465*0b57cec5SDimitry Andric   unsigned Position = 0;
4466*0b57cec5SDimitry Andric   writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
4467*0b57cec5SDimitry Andric   writeInt32ToBuffer(0, Buffer, Position); // Version.
4468*0b57cec5SDimitry Andric   writeInt32ToBuffer(BCOffset, Buffer, Position);
4469*0b57cec5SDimitry Andric   writeInt32ToBuffer(BCSize, Buffer, Position);
4470*0b57cec5SDimitry Andric   writeInt32ToBuffer(CPUType, Buffer, Position);
4471*0b57cec5SDimitry Andric 
4472*0b57cec5SDimitry Andric   // If the file is not a multiple of 16 bytes, insert dummy padding.
4473*0b57cec5SDimitry Andric   while (Buffer.size() & 15)
4474*0b57cec5SDimitry Andric     Buffer.push_back(0);
4475*0b57cec5SDimitry Andric }
4476*0b57cec5SDimitry Andric 
4477*0b57cec5SDimitry Andric /// Helper to write the header common to all bitcode files.
4478*0b57cec5SDimitry Andric static void writeBitcodeHeader(BitstreamWriter &Stream) {
4479*0b57cec5SDimitry Andric   // Emit the file header.
4480*0b57cec5SDimitry Andric   Stream.Emit((unsigned)'B', 8);
4481*0b57cec5SDimitry Andric   Stream.Emit((unsigned)'C', 8);
4482*0b57cec5SDimitry Andric   Stream.Emit(0x0, 4);
4483*0b57cec5SDimitry Andric   Stream.Emit(0xC, 4);
4484*0b57cec5SDimitry Andric   Stream.Emit(0xE, 4);
4485*0b57cec5SDimitry Andric   Stream.Emit(0xD, 4);
4486*0b57cec5SDimitry Andric }
4487*0b57cec5SDimitry Andric 
4488e8d8bef9SDimitry Andric BitcodeWriter::BitcodeWriter(SmallVectorImpl<char> &Buffer, raw_fd_stream *FS)
4489e8d8bef9SDimitry Andric     : Buffer(Buffer), Stream(new BitstreamWriter(Buffer, FS, FlushThreshold)) {
4490*0b57cec5SDimitry Andric   writeBitcodeHeader(*Stream);
4491*0b57cec5SDimitry Andric }
4492*0b57cec5SDimitry Andric 
4493*0b57cec5SDimitry Andric BitcodeWriter::~BitcodeWriter() { assert(WroteStrtab); }
4494*0b57cec5SDimitry Andric 
4495*0b57cec5SDimitry Andric void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) {
4496*0b57cec5SDimitry Andric   Stream->EnterSubblock(Block, 3);
4497*0b57cec5SDimitry Andric 
4498*0b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
4499*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(Record));
4500*0b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4501*0b57cec5SDimitry Andric   auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv));
4502*0b57cec5SDimitry Andric 
4503*0b57cec5SDimitry Andric   Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob);
4504*0b57cec5SDimitry Andric 
4505*0b57cec5SDimitry Andric   Stream->ExitBlock();
4506*0b57cec5SDimitry Andric }
4507*0b57cec5SDimitry Andric 
4508*0b57cec5SDimitry Andric void BitcodeWriter::writeSymtab() {
4509*0b57cec5SDimitry Andric   assert(!WroteStrtab && !WroteSymtab);
4510*0b57cec5SDimitry Andric 
4511*0b57cec5SDimitry Andric   // If any module has module-level inline asm, we will require a registered asm
4512*0b57cec5SDimitry Andric   // parser for the target so that we can create an accurate symbol table for
4513*0b57cec5SDimitry Andric   // the module.
4514*0b57cec5SDimitry Andric   for (Module *M : Mods) {
4515*0b57cec5SDimitry Andric     if (M->getModuleInlineAsm().empty())
4516*0b57cec5SDimitry Andric       continue;
4517*0b57cec5SDimitry Andric 
4518*0b57cec5SDimitry Andric     std::string Err;
4519*0b57cec5SDimitry Andric     const Triple TT(M->getTargetTriple());
4520*0b57cec5SDimitry Andric     const Target *T = TargetRegistry::lookupTarget(TT.str(), Err);
4521*0b57cec5SDimitry Andric     if (!T || !T->hasMCAsmParser())
4522*0b57cec5SDimitry Andric       return;
4523*0b57cec5SDimitry Andric   }
4524*0b57cec5SDimitry Andric 
4525*0b57cec5SDimitry Andric   WroteSymtab = true;
4526*0b57cec5SDimitry Andric   SmallVector<char, 0> Symtab;
4527*0b57cec5SDimitry Andric   // The irsymtab::build function may be unable to create a symbol table if the
4528*0b57cec5SDimitry Andric   // module is malformed (e.g. it contains an invalid alias). Writing a symbol
4529*0b57cec5SDimitry Andric   // table is not required for correctness, but we still want to be able to
4530*0b57cec5SDimitry Andric   // write malformed modules to bitcode files, so swallow the error.
4531*0b57cec5SDimitry Andric   if (Error E = irsymtab::build(Mods, Symtab, StrtabBuilder, Alloc)) {
4532*0b57cec5SDimitry Andric     consumeError(std::move(E));
4533*0b57cec5SDimitry Andric     return;
4534*0b57cec5SDimitry Andric   }
4535*0b57cec5SDimitry Andric 
4536*0b57cec5SDimitry Andric   writeBlob(bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB,
4537*0b57cec5SDimitry Andric             {Symtab.data(), Symtab.size()});
4538*0b57cec5SDimitry Andric }
4539*0b57cec5SDimitry Andric 
4540*0b57cec5SDimitry Andric void BitcodeWriter::writeStrtab() {
4541*0b57cec5SDimitry Andric   assert(!WroteStrtab);
4542*0b57cec5SDimitry Andric 
4543*0b57cec5SDimitry Andric   std::vector<char> Strtab;
4544*0b57cec5SDimitry Andric   StrtabBuilder.finalizeInOrder();
4545*0b57cec5SDimitry Andric   Strtab.resize(StrtabBuilder.getSize());
4546*0b57cec5SDimitry Andric   StrtabBuilder.write((uint8_t *)Strtab.data());
4547*0b57cec5SDimitry Andric 
4548*0b57cec5SDimitry Andric   writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB,
4549*0b57cec5SDimitry Andric             {Strtab.data(), Strtab.size()});
4550*0b57cec5SDimitry Andric 
4551*0b57cec5SDimitry Andric   WroteStrtab = true;
4552*0b57cec5SDimitry Andric }
4553*0b57cec5SDimitry Andric 
4554*0b57cec5SDimitry Andric void BitcodeWriter::copyStrtab(StringRef Strtab) {
4555*0b57cec5SDimitry Andric   writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab);
4556*0b57cec5SDimitry Andric   WroteStrtab = true;
4557*0b57cec5SDimitry Andric }
4558*0b57cec5SDimitry Andric 
4559*0b57cec5SDimitry Andric void BitcodeWriter::writeModule(const Module &M,
4560*0b57cec5SDimitry Andric                                 bool ShouldPreserveUseListOrder,
4561*0b57cec5SDimitry Andric                                 const ModuleSummaryIndex *Index,
4562*0b57cec5SDimitry Andric                                 bool GenerateHash, ModuleHash *ModHash) {
4563*0b57cec5SDimitry Andric   assert(!WroteStrtab);
4564*0b57cec5SDimitry Andric 
4565*0b57cec5SDimitry Andric   // The Mods vector is used by irsymtab::build, which requires non-const
4566*0b57cec5SDimitry Andric   // Modules in case it needs to materialize metadata. But the bitcode writer
4567*0b57cec5SDimitry Andric   // requires that the module is materialized, so we can cast to non-const here,
4568*0b57cec5SDimitry Andric   // after checking that it is in fact materialized.
4569*0b57cec5SDimitry Andric   assert(M.isMaterialized());
4570*0b57cec5SDimitry Andric   Mods.push_back(const_cast<Module *>(&M));
4571*0b57cec5SDimitry Andric 
4572*0b57cec5SDimitry Andric   ModuleBitcodeWriter ModuleWriter(M, Buffer, StrtabBuilder, *Stream,
4573*0b57cec5SDimitry Andric                                    ShouldPreserveUseListOrder, Index,
4574*0b57cec5SDimitry Andric                                    GenerateHash, ModHash);
4575*0b57cec5SDimitry Andric   ModuleWriter.write();
4576*0b57cec5SDimitry Andric }
4577*0b57cec5SDimitry Andric 
4578*0b57cec5SDimitry Andric void BitcodeWriter::writeIndex(
4579*0b57cec5SDimitry Andric     const ModuleSummaryIndex *Index,
4580*0b57cec5SDimitry Andric     const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
4581*0b57cec5SDimitry Andric   IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index,
4582*0b57cec5SDimitry Andric                                  ModuleToSummariesForIndex);
4583*0b57cec5SDimitry Andric   IndexWriter.write();
4584*0b57cec5SDimitry Andric }
4585*0b57cec5SDimitry Andric 
4586*0b57cec5SDimitry Andric /// Write the specified module to the specified output stream.
4587*0b57cec5SDimitry Andric void llvm::WriteBitcodeToFile(const Module &M, raw_ostream &Out,
4588*0b57cec5SDimitry Andric                               bool ShouldPreserveUseListOrder,
4589*0b57cec5SDimitry Andric                               const ModuleSummaryIndex *Index,
4590*0b57cec5SDimitry Andric                               bool GenerateHash, ModuleHash *ModHash) {
4591*0b57cec5SDimitry Andric   SmallVector<char, 0> Buffer;
4592*0b57cec5SDimitry Andric   Buffer.reserve(256*1024);
4593*0b57cec5SDimitry Andric 
4594*0b57cec5SDimitry Andric   // If this is darwin or another generic macho target, reserve space for the
4595*0b57cec5SDimitry Andric   // header.
4596*0b57cec5SDimitry Andric   Triple TT(M.getTargetTriple());
4597*0b57cec5SDimitry Andric   if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
4598*0b57cec5SDimitry Andric     Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
4599*0b57cec5SDimitry Andric 
4600e8d8bef9SDimitry Andric   BitcodeWriter Writer(Buffer, dyn_cast<raw_fd_stream>(&Out));
4601*0b57cec5SDimitry Andric   Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
4602*0b57cec5SDimitry Andric                      ModHash);
4603*0b57cec5SDimitry Andric   Writer.writeSymtab();
4604*0b57cec5SDimitry Andric   Writer.writeStrtab();
4605*0b57cec5SDimitry Andric 
4606*0b57cec5SDimitry Andric   if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
4607*0b57cec5SDimitry Andric     emitDarwinBCHeaderAndTrailer(Buffer, TT);
4608*0b57cec5SDimitry Andric 
4609*0b57cec5SDimitry Andric   // Write the generated bitstream to "Out".
4610e8d8bef9SDimitry Andric   if (!Buffer.empty())
4611*0b57cec5SDimitry Andric     Out.write((char *)&Buffer.front(), Buffer.size());
4612*0b57cec5SDimitry Andric }
4613*0b57cec5SDimitry Andric 
4614*0b57cec5SDimitry Andric void IndexBitcodeWriter::write() {
4615*0b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
4616*0b57cec5SDimitry Andric 
4617*0b57cec5SDimitry Andric   writeModuleVersion();
4618*0b57cec5SDimitry Andric 
4619*0b57cec5SDimitry Andric   // Write the module paths in the combined index.
4620*0b57cec5SDimitry Andric   writeModStrings();
4621*0b57cec5SDimitry Andric 
4622*0b57cec5SDimitry Andric   // Write the summary combined index records.
4623*0b57cec5SDimitry Andric   writeCombinedGlobalValueSummary();
4624*0b57cec5SDimitry Andric 
4625*0b57cec5SDimitry Andric   Stream.ExitBlock();
4626*0b57cec5SDimitry Andric }
4627*0b57cec5SDimitry Andric 
4628*0b57cec5SDimitry Andric // Write the specified module summary index to the given raw output stream,
4629*0b57cec5SDimitry Andric // where it will be written in a new bitcode block. This is used when
4630*0b57cec5SDimitry Andric // writing the combined index file for ThinLTO. When writing a subset of the
4631*0b57cec5SDimitry Andric // index for a distributed backend, provide a \p ModuleToSummariesForIndex map.
4632*0b57cec5SDimitry Andric void llvm::WriteIndexToFile(
4633*0b57cec5SDimitry Andric     const ModuleSummaryIndex &Index, raw_ostream &Out,
4634*0b57cec5SDimitry Andric     const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
4635*0b57cec5SDimitry Andric   SmallVector<char, 0> Buffer;
4636*0b57cec5SDimitry Andric   Buffer.reserve(256 * 1024);
4637*0b57cec5SDimitry Andric 
4638*0b57cec5SDimitry Andric   BitcodeWriter Writer(Buffer);
4639*0b57cec5SDimitry Andric   Writer.writeIndex(&Index, ModuleToSummariesForIndex);
4640*0b57cec5SDimitry Andric   Writer.writeStrtab();
4641*0b57cec5SDimitry Andric 
4642*0b57cec5SDimitry Andric   Out.write((char *)&Buffer.front(), Buffer.size());
4643*0b57cec5SDimitry Andric }
4644*0b57cec5SDimitry Andric 
4645*0b57cec5SDimitry Andric namespace {
4646*0b57cec5SDimitry Andric 
4647*0b57cec5SDimitry Andric /// Class to manage the bitcode writing for a thin link bitcode file.
4648*0b57cec5SDimitry Andric class ThinLinkBitcodeWriter : public ModuleBitcodeWriterBase {
4649*0b57cec5SDimitry Andric   /// ModHash is for use in ThinLTO incremental build, generated while writing
4650*0b57cec5SDimitry Andric   /// the module bitcode file.
4651*0b57cec5SDimitry Andric   const ModuleHash *ModHash;
4652*0b57cec5SDimitry Andric 
4653*0b57cec5SDimitry Andric public:
4654*0b57cec5SDimitry Andric   ThinLinkBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder,
4655*0b57cec5SDimitry Andric                         BitstreamWriter &Stream,
4656*0b57cec5SDimitry Andric                         const ModuleSummaryIndex &Index,
4657*0b57cec5SDimitry Andric                         const ModuleHash &ModHash)
4658*0b57cec5SDimitry Andric       : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
4659*0b57cec5SDimitry Andric                                 /*ShouldPreserveUseListOrder=*/false, &Index),
4660*0b57cec5SDimitry Andric         ModHash(&ModHash) {}
4661*0b57cec5SDimitry Andric 
4662*0b57cec5SDimitry Andric   void write();
4663*0b57cec5SDimitry Andric 
4664*0b57cec5SDimitry Andric private:
4665*0b57cec5SDimitry Andric   void writeSimplifiedModuleInfo();
4666*0b57cec5SDimitry Andric };
4667*0b57cec5SDimitry Andric 
4668*0b57cec5SDimitry Andric } // end anonymous namespace
4669*0b57cec5SDimitry Andric 
4670*0b57cec5SDimitry Andric // This function writes a simpilified module info for thin link bitcode file.
4671*0b57cec5SDimitry Andric // It only contains the source file name along with the name(the offset and
4672*0b57cec5SDimitry Andric // size in strtab) and linkage for global values. For the global value info
4673*0b57cec5SDimitry Andric // entry, in order to keep linkage at offset 5, there are three zeros used
4674*0b57cec5SDimitry Andric // as padding.
4675*0b57cec5SDimitry Andric void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {
4676*0b57cec5SDimitry Andric   SmallVector<unsigned, 64> Vals;
4677*0b57cec5SDimitry Andric   // Emit the module's source file name.
4678*0b57cec5SDimitry Andric   {
4679*0b57cec5SDimitry Andric     StringEncoding Bits = getStringEncoding(M.getSourceFileName());
4680*0b57cec5SDimitry Andric     BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
4681*0b57cec5SDimitry Andric     if (Bits == SE_Char6)
4682*0b57cec5SDimitry Andric       AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
4683*0b57cec5SDimitry Andric     else if (Bits == SE_Fixed7)
4684*0b57cec5SDimitry Andric       AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
4685*0b57cec5SDimitry Andric 
4686*0b57cec5SDimitry Andric     // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
4687*0b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
4688*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
4689*0b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4690*0b57cec5SDimitry Andric     Abbv->Add(AbbrevOpToUse);
4691*0b57cec5SDimitry Andric     unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4692*0b57cec5SDimitry Andric 
4693*0b57cec5SDimitry Andric     for (const auto P : M.getSourceFileName())
4694*0b57cec5SDimitry Andric       Vals.push_back((unsigned char)P);
4695*0b57cec5SDimitry Andric 
4696*0b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
4697*0b57cec5SDimitry Andric     Vals.clear();
4698*0b57cec5SDimitry Andric   }
4699*0b57cec5SDimitry Andric 
4700*0b57cec5SDimitry Andric   // Emit the global variable information.
4701*0b57cec5SDimitry Andric   for (const GlobalVariable &GV : M.globals()) {
4702*0b57cec5SDimitry Andric     // GLOBALVAR: [strtab offset, strtab size, 0, 0, 0, linkage]
4703*0b57cec5SDimitry Andric     Vals.push_back(StrtabBuilder.add(GV.getName()));
4704*0b57cec5SDimitry Andric     Vals.push_back(GV.getName().size());
4705*0b57cec5SDimitry Andric     Vals.push_back(0);
4706*0b57cec5SDimitry Andric     Vals.push_back(0);
4707*0b57cec5SDimitry Andric     Vals.push_back(0);
4708*0b57cec5SDimitry Andric     Vals.push_back(getEncodedLinkage(GV));
4709*0b57cec5SDimitry Andric 
4710*0b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals);
4711*0b57cec5SDimitry Andric     Vals.clear();
4712*0b57cec5SDimitry Andric   }
4713*0b57cec5SDimitry Andric 
4714*0b57cec5SDimitry Andric   // Emit the function proto information.
4715*0b57cec5SDimitry Andric   for (const Function &F : M) {
4716*0b57cec5SDimitry Andric     // FUNCTION:  [strtab offset, strtab size, 0, 0, 0, linkage]
4717*0b57cec5SDimitry Andric     Vals.push_back(StrtabBuilder.add(F.getName()));
4718*0b57cec5SDimitry Andric     Vals.push_back(F.getName().size());
4719*0b57cec5SDimitry Andric     Vals.push_back(0);
4720*0b57cec5SDimitry Andric     Vals.push_back(0);
4721*0b57cec5SDimitry Andric     Vals.push_back(0);
4722*0b57cec5SDimitry Andric     Vals.push_back(getEncodedLinkage(F));
4723*0b57cec5SDimitry Andric 
4724*0b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals);
4725*0b57cec5SDimitry Andric     Vals.clear();
4726*0b57cec5SDimitry Andric   }
4727*0b57cec5SDimitry Andric 
4728*0b57cec5SDimitry Andric   // Emit the alias information.
4729*0b57cec5SDimitry Andric   for (const GlobalAlias &A : M.aliases()) {
4730*0b57cec5SDimitry Andric     // ALIAS: [strtab offset, strtab size, 0, 0, 0, linkage]
4731*0b57cec5SDimitry Andric     Vals.push_back(StrtabBuilder.add(A.getName()));
4732*0b57cec5SDimitry Andric     Vals.push_back(A.getName().size());
4733*0b57cec5SDimitry Andric     Vals.push_back(0);
4734*0b57cec5SDimitry Andric     Vals.push_back(0);
4735*0b57cec5SDimitry Andric     Vals.push_back(0);
4736*0b57cec5SDimitry Andric     Vals.push_back(getEncodedLinkage(A));
4737*0b57cec5SDimitry Andric 
4738*0b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals);
4739*0b57cec5SDimitry Andric     Vals.clear();
4740*0b57cec5SDimitry Andric   }
4741*0b57cec5SDimitry Andric 
4742*0b57cec5SDimitry Andric   // Emit the ifunc information.
4743*0b57cec5SDimitry Andric   for (const GlobalIFunc &I : M.ifuncs()) {
4744*0b57cec5SDimitry Andric     // IFUNC: [strtab offset, strtab size, 0, 0, 0, linkage]
4745*0b57cec5SDimitry Andric     Vals.push_back(StrtabBuilder.add(I.getName()));
4746*0b57cec5SDimitry Andric     Vals.push_back(I.getName().size());
4747*0b57cec5SDimitry Andric     Vals.push_back(0);
4748*0b57cec5SDimitry Andric     Vals.push_back(0);
4749*0b57cec5SDimitry Andric     Vals.push_back(0);
4750*0b57cec5SDimitry Andric     Vals.push_back(getEncodedLinkage(I));
4751*0b57cec5SDimitry Andric 
4752*0b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
4753*0b57cec5SDimitry Andric     Vals.clear();
4754*0b57cec5SDimitry Andric   }
4755*0b57cec5SDimitry Andric }
4756*0b57cec5SDimitry Andric 
4757*0b57cec5SDimitry Andric void ThinLinkBitcodeWriter::write() {
4758*0b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
4759*0b57cec5SDimitry Andric 
4760*0b57cec5SDimitry Andric   writeModuleVersion();
4761*0b57cec5SDimitry Andric 
4762*0b57cec5SDimitry Andric   writeSimplifiedModuleInfo();
4763*0b57cec5SDimitry Andric 
4764*0b57cec5SDimitry Andric   writePerModuleGlobalValueSummary();
4765*0b57cec5SDimitry Andric 
4766*0b57cec5SDimitry Andric   // Write module hash.
4767*0b57cec5SDimitry Andric   Stream.EmitRecord(bitc::MODULE_CODE_HASH, ArrayRef<uint32_t>(*ModHash));
4768*0b57cec5SDimitry Andric 
4769*0b57cec5SDimitry Andric   Stream.ExitBlock();
4770*0b57cec5SDimitry Andric }
4771*0b57cec5SDimitry Andric 
4772*0b57cec5SDimitry Andric void BitcodeWriter::writeThinLinkBitcode(const Module &M,
4773*0b57cec5SDimitry Andric                                          const ModuleSummaryIndex &Index,
4774*0b57cec5SDimitry Andric                                          const ModuleHash &ModHash) {
4775*0b57cec5SDimitry Andric   assert(!WroteStrtab);
4776*0b57cec5SDimitry Andric 
4777*0b57cec5SDimitry Andric   // The Mods vector is used by irsymtab::build, which requires non-const
4778*0b57cec5SDimitry Andric   // Modules in case it needs to materialize metadata. But the bitcode writer
4779*0b57cec5SDimitry Andric   // requires that the module is materialized, so we can cast to non-const here,
4780*0b57cec5SDimitry Andric   // after checking that it is in fact materialized.
4781*0b57cec5SDimitry Andric   assert(M.isMaterialized());
4782*0b57cec5SDimitry Andric   Mods.push_back(const_cast<Module *>(&M));
4783*0b57cec5SDimitry Andric 
4784*0b57cec5SDimitry Andric   ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index,
4785*0b57cec5SDimitry Andric                                        ModHash);
4786*0b57cec5SDimitry Andric   ThinLinkWriter.write();
4787*0b57cec5SDimitry Andric }
4788*0b57cec5SDimitry Andric 
4789*0b57cec5SDimitry Andric // Write the specified thin link bitcode file to the given raw output stream,
4790*0b57cec5SDimitry Andric // where it will be written in a new bitcode block. This is used when
4791*0b57cec5SDimitry Andric // writing the per-module index file for ThinLTO.
4792*0b57cec5SDimitry Andric void llvm::WriteThinLinkBitcodeToFile(const Module &M, raw_ostream &Out,
4793*0b57cec5SDimitry Andric                                       const ModuleSummaryIndex &Index,
4794*0b57cec5SDimitry Andric                                       const ModuleHash &ModHash) {
4795*0b57cec5SDimitry Andric   SmallVector<char, 0> Buffer;
4796*0b57cec5SDimitry Andric   Buffer.reserve(256 * 1024);
4797*0b57cec5SDimitry Andric 
4798*0b57cec5SDimitry Andric   BitcodeWriter Writer(Buffer);
4799*0b57cec5SDimitry Andric   Writer.writeThinLinkBitcode(M, Index, ModHash);
4800*0b57cec5SDimitry Andric   Writer.writeSymtab();
4801*0b57cec5SDimitry Andric   Writer.writeStrtab();
4802*0b57cec5SDimitry Andric 
4803*0b57cec5SDimitry Andric   Out.write((char *)&Buffer.front(), Buffer.size());
4804*0b57cec5SDimitry Andric }
4805480093f4SDimitry Andric 
4806480093f4SDimitry Andric static const char *getSectionNameForBitcode(const Triple &T) {
4807480093f4SDimitry Andric   switch (T.getObjectFormat()) {
4808480093f4SDimitry Andric   case Triple::MachO:
4809480093f4SDimitry Andric     return "__LLVM,__bitcode";
4810480093f4SDimitry Andric   case Triple::COFF:
4811480093f4SDimitry Andric   case Triple::ELF:
4812480093f4SDimitry Andric   case Triple::Wasm:
4813480093f4SDimitry Andric   case Triple::UnknownObjectFormat:
4814480093f4SDimitry Andric     return ".llvmbc";
4815e8d8bef9SDimitry Andric   case Triple::GOFF:
4816e8d8bef9SDimitry Andric     llvm_unreachable("GOFF is not yet implemented");
4817e8d8bef9SDimitry Andric     break;
4818480093f4SDimitry Andric   case Triple::XCOFF:
4819480093f4SDimitry Andric     llvm_unreachable("XCOFF is not yet implemented");
4820480093f4SDimitry Andric     break;
4821480093f4SDimitry Andric   }
4822480093f4SDimitry Andric   llvm_unreachable("Unimplemented ObjectFormatType");
4823480093f4SDimitry Andric }
4824480093f4SDimitry Andric 
4825480093f4SDimitry Andric static const char *getSectionNameForCommandline(const Triple &T) {
4826480093f4SDimitry Andric   switch (T.getObjectFormat()) {
4827480093f4SDimitry Andric   case Triple::MachO:
4828480093f4SDimitry Andric     return "__LLVM,__cmdline";
4829480093f4SDimitry Andric   case Triple::COFF:
4830480093f4SDimitry Andric   case Triple::ELF:
4831480093f4SDimitry Andric   case Triple::Wasm:
4832480093f4SDimitry Andric   case Triple::UnknownObjectFormat:
4833480093f4SDimitry Andric     return ".llvmcmd";
4834e8d8bef9SDimitry Andric   case Triple::GOFF:
4835e8d8bef9SDimitry Andric     llvm_unreachable("GOFF is not yet implemented");
4836e8d8bef9SDimitry Andric     break;
4837480093f4SDimitry Andric   case Triple::XCOFF:
4838480093f4SDimitry Andric     llvm_unreachable("XCOFF is not yet implemented");
4839480093f4SDimitry Andric     break;
4840480093f4SDimitry Andric   }
4841480093f4SDimitry Andric   llvm_unreachable("Unimplemented ObjectFormatType");
4842480093f4SDimitry Andric }
4843480093f4SDimitry Andric 
4844480093f4SDimitry Andric void llvm::EmbedBitcodeInModule(llvm::Module &M, llvm::MemoryBufferRef Buf,
4845e8d8bef9SDimitry Andric                                 bool EmbedBitcode, bool EmbedCmdline,
4846e8d8bef9SDimitry Andric                                 const std::vector<uint8_t> &CmdArgs) {
4847480093f4SDimitry Andric   // Save llvm.compiler.used and remove it.
4848480093f4SDimitry Andric   SmallVector<Constant *, 2> UsedArray;
4849480093f4SDimitry Andric   SmallPtrSet<GlobalValue *, 4> UsedGlobals;
4850480093f4SDimitry Andric   Type *UsedElementType = Type::getInt8Ty(M.getContext())->getPointerTo(0);
4851480093f4SDimitry Andric   GlobalVariable *Used = collectUsedGlobalVariables(M, UsedGlobals, true);
4852480093f4SDimitry Andric   for (auto *GV : UsedGlobals) {
4853480093f4SDimitry Andric     if (GV->getName() != "llvm.embedded.module" &&
4854480093f4SDimitry Andric         GV->getName() != "llvm.cmdline")
4855480093f4SDimitry Andric       UsedArray.push_back(
4856480093f4SDimitry Andric           ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
4857480093f4SDimitry Andric   }
4858480093f4SDimitry Andric   if (Used)
4859480093f4SDimitry Andric     Used->eraseFromParent();
4860480093f4SDimitry Andric 
4861480093f4SDimitry Andric   // Embed the bitcode for the llvm module.
4862480093f4SDimitry Andric   std::string Data;
4863480093f4SDimitry Andric   ArrayRef<uint8_t> ModuleData;
4864480093f4SDimitry Andric   Triple T(M.getTargetTriple());
4865e8d8bef9SDimitry Andric 
4866480093f4SDimitry Andric   if (EmbedBitcode) {
4867e8d8bef9SDimitry Andric     if (Buf.getBufferSize() == 0 ||
4868e8d8bef9SDimitry Andric         !isBitcode((const unsigned char *)Buf.getBufferStart(),
4869480093f4SDimitry Andric                    (const unsigned char *)Buf.getBufferEnd())) {
4870480093f4SDimitry Andric       // If the input is LLVM Assembly, bitcode is produced by serializing
4871480093f4SDimitry Andric       // the module. Use-lists order need to be preserved in this case.
4872480093f4SDimitry Andric       llvm::raw_string_ostream OS(Data);
4873480093f4SDimitry Andric       llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true);
4874480093f4SDimitry Andric       ModuleData =
4875480093f4SDimitry Andric           ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
4876480093f4SDimitry Andric     } else
4877480093f4SDimitry Andric       // If the input is LLVM bitcode, write the input byte stream directly.
4878480093f4SDimitry Andric       ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
4879480093f4SDimitry Andric                                      Buf.getBufferSize());
4880480093f4SDimitry Andric   }
4881480093f4SDimitry Andric   llvm::Constant *ModuleConstant =
4882480093f4SDimitry Andric       llvm::ConstantDataArray::get(M.getContext(), ModuleData);
4883480093f4SDimitry Andric   llvm::GlobalVariable *GV = new llvm::GlobalVariable(
4884480093f4SDimitry Andric       M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
4885480093f4SDimitry Andric       ModuleConstant);
4886480093f4SDimitry Andric   GV->setSection(getSectionNameForBitcode(T));
4887e8d8bef9SDimitry Andric   // Set alignment to 1 to prevent padding between two contributions from input
4888e8d8bef9SDimitry Andric   // sections after linking.
4889e8d8bef9SDimitry Andric   GV->setAlignment(Align(1));
4890480093f4SDimitry Andric   UsedArray.push_back(
4891480093f4SDimitry Andric       ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
4892480093f4SDimitry Andric   if (llvm::GlobalVariable *Old =
4893480093f4SDimitry Andric           M.getGlobalVariable("llvm.embedded.module", true)) {
4894480093f4SDimitry Andric     assert(Old->hasOneUse() &&
4895480093f4SDimitry Andric            "llvm.embedded.module can only be used once in llvm.compiler.used");
4896480093f4SDimitry Andric     GV->takeName(Old);
4897480093f4SDimitry Andric     Old->eraseFromParent();
4898480093f4SDimitry Andric   } else {
4899480093f4SDimitry Andric     GV->setName("llvm.embedded.module");
4900480093f4SDimitry Andric   }
4901480093f4SDimitry Andric 
4902480093f4SDimitry Andric   // Skip if only bitcode needs to be embedded.
4903e8d8bef9SDimitry Andric   if (EmbedCmdline) {
4904480093f4SDimitry Andric     // Embed command-line options.
4905e8d8bef9SDimitry Andric     ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CmdArgs.data()),
4906e8d8bef9SDimitry Andric                               CmdArgs.size());
4907480093f4SDimitry Andric     llvm::Constant *CmdConstant =
4908480093f4SDimitry Andric         llvm::ConstantDataArray::get(M.getContext(), CmdData);
4909480093f4SDimitry Andric     GV = new llvm::GlobalVariable(M, CmdConstant->getType(), true,
4910480093f4SDimitry Andric                                   llvm::GlobalValue::PrivateLinkage,
4911480093f4SDimitry Andric                                   CmdConstant);
4912480093f4SDimitry Andric     GV->setSection(getSectionNameForCommandline(T));
4913e8d8bef9SDimitry Andric     GV->setAlignment(Align(1));
4914480093f4SDimitry Andric     UsedArray.push_back(
4915480093f4SDimitry Andric         ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
4916480093f4SDimitry Andric     if (llvm::GlobalVariable *Old = M.getGlobalVariable("llvm.cmdline", true)) {
4917480093f4SDimitry Andric       assert(Old->hasOneUse() &&
4918480093f4SDimitry Andric              "llvm.cmdline can only be used once in llvm.compiler.used");
4919480093f4SDimitry Andric       GV->takeName(Old);
4920480093f4SDimitry Andric       Old->eraseFromParent();
4921480093f4SDimitry Andric     } else {
4922480093f4SDimitry Andric       GV->setName("llvm.cmdline");
4923480093f4SDimitry Andric     }
4924480093f4SDimitry Andric   }
4925480093f4SDimitry Andric 
4926480093f4SDimitry Andric   if (UsedArray.empty())
4927480093f4SDimitry Andric     return;
4928480093f4SDimitry Andric 
4929480093f4SDimitry Andric   // Recreate llvm.compiler.used.
4930480093f4SDimitry Andric   ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
4931480093f4SDimitry Andric   auto *NewUsed = new GlobalVariable(
4932480093f4SDimitry Andric       M, ATy, false, llvm::GlobalValue::AppendingLinkage,
4933480093f4SDimitry Andric       llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
4934480093f4SDimitry Andric   NewUsed->setSection("llvm.metadata");
4935480093f4SDimitry Andric }
4936