Coverage Report

Created: 2019-07-24 05:18

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