Coverage Report

Created: 2022-01-18 06:27

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Serialization/ASTWriter.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- ASTWriter.cpp - AST File 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
//  This file defines the ASTWriter class, which writes AST files.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "ASTCommon.h"
14
#include "ASTReaderInternals.h"
15
#include "MultiOnDiskHashTable.h"
16
#include "clang/AST/ASTContext.h"
17
#include "clang/AST/ASTUnresolvedSet.h"
18
#include "clang/AST/AbstractTypeWriter.h"
19
#include "clang/AST/Attr.h"
20
#include "clang/AST/Decl.h"
21
#include "clang/AST/DeclBase.h"
22
#include "clang/AST/DeclCXX.h"
23
#include "clang/AST/DeclContextInternals.h"
24
#include "clang/AST/DeclFriend.h"
25
#include "clang/AST/DeclObjC.h"
26
#include "clang/AST/DeclTemplate.h"
27
#include "clang/AST/DeclarationName.h"
28
#include "clang/AST/Expr.h"
29
#include "clang/AST/ExprCXX.h"
30
#include "clang/AST/LambdaCapture.h"
31
#include "clang/AST/NestedNameSpecifier.h"
32
#include "clang/AST/OpenMPClause.h"
33
#include "clang/AST/RawCommentList.h"
34
#include "clang/AST/TemplateName.h"
35
#include "clang/AST/Type.h"
36
#include "clang/AST/TypeLocVisitor.h"
37
#include "clang/Basic/Diagnostic.h"
38
#include "clang/Basic/DiagnosticOptions.h"
39
#include "clang/Basic/FileManager.h"
40
#include "clang/Basic/FileSystemOptions.h"
41
#include "clang/Basic/IdentifierTable.h"
42
#include "clang/Basic/LLVM.h"
43
#include "clang/Basic/Lambda.h"
44
#include "clang/Basic/LangOptions.h"
45
#include "clang/Basic/Module.h"
46
#include "clang/Basic/ObjCRuntime.h"
47
#include "clang/Basic/OpenCLOptions.h"
48
#include "clang/Basic/SourceLocation.h"
49
#include "clang/Basic/SourceManager.h"
50
#include "clang/Basic/SourceManagerInternals.h"
51
#include "clang/Basic/Specifiers.h"
52
#include "clang/Basic/TargetInfo.h"
53
#include "clang/Basic/TargetOptions.h"
54
#include "clang/Basic/Version.h"
55
#include "clang/Lex/HeaderSearch.h"
56
#include "clang/Lex/HeaderSearchOptions.h"
57
#include "clang/Lex/MacroInfo.h"
58
#include "clang/Lex/ModuleMap.h"
59
#include "clang/Lex/PreprocessingRecord.h"
60
#include "clang/Lex/Preprocessor.h"
61
#include "clang/Lex/PreprocessorOptions.h"
62
#include "clang/Lex/Token.h"
63
#include "clang/Sema/IdentifierResolver.h"
64
#include "clang/Sema/ObjCMethodList.h"
65
#include "clang/Sema/Sema.h"
66
#include "clang/Sema/Weak.h"
67
#include "clang/Serialization/ASTBitCodes.h"
68
#include "clang/Serialization/ASTReader.h"
69
#include "clang/Serialization/ASTRecordWriter.h"
70
#include "clang/Serialization/InMemoryModuleCache.h"
71
#include "clang/Serialization/ModuleFile.h"
72
#include "clang/Serialization/ModuleFileExtension.h"
73
#include "clang/Serialization/SerializationDiagnostic.h"
74
#include "llvm/ADT/APFloat.h"
75
#include "llvm/ADT/APInt.h"
76
#include "llvm/ADT/APSInt.h"
77
#include "llvm/ADT/ArrayRef.h"
78
#include "llvm/ADT/DenseMap.h"
79
#include "llvm/ADT/Hashing.h"
80
#include "llvm/ADT/Optional.h"
81
#include "llvm/ADT/PointerIntPair.h"
82
#include "llvm/ADT/STLExtras.h"
83
#include "llvm/ADT/ScopeExit.h"
84
#include "llvm/ADT/SmallPtrSet.h"
85
#include "llvm/ADT/SmallString.h"
86
#include "llvm/ADT/SmallVector.h"
87
#include "llvm/ADT/StringMap.h"
88
#include "llvm/ADT/StringRef.h"
89
#include "llvm/Bitstream/BitCodes.h"
90
#include "llvm/Bitstream/BitstreamWriter.h"
91
#include "llvm/Support/Casting.h"
92
#include "llvm/Support/Compression.h"
93
#include "llvm/Support/DJB.h"
94
#include "llvm/Support/Endian.h"
95
#include "llvm/Support/EndianStream.h"
96
#include "llvm/Support/Error.h"
97
#include "llvm/Support/ErrorHandling.h"
98
#include "llvm/Support/LEB128.h"
99
#include "llvm/Support/MemoryBuffer.h"
100
#include "llvm/Support/OnDiskHashTable.h"
101
#include "llvm/Support/Path.h"
102
#include "llvm/Support/SHA1.h"
103
#include "llvm/Support/VersionTuple.h"
104
#include "llvm/Support/raw_ostream.h"
105
#include <algorithm>
106
#include <cassert>
107
#include <cstdint>
108
#include <cstdlib>
109
#include <cstring>
110
#include <ctime>
111
#include <deque>
112
#include <limits>
113
#include <memory>
114
#include <queue>
115
#include <tuple>
116
#include <utility>
117
#include <vector>
118
119
using namespace clang;
120
using namespace clang::serialization;
121
122
template <typename T, typename Allocator>
123
32.5k
static StringRef bytes(const std::vector<T, Allocator> &v) {
124
32.5k
  if (v.empty()) 
return StringRef()1.69k
;
125
30.8k
  return StringRef(reinterpret_cast<const char*>(&v[0]),
126
30.8k
                         sizeof(T) * v.size());
127
32.5k
}
ASTWriter.cpp:llvm::StringRef bytes<unsigned long long, std::__1::allocator<unsigned long long> >(std::__1::vector<unsigned long long, std::__1::allocator<unsigned long long> > const&)
Line
Count
Source
123
5.38k
static StringRef bytes(const std::vector<T, Allocator> &v) {
124
5.38k
  if (v.empty()) 
return StringRef()0
;
125
5.38k
  return StringRef(reinterpret_cast<const char*>(&v[0]),
126
5.38k
                         sizeof(T) * v.size());
127
5.38k
}
ASTWriter.cpp:llvm::StringRef bytes<unsigned int, std::__1::allocator<unsigned int> >(std::__1::vector<unsigned int, std::__1::allocator<unsigned int> > const&)
Line
Count
Source
123
16.3k
static StringRef bytes(const std::vector<T, Allocator> &v) {
124
16.3k
  if (v.empty()) 
return StringRef()1.45k
;
125
14.9k
  return StringRef(reinterpret_cast<const char*>(&v[0]),
126
14.9k
                         sizeof(T) * v.size());
127
16.3k
}
ASTWriter.cpp:llvm::StringRef bytes<clang::serialization::PPSkippedRange, std::__1::allocator<clang::serialization::PPSkippedRange> >(std::__1::vector<clang::serialization::PPSkippedRange, std::__1::allocator<clang::serialization::PPSkippedRange> > const&)
Line
Count
Source
123
34
static StringRef bytes(const std::vector<T, Allocator> &v) {
124
34
  if (v.empty()) 
return StringRef()0
;
125
34
  return StringRef(reinterpret_cast<const char*>(&v[0]),
126
34
                         sizeof(T) * v.size());
127
34
}
ASTWriter.cpp:llvm::StringRef bytes<clang::serialization::UnderalignedInt64, std::__1::allocator<clang::serialization::UnderalignedInt64> >(std::__1::vector<clang::serialization::UnderalignedInt64, std::__1::allocator<clang::serialization::UnderalignedInt64> > const&)
Line
Count
Source
123
5.38k
static StringRef bytes(const std::vector<T, Allocator> &v) {
124
5.38k
  if (v.empty()) 
return StringRef()63
;
125
5.31k
  return StringRef(reinterpret_cast<const char*>(&v[0]),
126
5.31k
                         sizeof(T) * v.size());
127
5.38k
}
ASTWriter.cpp:llvm::StringRef bytes<clang::serialization::DeclOffset, std::__1::allocator<clang::serialization::DeclOffset> >(std::__1::vector<clang::serialization::DeclOffset, std::__1::allocator<clang::serialization::DeclOffset> > const&)
Line
Count
Source
123
5.38k
static StringRef bytes(const std::vector<T, Allocator> &v) {
124
5.38k
  if (v.empty()) 
return StringRef()180
;
125
5.20k
  return StringRef(reinterpret_cast<const char*>(&v[0]),
126
5.20k
                         sizeof(T) * v.size());
127
5.38k
}
128
129
template <typename T>
130
326k
static StringRef bytes(const SmallVectorImpl<T> &v) {
131
326k
  return StringRef(reinterpret_cast<const char*>(v.data()),
132
326k
                         sizeof(T) * v.size());
133
326k
}
ASTWriter.cpp:llvm::StringRef bytes<clang::serialization::PPEntityOffset>(llvm::SmallVectorImpl<clang::serialization::PPEntityOffset> const&)
Line
Count
Source
130
208
static StringRef bytes(const SmallVectorImpl<T> &v) {
131
208
  return StringRef(reinterpret_cast<const char*>(v.data()),
132
208
                         sizeof(T) * v.size());
133
208
}
ASTWriter.cpp:llvm::StringRef bytes<unsigned int>(llvm::SmallVectorImpl<unsigned int> const&)
Line
Count
Source
130
326k
static StringRef bytes(const SmallVectorImpl<T> &v) {
131
326k
  return StringRef(reinterpret_cast<const char*>(v.data()),
132
326k
                         sizeof(T) * v.size());
133
326k
}
134
135
5.38k
static std::string bytes(const std::vector<bool> &V) {
136
5.38k
  std::string Str;
137
5.38k
  Str.reserve(V.size() / 8);
138
10.7k
  for (unsigned I = 0, E = V.size(); I < E;) {
139
5.37k
    char Byte = 0;
140
14.3k
    for (unsigned Bit = 0; Bit < 8 && 
I < E14.2k
;
++Bit, ++I8.92k
)
141
8.92k
      Byte |= V[I] << Bit;
142
5.37k
    Str += Byte;
143
5.37k
  }
144
5.38k
  return Str;
145
5.38k
}
146
147
//===----------------------------------------------------------------------===//
148
// Type serialization
149
//===----------------------------------------------------------------------===//
150
151
1.45M
static TypeCode getTypeCodeForTypeClass(Type::TypeClass id) {
152
1.45M
  switch (id) {
153
0
#define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \
154
1.45M
  case Type::CLASS_ID: return TYPE_##CODE_ID;
155
0
#include "clang/Serialization/TypeBitCodes.def"
156
0
  case Type::Builtin:
157
0
    llvm_unreachable("shouldn't be serializing a builtin type this way");
158
1.45M
  }
159
0
  llvm_unreachable("bad type kind");
160
0
}
161
162
namespace {
163
164
std::set<const FileEntry *> GetAllModuleMaps(const HeaderSearch &HS,
165
1.95k
                                             Module *RootModule) {
166
1.95k
  std::set<const FileEntry *> ModuleMaps{};
167
1.95k
  std::set<Module *> ProcessedModules;
168
1.95k
  SmallVector<Module *> ModulesToProcess{RootModule};
169
170
1.95k
  SmallVector<const FileEntry *, 16> FilesByUID;
171
1.95k
  HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
172
173
1.95k
  if (FilesByUID.size() > HS.header_file_size())
174
883
    FilesByUID.resize(HS.header_file_size());
175
176
311k
  for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; 
++UID309k
) {
177
309k
    const FileEntry *File = FilesByUID[UID];
178
309k
    if (!File)
179
0
      continue;
180
181
309k
    const HeaderFileInfo *HFI =
182
309k
        HS.getExistingFileInfo(File, /*WantExternal*/ false);
183
309k
    if (!HFI || 
(186k
HFI->isModuleHeader186k
&&
!HFI->isCompilingModuleHeader176k
))
184
283k
      continue;
185
186
25.6k
    for (const auto &KH : HS.findAllModulesForHeader(File)) {
187
23.8k
      if (!KH.getModule())
188
0
        continue;
189
23.8k
      ModulesToProcess.push_back(KH.getModule());
190
23.8k
    }
191
25.6k
  }
192
193
77.8k
  while (!ModulesToProcess.empty()) {
194
75.9k
    auto *CurrentModule = ModulesToProcess.pop_back_val();
195
75.9k
    ProcessedModules.insert(CurrentModule);
196
197
75.9k
    auto *ModuleMapFile =
198
75.9k
        HS.getModuleMap().getModuleMapFileForUniquing(CurrentModule);
199
75.9k
    if (!ModuleMapFile) {
200
23.5k
      continue;
201
23.5k
    }
202
203
52.3k
    ModuleMaps.insert(ModuleMapFile);
204
205
228k
    for (auto *ImportedModule : (CurrentModule)->Imports) {
206
228k
      if (!ImportedModule ||
207
228k
          ProcessedModules.find(ImportedModule) != ProcessedModules.end()) {
208
178k
        continue;
209
178k
      }
210
50.0k
      ModulesToProcess.push_back(ImportedModule);
211
50.0k
    }
212
52.3k
  }
213
214
1.95k
  return ModuleMaps;
215
1.95k
}
216
217
class ASTTypeWriter {
218
  ASTWriter &Writer;
219
  ASTWriter::RecordData Record;
220
  ASTRecordWriter BasicWriter;
221
222
public:
223
  ASTTypeWriter(ASTWriter &Writer)
224
1.46M
    : Writer(Writer), BasicWriter(Writer, Record) {}
225
226
1.46M
  uint64_t write(QualType T) {
227
1.46M
    if (T.hasLocalNonFastQualifiers()) {
228
6.24k
      Qualifiers Qs = T.getLocalQualifiers();
229
6.24k
      BasicWriter.writeQualType(T.getLocalUnqualifiedType());
230
6.24k
      BasicWriter.writeQualifiers(Qs);
231
6.24k
      return BasicWriter.Emit(TYPE_EXT_QUAL, Writer.getTypeExtQualAbbrev());
232
6.24k
    }
233
234
1.45M
    const Type *typePtr = T.getTypePtr();
235
1.45M
    serialization::AbstractTypeWriter<ASTRecordWriter> atw(BasicWriter);
236
1.45M
    atw.write(typePtr);
237
1.45M
    return BasicWriter.Emit(getTypeCodeForTypeClass(typePtr->getTypeClass()),
238
1.45M
                            /*abbrev*/ 0);
239
1.46M
  }
240
};
241
242
class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
243
  ASTRecordWriter &Record;
244
245
public:
246
2.79M
  TypeLocWriter(ASTRecordWriter &Record) : Record(Record) {}
247
248
#define ABSTRACT_TYPELOC(CLASS, PARENT)
249
#define TYPELOC(CLASS, PARENT) \
250
    void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
251
#include "clang/AST/TypeLocNodes.def"
252
253
  void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
254
  void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
255
};
256
257
} // namespace
258
259
192k
void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
260
  // nothing to do
261
192k
}
262
263
572k
void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
264
572k
  Record.AddSourceLocation(TL.getBuiltinLoc());
265
572k
  if (TL.needsExtraLocalData()) {
266
312k
    Record.push_back(TL.getWrittenTypeSpec());
267
312k
    Record.push_back(static_cast<uint64_t>(TL.getWrittenSignSpec()));
268
312k
    Record.push_back(static_cast<uint64_t>(TL.getWrittenWidthSpec()));
269
312k
    Record.push_back(TL.hasModeAttr());
270
312k
  }
271
572k
}
272
273
4.49k
void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
274
4.49k
  Record.AddSourceLocation(TL.getNameLoc());
275
4.49k
}
276
277
280k
void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
278
280k
  Record.AddSourceLocation(TL.getStarLoc());
279
280k
}
280
281
158
void TypeLocWriter::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
282
  // nothing to do
283
158
}
284
285
0
void TypeLocWriter::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
286
  // nothing to do
287
0
}
288
289
1.84k
void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
290
1.84k
  Record.AddSourceLocation(TL.getCaretLoc());
291
1.84k
}
292
293
131k
void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
294
131k
  Record.AddSourceLocation(TL.getAmpLoc());
295
131k
}
296
297
17.4k
void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
298
17.4k
  Record.AddSourceLocation(TL.getAmpAmpLoc());
299
17.4k
}
300
301
1.12k
void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
302
1.12k
  Record.AddSourceLocation(TL.getStarLoc());
303
1.12k
  Record.AddTypeSourceInfo(TL.getClassTInfo());
304
1.12k
}
305
306
32.5k
void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
307
32.5k
  Record.AddSourceLocation(TL.getLBracketLoc());
308
32.5k
  Record.AddSourceLocation(TL.getRBracketLoc());
309
32.5k
  Record.push_back(TL.getSizeExpr() ? 
119.4k
:
013.0k
);
310
32.5k
  if (TL.getSizeExpr())
311
19.4k
    Record.AddStmt(TL.getSizeExpr());
312
32.5k
}
313
314
21.9k
void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
315
21.9k
  VisitArrayTypeLoc(TL);
316
21.9k
}
317
318
3.95k
void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
319
3.95k
  VisitArrayTypeLoc(TL);
320
3.95k
}
321
322
5.31k
void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
323
5.31k
  VisitArrayTypeLoc(TL);
324
5.31k
}
325
326
void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
327
1.28k
                                            DependentSizedArrayTypeLoc TL) {
328
1.28k
  VisitArrayTypeLoc(TL);
329
1.28k
}
330
331
void TypeLocWriter::VisitDependentAddressSpaceTypeLoc(
332
11
    DependentAddressSpaceTypeLoc TL) {
333
11
  Record.AddSourceLocation(TL.getAttrNameLoc());
334
11
  SourceRange range = TL.getAttrOperandParensRange();
335
11
  Record.AddSourceLocation(range.getBegin());
336
11
  Record.AddSourceLocation(range.getEnd());
337
11
  Record.AddStmt(TL.getAttrExprOperand());
338
11
}
339
340
void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
341
8
                                        DependentSizedExtVectorTypeLoc TL) {
342
8
  Record.AddSourceLocation(TL.getNameLoc());
343
8
}
344
345
1.92k
void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
346
1.92k
  Record.AddSourceLocation(TL.getNameLoc());
347
1.92k
}
348
349
void TypeLocWriter::VisitDependentVectorTypeLoc(
350
0
    DependentVectorTypeLoc TL) {
351
0
  Record.AddSourceLocation(TL.getNameLoc());
352
0
}
353
354
352
void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
355
352
  Record.AddSourceLocation(TL.getNameLoc());
356
352
}
357
358
0
void TypeLocWriter::VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc TL) {
359
0
  Record.AddSourceLocation(TL.getAttrNameLoc());
360
0
  SourceRange range = TL.getAttrOperandParensRange();
361
0
  Record.AddSourceLocation(range.getBegin());
362
0
  Record.AddSourceLocation(range.getEnd());
363
0
  Record.AddStmt(TL.getAttrRowOperand());
364
0
  Record.AddStmt(TL.getAttrColumnOperand());
365
0
}
366
367
void TypeLocWriter::VisitDependentSizedMatrixTypeLoc(
368
0
    DependentSizedMatrixTypeLoc TL) {
369
0
  Record.AddSourceLocation(TL.getAttrNameLoc());
370
0
  SourceRange range = TL.getAttrOperandParensRange();
371
0
  Record.AddSourceLocation(range.getBegin());
372
0
  Record.AddSourceLocation(range.getEnd());
373
0
  Record.AddStmt(TL.getAttrRowOperand());
374
0
  Record.AddStmt(TL.getAttrColumnOperand());
375
0
}
376
377
434k
void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
378
434k
  Record.AddSourceLocation(TL.getLocalRangeBegin());
379
434k
  Record.AddSourceLocation(TL.getLParenLoc());
380
434k
  Record.AddSourceLocation(TL.getRParenLoc());
381
434k
  Record.AddSourceRange(TL.getExceptionSpecRange());
382
434k
  Record.AddSourceLocation(TL.getLocalRangeEnd());
383
1.21M
  for (unsigned i = 0, e = TL.getNumParams(); i != e; 
++i782k
)
384
782k
    Record.AddDeclRef(TL.getParam(i));
385
434k
}
386
387
434k
void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
388
434k
  VisitFunctionTypeLoc(TL);
389
434k
}
390
391
233
void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
392
233
  VisitFunctionTypeLoc(TL);
393
233
}
394
395
128
void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
396
128
  Record.AddSourceLocation(TL.getNameLoc());
397
128
}
398
399
29.7k
void TypeLocWriter::VisitUsingTypeLoc(UsingTypeLoc TL) {
400
29.7k
  Record.AddSourceLocation(TL.getNameLoc());
401
29.7k
}
402
403
1.20M
void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
404
1.20M
  Record.AddSourceLocation(TL.getNameLoc());
405
1.20M
}
406
407
1.62k
void TypeLocWriter::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
408
1.62k
  if (TL.getNumProtocols()) {
409
38
    Record.AddSourceLocation(TL.getProtocolLAngleLoc());
410
38
    Record.AddSourceLocation(TL.getProtocolRAngleLoc());
411
38
  }
412
1.66k
  for (unsigned i = 0, e = TL.getNumProtocols(); i != e; 
++i39
)
413
39
    Record.AddSourceLocation(TL.getProtocolLoc(i));
414
1.62k
}
415
416
77
void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
417
77
  Record.AddSourceLocation(TL.getTypeofLoc());
418
77
  Record.AddSourceLocation(TL.getLParenLoc());
419
77
  Record.AddSourceLocation(TL.getRParenLoc());
420
77
}
421
422
18
void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
423
18
  Record.AddSourceLocation(TL.getTypeofLoc());
424
18
  Record.AddSourceLocation(TL.getLParenLoc());
425
18
  Record.AddSourceLocation(TL.getRParenLoc());
426
18
  Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
427
18
}
428
429
4.11k
void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
430
4.11k
  Record.AddSourceLocation(TL.getDecltypeLoc());
431
4.11k
  Record.AddSourceLocation(TL.getRParenLoc());
432
4.11k
}
433
434
63
void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
435
63
  Record.AddSourceLocation(TL.getKWLoc());
436
63
  Record.AddSourceLocation(TL.getLParenLoc());
437
63
  Record.AddSourceLocation(TL.getRParenLoc());
438
63
  Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
439
63
}
440
441
1.27k
void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
442
1.27k
  Record.AddSourceLocation(TL.getNameLoc());
443
1.27k
  Record.push_back(TL.isConstrained());
444
1.27k
  if (TL.isConstrained()) {
445
0
    Record.AddNestedNameSpecifierLoc(TL.getNestedNameSpecifierLoc());
446
0
    Record.AddSourceLocation(TL.getTemplateKWLoc());
447
0
    Record.AddSourceLocation(TL.getConceptNameLoc());
448
0
    Record.AddDeclRef(TL.getFoundDecl());
449
0
    Record.AddSourceLocation(TL.getLAngleLoc());
450
0
    Record.AddSourceLocation(TL.getRAngleLoc());
451
0
    for (unsigned I = 0; I < TL.getNumArgs(); ++I)
452
0
      Record.AddTemplateArgumentLocInfo(TL.getTypePtr()->getArg(I).getKind(),
453
0
                                        TL.getArgLocInfo(I));
454
0
  }
455
1.27k
  Record.push_back(TL.isDecltypeAuto());
456
1.27k
  if (TL.isDecltypeAuto())
457
62
    Record.AddSourceLocation(TL.getRParenLoc());
458
1.27k
}
459
460
void TypeLocWriter::VisitDeducedTemplateSpecializationTypeLoc(
461
9
    DeducedTemplateSpecializationTypeLoc TL) {
462
9
  Record.AddSourceLocation(TL.getTemplateNameLoc());
463
9
}
464
465
137k
void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
466
137k
  Record.AddSourceLocation(TL.getNameLoc());
467
137k
}
468
469
11.1k
void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
470
11.1k
  Record.AddSourceLocation(TL.getNameLoc());
471
11.1k
}
472
473
101k
void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
474
101k
  Record.AddAttr(TL.getAttr());
475
101k
}
476
477
319k
void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
478
319k
  Record.AddSourceLocation(TL.getNameLoc());
479
319k
}
480
481
void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
482
116k
                                            SubstTemplateTypeParmTypeLoc TL) {
483
116k
  Record.AddSourceLocation(TL.getNameLoc());
484
116k
}
485
486
void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
487
0
                                          SubstTemplateTypeParmPackTypeLoc TL) {
488
0
  Record.AddSourceLocation(TL.getNameLoc());
489
0
}
490
491
void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
492
293k
                                           TemplateSpecializationTypeLoc TL) {
493
293k
  Record.AddSourceLocation(TL.getTemplateKeywordLoc());
494
293k
  Record.AddSourceLocation(TL.getTemplateNameLoc());
495
293k
  Record.AddSourceLocation(TL.getLAngleLoc());
496
293k
  Record.AddSourceLocation(TL.getRAngleLoc());
497
766k
  for (unsigned i = 0, e = TL.getNumArgs(); i != e; 
++i472k
)
498
472k
    Record.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
499
472k
                                      TL.getArgLoc(i).getLocInfo());
500
293k
}
501
502
27.4k
void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
503
27.4k
  Record.AddSourceLocation(TL.getLParenLoc());
504
27.4k
  Record.AddSourceLocation(TL.getRParenLoc());
505
27.4k
}
506
507
7.15k
void TypeLocWriter::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
508
7.15k
  Record.AddSourceLocation(TL.getExpansionLoc());
509
7.15k
}
510
511
92.0k
void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
512
92.0k
  Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
513
92.0k
  Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
514
92.0k
}
515
516
24.5k
void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
517
24.5k
  Record.AddSourceLocation(TL.getNameLoc());
518
24.5k
}
519
520
35.8k
void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
521
35.8k
  Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
522
35.8k
  Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
523
35.8k
  Record.AddSourceLocation(TL.getNameLoc());
524
35.8k
}
525
526
void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
527
262
       DependentTemplateSpecializationTypeLoc TL) {
528
262
  Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
529
262
  Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
530
262
  Record.AddSourceLocation(TL.getTemplateKeywordLoc());
531
262
  Record.AddSourceLocation(TL.getTemplateNameLoc());
532
262
  Record.AddSourceLocation(TL.getLAngleLoc());
533
262
  Record.AddSourceLocation(TL.getRAngleLoc());
534
556
  for (unsigned I = 0, E = TL.getNumArgs(); I != E; 
++I294
)
535
294
    Record.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
536
294
                                      TL.getArgLoc(I).getLocInfo());
537
262
}
538
539
15.7k
void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
540
15.7k
  Record.AddSourceLocation(TL.getEllipsisLoc());
541
15.7k
}
542
543
38.3k
void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
544
38.3k
  Record.AddSourceLocation(TL.getNameLoc());
545
38.3k
}
546
547
5.82k
void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
548
5.82k
  Record.push_back(TL.hasBaseTypeAsWritten());
549
5.82k
  Record.AddSourceLocation(TL.getTypeArgsLAngleLoc());
550
5.82k
  Record.AddSourceLocation(TL.getTypeArgsRAngleLoc());
551
11.1k
  for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; 
++i5.27k
)
552
5.27k
    Record.AddTypeSourceInfo(TL.getTypeArgTInfo(i));
553
5.82k
  Record.AddSourceLocation(TL.getProtocolLAngleLoc());
554
5.82k
  Record.AddSourceLocation(TL.getProtocolRAngleLoc());
555
7.46k
  for (unsigned i = 0, e = TL.getNumProtocols(); i != e; 
++i1.64k
)
556
1.64k
    Record.AddSourceLocation(TL.getProtocolLoc(i));
557
5.82k
}
558
559
37.3k
void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
560
37.3k
  Record.AddSourceLocation(TL.getStarLoc());
561
37.3k
}
562
563
1.04k
void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
564
1.04k
  Record.AddSourceLocation(TL.getKWLoc());
565
1.04k
  Record.AddSourceLocation(TL.getLParenLoc());
566
1.04k
  Record.AddSourceLocation(TL.getRParenLoc());
567
1.04k
}
568
569
15
void TypeLocWriter::VisitPipeTypeLoc(PipeTypeLoc TL) {
570
15
  Record.AddSourceLocation(TL.getKWLoc());
571
15
}
572
573
0
void TypeLocWriter::VisitBitIntTypeLoc(clang::BitIntTypeLoc TL) {
574
0
  Record.AddSourceLocation(TL.getNameLoc());
575
0
}
576
void TypeLocWriter::VisitDependentBitIntTypeLoc(
577
0
    clang::DependentBitIntTypeLoc TL) {
578
0
  Record.AddSourceLocation(TL.getNameLoc());
579
0
}
580
581
5.38k
void ASTWriter::WriteTypeAbbrevs() {
582
5.38k
  using namespace llvm;
583
584
5.38k
  std::shared_ptr<BitCodeAbbrev> Abv;
585
586
  // Abbreviation for TYPE_EXT_QUAL
587
5.38k
  Abv = std::make_shared<BitCodeAbbrev>();
588
5.38k
  Abv->Add(BitCodeAbbrevOp(serialization::TYPE_EXT_QUAL));
589
5.38k
  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // Type
590
5.38k
  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3));   // Quals
591
5.38k
  TypeExtQualAbbrev = Stream.EmitAbbrev(std::move(Abv));
592
593
  // Abbreviation for TYPE_FUNCTION_PROTO
594
5.38k
  Abv = std::make_shared<BitCodeAbbrev>();
595
5.38k
  Abv->Add(BitCodeAbbrevOp(serialization::TYPE_FUNCTION_PROTO));
596
  // FunctionType
597
5.38k
  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // ReturnType
598
5.38k
  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // NoReturn
599
5.38k
  Abv->Add(BitCodeAbbrevOp(0));                         // HasRegParm
600
5.38k
  Abv->Add(BitCodeAbbrevOp(0));                         // RegParm
601
5.38k
  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // CC
602
5.38k
  Abv->Add(BitCodeAbbrevOp(0));                         // ProducesResult
603
5.38k
  Abv->Add(BitCodeAbbrevOp(0));                         // NoCallerSavedRegs
604
5.38k
  Abv->Add(BitCodeAbbrevOp(0));                         // NoCfCheck
605
5.38k
  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // CmseNSCall
606
  // FunctionProtoType
607
5.38k
  Abv->Add(BitCodeAbbrevOp(0));                         // IsVariadic
608
5.38k
  Abv->Add(BitCodeAbbrevOp(0));                         // HasTrailingReturn
609
5.38k
  Abv->Add(BitCodeAbbrevOp(0));                         // TypeQuals
610
5.38k
  Abv->Add(BitCodeAbbrevOp(0));                         // RefQualifier
611
5.38k
  Abv->Add(BitCodeAbbrevOp(EST_None));                  // ExceptionSpec
612
5.38k
  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // NumParams
613
5.38k
  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
614
5.38k
  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // Params
615
5.38k
  TypeFunctionProtoAbbrev = Stream.EmitAbbrev(std::move(Abv));
616
5.38k
}
617
618
//===----------------------------------------------------------------------===//
619
// ASTWriter Implementation
620
//===----------------------------------------------------------------------===//
621
622
static void EmitBlockID(unsigned ID, const char *Name,
623
                        llvm::BitstreamWriter &Stream,
624
64.5k
                        ASTWriter::RecordDataImpl &Record) {
625
64.5k
  Record.clear();
626
64.5k
  Record.push_back(ID);
627
64.5k
  Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
628
629
  // Emit the block name if present.
630
64.5k
  if (!Name || Name[0] == 0)
631
0
    return;
632
64.5k
  Record.clear();
633
1.11M
  while (*Name)
634
1.05M
    Record.push_back(*Name++);
635
64.5k
  Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
636
64.5k
}
637
638
static void EmitRecordID(unsigned ID, const char *Name,
639
                         llvm::BitstreamWriter &Stream,
640
1.86M
                         ASTWriter::RecordDataImpl &Record) {
641
1.86M
  Record.clear();
642
1.86M
  Record.push_back(ID);
643
37.5M
  while (*Name)
644
35.7M
    Record.push_back(*Name++);
645
1.86M
  Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
646
1.86M
}
647
648
static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
649
5.38k
                          ASTWriter::RecordDataImpl &Record) {
650
677k
#define RECORD(X) EmitRecordID(X, #X, Stream, Record)
651
5.38k
  RECORD(STMT_STOP);
652
5.38k
  RECORD(STMT_NULL_PTR);
653
5.38k
  RECORD(STMT_REF_PTR);
654
5.38k
  RECORD(STMT_NULL);
655
5.38k
  RECORD(STMT_COMPOUND);
656
5.38k
  RECORD(STMT_CASE);
657
5.38k
  RECORD(STMT_DEFAULT);
658
5.38k
  RECORD(STMT_LABEL);
659
5.38k
  RECORD(STMT_ATTRIBUTED);
660
5.38k
  RECORD(STMT_IF);
661
5.38k
  RECORD(STMT_SWITCH);
662
5.38k
  RECORD(STMT_WHILE);
663
5.38k
  RECORD(STMT_DO);
664
5.38k
  RECORD(STMT_FOR);
665
5.38k
  RECORD(STMT_GOTO);
666
5.38k
  RECORD(STMT_INDIRECT_GOTO);
667
5.38k
  RECORD(STMT_CONTINUE);
668
5.38k
  RECORD(STMT_BREAK);
669
5.38k
  RECORD(STMT_RETURN);
670
5.38k
  RECORD(STMT_DECL);
671
5.38k
  RECORD(STMT_GCCASM);
672
5.38k
  RECORD(STMT_MSASM);
673
5.38k
  RECORD(EXPR_PREDEFINED);
674
5.38k
  RECORD(EXPR_DECL_REF);
675
5.38k
  RECORD(EXPR_INTEGER_LITERAL);
676
5.38k
  RECORD(EXPR_FIXEDPOINT_LITERAL);
677
5.38k
  RECORD(EXPR_FLOATING_LITERAL);
678
5.38k
  RECORD(EXPR_IMAGINARY_LITERAL);
679
5.38k
  RECORD(EXPR_STRING_LITERAL);
680
5.38k
  RECORD(EXPR_CHARACTER_LITERAL);
681
5.38k
  RECORD(EXPR_PAREN);
682
5.38k
  RECORD(EXPR_PAREN_LIST);
683
5.38k
  RECORD(EXPR_UNARY_OPERATOR);
684
5.38k
  RECORD(EXPR_SIZEOF_ALIGN_OF);
685
5.38k
  RECORD(EXPR_ARRAY_SUBSCRIPT);
686
5.38k
  RECORD(EXPR_CALL);
687
5.38k
  RECORD(EXPR_MEMBER);
688
5.38k
  RECORD(EXPR_BINARY_OPERATOR);
689
5.38k
  RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
690
5.38k
  RECORD(EXPR_CONDITIONAL_OPERATOR);
691
5.38k
  RECORD(EXPR_IMPLICIT_CAST);
692
5.38k
  RECORD(EXPR_CSTYLE_CAST);
693
5.38k
  RECORD(EXPR_COMPOUND_LITERAL);
694
5.38k
  RECORD(EXPR_EXT_VECTOR_ELEMENT);
695
5.38k
  RECORD(EXPR_INIT_LIST);
696
5.38k
  RECORD(EXPR_DESIGNATED_INIT);
697
5.38k
  RECORD(EXPR_DESIGNATED_INIT_UPDATE);
698
5.38k
  RECORD(EXPR_IMPLICIT_VALUE_INIT);
699
5.38k
  RECORD(EXPR_NO_INIT);
700
5.38k
  RECORD(EXPR_VA_ARG);
701
5.38k
  RECORD(EXPR_ADDR_LABEL);
702
5.38k
  RECORD(EXPR_STMT);
703
5.38k
  RECORD(EXPR_CHOOSE);
704
5.38k
  RECORD(EXPR_GNU_NULL);
705
5.38k
  RECORD(EXPR_SHUFFLE_VECTOR);
706
5.38k
  RECORD(EXPR_BLOCK);
707
5.38k
  RECORD(EXPR_GENERIC_SELECTION);
708
5.38k
  RECORD(EXPR_OBJC_STRING_LITERAL);
709
5.38k
  RECORD(EXPR_OBJC_BOXED_EXPRESSION);
710
5.38k
  RECORD(EXPR_OBJC_ARRAY_LITERAL);
711
5.38k
  RECORD(EXPR_OBJC_DICTIONARY_LITERAL);
712
5.38k
  RECORD(EXPR_OBJC_ENCODE);
713
5.38k
  RECORD(EXPR_OBJC_SELECTOR_EXPR);
714
5.38k
  RECORD(EXPR_OBJC_PROTOCOL_EXPR);
715
5.38k
  RECORD(EXPR_OBJC_IVAR_REF_EXPR);
716
5.38k
  RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
717
5.38k
  RECORD(EXPR_OBJC_KVC_REF_EXPR);
718
5.38k
  RECORD(EXPR_OBJC_MESSAGE_EXPR);
719
5.38k
  RECORD(STMT_OBJC_FOR_COLLECTION);
720
5.38k
  RECORD(STMT_OBJC_CATCH);
721
5.38k
  RECORD(STMT_OBJC_FINALLY);
722
5.38k
  RECORD(STMT_OBJC_AT_TRY);
723
5.38k
  RECORD(STMT_OBJC_AT_SYNCHRONIZED);
724
5.38k
  RECORD(STMT_OBJC_AT_THROW);
725
5.38k
  RECORD(EXPR_OBJC_BOOL_LITERAL);
726
5.38k
  RECORD(STMT_CXX_CATCH);
727
5.38k
  RECORD(STMT_CXX_TRY);
728
5.38k
  RECORD(STMT_CXX_FOR_RANGE);
729
5.38k
  RECORD(EXPR_CXX_OPERATOR_CALL);
730
5.38k
  RECORD(EXPR_CXX_MEMBER_CALL);
731
5.38k
  RECORD(EXPR_CXX_REWRITTEN_BINARY_OPERATOR);
732
5.38k
  RECORD(EXPR_CXX_CONSTRUCT);
733
5.38k
  RECORD(EXPR_CXX_TEMPORARY_OBJECT);
734
5.38k
  RECORD(EXPR_CXX_STATIC_CAST);
735
5.38k
  RECORD(EXPR_CXX_DYNAMIC_CAST);
736
5.38k
  RECORD(EXPR_CXX_REINTERPRET_CAST);
737
5.38k
  RECORD(EXPR_CXX_CONST_CAST);
738
5.38k
  RECORD(EXPR_CXX_ADDRSPACE_CAST);
739
5.38k
  RECORD(EXPR_CXX_FUNCTIONAL_CAST);
740
5.38k
  RECORD(EXPR_USER_DEFINED_LITERAL);
741
5.38k
  RECORD(EXPR_CXX_STD_INITIALIZER_LIST);
742
5.38k
  RECORD(EXPR_CXX_BOOL_LITERAL);
743
5.38k
  RECORD(EXPR_CXX_NULL_PTR_LITERAL);
744
5.38k
  RECORD(EXPR_CXX_TYPEID_EXPR);
745
5.38k
  RECORD(EXPR_CXX_TYPEID_TYPE);
746
5.38k
  RECORD(EXPR_CXX_THIS);
747
5.38k
  RECORD(EXPR_CXX_THROW);
748
5.38k
  RECORD(EXPR_CXX_DEFAULT_ARG);
749
5.38k
  RECORD(EXPR_CXX_DEFAULT_INIT);
750
5.38k
  RECORD(EXPR_CXX_BIND_TEMPORARY);
751
5.38k
  RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
752
5.38k
  RECORD(EXPR_CXX_NEW);
753
5.38k
  RECORD(EXPR_CXX_DELETE);
754
5.38k
  RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
755
5.38k
  RECORD(EXPR_EXPR_WITH_CLEANUPS);
756
5.38k
  RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
757
5.38k
  RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
758
5.38k
  RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
759
5.38k
  RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
760
5.38k
  RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
761
5.38k
  RECORD(EXPR_CXX_EXPRESSION_TRAIT);
762
5.38k
  RECORD(EXPR_CXX_NOEXCEPT);
763
5.38k
  RECORD(EXPR_OPAQUE_VALUE);
764
5.38k
  RECORD(EXPR_BINARY_CONDITIONAL_OPERATOR);
765
5.38k
  RECORD(EXPR_TYPE_TRAIT);
766
5.38k
  RECORD(EXPR_ARRAY_TYPE_TRAIT);
767
5.38k
  RECORD(EXPR_PACK_EXPANSION);
768
5.38k
  RECORD(EXPR_SIZEOF_PACK);
769
5.38k
  RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM);
770
5.38k
  RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
771
5.38k
  RECORD(EXPR_FUNCTION_PARM_PACK);
772
5.38k
  RECORD(EXPR_MATERIALIZE_TEMPORARY);
773
5.38k
  RECORD(EXPR_CUDA_KERNEL_CALL);
774
5.38k
  RECORD(EXPR_CXX_UUIDOF_EXPR);
775
5.38k
  RECORD(EXPR_CXX_UUIDOF_TYPE);
776
5.38k
  RECORD(EXPR_LAMBDA);
777
5.38k
#undef RECORD
778
5.38k
}
779
780
5.38k
void ASTWriter::WriteBlockInfoBlock() {
781
5.38k
  RecordData Record;
782
5.38k
  Stream.EnterBlockInfoBlock();
783
784
64.5k
#define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
785
1.18M
#define RECORD(X) EmitRecordID(X, #X, Stream, Record)
786
787
  // Control Block.
788
5.38k
  BLOCK(CONTROL_BLOCK);
789
5.38k
  RECORD(METADATA);
790
5.38k
  RECORD(MODULE_NAME);
791
5.38k
  RECORD(MODULE_DIRECTORY);
792
5.38k
  RECORD(MODULE_MAP_FILE);
793
5.38k
  RECORD(IMPORTS);
794
5.38k
  RECORD(ORIGINAL_FILE);
795
5.38k
  RECORD(ORIGINAL_PCH_DIR);
796
5.38k
  RECORD(ORIGINAL_FILE_ID);
797
5.38k
  RECORD(INPUT_FILE_OFFSETS);
798
799
5.38k
  BLOCK(OPTIONS_BLOCK);
800
5.38k
  RECORD(LANGUAGE_OPTIONS);
801
5.38k
  RECORD(TARGET_OPTIONS);
802
5.38k
  RECORD(FILE_SYSTEM_OPTIONS);
803
5.38k
  RECORD(HEADER_SEARCH_OPTIONS);
804
5.38k
  RECORD(PREPROCESSOR_OPTIONS);
805
806
5.38k
  BLOCK(INPUT_FILES_BLOCK);
807
5.38k
  RECORD(INPUT_FILE);
808
5.38k
  RECORD(INPUT_FILE_HASH);
809
810
  // AST Top-Level Block.
811
5.38k
  BLOCK(AST_BLOCK);
812
5.38k
  RECORD(TYPE_OFFSET);
813
5.38k
  RECORD(DECL_OFFSET);
814
5.38k
  RECORD(IDENTIFIER_OFFSET);
815
5.38k
  RECORD(IDENTIFIER_TABLE);
816
5.38k
  RECORD(EAGERLY_DESERIALIZED_DECLS);
817
5.38k
  RECORD(MODULAR_CODEGEN_DECLS);
818
5.38k
  RECORD(SPECIAL_TYPES);
819
5.38k
  RECORD(STATISTICS);
820
5.38k
  RECORD(TENTATIVE_DEFINITIONS);
821
5.38k
  RECORD(SELECTOR_OFFSETS);
822
5.38k
  RECORD(METHOD_POOL);
823
5.38k
  RECORD(PP_COUNTER_VALUE);
824
5.38k
  RECORD(SOURCE_LOCATION_OFFSETS);
825
5.38k
  RECORD(SOURCE_LOCATION_PRELOADS);
826
5.38k
  RECORD(EXT_VECTOR_DECLS);
827
5.38k
  RECORD(UNUSED_FILESCOPED_DECLS);
828
5.38k
  RECORD(PPD_ENTITIES_OFFSETS);
829
5.38k
  RECORD(VTABLE_USES);
830
5.38k
  RECORD(PPD_SKIPPED_RANGES);
831
5.38k
  RECORD(REFERENCED_SELECTOR_POOL);
832
5.38k
  RECORD(TU_UPDATE_LEXICAL);
833
5.38k
  RECORD(SEMA_DECL_REFS);
834
5.38k
  RECORD(WEAK_UNDECLARED_IDENTIFIERS);
835
5.38k
  RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
836
5.38k
  RECORD(UPDATE_VISIBLE);
837
5.38k
  RECORD(DECL_UPDATE_OFFSETS);
838
5.38k
  RECORD(DECL_UPDATES);
839
5.38k
  RECORD(CUDA_SPECIAL_DECL_REFS);
840
5.38k
  RECORD(HEADER_SEARCH_TABLE);
841
5.38k
  RECORD(FP_PRAGMA_OPTIONS);
842
5.38k
  RECORD(OPENCL_EXTENSIONS);
843
5.38k
  RECORD(OPENCL_EXTENSION_TYPES);
844
5.38k
  RECORD(OPENCL_EXTENSION_DECLS);
845
5.38k
  RECORD(DELEGATING_CTORS);
846
5.38k
  RECORD(KNOWN_NAMESPACES);
847
5.38k
  RECORD(MODULE_OFFSET_MAP);
848
5.38k
  RECORD(SOURCE_MANAGER_LINE_TABLE);
849
5.38k
  RECORD(OBJC_CATEGORIES_MAP);
850
5.38k
  RECORD(FILE_SORTED_DECLS);
851
5.38k
  RECORD(IMPORTED_MODULES);
852
5.38k
  RECORD(OBJC_CATEGORIES);
853
5.38k
  RECORD(MACRO_OFFSET);
854
5.38k
  RECORD(INTERESTING_IDENTIFIERS);
855
5.38k
  RECORD(UNDEFINED_BUT_USED);
856
5.38k
  RECORD(LATE_PARSED_TEMPLATE);
857
5.38k
  RECORD(OPTIMIZE_PRAGMA_OPTIONS);
858
5.38k
  RECORD(MSSTRUCT_PRAGMA_OPTIONS);
859
5.38k
  RECORD(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS);
860
5.38k
  RECORD(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES);
861
5.38k
  RECORD(DELETE_EXPRS_TO_ANALYZE);
862
5.38k
  RECORD(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH);
863
5.38k
  RECORD(PP_CONDITIONAL_STACK);
864
5.38k
  RECORD(DECLS_TO_CHECK_FOR_DEFERRED_DIAGS);
865
866
  // SourceManager Block.
867
5.38k
  BLOCK(SOURCE_MANAGER_BLOCK);
868
5.38k
  RECORD(SM_SLOC_FILE_ENTRY);
869
5.38k
  RECORD(SM_SLOC_BUFFER_ENTRY);
870
5.38k
  RECORD(SM_SLOC_BUFFER_BLOB);
871
5.38k
  RECORD(SM_SLOC_BUFFER_BLOB_COMPRESSED);
872
5.38k
  RECORD(SM_SLOC_EXPANSION_ENTRY);
873
874
  // Preprocessor Block.
875
5.38k
  BLOCK(PREPROCESSOR_BLOCK);
876
5.38k
  RECORD(PP_MACRO_DIRECTIVE_HISTORY);
877
5.38k
  RECORD(PP_MACRO_FUNCTION_LIKE);
878
5.38k
  RECORD(PP_MACRO_OBJECT_LIKE);
879
5.38k
  RECORD(PP_MODULE_MACRO);
880
5.38k
  RECORD(PP_TOKEN);
881
882
  // Submodule Block.
883
5.38k
  BLOCK(SUBMODULE_BLOCK);
884
5.38k
  RECORD(SUBMODULE_METADATA);
885
5.38k
  RECORD(SUBMODULE_DEFINITION);
886
5.38k
  RECORD(SUBMODULE_UMBRELLA_HEADER);
887
5.38k
  RECORD(SUBMODULE_HEADER);
888
5.38k
  RECORD(SUBMODULE_TOPHEADER);
889
5.38k
  RECORD(SUBMODULE_UMBRELLA_DIR);
890
5.38k
  RECORD(SUBMODULE_IMPORTS);
891
5.38k
  RECORD(SUBMODULE_EXPORTS);
892
5.38k
  RECORD(SUBMODULE_REQUIRES);
893
5.38k
  RECORD(SUBMODULE_EXCLUDED_HEADER);
894
5.38k
  RECORD(SUBMODULE_LINK_LIBRARY);
895
5.38k
  RECORD(SUBMODULE_CONFIG_MACRO);
896
5.38k
  RECORD(SUBMODULE_CONFLICT);
897
5.38k
  RECORD(SUBMODULE_PRIVATE_HEADER);
898
5.38k
  RECORD(SUBMODULE_TEXTUAL_HEADER);
899
5.38k
  RECORD(SUBMODULE_PRIVATE_TEXTUAL_HEADER);
900
5.38k
  RECORD(SUBMODULE_INITIALIZERS);
901
5.38k
  RECORD(SUBMODULE_EXPORT_AS);
902
903
  // Comments Block.
904
5.38k
  BLOCK(COMMENTS_BLOCK);
905
5.38k
  RECORD(COMMENTS_RAW_COMMENT);
906
907
  // Decls and Types block.
908
5.38k
  BLOCK(DECLTYPES_BLOCK);
909
5.38k
  RECORD(TYPE_EXT_QUAL);
910
5.38k
  RECORD(TYPE_COMPLEX);
911
5.38k
  RECORD(TYPE_POINTER);
912
5.38k
  RECORD(TYPE_BLOCK_POINTER);
913
5.38k
  RECORD(TYPE_LVALUE_REFERENCE);
914
5.38k
  RECORD(TYPE_RVALUE_REFERENCE);
915
5.38k
  RECORD(TYPE_MEMBER_POINTER);
916
5.38k
  RECORD(TYPE_CONSTANT_ARRAY);
917
5.38k
  RECORD(TYPE_INCOMPLETE_ARRAY);
918
5.38k
  RECORD(TYPE_VARIABLE_ARRAY);
919
5.38k
  RECORD(TYPE_VECTOR);
920
5.38k
  RECORD(TYPE_EXT_VECTOR);
921
5.38k
  RECORD(TYPE_FUNCTION_NO_PROTO);
922
5.38k
  RECORD(TYPE_FUNCTION_PROTO);
923
5.38k
  RECORD(TYPE_TYPEDEF);
924
5.38k
  RECORD(TYPE_TYPEOF_EXPR);
925
5.38k
  RECORD(TYPE_TYPEOF);
926
5.38k
  RECORD(TYPE_RECORD);
927
5.38k
  RECORD(TYPE_ENUM);
928
5.38k
  RECORD(TYPE_OBJC_INTERFACE);
929
5.38k
  RECORD(TYPE_OBJC_OBJECT_POINTER);
930
5.38k
  RECORD(TYPE_DECLTYPE);
931
5.38k
  RECORD(TYPE_ELABORATED);
932
5.38k
  RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
933
5.38k
  RECORD(TYPE_UNRESOLVED_USING);
934
5.38k
  RECORD(TYPE_INJECTED_CLASS_NAME);
935
5.38k
  RECORD(TYPE_OBJC_OBJECT);
936
5.38k
  RECORD(TYPE_TEMPLATE_TYPE_PARM);
937
5.38k
  RECORD(TYPE_TEMPLATE_SPECIALIZATION);
938
5.38k
  RECORD(TYPE_DEPENDENT_NAME);
939
5.38k
  RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
940
5.38k
  RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
941
5.38k
  RECORD(TYPE_PAREN);
942
5.38k
  RECORD(TYPE_MACRO_QUALIFIED);
943
5.38k
  RECORD(TYPE_PACK_EXPANSION);
944
5.38k
  RECORD(TYPE_ATTRIBUTED);
945
5.38k
  RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
946
5.38k
  RECORD(TYPE_AUTO);
947
5.38k
  RECORD(TYPE_UNARY_TRANSFORM);
948
5.38k
  RECORD(TYPE_ATOMIC);
949
5.38k
  RECORD(TYPE_DECAYED);
950
5.38k
  RECORD(TYPE_ADJUSTED);
951
5.38k
  RECORD(TYPE_OBJC_TYPE_PARAM);
952
5.38k
  RECORD(LOCAL_REDECLARATIONS);
953
5.38k
  RECORD(DECL_TYPEDEF);
954
5.38k
  RECORD(DECL_TYPEALIAS);
955
5.38k
  RECORD(DECL_ENUM);
956
5.38k
  RECORD(DECL_RECORD);
957
5.38k
  RECORD(DECL_ENUM_CONSTANT);
958
5.38k
  RECORD(DECL_FUNCTION);
959
5.38k
  RECORD(DECL_OBJC_METHOD);
960
5.38k
  RECORD(DECL_OBJC_INTERFACE);
961
5.38k
  RECORD(DECL_OBJC_PROTOCOL);
962
5.38k
  RECORD(DECL_OBJC_IVAR);
963
5.38k
  RECORD(DECL_OBJC_AT_DEFS_FIELD);
964
5.38k
  RECORD(DECL_OBJC_CATEGORY);
965
5.38k
  RECORD(DECL_OBJC_CATEGORY_IMPL);
966
5.38k
  RECORD(DECL_OBJC_IMPLEMENTATION);
967
5.38k
  RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
968
5.38k
  RECORD(DECL_OBJC_PROPERTY);
969
5.38k
  RECORD(DECL_OBJC_PROPERTY_IMPL);
970
5.38k
  RECORD(DECL_FIELD);
971
5.38k
  RECORD(DECL_MS_PROPERTY);
972
5.38k
  RECORD(DECL_VAR);
973
5.38k
  RECORD(DECL_IMPLICIT_PARAM);
974
5.38k
  RECORD(DECL_PARM_VAR);
975
5.38k
  RECORD(DECL_FILE_SCOPE_ASM);
976
5.38k
  RECORD(DECL_BLOCK);
977
5.38k
  RECORD(DECL_CONTEXT_LEXICAL);
978
5.38k
  RECORD(DECL_CONTEXT_VISIBLE);
979
5.38k
  RECORD(DECL_NAMESPACE);
980
5.38k
  RECORD(DECL_NAMESPACE_ALIAS);
981
5.38k
  RECORD(DECL_USING);
982
5.38k
  RECORD(DECL_USING_SHADOW);
983
5.38k
  RECORD(DECL_USING_DIRECTIVE);
984
5.38k
  RECORD(DECL_UNRESOLVED_USING_VALUE);
985
5.38k
  RECORD(DECL_UNRESOLVED_USING_TYPENAME);
986
5.38k
  RECORD(DECL_LINKAGE_SPEC);
987
5.38k
  RECORD(DECL_CXX_RECORD);
988
5.38k
  RECORD(DECL_CXX_METHOD);
989
5.38k
  RECORD(DECL_CXX_CONSTRUCTOR);
990
5.38k
  RECORD(DECL_CXX_DESTRUCTOR);
991
5.38k
  RECORD(DECL_CXX_CONVERSION);
992
5.38k
  RECORD(DECL_ACCESS_SPEC);
993
5.38k
  RECORD(DECL_FRIEND);
994
5.38k
  RECORD(DECL_FRIEND_TEMPLATE);
995
5.38k
  RECORD(DECL_CLASS_TEMPLATE);
996
5.38k
  RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
997
5.38k
  RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
998
5.38k
  RECORD(DECL_VAR_TEMPLATE);
999
5.38k
  RECORD(DECL_VAR_TEMPLATE_SPECIALIZATION);
1000
5.38k
  RECORD(DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION);
1001
5.38k
  RECORD(DECL_FUNCTION_TEMPLATE);
1002
5.38k
  RECORD(DECL_TEMPLATE_TYPE_PARM);
1003
5.38k
  RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
1004
5.38k
  RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
1005
5.38k
  RECORD(DECL_CONCEPT);
1006
5.38k
  RECORD(DECL_REQUIRES_EXPR_BODY);
1007
5.38k
  RECORD(DECL_TYPE_ALIAS_TEMPLATE);
1008
5.38k
  RECORD(DECL_STATIC_ASSERT);
1009
5.38k
  RECORD(DECL_CXX_BASE_SPECIFIERS);
1010
5.38k
  RECORD(DECL_CXX_CTOR_INITIALIZERS);
1011
5.38k
  RECORD(DECL_INDIRECTFIELD);
1012
5.38k
  RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
1013
5.38k
  RECORD(DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK);
1014
5.38k
  RECORD(DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION);
1015
5.38k
  RECORD(DECL_IMPORT);
1016
5.38k
  RECORD(DECL_OMP_THREADPRIVATE);
1017
5.38k
  RECORD(DECL_EMPTY);
1018
5.38k
  RECORD(DECL_OBJC_TYPE_PARAM);
1019
5.38k
  RECORD(DECL_OMP_CAPTUREDEXPR);
1020
5.38k
  RECORD(DECL_PRAGMA_COMMENT);
1021
5.38k
  RECORD(DECL_PRAGMA_DETECT_MISMATCH);
1022
5.38k
  RECORD(DECL_OMP_DECLARE_REDUCTION);
1023
5.38k
  RECORD(DECL_OMP_ALLOCATE);
1024
1025
  // Statements and Exprs can occur in the Decls and Types block.
1026
5.38k
  AddStmtsExprs(Stream, Record);
1027
1028
5.38k
  BLOCK(PREPROCESSOR_DETAIL_BLOCK);
1029
5.38k
  RECORD(PPD_MACRO_EXPANSION);
1030
5.38k
  RECORD(PPD_MACRO_DEFINITION);
1031
5.38k
  RECORD(PPD_INCLUSION_DIRECTIVE);
1032
1033
  // Decls and Types block.
1034
5.38k
  BLOCK(EXTENSION_BLOCK);
1035
5.38k
  RECORD(EXTENSION_METADATA);
1036
1037
5.38k
  BLOCK(UNHASHED_CONTROL_BLOCK);
1038
5.38k
  RECORD(SIGNATURE);
1039
5.38k
  RECORD(AST_BLOCK_HASH);
1040
5.38k
  RECORD(DIAGNOSTIC_OPTIONS);
1041
5.38k
  RECORD(DIAG_PRAGMA_MAPPINGS);
1042
1043
5.38k
#undef RECORD
1044
5.38k
#undef BLOCK
1045
5.38k
  Stream.ExitBlock();
1046
5.38k
}
1047
1048
/// Prepares a path for being written to an AST file by converting it
1049
/// to an absolute path and removing nested './'s.
1050
///
1051
/// \return \c true if the path was changed.
1052
static bool cleanPathForOutput(FileManager &FileMgr,
1053
87.1k
                               SmallVectorImpl<char> &Path) {
1054
87.1k
  bool Changed = FileMgr.makeAbsolutePath(Path);
1055
87.1k
  return Changed | llvm::sys::path::remove_dots(Path);
1056
87.1k
}
1057
1058
/// Adjusts the given filename to only write out the portion of the
1059
/// filename that is not part of the system root directory.
1060
///
1061
/// \param Filename the file name to adjust.
1062
///
1063
/// \param BaseDir When non-NULL, the PCH file is a relocatable AST file and
1064
/// the returned filename will be adjusted by this root directory.
1065
///
1066
/// \returns either the original filename (if it needs no adjustment) or the
1067
/// adjusted filename (which points into the @p Filename parameter).
1068
static const char *
1069
85.2k
adjustFilenameForRelocatableAST(const char *Filename, StringRef BaseDir) {
1070
85.2k
  assert(Filename && "No file name to adjust?");
1071
1072
85.2k
  if (BaseDir.empty())
1073
18.4k
    return Filename;
1074
1075
  // Verify that the filename and the system root have the same prefix.
1076
66.7k
  unsigned Pos = 0;
1077
6.64M
  for (; Filename[Pos] && Pos < BaseDir.size(); 
++Pos6.57M
)
1078
6.58M
    if (Filename[Pos] != BaseDir[Pos])
1079
8.62k
      return Filename; // Prefixes don't match.
1080
1081
  // We hit the end of the filename before we hit the end of the system root.
1082
58.1k
  if (!Filename[Pos])
1083
0
    return Filename;
1084
1085
  // If there's not a path separator at the end of the base directory nor
1086
  // immediately after it, then this isn't within the base directory.
1087
58.1k
  if (!llvm::sys::path::is_separator(Filename[Pos])) {
1088
3
    if (!llvm::sys::path::is_separator(BaseDir.back()))
1089
3
      return Filename;
1090
58.1k
  } else {
1091
    // If the file name has a '/' at the current position, skip over the '/'.
1092
    // We distinguish relative paths from absolute paths by the
1093
    // absence of '/' at the beginning of relative paths.
1094
    //
1095
    // FIXME: This is wrong. We distinguish them by asking if the path is
1096
    // absolute, which isn't the same thing. And there might be multiple '/'s
1097
    // in a row. Use a better mechanism to indicate whether we have emitted an
1098
    // absolute or relative path.
1099
58.1k
    ++Pos;
1100
58.1k
  }
1101
1102
58.1k
  return Filename + Pos;
1103
58.1k
}
1104
1105
std::pair<ASTFileSignature, ASTFileSignature>
1106
1.68k
ASTWriter::createSignature(StringRef AllBytes, StringRef ASTBlockBytes) {
1107
1.68k
  llvm::SHA1 Hasher;
1108
1.68k
  Hasher.update(ASTBlockBytes);
1109
1.68k
  auto Hash = Hasher.result();
1110
1.68k
  ASTFileSignature ASTBlockHash = ASTFileSignature::create(Hash);
1111
1112
  // Add the remaining bytes (i.e. bytes before the unhashed control block that
1113
  // are not part of the AST block).
1114
1.68k
  Hasher.update(
1115
1.68k
      AllBytes.take_front(ASTBlockBytes.bytes_end() - AllBytes.bytes_begin()));
1116
1.68k
  Hasher.update(
1117
1.68k
      AllBytes.take_back(AllBytes.bytes_end() - ASTBlockBytes.bytes_end()));
1118
1.68k
  Hash = Hasher.result();
1119
1.68k
  ASTFileSignature Signature = ASTFileSignature::create(Hash);
1120
1121
1.68k
  return std::make_pair(ASTBlockHash, Signature);
1122
1.68k
}
1123
1124
ASTFileSignature ASTWriter::writeUnhashedControlBlock(Preprocessor &PP,
1125
5.38k
                                                      ASTContext &Context) {
1126
5.38k
  using namespace llvm;
1127
1128
  // Flush first to prepare the PCM hash (signature).
1129
5.38k
  Stream.FlushToWord();
1130
5.38k
  auto StartOfUnhashedControl = Stream.GetCurrentBitNo() >> 3;
1131
1132
  // Enter the block and prepare to write records.
1133
5.38k
  RecordData Record;
1134
5.38k
  Stream.EnterSubblock(UNHASHED_CONTROL_BLOCK_ID, 5);
1135
1136
  // For implicit modules, write the hash of the PCM as its signature.
1137
5.38k
  ASTFileSignature Signature;
1138
5.38k
  if (WritingModule &&
1139
5.38k
      
PP.getHeaderSearchInfo().getHeaderSearchOpts().ModulesHashContent1.95k
) {
1140
1.68k
    ASTFileSignature ASTBlockHash;
1141
1.68k
    auto ASTBlockStartByte = ASTBlockRange.first >> 3;
1142
1.68k
    auto ASTBlockByteLength = (ASTBlockRange.second >> 3) - ASTBlockStartByte;
1143
1.68k
    std::tie(ASTBlockHash, Signature) = createSignature(
1144
1.68k
        StringRef(Buffer.begin(), StartOfUnhashedControl),
1145
1.68k
        StringRef(Buffer.begin() + ASTBlockStartByte, ASTBlockByteLength));
1146
1147
1.68k
    Record.append(ASTBlockHash.begin(), ASTBlockHash.end());
1148
1.68k
    Stream.EmitRecord(AST_BLOCK_HASH, Record);
1149
1.68k
    Record.clear();
1150
1.68k
    Record.append(Signature.begin(), Signature.end());
1151
1.68k
    Stream.EmitRecord(SIGNATURE, Record);
1152
1.68k
    Record.clear();
1153
1.68k
  }
1154
1155
  // Diagnostic options.
1156
5.38k
  const auto &Diags = Context.getDiagnostics();
1157
5.38k
  const DiagnosticOptions &DiagOpts = Diags.getDiagnosticOptions();
1158
161k
#define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name);
1159
5.38k
#define ENUM_DIAGOPT(Name, Type, Bits, Default)                                \
1160
16.1k
  Record.push_back(static_cast<unsigned>(DiagOpts.get##Name()));
1161
5.38k
#include "clang/Basic/DiagnosticOptions.def"
1162
5.38k
  Record.push_back(DiagOpts.Warnings.size());
1163
7.60k
  for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; 
++I2.22k
)
1164
2.22k
    AddString(DiagOpts.Warnings[I], Record);
1165
5.38k
  Record.push_back(DiagOpts.Remarks.size());
1166
5.49k
  for (unsigned I = 0, N = DiagOpts.Remarks.size(); I != N; 
++I112
)
1167
112
    AddString(DiagOpts.Remarks[I], Record);
1168
  // Note: we don't serialize the log or serialization file names, because they
1169
  // are generally transient files and will almost always be overridden.
1170
5.38k
  Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record);
1171
5.38k
  Record.clear();
1172
1173
  // Write out the diagnostic/pragma mappings.
1174
5.38k
  WritePragmaDiagnosticMappings(Diags, /* isModule = */ WritingModule);
1175
1176
  // Header search entry usage.
1177
5.38k
  auto HSEntryUsage = PP.getHeaderSearchInfo().computeUserEntryUsage();
1178
5.38k
  auto Abbrev = std::make_shared<BitCodeAbbrev>();
1179
5.38k
  Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_ENTRY_USAGE));
1180
5.38k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // Number of bits.
1181
5.38k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));      // Bit vector.
1182
5.38k
  unsigned HSUsageAbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1183
5.38k
  {
1184
5.38k
    RecordData::value_type Record[] = {HEADER_SEARCH_ENTRY_USAGE,
1185
5.38k
                                       HSEntryUsage.size()};
1186
5.38k
    Stream.EmitRecordWithBlob(HSUsageAbbrevCode, Record, bytes(HSEntryUsage));
1187
5.38k
  }
1188
1189
  // Leave the options block.
1190
5.38k
  Stream.ExitBlock();
1191
5.38k
  return Signature;
1192
5.38k
}
1193
1194
/// Write the control block.
1195
void ASTWriter::WriteControlBlock(Preprocessor &PP, ASTContext &Context,
1196
                                  StringRef isysroot,
1197
5.38k
                                  const std::string &OutputFile) {
1198
5.38k
  using namespace llvm;
1199
1200
5.38k
  Stream.EnterSubblock(CONTROL_BLOCK_ID, 5);
1201
5.38k
  RecordData Record;
1202
1203
  // Metadata
1204
5.38k
  auto MetadataAbbrev = std::make_shared<BitCodeAbbrev>();
1205
5.38k
  MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA));
1206
5.38k
  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major
1207
5.38k
  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor
1208
5.38k
  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj.
1209
5.38k
  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min.
1210
5.38k
  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
1211
5.38k
  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Timestamps
1212
5.38k
  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors
1213
5.38k
  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
1214
5.38k
  unsigned MetadataAbbrevCode = Stream.EmitAbbrev(std::move(MetadataAbbrev));
1215
5.38k
  assert((!WritingModule || isysroot.empty()) &&
1216
5.38k
         "writing module as a relocatable PCH?");
1217
0
  {
1218
5.38k
    RecordData::value_type Record[] = {
1219
5.38k
        METADATA,
1220
5.38k
        VERSION_MAJOR,
1221
5.38k
        VERSION_MINOR,
1222
5.38k
        CLANG_VERSION_MAJOR,
1223
5.38k
        CLANG_VERSION_MINOR,
1224
5.38k
        !isysroot.empty(),
1225
5.38k
        IncludeTimestamps,
1226
5.38k
        ASTHasCompilerErrors};
1227
5.38k
    Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record,
1228
5.38k
                              getClangFullRepositoryVersion());
1229
5.38k
  }
1230
1231
5.38k
  if (WritingModule) {
1232
    // Module name
1233
1.95k
    auto Abbrev = std::make_shared<BitCodeAbbrev>();
1234
1.95k
    Abbrev->Add(BitCodeAbbrevOp(MODULE_NAME));
1235
1.95k
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
1236
1.95k
    unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1237
1.95k
    RecordData::value_type Record[] = {MODULE_NAME};
1238
1.95k
    Stream.EmitRecordWithBlob(AbbrevCode, Record, WritingModule->Name);
1239
1.95k
  }
1240
1241
5.38k
  if (WritingModule && 
WritingModule->Directory1.95k
) {
1242
1.89k
    SmallString<128> BaseDir(WritingModule->Directory->getName());
1243
1.89k
    cleanPathForOutput(Context.getSourceManager().getFileManager(), BaseDir);
1244
1245
    // If the home of the module is the current working directory, then we
1246
    // want to pick up the cwd of the build process loading the module, not
1247
    // our cwd, when we load this module.
1248
1.89k
    if (!PP.getHeaderSearchInfo()
1249
1.89k
             .getHeaderSearchOpts()
1250
1.89k
             .ModuleMapFileHomeIsCwd ||
1251
1.89k
        
WritingModule->Directory->getName() != StringRef(".")27
) {
1252
      // Module directory.
1253
1.87k
      auto Abbrev = std::make_shared<BitCodeAbbrev>();
1254
1.87k
      Abbrev->Add(BitCodeAbbrevOp(MODULE_DIRECTORY));
1255
1.87k
      Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Directory
1256
1.87k
      unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1257
1258
1.87k
      RecordData::value_type Record[] = {MODULE_DIRECTORY};
1259
1.87k
      Stream.EmitRecordWithBlob(AbbrevCode, Record, BaseDir);
1260
1.87k
    }
1261
1262
    // Write out all other paths relative to the base directory if possible.
1263
1.89k
    BaseDirectory.assign(BaseDir.begin(), BaseDir.end());
1264
3.48k
  } else if (!isysroot.empty()) {
1265
    // Write out paths relative to the sysroot if possible.
1266
1
    BaseDirectory = std::string(isysroot);
1267
1
  }
1268
1269
  // Module map file
1270
5.38k
  if (WritingModule && 
WritingModule->Kind == Module::ModuleMapModule1.95k
) {
1271
1.89k
    Record.clear();
1272
1273
1.89k
    auto &Map = PP.getHeaderSearchInfo().getModuleMap();
1274
1.89k
    AddPath(WritingModule->PresumedModuleMapFile.empty()
1275
1.89k
                ? 
Map.getModuleMapFileForUniquing(WritingModule)->getName()1.88k
1276
1.89k
                : 
StringRef(WritingModule->PresumedModuleMapFile)16
,
1277
1.89k
            Record);
1278
1279
    // Additional module map files.
1280
1.89k
    if (auto *AdditionalModMaps =
1281
1.89k
            Map.getAdditionalModuleMapFiles(WritingModule)) {
1282
43
      Record.push_back(AdditionalModMaps->size());
1283
43
      for (const FileEntry *F : *AdditionalModMaps)
1284
43
        AddPath(F->getName(), Record);
1285
1.85k
    } else {
1286
1.85k
      Record.push_back(0);
1287
1.85k
    }
1288
1289
1.89k
    Stream.EmitRecord(MODULE_MAP_FILE, Record);
1290
1.89k
  }
1291
1292
  // Imports
1293
5.38k
  if (Chain) {
1294
2.13k
    serialization::ModuleManager &Mgr = Chain->getModuleManager();
1295
2.13k
    Record.clear();
1296
1297
3.35k
    for (ModuleFile &M : Mgr) {
1298
      // Skip modules that weren't directly imported.
1299
3.35k
      if (!M.isDirectlyImported())
1300
1.88k
        continue;
1301
1302
1.46k
      Record.push_back((unsigned)M.Kind); // FIXME: Stable encoding
1303
1.46k
      AddSourceLocation(M.ImportLoc, Record);
1304
1305
      // If we have calculated signature, there is no need to store
1306
      // the size or timestamp.
1307
1.46k
      Record.push_back(M.Signature ? 
01.23k
:
M.File->getSize()231
);
1308
1.46k
      Record.push_back(M.Signature ? 
01.23k
:
getTimestampForOutput(M.File)231
);
1309
1310
1.46k
      for (auto I : M.Signature)
1311
29.3k
        Record.push_back(I);
1312
1313
1.46k
      AddString(M.ModuleName, Record);
1314
1.46k
      AddPath(M.FileName, Record);
1315
1.46k
    }
1316
2.13k
    Stream.EmitRecord(IMPORTS, Record);
1317
2.13k
  }
1318
1319
  // Write the options block.
1320
5.38k
  Stream.EnterSubblock(OPTIONS_BLOCK_ID, 4);
1321
1322
  // Language options.
1323
5.38k
  Record.clear();
1324
5.38k
  const LangOptions &LangOpts = Context.getLangOpts();
1325
5.38k
#define LANGOPT(Name, Bits, Default, Description) \
1326
1.27M
  Record.push_back(LangOpts.Name);
1327
5.38k
#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
1328
145k
  Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
1329
5.38k
#include "clang/Basic/LangOptions.def"
1330
5.38k
#define SANITIZER(NAME, ID)                                                    \
1331
295k
  Record.push_back(LangOpts.Sanitize.has(SanitizerKind::ID));
1332
5.38k
#include "clang/Basic/Sanitizers.def"
1333
1334
5.38k
  Record.push_back(LangOpts.ModuleFeatures.size());
1335
5.38k
  for (StringRef Feature : LangOpts.ModuleFeatures)
1336
15
    AddString(Feature, Record);
1337
1338
5.38k
  Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind());
1339
5.38k
  AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record);
1340
1341
5.38k
  AddString(LangOpts.CurrentModule, Record);
1342
1343
  // Comment options.
1344
5.38k
  Record.push_back(LangOpts.CommentOpts.BlockCommandNames.size());
1345
5.38k
  for (const auto &I : LangOpts.CommentOpts.BlockCommandNames) {
1346
4
    AddString(I, Record);
1347
4
  }
1348
5.38k
  Record.push_back(LangOpts.CommentOpts.ParseAllComments);
1349
1350
  // OpenMP offloading options.
1351
5.38k
  Record.push_back(LangOpts.OMPTargetTriples.size());
1352
5.38k
  for (auto &T : LangOpts.OMPTargetTriples)
1353
1.96k
    AddString(T.getTriple(), Record);
1354
1355
5.38k
  AddString(LangOpts.OMPHostIRFile, Record);
1356
1357
5.38k
  Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1358
1359
  // Target options.
1360
5.38k
  Record.clear();
1361
5.38k
  const TargetInfo &Target = Context.getTargetInfo();
1362
5.38k
  const TargetOptions &TargetOpts = Target.getTargetOpts();
1363
5.38k
  AddString(TargetOpts.Triple, Record);
1364
5.38k
  AddString(TargetOpts.CPU, Record);
1365
5.38k
  AddString(TargetOpts.TuneCPU, Record);
1366
5.38k
  AddString(TargetOpts.ABI, Record);
1367
5.38k
  Record.push_back(TargetOpts.FeaturesAsWritten.size());
1368
5.38k
  for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; 
++I4
) {
1369
4
    AddString(TargetOpts.FeaturesAsWritten[I], Record);
1370
4
  }
1371
5.38k
  Record.push_back(TargetOpts.Features.size());
1372
42.7k
  for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; 
++I37.4k
) {
1373
37.4k
    AddString(TargetOpts.Features[I], Record);
1374
37.4k
  }
1375
5.38k
  Stream.EmitRecord(TARGET_OPTIONS, Record);
1376
1377
  // File system options.
1378
5.38k
  Record.clear();
1379
5.38k
  const FileSystemOptions &FSOpts =
1380
5.38k
      Context.getSourceManager().getFileManager().getFileSystemOpts();
1381
5.38k
  AddString(FSOpts.WorkingDir, Record);
1382
5.38k
  Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record);
1383
1384
  // Header search options.
1385
5.38k
  Record.clear();
1386
5.38k
  const HeaderSearchOptions &HSOpts
1387
5.38k
    = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1388
5.38k
  AddString(HSOpts.Sysroot, Record);
1389
1390
  // Include entries.
1391
5.38k
  Record.push_back(HSOpts.UserEntries.size());
1392
14.3k
  for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; 
++I8.92k
) {
1393
8.92k
    const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I];
1394
8.92k
    AddString(Entry.Path, Record);
1395
8.92k
    Record.push_back(static_cast<unsigned>(Entry.Group));
1396
8.92k
    Record.push_back(Entry.IsFramework);
1397
8.92k
    Record.push_back(Entry.IgnoreSysRoot);
1398
8.92k
  }
1399
1400
  // System header prefixes.
1401
5.38k
  Record.push_back(HSOpts.SystemHeaderPrefixes.size());
1402
5.38k
  for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; 
++I0
) {
1403
0
    AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record);
1404
0
    Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader);
1405
0
  }
1406
1407
5.38k
  AddString(HSOpts.ResourceDir, Record);
1408
5.38k
  AddString(HSOpts.ModuleCachePath, Record);
1409
5.38k
  AddString(HSOpts.ModuleUserBuildPath, Record);
1410
5.38k
  Record.push_back(HSOpts.DisableModuleHash);
1411
5.38k
  Record.push_back(HSOpts.ImplicitModuleMaps);
1412
5.38k
  Record.push_back(HSOpts.ModuleMapFileHomeIsCwd);
1413
5.38k
  Record.push_back(HSOpts.EnablePrebuiltImplicitModules);
1414
5.38k
  Record.push_back(HSOpts.UseBuiltinIncludes);
1415
5.38k
  Record.push_back(HSOpts.UseStandardSystemIncludes);
1416
5.38k
  Record.push_back(HSOpts.UseStandardCXXIncludes);
1417
5.38k
  Record.push_back(HSOpts.UseLibcxx);
1418
  // Write out the specific module cache path that contains the module files.
1419
5.38k
  AddString(PP.getHeaderSearchInfo().getModuleCachePath(), Record);
1420
5.38k
  Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record);
1421
1422
  // Preprocessor options.
1423
5.38k
  Record.clear();
1424
5.38k
  const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts();
1425
1426
  // Macro definitions.
1427
5.38k
  Record.push_back(PPOpts.Macros.size());
1428
8.54k
  for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; 
++I3.16k
) {
1429
3.16k
    AddString(PPOpts.Macros[I].first, Record);
1430
3.16k
    Record.push_back(PPOpts.Macros[I].second);
1431
3.16k
  }
1432
1433
  // Includes
1434
5.38k
  Record.push_back(PPOpts.Includes.size());
1435
5.39k
  for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; 
++I14
)
1436
14
    AddString(PPOpts.Includes[I], Record);
1437
1438
  // Macro includes
1439
5.38k
  Record.push_back(PPOpts.MacroIncludes.size());
1440
5.38k
  for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; 
++I0
)
1441
0
    AddString(PPOpts.MacroIncludes[I], Record);
1442
1443
5.38k
  Record.push_back(PPOpts.UsePredefines);
1444
  // Detailed record is important since it is used for the module cache hash.
1445
5.38k
  Record.push_back(PPOpts.DetailedRecord);
1446
5.38k
  AddString(PPOpts.ImplicitPCHInclude, Record);
1447
5.38k
  Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary));
1448
5.38k
  Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record);
1449
1450
  // Leave the options block.
1451
5.38k
  Stream.ExitBlock();
1452
1453
  // Original file name and file ID
1454
5.38k
  SourceManager &SM = Context.getSourceManager();
1455
5.38k
  if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1456
3.55k
    auto FileAbbrev = std::make_shared<BitCodeAbbrev>();
1457
3.55k
    FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE));
1458
3.55k
    FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID
1459
3.55k
    FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1460
3.55k
    unsigned FileAbbrevCode = Stream.EmitAbbrev(std::move(FileAbbrev));
1461
1462
3.55k
    Record.clear();
1463
3.55k
    Record.push_back(ORIGINAL_FILE);
1464
3.55k
    Record.push_back(SM.getMainFileID().getOpaqueValue());
1465
3.55k
    EmitRecordWithPath(FileAbbrevCode, Record, MainFile->getName());
1466
3.55k
  }
1467
1468
5.38k
  Record.clear();
1469
5.38k
  Record.push_back(SM.getMainFileID().getOpaqueValue());
1470
5.38k
  Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
1471
1472
  // Original PCH directory
1473
5.38k
  if (!OutputFile.empty() && 
OutputFile != "-"5.22k
) {
1474
5.17k
    auto Abbrev = std::make_shared<BitCodeAbbrev>();
1475
5.17k
    Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR));
1476
5.17k
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1477
5.17k
    unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1478
1479
5.17k
    SmallString<128> OutputPath(OutputFile);
1480
1481
5.17k
    SM.getFileManager().makeAbsolutePath(OutputPath);
1482
5.17k
    StringRef origDir = llvm::sys::path::parent_path(OutputPath);
1483
1484
5.17k
    RecordData::value_type Record[] = {ORIGINAL_PCH_DIR};
1485
5.17k
    Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir);
1486
5.17k
  }
1487
1488
5.38k
  std::set<const FileEntry *> AffectingModuleMaps;
1489
5.38k
  if (WritingModule) {
1490
1.95k
    AffectingModuleMaps =
1491
1.95k
        GetAllModuleMaps(PP.getHeaderSearchInfo(), WritingModule);
1492
1.95k
  }
1493
1494
5.38k
  WriteInputFiles(Context.SourceMgr,
1495
5.38k
                  PP.getHeaderSearchInfo().getHeaderSearchOpts(),
1496
5.38k
                  AffectingModuleMaps);
1497
5.38k
  Stream.ExitBlock();
1498
5.38k
}
1499
1500
namespace  {
1501
1502
/// An input file.
1503
struct InputFileEntry {
1504
  const FileEntry *File;
1505
  bool IsSystemFile;
1506
  bool IsTransient;
1507
  bool BufferOverridden;
1508
  bool IsTopLevelModuleMap;
1509
  uint32_t ContentHash[2];
1510
};
1511
1512
} // namespace
1513
1514
void ASTWriter::WriteInputFiles(
1515
    SourceManager &SourceMgr, HeaderSearchOptions &HSOpts,
1516
5.38k
    std::set<const FileEntry *> &AffectingModuleMaps) {
1517
5.38k
  using namespace llvm;
1518
1519
5.38k
  Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4);
1520
1521
  // Create input-file abbreviation.
1522
5.38k
  auto IFAbbrev = std::make_shared<BitCodeAbbrev>();
1523
5.38k
  IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE));
1524
5.38k
  IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
1525
5.38k
  IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1526
5.38k
  IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
1527
5.38k
  IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden
1528
5.38k
  IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Transient
1529
5.38k
  IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Module map
1530
5.38k
  IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1531
5.38k
  unsigned IFAbbrevCode = Stream.EmitAbbrev(std::move(IFAbbrev));
1532
1533
  // Create input file hash abbreviation.
1534
5.38k
  auto IFHAbbrev = std::make_shared<BitCodeAbbrev>();
1535
5.38k
  IFHAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_HASH));
1536
5.38k
  IFHAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1537
5.38k
  IFHAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1538
5.38k
  unsigned IFHAbbrevCode = Stream.EmitAbbrev(std::move(IFHAbbrev));
1539
1540
  // Get all ContentCache objects for files, sorted by whether the file is a
1541
  // system one or not. System files go at the back, users files at the front.
1542
5.38k
  std::deque<InputFileEntry> SortedFiles;
1543
3.29M
  for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; 
++I3.29M
) {
1544
    // Get this source location entry.
1545
3.29M
    const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
1546
3.29M
    assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc);
1547
1548
    // We only care about file entries that were not overridden.
1549
3.29M
    if (!SLoc->isFile())
1550
3.18M
      continue;
1551
100k
    const SrcMgr::FileInfo &File = SLoc->getFile();
1552
100k
    const SrcMgr::ContentCache *Cache = &File.getContentCache();
1553
100k
    if (!Cache->OrigEntry)
1554
9.37k
      continue;
1555
1556
91.2k
    if (isModuleMap(File.getFileCharacteristic()) &&
1557
91.2k
        
!isSystem(File.getFileCharacteristic())4.54k
&&
1558
91.2k
        
!AffectingModuleMaps.empty()1.98k
&&
1559
91.2k
        AffectingModuleMaps.find(Cache->OrigEntry) ==
1560
1.91k
            AffectingModuleMaps.end()) {
1561
194
      SkippedModuleMaps.insert(Cache->OrigEntry);
1562
      // Do not emit modulemaps that do not affect current module.
1563
194
      continue;
1564
194
    }
1565
1566
91.0k
    InputFileEntry Entry;
1567
91.0k
    Entry.File = Cache->OrigEntry;
1568
91.0k
    Entry.IsSystemFile = isSystem(File.getFileCharacteristic());
1569
91.0k
    Entry.IsTransient = Cache->IsTransient;
1570
91.0k
    Entry.BufferOverridden = Cache->BufferOverridden;
1571
91.0k
    Entry.IsTopLevelModuleMap = isModuleMap(File.getFileCharacteristic()) &&
1572
91.0k
                                
File.getIncludeLoc().isInvalid()4.34k
;
1573
1574
91.0k
    auto ContentHash = hash_code(-1);
1575
91.0k
    if (PP->getHeaderSearchInfo()
1576
91.0k
            .getHeaderSearchOpts()
1577
91.0k
            .ValidateASTInputFilesContent) {
1578
12
      auto MemBuff = Cache->getBufferIfLoaded();
1579
12
      if (MemBuff)
1580
12
        ContentHash = hash_value(MemBuff->getBuffer());
1581
0
      else
1582
        // FIXME: The path should be taken from the FileEntryRef.
1583
0
        PP->Diag(SourceLocation(), diag::err_module_unable_to_hash_content)
1584
0
            << Entry.File->getName();
1585
12
    }
1586
91.0k
    auto CH = llvm::APInt(64, ContentHash);
1587
91.0k
    Entry.ContentHash[0] =
1588
91.0k
        static_cast<uint32_t>(CH.getLoBits(32).getZExtValue());
1589
91.0k
    Entry.ContentHash[1] =
1590
91.0k
        static_cast<uint32_t>(CH.getHiBits(32).getZExtValue());
1591
1592
91.0k
    if (Entry.IsSystemFile)
1593
82.4k
      SortedFiles.push_back(Entry);
1594
8.61k
    else
1595
8.61k
      SortedFiles.push_front(Entry);
1596
91.0k
  }
1597
1598
5.38k
  unsigned UserFilesNum = 0;
1599
  // Write out all of the input files.
1600
5.38k
  std::vector<uint64_t> InputFileOffsets;
1601
91.0k
  for (const auto &Entry : SortedFiles) {
1602
91.0k
    uint32_t &InputFileID = InputFileIDs[Entry.File];
1603
91.0k
    if (InputFileID != 0)
1604
57.8k
      continue; // already recorded this file.
1605
1606
    // Record this entry's offset.
1607
33.1k
    InputFileOffsets.push_back(Stream.GetCurrentBitNo());
1608
1609
33.1k
    InputFileID = InputFileOffsets.size();
1610
1611
33.1k
    if (!Entry.IsSystemFile)
1612
8.25k
      ++UserFilesNum;
1613
1614
    // Emit size/modification time for this file.
1615
    // And whether this file was overridden.
1616
33.1k
    {
1617
33.1k
      RecordData::value_type Record[] = {
1618
33.1k
          INPUT_FILE,
1619
33.1k
          InputFileOffsets.size(),
1620
33.1k
          (uint64_t)Entry.File->getSize(),
1621
33.1k
          (uint64_t)getTimestampForOutput(Entry.File),
1622
33.1k
          Entry.BufferOverridden,
1623
33.1k
          Entry.IsTransient,
1624
33.1k
          Entry.IsTopLevelModuleMap};
1625
1626
      // FIXME: The path should be taken from the FileEntryRef.
1627
33.1k
      EmitRecordWithPath(IFAbbrevCode, Record, Entry.File->getName());
1628
33.1k
    }
1629
1630
    // Emit content hash for this file.
1631
33.1k
    {
1632
33.1k
      RecordData::value_type Record[] = {INPUT_FILE_HASH, Entry.ContentHash[0],
1633
33.1k
                                         Entry.ContentHash[1]};
1634
33.1k
      Stream.EmitRecordWithAbbrev(IFHAbbrevCode, Record);
1635
33.1k
    }
1636
33.1k
  }
1637
1638
5.38k
  Stream.ExitBlock();
1639
1640
  // Create input file offsets abbreviation.
1641
5.38k
  auto OffsetsAbbrev = std::make_shared<BitCodeAbbrev>();
1642
5.38k
  OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS));
1643
5.38k
  OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files
1644
5.38k
  OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system
1645
                                                                //   input files
1646
5.38k
  OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));   // Array
1647
5.38k
  unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(std::move(OffsetsAbbrev));
1648
1649
  // Write input file offsets.
1650
5.38k
  RecordData::value_type Record[] = {INPUT_FILE_OFFSETS,
1651
5.38k
                                     InputFileOffsets.size(), UserFilesNum};
1652
5.38k
  Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, bytes(InputFileOffsets));
1653
5.38k
}
1654
1655
//===----------------------------------------------------------------------===//
1656
// Source Manager Serialization
1657
//===----------------------------------------------------------------------===//
1658
1659
/// Create an abbreviation for the SLocEntry that refers to a
1660
/// file.
1661
5.38k
static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
1662
5.38k
  using namespace llvm;
1663
1664
5.38k
  auto Abbrev = std::make_shared<BitCodeAbbrev>();
1665
5.38k
  Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
1666
5.38k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1667
5.38k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1668
5.38k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
1669
5.38k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1670
  // FileEntry fields.
1671
5.38k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID
1672
5.38k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
1673
5.38k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
1674
5.38k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
1675
5.38k
  return Stream.EmitAbbrev(std::move(Abbrev));
1676
5.38k
}
1677
1678
/// Create an abbreviation for the SLocEntry that refers to a
1679
/// buffer.
1680
5.38k
static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
1681
5.38k
  using namespace llvm;
1682
1683
5.38k
  auto Abbrev = std::make_shared<BitCodeAbbrev>();
1684
5.38k
  Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
1685
5.38k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1686
5.38k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1687
5.38k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
1688
5.38k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1689
5.38k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
1690
5.38k
  return Stream.EmitAbbrev(std::move(Abbrev));
1691
5.38k
}
1692
1693
/// Create an abbreviation for the SLocEntry that refers to a
1694
/// buffer's blob.
1695
static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream,
1696
10.7k
                                           bool Compressed) {
1697
10.7k
  using namespace llvm;
1698
1699
10.7k
  auto Abbrev = std::make_shared<BitCodeAbbrev>();
1700
10.7k
  Abbrev->Add(BitCodeAbbrevOp(Compressed ? 
SM_SLOC_BUFFER_BLOB_COMPRESSED5.38k
1701
10.7k
                                         : 
SM_SLOC_BUFFER_BLOB5.38k
));
1702
10.7k
  if (Compressed)
1703
5.38k
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Uncompressed size
1704
10.7k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
1705
10.7k
  return Stream.EmitAbbrev(std::move(Abbrev));
1706
10.7k
}
1707
1708
/// Create an abbreviation for the SLocEntry that refers to a macro
1709
/// expansion.
1710
5.38k
static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
1711
5.38k
  using namespace llvm;
1712
1713
5.38k
  auto Abbrev = std::make_shared<BitCodeAbbrev>();
1714
5.38k
  Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
1715
5.38k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1716
5.38k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1717
5.38k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
1718
5.38k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
1719
5.38k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Is token range
1720
5.38k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
1721
5.38k
  return Stream.EmitAbbrev(std::move(Abbrev));
1722
5.38k
}
1723
1724
/// Emit key length and data length as ULEB-encoded data, and return them as a
1725
/// pair.
1726
static std::pair<unsigned, unsigned>
1727
13.4M
emitULEBKeyDataLength(unsigned KeyLen, unsigned DataLen, raw_ostream &Out) {
1728
13.4M
  llvm::encodeULEB128(KeyLen, Out);
1729
13.4M
  llvm::encodeULEB128(DataLen, Out);
1730
13.4M
  return std::make_pair(KeyLen, DataLen);
1731
13.4M
}
1732
1733
namespace {
1734
1735
  // Trait used for the on-disk hash table of header search information.
1736
  class HeaderFileInfoTrait {
1737
    ASTWriter &Writer;
1738
1739
    // Keep track of the framework names we've used during serialization.
1740
    SmallString<128> FrameworkStringData;
1741
    llvm::StringMap<unsigned> FrameworkNameOffset;
1742
1743
  public:
1744
5.38k
    HeaderFileInfoTrait(ASTWriter &Writer) : Writer(Writer) {}
1745
1746
    struct key_type {
1747
      StringRef Filename;
1748
      off_t Size;
1749
      time_t ModTime;
1750
    };
1751
    using key_type_ref = const key_type &;
1752
1753
    using UnresolvedModule =
1754
        llvm::PointerIntPair<Module *, 2, ModuleMap::ModuleHeaderRole>;
1755
1756
    struct data_type {
1757
      const HeaderFileInfo &HFI;
1758
      ArrayRef<ModuleMap::KnownHeader> KnownHeaders;
1759
      UnresolvedModule Unresolved;
1760
    };
1761
    using data_type_ref = const data_type &;
1762
1763
    using hash_value_type = unsigned;
1764
    using offset_type = unsigned;
1765
1766
29.5k
    hash_value_type ComputeHash(key_type_ref key) {
1767
      // The hash is based only on size/time of the file, so that the reader can
1768
      // match even when symlinking or excess path elements ("foo/../", "../")
1769
      // change the form of the name. However, complete path is still the key.
1770
29.5k
      return llvm::hash_combine(key.Size, key.ModTime);
1771
29.5k
    }
1772
1773
    std::pair<unsigned, unsigned>
1774
29.5k
    EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) {
1775
29.5k
      unsigned KeyLen = key.Filename.size() + 1 + 8 + 8;
1776
29.5k
      unsigned DataLen = 1 + 2 + 4 + 4;
1777
29.5k
      for (auto ModInfo : Data.KnownHeaders)
1778
23.8k
        if (Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule()))
1779
23.7k
          DataLen += 4;
1780
29.5k
      if (Data.Unresolved.getPointer())
1781
12
        DataLen += 4;
1782
29.5k
      return emitULEBKeyDataLength(KeyLen, DataLen, Out);
1783
29.5k
    }
1784
1785
29.5k
    void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) {
1786
29.5k
      using namespace llvm::support;
1787
1788
29.5k
      endian::Writer LE(Out, little);
1789
29.5k
      LE.write<uint64_t>(key.Size);
1790
29.5k
      KeyLen -= 8;
1791
29.5k
      LE.write<uint64_t>(key.ModTime);
1792
29.5k
      KeyLen -= 8;
1793
29.5k
      Out.write(key.Filename.data(), KeyLen);
1794
29.5k
    }
1795
1796
    void EmitData(raw_ostream &Out, key_type_ref key,
1797
29.5k
                  data_type_ref Data, unsigned DataLen) {
1798
29.5k
      using namespace llvm::support;
1799
1800
29.5k
      endian::Writer LE(Out, little);
1801
29.5k
      uint64_t Start = Out.tell(); (void)Start;
1802
1803
29.5k
      unsigned char Flags = (Data.HFI.isImport << 5)
1804
29.5k
                          | (Data.HFI.isPragmaOnce << 4)
1805
29.5k
                          | (Data.HFI.DirInfo << 1)
1806
29.5k
                          | Data.HFI.IndexHeaderMapHeader;
1807
29.5k
      LE.write<uint8_t>(Flags);
1808
29.5k
      LE.write<uint16_t>(Data.HFI.NumIncludes);
1809
1810
29.5k
      if (!Data.HFI.ControllingMacro)
1811
7.48k
        LE.write<uint32_t>(Data.HFI.ControllingMacroID);
1812
22.0k
      else
1813
22.0k
        LE.write<uint32_t>(Writer.getIdentifierRef(Data.HFI.ControllingMacro));
1814
1815
29.5k
      unsigned Offset = 0;
1816
29.5k
      if (!Data.HFI.Framework.empty()) {
1817
        // If this header refers into a framework, save the framework name.
1818
0
        llvm::StringMap<unsigned>::iterator Pos
1819
0
          = FrameworkNameOffset.find(Data.HFI.Framework);
1820
0
        if (Pos == FrameworkNameOffset.end()) {
1821
0
          Offset = FrameworkStringData.size() + 1;
1822
0
          FrameworkStringData.append(Data.HFI.Framework);
1823
0
          FrameworkStringData.push_back(0);
1824
1825
0
          FrameworkNameOffset[Data.HFI.Framework] = Offset;
1826
0
        } else
1827
0
          Offset = Pos->second;
1828
0
      }
1829
29.5k
      LE.write<uint32_t>(Offset);
1830
1831
29.5k
      auto EmitModule = [&](Module *M, ModuleMap::ModuleHeaderRole Role) {
1832
23.9k
        if (uint32_t ModID = Writer.getLocalOrImportedSubmoduleID(M)) {
1833
23.7k
          uint32_t Value = (ModID << 2) | (unsigned)Role;
1834
23.7k
          assert((Value >> 2) == ModID && "overflow in header module info");
1835
0
          LE.write<uint32_t>(Value);
1836
23.7k
        }
1837
23.9k
      };
1838
1839
      // FIXME: If the header is excluded, we should write out some
1840
      // record of that fact.
1841
29.5k
      for (auto ModInfo : Data.KnownHeaders)
1842
23.8k
        EmitModule(ModInfo.getModule(), ModInfo.getRole());
1843
29.5k
      if (Data.Unresolved.getPointer())
1844
12
        EmitModule(Data.Unresolved.getPointer(), Data.Unresolved.getInt());
1845
1846
29.5k
      assert(Out.tell() - Start == DataLen && "Wrong data length");
1847
29.5k
    }
1848
1849
5.38k
    const char *strings_begin() const { return FrameworkStringData.begin(); }
1850
5.38k
    const char *strings_end() const { return FrameworkStringData.end(); }
1851
  };
1852
1853
} // namespace
1854
1855
/// Write the header search block for the list of files that
1856
///
1857
/// \param HS The header search structure to save.
1858
5.38k
void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS) {
1859
5.38k
  HeaderFileInfoTrait GeneratorTrait(*this);
1860
5.38k
  llvm::OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
1861
5.38k
  SmallVector<const char *, 4> SavedStrings;
1862
5.38k
  unsigned NumHeaderSearchEntries = 0;
1863
1864
  // Find all unresolved headers for the current module. We generally will
1865
  // have resolved them before we get here, but not necessarily: we might be
1866
  // compiling a preprocessed module, where there is no requirement for the
1867
  // original files to exist any more.
1868
5.38k
  const HeaderFileInfo Empty; // So we can take a reference.
1869
5.38k
  if (WritingModule) {
1870
1.95k
    llvm::SmallVector<Module *, 16> Worklist(1, WritingModule);
1871
25.6k
    while (!Worklist.empty()) {
1872
23.6k
      Module *M = Worklist.pop_back_val();
1873
      // We don't care about headers in unimportable submodules.
1874
23.6k
      if (M->isUnimportable())
1875
374
        continue;
1876
1877
      // Map to disk files where possible, to pick up any missing stat
1878
      // information. This also means we don't need to check the unresolved
1879
      // headers list when emitting resolved headers in the first loop below.
1880
      // FIXME: It'd be preferable to avoid doing this if we were given
1881
      // sufficient stat information in the module map.
1882
23.2k
      HS.getModuleMap().resolveHeaderDirectives(M);
1883
1884
      // If the file didn't exist, we can still create a module if we were given
1885
      // enough information in the module map.
1886
23.2k
      for (auto U : M->MissingHeaders) {
1887
        // Check that we were given enough information to build a module
1888
        // without this file existing on disk.
1889
13
        if (!U.Size || 
(12
!U.ModTime12
&&
IncludeTimestamps1
)) {
1890
1
          PP->Diag(U.FileNameLoc, diag::err_module_no_size_mtime_for_header)
1891
1
            << WritingModule->getFullModuleName() << U.Size.hasValue()
1892
1
            << U.FileName;
1893
1
          continue;
1894
1
        }
1895
1896
        // Form the effective relative pathname for the file.
1897
12
        SmallString<128> Filename(M->Directory->getName());
1898
12
        llvm::sys::path::append(Filename, U.FileName);
1899
12
        PreparePathForOutput(Filename);
1900
1901
12
        StringRef FilenameDup = strdup(Filename.c_str());
1902
12
        SavedStrings.push_back(FilenameDup.data());
1903
1904
12
        HeaderFileInfoTrait::key_type Key = {
1905
12
          FilenameDup, *U.Size, IncludeTimestamps ? 
*U.ModTime8
:
04
1906
12
        };
1907
12
        HeaderFileInfoTrait::data_type Data = {
1908
12
          Empty, {}, {M, ModuleMap::headerKindToRole(U.Kind)}
1909
12
        };
1910
        // FIXME: Deal with cases where there are multiple unresolved header
1911
        // directives in different submodules for the same header.
1912
12
        Generator.insert(Key, Data, GeneratorTrait);
1913
12
        ++NumHeaderSearchEntries;
1914
12
      }
1915
1916
23.2k
      Worklist.append(M->submodule_begin(), M->submodule_end());
1917
23.2k
    }
1918
1.95k
  }
1919
1920
5.38k
  SmallVector<const FileEntry *, 16> FilesByUID;
1921
5.38k
  HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
1922
1923
5.38k
  if (FilesByUID.size() > HS.header_file_size())
1924
953
    FilesByUID.resize(HS.header_file_size());
1925
1926
321k
  for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; 
++UID316k
) {
1927
316k
    const FileEntry *File = FilesByUID[UID];
1928
316k
    if (!File)
1929
0
      continue;
1930
1931
    // Get the file info. This will load info from the external source if
1932
    // necessary. Skip emitting this file if we have no information on it
1933
    // as a header file (in which case HFI will be null) or if it hasn't
1934
    // changed since it was loaded. Also skip it if it's for a modular header
1935
    // from a different module; in that case, we rely on the module(s)
1936
    // containing the header to provide this information.
1937
316k
    const HeaderFileInfo *HFI =
1938
316k
        HS.getExistingFileInfo(File, /*WantExternal*/!Chain);
1939
316k
    if (!HFI || 
(193k
HFI->isModuleHeader193k
&&
!HFI->isCompilingModuleHeader179k
))
1940
286k
      continue;
1941
1942
    // Massage the file path into an appropriate form.
1943
29.5k
    StringRef Filename = File->getName();
1944
29.5k
    SmallString<128> FilenameTmp(Filename);
1945
29.5k
    if (PreparePathForOutput(FilenameTmp)) {
1946
      // If we performed any translation on the file name at all, we need to
1947
      // save this string, since the generator will refer to it later.
1948
25.1k
      Filename = StringRef(strdup(FilenameTmp.c_str()));
1949
25.1k
      SavedStrings.push_back(Filename.data());
1950
25.1k
    }
1951
1952
29.5k
    HeaderFileInfoTrait::key_type Key = {
1953
29.5k
      Filename, File->getSize(), getTimestampForOutput(File)
1954
29.5k
    };
1955
29.5k
    HeaderFileInfoTrait::data_type Data = {
1956
29.5k
      *HFI, HS.getModuleMap().findResolvedModulesForHeader(File), {}
1957
29.5k
    };
1958
29.5k
    Generator.insert(Key, Data, GeneratorTrait);
1959
29.5k
    ++NumHeaderSearchEntries;
1960
29.5k
  }
1961
1962
  // Create the on-disk hash table in a buffer.
1963
5.38k
  SmallString<4096> TableData;
1964
5.38k
  uint32_t BucketOffset;
1965
5.38k
  {
1966
5.38k
    using namespace llvm::support;
1967
1968
5.38k
    llvm::raw_svector_ostream Out(TableData);
1969
    // Make sure that no bucket is at offset 0
1970
5.38k
    endian::write<uint32_t>(Out, 0, little);
1971
5.38k
    BucketOffset = Generator.Emit(Out, GeneratorTrait);
1972
5.38k
  }
1973
1974
  // Create a blob abbreviation
1975
5.38k
  using namespace llvm;
1976
1977
5.38k
  auto Abbrev = std::make_shared<BitCodeAbbrev>();
1978
5.38k
  Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
1979
5.38k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1980
5.38k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1981
5.38k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1982
5.38k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1983
5.38k
  unsigned TableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
1984
1985
  // Write the header search table
1986
5.38k
  RecordData::value_type Record[] = {HEADER_SEARCH_TABLE, BucketOffset,
1987
5.38k
                                     NumHeaderSearchEntries, TableData.size()};
1988
5.38k
  TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end());
1989
5.38k
  Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData);
1990
1991
  // Free all of the strings we had to duplicate.
1992
30.5k
  for (unsigned I = 0, N = SavedStrings.size(); I != N; 
++I25.2k
)
1993
25.2k
    free(const_cast<char *>(SavedStrings[I]));
1994
5.38k
}
1995
1996
static void emitBlob(llvm::BitstreamWriter &Stream, StringRef Blob,
1997
                     unsigned SLocBufferBlobCompressedAbbrv,
1998
9.65k
                     unsigned SLocBufferBlobAbbrv) {
1999
9.65k
  using RecordDataType = ASTWriter::RecordData::value_type;
2000
2001
  // Compress the buffer if possible. We expect that almost all PCM
2002
  // consumers will not want its contents.
2003
9.65k
  SmallString<0> CompressedBuffer;
2004
9.65k
  if (llvm::zlib::isAvailable()) {
2005
9.65k
    llvm::Error E = llvm::zlib::compress(Blob.drop_back(1), CompressedBuffer);
2006
9.65k
    if (!E) {
2007
9.65k
      RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB_COMPRESSED,
2008
9.65k
                                 Blob.size() - 1};
2009
9.65k
      Stream.EmitRecordWithBlob(SLocBufferBlobCompressedAbbrv, Record,
2010
9.65k
                                CompressedBuffer);
2011
9.65k
      return;
2012
9.65k
    }
2013
0
    llvm::consumeError(std::move(E));
2014
0
  }
2015
2016
0
  RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB};
2017
0
  Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, Blob);
2018
0
}
2019
2020
/// Writes the block containing the serialized form of the
2021
/// source manager.
2022
///
2023
/// TODO: We should probably use an on-disk hash table (stored in a
2024
/// blob), indexed based on the file name, so that we only create
2025
/// entries for files that we actually need. In the common case (no
2026
/// errors), we probably won't have to create file entries for any of
2027
/// the files in the AST.
2028
void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
2029
5.38k
                                        const Preprocessor &PP) {
2030
5.38k
  RecordData Record;
2031
2032
  // Enter the source manager block.
2033
5.38k
  Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 4);
2034
5.38k
  const uint64_t SourceManagerBlockOffset = Stream.GetCurrentBitNo();
2035
2036
  // Abbreviations for the various kinds of source-location entries.
2037
5.38k
  unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
2038
5.38k
  unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
2039
5.38k
  unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream, false);
2040
5.38k
  unsigned SLocBufferBlobCompressedAbbrv =
2041
5.38k
      CreateSLocBufferBlobAbbrev(Stream, true);
2042
5.38k
  unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
2043
2044
  // Write out the source location entry table. We skip the first
2045
  // entry, which is always the same dummy entry.
2046
5.38k
  std::vector<uint32_t> SLocEntryOffsets;
2047
5.38k
  uint64_t SLocEntryOffsetsBase = Stream.GetCurrentBitNo();
2048
5.38k
  RecordData PreloadSLocs;
2049
5.38k
  SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
2050
5.38k
  for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
2051
3.29M
       I != N; 
++I3.29M
) {
2052
    // Get this source location entry.
2053
3.29M
    const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
2054
3.29M
    FileID FID = FileID::get(I);
2055
3.29M
    assert(&SourceMgr.getSLocEntry(FID) == SLoc);
2056
2057
    // Record the offset of this source-location entry.
2058
0
    uint64_t Offset = Stream.GetCurrentBitNo() - SLocEntryOffsetsBase;
2059
3.29M
    assert((Offset >> 32) == 0 && "SLocEntry offset too large");
2060
0
    SLocEntryOffsets.push_back(Offset);
2061
2062
    // Figure out which record code to use.
2063
3.29M
    unsigned Code;
2064
3.29M
    if (SLoc->isFile()) {
2065
100k
      const SrcMgr::ContentCache *Cache = &SLoc->getFile().getContentCache();
2066
100k
      if (Cache->OrigEntry) {
2067
91.2k
        Code = SM_SLOC_FILE_ENTRY;
2068
91.2k
      } else
2069
9.37k
        Code = SM_SLOC_BUFFER_ENTRY;
2070
100k
    } else
2071
3.18M
      Code = SM_SLOC_EXPANSION_ENTRY;
2072
3.29M
    Record.clear();
2073
3.29M
    Record.push_back(Code);
2074
2075
    // Starting offset of this entry within this module, so skip the dummy.
2076
3.29M
    Record.push_back(SLoc->getOffset() - 2);
2077
3.29M
    if (SLoc->isFile()) {
2078
100k
      const SrcMgr::FileInfo &File = SLoc->getFile();
2079
100k
      const SrcMgr::ContentCache *Content = &File.getContentCache();
2080
100k
      if (Content->OrigEntry && 
!SkippedModuleMaps.empty()91.2k
&&
2081
100k
          SkippedModuleMaps.find(Content->OrigEntry) !=
2082
33.8k
              SkippedModuleMaps.end()) {
2083
        // Do not emit files that were not listed as inputs.
2084
194
        continue;
2085
194
      }
2086
100k
      AddSourceLocation(File.getIncludeLoc(), Record);
2087
100k
      Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
2088
100k
      Record.push_back(File.hasLineDirectives());
2089
2090
100k
      bool EmitBlob = false;
2091
100k
      if (Content->OrigEntry) {
2092
91.0k
        assert(Content->OrigEntry == Content->ContentsEntry &&
2093
91.0k
               "Writing to AST an overridden file is not supported");
2094
2095
        // The source location entry is a file. Emit input file ID.
2096
0
        assert(InputFileIDs[Content->OrigEntry] != 0 && "Missed file entry");
2097
0
        Record.push_back(InputFileIDs[Content->OrigEntry]);
2098
2099
91.0k
        Record.push_back(File.NumCreatedFIDs);
2100
2101
91.0k
        FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID);
2102
91.0k
        if (FDI != FileDeclIDs.end()) {
2103
84.5k
          Record.push_back(FDI->second->FirstDeclIndex);
2104
84.5k
          Record.push_back(FDI->second->DeclIDs.size());
2105
84.5k
        } else {
2106
6.48k
          Record.push_back(0);
2107
6.48k
          Record.push_back(0);
2108
6.48k
        }
2109
2110
91.0k
        Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record);
2111
2112
91.0k
        if (Content->BufferOverridden || 
Content->IsTransient90.8k
)
2113
279
          EmitBlob = true;
2114
91.0k
      } else {
2115
        // The source location entry is a buffer. The blob associated
2116
        // with this entry contains the contents of the buffer.
2117
2118
        // We add one to the size so that we capture the trailing NULL
2119
        // that is required by llvm::MemoryBuffer::getMemBuffer (on
2120
        // the reader side).
2121
9.37k
        llvm::Optional<llvm::MemoryBufferRef> Buffer =
2122
9.37k
            Content->getBufferOrNone(PP.getDiagnostics(), PP.getFileManager());
2123
9.37k
        StringRef Name = Buffer ? Buffer->getBufferIdentifier() : 
""0
;
2124
9.37k
        Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
2125
9.37k
                                  StringRef(Name.data(), Name.size() + 1));
2126
9.37k
        EmitBlob = true;
2127
2128
9.37k
        if (Name == "<built-in>")
2129
5.38k
          PreloadSLocs.push_back(SLocEntryOffsets.size());
2130
9.37k
      }
2131
2132
100k
      if (EmitBlob) {
2133
        // Include the implicit terminating null character in the on-disk buffer
2134
        // if we're writing it uncompressed.
2135
9.65k
        llvm::Optional<llvm::MemoryBufferRef> Buffer =
2136
9.65k
            Content->getBufferOrNone(PP.getDiagnostics(), PP.getFileManager());
2137
9.65k
        if (!Buffer)
2138
0
          Buffer = llvm::MemoryBufferRef("<<<INVALID BUFFER>>>", "");
2139
9.65k
        StringRef Blob(Buffer->getBufferStart(), Buffer->getBufferSize() + 1);
2140
9.65k
        emitBlob(Stream, Blob, SLocBufferBlobCompressedAbbrv,
2141
9.65k
                 SLocBufferBlobAbbrv);
2142
9.65k
      }
2143
3.18M
    } else {
2144
      // The source location entry is a macro expansion.
2145
3.18M
      const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
2146
3.18M
      AddSourceLocation(Expansion.getSpellingLoc(), Record);
2147
3.18M
      AddSourceLocation(Expansion.getExpansionLocStart(), Record);
2148
3.18M
      AddSourceLocation(Expansion.isMacroArgExpansion()
2149
3.18M
                            ? 
SourceLocation()1.32M
2150
3.18M
                            : 
Expansion.getExpansionLocEnd()1.86M
,
2151
3.18M
                        Record);
2152
3.18M
      Record.push_back(Expansion.isExpansionTokenRange());
2153
2154
      // Compute the token length for this macro expansion.
2155
3.18M
      SourceLocation::UIntTy NextOffset = SourceMgr.getNextLocalOffset();
2156
3.18M
      if (I + 1 != N)
2157
3.18M
        NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
2158
3.18M
      Record.push_back(NextOffset - SLoc->getOffset() - 1);
2159
3.18M
      Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
2160
3.18M
    }
2161
3.29M
  }
2162
2163
5.38k
  Stream.ExitBlock();
2164
2165
5.38k
  if (SLocEntryOffsets.empty())
2166
0
    return;
2167
2168
  // Write the source-location offsets table into the AST block. This
2169
  // table is used for lazily loading source-location information.
2170
5.38k
  using namespace llvm;
2171
2172
5.38k
  auto Abbrev = std::make_shared<BitCodeAbbrev>();
2173
5.38k
  Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
2174
5.38k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
2175
5.38k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
2176
5.38k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // base offset
2177
5.38k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
2178
5.38k
  unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2179
5.38k
  {
2180
5.38k
    RecordData::value_type Record[] = {
2181
5.38k
        SOURCE_LOCATION_OFFSETS, SLocEntryOffsets.size(),
2182
5.38k
        SourceMgr.getNextLocalOffset() - 1 /* skip dummy */,
2183
5.38k
        SLocEntryOffsetsBase - SourceManagerBlockOffset};
2184
5.38k
    Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
2185
5.38k
                              bytes(SLocEntryOffsets));
2186
5.38k
  }
2187
  // Write the source location entry preloads array, telling the AST
2188
  // reader which source locations entries it should load eagerly.
2189
5.38k
  Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
2190
2191
  // Write the line table. It depends on remapping working, so it must come
2192
  // after the source location offsets.
2193
5.38k
  if (SourceMgr.hasLineTable()) {
2194
5.38k
    LineTableInfo &LineTable = SourceMgr.getLineTable();
2195
2196
5.38k
    Record.clear();
2197
2198
    // Emit the needed file names.
2199
5.38k
    llvm::DenseMap<int, int> FilenameMap;
2200
5.38k
    FilenameMap[-1] = -1; // For unspecified filenames.
2201
32.9k
    for (const auto &L : LineTable) {
2202
32.9k
      if (L.first.ID < 0)
2203
22.8k
        continue;
2204
21.0k
      
for (auto &LE : L.second)10.1k
{
2205
21.0k
        if (FilenameMap.insert(std::make_pair(LE.FilenameID,
2206
21.0k
                                              FilenameMap.size() - 1)).second)
2207
15.5k
          AddPath(LineTable.getFilename(LE.FilenameID), Record);
2208
21.0k
      }
2209
10.1k
    }
2210
5.38k
    Record.push_back(0);
2211
2212
    // Emit the line entries
2213
32.9k
    for (const auto &L : LineTable) {
2214
      // Only emit entries for local files.
2215
32.9k
      if (L.first.ID < 0)
2216
22.8k
        continue;
2217
2218
      // Emit the file ID
2219
10.1k
      Record.push_back(L.first.ID);
2220
2221
      // Emit the line entries
2222
10.1k
      Record.push_back(L.second.size());
2223
21.0k
      for (const auto &LE : L.second) {
2224
21.0k
        Record.push_back(LE.FileOffset);
2225
21.0k
        Record.push_back(LE.LineNo);
2226
21.0k
        Record.push_back(FilenameMap[LE.FilenameID]);
2227
21.0k
        Record.push_back((unsigned)LE.FileKind);
2228
21.0k
        Record.push_back(LE.IncludeOffset);
2229
21.0k
      }
2230
10.1k
    }
2231
2232
5.38k
    Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
2233
5.38k
  }
2234
5.38k
}
2235
2236
//===----------------------------------------------------------------------===//
2237
// Preprocessor Serialization
2238
//===----------------------------------------------------------------------===//
2239
2240
static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule,
2241
2.06M
                              const Preprocessor &PP) {
2242
2.06M
  if (MacroInfo *MI = MD->getMacroInfo())
2243
2.06M
    if (MI->isBuiltinMacro())
2244
136k
      return true;
2245
2246
1.92M
  if (IsModule) {
2247
723k
    SourceLocation Loc = MD->getLocation();
2248
723k
    if (Loc.isInvalid())
2249
0
      return true;
2250
723k
    if (PP.getSourceManager().getFileID(Loc) == PP.getPredefinesFileID())
2251
722k
      return true;
2252
723k
  }
2253
2254
1.20M
  return false;
2255
1.92M
}
2256
2257
/// Writes the block containing the serialized form of the
2258
/// preprocessor.
2259
5.38k
void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
2260
5.38k
  uint64_t MacroOffsetsBase = Stream.GetCurrentBitNo();
2261
2262
5.38k
  PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
2263
5.38k
  if (PPRec)
2264
209
    WritePreprocessorDetail(*PPRec, MacroOffsetsBase);
2265
2266
5.38k
  RecordData Record;
2267
5.38k
  RecordData ModuleMacroRecord;
2268
2269
  // If the preprocessor __COUNTER__ value has been bumped, remember it.
2270
5.38k
  if (PP.getCounterValue() != 0) {
2271
5
    RecordData::value_type Record[] = {PP.getCounterValue()};
2272
5
    Stream.EmitRecord(PP_COUNTER_VALUE, Record);
2273
5
  }
2274
2275
5.38k
  if (PP.isRecordingPreamble() && 
PP.hasRecordedPreamble()91
) {
2276
7
    assert(!IsModule);
2277
0
    auto SkipInfo = PP.getPreambleSkipInfo();
2278
7
    if (SkipInfo.hasValue()) {
2279
5
      Record.push_back(true);
2280
5
      AddSourceLocation(SkipInfo->HashTokenLoc, Record);
2281
5
      AddSourceLocation(SkipInfo->IfTokenLoc, Record);
2282
5
      Record.push_back(SkipInfo->FoundNonSkipPortion);
2283
5
      Record.push_back(SkipInfo->FoundElse);
2284
5
      AddSourceLocation(SkipInfo->ElseLoc, Record);
2285
5
    } else {
2286
2
      Record.push_back(false);
2287
2
    }
2288
7
    for (const auto &Cond : PP.getPreambleConditionalStack()) {
2289
7
      AddSourceLocation(Cond.IfLoc, Record);
2290
7
      Record.push_back(Cond.WasSkipping);
2291
7
      Record.push_back(Cond.FoundNonSkip);
2292
7
      Record.push_back(Cond.FoundElse);
2293
7
    }
2294
7
    Stream.EmitRecord(PP_CONDITIONAL_STACK, Record);
2295
7
    Record.clear();
2296
7
  }
2297
2298
  // Enter the preprocessor block.
2299
0
  Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
2300
2301
  // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
2302
  // FIXME: Include a location for the use, and say which one was used.
2303
5.38k
  if (PP.SawDateOrTime())
2304
1
    PP.Diag(SourceLocation(), diag::warn_module_uses_date_time) << IsModule;
2305
2306
  // Loop over all the macro directives that are live at the end of the file,
2307
  // emitting each to the PP section.
2308
2309
  // Construct the list of identifiers with macro directives that need to be
2310
  // serialized.
2311
5.38k
  SmallVector<const IdentifierInfo *, 128> MacroIdentifiers;
2312
5.38k
  for (auto &Id : PP.getIdentifierTable())
2313
21.5M
    if (Id.second->hadMacroDefinition() &&
2314
21.5M
        
(2.38M
!Id.second->isFromAST()2.38M
||
2315
2.38M
         
Id.second->hasChangedSinceDeserialization()23.3k
))
2316
2.37M
      MacroIdentifiers.push_back(Id.second);
2317
  // Sort the set of macro definitions that need to be serialized by the
2318
  // name of the macro, to provide a stable ordering.
2319
5.38k
  llvm::sort(MacroIdentifiers, llvm::deref<std::less<>>());
2320
2321
  // Emit the macro directives as a list and associate the offset with the
2322
  // identifier they belong to.
2323
2.37M
  for (const IdentifierInfo *Name : MacroIdentifiers) {
2324
2.37M
    MacroDirective *MD = PP.getLocalMacroDirectiveHistory(Name);
2325
2.37M
    uint64_t StartOffset = Stream.GetCurrentBitNo() - MacroOffsetsBase;
2326
2.37M
    assert((StartOffset >> 32) == 0 && "Macro identifiers offset too large");
2327
2328
    // Emit the macro directives in reverse source order.
2329
3.57M
    for (; MD; 
MD = MD->getPrevious()1.20M
) {
2330
      // Once we hit an ignored macro, we're done: the rest of the chain
2331
      // will all be ignored macros.
2332
2.06M
      if (shouldIgnoreMacro(MD, IsModule, PP))
2333
859k
        break;
2334
2335
1.20M
      AddSourceLocation(MD->getLocation(), Record);
2336
1.20M
      Record.push_back(MD->getKind());
2337
1.20M
      if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) {
2338
1.20M
        Record.push_back(getMacroRef(DefMD->getInfo(), Name));
2339
1.20M
      } else 
if (auto *197
VisMD197
= dyn_cast<VisibilityMacroDirective>(MD)) {
2340
158
        Record.push_back(VisMD->isPublic());
2341
158
      }
2342
1.20M
    }
2343
2344
    // Write out any exported module macros.
2345
2.37M
    bool EmittedModuleMacros = false;
2346
    // We write out exported module macros for PCH as well.
2347
2.37M
    auto Leafs = PP.getLeafModuleMacros(Name);
2348
2.37M
    SmallVector<ModuleMacro*, 8> Worklist(Leafs.begin(), Leafs.end());
2349
2.37M
    llvm::DenseMap<ModuleMacro*, unsigned> Visits;
2350
2.68M
    while (!Worklist.empty()) {
2351
315k
      auto *Macro = Worklist.pop_back_val();
2352
2353
      // Emit a record indicating this submodule exports this macro.
2354
315k
      ModuleMacroRecord.push_back(
2355
315k
          getSubmoduleID(Macro->getOwningModule()));
2356
315k
      ModuleMacroRecord.push_back(getMacroRef(Macro->getMacroInfo(), Name));
2357
315k
      for (auto *M : Macro->overrides())
2358
3.45k
        ModuleMacroRecord.push_back(getSubmoduleID(M->getOwningModule()));
2359
2360
315k
      Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord);
2361
315k
      ModuleMacroRecord.clear();
2362
2363
      // Enqueue overridden macros once we've visited all their ancestors.
2364
315k
      for (auto *M : Macro->overrides())
2365
3.45k
        if (++Visits[M] == M->getNumOverridingMacros())
2366
3.35k
          Worklist.push_back(M);
2367
2368
315k
      EmittedModuleMacros = true;
2369
315k
    }
2370
2371
2.37M
    if (Record.empty() && 
!EmittedModuleMacros1.17M
)
2372
860k
      continue;
2373
2374
1.51M
    IdentMacroDirectivesOffsetMap[Name] = StartOffset;
2375
1.51M
    Stream.EmitRecord(PP_MACRO_DIRECTIVE_HISTORY, Record);
2376
1.51M
    Record.clear();
2377
1.51M
  }
2378
2379
  /// Offsets of each of the macros into the bitstream, indexed by
2380
  /// the local macro ID
2381
  ///
2382
  /// For each identifier that is associated with a macro, this map
2383
  /// provides the offset into the bitstream where that macro is
2384
  /// defined.
2385
5.38k
  std::vector<uint32_t> MacroOffsets;
2386
2387
1.52M
  for (unsigned I = 0, N = MacroInfosToEmit.size(); I != N; 
++I1.51M
) {
2388
1.51M
    const IdentifierInfo *Name = MacroInfosToEmit[I].Name;
2389
1.51M
    MacroInfo *MI = MacroInfosToEmit[I].MI;
2390
1.51M
    MacroID ID = MacroInfosToEmit[I].ID;
2391
2392
1.51M
    if (ID < FirstMacroID) {
2393
0
      assert(0 && "Loaded MacroInfo entered MacroInfosToEmit ?");
2394
0
      continue;
2395
0
    }
2396
2397
    // Record the local offset of this macro.
2398
1.51M
    unsigned Index = ID - FirstMacroID;
2399
1.51M
    if (Index >= MacroOffsets.size())
2400
1.51M
      MacroOffsets.resize(Index + 1);
2401
2402
1.51M
    uint64_t Offset = Stream.GetCurrentBitNo() - MacroOffsetsBase;
2403
1.51M
    assert((Offset >> 32) == 0 && "Macro offset too large");
2404
0
    MacroOffsets[Index] = Offset;
2405
2406
1.51M
    AddIdentifierRef(Name, Record);
2407
1.51M
    AddSourceLocation(MI->getDefinitionLoc(), Record);
2408
1.51M
    AddSourceLocation(MI->getDefinitionEndLoc(), Record);
2409
1.51M
    Record.push_back(MI->isUsed());
2410
1.51M
    Record.push_back(MI->isUsedForHeaderGuard());
2411
1.51M
    unsigned Code;
2412
1.51M
    if (MI->isObjectLike()) {
2413
1.45M
      Code = PP_MACRO_OBJECT_LIKE;
2414
1.45M
    } else {
2415
56.9k
      Code = PP_MACRO_FUNCTION_LIKE;
2416
2417
56.9k
      Record.push_back(MI->isC99Varargs());
2418
56.9k
      Record.push_back(MI->isGNUVarargs());
2419
56.9k
      Record.push_back(MI->hasCommaPasting());
2420
56.9k
      Record.push_back(MI->getNumParams());
2421
56.9k
      for (const IdentifierInfo *Param : MI->params())
2422
130k
        AddIdentifierRef(Param, Record);
2423
56.9k
    }
2424
2425
    // If we have a detailed preprocessing record, record the macro definition
2426
    // ID that corresponds to this macro.
2427
1.51M
    if (PPRec)
2428
47.2k
      Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
2429
2430
1.51M
    Stream.EmitRecord(Code, Record);
2431
1.51M
    Record.clear();
2432
2433
    // Emit the tokens array.
2434
4.94M
    for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; 
++TokNo3.42M
) {
2435
      // Note that we know that the preprocessor does not have any annotation
2436
      // tokens in it because they are created by the parser, and thus can't
2437
      // be in a macro definition.
2438
3.42M
      const Token &Tok = MI->getReplacementToken(TokNo);
2439
3.42M
      AddToken(Tok, Record);
2440
3.42M
      Stream.EmitRecord(PP_TOKEN, Record);
2441
3.42M
      Record.clear();
2442
3.42M
    }
2443
1.51M
    ++NumMacros;
2444
1.51M
  }
2445
2446
5.38k
  Stream.ExitBlock();
2447
2448
  // Write the offsets table for macro IDs.
2449
5.38k
  using namespace llvm;
2450
2451
5.38k
  auto Abbrev = std::make_shared<BitCodeAbbrev>();
2452
5.38k
  Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET));
2453
5.38k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros
2454
5.38k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
2455
5.38k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32));   // base offset
2456
5.38k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2457
2458
5.38k
  unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2459
5.38k
  {
2460
5.38k
    RecordData::value_type Record[] = {MACRO_OFFSET, MacroOffsets.size(),
2461
5.38k
                                       FirstMacroID - NUM_PREDEF_MACRO_IDS,
2462
5.38k
                                       MacroOffsetsBase - ASTBlockStartOffset};
2463
5.38k
    Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record, bytes(MacroOffsets));
2464
5.38k
  }
2465
5.38k
}
2466
2467
void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec,
2468
209
                                        uint64_t MacroOffsetsBase) {
2469
209
  if (PPRec.local_begin() == PPRec.local_end())
2470
1
    return;
2471
2472
208
  SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
2473
2474
  // Enter the preprocessor block.
2475
208
  Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
2476
2477
  // If the preprocessor has a preprocessing record, emit it.
2478
208
  unsigned NumPreprocessingRecords = 0;
2479
208
  using namespace llvm;
2480
2481
  // Set up the abbreviation for
2482
208
  unsigned InclusionAbbrev = 0;
2483
208
  {
2484
208
    auto Abbrev = std::make_shared<BitCodeAbbrev>();
2485
208
    Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
2486
208
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
2487
208
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
2488
208
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
2489
208
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module
2490
208
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2491
208
    InclusionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2492
208
  }
2493
2494
208
  unsigned FirstPreprocessorEntityID
2495
208
    = (Chain ? 
PPRec.getNumLoadedPreprocessedEntities()95
:
0113
)
2496
208
    + NUM_PREDEF_PP_ENTITY_IDS;
2497
208
  unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
2498
208
  RecordData Record;
2499
208
  for (PreprocessingRecord::iterator E = PPRec.local_begin(),
2500
208
                                  EEnd = PPRec.local_end();
2501
71.1k
       E != EEnd;
2502
70.9k
       (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
2503
70.9k
    Record.clear();
2504
2505
70.9k
    uint64_t Offset = Stream.GetCurrentBitNo() - MacroOffsetsBase;
2506
70.9k
    assert((Offset >> 32) == 0 && "Preprocessed entity offset too large");
2507
0
    PreprocessedEntityOffsets.push_back(
2508
70.9k
        PPEntityOffset((*E)->getSourceRange(), Offset));
2509
2510
70.9k
    if (auto *MD = dyn_cast<MacroDefinitionRecord>(*E)) {
2511
      // Record this macro definition's ID.
2512
70.6k
      MacroDefinitions[MD] = NextPreprocessorEntityID;
2513
2514
70.6k
      AddIdentifierRef(MD->getName(), Record);
2515
70.6k
      Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
2516
70.6k
      continue;
2517
70.6k
    }
2518
2519
295
    if (auto *ME = dyn_cast<MacroExpansion>(*E)) {
2520
38
      Record.push_back(ME->isBuiltinMacro());
2521
38
      if (ME->isBuiltinMacro())
2522
6
        AddIdentifierRef(ME->getName(), Record);
2523
32
      else
2524
32
        Record.push_back(MacroDefinitions[ME->getDefinition()]);
2525
38
      Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
2526
38
      continue;
2527
38
    }
2528
2529
257
    if (auto *ID = dyn_cast<InclusionDirective>(*E)) {
2530
257
      Record.push_back(PPD_INCLUSION_DIRECTIVE);
2531
257
      Record.push_back(ID->getFileName().size());
2532
257
      Record.push_back(ID->wasInQuotes());
2533
257
      Record.push_back(static_cast<unsigned>(ID->getKind()));
2534
257
      Record.push_back(ID->importedModule());
2535
257
      SmallString<64> Buffer;
2536
257
      Buffer += ID->getFileName();
2537
      // Check that the FileEntry is not null because it was not resolved and
2538
      // we create a PCH even with compiler errors.
2539
257
      if (ID->getFile())
2540
254
        Buffer += ID->getFile()->getName();
2541
257
      Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
2542
257
      continue;
2543
257
    }
2544
2545
0
    llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
2546
0
  }
2547
208
  Stream.ExitBlock();
2548
2549
  // Write the offsets table for the preprocessing record.
2550
208
  if (NumPreprocessingRecords > 0) {
2551
208
    assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords);
2552
2553
    // Write the offsets table for identifier IDs.
2554
0
    using namespace llvm;
2555
2556
208
    auto Abbrev = std::make_shared<BitCodeAbbrev>();
2557
208
    Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
2558
208
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
2559
208
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2560
208
    unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2561
2562
208
    RecordData::value_type Record[] = {PPD_ENTITIES_OFFSETS,
2563
208
                                       FirstPreprocessorEntityID -
2564
208
                                           NUM_PREDEF_PP_ENTITY_IDS};
2565
208
    Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
2566
208
                              bytes(PreprocessedEntityOffsets));
2567
208
  }
2568
2569
  // Write the skipped region table for the preprocessing record.
2570
0
  ArrayRef<SourceRange> SkippedRanges = PPRec.getSkippedRanges();
2571
208
  if (SkippedRanges.size() > 0) {
2572
34
    std::vector<PPSkippedRange> SerializedSkippedRanges;
2573
34
    SerializedSkippedRanges.reserve(SkippedRanges.size());
2574
34
    for (auto const& Range : SkippedRanges)
2575
49
      SerializedSkippedRanges.emplace_back(Range);
2576
2577
34
    using namespace llvm;
2578
34
    auto Abbrev = std::make_shared<BitCodeAbbrev>();
2579
34
    Abbrev->Add(BitCodeAbbrevOp(PPD_SKIPPED_RANGES));
2580
34
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2581
34
    unsigned PPESkippedRangeAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2582
2583
34
    Record.clear();
2584
34
    Record.push_back(PPD_SKIPPED_RANGES);
2585
34
    Stream.EmitRecordWithBlob(PPESkippedRangeAbbrev, Record,
2586
34
                              bytes(SerializedSkippedRanges));
2587
34
  }
2588
208
}
2589
2590
3.53M
unsigned ASTWriter::getLocalOrImportedSubmoduleID(const Module *Mod) {
2591
3.53M
  if (!Mod)
2592
445k
    return 0;
2593
2594
3.08M
  auto Known = SubmoduleIDs.find(Mod);
2595
3.08M
  if (Known != SubmoduleIDs.end())
2596
3.06M
    return Known->second;
2597
2598
24.1k
  auto *Top = Mod->getTopLevelModule();
2599
24.1k
  if (Top != WritingModule &&
2600
24.1k
      
(366
getLangOpts().CompilingPCH366
||
2601
366
       
!Top->fullModuleNameIs(StringRef(getLangOpts().CurrentModule))362
))
2602
366
    return 0;
2603
2604
23.7k
  return SubmoduleIDs[Mod] = NextSubmoduleID++;
2605
24.1k
}
2606
2607
3.48M
unsigned ASTWriter::getSubmoduleID(Module *Mod) {
2608
  // FIXME: This can easily happen, if we have a reference to a submodule that
2609
  // did not result in us loading a module file for that submodule. For
2610
  // instance, a cross-top-level-module 'conflict' declaration will hit this.
2611
3.48M
  unsigned ID = getLocalOrImportedSubmoduleID(Mod);
2612
3.48M
  assert((ID || !Mod) &&
2613
3.48M
         "asked for module ID for non-local, non-imported module");
2614
0
  return ID;
2615
3.48M
}
2616
2617
/// Compute the number of modules within the given tree (including the
2618
/// given module).
2619
47.5k
static unsigned getNumberOfModules(Module *Mod) {
2620
47.5k
  unsigned ChildModules = 0;
2621
47.5k
  for (auto Sub = Mod->submodule_begin(), SubEnd = Mod->submodule_end();
2622
91.2k
       Sub != SubEnd; 
++Sub43.6k
)
2623
43.6k
    ChildModules += getNumberOfModules(*Sub);
2624
2625
47.5k
  return ChildModules + 1;
2626
47.5k
}
2627
2628
1.95k
void ASTWriter::WriteSubmodules(Module *WritingModule) {
2629
  // Enter the submodule description block.
2630
1.95k
  Stream.EnterSubblock(SUBMODULE_BLOCK_ID, /*bits for abbreviations*/5);
2631
2632
  // Write the abbreviations needed for the submodules block.
2633
1.95k
  using namespace llvm;
2634
2635
1.95k
  auto Abbrev = std::make_shared<BitCodeAbbrev>();
2636
1.95k
  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
2637
1.95k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
2638
1.95k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
2639
1.95k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Kind
2640
1.95k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2641
1.95k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
2642
1.95k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem
2643
1.95k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExternC
2644
1.95k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules...
2645
1.95k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
2646
1.95k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
2647
1.95k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ConfigMacrosExh...
2648
1.95k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ModuleMapIsPriv...
2649
1.95k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2650
1.95k
  unsigned DefinitionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2651
2652
1.95k
  Abbrev = std::make_shared<BitCodeAbbrev>();
2653
1.95k
  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
2654
1.95k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2655
1.95k
  unsigned UmbrellaAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2656
2657
1.95k
  Abbrev = std::make_shared<BitCodeAbbrev>();
2658
1.95k
  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
2659
1.95k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2660
1.95k
  unsigned HeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2661
2662
1.95k
  Abbrev = std::make_shared<BitCodeAbbrev>();
2663
1.95k
  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TOPHEADER));
2664
1.95k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2665
1.95k
  unsigned TopHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2666
2667
1.95k
  Abbrev = std::make_shared<BitCodeAbbrev>();
2668
1.95k
  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
2669
1.95k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2670
1.95k
  unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2671
2672
1.95k
  Abbrev = std::make_shared<BitCodeAbbrev>();
2673
1.95k
  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES));
2674
1.95k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // State
2675
1.95k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));     // Feature
2676
1.95k
  unsigned RequiresAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2677
2678
1.95k
  Abbrev = std::make_shared<BitCodeAbbrev>();
2679
1.95k
  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXCLUDED_HEADER));
2680
1.95k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2681
1.95k
  unsigned ExcludedHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2682
2683
1.95k
  Abbrev = std::make_shared<BitCodeAbbrev>();
2684
1.95k
  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TEXTUAL_HEADER));
2685
1.95k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2686
1.95k
  unsigned TextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2687
2688
1.95k
  Abbrev = std::make_shared<BitCodeAbbrev>();
2689
1.95k
  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_HEADER));
2690
1.95k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2691
1.95k
  unsigned PrivateHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2692
2693
1.95k
  Abbrev = std::make_shared<BitCodeAbbrev>();
2694
1.95k
  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_TEXTUAL_HEADER));
2695
1.95k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2696
1.95k
  unsigned PrivateTextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2697
2698
1.95k
  Abbrev = std::make_shared<BitCodeAbbrev>();
2699
1.95k
  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_LINK_LIBRARY));
2700
1.95k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2701
1.95k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));     // Name
2702
1.95k
  unsigned LinkLibraryAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2703
2704
1.95k
  Abbrev = std::make_shared<BitCodeAbbrev>();
2705
1.95k
  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFIG_MACRO));
2706
1.95k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));    // Macro name
2707
1.95k
  unsigned ConfigMacroAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2708
2709
1.95k
  Abbrev = std::make_shared<BitCodeAbbrev>();
2710
1.95k
  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFLICT));
2711
1.95k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));  // Other module
2712
1.95k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));    // Message
2713
1.95k
  unsigned ConflictAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2714
2715
1.95k
  Abbrev = std::make_shared<BitCodeAbbrev>();
2716
1.95k
  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXPORT_AS));
2717
1.95k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));    // Macro name
2718
1.95k
  unsigned ExportAsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2719
2720
  // Write the submodule metadata block.
2721
1.95k
  RecordData::value_type Record[] = {
2722
1.95k
      getNumberOfModules(WritingModule),
2723
1.95k
      FirstSubmoduleID - NUM_PREDEF_SUBMODULE_IDS};
2724
1.95k
  Stream.EmitRecord(SUBMODULE_METADATA, Record);
2725
2726
  // Write all of the submodules.
2727
1.95k
  std::queue<Module *> Q;
2728
1.95k
  Q.push(WritingModule);
2729
25.7k
  while (!Q.empty()) {
2730
23.7k
    Module *Mod = Q.front();
2731
23.7k
    Q.pop();
2732
23.7k
    unsigned ID = getSubmoduleID(Mod);
2733
2734
23.7k
    uint64_t ParentID = 0;
2735
23.7k
    if (Mod->Parent) {
2736
21.8k
      assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?");
2737
0
      ParentID = SubmoduleIDs[Mod->Parent];
2738
21.8k
    }
2739
2740
    // Emit the definition of the block.
2741
0
    {
2742
23.7k
      RecordData::value_type Record[] = {SUBMODULE_DEFINITION,
2743
23.7k
                                         ID,
2744
23.7k
                                         ParentID,
2745
23.7k
                                         (RecordData::value_type)Mod->Kind,
2746
23.7k
                                         Mod->IsFramework,
2747
23.7k
                                         Mod->IsExplicit,
2748
23.7k
                                         Mod->IsSystem,
2749
23.7k
                                         Mod->IsExternC,
2750
23.7k
                                         Mod->InferSubmodules,
2751
23.7k
                                         Mod->InferExplicitSubmodules,
2752
23.7k
                                         Mod->InferExportWildcard,
2753
23.7k
                                         Mod->ConfigMacrosExhaustive,
2754
23.7k
                                         Mod->ModuleMapIsPrivate};
2755
23.7k
      Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
2756
23.7k
    }
2757
2758
    // Emit the requirements.
2759
23.7k
    for (const auto &R : Mod->Requirements) {
2760
698
      RecordData::value_type Record[] = {SUBMODULE_REQUIRES, R.second};
2761
698
      Stream.EmitRecordWithBlob(RequiresAbbrev, Record, R.first);
2762
698
    }
2763
2764
    // Emit the umbrella header, if there is one.
2765
23.7k
    if (auto UmbrellaHeader = Mod->getUmbrellaHeader()) {
2766
475
      RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_HEADER};
2767
475
      Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
2768
475
                                UmbrellaHeader.NameAsWritten);
2769
23.3k
    } else if (auto UmbrellaDir = Mod->getUmbrellaDir()) {
2770
202
      RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_DIR};
2771
202
      Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,
2772
202
                                UmbrellaDir.NameAsWritten);
2773
202
    }
2774
2775
    // Emit the headers.
2776
23.7k
    struct {
2777
23.7k
      unsigned RecordKind;
2778
23.7k
      unsigned Abbrev;
2779
23.7k
      Module::HeaderKind HeaderKind;
2780
23.7k
    } HeaderLists[] = {
2781
23.7k
      {SUBMODULE_HEADER, HeaderAbbrev, Module::HK_Normal},
2782
23.7k
      {SUBMODULE_TEXTUAL_HEADER, TextualHeaderAbbrev, Module::HK_Textual},
2783
23.7k
      {SUBMODULE_PRIVATE_HEADER, PrivateHeaderAbbrev, Module::HK_Private},
2784
23.7k
      {SUBMODULE_PRIVATE_TEXTUAL_HEADER, PrivateTextualHeaderAbbrev,
2785
23.7k
        Module::HK_PrivateTextual},
2786
23.7k
      {SUBMODULE_EXCLUDED_HEADER, ExcludedHeaderAbbrev, Module::HK_Excluded}
2787
23.7k
    };
2788
118k
    for (auto &HL : HeaderLists) {
2789
118k
      RecordData::value_type Record[] = {HL.RecordKind};
2790
118k
      for (auto &H : Mod->Headers[HL.HeaderKind])
2791
16.2k
        Stream.EmitRecordWithBlob(HL.Abbrev, Record, H.NameAsWritten);
2792
118k
    }
2793
2794
    // Emit the top headers.
2795
23.7k
    {
2796
23.7k
      auto TopHeaders = Mod->getTopHeaders(PP->getFileManager());
2797
23.7k
      RecordData::value_type Record[] = {SUBMODULE_TOPHEADER};
2798
23.7k
      for (auto *H : TopHeaders)
2799
25.5k
        Stream.EmitRecordWithBlob(TopHeaderAbbrev, Record, H->getName());
2800
23.7k
    }
2801
2802
    // Emit the imports.
2803
23.7k
    if (!Mod->Imports.empty()) {
2804
17.4k
      RecordData Record;
2805
17.4k
      for (auto *I : Mod->Imports)
2806
77.9k
        Record.push_back(getSubmoduleID(I));
2807
17.4k
      Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
2808
17.4k
    }
2809
2810
    // Emit the exports.
2811
23.7k
    if (!Mod->Exports.empty()) {
2812
17.1k
      RecordData Record;
2813
17.7k
      for (const auto &E : Mod->Exports) {
2814
        // FIXME: This may fail; we don't require that all exported modules
2815
        // are local or imported.
2816
17.7k
        Record.push_back(getSubmoduleID(E.getPointer()));
2817
17.7k
        Record.push_back(E.getInt());
2818
17.7k
      }
2819
17.1k
      Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
2820
17.1k
    }
2821
2822
    //FIXME: How do we emit the 'use'd modules?  They may not be submodules.
2823
    // Might be unnecessary as use declarations are only used to build the
2824
    // module itself.
2825
2826
    // Emit the link libraries.
2827
23.7k
    for (const auto &LL : Mod->LinkLibraries) {
2828
195
      RecordData::value_type Record[] = {SUBMODULE_LINK_LIBRARY,
2829
195
                                         LL.IsFramework};
2830
195
      Stream.EmitRecordWithBlob(LinkLibraryAbbrev, Record, LL.Library);
2831
195
    }
2832
2833
    // Emit the conflicts.
2834
23.7k
    for (const auto &C : Mod->Conflicts) {
2835
      // FIXME: This may fail; we don't require that all conflicting modules
2836
      // are local or imported.
2837
1
      RecordData::value_type Record[] = {SUBMODULE_CONFLICT,
2838
1
                                         getSubmoduleID(C.Other)};
2839
1
      Stream.EmitRecordWithBlob(ConflictAbbrev, Record, C.Message);
2840
1
    }
2841
2842
    // Emit the configuration macros.
2843
23.7k
    for (const auto &CM : Mod->ConfigMacros) {
2844
2
      RecordData::value_type Record[] = {SUBMODULE_CONFIG_MACRO};
2845
2
      Stream.EmitRecordWithBlob(ConfigMacroAbbrev, Record, CM);
2846
2
    }
2847
2848
    // Emit the initializers, if any.
2849
23.7k
    RecordData Inits;
2850
23.7k
    for (Decl *D : Context->getModuleInitializers(Mod))
2851
336
      Inits.push_back(GetDeclRef(D));
2852
23.7k
    if (!Inits.empty())
2853
205
      Stream.EmitRecord(SUBMODULE_INITIALIZERS, Inits);
2854
2855
    // Emit the name of the re-exported module, if any.
2856
23.7k
    if (!Mod->ExportAsModule.empty()) {
2857
6
      RecordData::value_type Record[] = {SUBMODULE_EXPORT_AS};
2858
6
      Stream.EmitRecordWithBlob(ExportAsAbbrev, Record, Mod->ExportAsModule);
2859
6
    }
2860
2861
    // Queue up the submodules of this module.
2862
23.7k
    for (auto *M : Mod->submodules())
2863
21.8k
      Q.push(M);
2864
23.7k
  }
2865
2866
1.95k
  Stream.ExitBlock();
2867
2868
1.95k
  assert((NextSubmoduleID - FirstSubmoduleID ==
2869
1.95k
          getNumberOfModules(WritingModule)) &&
2870
1.95k
         "Wrong # of submodules; found a reference to a non-local, "
2871
1.95k
         "non-imported submodule?");
2872
1.95k
}
2873
2874
void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
2875
5.38k
                                              bool isModule) {
2876
5.38k
  llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64>
2877
5.38k
      DiagStateIDMap;
2878
5.38k
  unsigned CurrID = 0;
2879
5.38k
  RecordData Record;
2880
2881
5.38k
  auto EncodeDiagStateFlags =
2882
34.5k
      [](const DiagnosticsEngine::DiagState *DS) -> unsigned {
2883
34.5k
    unsigned Result = (unsigned)DS->ExtBehavior;
2884
34.5k
    for (unsigned Val :
2885
34.5k
         {(unsigned)DS->IgnoreAllWarnings, (unsigned)DS->EnableAllWarnings,
2886
34.5k
          (unsigned)DS->WarningsAsErrors, (unsigned)DS->ErrorsAsFatal,
2887
34.5k
          (unsigned)DS->SuppressSystemWarnings})
2888
172k
      Result = (Result << 1) | Val;
2889
34.5k
    return Result;
2890
34.5k
  };
2891
2892
5.38k
  unsigned Flags = EncodeDiagStateFlags(Diag.DiagStatesByLoc.FirstDiagState);
2893
5.38k
  Record.push_back(Flags);
2894
2895
5.38k
  auto AddDiagState = [&](const DiagnosticsEngine::DiagState *State,
2896
29.1k
                          bool IncludeNonPragmaStates) {
2897
    // Ensure that the diagnostic state wasn't modified since it was created.
2898
    // We will not correctly round-trip this information otherwise.
2899
29.1k
    assert(Flags == EncodeDiagStateFlags(State) &&
2900
29.1k
           "diag state flags vary in single AST file");
2901
2902
0
    unsigned &DiagStateID = DiagStateIDMap[State];
2903
29.1k
    Record.push_back(DiagStateID);
2904
2905
29.1k
    if (DiagStateID == 0) {
2906
8.30k
      DiagStateID = ++CurrID;
2907
2908
      // Add a placeholder for the number of mappings.
2909
8.30k
      auto SizeIdx = Record.size();
2910
8.30k
      Record.emplace_back();
2911
410k
      for (const auto &I : *State) {
2912
410k
        if (I.second.isPragma() || 
IncludeNonPragmaStates332k
) {
2913
119k
          Record.push_back(I.first);
2914
119k
          Record.push_back(I.second.serialize());
2915
119k
        }
2916
410k
      }
2917
      // Update the placeholder.
2918
8.30k
      Record[SizeIdx] = (Record.size() - SizeIdx) / 2;
2919
8.30k
    }
2920
29.1k
  };
2921
2922
5.38k
  AddDiagState(Diag.DiagStatesByLoc.FirstDiagState, isModule);
2923
2924
  // Reserve a spot for the number of locations with state transitions.
2925
5.38k
  auto NumLocationsIdx = Record.size();
2926
5.38k
  Record.emplace_back();
2927
2928
  // Emit the state transitions.
2929
5.38k
  unsigned NumLocations = 0;
2930
183k
  for (auto &FileIDAndFile : Diag.DiagStatesByLoc.Files) {
2931
183k
    if (!FileIDAndFile.first.isValid() ||
2932
183k
        
!FileIDAndFile.second.HasLocalTransitions182k
)
2933
172k
      continue;
2934
10.2k
    ++NumLocations;
2935
2936
10.2k
    SourceLocation Loc = Diag.SourceMgr->getComposedLoc(FileIDAndFile.first, 0);
2937
10.2k
    assert(!Loc.isInvalid() && "start loc for valid FileID is invalid");
2938
0
    AddSourceLocation(Loc, Record);
2939
2940
10.2k
    Record.push_back(FileIDAndFile.second.StateTransitions.size());
2941
18.4k
    for (auto &StatePoint : FileIDAndFile.second.StateTransitions) {
2942
18.4k
      Record.push_back(StatePoint.Offset);
2943
18.4k
      AddDiagState(StatePoint.State, false);
2944
18.4k
    }
2945
10.2k
  }
2946
2947
  // Backpatch the number of locations.
2948
5.38k
  Record[NumLocationsIdx] = NumLocations;
2949
2950
  // Emit CurDiagStateLoc.  Do it last in order to match source order.
2951
  //
2952
  // This also protects against a hypothetical corner case with simulating
2953
  // -Werror settings for implicit modules in the ASTReader, where reading
2954
  // CurDiagState out of context could change whether warning pragmas are
2955
  // treated as errors.
2956
5.38k
  AddSourceLocation(Diag.DiagStatesByLoc.CurDiagStateLoc, Record);
2957
5.38k
  AddDiagState(Diag.DiagStatesByLoc.CurDiagState, false);
2958
2959
5.38k
  Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
2960
5.38k
}
2961
2962
//===----------------------------------------------------------------------===//
2963
// Type Serialization
2964
//===----------------------------------------------------------------------===//
2965
2966
/// Write the representation of a type to the AST stream.
2967
1.46M
void ASTWriter::WriteType(QualType T) {
2968
1.46M
  TypeIdx &IdxRef = TypeIdxs[T];
2969
1.46M
  if (IdxRef.getIndex() == 0) // we haven't seen this type before.
2970
0
    IdxRef = TypeIdx(NextTypeID++);
2971
1.46M
  TypeIdx Idx = IdxRef;
2972
2973
1.46M
  assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
2974
2975
  // Emit the type's representation.
2976
0
  uint64_t Offset = ASTTypeWriter(*this).write(T) - DeclTypesBlockStartOffset;
2977
2978
  // Record the offset for this type.
2979
1.46M
  unsigned Index = Idx.getIndex() - FirstTypeID;
2980
1.46M
  if (TypeOffsets.size() == Index)
2981
1.46M
    TypeOffsets.emplace_back(Offset);
2982
0
  else if (TypeOffsets.size() < Index) {
2983
0
    TypeOffsets.resize(Index + 1);
2984
0
    TypeOffsets[Index].setBitOffset(Offset);
2985
0
  } else {
2986
0
    llvm_unreachable("Types emitted in wrong order");
2987
0
  }
2988
1.46M
}
2989
2990
//===----------------------------------------------------------------------===//
2991
// Declaration Serialization
2992
//===----------------------------------------------------------------------===//
2993
2994
/// Write the block containing all of the declaration IDs
2995
/// lexically declared within the given DeclContext.
2996
///
2997
/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
2998
/// bitstream, or 0 if no block was written.
2999
uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
3000
789k
                                                 DeclContext *DC) {
3001
789k
  if (DC->decls_empty())
3002
473k
    return 0;
3003
3004
315k
  uint64_t Offset = Stream.GetCurrentBitNo();
3005
315k
  SmallVector<uint32_t, 128> KindDeclPairs;
3006
1.53M
  for (const auto *D : DC->decls()) {
3007
1.53M
    KindDeclPairs.push_back(D->getKind());
3008
1.53M
    KindDeclPairs.push_back(GetDeclRef(D));
3009
1.53M
  }
3010
3011
315k
  ++NumLexicalDeclContexts;
3012
315k
  RecordData::value_type Record[] = {DECL_CONTEXT_LEXICAL};
3013
315k
  Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record,
3014
315k
                            bytes(KindDeclPairs));
3015
315k
  return Offset;
3016
789k
}
3017
3018
5.38k
void ASTWriter::WriteTypeDeclOffsets() {
3019
5.38k
  using namespace llvm;
3020
3021
  // Write the type offsets array
3022
5.38k
  auto Abbrev = std::make_shared<BitCodeAbbrev>();
3023
5.38k
  Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
3024
5.38k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
3025
5.38k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index
3026
5.38k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
3027
5.38k
  unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3028
5.38k
  {
3029
5.38k
    RecordData::value_type Record[] = {TYPE_OFFSET, TypeOffsets.size(),
3030
5.38k
                                       FirstTypeID - NUM_PREDEF_TYPE_IDS};
3031
5.38k
    Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, bytes(TypeOffsets));
3032
5.38k
  }
3033
3034
  // Write the declaration offsets array
3035
5.38k
  Abbrev = std::make_shared<BitCodeAbbrev>();
3036
5.38k
  Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
3037
5.38k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
3038
5.38k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID
3039
5.38k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
3040
5.38k
  unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3041
5.38k
  {
3042
5.38k
    RecordData::value_type Record[] = {DECL_OFFSET, DeclOffsets.size(),
3043
5.38k
                                       FirstDeclID - NUM_PREDEF_DECL_IDS};
3044
5.38k
    Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, bytes(DeclOffsets));
3045
5.38k
  }
3046
5.38k
}
3047
3048
5.38k
void ASTWriter::WriteFileDeclIDsMap() {
3049
5.38k
  using namespace llvm;
3050
3051
5.38k
  SmallVector<std::pair<FileID, DeclIDInFileInfo *>, 64> SortedFileDeclIDs;
3052
5.38k
  SortedFileDeclIDs.reserve(FileDeclIDs.size());
3053
5.38k
  for (const auto &P : FileDeclIDs)
3054
84.7k
    SortedFileDeclIDs.push_back(std::make_pair(P.first, P.second.get()));
3055
5.38k
  llvm::sort(SortedFileDeclIDs, llvm::less_first());
3056
3057
  // Join the vectors of DeclIDs from all files.
3058
5.38k
  SmallVector<DeclID, 256> FileGroupedDeclIDs;
3059
84.7k
  for (auto &FileDeclEntry : SortedFileDeclIDs) {
3060
84.7k
    DeclIDInFileInfo &Info = *FileDeclEntry.second;
3061
84.7k
    Info.FirstDeclIndex = FileGroupedDeclIDs.size();
3062
84.7k
    for (auto &LocDeclEntry : Info.DeclIDs)
3063
563k
      FileGroupedDeclIDs.push_back(LocDeclEntry.second);
3064
84.7k
  }
3065
3066
5.38k
  auto Abbrev = std::make_shared<BitCodeAbbrev>();
3067
5.38k
  Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
3068
5.38k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3069
5.38k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3070
5.38k
  unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
3071
5.38k
  RecordData::value_type Record[] = {FILE_SORTED_DECLS,
3072
5.38k
                                     FileGroupedDeclIDs.size()};
3073
5.38k
  Stream.EmitRecordWithBlob(AbbrevCode, Record, bytes(FileGroupedDeclIDs));
3074
5.38k
}
3075
3076
5.38k
void ASTWriter::WriteComments() {
3077
5.38k
  Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
3078
5.38k
  auto _ = llvm::make_scope_exit([this] { Stream.ExitBlock(); });
3079
5.38k
  if (!PP->getPreprocessorOpts().WriteCommentListToPCH)
3080
0
    return;
3081
5.38k
  RecordData Record;
3082
5.38k
  for (const auto &FO : Context->Comments.OrderedComments) {
3083
6.73k
    for (const auto &OC : FO.second) {
3084
6.73k
      const RawComment *I = OC.second;
3085
6.73k
      Record.clear();
3086
6.73k
      AddSourceRange(I->getSourceRange(), Record);
3087
6.73k
      Record.push_back(I->getKind());
3088
6.73k
      Record.push_back(I->isTrailingComment());
3089
6.73k
      Record.push_back(I->isAlmostTrailingComment());
3090
6.73k
      Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
3091
6.73k
    }
3092
698
  }
3093
5.38k
}
3094
3095
//===----------------------------------------------------------------------===//
3096
// Global Method Pool and Selector Serialization
3097
//===----------------------------------------------------------------------===//
3098
3099
namespace {
3100
3101
// Trait used for the on-disk hash table used in the method pool.
3102
class ASTMethodPoolTrait {
3103
  ASTWriter &Writer;
3104
3105
public:
3106
  using key_type = Selector;
3107
  using key_type_ref = key_type;
3108
3109
  struct data_type {
3110
    SelectorID ID;
3111
    ObjCMethodList Instance, Factory;
3112
  };
3113
  using data_type_ref = const data_type &;
3114
3115
  using hash_value_type = unsigned;
3116
  using offset_type = unsigned;
3117
3118
480
  explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) {}
3119
3120
40.9k
  static hash_value_type ComputeHash(Selector Sel) {
3121
40.9k
    return serialization::ComputeHash(Sel);
3122
40.9k
  }
3123
3124
  std::pair<unsigned, unsigned>
3125
    EmitKeyDataLength(raw_ostream& Out, Selector Sel,
3126
40.9k
                      data_type_ref Methods) {
3127
40.9k
    unsigned KeyLen = 2 + (Sel.getNumArgs()? 
Sel.getNumArgs() * 426.7k
:
414.2k
);
3128
40.9k
    unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
3129
92.6k
    for (const ObjCMethodList *Method = &Methods.Instance; Method;
3130
51.6k
         Method = Method->getNext())
3131
51.6k
      if (ShouldWriteMethodListNode(Method))
3132
39.9k
        DataLen += 4;
3133
82.2k
    for (const ObjCMethodList *Method = &Methods.Factory; Method;
3134
41.3k
         Method = Method->getNext())
3135
41.3k
      if (ShouldWriteMethodListNode(Method))
3136
5.85k
        DataLen += 4;
3137
40.9k
    return emitULEBKeyDataLength(KeyLen, DataLen, Out);
3138
40.9k
  }
3139
3140
40.9k
  void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
3141
40.9k
    using namespace llvm::support;
3142
3143
40.9k
    endian::Writer LE(Out, little);
3144
40.9k
    uint64_t Start = Out.tell();
3145
40.9k
    assert((Start >> 32) == 0 && "Selector key offset too large");
3146
0
    Writer.SetSelectorOffset(Sel, Start);
3147
40.9k
    unsigned N = Sel.getNumArgs();
3148
40.9k
    LE.write<uint16_t>(N);
3149
40.9k
    if (N == 0)
3150
14.2k
      N = 1;
3151
95.7k
    for (unsigned I = 0; I != N; 
++I54.7k
)
3152
54.7k
      LE.write<uint32_t>(
3153
54.7k
          Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
3154
40.9k
  }
3155
3156
  void EmitData(raw_ostream& Out, key_type_ref,
3157
40.9k
                data_type_ref Methods, unsigned DataLen) {
3158
40.9k
    using namespace llvm::support;
3159
3160
40.9k
    endian::Writer LE(Out, little);
3161
40.9k
    uint64_t Start = Out.tell(); (void)Start;
3162
40.9k
    LE.write<uint32_t>(Methods.ID);
3163
40.9k
    unsigned NumInstanceMethods = 0;
3164
92.6k
    for (const ObjCMethodList *Method = &Methods.Instance; Method;
3165
51.6k
         Method = Method->getNext())
3166
51.6k
      if (ShouldWriteMethodListNode(Method))
3167
39.9k
        ++NumInstanceMethods;
3168
3169
40.9k
    unsigned NumFactoryMethods = 0;
3170
82.2k
    for (const ObjCMethodList *Method = &Methods.Factory; Method;
3171
41.3k
         Method = Method->getNext())
3172
41.3k
      if (ShouldWriteMethodListNode(Method))
3173
5.85k
        ++NumFactoryMethods;
3174
3175
40.9k
    unsigned InstanceBits = Methods.Instance.getBits();
3176
40.9k
    assert(InstanceBits < 4);
3177
0
    unsigned InstanceHasMoreThanOneDeclBit =
3178
40.9k
        Methods.Instance.hasMoreThanOneDecl();
3179
40.9k
    unsigned FullInstanceBits = (NumInstanceMethods << 3) |
3180
40.9k
                                (InstanceHasMoreThanOneDeclBit << 2) |
3181
40.9k
                                InstanceBits;
3182
40.9k
    unsigned FactoryBits = Methods.Factory.getBits();
3183
40.9k
    assert(FactoryBits < 4);
3184
0
    unsigned FactoryHasMoreThanOneDeclBit =
3185
40.9k
        Methods.Factory.hasMoreThanOneDecl();
3186
40.9k
    unsigned FullFactoryBits = (NumFactoryMethods << 3) |
3187
40.9k
                               (FactoryHasMoreThanOneDeclBit << 2) |
3188
40.9k
                               FactoryBits;
3189
40.9k
    LE.write<uint16_t>(FullInstanceBits);
3190
40.9k
    LE.write<uint16_t>(FullFactoryBits);
3191
92.6k
    for (const ObjCMethodList *Method = &Methods.Instance; Method;
3192
51.6k
         Method = Method->getNext())
3193
51.6k
      if (ShouldWriteMethodListNode(Method))
3194
39.9k
        LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
3195
82.2k
    for (const ObjCMethodList *Method = &Methods.Factory; Method;
3196
41.3k
         Method = Method->getNext())
3197
41.3k
      if (ShouldWriteMethodListNode(Method))
3198
5.85k
        LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
3199
3200
40.9k
    assert(Out.tell() - Start == DataLen && "Data length is wrong");
3201
40.9k
  }
3202
3203
private:
3204
278k
  static bool ShouldWriteMethodListNode(const ObjCMethodList *Node) {
3205
278k
    return (Node->getMethod() && 
!Node->getMethod()->isFromASTFile()139k
);
3206
278k
  }
3207
};
3208
3209
} // namespace
3210
3211
/// Write ObjC data: selectors and the method pool.
3212
///
3213
/// The method pool contains both instance and factory methods, stored
3214
/// in an on-disk hash table indexed by the selector. The hash table also
3215
/// contains an empty entry for every other selector known to Sema.
3216
5.38k
void ASTWriter::WriteSelectors(Sema &SemaRef) {
3217
5.38k
  using namespace llvm;
3218
3219
  // Do we have to do anything at all?
3220
5.38k
  if (SemaRef.MethodPool.empty() && 
SelectorIDs.empty()5.14k
)
3221
5.14k
    return;
3222
240
  unsigned NumTableEntries = 0;
3223
  // Create and write out the blob that contains selectors and the method pool.
3224
240
  {
3225
240
    llvm::OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
3226
240
    ASTMethodPoolTrait Trait(*this);
3227
3228
    // Create the on-disk hash table representation. We walk through every
3229
    // selector we've seen and look it up in the method pool.
3230
240
    SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
3231
41.8k
    for (auto &SelectorAndID : SelectorIDs) {
3232
41.8k
      Selector S = SelectorAndID.first;
3233
41.8k
      SelectorID ID = SelectorAndID.second;
3234
41.8k
      Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
3235
41.8k
      ASTMethodPoolTrait::data_type Data = {
3236
41.8k
        ID,
3237
41.8k
        ObjCMethodList(),
3238
41.8k
        ObjCMethodList()
3239
41.8k
      };
3240
41.8k
      if (F != SemaRef.MethodPool.end()) {
3241
35.3k
        Data.Instance = F->second.first;
3242
35.3k
        Data.Factory = F->second.second;
3243
35.3k
      }
3244
      // Only write this selector if it's not in an existing AST or something
3245
      // changed.
3246
41.8k
      if (Chain && 
ID < FirstSelectorID41.5k
) {
3247
        // Selector already exists. Did it change?
3248
2.00k
        bool changed = false;
3249
5.45k
        for (ObjCMethodList *M = &Data.Instance; M && 
M->getMethod()5.35k
;
3250
4.51k
             
M = M->getNext()3.45k
) {
3251
4.51k
          if (!M->getMethod()->isFromASTFile()) {
3252
1.06k
            changed = true;
3253
1.06k
            Data.Instance = *M;
3254
1.06k
            break;
3255
1.06k
          }
3256
4.51k
        }
3257
2.18k
        for (ObjCMethodList *M = &Data.Factory; M && 
M->getMethod()2.12k
;
3258
2.00k
             
M = M->getNext()180
) {
3259
257
          if (!M->getMethod()->isFromASTFile()) {
3260
77
            changed = true;
3261
77
            Data.Factory = *M;
3262
77
            break;
3263
77
          }
3264
257
        }
3265
2.00k
        if (!changed)
3266
869
          continue;
3267
39.8k
      } else if (Data.Instance.getMethod() || 
Data.Factory.getMethod()10.9k
) {
3268
        // A new method pool entry.
3269
34.1k
        ++NumTableEntries;
3270
34.1k
      }
3271
40.9k
      Generator.insert(S, Data, Trait);
3272
40.9k
    }
3273
3274
    // Create the on-disk hash table in a buffer.
3275
240
    SmallString<4096> MethodPool;
3276
240
    uint32_t BucketOffset;
3277
240
    {
3278
240
      using namespace llvm::support;
3279
3280
240
      ASTMethodPoolTrait Trait(*this);
3281
240
      llvm::raw_svector_ostream Out(MethodPool);
3282
      // Make sure that no bucket is at offset 0
3283
240
      endian::write<uint32_t>(Out, 0, little);
3284
240
      BucketOffset = Generator.Emit(Out, Trait);
3285
240
    }
3286
3287
    // Create a blob abbreviation
3288
240
    auto Abbrev = std::make_shared<BitCodeAbbrev>();
3289
240
    Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
3290
240
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3291
240
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3292
240
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3293
240
    unsigned MethodPoolAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3294
3295
    // Write the method pool
3296
240
    {
3297
240
      RecordData::value_type Record[] = {METHOD_POOL, BucketOffset,
3298
240
                                         NumTableEntries};
3299
240
      Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool);
3300
240
    }
3301
3302
    // Create a blob abbreviation for the selector table offsets.
3303
240
    Abbrev = std::make_shared<BitCodeAbbrev>();
3304
240
    Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
3305
240
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
3306
240
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
3307
240
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3308
240
    unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3309
3310
    // Write the selector offsets table.
3311
240
    {
3312
240
      RecordData::value_type Record[] = {
3313
240
          SELECTOR_OFFSETS, SelectorOffsets.size(),
3314
240
          FirstSelectorID - NUM_PREDEF_SELECTOR_IDS};
3315
240
      Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
3316
240
                                bytes(SelectorOffsets));
3317
240
    }
3318
240
  }
3319
240
}
3320
3321
/// Write the selectors referenced in @selector expression into AST file.
3322
5.38k
void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
3323
5.38k
  using namespace llvm;
3324
3325
5.38k
  if (SemaRef.ReferencedSelectors.empty())
3326
5.37k
    return;
3327
3328
2
  RecordData Record;
3329
2
  ASTRecordWriter Writer(*this, Record);
3330
3331
  // Note: this writes out all references even for a dependent AST. But it is
3332
  // very tricky to fix, and given that @selector shouldn't really appear in
3333
  // headers, probably not worth it. It's not a correctness issue.
3334
2
  for (auto &SelectorAndLocation : SemaRef.ReferencedSelectors) {
3335
2
    Selector Sel = SelectorAndLocation.first;
3336
2
    SourceLocation Loc = SelectorAndLocation.second;
3337
2
    Writer.AddSelectorRef(Sel);
3338
2
    Writer.AddSourceLocation(Loc);
3339
2
  }
3340
2
  Writer.Emit(REFERENCED_SELECTOR_POOL);
3341
2
}
3342
3343
//===----------------------------------------------------------------------===//
3344
// Identifier Table Serialization
3345
//===----------------------------------------------------------------------===//
3346
3347
/// Determine the declaration that should be put into the name lookup table to
3348
/// represent the given declaration in this module. This is usually D itself,
3349
/// but if D was imported and merged into a local declaration, we want the most
3350
/// recent local declaration instead. The chosen declaration will be the most
3351
/// recent declaration in any module that imports this one.
3352
static NamedDecl *getDeclForLocalLookup(const LangOptions &LangOpts,
3353
1.48M
                                        NamedDecl *D) {
3354
1.48M
  if (!LangOpts.Modules || 
!D->isFromASTFile()1.37M
)
3355
1.42M
    return D;
3356
3357
61.1k
  if (Decl *Redecl = D->getPreviousDecl()) {
3358
    // For Redeclarable decls, a prior declaration might be local.
3359
68.6k
    for (; Redecl; 
Redecl = Redecl->getPreviousDecl()54.9k
) {
3360
      // If we find a local decl, we're done.
3361
55.4k
      if (!Redecl->isFromASTFile()) {
3362
        // Exception: in very rare cases (for injected-class-names), not all
3363
        // redeclarations are in the same semantic context. Skip ones in a
3364
        // different context. They don't go in this lookup table at all.
3365
435
        if (!Redecl->getDeclContext()->getRedeclContext()->Equals(
3366
435
                D->getDeclContext()->getRedeclContext()))
3367
0
          continue;
3368
435
        return cast<NamedDecl>(Redecl);
3369
435
      }
3370
3371
      // If we find a decl from a (chained-)PCH stop since we won't find a
3372
      // local one.
3373
54.9k
      if (Redecl->getOwningModuleID() == 0)
3374
3
        break;
3375
54.9k
    }
3376
47.4k
  } else if (Decl *First = D->getCanonicalDecl()) {
3377
    // For Mergeable decls, the first decl might be local.
3378
47.4k
    if (!First->isFromASTFile())
3379
96
      return cast<NamedDecl>(First);
3380
47.4k
  }
3381
3382
  // All declarations are imported. Our most recent declaration will also be
3383
  // the most recent one in anyone who imports us.
3384
60.6k
  return D;
3385
61.1k
}
3386
3387
namespace {
3388
3389
class ASTIdentifierTableTrait {
3390
  ASTWriter &Writer;
3391
  Preprocessor &PP;
3392
  IdentifierResolver &IdResolver;
3393
  bool IsModule;
3394
  bool NeedDecls;
3395
  ASTWriter::RecordData *InterestingIdentifierOffsets;
3396
3397
  /// Determines whether this is an "interesting" identifier that needs a
3398
  /// full IdentifierInfo structure written into the hash table. Notably, this
3399
  /// doesn't check whether the name has macros defined; use PublicMacroIterator
3400
  /// to check that.
3401
45.3M
  bool isInterestingIdentifier(const IdentifierInfo *II, uint64_t MacroOffset) {
3402
45.3M
    if (MacroOffset || 
II->isPoisoned()42.1M
||
3403
45.3M
        
(42.1M
!IsModule42.1M
&&
II->getObjCOrBuiltinID()30.1M
) ||
3404
45.3M
        
II->hasRevertedTokenIDToIdentifier()14.5M
||
3405
45.3M
        
(14.5M
NeedDecls14.5M
&&
II->getFETokenInfo()6.82M
))
3406
31.7M
      return true;
3407
3408
13.6M
    return false;
3409
45.3M
  }
3410
3411
public:
3412
  using key_type = IdentifierInfo *;
3413
  using key_type_ref = key_type;
3414
3415
  using data_type = IdentID;
3416
  using data_type_ref = data_type;
3417
3418
  using hash_value_type = unsigned;
3419
  using offset_type = unsigned;
3420
3421
  ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
3422
                          IdentifierResolver &IdResolver, bool IsModule,
3423
                          ASTWriter::RecordData *InterestingIdentifierOffsets)
3424
      : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule),
3425
        NeedDecls(!IsModule || !Writer.getLangOpts().CPlusPlus),
3426
5.38k
        InterestingIdentifierOffsets(InterestingIdentifierOffsets) {}
3427
3428
1.85M
  bool needDecls() const { return NeedDecls; }
3429
3430
11.6M
  static hash_value_type ComputeHash(const IdentifierInfo* II) {
3431
11.6M
    return llvm::djbHash(II->getName());
3432
11.6M
  }
3433
3434
535k
  bool isInterestingIdentifier(const IdentifierInfo *II) {
3435
535k
    auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3436
535k
    return isInterestingIdentifier(II, MacroOffset);
3437
535k
  }
3438
3439
21.5M
  bool isInterestingNonMacroIdentifier(const IdentifierInfo *II) {
3440
21.5M
    return isInterestingIdentifier(II, 0);
3441
21.5M
  }
3442
3443
  std::pair<unsigned, unsigned>
3444
11.6M
  EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
3445
    // Record the location of the identifier data. This is used when generating
3446
    // the mapping from persistent IDs to strings.
3447
11.6M
    Writer.SetIdentifierOffset(II, Out.tell());
3448
3449
    // Emit the offset of the key/data length information to the interesting
3450
    // identifiers table if necessary.
3451
11.6M
    if (InterestingIdentifierOffsets && 
isInterestingIdentifier(II)535k
)
3452
162k
      InterestingIdentifierOffsets->push_back(Out.tell());
3453
3454
11.6M
    unsigned KeyLen = II->getLength() + 1;
3455
11.6M
    unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
3456
11.6M
    auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3457
11.6M
    if (isInterestingIdentifier(II, MacroOffset)) {
3458
11.0M
      DataLen += 2; // 2 bytes for builtin ID
3459
11.0M
      DataLen += 2; // 2 bytes for flags
3460
11.0M
      if (MacroOffset)
3461
1.51M
        DataLen += 4; // MacroDirectives offset.
3462
3463
11.0M
      if (NeedDecls) {
3464
10.8M
        for (IdentifierResolver::iterator D = IdResolver.begin(II),
3465
10.8M
                                       DEnd = IdResolver.end();
3466
11.2M
             D != DEnd; 
++D361k
)
3467
361k
          DataLen += 4;
3468
10.8M
      }
3469
11.0M
    }
3470
11.6M
    return emitULEBKeyDataLength(KeyLen, DataLen, Out);
3471
11.6M
  }
3472
3473
  void EmitKey(raw_ostream& Out, const IdentifierInfo* II,
3474
11.6M
               unsigned KeyLen) {
3475
11.6M
    Out.write(II->getNameStart(), KeyLen);
3476
11.6M
  }
3477
3478
  void EmitData(raw_ostream& Out, IdentifierInfo* II,
3479
11.6M
                IdentID ID, unsigned) {
3480
11.6M
    using namespace llvm::support;
3481
3482
11.6M
    endian::Writer LE(Out, little);
3483
3484
11.6M
    auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3485
11.6M
    if (!isInterestingIdentifier(II, MacroOffset)) {
3486
597k
      LE.write<uint32_t>(ID << 1);
3487
597k
      return;
3488
597k
    }
3489
3490
11.0M
    LE.write<uint32_t>((ID << 1) | 0x01);
3491
11.0M
    uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID();
3492
11.0M
    assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader.");
3493
0
    LE.write<uint16_t>(Bits);
3494
11.0M
    Bits = 0;
3495
11.0M
    bool HadMacroDefinition = MacroOffset != 0;
3496
11.0M
    Bits = (Bits << 1) | unsigned(HadMacroDefinition);
3497
11.0M
    Bits = (Bits << 1) | unsigned(II->isExtensionToken());
3498
11.0M
    Bits = (Bits << 1) | unsigned(II->isPoisoned());
3499
11.0M
    Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
3500
11.0M
    Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
3501
11.0M
    LE.write<uint16_t>(Bits);
3502
3503
11.0M
    if (HadMacroDefinition)
3504
1.51M
      LE.write<uint32_t>(MacroOffset);
3505
3506
11.0M
    if (NeedDecls) {
3507
      // Emit the declaration IDs in reverse order, because the
3508
      // IdentifierResolver provides the declarations as they would be
3509
      // visible (e.g., the function "stat" would come before the struct
3510
      // "stat"), but the ASTReader adds declarations to the end of the list
3511
      // (so we need to see the struct "stat" before the function "stat").
3512
      // Only emit declarations that aren't from a chained PCH, though.
3513
10.8M
      SmallVector<NamedDecl *, 16> Decls(IdResolver.begin(II),
3514
10.8M
                                         IdResolver.end());
3515
10.8M
      for (NamedDecl *D : llvm::reverse(Decls))
3516
361k
        LE.write<uint32_t>(
3517
361k
            Writer.getDeclID(getDeclForLocalLookup(PP.getLangOpts(), D)));
3518
10.8M
    }
3519
11.0M
  }
3520
};
3521
3522
} // namespace
3523
3524
/// Write the identifier table into the AST file.
3525
///
3526
/// The identifier table consists of a blob containing string data
3527
/// (the actual identifiers themselves) and a separate "offsets" index
3528
/// that maps identifier IDs to locations within the blob.
3529
void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
3530
                                     IdentifierResolver &IdResolver,
3531
5.38k
                                     bool IsModule) {
3532
5.38k
  using namespace llvm;
3533
3534
5.38k
  RecordData InterestingIdents;
3535
3536
  // Create and write out the blob that contains the identifier
3537
  // strings.
3538
5.38k
  {
3539
5.38k
    llvm::OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
3540
5.38k
    ASTIdentifierTableTrait Trait(
3541
5.38k
        *this, PP, IdResolver, IsModule,
3542
5.38k
        (getLangOpts().CPlusPlus && 
IsModule4.09k
) ?
&InterestingIdents1.13k
:
nullptr4.24k
);
3543
3544
    // Look for any identifiers that were named while processing the
3545
    // headers, but are otherwise not needed. We add these to the hash
3546
    // table to enable checking of the predefines buffer in the case
3547
    // where the user adds new macro definitions when building the AST
3548
    // file.
3549
5.38k
    SmallVector<const IdentifierInfo *, 128> IIs;
3550
5.38k
    for (const auto &ID : PP.getIdentifierTable())
3551
21.5M
      IIs.push_back(ID.second);
3552
    // Sort the identifiers lexicographically before getting them references so
3553
    // that their order is stable.
3554
5.38k
    llvm::sort(IIs, llvm::deref<std::less<>>());
3555
5.38k
    for (const IdentifierInfo *II : IIs)
3556
21.5M
      if (Trait.isInterestingNonMacroIdentifier(II))
3557
9.51M
        getIdentifierRef(II);
3558
3559
    // Create the on-disk hash table representation. We only store offsets
3560
    // for identifiers that appear here for the first time.
3561
5.38k
    IdentifierOffsets.resize(NextIdentID - FirstIdentID);
3562
13.4M
    for (auto IdentIDPair : IdentifierIDs) {
3563
13.4M
      auto *II = const_cast<IdentifierInfo *>(IdentIDPair.first);
3564
13.4M
      IdentID ID = IdentIDPair.second;
3565
13.4M
      assert(II && "NULL identifier in identifier table");
3566
      // Write out identifiers if either the ID is local or the identifier has
3567
      // changed since it was loaded.
3568
13.4M
      if (ID >= FirstIdentID || 
!Chain1.87M
||
!II->isFromAST()1.87M
3569
13.4M
          || 
II->hasChangedSinceDeserialization()1.87M
||
3570
13.4M
          
(1.85M
Trait.needDecls()1.85M
&&
3571
1.85M
           
II->hasFETokenInfoChangedSinceDeserialization()82.7k
))
3572
11.6M
        Generator.insert(II, ID, Trait);
3573
13.4M
    }
3574
3575
    // Create the on-disk hash table in a buffer.
3576
5.38k
    SmallString<4096> IdentifierTable;
3577
5.38k
    uint32_t BucketOffset;
3578
5.38k
    {
3579
5.38k
      using namespace llvm::support;
3580
3581
5.38k
      llvm::raw_svector_ostream Out(IdentifierTable);
3582
      // Make sure that no bucket is at offset 0
3583
5.38k
      endian::write<uint32_t>(Out, 0, little);
3584
5.38k
      BucketOffset = Generator.Emit(Out, Trait);
3585
5.38k
    }
3586
3587
    // Create a blob abbreviation
3588
5.38k
    auto Abbrev = std::make_shared<BitCodeAbbrev>();
3589
5.38k
    Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
3590
5.38k
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3591
5.38k
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3592
5.38k
    unsigned IDTableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3593
3594
    // Write the identifier table
3595
5.38k
    RecordData::value_type Record[] = {IDENTIFIER_TABLE, BucketOffset};
3596
5.38k
    Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable);
3597
5.38k
  }
3598
3599
  // Write the offsets table for identifier IDs.
3600
5.38k
  auto Abbrev = std::make_shared<BitCodeAbbrev>();
3601
5.38k
  Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
3602
5.38k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
3603
5.38k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
3604
5.38k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3605
5.38k
  unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3606
3607
5.38k
#ifndef NDEBUG
3608
11.5M
  for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; 
++I11.5M
)
3609
11.5M
    assert(IdentifierOffsets[I] && "Missing identifier offset?");
3610
5.38k
#endif
3611
3612
5.38k
  RecordData::value_type Record[] = {IDENTIFIER_OFFSET,
3613
5.38k
                                     IdentifierOffsets.size(),
3614
5.38k
                                     FirstIdentID - NUM_PREDEF_IDENT_IDS};
3615
5.38k
  Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
3616
5.38k
                            bytes(IdentifierOffsets));
3617
3618
  // In C++, write the list of interesting identifiers (those that are
3619
  // defined as macros, poisoned, or similar unusual things).
3620
5.38k
  if (!InterestingIdents.empty())
3621
1.13k
    Stream.EmitRecord(INTERESTING_IDENTIFIERS, InterestingIdents);
3622
5.38k
}
3623
3624
//===----------------------------------------------------------------------===//
3625
// DeclContext's Name Lookup Table Serialization
3626
//===----------------------------------------------------------------------===//
3627
3628
namespace {
3629
3630
// Trait used for the on-disk hash table used in the method pool.
3631
class ASTDeclContextNameLookupTrait {
3632
  ASTWriter &Writer;
3633
  llvm::SmallVector<DeclID, 64> DeclIDs;
3634
3635
public:
3636
  using key_type = DeclarationNameKey;
3637
  using key_type_ref = key_type;
3638
3639
  /// A start and end index into DeclIDs, representing a sequence of decls.
3640
  using data_type = std::pair<unsigned, unsigned>;
3641
  using data_type_ref = const data_type &;
3642
3643
  using hash_value_type = unsigned;
3644
  using offset_type = unsigned;
3645
3646
116k
  explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) {}
3647
3648
  template<typename Coll>
3649
1.01M
  data_type getData(const Coll &Decls) {
3650
1.01M
    unsigned Start = DeclIDs.size();
3651
1.12M
    for (NamedDecl *D : Decls) {
3652
1.12M
      DeclIDs.push_back(
3653
1.12M
          Writer.GetDeclRef(getDeclForLocalLookup(Writer.getLangOpts(), D)));
3654
1.12M
    }
3655
1.01M
    return std::make_pair(Start, DeclIDs.size());
3656
1.01M
  }
ASTWriter.cpp:std::__1::pair<unsigned int, unsigned int> (anonymous namespace)::ASTDeclContextNameLookupTrait::getData<clang::DeclContextLookupResult>(clang::DeclContextLookupResult const&)
Line
Count
Source
3649
1.00M
  data_type getData(const Coll &Decls) {
3650
1.00M
    unsigned Start = DeclIDs.size();
3651
1.08M
    for (NamedDecl *D : Decls) {
3652
1.08M
      DeclIDs.push_back(
3653
1.08M
          Writer.GetDeclRef(getDeclForLocalLookup(Writer.getLangOpts(), D)));
3654
1.08M
    }
3655
1.00M
    return std::make_pair(Start, DeclIDs.size());
3656
1.00M
  }
ASTWriter.cpp:std::__1::pair<unsigned int, unsigned int> (anonymous namespace)::ASTDeclContextNameLookupTrait::getData<llvm::SmallVector<clang::NamedDecl*, 8u> >(llvm::SmallVector<clang::NamedDecl*, 8u> const&)
Line
Count
Source
3649
14.2k
  data_type getData(const Coll &Decls) {
3650
14.2k
    unsigned Start = DeclIDs.size();
3651
42.1k
    for (NamedDecl *D : Decls) {
3652
42.1k
      DeclIDs.push_back(
3653
42.1k
          Writer.GetDeclRef(getDeclForLocalLookup(Writer.getLangOpts(), D)));
3654
42.1k
    }
3655
14.2k
    return std::make_pair(Start, DeclIDs.size());
3656
14.2k
  }
3657
3658
710k
  data_type ImportData(const reader::ASTDeclContextNameLookupTrait::data_type &FromReader) {
3659
710k
    unsigned Start = DeclIDs.size();
3660
710k
    for (auto ID : FromReader)
3661
1.13M
      DeclIDs.push_back(ID);
3662
710k
    return std::make_pair(Start, DeclIDs.size());
3663
710k
  }
3664
3665
3.00k
  static bool EqualKey(key_type_ref a, key_type_ref b) {
3666
3.00k
    return a == b;
3667
3.00k
  }
3668
3669
2.44M
  hash_value_type ComputeHash(DeclarationNameKey Name) {
3670
2.44M
    return Name.getHash();
3671
2.44M
  }
3672
3673
406
  void EmitFileRef(raw_ostream &Out, ModuleFile *F) const {
3674
406
    assert(Writer.hasChain() &&
3675
406
           "have reference to loaded module file but no chain?");
3676
3677
0
    using namespace llvm::support;
3678
3679
406
    endian::write<uint32_t>(Out, Writer.getChain()->getModuleFileID(F), little);
3680
406
  }
3681
3682
  std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &Out,
3683
                                                  DeclarationNameKey Name,
3684
1.72M
                                                  data_type_ref Lookup) {
3685
1.72M
    unsigned KeyLen = 1;
3686
1.72M
    switch (Name.getKind()) {
3687
1.64M
    case DeclarationName::Identifier:
3688
1.66M
    case DeclarationName::ObjCZeroArgSelector:
3689
1.68M
    case DeclarationName::ObjCOneArgSelector:
3690
1.68M
    case DeclarationName::ObjCMultiArgSelector:
3691
1.69M
    case DeclarationName::CXXLiteralOperatorName:
3692
1.69M
    case DeclarationName::CXXDeductionGuideName:
3693
1.69M
      KeyLen += 4;
3694
1.69M
      break;
3695
16.1k
    case DeclarationName::CXXOperatorName:
3696
16.1k
      KeyLen += 1;
3697
16.1k
      break;
3698
12.6k
    case DeclarationName::CXXConstructorName:
3699
21.3k
    case DeclarationName::CXXDestructorName:
3700
22.9k
    case DeclarationName::CXXConversionFunctionName:
3701
22.9k
    case DeclarationName::CXXUsingDirective:
3702
22.9k
      break;
3703
1.72M
    }
3704
3705
    // 4 bytes for each DeclID.
3706
1.72M
    unsigned DataLen = 4 * (Lookup.second - Lookup.first);
3707
3708
1.72M
    return emitULEBKeyDataLength(KeyLen, DataLen, Out);
3709
1.72M
  }
3710
3711
1.72M
  void EmitKey(raw_ostream &Out, DeclarationNameKey Name, unsigned) {
3712
1.72M
    using namespace llvm::support;
3713
3714
1.72M
    endian::Writer LE(Out, little);
3715
1.72M
    LE.write<uint8_t>(Name.getKind());
3716
1.72M
    switch (Name.getKind()) {
3717
1.64M
    case DeclarationName::Identifier:
3718
1.64M
    case DeclarationName::CXXLiteralOperatorName:
3719
1.64M
    case DeclarationName::CXXDeductionGuideName:
3720
1.64M
      LE.write<uint32_t>(Writer.getIdentifierRef(Name.getIdentifier()));
3721
1.64M
      return;
3722
19.8k
    case DeclarationName::ObjCZeroArgSelector:
3723
37.1k
    case DeclarationName::ObjCOneArgSelector:
3724
45.7k
    case DeclarationName::ObjCMultiArgSelector:
3725
45.7k
      LE.write<uint32_t>(Writer.getSelectorRef(Name.getSelector()));
3726
45.7k
      return;
3727
16.1k
    case DeclarationName::CXXOperatorName:
3728
16.1k
      assert(Name.getOperatorKind() < NUM_OVERLOADED_OPERATORS &&
3729
16.1k
             "Invalid operator?");
3730
0
      LE.write<uint8_t>(Name.getOperatorKind());
3731
16.1k
      return;
3732
12.6k
    case DeclarationName::CXXConstructorName:
3733
21.3k
    case DeclarationName::CXXDestructorName:
3734
22.9k
    case DeclarationName::CXXConversionFunctionName:
3735
22.9k
    case DeclarationName::CXXUsingDirective:
3736
22.9k
      return;
3737
1.72M
    }
3738
3739
0
    llvm_unreachable("Invalid name kind?");
3740
0
  }
3741
3742
  void EmitData(raw_ostream &Out, key_type_ref, data_type Lookup,
3743
1.72M
                unsigned DataLen) {
3744
1.72M
    using namespace llvm::support;
3745
3746
1.72M
    endian::Writer LE(Out, little);
3747
1.72M
    uint64_t Start = Out.tell(); (void)Start;
3748
3.99M
    for (unsigned I = Lookup.first, N = Lookup.second; I != N; 
++I2.26M
)
3749
2.26M
      LE.write<uint32_t>(DeclIDs[I]);
3750
1.72M
    assert(Out.tell() - Start == DataLen && "Data length is wrong");
3751
1.72M
  }
3752
};
3753
3754
} // namespace
3755
3756
bool ASTWriter::isLookupResultExternal(StoredDeclsList &Result,
3757
1.07M
                                       DeclContext *DC) {
3758
1.07M
  return Result.hasExternalDecls() &&
3759
1.07M
         
DC->hasNeedToReconcileExternalVisibleStorage()98.3k
;
3760
1.07M
}
3761
3762
bool ASTWriter::isLookupResultEntirelyExternal(StoredDeclsList &Result,
3763
41
                                               DeclContext *DC) {
3764
41
  for (auto *D : Result.getLookupResult())
3765
43
    if (!getDeclForLocalLookup(getLangOpts(), D)->isFromASTFile())
3766
21
      return false;
3767
3768
20
  return true;
3769
41
}
3770
3771
void
3772
ASTWriter::GenerateNameLookupTable(const DeclContext *ConstDC,
3773
116k
                                   llvm::SmallVectorImpl<char> &LookupTable) {
3774
116k
  assert(!ConstDC->hasLazyLocalLexicalLookups() &&
3775
116k
         !ConstDC->hasLazyExternalLexicalLookups() &&
3776
116k
         "must call buildLookups first");
3777
3778
  // FIXME: We need to build the lookups table, which is logically const.
3779
0
  auto *DC = const_cast<DeclContext*>(ConstDC);
3780
116k
  assert(DC == DC->getPrimaryContext() && "only primary DC has lookup table");
3781
3782
  // Create the on-disk hash table representation.
3783
0
  MultiOnDiskHashTableGenerator<reader::ASTDeclContextNameLookupTrait,
3784
116k
                                ASTDeclContextNameLookupTrait> Generator;
3785
116k
  ASTDeclContextNameLookupTrait Trait(*this);
3786
3787
  // The first step is to collect the declaration names which we need to
3788
  // serialize into the name lookup table, and to collect them in a stable
3789
  // order.
3790
116k
  SmallVector<DeclarationName, 16> Names;
3791
3792
  // We also build up small sets of the constructor and conversion function
3793
  // names which are visible.
3794
116k
  llvm::SmallPtrSet<DeclarationName, 8> ConstructorNameSet, ConversionNameSet;
3795
3796
1.07M
  for (auto &Lookup : *DC->buildLookup()) {
3797
1.07M
    auto &Name = Lookup.first;
3798
1.07M
    auto &Result = Lookup.second;
3799
3800
    // If there are no local declarations in our lookup result, we
3801
    // don't need to write an entry for the name at all. If we can't
3802
    // write out a lookup set without performing more deserialization,
3803
    // just skip this entry.
3804
1.07M
    if (isLookupResultExternal(Result, DC) &&
3805
1.07M
        
isLookupResultEntirelyExternal(Result, DC)41
)
3806
20
      continue;
3807
3808
    // We also skip empty results. If any of the results could be external and
3809
    // the currently available results are empty, then all of the results are
3810
    // external and we skip it above. So the only way we get here with an empty
3811
    // results is when no results could have been external *and* we have
3812
    // external results.
3813
    //
3814
    // FIXME: While we might want to start emitting on-disk entries for negative
3815
    // lookups into a decl context as an optimization, today we *have* to skip
3816
    // them because there are names with empty lookup results in decl contexts
3817
    // which we can't emit in any stable ordering: we lookup constructors and
3818
    // conversion functions in the enclosing namespace scope creating empty
3819
    // results for them. This in almost certainly a bug in Clang's name lookup,
3820
    // but that is likely to be hard or impossible to fix and so we tolerate it
3821
    // here by omitting lookups with empty results.
3822
1.07M
    if (Lookup.second.getLookupResult().empty())
3823
51.0k
      continue;
3824
3825
1.01M
    switch (Lookup.first.getNameKind()) {
3826
1.00M
    default:
3827
1.00M
      Names.push_back(Lookup.first);
3828
1.00M
      break;
3829
3830
12.6k
    case DeclarationName::CXXConstructorName:
3831
12.6k
      assert(isa<CXXRecordDecl>(DC) &&
3832
12.6k
             "Cannot have a constructor name outside of a class!");
3833
0
      ConstructorNameSet.insert(Name);
3834
12.6k
      break;
3835
3836
1.60k
    case DeclarationName::CXXConversionFunctionName:
3837
1.60k
      assert(isa<CXXRecordDecl>(DC) &&
3838
1.60k
             "Cannot have a conversion function name outside of a class!");
3839
0
      ConversionNameSet.insert(Name);
3840
1.60k
      break;
3841
1.01M
    }
3842
1.01M
  }
3843
3844
  // Sort the names into a stable order.
3845
116k
  llvm::sort(Names);
3846
3847
116k
  if (auto *D = dyn_cast<CXXRecordDecl>(DC)) {
3848
    // We need to establish an ordering of constructor and conversion function
3849
    // names, and they don't have an intrinsic ordering.
3850
3851
    // First we try the easy case by forming the current context's constructor
3852
    // name and adding that name first. This is a very useful optimization to
3853
    // avoid walking the lexical declarations in many cases, and it also
3854
    // handles the only case where a constructor name can come from some other
3855
    // lexical context -- when that name is an implicit constructor merged from
3856
    // another declaration in the redecl chain. Any non-implicit constructor or
3857
    // conversion function which doesn't occur in all the lexical contexts
3858
    // would be an ODR violation.
3859
72.9k
    auto ImplicitCtorName = Context->DeclarationNames.getCXXConstructorName(
3860
72.9k
        Context->getCanonicalType(Context->getRecordType(D)));
3861
72.9k
    if (ConstructorNameSet.erase(ImplicitCtorName))
3862
12.6k
      Names.push_back(ImplicitCtorName);
3863
3864
    // If we still have constructors or conversion functions, we walk all the
3865
    // names in the decl and add the constructors and conversion functions
3866
    // which are visible in the order they lexically occur within the context.
3867
72.9k
    if (!ConstructorNameSet.empty() || 
!ConversionNameSet.empty()72.9k
)
3868
1.61k
      for (Decl *ChildD : cast<CXXRecordDecl>(DC)->decls())
3869
19.6k
        if (auto *ChildND = dyn_cast<NamedDecl>(ChildD)) {
3870
17.9k
          auto Name = ChildND->getDeclName();
3871
17.9k
          switch (Name.getNameKind()) {
3872
10.6k
          default:
3873
10.6k
            continue;
3874
3875
10.6k
          case DeclarationName::CXXConstructorName:
3876
5.78k
            if (ConstructorNameSet.erase(Name))
3877
65
              Names.push_back(Name);
3878
5.78k
            break;
3879
3880
1.60k
          case DeclarationName::CXXConversionFunctionName:
3881
1.60k
            if (ConversionNameSet.erase(Name))
3882
1.60k
              Names.push_back(Name);
3883
1.60k
            break;
3884
17.9k
          }
3885
3886
7.38k
          if (ConstructorNameSet.empty() && 
ConversionNameSet.empty()7.37k
)
3887
1.61k
            break;
3888
7.38k
        }
3889
3890
72.9k
    assert(ConstructorNameSet.empty() && "Failed to find all of the visible "
3891
72.9k
                                         "constructors by walking all the "
3892
72.9k
                                         "lexical members of the context.");
3893
0
    assert(ConversionNameSet.empty() && "Failed to find all of the visible "
3894
72.9k
                                        "conversion functions by walking all "
3895
72.9k
                                        "the lexical members of the context.");
3896
72.9k
  }
3897
3898
  // Next we need to do a lookup with each name into this decl context to fully
3899
  // populate any results from external sources. We don't actually use the
3900
  // results of these lookups because we only want to use the results after all
3901
  // results have been loaded and the pointers into them will be stable.
3902
116k
  for (auto &Name : Names)
3903
1.01M
    DC->lookup(Name);
3904
3905
  // Now we need to insert the results for each name into the hash table. For
3906
  // constructor names and conversion function names, we actually need to merge
3907
  // all of the results for them into one list of results each and insert
3908
  // those.
3909
116k
  SmallVector<NamedDecl *, 8> ConstructorDecls;
3910
116k
  SmallVector<NamedDecl *, 8> ConversionDecls;
3911
3912
  // Now loop over the names, either inserting them or appending for the two
3913
  // special cases.
3914
1.01M
  for (auto &Name : Names) {
3915
1.01M
    DeclContext::lookup_result Result = DC->noload_lookup(Name);
3916
3917
1.01M
    switch (Name.getNameKind()) {
3918
1.00M
    default:
3919
1.00M
      Generator.insert(Name, Trait.getData(Result), Trait);
3920
1.00M
      break;
3921
3922
12.6k
    case DeclarationName::CXXConstructorName:
3923
12.6k
      ConstructorDecls.append(Result.begin(), Result.end());
3924
12.6k
      break;
3925
3926
1.60k
    case DeclarationName::CXXConversionFunctionName:
3927
1.60k
      ConversionDecls.append(Result.begin(), Result.end());
3928
1.60k
      break;
3929
1.01M
    }
3930
1.01M
  }
3931
3932
  // Handle our two special cases if we ended up having any. We arbitrarily use
3933
  // the first declaration's name here because the name itself isn't part of
3934
  // the key, only the kind of name is used.
3935
116k
  if (!ConstructorDecls.empty())
3936
12.6k
    Generator.insert(ConstructorDecls.front()->getDeclName(),
3937
12.6k
                     Trait.getData(ConstructorDecls), Trait);
3938
116k
  if (!ConversionDecls.empty())
3939
1.55k
    Generator.insert(ConversionDecls.front()->getDeclName(),
3940
1.55k
                     Trait.getData(ConversionDecls), Trait);
3941
3942
  // Create the on-disk hash table. Also emit the existing imported and
3943
  // merged table if there is one.
3944
116k
  auto *Lookups = Chain ? 
Chain->getLoadedLookupTables(DC)106k
:
nullptr10.0k
;
3945
116k
  Generator.emit(LookupTable, Trait, Lookups ? 
&Lookups->Table744
:
nullptr116k
);
3946
116k
}
3947
3948
/// Write the block containing all of the declaration IDs
3949
/// visible from the given DeclContext.
3950
///
3951
/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
3952
/// bitstream, or 0 if no block was written.
3953
uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
3954
789k
                                                 DeclContext *DC) {
3955
  // If we imported a key declaration of this namespace, write the visible
3956
  // lookup results as an update record for it rather than including them
3957
  // on this declaration. We will only look at key declarations on reload.
3958
789k
  if (isa<NamespaceDecl>(DC) && 
Chain10.8k
&&
3959
789k
      
Chain->getKeyDeclaration(cast<Decl>(DC))->isFromASTFile()10.6k
) {
3960
    // Only do this once, for the first local declaration of the namespace.
3961
9.03k
    for (auto *Prev = cast<NamespaceDecl>(DC)->getPreviousDecl(); Prev;
3962
8.92k
         
Prev = Prev->getPreviousDecl()116
)
3963
8.93k
      if (!Prev->isFromASTFile())
3964
8.82k
        return 0;
3965
3966
    // Note that we need to emit an update record for the primary context.
3967
98
    UpdatedDeclContexts.insert(DC->getPrimaryContext());
3968
3969
    // Make sure all visible decls are written. They will be recorded later. We
3970
    // do this using a side data structure so we can sort the names into
3971
    // a deterministic order.
3972
98
    StoredDeclsMap *Map = DC->getPrimaryContext()->buildLookup();
3973
98
    SmallVector<std::pair<DeclarationName, DeclContext::lookup_result>, 16>
3974
98
        LookupResults;
3975
98
    if (Map) {
3976
96
      LookupResults.reserve(Map->size());
3977
96
      for (auto &Entry : *Map)
3978
45.8k
        LookupResults.push_back(
3979
45.8k
            std::make_pair(Entry.first, Entry.second.getLookupResult()));
3980
96
    }
3981
3982
98
    llvm::sort(LookupResults, llvm::less_first());
3983
45.8k
    for (auto &NameAndResult : LookupResults) {
3984
45.8k
      DeclarationName Name = NameAndResult.first;
3985
45.8k
      DeclContext::lookup_result Result = NameAndResult.second;
3986
45.8k
      if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
3987
45.8k
          
Name.getNameKind() == DeclarationName::CXXConversionFunctionName45.6k
) {
3988
        // We have to work around a name lookup bug here where negative lookup
3989
        // results for these names get cached in namespace lookup tables (these
3990
        // names should never be looked up in a namespace).
3991
220
        assert(Result.empty() && "Cannot have a constructor or conversion "
3992
220
                                 "function name in a namespace!");
3993
0
        continue;
3994
220
      }
3995
3996
45.6k
      for (NamedDecl *ND : Result)
3997
77.9k
        if (!ND->isFromASTFile())
3998
77.7k
          GetDeclRef(ND);
3999
45.6k
    }
4000
4001
98
    return 0;
4002
8.92k
  }
4003
4004
780k
  if (DC->getPrimaryContext() != DC)
4005
14.4k
    return 0;
4006
4007
  // Skip contexts which don't support name lookup.
4008
766k
  if (!DC->isLookupContext())
4009
546k
    return 0;
4010
4011
  // If not in C++, we perform name lookup for the translation unit via the
4012
  // IdentifierInfo chains, don't bother to build a visible-declarations table.
4013
219k
  if (DC->isTranslationUnit() && 
!Context.getLangOpts().CPlusPlus0
)
4014
0
    return 0;
4015
4016
  // Serialize the contents of the mapping used for lookup. Note that,
4017
  // although we have two very different code paths, the serialized
4018
  // representation is the same for both cases: a declaration name,
4019
  // followed by a size, followed by references to the visible
4020
  // declarations that have that name.
4021
219k
  uint64_t Offset = Stream.GetCurrentBitNo();
4022
219k
  StoredDeclsMap *Map = DC->buildLookup();
4023
219k
  if (!Map || 
Map->empty()112k
)
4024
107k
    return 0;
4025
4026
  // Create the on-disk hash table in a buffer.
4027
112k
  SmallString<4096> LookupTable;
4028
112k
  GenerateNameLookupTable(DC, LookupTable);
4029
4030
  // Write the lookup table
4031
112k
  RecordData::value_type Record[] = {DECL_CONTEXT_VISIBLE};
4032
112k
  Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
4033
112k
                            LookupTable);
4034
112k
  ++NumVisibleDeclContexts;
4035
112k
  return Offset;
4036
219k
}
4037
4038
/// Write an UPDATE_VISIBLE block for the given context.
4039
///
4040
/// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
4041
/// DeclContext in a dependent AST file. As such, they only exist for the TU
4042
/// (in C++), for namespaces, and for classes with forward-declared unscoped
4043
/// enumeration members (in C++11).
4044
9.59k
void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
4045
9.59k
  StoredDeclsMap *Map = DC->getLookupPtr();
4046
9.59k
  if (!Map || 
Map->empty()4.19k
)
4047
5.40k
    return;
4048
4049
  // Create the on-disk hash table in a buffer.
4050
4.19k
  SmallString<4096> LookupTable;
4051
4.19k
  GenerateNameLookupTable(DC, LookupTable);
4052
4053
  // If we're updating a namespace, select a key declaration as the key for the
4054
  // update record; those are the only ones that will be checked on reload.
4055
4.19k
  if (isa<NamespaceDecl>(DC))
4056
106
    DC = cast<DeclContext>(Chain->getKeyDeclaration(cast<Decl>(DC)));
4057
4058
  // Write the lookup table
4059
4.19k
  RecordData::value_type Record[] = {UPDATE_VISIBLE, getDeclID(cast<Decl>(DC))};
4060
4.19k
  Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable);
4061
4.19k
}
4062
4063
/// Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
4064
5.38k
void ASTWriter::WriteFPPragmaOptions(const FPOptionsOverride &Opts) {
4065
5.38k
  RecordData::value_type Record[] = {Opts.getAsOpaqueInt()};
4066
5.38k
  Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
4067
5.38k
}
4068
4069
/// Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
4070
5.38k
void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
4071
5.38k
  if (!SemaRef.Context.getLangOpts().OpenCL)
4072
5.36k
    return;
4073
4074
14
  const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
4075
14
  RecordData Record;
4076
593
  for (const auto &I:Opts.OptMap) {
4077
593
    AddString(I.getKey(), Record);
4078
593
    auto V = I.getValue();
4079
593
    Record.push_back(V.Supported ? 
1389
:
0204
);
4080
593
    Record.push_back(V.Enabled ? 
13
:
0590
);
4081
593
    Record.push_back(V.WithPragma ? 
1439
:
0154
);
4082
593
    Record.push_back(V.Avail);
4083
593
    Record.push_back(V.Core);
4084
593
    Record.push_back(V.Opt);
4085
593
  }
4086
14
  Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
4087
14
}
4088
5.38k
void ASTWriter::WriteCUDAPragmas(Sema &SemaRef) {
4089
5.38k
  if (SemaRef.ForceCUDAHostDeviceDepth > 0) {
4090
1
    RecordData::value_type Record[] = {SemaRef.ForceCUDAHostDeviceDepth};
4091
1
    Stream.EmitRecord(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH, Record);
4092
1
  }
4093
5.38k
}
4094
4095
5.38k
void ASTWriter::WriteObjCCategories() {
4096
5.38k
  SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
4097
5.38k
  RecordData Categories;
4098
4099
5.93k
  for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; 
++I551
) {
4100
551
    unsigned Size = 0;
4101
551
    unsigned StartIndex = Categories.size();
4102
4103
551
    ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
4104
4105
    // Allocate space for the size.
4106
551
    Categories.push_back(0);
4107
4108
    // Add the categories.
4109
551
    for (ObjCInterfaceDecl::known_categories_iterator
4110
551
           Cat = Class->known_categories_begin(),
4111
551
           CatEnd = Class->known_categories_end();
4112
2.27k
         Cat != CatEnd; 
++Cat, ++Size1.72k
) {
4113
1.72k
      assert(getDeclID(*Cat) != 0 && "Bogus category");
4114
0
      AddDeclRef(*Cat, Categories);
4115
1.72k
    }
4116
4117
    // Update the size.
4118
551
    Categories[StartIndex] = Size;
4119
4120
    // Record this interface -> category map.
4121
551
    ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
4122
551
    CategoriesMap.push_back(CatInfo);
4123
551
  }
4124
4125
  // Sort the categories map by the definition ID, since the reader will be
4126
  // performing binary searches on this information.
4127
5.38k
  llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
4128
4129
  // Emit the categories map.
4130
5.38k
  using namespace llvm;
4131
4132
5.38k
  auto Abbrev = std::make_shared<BitCodeAbbrev>();
4133
5.38k
  Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
4134
5.38k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
4135
5.38k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4136
5.38k
  unsigned AbbrevID = Stream.EmitAbbrev(std::move(Abbrev));
4137
4138
5.38k
  RecordData::value_type Record[] = {OBJC_CATEGORIES_MAP, CategoriesMap.size()};
4139
5.38k
  Stream.EmitRecordWithBlob(AbbrevID, Record,
4140
5.38k
                            reinterpret_cast<char *>(CategoriesMap.data()),
4141
5.38k
                            CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
4142
4143
  // Emit the category lists.
4144
5.38k
  Stream.EmitRecord(OBJC_CATEGORIES, Categories);
4145
5.38k
}
4146
4147
5.38k
void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) {
4148
5.38k
  Sema::LateParsedTemplateMapT &LPTMap = SemaRef.LateParsedTemplateMap;
4149
4150
5.38k
  if (LPTMap.empty())
4151
5.37k
    return;
4152
4153
6
  RecordData Record;
4154
37
  for (auto &LPTMapEntry : LPTMap) {
4155
37
    const FunctionDecl *FD = LPTMapEntry.first;
4156
37
    LateParsedTemplate &LPT = *LPTMapEntry.second;
4157
37
    AddDeclRef(FD, Record);
4158
37
    AddDeclRef(LPT.D, Record);
4159
37
    Record.push_back(LPT.Toks.size());
4160
4161
365
    for (const auto &Tok : LPT.Toks) {
4162
365
      AddToken(Tok, Record);
4163
365
    }
4164
37
  }
4165
6
  Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record);
4166
6
}
4167
4168
/// Write the state of 'pragma clang optimize' at the end of the module.
4169
3.42k
void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) {
4170
3.42k
  RecordData Record;
4171
3.42k
  SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation();
4172
3.42k
  AddSourceLocation(PragmaLoc, Record);
4173
3.42k
  Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record);
4174
3.42k
}
4175
4176
/// Write the state of 'pragma ms_struct' at the end of the module.
4177
3.42k
void ASTWriter::WriteMSStructPragmaOptions(Sema &SemaRef) {
4178
3.42k
  RecordData Record;
4179
3.42k
  Record.push_back(SemaRef.MSStructPragmaOn ? 
PMSST_ON1
:
PMSST_OFF3.42k
);
4180
3.42k
  Stream.EmitRecord(MSSTRUCT_PRAGMA_OPTIONS, Record);
4181
3.42k
}
4182
4183
/// Write the state of 'pragma pointers_to_members' at the end of the
4184
//module.
4185
3.42k
void ASTWriter::WriteMSPointersToMembersPragmaOptions(Sema &SemaRef) {
4186
3.42k
  RecordData Record;
4187
3.42k
  Record.push_back(SemaRef.MSPointerToMemberRepresentationMethod);
4188
3.42k
  AddSourceLocation(SemaRef.ImplicitMSInheritanceAttrLoc, Record);
4189
3.42k
  Stream.EmitRecord(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS, Record);
4190
3.42k
}
4191
4192
/// Write the state of 'pragma align/pack' at the end of the module.
4193
5.38k
void ASTWriter::WritePackPragmaOptions(Sema &SemaRef) {
4194
  // Don't serialize pragma align/pack state for modules, since it should only
4195
  // take effect on a per-submodule basis.
4196
5.38k
  if (WritingModule)
4197
1.95k
    return;
4198
4199
3.42k
  RecordData Record;
4200
3.42k
  AddAlignPackInfo(SemaRef.AlignPackStack.CurrentValue, Record);
4201
3.42k
  AddSourceLocation(SemaRef.AlignPackStack.CurrentPragmaLocation, Record);
4202
3.42k
  Record.push_back(SemaRef.AlignPackStack.Stack.size());
4203
3.42k
  for (const auto &StackEntry : SemaRef.AlignPackStack.Stack) {
4204
14
    AddAlignPackInfo(StackEntry.Value, Record);
4205
14
    AddSourceLocation(StackEntry.PragmaLocation, Record);
4206
14
    AddSourceLocation(StackEntry.PragmaPushLocation, Record);
4207
14
    AddString(StackEntry.StackSlotLabel, Record);
4208
14
  }
4209
3.42k
  Stream.EmitRecord(ALIGN_PACK_PRAGMA_OPTIONS, Record);
4210
3.42k
}
4211
4212
/// Write the state of 'pragma float_control' at the end of the module.
4213
5.38k
void ASTWriter::WriteFloatControlPragmaOptions(Sema &SemaRef) {
4214
  // Don't serialize pragma float_control state for modules,
4215
  // since it should only take effect on a per-submodule basis.
4216
5.38k
  if (WritingModule)
4217
1.95k
    return;
4218
4219
3.42k
  RecordData Record;
4220
3.42k
  Record.push_back(SemaRef.FpPragmaStack.CurrentValue.getAsOpaqueInt());
4221
3.42k
  AddSourceLocation(SemaRef.FpPragmaStack.CurrentPragmaLocation, Record);
4222
3.42k
  Record.push_back(SemaRef.FpPragmaStack.Stack.size());
4223
3.42k
  for (const auto &StackEntry : SemaRef.FpPragmaStack.Stack) {
4224
2
    Record.push_back(StackEntry.Value.getAsOpaqueInt());
4225
2
    AddSourceLocation(StackEntry.PragmaLocation, Record);
4226
2
    AddSourceLocation(StackEntry.PragmaPushLocation, Record);
4227
2
    AddString(StackEntry.StackSlotLabel, Record);
4228
2
  }
4229
3.42k
  Stream.EmitRecord(FLOAT_CONTROL_PRAGMA_OPTIONS, Record);
4230
3.42k
}
4231
4232
void ASTWriter::WriteModuleFileExtension(Sema &SemaRef,
4233
12
                                         ModuleFileExtensionWriter &Writer) {
4234
  // Enter the extension block.
4235
12
  Stream.EnterSubblock(EXTENSION_BLOCK_ID, 4);
4236
4237
  // Emit the metadata record abbreviation.
4238
12
  auto Abv = std::make_shared<llvm::BitCodeAbbrev>();
4239
12
  Abv->Add(llvm::BitCodeAbbrevOp(EXTENSION_METADATA));
4240
12
  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4241
12
  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4242
12
  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4243
12
  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4244
12
  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4245
12
  unsigned Abbrev = Stream.EmitAbbrev(std::move(Abv));
4246
4247
  // Emit the metadata record.
4248
12
  RecordData Record;
4249
12
  auto Metadata = Writer.getExtension()->getExtensionMetadata();
4250
12
  Record.push_back(EXTENSION_METADATA);
4251
12
  Record.push_back(Metadata.MajorVersion);
4252
12
  Record.push_back(Metadata.MinorVersion);
4253
12
  Record.push_back(Metadata.BlockName.size());
4254
12
  Record.push_back(Metadata.UserInfo.size());
4255
12
  SmallString<64> Buffer;
4256
12
  Buffer += Metadata.BlockName;
4257
12
  Buffer += Metadata.UserInfo;
4258
12
  Stream.EmitRecordWithBlob(Abbrev, Record, Buffer);
4259
4260
  // Emit the contents of the extension block.
4261
12
  Writer.writeExtensionContents(SemaRef, Stream);
4262
4263
  // Exit the extension block.
4264
12
  Stream.ExitBlock();
4265
12
}
4266
4267
//===----------------------------------------------------------------------===//
4268
// General Serialization Routines
4269
//===----------------------------------------------------------------------===//
4270
4271
1.08M
void ASTRecordWriter::AddAttr(const Attr *A) {
4272
1.08M
  auto &Record = *this;
4273
1.08M
  if (!A)
4274
11
    return Record.push_back(0);
4275
1.08M
  Record.push_back(A->getKind() + 1); // FIXME: stable encoding, target attrs
4276
4277
1.08M
  Record.AddIdentifierRef(A->getAttrName());
4278
1.08M
  Record.AddIdentifierRef(A->getScopeName());
4279
1.08M
  Record.AddSourceRange(A->getRange());
4280
1.08M
  Record.AddSourceLocation(A->getScopeLoc());
4281
1.08M
  Record.push_back(A->getParsedKind());
4282
1.08M
  Record.push_back(A->getSyntax());
4283
1.08M
  Record.push_back(A->getAttributeSpellingListIndexRaw());
4284
4285
1.08M
#include "clang/Serialization/AttrPCHWrite.inc"
4286
1.08M
}
4287
4288
/// Emit the list of attributes to the specified record.
4289
531k
void ASTRecordWriter::AddAttributes(ArrayRef<const Attr *> Attrs) {
4290
531k
  push_back(Attrs.size());
4291
531k
  for (const auto *A : Attrs)
4292
987k
    AddAttr(A);
4293
531k
}
4294
4295
3.42M
void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) {
4296
3.42M
  AddSourceLocation(Tok.getLocation(), Record);
4297
3.42M
  Record.push_back(Tok.getLength());
4298
4299
  // FIXME: When reading literal tokens, reconstruct the literal pointer
4300
  // if it is needed.
4301
3.42M
  AddIdentifierRef(Tok.getIdentifierInfo(), Record);
4302
  // FIXME: Should translate token kind to a stable encoding.
4303
3.42M
  Record.push_back(Tok.getKind());
4304
  // FIXME: Should translate token flags to a stable encoding.
4305
3.42M
  Record.push_back(Tok.getFlags());
4306
3.42M
}
4307
4308
700k
void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
4309
700k
  Record.push_back(Str.size());
4310
700k
  Record.insert(Record.end(), Str.begin(), Str.end());
4311
700k
}
4312
4313
85.2k
bool ASTWriter::PreparePathForOutput(SmallVectorImpl<char> &Path) {
4314
85.2k
  assert(Context && "should have context when outputting path");
4315
4316
0
  bool Changed =
4317
85.2k
      cleanPathForOutput(Context->getSourceManager().getFileManager(), Path);
4318
4319
  // Remove a prefix to make the path relative, if relevant.
4320
85.2k
  const char *PathBegin = Path.data();
4321
85.2k
  const char *PathPtr =
4322
85.2k
      adjustFilenameForRelocatableAST(PathBegin, BaseDirectory);
4323
85.2k
  if (PathPtr != PathBegin) {
4324
58.1k
    Path.erase(Path.begin(), Path.begin() + (PathPtr - PathBegin));
4325
58.1k
    Changed = true;
4326
58.1k
  }
4327
4328
85.2k
  return Changed;
4329
85.2k
}
4330
4331
18.9k
void ASTWriter::AddPath(StringRef Path, RecordDataImpl &Record) {
4332
18.9k
  SmallString<128> FilePath(Path);
4333
18.9k
  PreparePathForOutput(FilePath);
4334
18.9k
  AddString(FilePath, Record);
4335
18.9k
}
4336
4337
void ASTWriter::EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record,
4338
36.7k
                                   StringRef Path) {
4339
36.7k
  SmallString<128> FilePath(Path);
4340
36.7k
  PreparePathForOutput(FilePath);
4341
36.7k
  Stream.EmitRecordWithBlob(Abbrev, Record, FilePath);
4342
36.7k
}
4343
4344
void ASTWriter::AddVersionTuple(const VersionTuple &Version,
4345
754k
                                RecordDataImpl &Record) {
4346
754k
  Record.push_back(Version.getMajor());
4347
754k
  if (Optional<unsigned> Minor = Version.getMinor())
4348
194k
    Record.push_back(*Minor + 1);
4349
559k
  else
4350
559k
    Record.push_back(0);
4351
754k
  if (Optional<unsigned> Subminor = Version.getSubminor())
4352
2.07k
    Record.push_back(*Subminor + 1);
4353
752k
  else
4354
752k
    Record.push_back(0);
4355
754k
}
4356
4357
/// Note that the identifier II occurs at the given offset
4358
/// within the identifier table.
4359
11.6M
void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
4360
11.6M
  IdentID ID = IdentifierIDs[II];
4361
  // Only store offsets new to this AST file. Other identifier names are looked
4362
  // up earlier in the chain and thus don't need an offset.
4363
11.6M
  if (ID >= FirstIdentID)
4364
11.5M
    IdentifierOffsets[ID - FirstIdentID] = Offset;
4365
11.6M
}
4366
4367
/// Note that the selector Sel occurs at the given offset
4368
/// within the method pool/selector table.
4369
40.9k
void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
4370
40.9k
  unsigned ID = SelectorIDs[Sel];
4371
40.9k
  assert(ID && "Unknown selector");
4372
  // Don't record offsets for selectors that are also available in a different
4373
  // file.
4374
40.9k
  if (ID < FirstSelectorID)
4375
1.13k
    return;
4376
39.8k
  SelectorOffsets[ID - FirstSelectorID] = Offset;
4377
39.8k
}
4378
4379
ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream,
4380
                     SmallVectorImpl<char> &Buffer,
4381
                     InMemoryModuleCache &ModuleCache,
4382
                     ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
4383
                     bool IncludeTimestamps)
4384
    : Stream(Stream), Buffer(Buffer), ModuleCache(ModuleCache),
4385
5.44k
      IncludeTimestamps(IncludeTimestamps) {
4386
5.44k
  for (const auto &Ext : Extensions) {
4387
12
    if (auto Writer = Ext->createExtensionWriter(*this))
4388
12
      ModuleFileExtensionWriters.push_back(std::move(Writer));
4389
12
  }
4390
5.44k
}
4391
4392
5.44k
ASTWriter::~ASTWriter() = default;
4393
4394
1.13M
const LangOptions &ASTWriter::getLangOpts() const {
4395
1.13M
  assert(WritingAST && "can't determine lang opts when not writing AST");
4396
0
  return Context->getLangOpts();
4397
1.13M
}
4398
4399
62.9k
time_t ASTWriter::getTimestampForOutput(const FileEntry *E) const {
4400
62.9k
  return IncludeTimestamps ? 
E->getModificationTime()61.8k
:
01.12k
;
4401
62.9k
}
4402
4403
ASTFileSignature ASTWriter::WriteAST(Sema &SemaRef,
4404
                                     const std::string &OutputFile,
4405
                                     Module *WritingModule, StringRef isysroot,
4406
                                     bool hasErrors,
4407
5.38k
                                     bool ShouldCacheASTInMemory) {
4408
5.38k
  WritingAST = true;
4409
4410
5.38k
  ASTHasCompilerErrors = hasErrors;
4411
4412
  // Emit the file header.
4413
5.38k
  Stream.Emit((unsigned)'C', 8);
4414
5.38k
  Stream.Emit((unsigned)'P', 8);
4415
5.38k
  Stream.Emit((unsigned)'C', 8);
4416
5.38k
  Stream.Emit((unsigned)'H', 8);
4417
4418
5.38k
  WriteBlockInfoBlock();
4419
4420
5.38k
  Context = &SemaRef.Context;
4421
5.38k
  PP = &SemaRef.PP;
4422
5.38k
  this->WritingModule = WritingModule;
4423
5.38k
  ASTFileSignature Signature =
4424
5.38k
      WriteASTCore(SemaRef, isysroot, OutputFile, WritingModule);
4425
5.38k
  Context = nullptr;
4426
5.38k
  PP = nullptr;
4427
5.38k
  this->WritingModule = nullptr;
4428
5.38k
  this->BaseDirectory.clear();
4429
4430
5.38k
  WritingAST = false;
4431
5.38k
  if (ShouldCacheASTInMemory) {
4432
    // Construct MemoryBuffer and update buffer manager.
4433
1.68k
    ModuleCache.addBuiltPCM(OutputFile,
4434
1.68k
                            llvm::MemoryBuffer::getMemBufferCopy(
4435
1.68k
                                StringRef(Buffer.begin(), Buffer.size())));
4436
1.68k
  }
4437
5.38k
  return Signature;
4438
5.38k
}
4439
4440
template<typename Vector>
4441
static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
4442
17.6k
                               ASTWriter::RecordData &Record) {
4443
17.6k
  for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
4444
19.2k
       I != E; 
++I1.66k
) {
4445
1.66k
    Writer.AddDeclRef(*I, Record);
4446
1.66k
  }
4447
17.6k
}
ASTWriter.cpp:void AddLazyVectorDecls<clang::LazyVector<clang::VarDecl*, clang::ExternalSemaSource, &(clang::ExternalSemaSource::ReadTentativeDefinitions(llvm::SmallVectorImpl<clang::VarDecl*>&)), 2u, 2u> >(clang::ASTWriter&, clang::LazyVector<clang::VarDecl*, clang::ExternalSemaSource, &(clang::ExternalSemaSource::ReadTentativeDefinitions(llvm::SmallVectorImpl<clang::VarDecl*>&)), 2u, 2u>&, llvm::SmallVector<unsigned long long, 64u>&)
Line
Count
Source
4442
5.38k
                               ASTWriter::RecordData &Record) {
4443
5.38k
  for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
4444
6.48k
       I != E; 
++I1.10k
) {
4445
1.10k
    Writer.AddDeclRef(*I, Record);
4446
1.10k
  }
4447
5.38k
}
ASTWriter.cpp:void AddLazyVectorDecls<clang::LazyVector<clang::DeclaratorDecl const*, clang::ExternalSemaSource, &(clang::ExternalSemaSource::ReadUnusedFileScopedDecls(llvm::SmallVectorImpl<clang::DeclaratorDecl const*>&)), 2u, 2u> >(clang::ASTWriter&, clang::LazyVector<clang::DeclaratorDecl const*, clang::ExternalSemaSource, &(clang::ExternalSemaSource::ReadUnusedFileScopedDecls(llvm::SmallVectorImpl<clang::DeclaratorDecl const*>&)), 2u, 2u>&, llvm::SmallVector<unsigned long long, 64u>&)
Line
Count
Source
4442
3.42k
                               ASTWriter::RecordData &Record) {
4443
3.42k
  for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
4444
3.62k
       I != E; 
++I198
) {
4445
198
    Writer.AddDeclRef(*I, Record);
4446
198
  }
4447
3.42k
}
ASTWriter.cpp:void AddLazyVectorDecls<clang::LazyVector<clang::CXXConstructorDecl*, clang::ExternalSemaSource, &(clang::ExternalSemaSource::ReadDelegatingConstructors(llvm::SmallVectorImpl<clang::CXXConstructorDecl*>&)), 2u, 2u> >(clang::ASTWriter&, clang::LazyVector<clang::CXXConstructorDecl*, clang::ExternalSemaSource, &(clang::ExternalSemaSource::ReadDelegatingConstructors(llvm::SmallVectorImpl<clang::CXXConstructorDecl*>&)), 2u, 2u>&, llvm::SmallVector<unsigned long long, 64u>&)
Line
Count
Source
4442
3.42k
                               ASTWriter::RecordData &Record) {
4443
3.42k
  for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
4444
3.43k
       I != E; 
++I6
) {
4445
6
    Writer.AddDeclRef(*I, Record);
4446
6
  }
4447
3.42k
}
ASTWriter.cpp:void AddLazyVectorDecls<clang::LazyVector<clang::TypedefNameDecl*, clang::ExternalSemaSource, &(clang::ExternalSemaSource::ReadExtVectorDecls(llvm::SmallVectorImpl<clang::TypedefNameDecl*>&)), 2u, 2u> >(clang::ASTWriter&, clang::LazyVector<clang::TypedefNameDecl*, clang::ExternalSemaSource, &(clang::ExternalSemaSource::ReadExtVectorDecls(llvm::SmallVectorImpl<clang::TypedefNameDecl*>&)), 2u, 2u>&, llvm::SmallVector<unsigned long long, 64u>&)
Line
Count
Source
4442
5.38k
                               ASTWriter::RecordData &Record) {
4443
5.38k
  for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
4444
5.73k
       I != E; 
++I354
) {
4445
354
    Writer.AddDeclRef(*I, Record);
4446
354
  }
4447
5.38k
}
4448
4449
ASTFileSignature ASTWriter::WriteASTCore(Sema &SemaRef, StringRef isysroot,
4450
                                         const std::string &OutputFile,
4451
5.38k
                                         Module *WritingModule) {
4452
5.38k
  using namespace llvm;
4453
4454
5.38k
  bool isModule = WritingModule != nullptr;
4455
4456
  // Make sure that the AST reader knows to finalize itself.
4457
5.38k
  if (Chain)
4458
2.13k
    Chain->finalizeForWriting();
4459
4460
5.38k
  ASTContext &Context = SemaRef.Context;
4461
5.38k
  Preprocessor &PP = SemaRef.PP;
4462
4463
  // Set up predefined declaration IDs.
4464
91.4k
  auto RegisterPredefDecl = [&] (Decl *D, PredefinedDeclIDs ID) {
4465
91.4k
    if (D) {
4466
45.9k
      assert(D->isCanonicalDecl() && "predefined decl is not canonical");
4467
0
      DeclIDs[D] = ID;
4468
45.9k
    }
4469
91.4k
  };
4470
5.38k
  RegisterPredefDecl(Context.getTranslationUnitDecl(),
4471
5.38k
                     PREDEF_DECL_TRANSLATION_UNIT_ID);
4472
5.38k
  RegisterPredefDecl(Context.ObjCIdDecl, PREDEF_DECL_OBJC_ID_ID);
4473
5.38k
  RegisterPredefDecl(Context.ObjCSelDecl, PREDEF_DECL_OBJC_SEL_ID);
4474
5.38k
  RegisterPredefDecl(Context.ObjCClassDecl, PREDEF_DECL_OBJC_CLASS_ID);
4475
5.38k
  RegisterPredefDecl(Context.ObjCProtocolClassDecl,
4476
5.38k
                     PREDEF_DECL_OBJC_PROTOCOL_ID);
4477
5.38k
  RegisterPredefDecl(Context.Int128Decl, PREDEF_DECL_INT_128_ID);
4478
5.38k
  RegisterPredefDecl(Context.UInt128Decl, PREDEF_DECL_UNSIGNED_INT_128_ID);
4479
5.38k
  RegisterPredefDecl(Context.ObjCInstanceTypeDecl,
4480
5.38k
                     PREDEF_DECL_OBJC_INSTANCETYPE_ID);
4481
5.38k
  RegisterPredefDecl(Context.BuiltinVaListDecl, PREDEF_DECL_BUILTIN_VA_LIST_ID);
4482
5.38k
  RegisterPredefDecl(Context.VaListTagDecl, PREDEF_DECL_VA_LIST_TAG);
4483
5.38k
  RegisterPredefDecl(Context.BuiltinMSVaListDecl,
4484
5.38k
                     PREDEF_DECL_BUILTIN_MS_VA_LIST_ID);
4485
5.38k
  RegisterPredefDecl(Context.MSGuidTagDecl,
4486
5.38k
                     PREDEF_DECL_BUILTIN_MS_GUID_ID);
4487
5.38k
  RegisterPredefDecl(Context.ExternCContext, PREDEF_DECL_EXTERN_C_CONTEXT_ID);
4488
5.38k
  RegisterPredefDecl(Context.MakeIntegerSeqDecl,
4489
5.38k
                     PREDEF_DECL_MAKE_INTEGER_SEQ_ID);
4490
5.38k
  RegisterPredefDecl(Context.CFConstantStringTypeDecl,
4491
5.38k
                     PREDEF_DECL_CF_CONSTANT_STRING_ID);
4492
5.38k
  RegisterPredefDecl(Context.CFConstantStringTagDecl,
4493
5.38k
                     PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID);
4494
5.38k
  RegisterPredefDecl(Context.TypePackElementDecl,
4495
5.38k
                     PREDEF_DECL_TYPE_PACK_ELEMENT_ID);
4496
4497
  // Build a record containing all of the tentative definitions in this file, in
4498
  // TentativeDefinitions order.  Generally, this record will be empty for
4499
  // headers.
4500
5.38k
  RecordData TentativeDefinitions;
4501
5.38k
  AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
4502
4503
  // Build a record containing all of the file scoped decls in this file.
4504
5.38k
  RecordData UnusedFileScopedDecls;
4505
5.38k
  if (!isModule)
4506
3.42k
    AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls,
4507
3.42k
                       UnusedFileScopedDecls);
4508
4509
  // Build a record containing all of the delegating constructors we still need
4510
  // to resolve.
4511
5.38k
  RecordData DelegatingCtorDecls;
4512
5.38k
  if (!isModule)
4513
3.42k
    AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
4514
4515
  // Write the set of weak, undeclared identifiers. We always write the
4516
  // entire table, since later PCH files in a PCH chain are only interested in
4517
  // the results at the end of the chain.
4518
5.38k
  RecordData WeakUndeclaredIdentifiers;
4519
5.38k
  for (auto &WeakUndeclaredIdentifier : SemaRef.WeakUndeclaredIdentifiers) {
4520
63
    IdentifierInfo *II = WeakUndeclaredIdentifier.first;
4521
63
    WeakInfo &WI = WeakUndeclaredIdentifier.second;
4522
63
    AddIdentifierRef(II, WeakUndeclaredIdentifiers);
4523
63
    AddIdentifierRef(WI.getAlias(), WeakUndeclaredIdentifiers);
4524
63
    AddSourceLocation(WI.getLocation(), WeakUndeclaredIdentifiers);
4525
63
    WeakUndeclaredIdentifiers.push_back(WI.getUsed());
4526
63
  }
4527
4528
  // Build a record containing all of the ext_vector declarations.
4529
5.38k
  RecordData ExtVectorDecls;
4530
5.38k
  AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
4531
4532
  // Build a record containing all of the VTable uses information.
4533
5.38k
  RecordData VTableUses;
4534
5.38k
  if (!SemaRef.VTableUses.empty()) {
4535
38
    for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; 
++I27
) {
4536
27
      AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
4537
27
      AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
4538
27
      VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
4539
27
    }
4540
11
  }
4541
4542
  // Build a record containing all of the UnusedLocalTypedefNameCandidates.
4543
5.38k
  RecordData UnusedLocalTypedefNameCandidates;
4544
5.38k
  for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates)
4545
3
    AddDeclRef(TD, UnusedLocalTypedefNameCandidates);
4546
4547
  // Build a record containing all of pending implicit instantiations.
4548
5.38k
  RecordData PendingInstantiations;
4549
5.38k
  for (const auto &I : SemaRef.PendingInstantiations) {
4550
3.63k
    AddDeclRef(I.first, PendingInstantiations);
4551
3.63k
    AddSourceLocation(I.second, PendingInstantiations);
4552
3.63k
  }
4553
5.38k
  assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
4554
5.38k
         "There are local ones at end of translation unit!");
4555
4556
  // Build a record containing some declaration references.
4557
0
  RecordData SemaDeclRefs;
4558
5.38k
  if (SemaRef.StdNamespace || 
SemaRef.StdBadAlloc5.24k
||
SemaRef.StdAlignValT5.24k
) {
4559
131
    AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
4560
131
    AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
4561
131
    AddDeclRef(SemaRef.getStdAlignValT(), SemaDeclRefs);
4562
131
  }
4563
4564
5.38k
  RecordData CUDASpecialDeclRefs;
4565
5.38k
  if (Context.getcudaConfigureCallDecl()) {
4566
1
    AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
4567
1
  }
4568
4569
  // Build a record containing all of the known namespaces.
4570
5.38k
  RecordData KnownNamespaces;
4571
5.38k
  for (const auto &I : SemaRef.KnownNamespaces) {
4572
868
    if (!I.second)
4573
868
      AddDeclRef(I.first, KnownNamespaces);
4574
868
  }
4575
4576
  // Build a record of all used, undefined objects that require definitions.
4577
5.38k
  RecordData UndefinedButUsed;
4578
4579
5.38k
  SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
4580
5.38k
  SemaRef.getUndefinedButUsed(Undefined);
4581
5.38k
  for (const auto &I : Undefined) {
4582
2.28k
    AddDeclRef(I.first, UndefinedButUsed);
4583
2.28k
    AddSourceLocation(I.second, UndefinedButUsed);
4584
2.28k
  }
4585
4586
  // Build a record containing all delete-expressions that we would like to
4587
  // analyze later in AST.
4588
5.38k
  RecordData DeleteExprsToAnalyze;
4589
4590
5.38k
  if (!isModule) {
4591
3.42k
    for (const auto &DeleteExprsInfo :
4592
3.42k
         SemaRef.getMismatchingDeleteExpressions()) {
4593
1
      AddDeclRef(DeleteExprsInfo.first, DeleteExprsToAnalyze);
4594
1
      DeleteExprsToAnalyze.push_back(DeleteExprsInfo.second.size());
4595
1
      for (const auto &DeleteLoc : DeleteExprsInfo.second) {
4596
1
        AddSourceLocation(DeleteLoc.first, DeleteExprsToAnalyze);
4597
1
        DeleteExprsToAnalyze.push_back(DeleteLoc.second);
4598
1
      }
4599
1
    }
4600
3.42k
  }
4601
4602
  // Write the control block
4603
5.38k
  WriteControlBlock(PP, Context, isysroot, OutputFile);
4604
4605
  // Write the remaining AST contents.
4606
5.38k
  Stream.FlushToWord();
4607
5.38k
  ASTBlockRange.first = Stream.GetCurrentBitNo();
4608
5.38k
  Stream.EnterSubblock(AST_BLOCK_ID, 5);
4609
5.38k
  ASTBlockStartOffset = Stream.GetCurrentBitNo();
4610
4611
  // This is so that older clang versions, before the introduction
4612
  // of the control block, can read and reject the newer PCH format.
4613
5.38k
  {
4614
5.38k
    RecordData Record = {VERSION_MAJOR};
4615
5.38k
    Stream.EmitRecord(METADATA_OLD_FORMAT, Record);
4616
5.38k
  }
4617
4618
  // Create a lexical update block containing all of the declarations in the
4619
  // translation unit that do not come from other AST files.
4620
5.38k
  const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
4621
5.38k
  SmallVector<uint32_t, 128> NewGlobalKindDeclPairs;
4622
406k
  for (const auto *D : TU->noload_decls()) {
4623
406k
    if (!D->isFromASTFile()) {
4624
406k
      NewGlobalKindDeclPairs.push_back(D->getKind());
4625
406k
      NewGlobalKindDeclPairs.push_back(GetDeclRef(D));
4626
406k
    }
4627
406k
  }
4628
4629
5.38k
  auto Abv = std::make_shared<BitCodeAbbrev>();
4630
5.38k
  Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
4631
5.38k
  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4632
5.38k
  unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(std::move(Abv));
4633
5.38k
  {
4634
5.38k
    RecordData::value_type Record[] = {TU_UPDATE_LEXICAL};
4635
5.38k
    Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
4636
5.38k
                              bytes(NewGlobalKindDeclPairs));
4637
5.38k
  }
4638
4639
  // And a visible updates block for the translation unit.
4640
5.38k
  Abv = std::make_shared<BitCodeAbbrev>();
4641
5.38k
  Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
4642
5.38k
  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4643
5.38k
  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4644
5.38k
  UpdateVisibleAbbrev = Stream.EmitAbbrev(std::move(Abv));
4645
5.38k
  WriteDeclContextVisibleUpdate(TU);
4646
4647
  // If we have any extern "C" names, write out a visible update for them.
4648
5.38k
  if (Context.ExternCContext)
4649
3.94k
    WriteDeclContextVisibleUpdate(Context.ExternCContext);
4650
4651
  // If the translation unit has an anonymous namespace, and we don't already
4652
  // have an update block for it, write it as an update block.
4653
  // FIXME: Why do we not do this if there's already an update block?
4654
5.38k
  if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
4655
11
    ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
4656
11
    if (Record.empty())
4657
11
      Record.push_back(DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, NS));
4658
11
  }
4659
4660
  // Add update records for all mangling numbers and static local numbers.
4661
  // These aren't really update records, but this is a convenient way of
4662
  // tagging this rare extra data onto the declarations.
4663
5.38k
  for (const auto &Number : Context.MangleNumbers)
4664
1.25k
    if (!Number.first->isFromASTFile())
4665
1.23k
      DeclUpdates[Number.first].push_back(DeclUpdate(UPD_MANGLING_NUMBER,
4666
1.23k
                                                     Number.second));
4667
5.38k
  for (const auto &Number : Context.StaticLocalNumbers)
4668
0
    if (!Number.first->isFromASTFile())
4669
0
      DeclUpdates[Number.first].push_back(DeclUpdate(UPD_STATIC_LOCAL_NUMBER,
4670
0
                                                     Number.second));
4671
4672
  // Make sure visible decls, added to DeclContexts previously loaded from
4673
  // an AST file, are registered for serialization. Likewise for template
4674
  // specializations added to imported templates.
4675
30.6k
  for (const auto *I : DeclsToEmitEvenIfUnreferenced) {
4676
30.6k
    GetDeclRef(I);
4677
30.6k
  }
4678
4679
  // Make sure all decls associated with an identifier are registered for
4680
  // serialization, if we're storing decls with identifiers.
4681
5.38k
  if (!WritingModule || 
!getLangOpts().CPlusPlus1.95k
) {
4682
4.24k
    llvm::SmallVector<const IdentifierInfo*, 256> IIs;
4683
14.9M
    for (const auto &ID : PP.getIdentifierTable()) {
4684
14.9M
      const IdentifierInfo *II = ID.second;
4685
14.9M
      if (!Chain || 
!II->isFromAST()3.95M
||
II->hasChangedSinceDeserialization()33.6k
)
4686
14.9M
        IIs.push_back(II);
4687
14.9M
    }
4688
    // Sort the identifiers to visit based on their name.
4689
4.24k
    llvm::sort(IIs, llvm::deref<std::less<>>());
4690
14.9M
    for (const IdentifierInfo *II : IIs) {
4691
14.9M
      for (IdentifierResolver::iterator D = SemaRef.IdResolver.begin(II),
4692
14.9M
                                     DEnd = SemaRef.IdResolver.end();
4693
15.3M
           D != DEnd; 
++D349k
) {
4694
349k
        GetDeclRef(*D);
4695
349k
      }
4696
14.9M
    }
4697
4.24k
  }
4698
4699
  // For method pool in the module, if it contains an entry for a selector,
4700
  // the entry should be complete, containing everything introduced by that
4701
  // module and all modules it imports. It's possible that the entry is out of
4702
  // date, so we need to pull in the new content here.
4703
4704
  // It's possible that updateOutOfDateSelector can update SelectorIDs. To be
4705
  // safe, we copy all selectors out.
4706
5.38k
  llvm::SmallVector<Selector, 256> AllSelectors;
4707
5.38k
  for (auto &SelectorAndID : SelectorIDs)
4708
1.73k
    AllSelectors.push_back(SelectorAndID.first);
4709
5.38k
  for (auto &Selector : AllSelectors)
4710
1.73k
    SemaRef.updateOutOfDateSelector(Selector);
4711
4712
  // Form the record of special types.
4713
5.38k
  RecordData SpecialTypes;
4714
5.38k
  AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
4715
5.38k
  AddTypeRef(Context.getFILEType(), SpecialTypes);
4716
5.38k
  AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
4717
5.38k
  AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
4718
5.38k
  AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
4719
5.38k
  AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
4720
5.38k
  AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
4721
5.38k
  AddTypeRef(Context.getucontext_tType(), SpecialTypes);
4722
4723
5.38k
  if (Chain) {
4724
    // Write the mapping information describing our module dependencies and how
4725
    // each of those modules were mapped into our own offset/ID space, so that
4726
    // the reader can build the appropriate mapping to its own offset/ID space.
4727
    // The map consists solely of a blob with the following format:
4728
    // *(module-kind:i8
4729
    //   module-name-len:i16 module-name:len*i8
4730
    //   source-location-offset:i32
4731
    //   identifier-id:i32
4732
    //   preprocessed-entity-id:i32
4733
    //   macro-definition-id:i32
4734
    //   submodule-id:i32
4735
    //   selector-id:i32
4736
    //   declaration-id:i32
4737
    //   c++-base-specifiers-id:i32
4738
    //   type-id:i32)
4739
    //
4740
    // module-kind is the ModuleKind enum value. If it is MK_PrebuiltModule,
4741
    // MK_ExplicitModule or MK_ImplicitModule, then the module-name is the
4742
    // module name. Otherwise, it is the module file name.
4743
2.13k
    auto Abbrev = std::make_shared<BitCodeAbbrev>();
4744
2.13k
    Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
4745
2.13k
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4746
2.13k
    unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
4747
2.13k
    SmallString<2048> Buffer;
4748
2.13k
    {
4749
2.13k
      llvm::raw_svector_ostream Out(Buffer);
4750
3.35k
      for (ModuleFile &M : Chain->ModuleMgr) {
4751
3.35k
        using namespace llvm::support;
4752
4753
3.35k
        endian::Writer LE(Out, little);
4754
3.35k
        LE.write<uint8_t>(static_cast<uint8_t>(M.Kind));
4755
3.35k
        StringRef Name = M.isModule() ? 
M.ModuleName3.28k
:
M.FileName71
;
4756
3.35k
        LE.write<uint16_t>(Name.size());
4757
3.35k
        Out.write(Name.data(), Name.size());
4758
4759
        // Note: if a base ID was uint max, it would not be possible to load
4760
        // another module after it or have more than one entity inside it.
4761
3.35k
        uint32_t None = std::numeric_limits<uint32_t>::max();
4762
4763
26.8k
        auto writeBaseIDOrNone = [&](auto BaseID, bool ShouldWrite) {
4764
26.8k
          assert(BaseID < std::numeric_limits<uint32_t>::max() && "base id too high");
4765
26.8k
          if (ShouldWrite)
4766
18.2k
            LE.write<uint32_t>(BaseID);
4767
8.58k
          else
4768
8.58k
            LE.write<uint32_t>(None);
4769
26.8k
        };
4770
4771
        // These values should be unique within a chain, since they will be read
4772
        // as keys into ContinuousRangeMaps.
4773
3.35k
        writeBaseIDOrNone(M.SLocEntryBaseOffset, M.LocalNumSLocEntries);
4774
3.35k
        writeBaseIDOrNone(M.BaseIdentifierID, M.LocalNumIdentifiers);
4775
3.35k
        writeBaseIDOrNone(M.BaseMacroID, M.LocalNumMacros);
4776
3.35k
        writeBaseIDOrNone(M.BasePreprocessedEntityID,
4777
3.35k
                          M.NumPreprocessedEntities);
4778
3.35k
        writeBaseIDOrNone(M.BaseSubmoduleID, M.LocalNumSubmodules);
4779
3.35k
        writeBaseIDOrNone(M.BaseSelectorID, M.LocalNumSelectors);
4780
3.35k
        writeBaseIDOrNone(M.BaseDeclID, M.LocalNumDecls);
4781
3.35k
        writeBaseIDOrNone(M.BaseTypeIndex, M.LocalNumTypes);
4782
3.35k
      }
4783
2.13k
    }
4784
2.13k
    RecordData::value_type Record[] = {MODULE_OFFSET_MAP};
4785
2.13k
    Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
4786
2.13k
                              Buffer.data(), Buffer.size());
4787
2.13k
  }
4788
4789
  // Build a record containing all of the DeclsToCheckForDeferredDiags.
4790
5.38k
  SmallVector<serialization::DeclID, 64> DeclsToCheckForDeferredDiags;
4791
5.38k
  for (auto *D : SemaRef.DeclsToCheckForDeferredDiags)
4792
7.30k
    DeclsToCheckForDeferredDiags.push_back(GetDeclRef(D));
4793
4794
5.38k
  RecordData DeclUpdatesOffsetsRecord;
4795
4796
  // Keep writing types, declarations, and declaration update records
4797
  // until we've emitted all of them.
4798
5.38k
  Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/5);
4799
5.38k
  DeclTypesBlockStartOffset = Stream.GetCurrentBitNo();
4800
5.38k
  WriteTypeAbbrevs();
4801
5.38k
  WriteDeclAbbrevs();
4802
5.45k
  do {
4803
5.45k
    WriteDeclUpdatesBlocks(DeclUpdatesOffsetsRecord);
4804
4.41M
    while (!DeclTypesToEmit.empty()) {
4805
4.41M
      DeclOrType DOT = DeclTypesToEmit.front();
4806
4.41M
      DeclTypesToEmit.pop();
4807
4.41M
      if (DOT.isType())
4808
1.46M
        WriteType(DOT.getType());
4809
2.94M
      else
4810
2.94M
        WriteDecl(Context, DOT.getDecl());
4811
4.41M
    }
4812
5.45k
  } while (!DeclUpdates.empty());
4813
5.38k
  Stream.ExitBlock();
4814
4815
5.38k
  DoneWritingDeclsAndTypes = true;
4816
4817
  // These things can only be done once we've written out decls and types.
4818
5.38k
  WriteTypeDeclOffsets();
4819
5.38k
  if (!DeclUpdatesOffsetsRecord.empty())
4820
240
    Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord);
4821
5.38k
  WriteFileDeclIDsMap();
4822
5.38k
  WriteSourceManagerBlock(Context.getSourceManager(), PP);
4823
5.38k
  WriteComments();
4824
5.38k
  WritePreprocessor(PP, isModule);
4825
5.38k
  WriteHeaderSearch(PP.getHeaderSearchInfo());
4826
5.38k
  WriteSelectors(SemaRef);
4827
5.38k
  WriteReferencedSelectorsPool(SemaRef);
4828
5.38k
  WriteLateParsedTemplates(SemaRef);
4829
5.38k
  WriteIdentifierTable(PP, SemaRef.IdResolver, isModule);
4830
5.38k
  WriteFPPragmaOptions(SemaRef.CurFPFeatureOverrides());
4831
5.38k
  WriteOpenCLExtensions(SemaRef);
4832
5.38k
  WriteCUDAPragmas(SemaRef);
4833
4834
  // If we're emitting a module, write out the submodule information.
4835
5.38k
  if (WritingModule)
4836
1.95k
    WriteSubmodules(WritingModule);
4837
4838
5.38k
  Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
4839
4840
  // Write the record containing external, unnamed definitions.
4841
5.38k
  if (!EagerlyDeserializedDecls.empty())
4842
3.09k
    Stream.EmitRecord(EAGERLY_DESERIALIZED_DECLS, EagerlyDeserializedDecls);
4843
4844
5.38k
  if (!ModularCodegenDecls.empty())
4845
38
    Stream.EmitRecord(MODULAR_CODEGEN_DECLS, ModularCodegenDecls);
4846
4847
  // Write the record containing tentative definitions.
4848
5.38k
  if (!TentativeDefinitions.empty())
4849
176
    Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
4850
4851
  // Write the record containing unused file scoped decls.
4852
5.38k
  if (!UnusedFileScopedDecls.empty())
4853
45
    Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
4854
4855
  // Write the record containing weak undeclared identifiers.
4856
5.38k
  if (!WeakUndeclaredIdentifiers.empty())
4857
12
    Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
4858
12
                      WeakUndeclaredIdentifiers);
4859
4860
  // Write the record containing ext_vector type names.
4861
5.38k
  if (!ExtVectorDecls.empty())
4862
24
    Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
4863
4864
  // Write the record containing VTable uses information.
4865
5.38k
  if (!VTableUses.empty())
4866
11
    Stream.EmitRecord(VTABLE_USES, VTableUses);
4867
4868
  // Write the record containing potentially unused local typedefs.
4869
5.38k
  if (!UnusedLocalTypedefNameCandidates.empty())
4870
3
    Stream.EmitRecord(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES,
4871
3
                      UnusedLocalTypedefNameCandidates);
4872
4873
  // Write the record containing pending implicit instantiations.
4874
5.38k
  if (!PendingInstantiations.empty())
4875
1.46k
    Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
4876
4877
  // Write the record containing declaration references of Sema.
4878
5.38k
  if (!SemaDeclRefs.empty())
4879
131
    Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
4880
4881
  // Write the record containing decls to be checked for deferred diags.
4882
5.38k
  if (!DeclsToCheckForDeferredDiags.empty())
4883
1.97k
    Stream.EmitRecord(DECLS_TO_CHECK_FOR_DEFERRED_DIAGS,
4884
1.97k
        DeclsToCheckForDeferredDiags);
4885
4886
  // Write the record containing CUDA-specific declaration references.
4887
5.38k
  if (!CUDASpecialDeclRefs.empty())
4888
1
    Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
4889
4890
  // Write the delegating constructors.
4891
5.38k
  if (!DelegatingCtorDecls.empty())
4892
4
    Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
4893
4894
  // Write the known namespaces.
4895
5.38k
  if (!KnownNamespaces.empty())
4896
290
    Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
4897
4898
  // Write the undefined internal functions and variables, and inline functions.
4899
5.38k
  if (!UndefinedButUsed.empty())
4900
722
    Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed);
4901
4902
5.38k
  if (!DeleteExprsToAnalyze.empty())
4903
1
    Stream.EmitRecord(DELETE_EXPRS_TO_ANALYZE, DeleteExprsToAnalyze);
4904
4905
  // Write the visible updates to DeclContexts.
4906
5.38k
  for (auto *DC : UpdatedDeclContexts)
4907
274
    WriteDeclContextVisibleUpdate(DC);
4908
4909
5.38k
  if (!WritingModule) {
4910
    // Write the submodules that were imported, if any.
4911
3.42k
    struct ModuleInfo {
4912
3.42k
      uint64_t ID;
4913
3.42k
      Module *M;
4914
3.42k
      ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) 
{}71
4915
3.42k
    };
4916
3.42k
    llvm::SmallVector<ModuleInfo, 64> Imports;
4917
3.42k
    for (const auto *I : Context.local_imports()) {
4918
71
      assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end());
4919
0
      Imports.push_back(ModuleInfo(SubmoduleIDs[I->getImportedModule()],
4920
71
                         I->getImportedModule()));
4921
71
    }
4922
4923
3.42k
    if (!Imports.empty()) {
4924
54
      auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) {
4925
21
        return A.ID < B.ID;
4926
21
      };
4927
54
      auto Eq = [](const ModuleInfo &A, const ModuleInfo &B) {
4928
17
        return A.ID == B.ID;
4929
17
      };
4930
4931
      // Sort and deduplicate module IDs.
4932
54
      llvm::sort(Imports, Cmp);
4933
54
      Imports.erase(std::unique(Imports.begin(), Imports.end(), Eq),
4934
54
                    Imports.end());
4935
4936
54
      RecordData ImportedModules;
4937
65
      for (const auto &Import : Imports) {
4938
65
        ImportedModules.push_back(Import.ID);
4939
        // FIXME: If the module has macros imported then later has declarations
4940
        // imported, this location won't be the right one as a location for the
4941
        // declaration imports.
4942
65
        AddSourceLocation(PP.getModuleImportLoc(Import.M), ImportedModules);
4943
65
      }
4944
4945
54
      Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
4946
54
    }
4947
3.42k
  }
4948
4949
5.38k
  WriteObjCCategories();
4950
5.38k
  if(!WritingModule) {
4951
3.42k
    WriteOptimizePragmaOptions(SemaRef);
4952
3.42k
    WriteMSStructPragmaOptions(SemaRef);
4953
3.42k
    WriteMSPointersToMembersPragmaOptions(SemaRef);
4954
3.42k
  }
4955
5.38k
  WritePackPragmaOptions(SemaRef);
4956
5.38k
  WriteFloatControlPragmaOptions(SemaRef);
4957
4958
  // Some simple statistics
4959
5.38k
  RecordData::value_type Record[] = {
4960
5.38k
      NumStatements, NumMacros, NumLexicalDeclContexts, NumVisibleDeclContexts};
4961
5.38k
  Stream.EmitRecord(STATISTICS, Record);
4962
5.38k
  Stream.ExitBlock();
4963
5.38k
  Stream.FlushToWord();
4964
5.38k
  ASTBlockRange.second = Stream.GetCurrentBitNo();
4965
4966
  // Write the module file extension blocks.
4967
5.38k
  for (const auto &ExtWriter : ModuleFileExtensionWriters)
4968
12
    WriteModuleFileExtension(SemaRef, *ExtWriter);
4969
4970
5.38k
  return writeUnhashedControlBlock(PP, Context);
4971
5.38k
}
4972
4973
5.45k
void ASTWriter::WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord) {
4974
5.45k
  if (DeclUpdates.empty())
4975
5.17k
    return;
4976
4977
281
  DeclUpdateMap LocalUpdates;
4978
281
  LocalUpdates.swap(DeclUpdates);
4979
4980
3.76k
  for (auto &DeclUpdate : LocalUpdates) {
4981
3.76k
    const Decl *D = DeclUpdate.first;
4982
4983
3.76k
    bool HasUpdatedBody = false;
4984
3.76k
    RecordData RecordData;
4985
3.76k
    ASTRecordWriter Record(*this, RecordData);
4986
4.21k
    for (auto &Update : DeclUpdate.second) {
4987
4.21k
      DeclUpdateKind Kind = (DeclUpdateKind)Update.getKind();
4988
4989
      // An updated body is emitted last, so that the reader doesn't need
4990
      // to skip over the lazy body to reach statements for other records.
4991
4.21k
      if (Kind == UPD_CXX_ADDED_FUNCTION_DEFINITION)
4992
34
        HasUpdatedBody = true;
4993
4.18k
      else
4994
4.18k
        Record.push_back(Kind);
4995
4996
4.21k
      switch (Kind) {
4997
428
      case UPD_CXX_ADDED_IMPLICIT_MEMBER:
4998
650
      case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
4999
683
      case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE:
5000
683
        assert(Update.getDecl() && "no decl to add?");
5001
0
        Record.push_back(GetDeclRef(Update.getDecl()));
5002
683
        break;
5003
5004
34
      case UPD_CXX_ADDED_FUNCTION_DEFINITION:
5005
34
        break;
5006
5007
7
      case UPD_CXX_POINT_OF_INSTANTIATION:
5008
        // FIXME: Do we need to also save the template specialization kind here?
5009
7
        Record.AddSourceLocation(Update.getLoc());
5010
7
        break;
5011
5012
3
      case UPD_CXX_ADDED_VAR_DEFINITION: {
5013
3
        const VarDecl *VD = cast<VarDecl>(D);
5014
3
        Record.push_back(VD->isInline());
5015
3
        Record.push_back(VD->isInlineSpecified());
5016
3
        Record.AddVarDeclInit(VD);
5017
3
        break;
5018
650
      }
5019
5020
0
      case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT:
5021
0
        Record.AddStmt(const_cast<Expr *>(
5022
0
            cast<ParmVarDecl>(Update.getDecl())->getDefaultArg()));
5023
0
        break;
5024
5025
2
      case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER:
5026
2
        Record.AddStmt(
5027
2
            cast<FieldDecl>(Update.getDecl())->getInClassInitializer());
5028
2
        break;
5029
5030
24
      case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
5031
24
        auto *RD = cast<CXXRecordDecl>(D);
5032
24
        UpdatedDeclContexts.insert(RD->getPrimaryContext());
5033
24
        Record.push_back(RD->isParamDestroyedInCallee());
5034
24
        Record.push_back(RD->getArgPassingRestrictions());
5035
24
        Record.AddCXXDefinitionData(RD);
5036
24
        Record.AddOffset(WriteDeclContextLexicalBlock(
5037
24
            *Context, const_cast<CXXRecordDecl *>(RD)));
5038
5039
        // This state is sometimes updated by template instantiation, when we
5040
        // switch from the specialization referring to the template declaration
5041
        // to it referring to the template definition.
5042
24
        if (auto *MSInfo = RD->getMemberSpecializationInfo()) {
5043
0
          Record.push_back(MSInfo->getTemplateSpecializationKind());
5044
0
          Record.AddSourceLocation(MSInfo->getPointOfInstantiation());
5045
24
        } else {
5046
24
          auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
5047
24
          Record.push_back(Spec->getTemplateSpecializationKind());
5048
24
          Record.AddSourceLocation(Spec->getPointOfInstantiation());
5049
5050
          // The instantiation might have been resolved to a partial
5051
          // specialization. If so, record which one.
5052
24
          auto From = Spec->getInstantiatedFrom();
5053
24
          if (auto PartialSpec =
5054
24
                From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) {
5055
8
            Record.push_back(true);
5056
8
            Record.AddDeclRef(PartialSpec);
5057
8
            Record.AddTemplateArgumentList(
5058
8
                &Spec->getTemplateInstantiationArgs());
5059
16
          } else {
5060
16
            Record.push_back(false);
5061
16
          }
5062
24
        }
5063
24
        Record.push_back(RD->getTagKind());
5064
24
        Record.AddSourceLocation(RD->getLocation());
5065
24
        Record.AddSourceLocation(RD->getBeginLoc());
5066
24
        Record.AddSourceRange(RD->getBraceRange());
5067
5068
        // Instantiation may change attributes; write them all out afresh.
5069
24
        Record.push_back(D->hasAttrs());
5070
24
        if (D->hasAttrs())
5071
4
          Record.AddAttributes(D->getAttrs());
5072
5073
        // FIXME: Ensure we don't get here for explicit instantiations.
5074
24
        break;
5075
650
      }
5076
5077
5
      case UPD_CXX_RESOLVED_DTOR_DELETE:
5078
5
        Record.AddDeclRef(Update.getDecl());
5079
5
        Record.AddStmt(cast<CXXDestructorDecl>(D)->getOperatorDeleteThisArg());
5080
5
        break;
5081
5082
34
      case UPD_CXX_RESOLVED_EXCEPTION_SPEC: {
5083
34
        auto prototype =
5084
34
          cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>();
5085
34
        Record.writeExceptionSpecInfo(prototype->getExceptionSpecInfo());
5086
34
        break;
5087
650
      }
5088
5089
2
      case UPD_CXX_DEDUCED_RETURN_TYPE:
5090
2
        Record.push_back(GetOrCreateTypeID(Update.getType()));
5091
2
        break;
5092
5093
1.65k
      case UPD_DECL_MARKED_USED:
5094
1.65k
        break;
5095
5096
1.23k
      case UPD_MANGLING_NUMBER:
5097
1.23k
      case UPD_STATIC_LOCAL_NUMBER:
5098
1.23k
        Record.push_back(Update.getNumber());
5099
1.23k
        break;