Coverage Report

Created: 2024-01-17 10:31

/src/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/PointerIntPair.h"
81
#include "llvm/ADT/STLExtras.h"
82
#include "llvm/ADT/ScopeExit.h"
83
#include "llvm/ADT/SmallPtrSet.h"
84
#include "llvm/ADT/SmallString.h"
85
#include "llvm/ADT/SmallVector.h"
86
#include "llvm/ADT/StringMap.h"
87
#include "llvm/ADT/StringRef.h"
88
#include "llvm/Bitstream/BitCodes.h"
89
#include "llvm/Bitstream/BitstreamWriter.h"
90
#include "llvm/Support/Casting.h"
91
#include "llvm/Support/Compression.h"
92
#include "llvm/Support/DJB.h"
93
#include "llvm/Support/Endian.h"
94
#include "llvm/Support/EndianStream.h"
95
#include "llvm/Support/Error.h"
96
#include "llvm/Support/ErrorHandling.h"
97
#include "llvm/Support/LEB128.h"
98
#include "llvm/Support/MemoryBuffer.h"
99
#include "llvm/Support/OnDiskHashTable.h"
100
#include "llvm/Support/Path.h"
101
#include "llvm/Support/SHA1.h"
102
#include "llvm/Support/TimeProfiler.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 <limits>
112
#include <memory>
113
#include <optional>
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
0
static StringRef bytes(const std::vector<T, Allocator> &v) {
124
0
  if (v.empty()) return StringRef();
125
0
  return StringRef(reinterpret_cast<const char*>(&v[0]),
126
0
                         sizeof(T) * v.size());
127
0
}
Unexecuted instantiation: ASTWriter.cpp:llvm::StringRef bytes<unsigned long, std::__1::allocator<unsigned long> >(std::__1::vector<unsigned long, std::__1::allocator<unsigned long> > const&)
Unexecuted instantiation: ASTWriter.cpp:llvm::StringRef bytes<unsigned int, std::__1::allocator<unsigned int> >(std::__1::vector<unsigned int, std::__1::allocator<unsigned int> > const&)
Unexecuted instantiation: 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&)
Unexecuted instantiation: 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&)
Unexecuted instantiation: 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&)
128
129
template <typename T>
130
0
static StringRef bytes(const SmallVectorImpl<T> &v) {
131
0
  return StringRef(reinterpret_cast<const char*>(v.data()),
132
0
                         sizeof(T) * v.size());
133
0
}
Unexecuted instantiation: ASTWriter.cpp:llvm::StringRef bytes<clang::serialization::PPEntityOffset>(llvm::SmallVectorImpl<clang::serialization::PPEntityOffset> const&)
Unexecuted instantiation: ASTWriter.cpp:llvm::StringRef bytes<unsigned int>(llvm::SmallVectorImpl<unsigned int> const&)
134
135
0
static std::string bytes(const std::vector<bool> &V) {
136
0
  std::string Str;
137
0
  Str.reserve(V.size() / 8);
138
0
  for (unsigned I = 0, E = V.size(); I < E;) {
139
0
    char Byte = 0;
140
0
    for (unsigned Bit = 0; Bit < 8 && I < E; ++Bit, ++I)
141
0
      Byte |= V[I] << Bit;
142
0
    Str += Byte;
143
0
  }
144
0
  return Str;
145
0
}
146
147
//===----------------------------------------------------------------------===//
148
// Type serialization
149
//===----------------------------------------------------------------------===//
150
151
0
static TypeCode getTypeCodeForTypeClass(Type::TypeClass id) {
152
0
  switch (id) {
153
0
#define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \
154
0
  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
0
  }
159
0
  llvm_unreachable("bad type kind");
160
0
}
161
162
namespace {
163
164
std::set<const FileEntry *> GetAffectingModuleMaps(const Preprocessor &PP,
165
0
                                                   Module *RootModule) {
166
0
  SmallVector<const Module *> ModulesToProcess{RootModule};
167
168
0
  const HeaderSearch &HS = PP.getHeaderSearchInfo();
169
170
0
  SmallVector<OptionalFileEntryRef, 16> FilesByUID;
171
0
  HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
172
173
0
  if (FilesByUID.size() > HS.header_file_size())
174
0
    FilesByUID.resize(HS.header_file_size());
175
176
0
  for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
177
0
    OptionalFileEntryRef File = FilesByUID[UID];
178
0
    if (!File)
179
0
      continue;
180
181
0
    const HeaderFileInfo *HFI =
182
0
        HS.getExistingFileInfo(*File, /*WantExternal*/ false);
183
0
    if (!HFI || (HFI->isModuleHeader && !HFI->isCompilingModuleHeader))
184
0
      continue;
185
186
0
    for (const auto &KH : HS.findResolvedModulesForHeader(*File)) {
187
0
      if (!KH.getModule())
188
0
        continue;
189
0
      ModulesToProcess.push_back(KH.getModule());
190
0
    }
191
0
  }
192
193
0
  const ModuleMap &MM = HS.getModuleMap();
194
0
  SourceManager &SourceMgr = PP.getSourceManager();
195
196
0
  std::set<const FileEntry *> ModuleMaps{};
197
0
  auto CollectIncludingModuleMaps = [&](FileEntryRef F) {
198
0
    if (!ModuleMaps.insert(F).second)
199
0
      return;
200
0
    FileID FID = SourceMgr.translateFile(F);
201
0
    SourceLocation Loc = SourceMgr.getIncludeLoc(FID);
202
    // The include location of inferred module maps can point into the header
203
    // file that triggered the inferring. Cut off the walk if that's the case.
204
0
    while (Loc.isValid() && isModuleMap(SourceMgr.getFileCharacteristic(Loc))) {
205
0
      FID = SourceMgr.getFileID(Loc);
206
0
      if (!ModuleMaps.insert(*SourceMgr.getFileEntryRefForID(FID)).second)
207
0
        break;
208
0
      Loc = SourceMgr.getIncludeLoc(FID);
209
0
    }
210
0
  };
211
212
0
  std::set<const Module *> ProcessedModules;
213
0
  auto CollectIncludingMapsFromAncestors = [&](const Module *M) {
214
0
    for (const Module *Mod = M; Mod; Mod = Mod->Parent) {
215
0
      if (!ProcessedModules.insert(Mod).second)
216
0
        break;
217
      // The containing module map is affecting, because it's being pointed
218
      // into by Module::DefinitionLoc.
219
0
      if (auto ModuleMapFile = MM.getContainingModuleMapFile(Mod))
220
0
        CollectIncludingModuleMaps(*ModuleMapFile);
221
      // For inferred modules, the module map that allowed inferring is not in
222
      // the include chain of the virtual containing module map file. It did
223
      // affect the compilation, though.
224
0
      if (auto ModuleMapFile = MM.getModuleMapFileForUniquing(Mod))
225
0
        CollectIncludingModuleMaps(*ModuleMapFile);
226
0
    }
227
0
  };
228
229
0
  for (const Module *CurrentModule : ModulesToProcess) {
230
0
    CollectIncludingMapsFromAncestors(CurrentModule);
231
0
    for (const Module *ImportedModule : CurrentModule->Imports)
232
0
      CollectIncludingMapsFromAncestors(ImportedModule);
233
0
    for (const Module *UndeclaredModule : CurrentModule->UndeclaredUses)
234
0
      CollectIncludingMapsFromAncestors(UndeclaredModule);
235
0
  }
236
237
0
  return ModuleMaps;
238
0
}
239
240
class ASTTypeWriter {
241
  ASTWriter &Writer;
242
  ASTWriter::RecordData Record;
243
  ASTRecordWriter BasicWriter;
244
245
public:
246
  ASTTypeWriter(ASTWriter &Writer)
247
0
    : Writer(Writer), BasicWriter(Writer, Record) {}
248
249
0
  uint64_t write(QualType T) {
250
0
    if (T.hasLocalNonFastQualifiers()) {
251
0
      Qualifiers Qs = T.getLocalQualifiers();
252
0
      BasicWriter.writeQualType(T.getLocalUnqualifiedType());
253
0
      BasicWriter.writeQualifiers(Qs);
254
0
      return BasicWriter.Emit(TYPE_EXT_QUAL, Writer.getTypeExtQualAbbrev());
255
0
    }
256
257
0
    const Type *typePtr = T.getTypePtr();
258
0
    serialization::AbstractTypeWriter<ASTRecordWriter> atw(BasicWriter);
259
0
    atw.write(typePtr);
260
0
    return BasicWriter.Emit(getTypeCodeForTypeClass(typePtr->getTypeClass()),
261
0
                            /*abbrev*/ 0);
262
0
  }
263
};
264
265
class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
266
  using LocSeq = SourceLocationSequence;
267
268
  ASTRecordWriter &Record;
269
  LocSeq *Seq;
270
271
0
  void addSourceLocation(SourceLocation Loc) {
272
0
    Record.AddSourceLocation(Loc, Seq);
273
0
  }
274
0
  void addSourceRange(SourceRange Range) { Record.AddSourceRange(Range, Seq); }
275
276
public:
277
  TypeLocWriter(ASTRecordWriter &Record, LocSeq *Seq)
278
0
      : Record(Record), Seq(Seq) {}
279
280
#define ABSTRACT_TYPELOC(CLASS, PARENT)
281
#define TYPELOC(CLASS, PARENT) \
282
    void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
283
#include "clang/AST/TypeLocNodes.def"
284
285
  void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
286
  void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
287
};
288
289
} // namespace
290
291
0
void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
292
  // nothing to do
293
0
}
294
295
0
void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
296
0
  addSourceLocation(TL.getBuiltinLoc());
297
0
  if (TL.needsExtraLocalData()) {
298
0
    Record.push_back(TL.getWrittenTypeSpec());
299
0
    Record.push_back(static_cast<uint64_t>(TL.getWrittenSignSpec()));
300
0
    Record.push_back(static_cast<uint64_t>(TL.getWrittenWidthSpec()));
301
0
    Record.push_back(TL.hasModeAttr());
302
0
  }
303
0
}
304
305
0
void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
306
0
  addSourceLocation(TL.getNameLoc());
307
0
}
308
309
0
void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
310
0
  addSourceLocation(TL.getStarLoc());
311
0
}
312
313
0
void TypeLocWriter::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
314
  // nothing to do
315
0
}
316
317
0
void TypeLocWriter::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
318
  // nothing to do
319
0
}
320
321
0
void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
322
0
  addSourceLocation(TL.getCaretLoc());
323
0
}
324
325
0
void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
326
0
  addSourceLocation(TL.getAmpLoc());
327
0
}
328
329
0
void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
330
0
  addSourceLocation(TL.getAmpAmpLoc());
331
0
}
332
333
0
void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
334
0
  addSourceLocation(TL.getStarLoc());
335
0
  Record.AddTypeSourceInfo(TL.getClassTInfo());
336
0
}
337
338
0
void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
339
0
  addSourceLocation(TL.getLBracketLoc());
340
0
  addSourceLocation(TL.getRBracketLoc());
341
0
  Record.push_back(TL.getSizeExpr() ? 1 : 0);
342
0
  if (TL.getSizeExpr())
343
0
    Record.AddStmt(TL.getSizeExpr());
344
0
}
345
346
0
void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
347
0
  VisitArrayTypeLoc(TL);
348
0
}
349
350
0
void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
351
0
  VisitArrayTypeLoc(TL);
352
0
}
353
354
0
void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
355
0
  VisitArrayTypeLoc(TL);
356
0
}
357
358
void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
359
0
                                            DependentSizedArrayTypeLoc TL) {
360
0
  VisitArrayTypeLoc(TL);
361
0
}
362
363
void TypeLocWriter::VisitDependentAddressSpaceTypeLoc(
364
0
    DependentAddressSpaceTypeLoc TL) {
365
0
  addSourceLocation(TL.getAttrNameLoc());
366
0
  SourceRange range = TL.getAttrOperandParensRange();
367
0
  addSourceLocation(range.getBegin());
368
0
  addSourceLocation(range.getEnd());
369
0
  Record.AddStmt(TL.getAttrExprOperand());
370
0
}
371
372
void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
373
0
                                        DependentSizedExtVectorTypeLoc TL) {
374
0
  addSourceLocation(TL.getNameLoc());
375
0
}
376
377
0
void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
378
0
  addSourceLocation(TL.getNameLoc());
379
0
}
380
381
void TypeLocWriter::VisitDependentVectorTypeLoc(
382
0
    DependentVectorTypeLoc TL) {
383
0
  addSourceLocation(TL.getNameLoc());
384
0
}
385
386
0
void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
387
0
  addSourceLocation(TL.getNameLoc());
388
0
}
389
390
0
void TypeLocWriter::VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc TL) {
391
0
  addSourceLocation(TL.getAttrNameLoc());
392
0
  SourceRange range = TL.getAttrOperandParensRange();
393
0
  addSourceLocation(range.getBegin());
394
0
  addSourceLocation(range.getEnd());
395
0
  Record.AddStmt(TL.getAttrRowOperand());
396
0
  Record.AddStmt(TL.getAttrColumnOperand());
397
0
}
398
399
void TypeLocWriter::VisitDependentSizedMatrixTypeLoc(
400
0
    DependentSizedMatrixTypeLoc TL) {
401
0
  addSourceLocation(TL.getAttrNameLoc());
402
0
  SourceRange range = TL.getAttrOperandParensRange();
403
0
  addSourceLocation(range.getBegin());
404
0
  addSourceLocation(range.getEnd());
405
0
  Record.AddStmt(TL.getAttrRowOperand());
406
0
  Record.AddStmt(TL.getAttrColumnOperand());
407
0
}
408
409
0
void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
410
0
  addSourceLocation(TL.getLocalRangeBegin());
411
0
  addSourceLocation(TL.getLParenLoc());
412
0
  addSourceLocation(TL.getRParenLoc());
413
0
  addSourceRange(TL.getExceptionSpecRange());
414
0
  addSourceLocation(TL.getLocalRangeEnd());
415
0
  for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i)
416
0
    Record.AddDeclRef(TL.getParam(i));
417
0
}
418
419
0
void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
420
0
  VisitFunctionTypeLoc(TL);
421
0
}
422
423
0
void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
424
0
  VisitFunctionTypeLoc(TL);
425
0
}
426
427
0
void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
428
0
  addSourceLocation(TL.getNameLoc());
429
0
}
430
431
0
void TypeLocWriter::VisitUsingTypeLoc(UsingTypeLoc TL) {
432
0
  addSourceLocation(TL.getNameLoc());
433
0
}
434
435
0
void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
436
0
  addSourceLocation(TL.getNameLoc());
437
0
}
438
439
0
void TypeLocWriter::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
440
0
  if (TL.getNumProtocols()) {
441
0
    addSourceLocation(TL.getProtocolLAngleLoc());
442
0
    addSourceLocation(TL.getProtocolRAngleLoc());
443
0
  }
444
0
  for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
445
0
    addSourceLocation(TL.getProtocolLoc(i));
446
0
}
447
448
0
void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
449
0
  addSourceLocation(TL.getTypeofLoc());
450
0
  addSourceLocation(TL.getLParenLoc());
451
0
  addSourceLocation(TL.getRParenLoc());
452
0
}
453
454
0
void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
455
0
  addSourceLocation(TL.getTypeofLoc());
456
0
  addSourceLocation(TL.getLParenLoc());
457
0
  addSourceLocation(TL.getRParenLoc());
458
0
  Record.AddTypeSourceInfo(TL.getUnmodifiedTInfo());
459
0
}
460
461
0
void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
462
0
  addSourceLocation(TL.getDecltypeLoc());
463
0
  addSourceLocation(TL.getRParenLoc());
464
0
}
465
466
0
void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
467
0
  addSourceLocation(TL.getKWLoc());
468
0
  addSourceLocation(TL.getLParenLoc());
469
0
  addSourceLocation(TL.getRParenLoc());
470
0
  Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
471
0
}
472
473
0
void ASTRecordWriter::AddConceptReference(const ConceptReference *CR) {
474
0
  assert(CR);
475
0
  AddNestedNameSpecifierLoc(CR->getNestedNameSpecifierLoc());
476
0
  AddSourceLocation(CR->getTemplateKWLoc());
477
0
  AddDeclarationNameInfo(CR->getConceptNameInfo());
478
0
  AddDeclRef(CR->getFoundDecl());
479
0
  AddDeclRef(CR->getNamedConcept());
480
0
  push_back(CR->getTemplateArgsAsWritten() != nullptr);
481
0
  if (CR->getTemplateArgsAsWritten())
482
0
    AddASTTemplateArgumentListInfo(CR->getTemplateArgsAsWritten());
483
0
}
484
485
0
void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
486
0
  addSourceLocation(TL.getNameLoc());
487
0
  auto *CR = TL.getConceptReference();
488
0
  Record.push_back(TL.isConstrained() && CR);
489
0
  if (TL.isConstrained() && CR)
490
0
    Record.AddConceptReference(CR);
491
0
  Record.push_back(TL.isDecltypeAuto());
492
0
  if (TL.isDecltypeAuto())
493
0
    addSourceLocation(TL.getRParenLoc());
494
0
}
495
496
void TypeLocWriter::VisitDeducedTemplateSpecializationTypeLoc(
497
0
    DeducedTemplateSpecializationTypeLoc TL) {
498
0
  addSourceLocation(TL.getTemplateNameLoc());
499
0
}
500
501
0
void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
502
0
  addSourceLocation(TL.getNameLoc());
503
0
}
504
505
0
void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
506
0
  addSourceLocation(TL.getNameLoc());
507
0
}
508
509
0
void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
510
0
  Record.AddAttr(TL.getAttr());
511
0
}
512
513
0
void TypeLocWriter::VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
514
  // Nothing to do.
515
0
}
516
517
0
void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
518
0
  addSourceLocation(TL.getNameLoc());
519
0
}
520
521
void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
522
0
                                            SubstTemplateTypeParmTypeLoc TL) {
523
0
  addSourceLocation(TL.getNameLoc());
524
0
}
525
526
void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
527
0
                                          SubstTemplateTypeParmPackTypeLoc TL) {
528
0
  addSourceLocation(TL.getNameLoc());
529
0
}
530
531
void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
532
0
                                           TemplateSpecializationTypeLoc TL) {
533
0
  addSourceLocation(TL.getTemplateKeywordLoc());
534
0
  addSourceLocation(TL.getTemplateNameLoc());
535
0
  addSourceLocation(TL.getLAngleLoc());
536
0
  addSourceLocation(TL.getRAngleLoc());
537
0
  for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
538
0
    Record.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
539
0
                                      TL.getArgLoc(i).getLocInfo());
540
0
}
541
542
0
void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
543
0
  addSourceLocation(TL.getLParenLoc());
544
0
  addSourceLocation(TL.getRParenLoc());
545
0
}
546
547
0
void TypeLocWriter::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
548
0
  addSourceLocation(TL.getExpansionLoc());
549
0
}
550
551
0
void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
552
0
  addSourceLocation(TL.getElaboratedKeywordLoc());
553
0
  Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
554
0
}
555
556
0
void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
557
0
  addSourceLocation(TL.getNameLoc());
558
0
}
559
560
0
void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
561
0
  addSourceLocation(TL.getElaboratedKeywordLoc());
562
0
  Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
563
0
  addSourceLocation(TL.getNameLoc());
564
0
}
565
566
void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
567
0
       DependentTemplateSpecializationTypeLoc TL) {
568
0
  addSourceLocation(TL.getElaboratedKeywordLoc());
569
0
  Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
570
0
  addSourceLocation(TL.getTemplateKeywordLoc());
571
0
  addSourceLocation(TL.getTemplateNameLoc());
572
0
  addSourceLocation(TL.getLAngleLoc());
573
0
  addSourceLocation(TL.getRAngleLoc());
574
0
  for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
575
0
    Record.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
576
0
                                      TL.getArgLoc(I).getLocInfo());
577
0
}
578
579
0
void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
580
0
  addSourceLocation(TL.getEllipsisLoc());
581
0
}
582
583
0
void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
584
0
  addSourceLocation(TL.getNameLoc());
585
0
  addSourceLocation(TL.getNameEndLoc());
586
0
}
587
588
0
void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
589
0
  Record.push_back(TL.hasBaseTypeAsWritten());
590
0
  addSourceLocation(TL.getTypeArgsLAngleLoc());
591
0
  addSourceLocation(TL.getTypeArgsRAngleLoc());
592
0
  for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
593
0
    Record.AddTypeSourceInfo(TL.getTypeArgTInfo(i));
594
0
  addSourceLocation(TL.getProtocolLAngleLoc());
595
0
  addSourceLocation(TL.getProtocolRAngleLoc());
596
0
  for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
597
0
    addSourceLocation(TL.getProtocolLoc(i));
598
0
}
599
600
0
void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
601
0
  addSourceLocation(TL.getStarLoc());
602
0
}
603
604
0
void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
605
0
  addSourceLocation(TL.getKWLoc());
606
0
  addSourceLocation(TL.getLParenLoc());
607
0
  addSourceLocation(TL.getRParenLoc());
608
0
}
609
610
0
void TypeLocWriter::VisitPipeTypeLoc(PipeTypeLoc TL) {
611
0
  addSourceLocation(TL.getKWLoc());
612
0
}
613
614
0
void TypeLocWriter::VisitBitIntTypeLoc(clang::BitIntTypeLoc TL) {
615
0
  addSourceLocation(TL.getNameLoc());
616
0
}
617
void TypeLocWriter::VisitDependentBitIntTypeLoc(
618
0
    clang::DependentBitIntTypeLoc TL) {
619
0
  addSourceLocation(TL.getNameLoc());
620
0
}
621
622
0
void ASTWriter::WriteTypeAbbrevs() {
623
0
  using namespace llvm;
624
625
0
  std::shared_ptr<BitCodeAbbrev> Abv;
626
627
  // Abbreviation for TYPE_EXT_QUAL
628
0
  Abv = std::make_shared<BitCodeAbbrev>();
629
0
  Abv->Add(BitCodeAbbrevOp(serialization::TYPE_EXT_QUAL));
630
0
  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // Type
631
0
  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3));   // Quals
632
0
  TypeExtQualAbbrev = Stream.EmitAbbrev(std::move(Abv));
633
0
}
634
635
//===----------------------------------------------------------------------===//
636
// ASTWriter Implementation
637
//===----------------------------------------------------------------------===//
638
639
static void EmitBlockID(unsigned ID, const char *Name,
640
                        llvm::BitstreamWriter &Stream,
641
0
                        ASTWriter::RecordDataImpl &Record) {
642
0
  Record.clear();
643
0
  Record.push_back(ID);
644
0
  Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
645
646
  // Emit the block name if present.
647
0
  if (!Name || Name[0] == 0)
648
0
    return;
649
0
  Record.clear();
650
0
  while (*Name)
651
0
    Record.push_back(*Name++);
652
0
  Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
653
0
}
654
655
static void EmitRecordID(unsigned ID, const char *Name,
656
                         llvm::BitstreamWriter &Stream,
657
0
                         ASTWriter::RecordDataImpl &Record) {
658
0
  Record.clear();
659
0
  Record.push_back(ID);
660
0
  while (*Name)
661
0
    Record.push_back(*Name++);
662
0
  Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
663
0
}
664
665
static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
666
0
                          ASTWriter::RecordDataImpl &Record) {
667
0
#define RECORD(X) EmitRecordID(X, #X, Stream, Record)
668
0
  RECORD(STMT_STOP);
669
0
  RECORD(STMT_NULL_PTR);
670
0
  RECORD(STMT_REF_PTR);
671
0
  RECORD(STMT_NULL);
672
0
  RECORD(STMT_COMPOUND);
673
0
  RECORD(STMT_CASE);
674
0
  RECORD(STMT_DEFAULT);
675
0
  RECORD(STMT_LABEL);
676
0
  RECORD(STMT_ATTRIBUTED);
677
0
  RECORD(STMT_IF);
678
0
  RECORD(STMT_SWITCH);
679
0
  RECORD(STMT_WHILE);
680
0
  RECORD(STMT_DO);
681
0
  RECORD(STMT_FOR);
682
0
  RECORD(STMT_GOTO);
683
0
  RECORD(STMT_INDIRECT_GOTO);
684
0
  RECORD(STMT_CONTINUE);
685
0
  RECORD(STMT_BREAK);
686
0
  RECORD(STMT_RETURN);
687
0
  RECORD(STMT_DECL);
688
0
  RECORD(STMT_GCCASM);
689
0
  RECORD(STMT_MSASM);
690
0
  RECORD(EXPR_PREDEFINED);
691
0
  RECORD(EXPR_DECL_REF);
692
0
  RECORD(EXPR_INTEGER_LITERAL);
693
0
  RECORD(EXPR_FIXEDPOINT_LITERAL);
694
0
  RECORD(EXPR_FLOATING_LITERAL);
695
0
  RECORD(EXPR_IMAGINARY_LITERAL);
696
0
  RECORD(EXPR_STRING_LITERAL);
697
0
  RECORD(EXPR_CHARACTER_LITERAL);
698
0
  RECORD(EXPR_PAREN);
699
0
  RECORD(EXPR_PAREN_LIST);
700
0
  RECORD(EXPR_UNARY_OPERATOR);
701
0
  RECORD(EXPR_SIZEOF_ALIGN_OF);
702
0
  RECORD(EXPR_ARRAY_SUBSCRIPT);
703
0
  RECORD(EXPR_CALL);
704
0
  RECORD(EXPR_MEMBER);
705
0
  RECORD(EXPR_BINARY_OPERATOR);
706
0
  RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
707
0
  RECORD(EXPR_CONDITIONAL_OPERATOR);
708
0
  RECORD(EXPR_IMPLICIT_CAST);
709
0
  RECORD(EXPR_CSTYLE_CAST);
710
0
  RECORD(EXPR_COMPOUND_LITERAL);
711
0
  RECORD(EXPR_EXT_VECTOR_ELEMENT);
712
0
  RECORD(EXPR_INIT_LIST);
713
0
  RECORD(EXPR_DESIGNATED_INIT);
714
0
  RECORD(EXPR_DESIGNATED_INIT_UPDATE);
715
0
  RECORD(EXPR_IMPLICIT_VALUE_INIT);
716
0
  RECORD(EXPR_NO_INIT);
717
0
  RECORD(EXPR_VA_ARG);
718
0
  RECORD(EXPR_ADDR_LABEL);
719
0
  RECORD(EXPR_STMT);
720
0
  RECORD(EXPR_CHOOSE);
721
0
  RECORD(EXPR_GNU_NULL);
722
0
  RECORD(EXPR_SHUFFLE_VECTOR);
723
0
  RECORD(EXPR_BLOCK);
724
0
  RECORD(EXPR_GENERIC_SELECTION);
725
0
  RECORD(EXPR_OBJC_STRING_LITERAL);
726
0
  RECORD(EXPR_OBJC_BOXED_EXPRESSION);
727
0
  RECORD(EXPR_OBJC_ARRAY_LITERAL);
728
0
  RECORD(EXPR_OBJC_DICTIONARY_LITERAL);
729
0
  RECORD(EXPR_OBJC_ENCODE);
730
0
  RECORD(EXPR_OBJC_SELECTOR_EXPR);
731
0
  RECORD(EXPR_OBJC_PROTOCOL_EXPR);
732
0
  RECORD(EXPR_OBJC_IVAR_REF_EXPR);
733
0
  RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
734
0
  RECORD(EXPR_OBJC_KVC_REF_EXPR);
735
0
  RECORD(EXPR_OBJC_MESSAGE_EXPR);
736
0
  RECORD(STMT_OBJC_FOR_COLLECTION);
737
0
  RECORD(STMT_OBJC_CATCH);
738
0
  RECORD(STMT_OBJC_FINALLY);
739
0
  RECORD(STMT_OBJC_AT_TRY);
740
0
  RECORD(STMT_OBJC_AT_SYNCHRONIZED);
741
0
  RECORD(STMT_OBJC_AT_THROW);
742
0
  RECORD(EXPR_OBJC_BOOL_LITERAL);
743
0
  RECORD(STMT_CXX_CATCH);
744
0
  RECORD(STMT_CXX_TRY);
745
0
  RECORD(STMT_CXX_FOR_RANGE);
746
0
  RECORD(EXPR_CXX_OPERATOR_CALL);
747
0
  RECORD(EXPR_CXX_MEMBER_CALL);
748
0
  RECORD(EXPR_CXX_REWRITTEN_BINARY_OPERATOR);
749
0
  RECORD(EXPR_CXX_CONSTRUCT);
750
0
  RECORD(EXPR_CXX_TEMPORARY_OBJECT);
751
0
  RECORD(EXPR_CXX_STATIC_CAST);
752
0
  RECORD(EXPR_CXX_DYNAMIC_CAST);
753
0
  RECORD(EXPR_CXX_REINTERPRET_CAST);
754
0
  RECORD(EXPR_CXX_CONST_CAST);
755
0
  RECORD(EXPR_CXX_ADDRSPACE_CAST);
756
0
  RECORD(EXPR_CXX_FUNCTIONAL_CAST);
757
0
  RECORD(EXPR_USER_DEFINED_LITERAL);
758
0
  RECORD(EXPR_CXX_STD_INITIALIZER_LIST);
759
0
  RECORD(EXPR_CXX_BOOL_LITERAL);
760
0
  RECORD(EXPR_CXX_PAREN_LIST_INIT);
761
0
  RECORD(EXPR_CXX_NULL_PTR_LITERAL);
762
0
  RECORD(EXPR_CXX_TYPEID_EXPR);
763
0
  RECORD(EXPR_CXX_TYPEID_TYPE);
764
0
  RECORD(EXPR_CXX_THIS);
765
0
  RECORD(EXPR_CXX_THROW);
766
0
  RECORD(EXPR_CXX_DEFAULT_ARG);
767
0
  RECORD(EXPR_CXX_DEFAULT_INIT);
768
0
  RECORD(EXPR_CXX_BIND_TEMPORARY);
769
0
  RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
770
0
  RECORD(EXPR_CXX_NEW);
771
0
  RECORD(EXPR_CXX_DELETE);
772
0
  RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
773
0
  RECORD(EXPR_EXPR_WITH_CLEANUPS);
774
0
  RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
775
0
  RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
776
0
  RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
777
0
  RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
778
0
  RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
779
0
  RECORD(EXPR_CXX_EXPRESSION_TRAIT);
780
0
  RECORD(EXPR_CXX_NOEXCEPT);
781
0
  RECORD(EXPR_OPAQUE_VALUE);
782
0
  RECORD(EXPR_BINARY_CONDITIONAL_OPERATOR);
783
0
  RECORD(EXPR_TYPE_TRAIT);
784
0
  RECORD(EXPR_ARRAY_TYPE_TRAIT);
785
0
  RECORD(EXPR_PACK_EXPANSION);
786
0
  RECORD(EXPR_SIZEOF_PACK);
787
0
  RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM);
788
0
  RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
789
0
  RECORD(EXPR_FUNCTION_PARM_PACK);
790
0
  RECORD(EXPR_MATERIALIZE_TEMPORARY);
791
0
  RECORD(EXPR_CUDA_KERNEL_CALL);
792
0
  RECORD(EXPR_CXX_UUIDOF_EXPR);
793
0
  RECORD(EXPR_CXX_UUIDOF_TYPE);
794
0
  RECORD(EXPR_LAMBDA);
795
0
#undef RECORD
796
0
}
797
798
0
void ASTWriter::WriteBlockInfoBlock() {
799
0
  RecordData Record;
800
0
  Stream.EnterBlockInfoBlock();
801
802
0
#define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
803
0
#define RECORD(X) EmitRecordID(X, #X, Stream, Record)
804
805
  // Control Block.
806
0
  BLOCK(CONTROL_BLOCK);
807
0
  RECORD(METADATA);
808
0
  RECORD(MODULE_NAME);
809
0
  RECORD(MODULE_DIRECTORY);
810
0
  RECORD(MODULE_MAP_FILE);
811
0
  RECORD(IMPORTS);
812
0
  RECORD(ORIGINAL_FILE);
813
0
  RECORD(ORIGINAL_FILE_ID);
814
0
  RECORD(INPUT_FILE_OFFSETS);
815
816
0
  BLOCK(OPTIONS_BLOCK);
817
0
  RECORD(LANGUAGE_OPTIONS);
818
0
  RECORD(TARGET_OPTIONS);
819
0
  RECORD(FILE_SYSTEM_OPTIONS);
820
0
  RECORD(HEADER_SEARCH_OPTIONS);
821
0
  RECORD(PREPROCESSOR_OPTIONS);
822
823
0
  BLOCK(INPUT_FILES_BLOCK);
824
0
  RECORD(INPUT_FILE);
825
0
  RECORD(INPUT_FILE_HASH);
826
827
  // AST Top-Level Block.
828
0
  BLOCK(AST_BLOCK);
829
0
  RECORD(TYPE_OFFSET);
830
0
  RECORD(DECL_OFFSET);
831
0
  RECORD(IDENTIFIER_OFFSET);
832
0
  RECORD(IDENTIFIER_TABLE);
833
0
  RECORD(EAGERLY_DESERIALIZED_DECLS);
834
0
  RECORD(MODULAR_CODEGEN_DECLS);
835
0
  RECORD(SPECIAL_TYPES);
836
0
  RECORD(STATISTICS);
837
0
  RECORD(TENTATIVE_DEFINITIONS);
838
0
  RECORD(SELECTOR_OFFSETS);
839
0
  RECORD(METHOD_POOL);
840
0
  RECORD(PP_COUNTER_VALUE);
841
0
  RECORD(SOURCE_LOCATION_OFFSETS);
842
0
  RECORD(EXT_VECTOR_DECLS);
843
0
  RECORD(UNUSED_FILESCOPED_DECLS);
844
0
  RECORD(PPD_ENTITIES_OFFSETS);
845
0
  RECORD(VTABLE_USES);
846
0
  RECORD(PPD_SKIPPED_RANGES);
847
0
  RECORD(REFERENCED_SELECTOR_POOL);
848
0
  RECORD(TU_UPDATE_LEXICAL);
849
0
  RECORD(SEMA_DECL_REFS);
850
0
  RECORD(WEAK_UNDECLARED_IDENTIFIERS);
851
0
  RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
852
0
  RECORD(UPDATE_VISIBLE);
853
0
  RECORD(DECL_UPDATE_OFFSETS);
854
0
  RECORD(DECL_UPDATES);
855
0
  RECORD(CUDA_SPECIAL_DECL_REFS);
856
0
  RECORD(HEADER_SEARCH_TABLE);
857
0
  RECORD(FP_PRAGMA_OPTIONS);
858
0
  RECORD(OPENCL_EXTENSIONS);
859
0
  RECORD(OPENCL_EXTENSION_TYPES);
860
0
  RECORD(OPENCL_EXTENSION_DECLS);
861
0
  RECORD(DELEGATING_CTORS);
862
0
  RECORD(KNOWN_NAMESPACES);
863
0
  RECORD(MODULE_OFFSET_MAP);
864
0
  RECORD(SOURCE_MANAGER_LINE_TABLE);
865
0
  RECORD(OBJC_CATEGORIES_MAP);
866
0
  RECORD(FILE_SORTED_DECLS);
867
0
  RECORD(IMPORTED_MODULES);
868
0
  RECORD(OBJC_CATEGORIES);
869
0
  RECORD(MACRO_OFFSET);
870
0
  RECORD(INTERESTING_IDENTIFIERS);
871
0
  RECORD(UNDEFINED_BUT_USED);
872
0
  RECORD(LATE_PARSED_TEMPLATE);
873
0
  RECORD(OPTIMIZE_PRAGMA_OPTIONS);
874
0
  RECORD(MSSTRUCT_PRAGMA_OPTIONS);
875
0
  RECORD(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS);
876
0
  RECORD(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES);
877
0
  RECORD(DELETE_EXPRS_TO_ANALYZE);
878
0
  RECORD(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH);
879
0
  RECORD(PP_CONDITIONAL_STACK);
880
0
  RECORD(DECLS_TO_CHECK_FOR_DEFERRED_DIAGS);
881
0
  RECORD(PP_ASSUME_NONNULL_LOC);
882
883
  // SourceManager Block.
884
0
  BLOCK(SOURCE_MANAGER_BLOCK);
885
0
  RECORD(SM_SLOC_FILE_ENTRY);
886
0
  RECORD(SM_SLOC_BUFFER_ENTRY);
887
0
  RECORD(SM_SLOC_BUFFER_BLOB);
888
0
  RECORD(SM_SLOC_BUFFER_BLOB_COMPRESSED);
889
0
  RECORD(SM_SLOC_EXPANSION_ENTRY);
890
891
  // Preprocessor Block.
892
0
  BLOCK(PREPROCESSOR_BLOCK);
893
0
  RECORD(PP_MACRO_DIRECTIVE_HISTORY);
894
0
  RECORD(PP_MACRO_FUNCTION_LIKE);
895
0
  RECORD(PP_MACRO_OBJECT_LIKE);
896
0
  RECORD(PP_MODULE_MACRO);
897
0
  RECORD(PP_TOKEN);
898
899
  // Submodule Block.
900
0
  BLOCK(SUBMODULE_BLOCK);
901
0
  RECORD(SUBMODULE_METADATA);
902
0
  RECORD(SUBMODULE_DEFINITION);
903
0
  RECORD(SUBMODULE_UMBRELLA_HEADER);
904
0
  RECORD(SUBMODULE_HEADER);
905
0
  RECORD(SUBMODULE_TOPHEADER);
906
0
  RECORD(SUBMODULE_UMBRELLA_DIR);
907
0
  RECORD(SUBMODULE_IMPORTS);
908
0
  RECORD(SUBMODULE_AFFECTING_MODULES);
909
0
  RECORD(SUBMODULE_EXPORTS);
910
0
  RECORD(SUBMODULE_REQUIRES);
911
0
  RECORD(SUBMODULE_EXCLUDED_HEADER);
912
0
  RECORD(SUBMODULE_LINK_LIBRARY);
913
0
  RECORD(SUBMODULE_CONFIG_MACRO);
914
0
  RECORD(SUBMODULE_CONFLICT);
915
0
  RECORD(SUBMODULE_PRIVATE_HEADER);
916
0
  RECORD(SUBMODULE_TEXTUAL_HEADER);
917
0
  RECORD(SUBMODULE_PRIVATE_TEXTUAL_HEADER);
918
0
  RECORD(SUBMODULE_INITIALIZERS);
919
0
  RECORD(SUBMODULE_EXPORT_AS);
920
921
  // Comments Block.
922
0
  BLOCK(COMMENTS_BLOCK);
923
0
  RECORD(COMMENTS_RAW_COMMENT);
924
925
  // Decls and Types block.
926
0
  BLOCK(DECLTYPES_BLOCK);
927
0
  RECORD(TYPE_EXT_QUAL);
928
0
  RECORD(TYPE_COMPLEX);
929
0
  RECORD(TYPE_POINTER);
930
0
  RECORD(TYPE_BLOCK_POINTER);
931
0
  RECORD(TYPE_LVALUE_REFERENCE);
932
0
  RECORD(TYPE_RVALUE_REFERENCE);
933
0
  RECORD(TYPE_MEMBER_POINTER);
934
0
  RECORD(TYPE_CONSTANT_ARRAY);
935
0
  RECORD(TYPE_INCOMPLETE_ARRAY);
936
0
  RECORD(TYPE_VARIABLE_ARRAY);
937
0
  RECORD(TYPE_VECTOR);
938
0
  RECORD(TYPE_EXT_VECTOR);
939
0
  RECORD(TYPE_FUNCTION_NO_PROTO);
940
0
  RECORD(TYPE_FUNCTION_PROTO);
941
0
  RECORD(TYPE_TYPEDEF);
942
0
  RECORD(TYPE_TYPEOF_EXPR);
943
0
  RECORD(TYPE_TYPEOF);
944
0
  RECORD(TYPE_RECORD);
945
0
  RECORD(TYPE_ENUM);
946
0
  RECORD(TYPE_OBJC_INTERFACE);
947
0
  RECORD(TYPE_OBJC_OBJECT_POINTER);
948
0
  RECORD(TYPE_DECLTYPE);
949
0
  RECORD(TYPE_ELABORATED);
950
0
  RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
951
0
  RECORD(TYPE_UNRESOLVED_USING);
952
0
  RECORD(TYPE_INJECTED_CLASS_NAME);
953
0
  RECORD(TYPE_OBJC_OBJECT);
954
0
  RECORD(TYPE_TEMPLATE_TYPE_PARM);
955
0
  RECORD(TYPE_TEMPLATE_SPECIALIZATION);
956
0
  RECORD(TYPE_DEPENDENT_NAME);
957
0
  RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
958
0
  RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
959
0
  RECORD(TYPE_PAREN);
960
0
  RECORD(TYPE_MACRO_QUALIFIED);
961
0
  RECORD(TYPE_PACK_EXPANSION);
962
0
  RECORD(TYPE_ATTRIBUTED);
963
0
  RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
964
0
  RECORD(TYPE_AUTO);
965
0
  RECORD(TYPE_UNARY_TRANSFORM);
966
0
  RECORD(TYPE_ATOMIC);
967
0
  RECORD(TYPE_DECAYED);
968
0
  RECORD(TYPE_ADJUSTED);
969
0
  RECORD(TYPE_OBJC_TYPE_PARAM);
970
0
  RECORD(LOCAL_REDECLARATIONS);
971
0
  RECORD(DECL_TYPEDEF);
972
0
  RECORD(DECL_TYPEALIAS);
973
0
  RECORD(DECL_ENUM);
974
0
  RECORD(DECL_RECORD);
975
0
  RECORD(DECL_ENUM_CONSTANT);
976
0
  RECORD(DECL_FUNCTION);
977
0
  RECORD(DECL_OBJC_METHOD);
978
0
  RECORD(DECL_OBJC_INTERFACE);
979
0
  RECORD(DECL_OBJC_PROTOCOL);
980
0
  RECORD(DECL_OBJC_IVAR);
981
0
  RECORD(DECL_OBJC_AT_DEFS_FIELD);
982
0
  RECORD(DECL_OBJC_CATEGORY);
983
0
  RECORD(DECL_OBJC_CATEGORY_IMPL);
984
0
  RECORD(DECL_OBJC_IMPLEMENTATION);
985
0
  RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
986
0
  RECORD(DECL_OBJC_PROPERTY);
987
0
  RECORD(DECL_OBJC_PROPERTY_IMPL);
988
0
  RECORD(DECL_FIELD);
989
0
  RECORD(DECL_MS_PROPERTY);
990
0
  RECORD(DECL_VAR);
991
0
  RECORD(DECL_IMPLICIT_PARAM);
992
0
  RECORD(DECL_PARM_VAR);
993
0
  RECORD(DECL_FILE_SCOPE_ASM);
994
0
  RECORD(DECL_BLOCK);
995
0
  RECORD(DECL_CONTEXT_LEXICAL);
996
0
  RECORD(DECL_CONTEXT_VISIBLE);
997
0
  RECORD(DECL_NAMESPACE);
998
0
  RECORD(DECL_NAMESPACE_ALIAS);
999
0
  RECORD(DECL_USING);
1000
0
  RECORD(DECL_USING_SHADOW);
1001
0
  RECORD(DECL_USING_DIRECTIVE);
1002
0
  RECORD(DECL_UNRESOLVED_USING_VALUE);
1003
0
  RECORD(DECL_UNRESOLVED_USING_TYPENAME);
1004
0
  RECORD(DECL_LINKAGE_SPEC);
1005
0
  RECORD(DECL_CXX_RECORD);
1006
0
  RECORD(DECL_CXX_METHOD);
1007
0
  RECORD(DECL_CXX_CONSTRUCTOR);
1008
0
  RECORD(DECL_CXX_DESTRUCTOR);
1009
0
  RECORD(DECL_CXX_CONVERSION);
1010
0
  RECORD(DECL_ACCESS_SPEC);
1011
0
  RECORD(DECL_FRIEND);
1012
0
  RECORD(DECL_FRIEND_TEMPLATE);
1013
0
  RECORD(DECL_CLASS_TEMPLATE);
1014
0
  RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
1015
0
  RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
1016
0
  RECORD(DECL_VAR_TEMPLATE);
1017
0
  RECORD(DECL_VAR_TEMPLATE_SPECIALIZATION);
1018
0
  RECORD(DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION);
1019
0
  RECORD(DECL_FUNCTION_TEMPLATE);
1020
0
  RECORD(DECL_TEMPLATE_TYPE_PARM);
1021
0
  RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
1022
0
  RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
1023
0
  RECORD(DECL_CONCEPT);
1024
0
  RECORD(DECL_REQUIRES_EXPR_BODY);
1025
0
  RECORD(DECL_TYPE_ALIAS_TEMPLATE);
1026
0
  RECORD(DECL_STATIC_ASSERT);
1027
0
  RECORD(DECL_CXX_BASE_SPECIFIERS);
1028
0
  RECORD(DECL_CXX_CTOR_INITIALIZERS);
1029
0
  RECORD(DECL_INDIRECTFIELD);
1030
0
  RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
1031
0
  RECORD(DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK);
1032
0
  RECORD(DECL_IMPORT);
1033
0
  RECORD(DECL_OMP_THREADPRIVATE);
1034
0
  RECORD(DECL_EMPTY);
1035
0
  RECORD(DECL_OBJC_TYPE_PARAM);
1036
0
  RECORD(DECL_OMP_CAPTUREDEXPR);
1037
0
  RECORD(DECL_PRAGMA_COMMENT);
1038
0
  RECORD(DECL_PRAGMA_DETECT_MISMATCH);
1039
0
  RECORD(DECL_OMP_DECLARE_REDUCTION);
1040
0
  RECORD(DECL_OMP_ALLOCATE);
1041
0
  RECORD(DECL_HLSL_BUFFER);
1042
1043
  // Statements and Exprs can occur in the Decls and Types block.
1044
0
  AddStmtsExprs(Stream, Record);
1045
1046
0
  BLOCK(PREPROCESSOR_DETAIL_BLOCK);
1047
0
  RECORD(PPD_MACRO_EXPANSION);
1048
0
  RECORD(PPD_MACRO_DEFINITION);
1049
0
  RECORD(PPD_INCLUSION_DIRECTIVE);
1050
1051
  // Decls and Types block.
1052
0
  BLOCK(EXTENSION_BLOCK);
1053
0
  RECORD(EXTENSION_METADATA);
1054
1055
0
  BLOCK(UNHASHED_CONTROL_BLOCK);
1056
0
  RECORD(SIGNATURE);
1057
0
  RECORD(AST_BLOCK_HASH);
1058
0
  RECORD(DIAGNOSTIC_OPTIONS);
1059
0
  RECORD(HEADER_SEARCH_PATHS);
1060
0
  RECORD(DIAG_PRAGMA_MAPPINGS);
1061
1062
0
#undef RECORD
1063
0
#undef BLOCK
1064
0
  Stream.ExitBlock();
1065
0
}
1066
1067
/// Prepares a path for being written to an AST file by converting it
1068
/// to an absolute path and removing nested './'s.
1069
///
1070
/// \return \c true if the path was changed.
1071
static bool cleanPathForOutput(FileManager &FileMgr,
1072
0
                               SmallVectorImpl<char> &Path) {
1073
0
  bool Changed = FileMgr.makeAbsolutePath(Path);
1074
0
  return Changed | llvm::sys::path::remove_dots(Path);
1075
0
}
1076
1077
/// Adjusts the given filename to only write out the portion of the
1078
/// filename that is not part of the system root directory.
1079
///
1080
/// \param Filename the file name to adjust.
1081
///
1082
/// \param BaseDir When non-NULL, the PCH file is a relocatable AST file and
1083
/// the returned filename will be adjusted by this root directory.
1084
///
1085
/// \returns either the original filename (if it needs no adjustment) or the
1086
/// adjusted filename (which points into the @p Filename parameter).
1087
static const char *
1088
0
adjustFilenameForRelocatableAST(const char *Filename, StringRef BaseDir) {
1089
0
  assert(Filename && "No file name to adjust?");
1090
1091
0
  if (BaseDir.empty())
1092
0
    return Filename;
1093
1094
  // Verify that the filename and the system root have the same prefix.
1095
0
  unsigned Pos = 0;
1096
0
  for (; Filename[Pos] && Pos < BaseDir.size(); ++Pos)
1097
0
    if (Filename[Pos] != BaseDir[Pos])
1098
0
      return Filename; // Prefixes don't match.
1099
1100
  // We hit the end of the filename before we hit the end of the system root.
1101
0
  if (!Filename[Pos])
1102
0
    return Filename;
1103
1104
  // If there's not a path separator at the end of the base directory nor
1105
  // immediately after it, then this isn't within the base directory.
1106
0
  if (!llvm::sys::path::is_separator(Filename[Pos])) {
1107
0
    if (!llvm::sys::path::is_separator(BaseDir.back()))
1108
0
      return Filename;
1109
0
  } else {
1110
    // If the file name has a '/' at the current position, skip over the '/'.
1111
    // We distinguish relative paths from absolute paths by the
1112
    // absence of '/' at the beginning of relative paths.
1113
    //
1114
    // FIXME: This is wrong. We distinguish them by asking if the path is
1115
    // absolute, which isn't the same thing. And there might be multiple '/'s
1116
    // in a row. Use a better mechanism to indicate whether we have emitted an
1117
    // absolute or relative path.
1118
0
    ++Pos;
1119
0
  }
1120
1121
0
  return Filename + Pos;
1122
0
}
1123
1124
std::pair<ASTFileSignature, ASTFileSignature>
1125
0
ASTWriter::createSignature() const {
1126
0
  StringRef AllBytes(Buffer.data(), Buffer.size());
1127
1128
0
  llvm::SHA1 Hasher;
1129
0
  Hasher.update(AllBytes.slice(ASTBlockRange.first, ASTBlockRange.second));
1130
0
  ASTFileSignature ASTBlockHash = ASTFileSignature::create(Hasher.result());
1131
1132
  // Add the remaining bytes:
1133
  //  1. Before the unhashed control block.
1134
0
  Hasher.update(AllBytes.slice(0, UnhashedControlBlockRange.first));
1135
  //  2. Between the unhashed control block and the AST block.
1136
0
  Hasher.update(
1137
0
      AllBytes.slice(UnhashedControlBlockRange.second, ASTBlockRange.first));
1138
  //  3. After the AST block.
1139
0
  Hasher.update(AllBytes.slice(ASTBlockRange.second, StringRef::npos));
1140
0
  ASTFileSignature Signature = ASTFileSignature::create(Hasher.result());
1141
1142
0
  return std::make_pair(ASTBlockHash, Signature);
1143
0
}
1144
1145
0
ASTFileSignature ASTWriter::backpatchSignature() {
1146
0
  if (!WritingModule ||
1147
0
      !PP->getHeaderSearchInfo().getHeaderSearchOpts().ModulesHashContent)
1148
0
    return {};
1149
1150
  // For implicit modules, write the hash of the PCM as its signature.
1151
1152
0
  auto BackpatchSignatureAt = [&](const ASTFileSignature &S, uint64_t BitNo) {
1153
0
    for (uint8_t Byte : S) {
1154
0
      Stream.BackpatchByte(BitNo, Byte);
1155
0
      BitNo += 8;
1156
0
    }
1157
0
  };
1158
1159
0
  ASTFileSignature ASTBlockHash;
1160
0
  ASTFileSignature Signature;
1161
0
  std::tie(ASTBlockHash, Signature) = createSignature();
1162
1163
0
  BackpatchSignatureAt(ASTBlockHash, ASTBlockHashOffset);
1164
0
  BackpatchSignatureAt(Signature, SignatureOffset);
1165
1166
0
  return Signature;
1167
0
}
1168
1169
void ASTWriter::writeUnhashedControlBlock(Preprocessor &PP,
1170
0
                                          ASTContext &Context) {
1171
0
  using namespace llvm;
1172
1173
  // Flush first to prepare the PCM hash (signature).
1174
0
  Stream.FlushToWord();
1175
0
  UnhashedControlBlockRange.first = Stream.GetCurrentBitNo() >> 3;
1176
1177
  // Enter the block and prepare to write records.
1178
0
  RecordData Record;
1179
0
  Stream.EnterSubblock(UNHASHED_CONTROL_BLOCK_ID, 5);
1180
1181
  // For implicit modules, write the hash of the PCM as its signature.
1182
0
  if (WritingModule &&
1183
0
      PP.getHeaderSearchInfo().getHeaderSearchOpts().ModulesHashContent) {
1184
    // At this point, we don't know the actual signature of the file or the AST
1185
    // block - we're only able to compute those at the end of the serialization
1186
    // process. Let's store dummy signatures for now, and replace them with the
1187
    // real ones later on.
1188
    // The bitstream VBR-encodes record elements, which makes backpatching them
1189
    // really difficult. Let's store the signatures as blobs instead - they are
1190
    // guaranteed to be word-aligned, and we control their format/encoding.
1191
0
    auto Dummy = ASTFileSignature::createDummy();
1192
0
    SmallString<128> Blob{Dummy.begin(), Dummy.end()};
1193
1194
0
    auto Abbrev = std::make_shared<BitCodeAbbrev>();
1195
0
    Abbrev->Add(BitCodeAbbrevOp(AST_BLOCK_HASH));
1196
0
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1197
0
    unsigned ASTBlockHashAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
1198
1199
0
    Abbrev = std::make_shared<BitCodeAbbrev>();
1200
0
    Abbrev->Add(BitCodeAbbrevOp(SIGNATURE));
1201
0
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1202
0
    unsigned SignatureAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
1203
1204
0
    Record.push_back(AST_BLOCK_HASH);
1205
0
    Stream.EmitRecordWithBlob(ASTBlockHashAbbrev, Record, Blob);
1206
0
    ASTBlockHashOffset = Stream.GetCurrentBitNo() - Blob.size() * 8;
1207
0
    Record.clear();
1208
1209
0
    Record.push_back(SIGNATURE);
1210
0
    Stream.EmitRecordWithBlob(SignatureAbbrev, Record, Blob);
1211
0
    SignatureOffset = Stream.GetCurrentBitNo() - Blob.size() * 8;
1212
0
    Record.clear();
1213
0
  }
1214
1215
0
  const auto &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1216
1217
  // Diagnostic options.
1218
0
  const auto &Diags = Context.getDiagnostics();
1219
0
  const DiagnosticOptions &DiagOpts = Diags.getDiagnosticOptions();
1220
0
  if (!HSOpts.ModulesSkipDiagnosticOptions) {
1221
0
#define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name);
1222
0
#define ENUM_DIAGOPT(Name, Type, Bits, Default)                                \
1223
0
  Record.push_back(static_cast<unsigned>(DiagOpts.get##Name()));
1224
0
#include "clang/Basic/DiagnosticOptions.def"
1225
0
    Record.push_back(DiagOpts.Warnings.size());
1226
0
    for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; ++I)
1227
0
      AddString(DiagOpts.Warnings[I], Record);
1228
0
    Record.push_back(DiagOpts.Remarks.size());
1229
0
    for (unsigned I = 0, N = DiagOpts.Remarks.size(); I != N; ++I)
1230
0
      AddString(DiagOpts.Remarks[I], Record);
1231
    // Note: we don't serialize the log or serialization file names, because
1232
    // they are generally transient files and will almost always be overridden.
1233
0
    Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record);
1234
0
    Record.clear();
1235
0
  }
1236
1237
  // Header search paths.
1238
0
  if (!HSOpts.ModulesSkipHeaderSearchPaths) {
1239
    // Include entries.
1240
0
    Record.push_back(HSOpts.UserEntries.size());
1241
0
    for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; ++I) {
1242
0
      const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I];
1243
0
      AddString(Entry.Path, Record);
1244
0
      Record.push_back(static_cast<unsigned>(Entry.Group));
1245
0
      Record.push_back(Entry.IsFramework);
1246
0
      Record.push_back(Entry.IgnoreSysRoot);
1247
0
    }
1248
1249
    // System header prefixes.
1250
0
    Record.push_back(HSOpts.SystemHeaderPrefixes.size());
1251
0
    for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; ++I) {
1252
0
      AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record);
1253
0
      Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader);
1254
0
    }
1255
1256
    // VFS overlay files.
1257
0
    Record.push_back(HSOpts.VFSOverlayFiles.size());
1258
0
    for (StringRef VFSOverlayFile : HSOpts.VFSOverlayFiles)
1259
0
      AddString(VFSOverlayFile, Record);
1260
1261
0
    Stream.EmitRecord(HEADER_SEARCH_PATHS, Record);
1262
0
  }
1263
1264
0
  if (!HSOpts.ModulesSkipPragmaDiagnosticMappings)
1265
0
    WritePragmaDiagnosticMappings(Diags, /* isModule = */ WritingModule);
1266
1267
  // Header search entry usage.
1268
0
  auto HSEntryUsage = PP.getHeaderSearchInfo().computeUserEntryUsage();
1269
0
  auto Abbrev = std::make_shared<BitCodeAbbrev>();
1270
0
  Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_ENTRY_USAGE));
1271
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // Number of bits.
1272
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));      // Bit vector.
1273
0
  unsigned HSUsageAbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1274
0
  {
1275
0
    RecordData::value_type Record[] = {HEADER_SEARCH_ENTRY_USAGE,
1276
0
                                       HSEntryUsage.size()};
1277
0
    Stream.EmitRecordWithBlob(HSUsageAbbrevCode, Record, bytes(HSEntryUsage));
1278
0
  }
1279
1280
  // Leave the options block.
1281
0
  Stream.ExitBlock();
1282
0
  UnhashedControlBlockRange.second = Stream.GetCurrentBitNo() >> 3;
1283
0
}
1284
1285
/// Write the control block.
1286
void ASTWriter::WriteControlBlock(Preprocessor &PP, ASTContext &Context,
1287
0
                                  StringRef isysroot) {
1288
0
  using namespace llvm;
1289
1290
0
  Stream.EnterSubblock(CONTROL_BLOCK_ID, 5);
1291
0
  RecordData Record;
1292
1293
  // Metadata
1294
0
  auto MetadataAbbrev = std::make_shared<BitCodeAbbrev>();
1295
0
  MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA));
1296
0
  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major
1297
0
  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor
1298
0
  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj.
1299
0
  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min.
1300
0
  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
1301
  // Standard C++ module
1302
0
  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1303
0
  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Timestamps
1304
0
  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors
1305
0
  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
1306
0
  unsigned MetadataAbbrevCode = Stream.EmitAbbrev(std::move(MetadataAbbrev));
1307
0
  assert((!WritingModule || isysroot.empty()) &&
1308
0
         "writing module as a relocatable PCH?");
1309
0
  {
1310
0
    RecordData::value_type Record[] = {METADATA,
1311
0
                                       VERSION_MAJOR,
1312
0
                                       VERSION_MINOR,
1313
0
                                       CLANG_VERSION_MAJOR,
1314
0
                                       CLANG_VERSION_MINOR,
1315
0
                                       !isysroot.empty(),
1316
0
                                       isWritingStdCXXNamedModules(),
1317
0
                                       IncludeTimestamps,
1318
0
                                       ASTHasCompilerErrors};
1319
0
    Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record,
1320
0
                              getClangFullRepositoryVersion());
1321
0
  }
1322
1323
0
  if (WritingModule) {
1324
    // Module name
1325
0
    auto Abbrev = std::make_shared<BitCodeAbbrev>();
1326
0
    Abbrev->Add(BitCodeAbbrevOp(MODULE_NAME));
1327
0
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
1328
0
    unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1329
0
    RecordData::value_type Record[] = {MODULE_NAME};
1330
0
    Stream.EmitRecordWithBlob(AbbrevCode, Record, WritingModule->Name);
1331
0
  }
1332
1333
0
  if (WritingModule && WritingModule->Directory) {
1334
0
    SmallString<128> BaseDir;
1335
0
    if (PP.getHeaderSearchInfo().getHeaderSearchOpts().ModuleFileHomeIsCwd) {
1336
      // Use the current working directory as the base path for all inputs.
1337
0
      auto CWD =
1338
0
          Context.getSourceManager().getFileManager().getOptionalDirectoryRef(
1339
0
              ".");
1340
0
      BaseDir.assign(CWD->getName());
1341
0
    } else {
1342
0
      BaseDir.assign(WritingModule->Directory->getName());
1343
0
    }
1344
0
    cleanPathForOutput(Context.getSourceManager().getFileManager(), BaseDir);
1345
1346
    // If the home of the module is the current working directory, then we
1347
    // want to pick up the cwd of the build process loading the module, not
1348
    // our cwd, when we load this module.
1349
0
    if (!PP.getHeaderSearchInfo().getHeaderSearchOpts().ModuleFileHomeIsCwd &&
1350
0
        (!PP.getHeaderSearchInfo()
1351
0
              .getHeaderSearchOpts()
1352
0
              .ModuleMapFileHomeIsCwd ||
1353
0
         WritingModule->Directory->getName() != StringRef("."))) {
1354
      // Module directory.
1355
0
      auto Abbrev = std::make_shared<BitCodeAbbrev>();
1356
0
      Abbrev->Add(BitCodeAbbrevOp(MODULE_DIRECTORY));
1357
0
      Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Directory
1358
0
      unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1359
1360
0
      RecordData::value_type Record[] = {MODULE_DIRECTORY};
1361
0
      Stream.EmitRecordWithBlob(AbbrevCode, Record, BaseDir);
1362
0
    }
1363
1364
    // Write out all other paths relative to the base directory if possible.
1365
0
    BaseDirectory.assign(BaseDir.begin(), BaseDir.end());
1366
0
  } else if (!isysroot.empty()) {
1367
    // Write out paths relative to the sysroot if possible.
1368
0
    BaseDirectory = std::string(isysroot);
1369
0
  }
1370
1371
  // Module map file
1372
0
  if (WritingModule && WritingModule->Kind == Module::ModuleMapModule) {
1373
0
    Record.clear();
1374
1375
0
    auto &Map = PP.getHeaderSearchInfo().getModuleMap();
1376
0
    AddPath(WritingModule->PresumedModuleMapFile.empty()
1377
0
                ? Map.getModuleMapFileForUniquing(WritingModule)
1378
0
                      ->getNameAsRequested()
1379
0
                : StringRef(WritingModule->PresumedModuleMapFile),
1380
0
            Record);
1381
1382
    // Additional module map files.
1383
0
    if (auto *AdditionalModMaps =
1384
0
            Map.getAdditionalModuleMapFiles(WritingModule)) {
1385
0
      Record.push_back(AdditionalModMaps->size());
1386
0
      SmallVector<FileEntryRef, 1> ModMaps(AdditionalModMaps->begin(),
1387
0
                                           AdditionalModMaps->end());
1388
0
      llvm::sort(ModMaps, [](FileEntryRef A, FileEntryRef B) {
1389
0
        return A.getName() < B.getName();
1390
0
      });
1391
0
      for (FileEntryRef F : ModMaps)
1392
0
        AddPath(F.getName(), Record);
1393
0
    } else {
1394
0
      Record.push_back(0);
1395
0
    }
1396
1397
0
    Stream.EmitRecord(MODULE_MAP_FILE, Record);
1398
0
  }
1399
1400
  // Imports
1401
0
  if (Chain) {
1402
0
    serialization::ModuleManager &Mgr = Chain->getModuleManager();
1403
0
    Record.clear();
1404
1405
0
    for (ModuleFile &M : Mgr) {
1406
      // Skip modules that weren't directly imported.
1407
0
      if (!M.isDirectlyImported())
1408
0
        continue;
1409
1410
0
      Record.push_back((unsigned)M.Kind); // FIXME: Stable encoding
1411
0
      Record.push_back(M.StandardCXXModule);
1412
0
      AddSourceLocation(M.ImportLoc, Record);
1413
1414
      // We don't want to hard code the information about imported modules
1415
      // in the C++20 named modules.
1416
0
      if (!M.StandardCXXModule) {
1417
        // If we have calculated signature, there is no need to store
1418
        // the size or timestamp.
1419
0
        Record.push_back(M.Signature ? 0 : M.File.getSize());
1420
0
        Record.push_back(M.Signature ? 0 : getTimestampForOutput(M.File));
1421
0
        llvm::append_range(Record, M.Signature);
1422
0
      }
1423
1424
0
      AddString(M.ModuleName, Record);
1425
1426
0
      if (!M.StandardCXXModule)
1427
0
        AddPath(M.FileName, Record);
1428
0
    }
1429
0
    Stream.EmitRecord(IMPORTS, Record);
1430
0
  }
1431
1432
  // Write the options block.
1433
0
  Stream.EnterSubblock(OPTIONS_BLOCK_ID, 4);
1434
1435
  // Language options.
1436
0
  Record.clear();
1437
0
  const LangOptions &LangOpts = Context.getLangOpts();
1438
0
#define LANGOPT(Name, Bits, Default, Description) \
1439
0
  Record.push_back(LangOpts.Name);
1440
0
#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
1441
0
  Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
1442
0
#include "clang/Basic/LangOptions.def"
1443
0
#define SANITIZER(NAME, ID)                                                    \
1444
0
  Record.push_back(LangOpts.Sanitize.has(SanitizerKind::ID));
1445
0
#include "clang/Basic/Sanitizers.def"
1446
1447
0
  Record.push_back(LangOpts.ModuleFeatures.size());
1448
0
  for (StringRef Feature : LangOpts.ModuleFeatures)
1449
0
    AddString(Feature, Record);
1450
1451
0
  Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind());
1452
0
  AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record);
1453
1454
0
  AddString(LangOpts.CurrentModule, Record);
1455
1456
  // Comment options.
1457
0
  Record.push_back(LangOpts.CommentOpts.BlockCommandNames.size());
1458
0
  for (const auto &I : LangOpts.CommentOpts.BlockCommandNames) {
1459
0
    AddString(I, Record);
1460
0
  }
1461
0
  Record.push_back(LangOpts.CommentOpts.ParseAllComments);
1462
1463
  // OpenMP offloading options.
1464
0
  Record.push_back(LangOpts.OMPTargetTriples.size());
1465
0
  for (auto &T : LangOpts.OMPTargetTriples)
1466
0
    AddString(T.getTriple(), Record);
1467
1468
0
  AddString(LangOpts.OMPHostIRFile, Record);
1469
1470
0
  Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1471
1472
  // Target options.
1473
0
  Record.clear();
1474
0
  const TargetInfo &Target = Context.getTargetInfo();
1475
0
  const TargetOptions &TargetOpts = Target.getTargetOpts();
1476
0
  AddString(TargetOpts.Triple, Record);
1477
0
  AddString(TargetOpts.CPU, Record);
1478
0
  AddString(TargetOpts.TuneCPU, Record);
1479
0
  AddString(TargetOpts.ABI, Record);
1480
0
  Record.push_back(TargetOpts.FeaturesAsWritten.size());
1481
0
  for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; ++I) {
1482
0
    AddString(TargetOpts.FeaturesAsWritten[I], Record);
1483
0
  }
1484
0
  Record.push_back(TargetOpts.Features.size());
1485
0
  for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; ++I) {
1486
0
    AddString(TargetOpts.Features[I], Record);
1487
0
  }
1488
0
  Stream.EmitRecord(TARGET_OPTIONS, Record);
1489
1490
  // File system options.
1491
0
  Record.clear();
1492
0
  const FileSystemOptions &FSOpts =
1493
0
      Context.getSourceManager().getFileManager().getFileSystemOpts();
1494
0
  AddString(FSOpts.WorkingDir, Record);
1495
0
  Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record);
1496
1497
  // Header search options.
1498
0
  Record.clear();
1499
0
  const HeaderSearchOptions &HSOpts =
1500
0
      PP.getHeaderSearchInfo().getHeaderSearchOpts();
1501
1502
0
  AddString(HSOpts.Sysroot, Record);
1503
0
  AddString(HSOpts.ResourceDir, Record);
1504
0
  AddString(HSOpts.ModuleCachePath, Record);
1505
0
  AddString(HSOpts.ModuleUserBuildPath, Record);
1506
0
  Record.push_back(HSOpts.DisableModuleHash);
1507
0
  Record.push_back(HSOpts.ImplicitModuleMaps);
1508
0
  Record.push_back(HSOpts.ModuleMapFileHomeIsCwd);
1509
0
  Record.push_back(HSOpts.EnablePrebuiltImplicitModules);
1510
0
  Record.push_back(HSOpts.UseBuiltinIncludes);
1511
0
  Record.push_back(HSOpts.UseStandardSystemIncludes);
1512
0
  Record.push_back(HSOpts.UseStandardCXXIncludes);
1513
0
  Record.push_back(HSOpts.UseLibcxx);
1514
  // Write out the specific module cache path that contains the module files.
1515
0
  AddString(PP.getHeaderSearchInfo().getModuleCachePath(), Record);
1516
0
  Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record);
1517
1518
  // Preprocessor options.
1519
0
  Record.clear();
1520
0
  const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts();
1521
1522
  // If we're building an implicit module with a context hash, the importer is
1523
  // guaranteed to have the same macros defined on the command line. Skip
1524
  // writing them.
1525
0
  bool SkipMacros = BuildingImplicitModule && !HSOpts.DisableModuleHash;
1526
0
  bool WriteMacros = !SkipMacros;
1527
0
  Record.push_back(WriteMacros);
1528
0
  if (WriteMacros) {
1529
    // Macro definitions.
1530
0
    Record.push_back(PPOpts.Macros.size());
1531
0
    for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
1532
0
      AddString(PPOpts.Macros[I].first, Record);
1533
0
      Record.push_back(PPOpts.Macros[I].second);
1534
0
    }
1535
0
  }
1536
1537
  // Includes
1538
0
  Record.push_back(PPOpts.Includes.size());
1539
0
  for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I)
1540
0
    AddString(PPOpts.Includes[I], Record);
1541
1542
  // Macro includes
1543
0
  Record.push_back(PPOpts.MacroIncludes.size());
1544
0
  for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; ++I)
1545
0
    AddString(PPOpts.MacroIncludes[I], Record);
1546
1547
0
  Record.push_back(PPOpts.UsePredefines);
1548
  // Detailed record is important since it is used for the module cache hash.
1549
0
  Record.push_back(PPOpts.DetailedRecord);
1550
0
  AddString(PPOpts.ImplicitPCHInclude, Record);
1551
0
  Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary));
1552
0
  Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record);
1553
1554
  // Leave the options block.
1555
0
  Stream.ExitBlock();
1556
1557
  // Original file name and file ID
1558
0
  SourceManager &SM = Context.getSourceManager();
1559
0
  if (auto MainFile = SM.getFileEntryRefForID(SM.getMainFileID())) {
1560
0
    auto FileAbbrev = std::make_shared<BitCodeAbbrev>();
1561
0
    FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE));
1562
0
    FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID
1563
0
    FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1564
0
    unsigned FileAbbrevCode = Stream.EmitAbbrev(std::move(FileAbbrev));
1565
1566
0
    Record.clear();
1567
0
    Record.push_back(ORIGINAL_FILE);
1568
0
    AddFileID(SM.getMainFileID(), Record);
1569
0
    EmitRecordWithPath(FileAbbrevCode, Record, MainFile->getName());
1570
0
  }
1571
1572
0
  Record.clear();
1573
0
  AddFileID(SM.getMainFileID(), Record);
1574
0
  Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
1575
1576
0
  WriteInputFiles(Context.SourceMgr,
1577
0
                  PP.getHeaderSearchInfo().getHeaderSearchOpts());
1578
0
  Stream.ExitBlock();
1579
0
}
1580
1581
namespace  {
1582
1583
/// An input file.
1584
struct InputFileEntry {
1585
  FileEntryRef File;
1586
  bool IsSystemFile;
1587
  bool IsTransient;
1588
  bool BufferOverridden;
1589
  bool IsTopLevel;
1590
  bool IsModuleMap;
1591
  uint32_t ContentHash[2];
1592
1593
0
  InputFileEntry(FileEntryRef File) : File(File) {}
1594
};
1595
1596
} // namespace
1597
1598
void ASTWriter::WriteInputFiles(SourceManager &SourceMgr,
1599
0
                                HeaderSearchOptions &HSOpts) {
1600
0
  using namespace llvm;
1601
1602
0
  Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4);
1603
1604
  // Create input-file abbreviation.
1605
0
  auto IFAbbrev = std::make_shared<BitCodeAbbrev>();
1606
0
  IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE));
1607
0
  IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
1608
0
  IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1609
0
  IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
1610
0
  IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden
1611
0
  IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Transient
1612
0
  IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Top-level
1613
0
  IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Module map
1614
0
  IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // Name as req. len
1615
0
  IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name as req. + name
1616
0
  unsigned IFAbbrevCode = Stream.EmitAbbrev(std::move(IFAbbrev));
1617
1618
  // Create input file hash abbreviation.
1619
0
  auto IFHAbbrev = std::make_shared<BitCodeAbbrev>();
1620
0
  IFHAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_HASH));
1621
0
  IFHAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1622
0
  IFHAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1623
0
  unsigned IFHAbbrevCode = Stream.EmitAbbrev(std::move(IFHAbbrev));
1624
1625
0
  uint64_t InputFilesOffsetBase = Stream.GetCurrentBitNo();
1626
1627
  // Get all ContentCache objects for files.
1628
0
  std::vector<InputFileEntry> UserFiles;
1629
0
  std::vector<InputFileEntry> SystemFiles;
1630
0
  for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) {
1631
    // Get this source location entry.
1632
0
    const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
1633
0
    assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc);
1634
1635
    // We only care about file entries that were not overridden.
1636
0
    if (!SLoc->isFile())
1637
0
      continue;
1638
0
    const SrcMgr::FileInfo &File = SLoc->getFile();
1639
0
    const SrcMgr::ContentCache *Cache = &File.getContentCache();
1640
0
    if (!Cache->OrigEntry)
1641
0
      continue;
1642
1643
    // Do not emit input files that do not affect current module.
1644
0
    if (!IsSLocAffecting[I])
1645
0
      continue;
1646
1647
0
    InputFileEntry Entry(*Cache->OrigEntry);
1648
0
    Entry.IsSystemFile = isSystem(File.getFileCharacteristic());
1649
0
    Entry.IsTransient = Cache->IsTransient;
1650
0
    Entry.BufferOverridden = Cache->BufferOverridden;
1651
0
    Entry.IsTopLevel = File.getIncludeLoc().isInvalid();
1652
0
    Entry.IsModuleMap = isModuleMap(File.getFileCharacteristic());
1653
1654
0
    auto ContentHash = hash_code(-1);
1655
0
    if (PP->getHeaderSearchInfo()
1656
0
            .getHeaderSearchOpts()
1657
0
            .ValidateASTInputFilesContent) {
1658
0
      auto MemBuff = Cache->getBufferIfLoaded();
1659
0
      if (MemBuff)
1660
0
        ContentHash = hash_value(MemBuff->getBuffer());
1661
0
      else
1662
0
        PP->Diag(SourceLocation(), diag::err_module_unable_to_hash_content)
1663
0
            << Entry.File.getName();
1664
0
    }
1665
0
    auto CH = llvm::APInt(64, ContentHash);
1666
0
    Entry.ContentHash[0] =
1667
0
        static_cast<uint32_t>(CH.getLoBits(32).getZExtValue());
1668
0
    Entry.ContentHash[1] =
1669
0
        static_cast<uint32_t>(CH.getHiBits(32).getZExtValue());
1670
1671
0
    if (Entry.IsSystemFile)
1672
0
      SystemFiles.push_back(Entry);
1673
0
    else
1674
0
      UserFiles.push_back(Entry);
1675
0
  }
1676
1677
  // User files go at the front, system files at the back.
1678
0
  auto SortedFiles = llvm::concat<InputFileEntry>(std::move(UserFiles),
1679
0
                                                  std::move(SystemFiles));
1680
1681
0
  unsigned UserFilesNum = 0;
1682
  // Write out all of the input files.
1683
0
  std::vector<uint64_t> InputFileOffsets;
1684
0
  for (const auto &Entry : SortedFiles) {
1685
0
    uint32_t &InputFileID = InputFileIDs[Entry.File];
1686
0
    if (InputFileID != 0)
1687
0
      continue; // already recorded this file.
1688
1689
    // Record this entry's offset.
1690
0
    InputFileOffsets.push_back(Stream.GetCurrentBitNo() - InputFilesOffsetBase);
1691
1692
0
    InputFileID = InputFileOffsets.size();
1693
1694
0
    if (!Entry.IsSystemFile)
1695
0
      ++UserFilesNum;
1696
1697
    // Emit size/modification time for this file.
1698
    // And whether this file was overridden.
1699
0
    {
1700
0
      SmallString<128> NameAsRequested = Entry.File.getNameAsRequested();
1701
0
      SmallString<128> Name = Entry.File.getName();
1702
1703
0
      PreparePathForOutput(NameAsRequested);
1704
0
      PreparePathForOutput(Name);
1705
1706
0
      if (Name == NameAsRequested)
1707
0
        Name.clear();
1708
1709
0
      RecordData::value_type Record[] = {
1710
0
          INPUT_FILE,
1711
0
          InputFileOffsets.size(),
1712
0
          (uint64_t)Entry.File.getSize(),
1713
0
          (uint64_t)getTimestampForOutput(Entry.File),
1714
0
          Entry.BufferOverridden,
1715
0
          Entry.IsTransient,
1716
0
          Entry.IsTopLevel,
1717
0
          Entry.IsModuleMap,
1718
0
          NameAsRequested.size()};
1719
1720
0
      Stream.EmitRecordWithBlob(IFAbbrevCode, Record,
1721
0
                                (NameAsRequested + Name).str());
1722
0
    }
1723
1724
    // Emit content hash for this file.
1725
0
    {
1726
0
      RecordData::value_type Record[] = {INPUT_FILE_HASH, Entry.ContentHash[0],
1727
0
                                         Entry.ContentHash[1]};
1728
0
      Stream.EmitRecordWithAbbrev(IFHAbbrevCode, Record);
1729
0
    }
1730
0
  }
1731
1732
0
  Stream.ExitBlock();
1733
1734
  // Create input file offsets abbreviation.
1735
0
  auto OffsetsAbbrev = std::make_shared<BitCodeAbbrev>();
1736
0
  OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS));
1737
0
  OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files
1738
0
  OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system
1739
                                                                //   input files
1740
0
  OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));   // Array
1741
0
  unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(std::move(OffsetsAbbrev));
1742
1743
  // Write input file offsets.
1744
0
  RecordData::value_type Record[] = {INPUT_FILE_OFFSETS,
1745
0
                                     InputFileOffsets.size(), UserFilesNum};
1746
0
  Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, bytes(InputFileOffsets));
1747
0
}
1748
1749
//===----------------------------------------------------------------------===//
1750
// Source Manager Serialization
1751
//===----------------------------------------------------------------------===//
1752
1753
/// Create an abbreviation for the SLocEntry that refers to a
1754
/// file.
1755
0
static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
1756
0
  using namespace llvm;
1757
1758
0
  auto Abbrev = std::make_shared<BitCodeAbbrev>();
1759
0
  Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
1760
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1761
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1762
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
1763
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1764
  // FileEntry fields.
1765
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID
1766
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
1767
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
1768
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
1769
0
  return Stream.EmitAbbrev(std::move(Abbrev));
1770
0
}
1771
1772
/// Create an abbreviation for the SLocEntry that refers to a
1773
/// buffer.
1774
0
static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
1775
0
  using namespace llvm;
1776
1777
0
  auto Abbrev = std::make_shared<BitCodeAbbrev>();
1778
0
  Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
1779
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1780
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1781
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
1782
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1783
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
1784
0
  return Stream.EmitAbbrev(std::move(Abbrev));
1785
0
}
1786
1787
/// Create an abbreviation for the SLocEntry that refers to a
1788
/// buffer's blob.
1789
static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream,
1790
0
                                           bool Compressed) {
1791
0
  using namespace llvm;
1792
1793
0
  auto Abbrev = std::make_shared<BitCodeAbbrev>();
1794
0
  Abbrev->Add(BitCodeAbbrevOp(Compressed ? SM_SLOC_BUFFER_BLOB_COMPRESSED
1795
0
                                         : SM_SLOC_BUFFER_BLOB));
1796
0
  if (Compressed)
1797
0
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Uncompressed size
1798
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
1799
0
  return Stream.EmitAbbrev(std::move(Abbrev));
1800
0
}
1801
1802
/// Create an abbreviation for the SLocEntry that refers to a macro
1803
/// expansion.
1804
0
static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
1805
0
  using namespace llvm;
1806
1807
0
  auto Abbrev = std::make_shared<BitCodeAbbrev>();
1808
0
  Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
1809
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1810
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1811
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Start location
1812
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // End location
1813
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Is token range
1814
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
1815
0
  return Stream.EmitAbbrev(std::move(Abbrev));
1816
0
}
1817
1818
/// Emit key length and data length as ULEB-encoded data, and return them as a
1819
/// pair.
1820
static std::pair<unsigned, unsigned>
1821
0
emitULEBKeyDataLength(unsigned KeyLen, unsigned DataLen, raw_ostream &Out) {
1822
0
  llvm::encodeULEB128(KeyLen, Out);
1823
0
  llvm::encodeULEB128(DataLen, Out);
1824
0
  return std::make_pair(KeyLen, DataLen);
1825
0
}
1826
1827
namespace {
1828
1829
  // Trait used for the on-disk hash table of header search information.
1830
  class HeaderFileInfoTrait {
1831
    ASTWriter &Writer;
1832
1833
    // Keep track of the framework names we've used during serialization.
1834
    SmallString<128> FrameworkStringData;
1835
    llvm::StringMap<unsigned> FrameworkNameOffset;
1836
1837
  public:
1838
0
    HeaderFileInfoTrait(ASTWriter &Writer) : Writer(Writer) {}
1839
1840
    struct key_type {
1841
      StringRef Filename;
1842
      off_t Size;
1843
      time_t ModTime;
1844
    };
1845
    using key_type_ref = const key_type &;
1846
1847
    using UnresolvedModule =
1848
        llvm::PointerIntPair<Module *, 2, ModuleMap::ModuleHeaderRole>;
1849
1850
    struct data_type {
1851
      const HeaderFileInfo &HFI;
1852
      bool AlreadyIncluded;
1853
      ArrayRef<ModuleMap::KnownHeader> KnownHeaders;
1854
      UnresolvedModule Unresolved;
1855
    };
1856
    using data_type_ref = const data_type &;
1857
1858
    using hash_value_type = unsigned;
1859
    using offset_type = unsigned;
1860
1861
0
    hash_value_type ComputeHash(key_type_ref key) {
1862
      // The hash is based only on size/time of the file, so that the reader can
1863
      // match even when symlinking or excess path elements ("foo/../", "../")
1864
      // change the form of the name. However, complete path is still the key.
1865
0
      return llvm::hash_combine(key.Size, key.ModTime);
1866
0
    }
1867
1868
    std::pair<unsigned, unsigned>
1869
0
    EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) {
1870
0
      unsigned KeyLen = key.Filename.size() + 1 + 8 + 8;
1871
0
      unsigned DataLen = 1 + 4 + 4;
1872
0
      for (auto ModInfo : Data.KnownHeaders)
1873
0
        if (Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule()))
1874
0
          DataLen += 4;
1875
0
      if (Data.Unresolved.getPointer())
1876
0
        DataLen += 4;
1877
0
      return emitULEBKeyDataLength(KeyLen, DataLen, Out);
1878
0
    }
1879
1880
0
    void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) {
1881
0
      using namespace llvm::support;
1882
1883
0
      endian::Writer LE(Out, llvm::endianness::little);
1884
0
      LE.write<uint64_t>(key.Size);
1885
0
      KeyLen -= 8;
1886
0
      LE.write<uint64_t>(key.ModTime);
1887
0
      KeyLen -= 8;
1888
0
      Out.write(key.Filename.data(), KeyLen);
1889
0
    }
1890
1891
    void EmitData(raw_ostream &Out, key_type_ref key,
1892
0
                  data_type_ref Data, unsigned DataLen) {
1893
0
      using namespace llvm::support;
1894
1895
0
      endian::Writer LE(Out, llvm::endianness::little);
1896
0
      uint64_t Start = Out.tell(); (void)Start;
1897
1898
0
      unsigned char Flags = (Data.AlreadyIncluded << 6)
1899
0
                          | (Data.HFI.isImport << 5)
1900
0
                          | (Writer.isWritingStdCXXNamedModules() ? 0 :
1901
0
                             Data.HFI.isPragmaOnce << 4)
1902
0
                          | (Data.HFI.DirInfo << 1)
1903
0
                          | Data.HFI.IndexHeaderMapHeader;
1904
0
      LE.write<uint8_t>(Flags);
1905
1906
0
      if (!Data.HFI.ControllingMacro)
1907
0
        LE.write<uint32_t>(Data.HFI.ControllingMacroID);
1908
0
      else
1909
0
        LE.write<uint32_t>(Writer.getIdentifierRef(Data.HFI.ControllingMacro));
1910
1911
0
      unsigned Offset = 0;
1912
0
      if (!Data.HFI.Framework.empty()) {
1913
        // If this header refers into a framework, save the framework name.
1914
0
        llvm::StringMap<unsigned>::iterator Pos
1915
0
          = FrameworkNameOffset.find(Data.HFI.Framework);
1916
0
        if (Pos == FrameworkNameOffset.end()) {
1917
0
          Offset = FrameworkStringData.size() + 1;
1918
0
          FrameworkStringData.append(Data.HFI.Framework);
1919
0
          FrameworkStringData.push_back(0);
1920
1921
0
          FrameworkNameOffset[Data.HFI.Framework] = Offset;
1922
0
        } else
1923
0
          Offset = Pos->second;
1924
0
      }
1925
0
      LE.write<uint32_t>(Offset);
1926
1927
0
      auto EmitModule = [&](Module *M, ModuleMap::ModuleHeaderRole Role) {
1928
0
        if (uint32_t ModID = Writer.getLocalOrImportedSubmoduleID(M)) {
1929
0
          uint32_t Value = (ModID << 3) | (unsigned)Role;
1930
0
          assert((Value >> 3) == ModID && "overflow in header module info");
1931
0
          LE.write<uint32_t>(Value);
1932
0
        }
1933
0
      };
1934
1935
0
      for (auto ModInfo : Data.KnownHeaders)
1936
0
        EmitModule(ModInfo.getModule(), ModInfo.getRole());
1937
0
      if (Data.Unresolved.getPointer())
1938
0
        EmitModule(Data.Unresolved.getPointer(), Data.Unresolved.getInt());
1939
1940
0
      assert(Out.tell() - Start == DataLen && "Wrong data length");
1941
0
    }
1942
1943
0
    const char *strings_begin() const { return FrameworkStringData.begin(); }
1944
0
    const char *strings_end() const { return FrameworkStringData.end(); }
1945
  };
1946
1947
} // namespace
1948
1949
/// Write the header search block for the list of files that
1950
///
1951
/// \param HS The header search structure to save.
1952
0
void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS) {
1953
0
  HeaderFileInfoTrait GeneratorTrait(*this);
1954
0
  llvm::OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
1955
0
  SmallVector<const char *, 4> SavedStrings;
1956
0
  unsigned NumHeaderSearchEntries = 0;
1957
1958
  // Find all unresolved headers for the current module. We generally will
1959
  // have resolved them before we get here, but not necessarily: we might be
1960
  // compiling a preprocessed module, where there is no requirement for the
1961
  // original files to exist any more.
1962
0
  const HeaderFileInfo Empty; // So we can take a reference.
1963
0
  if (WritingModule) {
1964
0
    llvm::SmallVector<Module *, 16> Worklist(1, WritingModule);
1965
0
    while (!Worklist.empty()) {
1966
0
      Module *M = Worklist.pop_back_val();
1967
      // We don't care about headers in unimportable submodules.
1968
0
      if (M->isUnimportable())
1969
0
        continue;
1970
1971
      // Map to disk files where possible, to pick up any missing stat
1972
      // information. This also means we don't need to check the unresolved
1973
      // headers list when emitting resolved headers in the first loop below.
1974
      // FIXME: It'd be preferable to avoid doing this if we were given
1975
      // sufficient stat information in the module map.
1976
0
      HS.getModuleMap().resolveHeaderDirectives(M, /*File=*/std::nullopt);
1977
1978
      // If the file didn't exist, we can still create a module if we were given
1979
      // enough information in the module map.
1980
0
      for (const auto &U : M->MissingHeaders) {
1981
        // Check that we were given enough information to build a module
1982
        // without this file existing on disk.
1983
0
        if (!U.Size || (!U.ModTime && IncludeTimestamps)) {
1984
0
          PP->Diag(U.FileNameLoc, diag::err_module_no_size_mtime_for_header)
1985
0
              << WritingModule->getFullModuleName() << U.Size.has_value()
1986
0
              << U.FileName;
1987
0
          continue;
1988
0
        }
1989
1990
        // Form the effective relative pathname for the file.
1991
0
        SmallString<128> Filename(M->Directory->getName());
1992
0
        llvm::sys::path::append(Filename, U.FileName);
1993
0
        PreparePathForOutput(Filename);
1994
1995
0
        StringRef FilenameDup = strdup(Filename.c_str());
1996
0
        SavedStrings.push_back(FilenameDup.data());
1997
1998
0
        HeaderFileInfoTrait::key_type Key = {
1999
0
            FilenameDup, *U.Size, IncludeTimestamps ? *U.ModTime : 0};
2000
0
        HeaderFileInfoTrait::data_type Data = {
2001
0
            Empty, false, {}, {M, ModuleMap::headerKindToRole(U.Kind)}};
2002
        // FIXME: Deal with cases where there are multiple unresolved header
2003
        // directives in different submodules for the same header.
2004
0
        Generator.insert(Key, Data, GeneratorTrait);
2005
0
        ++NumHeaderSearchEntries;
2006
0
      }
2007
0
      auto SubmodulesRange = M->submodules();
2008
0
      Worklist.append(SubmodulesRange.begin(), SubmodulesRange.end());
2009
0
    }
2010
0
  }
2011
2012
0
  SmallVector<OptionalFileEntryRef, 16> FilesByUID;
2013
0
  HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
2014
2015
0
  if (FilesByUID.size() > HS.header_file_size())
2016
0
    FilesByUID.resize(HS.header_file_size());
2017
2018
0
  for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
2019
0
    OptionalFileEntryRef File = FilesByUID[UID];
2020
0
    if (!File)
2021
0
      continue;
2022
2023
    // Get the file info. This will load info from the external source if
2024
    // necessary. Skip emitting this file if we have no information on it
2025
    // as a header file (in which case HFI will be null) or if it hasn't
2026
    // changed since it was loaded. Also skip it if it's for a modular header
2027
    // from a different module; in that case, we rely on the module(s)
2028
    // containing the header to provide this information.
2029
0
    const HeaderFileInfo *HFI =
2030
0
        HS.getExistingFileInfo(*File, /*WantExternal*/!Chain);
2031
0
    if (!HFI || (HFI->isModuleHeader && !HFI->isCompilingModuleHeader))
2032
0
      continue;
2033
2034
    // Massage the file path into an appropriate form.
2035
0
    StringRef Filename = File->getName();
2036
0
    SmallString<128> FilenameTmp(Filename);
2037
0
    if (PreparePathForOutput(FilenameTmp)) {
2038
      // If we performed any translation on the file name at all, we need to
2039
      // save this string, since the generator will refer to it later.
2040
0
      Filename = StringRef(strdup(FilenameTmp.c_str()));
2041
0
      SavedStrings.push_back(Filename.data());
2042
0
    }
2043
2044
0
    bool Included = PP->alreadyIncluded(*File);
2045
2046
0
    HeaderFileInfoTrait::key_type Key = {
2047
0
      Filename, File->getSize(), getTimestampForOutput(*File)
2048
0
    };
2049
0
    HeaderFileInfoTrait::data_type Data = {
2050
0
      *HFI, Included, HS.getModuleMap().findResolvedModulesForHeader(*File), {}
2051
0
    };
2052
0
    Generator.insert(Key, Data, GeneratorTrait);
2053
0
    ++NumHeaderSearchEntries;
2054
0
  }
2055
2056
  // Create the on-disk hash table in a buffer.
2057
0
  SmallString<4096> TableData;
2058
0
  uint32_t BucketOffset;
2059
0
  {
2060
0
    using namespace llvm::support;
2061
2062
0
    llvm::raw_svector_ostream Out(TableData);
2063
    // Make sure that no bucket is at offset 0
2064
0
    endian::write<uint32_t>(Out, 0, llvm::endianness::little);
2065
0
    BucketOffset = Generator.Emit(Out, GeneratorTrait);
2066
0
  }
2067
2068
  // Create a blob abbreviation
2069
0
  using namespace llvm;
2070
2071
0
  auto Abbrev = std::make_shared<BitCodeAbbrev>();
2072
0
  Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
2073
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2074
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2075
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2076
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2077
0
  unsigned TableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2078
2079
  // Write the header search table
2080
0
  RecordData::value_type Record[] = {HEADER_SEARCH_TABLE, BucketOffset,
2081
0
                                     NumHeaderSearchEntries, TableData.size()};
2082
0
  TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end());
2083
0
  Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData);
2084
2085
  // Free all of the strings we had to duplicate.
2086
0
  for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
2087
0
    free(const_cast<char *>(SavedStrings[I]));
2088
0
}
2089
2090
static void emitBlob(llvm::BitstreamWriter &Stream, StringRef Blob,
2091
                     unsigned SLocBufferBlobCompressedAbbrv,
2092
0
                     unsigned SLocBufferBlobAbbrv) {
2093
0
  using RecordDataType = ASTWriter::RecordData::value_type;
2094
2095
  // Compress the buffer if possible. We expect that almost all PCM
2096
  // consumers will not want its contents.
2097
0
  SmallVector<uint8_t, 0> CompressedBuffer;
2098
0
  if (llvm::compression::zstd::isAvailable()) {
2099
0
    llvm::compression::zstd::compress(
2100
0
        llvm::arrayRefFromStringRef(Blob.drop_back(1)), CompressedBuffer, 9);
2101
0
    RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB_COMPRESSED, Blob.size() - 1};
2102
0
    Stream.EmitRecordWithBlob(SLocBufferBlobCompressedAbbrv, Record,
2103
0
                              llvm::toStringRef(CompressedBuffer));
2104
0
    return;
2105
0
  }
2106
0
  if (llvm::compression::zlib::isAvailable()) {
2107
0
    llvm::compression::zlib::compress(
2108
0
        llvm::arrayRefFromStringRef(Blob.drop_back(1)), CompressedBuffer);
2109
0
    RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB_COMPRESSED, Blob.size() - 1};
2110
0
    Stream.EmitRecordWithBlob(SLocBufferBlobCompressedAbbrv, Record,
2111
0
                              llvm::toStringRef(CompressedBuffer));
2112
0
    return;
2113
0
  }
2114
2115
0
  RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB};
2116
0
  Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, Blob);
2117
0
}
2118
2119
/// Writes the block containing the serialized form of the
2120
/// source manager.
2121
///
2122
/// TODO: We should probably use an on-disk hash table (stored in a
2123
/// blob), indexed based on the file name, so that we only create
2124
/// entries for files that we actually need. In the common case (no
2125
/// errors), we probably won't have to create file entries for any of
2126
/// the files in the AST.
2127
void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
2128
0
                                        const Preprocessor &PP) {
2129
0
  RecordData Record;
2130
2131
  // Enter the source manager block.
2132
0
  Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 4);
2133
0
  const uint64_t SourceManagerBlockOffset = Stream.GetCurrentBitNo();
2134
2135
  // Abbreviations for the various kinds of source-location entries.
2136
0
  unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
2137
0
  unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
2138
0
  unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream, false);
2139
0
  unsigned SLocBufferBlobCompressedAbbrv =
2140
0
      CreateSLocBufferBlobAbbrev(Stream, true);
2141
0
  unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
2142
2143
  // Write out the source location entry table. We skip the first
2144
  // entry, which is always the same dummy entry.
2145
0
  std::vector<uint32_t> SLocEntryOffsets;
2146
0
  uint64_t SLocEntryOffsetsBase = Stream.GetCurrentBitNo();
2147
0
  SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
2148
0
  for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
2149
0
       I != N; ++I) {
2150
    // Get this source location entry.
2151
0
    const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
2152
0
    FileID FID = FileID::get(I);
2153
0
    assert(&SourceMgr.getSLocEntry(FID) == SLoc);
2154
2155
    // Record the offset of this source-location entry.
2156
0
    uint64_t Offset = Stream.GetCurrentBitNo() - SLocEntryOffsetsBase;
2157
0
    assert((Offset >> 32) == 0 && "SLocEntry offset too large");
2158
2159
    // Figure out which record code to use.
2160
0
    unsigned Code;
2161
0
    if (SLoc->isFile()) {
2162
0
      const SrcMgr::ContentCache *Cache = &SLoc->getFile().getContentCache();
2163
0
      if (Cache->OrigEntry) {
2164
0
        Code = SM_SLOC_FILE_ENTRY;
2165
0
      } else
2166
0
        Code = SM_SLOC_BUFFER_ENTRY;
2167
0
    } else
2168
0
      Code = SM_SLOC_EXPANSION_ENTRY;
2169
0
    Record.clear();
2170
0
    Record.push_back(Code);
2171
2172
0
    if (SLoc->isFile()) {
2173
0
      const SrcMgr::FileInfo &File = SLoc->getFile();
2174
0
      const SrcMgr::ContentCache *Content = &File.getContentCache();
2175
      // Do not emit files that were not listed as inputs.
2176
0
      if (!IsSLocAffecting[I])
2177
0
        continue;
2178
0
      SLocEntryOffsets.push_back(Offset);
2179
      // Starting offset of this entry within this module, so skip the dummy.
2180
0
      Record.push_back(getAdjustedOffset(SLoc->getOffset()) - 2);
2181
0
      AddSourceLocation(File.getIncludeLoc(), Record);
2182
0
      Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
2183
0
      Record.push_back(File.hasLineDirectives());
2184
2185
0
      bool EmitBlob = false;
2186
0
      if (Content->OrigEntry) {
2187
0
        assert(Content->OrigEntry == Content->ContentsEntry &&
2188
0
               "Writing to AST an overridden file is not supported");
2189
2190
        // The source location entry is a file. Emit input file ID.
2191
0
        assert(InputFileIDs[*Content->OrigEntry] != 0 && "Missed file entry");
2192
0
        Record.push_back(InputFileIDs[*Content->OrigEntry]);
2193
2194
0
        Record.push_back(getAdjustedNumCreatedFIDs(FID));
2195
2196
0
        FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID);
2197
0
        if (FDI != FileDeclIDs.end()) {
2198
0
          Record.push_back(FDI->second->FirstDeclIndex);
2199
0
          Record.push_back(FDI->second->DeclIDs.size());
2200
0
        } else {
2201
0
          Record.push_back(0);
2202
0
          Record.push_back(0);
2203
0
        }
2204
2205
0
        Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record);
2206
2207
0
        if (Content->BufferOverridden || Content->IsTransient)
2208
0
          EmitBlob = true;
2209
0
      } else {
2210
        // The source location entry is a buffer. The blob associated
2211
        // with this entry contains the contents of the buffer.
2212
2213
        // We add one to the size so that we capture the trailing NULL
2214
        // that is required by llvm::MemoryBuffer::getMemBuffer (on
2215
        // the reader side).
2216
0
        std::optional<llvm::MemoryBufferRef> Buffer =
2217
0
            Content->getBufferOrNone(PP.getDiagnostics(), PP.getFileManager());
2218
0
        StringRef Name = Buffer ? Buffer->getBufferIdentifier() : "";
2219
0
        Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
2220
0
                                  StringRef(Name.data(), Name.size() + 1));
2221
0
        EmitBlob = true;
2222
0
      }
2223
2224
0
      if (EmitBlob) {
2225
        // Include the implicit terminating null character in the on-disk buffer
2226
        // if we're writing it uncompressed.
2227
0
        std::optional<llvm::MemoryBufferRef> Buffer =
2228
0
            Content->getBufferOrNone(PP.getDiagnostics(), PP.getFileManager());
2229
0
        if (!Buffer)
2230
0
          Buffer = llvm::MemoryBufferRef("<<<INVALID BUFFER>>>", "");
2231
0
        StringRef Blob(Buffer->getBufferStart(), Buffer->getBufferSize() + 1);
2232
0
        emitBlob(Stream, Blob, SLocBufferBlobCompressedAbbrv,
2233
0
                 SLocBufferBlobAbbrv);
2234
0
      }
2235
0
    } else {
2236
      // The source location entry is a macro expansion.
2237
0
      const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
2238
0
      SLocEntryOffsets.push_back(Offset);
2239
      // Starting offset of this entry within this module, so skip the dummy.
2240
0
      Record.push_back(getAdjustedOffset(SLoc->getOffset()) - 2);
2241
0
      LocSeq::State Seq;
2242
0
      AddSourceLocation(Expansion.getSpellingLoc(), Record, Seq);
2243
0
      AddSourceLocation(Expansion.getExpansionLocStart(), Record, Seq);
2244
0
      AddSourceLocation(Expansion.isMacroArgExpansion()
2245
0
                            ? SourceLocation()
2246
0
                            : Expansion.getExpansionLocEnd(),
2247
0
                        Record, Seq);
2248
0
      Record.push_back(Expansion.isExpansionTokenRange());
2249
2250
      // Compute the token length for this macro expansion.
2251
0
      SourceLocation::UIntTy NextOffset = SourceMgr.getNextLocalOffset();
2252
0
      if (I + 1 != N)
2253
0
        NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
2254
0
      Record.push_back(getAdjustedOffset(NextOffset - SLoc->getOffset()) - 1);
2255
0
      Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
2256
0
    }
2257
0
  }
2258
2259
0
  Stream.ExitBlock();
2260
2261
0
  if (SLocEntryOffsets.empty())
2262
0
    return;
2263
2264
  // Write the source-location offsets table into the AST block. This
2265
  // table is used for lazily loading source-location information.
2266
0
  using namespace llvm;
2267
2268
0
  auto Abbrev = std::make_shared<BitCodeAbbrev>();
2269
0
  Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
2270
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
2271
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
2272
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // base offset
2273
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
2274
0
  unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2275
0
  {
2276
0
    RecordData::value_type Record[] = {
2277
0
        SOURCE_LOCATION_OFFSETS, SLocEntryOffsets.size(),
2278
0
        getAdjustedOffset(SourceMgr.getNextLocalOffset()) - 1 /* skip dummy */,
2279
0
        SLocEntryOffsetsBase - SourceManagerBlockOffset};
2280
0
    Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
2281
0
                              bytes(SLocEntryOffsets));
2282
0
  }
2283
2284
  // Write the line table. It depends on remapping working, so it must come
2285
  // after the source location offsets.
2286
0
  if (SourceMgr.hasLineTable()) {
2287
0
    LineTableInfo &LineTable = SourceMgr.getLineTable();
2288
2289
0
    Record.clear();
2290
2291
    // Emit the needed file names.
2292
0
    llvm::DenseMap<int, int> FilenameMap;
2293
0
    FilenameMap[-1] = -1; // For unspecified filenames.
2294
0
    for (const auto &L : LineTable) {
2295
0
      if (L.first.ID < 0)
2296
0
        continue;
2297
0
      for (auto &LE : L.second) {
2298
0
        if (FilenameMap.insert(std::make_pair(LE.FilenameID,
2299
0
                                              FilenameMap.size() - 1)).second)
2300
0
          AddPath(LineTable.getFilename(LE.FilenameID), Record);
2301
0
      }
2302
0
    }
2303
0
    Record.push_back(0);
2304
2305
    // Emit the line entries
2306
0
    for (const auto &L : LineTable) {
2307
      // Only emit entries for local files.
2308
0
      if (L.first.ID < 0)
2309
0
        continue;
2310
2311
0
      AddFileID(L.first, Record);
2312
2313
      // Emit the line entries
2314
0
      Record.push_back(L.second.size());
2315
0
      for (const auto &LE : L.second) {
2316
0
        Record.push_back(LE.FileOffset);
2317
0
        Record.push_back(LE.LineNo);
2318
0
        Record.push_back(FilenameMap[LE.FilenameID]);
2319
0
        Record.push_back((unsigned)LE.FileKind);
2320
0
        Record.push_back(LE.IncludeOffset);
2321
0
      }
2322
0
    }
2323
2324
0
    Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
2325
0
  }
2326
0
}
2327
2328
//===----------------------------------------------------------------------===//
2329
// Preprocessor Serialization
2330
//===----------------------------------------------------------------------===//
2331
2332
static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule,
2333
0
                              const Preprocessor &PP) {
2334
0
  if (MacroInfo *MI = MD->getMacroInfo())
2335
0
    if (MI->isBuiltinMacro())
2336
0
      return true;
2337
2338
0
  if (IsModule) {
2339
0
    SourceLocation Loc = MD->getLocation();
2340
0
    if (Loc.isInvalid())
2341
0
      return true;
2342
0
    if (PP.getSourceManager().getFileID(Loc) == PP.getPredefinesFileID())
2343
0
      return true;
2344
0
  }
2345
2346
0
  return false;
2347
0
}
2348
2349
/// Writes the block containing the serialized form of the
2350
/// preprocessor.
2351
0
void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
2352
0
  uint64_t MacroOffsetsBase = Stream.GetCurrentBitNo();
2353
2354
0
  PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
2355
0
  if (PPRec)
2356
0
    WritePreprocessorDetail(*PPRec, MacroOffsetsBase);
2357
2358
0
  RecordData Record;
2359
0
  RecordData ModuleMacroRecord;
2360
2361
  // If the preprocessor __COUNTER__ value has been bumped, remember it.
2362
0
  if (PP.getCounterValue() != 0) {
2363
0
    RecordData::value_type Record[] = {PP.getCounterValue()};
2364
0
    Stream.EmitRecord(PP_COUNTER_VALUE, Record);
2365
0
  }
2366
2367
  // If we have a recorded #pragma assume_nonnull, remember it so it can be
2368
  // replayed when the preamble terminates into the main file.
2369
0
  SourceLocation AssumeNonNullLoc =
2370
0
      PP.getPreambleRecordedPragmaAssumeNonNullLoc();
2371
0
  if (AssumeNonNullLoc.isValid()) {
2372
0
    assert(PP.isRecordingPreamble());
2373
0
    AddSourceLocation(AssumeNonNullLoc, Record);
2374
0
    Stream.EmitRecord(PP_ASSUME_NONNULL_LOC, Record);
2375
0
    Record.clear();
2376
0
  }
2377
2378
0
  if (PP.isRecordingPreamble() && PP.hasRecordedPreamble()) {
2379
0
    assert(!IsModule);
2380
0
    auto SkipInfo = PP.getPreambleSkipInfo();
2381
0
    if (SkipInfo) {
2382
0
      Record.push_back(true);
2383
0
      AddSourceLocation(SkipInfo->HashTokenLoc, Record);
2384
0
      AddSourceLocation(SkipInfo->IfTokenLoc, Record);
2385
0
      Record.push_back(SkipInfo->FoundNonSkipPortion);
2386
0
      Record.push_back(SkipInfo->FoundElse);
2387
0
      AddSourceLocation(SkipInfo->ElseLoc, Record);
2388
0
    } else {
2389
0
      Record.push_back(false);
2390
0
    }
2391
0
    for (const auto &Cond : PP.getPreambleConditionalStack()) {
2392
0
      AddSourceLocation(Cond.IfLoc, Record);
2393
0
      Record.push_back(Cond.WasSkipping);
2394
0
      Record.push_back(Cond.FoundNonSkip);
2395
0
      Record.push_back(Cond.FoundElse);
2396
0
    }
2397
0
    Stream.EmitRecord(PP_CONDITIONAL_STACK, Record);
2398
0
    Record.clear();
2399
0
  }
2400
2401
  // Enter the preprocessor block.
2402
0
  Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
2403
2404
  // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
2405
  // FIXME: Include a location for the use, and say which one was used.
2406
0
  if (PP.SawDateOrTime())
2407
0
    PP.Diag(SourceLocation(), diag::warn_module_uses_date_time) << IsModule;
2408
2409
  // Loop over all the macro directives that are live at the end of the file,
2410
  // emitting each to the PP section.
2411
2412
  // Construct the list of identifiers with macro directives that need to be
2413
  // serialized.
2414
0
  SmallVector<const IdentifierInfo *, 128> MacroIdentifiers;
2415
  // It is meaningless to emit macros for named modules. It only wastes times
2416
  // and spaces.
2417
0
  if (!isWritingStdCXXNamedModules())
2418
0
    for (auto &Id : PP.getIdentifierTable())
2419
0
      if (Id.second->hadMacroDefinition() &&
2420
0
          (!Id.second->isFromAST() ||
2421
0
          Id.second->hasChangedSinceDeserialization()))
2422
0
        MacroIdentifiers.push_back(Id.second);
2423
  // Sort the set of macro definitions that need to be serialized by the
2424
  // name of the macro, to provide a stable ordering.
2425
0
  llvm::sort(MacroIdentifiers, llvm::deref<std::less<>>());
2426
2427
  // Emit the macro directives as a list and associate the offset with the
2428
  // identifier they belong to.
2429
0
  for (const IdentifierInfo *Name : MacroIdentifiers) {
2430
0
    MacroDirective *MD = PP.getLocalMacroDirectiveHistory(Name);
2431
0
    uint64_t StartOffset = Stream.GetCurrentBitNo() - MacroOffsetsBase;
2432
0
    assert((StartOffset >> 32) == 0 && "Macro identifiers offset too large");
2433
2434
    // Write out any exported module macros.
2435
0
    bool EmittedModuleMacros = false;
2436
    // C+=20 Header Units are compiled module interfaces, but they preserve
2437
    // macros that are live (i.e. have a defined value) at the end of the
2438
    // compilation.  So when writing a header unit, we preserve only the final
2439
    // value of each macro (and discard any that are undefined).  Header units
2440
    // do not have sub-modules (although they might import other header units).
2441
    // PCH files, conversely, retain the history of each macro's define/undef
2442
    // and of leaf macros in sub modules.
2443
0
    if (IsModule && WritingModule->isHeaderUnit()) {
2444
      // This is for the main TU when it is a C++20 header unit.
2445
      // We preserve the final state of defined macros, and we do not emit ones
2446
      // that are undefined.
2447
0
      if (!MD || shouldIgnoreMacro(MD, IsModule, PP) ||
2448
0
          MD->getKind() == MacroDirective::MD_Undefine)
2449
0
        continue;
2450
0
      AddSourceLocation(MD->getLocation(), Record);
2451
0
      Record.push_back(MD->getKind());
2452
0
      if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) {
2453
0
        Record.push_back(getMacroRef(DefMD->getInfo(), Name));
2454
0
      } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
2455
0
        Record.push_back(VisMD->isPublic());
2456
0
      }
2457
0
      ModuleMacroRecord.push_back(getSubmoduleID(WritingModule));
2458
0
      ModuleMacroRecord.push_back(getMacroRef(MD->getMacroInfo(), Name));
2459
0
      Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord);
2460
0
      ModuleMacroRecord.clear();
2461
0
      EmittedModuleMacros = true;
2462
0
    } else {
2463
      // Emit the macro directives in reverse source order.
2464
0
      for (; MD; MD = MD->getPrevious()) {
2465
        // Once we hit an ignored macro, we're done: the rest of the chain
2466
        // will all be ignored macros.
2467
0
        if (shouldIgnoreMacro(MD, IsModule, PP))
2468
0
          break;
2469
0
        AddSourceLocation(MD->getLocation(), Record);
2470
0
        Record.push_back(MD->getKind());
2471
0
        if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) {
2472
0
          Record.push_back(getMacroRef(DefMD->getInfo(), Name));
2473
0
        } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
2474
0
          Record.push_back(VisMD->isPublic());
2475
0
        }
2476
0
      }
2477
2478
      // We write out exported module macros for PCH as well.
2479
0
      auto Leafs = PP.getLeafModuleMacros(Name);
2480
0
      SmallVector<ModuleMacro *, 8> Worklist(Leafs.begin(), Leafs.end());
2481
0
      llvm::DenseMap<ModuleMacro *, unsigned> Visits;
2482
0
      while (!Worklist.empty()) {
2483
0
        auto *Macro = Worklist.pop_back_val();
2484
2485
        // Emit a record indicating this submodule exports this macro.
2486
0
        ModuleMacroRecord.push_back(getSubmoduleID(Macro->getOwningModule()));
2487
0
        ModuleMacroRecord.push_back(getMacroRef(Macro->getMacroInfo(), Name));
2488
0
        for (auto *M : Macro->overrides())
2489
0
          ModuleMacroRecord.push_back(getSubmoduleID(M->getOwningModule()));
2490
2491
0
        Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord);
2492
0
        ModuleMacroRecord.clear();
2493
2494
        // Enqueue overridden macros once we've visited all their ancestors.
2495
0
        for (auto *M : Macro->overrides())
2496
0
          if (++Visits[M] == M->getNumOverridingMacros())
2497
0
            Worklist.push_back(M);
2498
2499
0
        EmittedModuleMacros = true;
2500
0
      }
2501
0
    }
2502
0
    if (Record.empty() && !EmittedModuleMacros)
2503
0
      continue;
2504
2505
0
    IdentMacroDirectivesOffsetMap[Name] = StartOffset;
2506
0
    Stream.EmitRecord(PP_MACRO_DIRECTIVE_HISTORY, Record);
2507
0
    Record.clear();
2508
0
  }
2509
2510
  /// Offsets of each of the macros into the bitstream, indexed by
2511
  /// the local macro ID
2512
  ///
2513
  /// For each identifier that is associated with a macro, this map
2514
  /// provides the offset into the bitstream where that macro is
2515
  /// defined.
2516
0
  std::vector<uint32_t> MacroOffsets;
2517
2518
0
  for (unsigned I = 0, N = MacroInfosToEmit.size(); I != N; ++I) {
2519
0
    const IdentifierInfo *Name = MacroInfosToEmit[I].Name;
2520
0
    MacroInfo *MI = MacroInfosToEmit[I].MI;
2521
0
    MacroID ID = MacroInfosToEmit[I].ID;
2522
2523
0
    if (ID < FirstMacroID) {
2524
0
      assert(0 && "Loaded MacroInfo entered MacroInfosToEmit ?");
2525
0
      continue;
2526
0
    }
2527
2528
    // Record the local offset of this macro.
2529
0
    unsigned Index = ID - FirstMacroID;
2530
0
    if (Index >= MacroOffsets.size())
2531
0
      MacroOffsets.resize(Index + 1);
2532
2533
0
    uint64_t Offset = Stream.GetCurrentBitNo() - MacroOffsetsBase;
2534
0
    assert((Offset >> 32) == 0 && "Macro offset too large");
2535
0
    MacroOffsets[Index] = Offset;
2536
2537
0
    AddIdentifierRef(Name, Record);
2538
0
    AddSourceLocation(MI->getDefinitionLoc(), Record);
2539
0
    AddSourceLocation(MI->getDefinitionEndLoc(), Record);
2540
0
    Record.push_back(MI->isUsed());
2541
0
    Record.push_back(MI->isUsedForHeaderGuard());
2542
0
    Record.push_back(MI->getNumTokens());
2543
0
    unsigned Code;
2544
0
    if (MI->isObjectLike()) {
2545
0
      Code = PP_MACRO_OBJECT_LIKE;
2546
0
    } else {
2547
0
      Code = PP_MACRO_FUNCTION_LIKE;
2548
2549
0
      Record.push_back(MI->isC99Varargs());
2550
0
      Record.push_back(MI->isGNUVarargs());
2551
0
      Record.push_back(MI->hasCommaPasting());
2552
0
      Record.push_back(MI->getNumParams());
2553
0
      for (const IdentifierInfo *Param : MI->params())
2554
0
        AddIdentifierRef(Param, Record);
2555
0
    }
2556
2557
    // If we have a detailed preprocessing record, record the macro definition
2558
    // ID that corresponds to this macro.
2559
0
    if (PPRec)
2560
0
      Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
2561
2562
0
    Stream.EmitRecord(Code, Record);
2563
0
    Record.clear();
2564
2565
    // Emit the tokens array.
2566
0
    for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
2567
      // Note that we know that the preprocessor does not have any annotation
2568
      // tokens in it because they are created by the parser, and thus can't
2569
      // be in a macro definition.
2570
0
      const Token &Tok = MI->getReplacementToken(TokNo);
2571
0
      AddToken(Tok, Record);
2572
0
      Stream.EmitRecord(PP_TOKEN, Record);
2573
0
      Record.clear();
2574
0
    }
2575
0
    ++NumMacros;
2576
0
  }
2577
2578
0
  Stream.ExitBlock();
2579
2580
  // Write the offsets table for macro IDs.
2581
0
  using namespace llvm;
2582
2583
0
  auto Abbrev = std::make_shared<BitCodeAbbrev>();
2584
0
  Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET));
2585
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros
2586
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
2587
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32));   // base offset
2588
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2589
2590
0
  unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2591
0
  {
2592
0
    RecordData::value_type Record[] = {MACRO_OFFSET, MacroOffsets.size(),
2593
0
                                       FirstMacroID - NUM_PREDEF_MACRO_IDS,
2594
0
                                       MacroOffsetsBase - ASTBlockStartOffset};
2595
0
    Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record, bytes(MacroOffsets));
2596
0
  }
2597
0
}
2598
2599
void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec,
2600
0
                                        uint64_t MacroOffsetsBase) {
2601
0
  if (PPRec.local_begin() == PPRec.local_end())
2602
0
    return;
2603
2604
0
  SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
2605
2606
  // Enter the preprocessor block.
2607
0
  Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
2608
2609
  // If the preprocessor has a preprocessing record, emit it.
2610
0
  unsigned NumPreprocessingRecords = 0;
2611
0
  using namespace llvm;
2612
2613
  // Set up the abbreviation for
2614
0
  unsigned InclusionAbbrev = 0;
2615
0
  {
2616
0
    auto Abbrev = std::make_shared<BitCodeAbbrev>();
2617
0
    Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
2618
0
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
2619
0
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
2620
0
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
2621
0
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module
2622
0
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2623
0
    InclusionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2624
0
  }
2625
2626
0
  unsigned FirstPreprocessorEntityID
2627
0
    = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0)
2628
0
    + NUM_PREDEF_PP_ENTITY_IDS;
2629
0
  unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
2630
0
  RecordData Record;
2631
0
  for (PreprocessingRecord::iterator E = PPRec.local_begin(),
2632
0
                                  EEnd = PPRec.local_end();
2633
0
       E != EEnd;
2634
0
       (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
2635
0
    Record.clear();
2636
2637
0
    uint64_t Offset = Stream.GetCurrentBitNo() - MacroOffsetsBase;
2638
0
    assert((Offset >> 32) == 0 && "Preprocessed entity offset too large");
2639
0
    PreprocessedEntityOffsets.push_back(
2640
0
        PPEntityOffset(getAdjustedRange((*E)->getSourceRange()), Offset));
2641
2642
0
    if (auto *MD = dyn_cast<MacroDefinitionRecord>(*E)) {
2643
      // Record this macro definition's ID.
2644
0
      MacroDefinitions[MD] = NextPreprocessorEntityID;
2645
2646
0
      AddIdentifierRef(MD->getName(), Record);
2647
0
      Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
2648
0
      continue;
2649
0
    }
2650
2651
0
    if (auto *ME = dyn_cast<MacroExpansion>(*E)) {
2652
0
      Record.push_back(ME->isBuiltinMacro());
2653
0
      if (ME->isBuiltinMacro())
2654
0
        AddIdentifierRef(ME->getName(), Record);
2655
0
      else
2656
0
        Record.push_back(MacroDefinitions[ME->getDefinition()]);
2657
0
      Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
2658
0
      continue;
2659
0
    }
2660
2661
0
    if (auto *ID = dyn_cast<InclusionDirective>(*E)) {
2662
0
      Record.push_back(PPD_INCLUSION_DIRECTIVE);
2663
0
      Record.push_back(ID->getFileName().size());
2664
0
      Record.push_back(ID->wasInQuotes());
2665
0
      Record.push_back(static_cast<unsigned>(ID->getKind()));
2666
0
      Record.push_back(ID->importedModule());
2667
0
      SmallString<64> Buffer;
2668
0
      Buffer += ID->getFileName();
2669
      // Check that the FileEntry is not null because it was not resolved and
2670
      // we create a PCH even with compiler errors.
2671
0
      if (ID->getFile())
2672
0
        Buffer += ID->getFile()->getName();
2673
0
      Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
2674
0
      continue;
2675
0
    }
2676
2677
0
    llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
2678
0
  }
2679
0
  Stream.ExitBlock();
2680
2681
  // Write the offsets table for the preprocessing record.
2682
0
  if (NumPreprocessingRecords > 0) {
2683
0
    assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords);
2684
2685
    // Write the offsets table for identifier IDs.
2686
0
    using namespace llvm;
2687
2688
0
    auto Abbrev = std::make_shared<BitCodeAbbrev>();
2689
0
    Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
2690
0
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
2691
0
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2692
0
    unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2693
2694
0
    RecordData::value_type Record[] = {PPD_ENTITIES_OFFSETS,
2695
0
                                       FirstPreprocessorEntityID -
2696
0
                                           NUM_PREDEF_PP_ENTITY_IDS};
2697
0
    Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
2698
0
                              bytes(PreprocessedEntityOffsets));
2699
0
  }
2700
2701
  // Write the skipped region table for the preprocessing record.
2702
0
  ArrayRef<SourceRange> SkippedRanges = PPRec.getSkippedRanges();
2703
0
  if (SkippedRanges.size() > 0) {
2704
0
    std::vector<PPSkippedRange> SerializedSkippedRanges;
2705
0
    SerializedSkippedRanges.reserve(SkippedRanges.size());
2706
0
    for (auto const& Range : SkippedRanges)
2707
0
      SerializedSkippedRanges.emplace_back(Range);
2708
2709
0
    using namespace llvm;
2710
0
    auto Abbrev = std::make_shared<BitCodeAbbrev>();
2711
0
    Abbrev->Add(BitCodeAbbrevOp(PPD_SKIPPED_RANGES));
2712
0
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2713
0
    unsigned PPESkippedRangeAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2714
2715
0
    Record.clear();
2716
0
    Record.push_back(PPD_SKIPPED_RANGES);
2717
0
    Stream.EmitRecordWithBlob(PPESkippedRangeAbbrev, Record,
2718
0
                              bytes(SerializedSkippedRanges));
2719
0
  }
2720
0
}
2721
2722
0
unsigned ASTWriter::getLocalOrImportedSubmoduleID(const Module *Mod) {
2723
0
  if (!Mod)
2724
0
    return 0;
2725
2726
0
  auto Known = SubmoduleIDs.find(Mod);
2727
0
  if (Known != SubmoduleIDs.end())
2728
0
    return Known->second;
2729
2730
0
  auto *Top = Mod->getTopLevelModule();
2731
0
  if (Top != WritingModule &&
2732
0
      (getLangOpts().CompilingPCH ||
2733
0
       !Top->fullModuleNameIs(StringRef(getLangOpts().CurrentModule))))
2734
0
    return 0;
2735
2736
0
  return SubmoduleIDs[Mod] = NextSubmoduleID++;
2737
0
}
2738
2739
0
unsigned ASTWriter::getSubmoduleID(Module *Mod) {
2740
0
  unsigned ID = getLocalOrImportedSubmoduleID(Mod);
2741
  // FIXME: This can easily happen, if we have a reference to a submodule that
2742
  // did not result in us loading a module file for that submodule. For
2743
  // instance, a cross-top-level-module 'conflict' declaration will hit this.
2744
  // assert((ID || !Mod) &&
2745
  //        "asked for module ID for non-local, non-imported module");
2746
0
  return ID;
2747
0
}
2748
2749
/// Compute the number of modules within the given tree (including the
2750
/// given module).
2751
0
static unsigned getNumberOfModules(Module *Mod) {
2752
0
  unsigned ChildModules = 0;
2753
0
  for (auto *Submodule : Mod->submodules())
2754
0
    ChildModules += getNumberOfModules(Submodule);
2755
2756
0
  return ChildModules + 1;
2757
0
}
2758
2759
0
void ASTWriter::WriteSubmodules(Module *WritingModule) {
2760
  // Enter the submodule description block.
2761
0
  Stream.EnterSubblock(SUBMODULE_BLOCK_ID, /*bits for abbreviations*/5);
2762
2763
  // Write the abbreviations needed for the submodules block.
2764
0
  using namespace llvm;
2765
2766
0
  auto Abbrev = std::make_shared<BitCodeAbbrev>();
2767
0
  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
2768
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
2769
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
2770
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // Kind
2771
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Definition location
2772
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2773
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
2774
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem
2775
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExternC
2776
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules...
2777
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
2778
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
2779
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ConfigMacrosExh...
2780
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ModuleMapIsPriv...
2781
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // NamedModuleHasN...
2782
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2783
0
  unsigned DefinitionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2784
2785
0
  Abbrev = std::make_shared<BitCodeAbbrev>();
2786
0
  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
2787
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2788
0
  unsigned UmbrellaAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2789
2790
0
  Abbrev = std::make_shared<BitCodeAbbrev>();
2791
0
  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
2792
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2793
0
  unsigned HeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2794
2795
0
  Abbrev = std::make_shared<BitCodeAbbrev>();
2796
0
  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TOPHEADER));
2797
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2798
0
  unsigned TopHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2799
2800
0
  Abbrev = std::make_shared<BitCodeAbbrev>();
2801
0
  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
2802
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2803
0
  unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2804
2805
0
  Abbrev = std::make_shared<BitCodeAbbrev>();
2806
0
  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES));
2807
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // State
2808
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));     // Feature
2809
0
  unsigned RequiresAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2810
2811
0
  Abbrev = std::make_shared<BitCodeAbbrev>();
2812
0
  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXCLUDED_HEADER));
2813
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2814
0
  unsigned ExcludedHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2815
2816
0
  Abbrev = std::make_shared<BitCodeAbbrev>();
2817
0
  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TEXTUAL_HEADER));
2818
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2819
0
  unsigned TextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2820
2821
0
  Abbrev = std::make_shared<BitCodeAbbrev>();
2822
0
  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_HEADER));
2823
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2824
0
  unsigned PrivateHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2825
2826
0
  Abbrev = std::make_shared<BitCodeAbbrev>();
2827
0
  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_TEXTUAL_HEADER));
2828
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2829
0
  unsigned PrivateTextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2830
2831
0
  Abbrev = std::make_shared<BitCodeAbbrev>();
2832
0
  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_LINK_LIBRARY));
2833
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2834
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));     // Name
2835
0
  unsigned LinkLibraryAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2836
2837
0
  Abbrev = std::make_shared<BitCodeAbbrev>();
2838
0
  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFIG_MACRO));
2839
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));    // Macro name
2840
0
  unsigned ConfigMacroAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2841
2842
0
  Abbrev = std::make_shared<BitCodeAbbrev>();
2843
0
  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFLICT));
2844
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));  // Other module
2845
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));    // Message
2846
0
  unsigned ConflictAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2847
2848
0
  Abbrev = std::make_shared<BitCodeAbbrev>();
2849
0
  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXPORT_AS));
2850
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));    // Macro name
2851
0
  unsigned ExportAsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2852
2853
  // Write the submodule metadata block.
2854
0
  RecordData::value_type Record[] = {
2855
0
      getNumberOfModules(WritingModule),
2856
0
      FirstSubmoduleID - NUM_PREDEF_SUBMODULE_IDS};
2857
0
  Stream.EmitRecord(SUBMODULE_METADATA, Record);
2858
2859
  // Write all of the submodules.
2860
0
  std::queue<Module *> Q;
2861
0
  Q.push(WritingModule);
2862
0
  while (!Q.empty()) {
2863
0
    Module *Mod = Q.front();
2864
0
    Q.pop();
2865
0
    unsigned ID = getSubmoduleID(Mod);
2866
2867
0
    uint64_t ParentID = 0;
2868
0
    if (Mod->Parent) {
2869
0
      assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?");
2870
0
      ParentID = SubmoduleIDs[Mod->Parent];
2871
0
    }
2872
2873
0
    uint64_t DefinitionLoc =
2874
0
        SourceLocationEncoding::encode(getAdjustedLocation(Mod->DefinitionLoc));
2875
2876
    // Emit the definition of the block.
2877
0
    {
2878
0
      RecordData::value_type Record[] = {SUBMODULE_DEFINITION,
2879
0
                                         ID,
2880
0
                                         ParentID,
2881
0
                                         (RecordData::value_type)Mod->Kind,
2882
0
                                         DefinitionLoc,
2883
0
                                         Mod->IsFramework,
2884
0
                                         Mod->IsExplicit,
2885
0
                                         Mod->IsSystem,
2886
0
                                         Mod->IsExternC,
2887
0
                                         Mod->InferSubmodules,
2888
0
                                         Mod->InferExplicitSubmodules,
2889
0
                                         Mod->InferExportWildcard,
2890
0
                                         Mod->ConfigMacrosExhaustive,
2891
0
                                         Mod->ModuleMapIsPrivate,
2892
0
                                         Mod->NamedModuleHasInit};
2893
0
      Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
2894
0
    }
2895
2896
    // Emit the requirements.
2897
0
    for (const auto &R : Mod->Requirements) {
2898
0
      RecordData::value_type Record[] = {SUBMODULE_REQUIRES, R.second};
2899
0
      Stream.EmitRecordWithBlob(RequiresAbbrev, Record, R.first);
2900
0
    }
2901
2902
    // Emit the umbrella header, if there is one.
2903
0
    if (std::optional<Module::Header> UmbrellaHeader =
2904
0
            Mod->getUmbrellaHeaderAsWritten()) {
2905
0
      RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_HEADER};
2906
0
      Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
2907
0
                                UmbrellaHeader->NameAsWritten);
2908
0
    } else if (std::optional<Module::DirectoryName> UmbrellaDir =
2909
0
                   Mod->getUmbrellaDirAsWritten()) {
2910
0
      RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_DIR};
2911
0
      Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,
2912
0
                                UmbrellaDir->NameAsWritten);
2913
0
    }
2914
2915
    // Emit the headers.
2916
0
    struct {
2917
0
      unsigned RecordKind;
2918
0
      unsigned Abbrev;
2919
0
      Module::HeaderKind HeaderKind;
2920
0
    } HeaderLists[] = {
2921
0
      {SUBMODULE_HEADER, HeaderAbbrev, Module::HK_Normal},
2922
0
      {SUBMODULE_TEXTUAL_HEADER, TextualHeaderAbbrev, Module::HK_Textual},
2923
0
      {SUBMODULE_PRIVATE_HEADER, PrivateHeaderAbbrev, Module::HK_Private},
2924
0
      {SUBMODULE_PRIVATE_TEXTUAL_HEADER, PrivateTextualHeaderAbbrev,
2925
0
        Module::HK_PrivateTextual},
2926
0
      {SUBMODULE_EXCLUDED_HEADER, ExcludedHeaderAbbrev, Module::HK_Excluded}
2927
0
    };
2928
0
    for (auto &HL : HeaderLists) {
2929
0
      RecordData::value_type Record[] = {HL.RecordKind};
2930
0
      for (auto &H : Mod->Headers[HL.HeaderKind])
2931
0
        Stream.EmitRecordWithBlob(HL.Abbrev, Record, H.NameAsWritten);
2932
0
    }
2933
2934
    // Emit the top headers.
2935
0
    {
2936
0
      RecordData::value_type Record[] = {SUBMODULE_TOPHEADER};
2937
0
      for (FileEntryRef H : Mod->getTopHeaders(PP->getFileManager())) {
2938
0
        SmallString<128> HeaderName(H.getName());
2939
0
        PreparePathForOutput(HeaderName);
2940
0
        Stream.EmitRecordWithBlob(TopHeaderAbbrev, Record, HeaderName);
2941
0
      }
2942
0
    }
2943
2944
    // Emit the imports.
2945
0
    if (!Mod->Imports.empty()) {
2946
0
      RecordData Record;
2947
0
      for (auto *I : Mod->Imports)
2948
0
        Record.push_back(getSubmoduleID(I));
2949
0
      Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
2950
0
    }
2951
2952
    // Emit the modules affecting compilation that were not imported.
2953
0
    if (!Mod->AffectingClangModules.empty()) {
2954
0
      RecordData Record;
2955
0
      for (auto *I : Mod->AffectingClangModules)
2956
0
        Record.push_back(getSubmoduleID(I));
2957
0
      Stream.EmitRecord(SUBMODULE_AFFECTING_MODULES, Record);
2958
0
    }
2959
2960
    // Emit the exports.
2961
0
    if (!Mod->Exports.empty()) {
2962
0
      RecordData Record;
2963
0
      for (const auto &E : Mod->Exports) {
2964
        // FIXME: This may fail; we don't require that all exported modules
2965
        // are local or imported.
2966
0
        Record.push_back(getSubmoduleID(E.getPointer()));
2967
0
        Record.push_back(E.getInt());
2968
0
      }
2969
0
      Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
2970
0
    }
2971
2972
    //FIXME: How do we emit the 'use'd modules?  They may not be submodules.
2973
    // Might be unnecessary as use declarations are only used to build the
2974
    // module itself.
2975
2976
    // TODO: Consider serializing undeclared uses of modules.
2977
2978
    // Emit the link libraries.
2979
0
    for (const auto &LL : Mod->LinkLibraries) {
2980
0
      RecordData::value_type Record[] = {SUBMODULE_LINK_LIBRARY,
2981
0
                                         LL.IsFramework};
2982
0
      Stream.EmitRecordWithBlob(LinkLibraryAbbrev, Record, LL.Library);
2983
0
    }
2984
2985
    // Emit the conflicts.
2986
0
    for (const auto &C : Mod->Conflicts) {
2987
      // FIXME: This may fail; we don't require that all conflicting modules
2988
      // are local or imported.
2989
0
      RecordData::value_type Record[] = {SUBMODULE_CONFLICT,
2990
0
                                         getSubmoduleID(C.Other)};
2991
0
      Stream.EmitRecordWithBlob(ConflictAbbrev, Record, C.Message);
2992
0
    }
2993
2994
    // Emit the configuration macros.
2995
0
    for (const auto &CM : Mod->ConfigMacros) {
2996
0
      RecordData::value_type Record[] = {SUBMODULE_CONFIG_MACRO};
2997
0
      Stream.EmitRecordWithBlob(ConfigMacroAbbrev, Record, CM);
2998
0
    }
2999
3000
    // Emit the initializers, if any.
3001
0
    RecordData Inits;
3002
0
    for (Decl *D : Context->getModuleInitializers(Mod))
3003
0
      Inits.push_back(GetDeclRef(D));
3004
0
    if (!Inits.empty())
3005
0
      Stream.EmitRecord(SUBMODULE_INITIALIZERS, Inits);
3006
3007
    // Emit the name of the re-exported module, if any.
3008
0
    if (!Mod->ExportAsModule.empty()) {
3009
0
      RecordData::value_type Record[] = {SUBMODULE_EXPORT_AS};
3010
0
      Stream.EmitRecordWithBlob(ExportAsAbbrev, Record, Mod->ExportAsModule);
3011
0
    }
3012
3013
    // Queue up the submodules of this module.
3014
0
    for (auto *M : Mod->submodules())
3015
0
      Q.push(M);
3016
0
  }
3017
3018
0
  Stream.ExitBlock();
3019
3020
0
  assert((NextSubmoduleID - FirstSubmoduleID ==
3021
0
          getNumberOfModules(WritingModule)) &&
3022
0
         "Wrong # of submodules; found a reference to a non-local, "
3023
0
         "non-imported submodule?");
3024
0
}
3025
3026
void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
3027
0
                                              bool isModule) {
3028
0
  llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64>
3029
0
      DiagStateIDMap;
3030
0
  unsigned CurrID = 0;
3031
0
  RecordData Record;
3032
3033
0
  auto EncodeDiagStateFlags =
3034
0
      [](const DiagnosticsEngine::DiagState *DS) -> unsigned {
3035
0
    unsigned Result = (unsigned)DS->ExtBehavior;
3036
0
    for (unsigned Val :
3037
0
         {(unsigned)DS->IgnoreAllWarnings, (unsigned)DS->EnableAllWarnings,
3038
0
          (unsigned)DS->WarningsAsErrors, (unsigned)DS->ErrorsAsFatal,
3039
0
          (unsigned)DS->SuppressSystemWarnings})
3040
0
      Result = (Result << 1) | Val;
3041
0
    return Result;
3042
0
  };
3043
3044
0
  unsigned Flags = EncodeDiagStateFlags(Diag.DiagStatesByLoc.FirstDiagState);
3045
0
  Record.push_back(Flags);
3046
3047
0
  auto AddDiagState = [&](const DiagnosticsEngine::DiagState *State,
3048
0
                          bool IncludeNonPragmaStates) {
3049
    // Ensure that the diagnostic state wasn't modified since it was created.
3050
    // We will not correctly round-trip this information otherwise.
3051
0
    assert(Flags == EncodeDiagStateFlags(State) &&
3052
0
           "diag state flags vary in single AST file");
3053
3054
    // If we ever serialize non-pragma mappings outside the initial state, the
3055
    // code below will need to consider more than getDefaultMapping.
3056
0
    assert(!IncludeNonPragmaStates ||
3057
0
           State == Diag.DiagStatesByLoc.FirstDiagState);
3058
3059
0
    unsigned &DiagStateID = DiagStateIDMap[State];
3060
0
    Record.push_back(DiagStateID);
3061
3062
0
    if (DiagStateID == 0) {
3063
0
      DiagStateID = ++CurrID;
3064
0
      SmallVector<std::pair<unsigned, DiagnosticMapping>> Mappings;
3065
3066
      // Add a placeholder for the number of mappings.
3067
0
      auto SizeIdx = Record.size();
3068
0
      Record.emplace_back();
3069
0
      for (const auto &I : *State) {
3070
        // Maybe skip non-pragmas.
3071
0
        if (!I.second.isPragma() && !IncludeNonPragmaStates)
3072
0
          continue;
3073
        // Skip default mappings. We have a mapping for every diagnostic ever
3074
        // emitted, regardless of whether it was customized.
3075
0
        if (!I.second.isPragma() &&
3076
0
            I.second == DiagnosticIDs::getDefaultMapping(I.first))
3077
0
          continue;
3078
0
        Mappings.push_back(I);
3079
0
      }
3080
3081
      // Sort by diag::kind for deterministic output.
3082
0
      llvm::sort(Mappings, [](const auto &LHS, const auto &RHS) {
3083
0
        return LHS.first < RHS.first;
3084
0
      });
3085
3086
0
      for (const auto &I : Mappings) {
3087
0
        Record.push_back(I.first);
3088
0
        Record.push_back(I.second.serialize());
3089
0
      }
3090
      // Update the placeholder.
3091
0
      Record[SizeIdx] = (Record.size() - SizeIdx) / 2;
3092
0
    }
3093
0
  };
3094
3095
0
  AddDiagState(Diag.DiagStatesByLoc.FirstDiagState, isModule);
3096
3097
  // Reserve a spot for the number of locations with state transitions.
3098
0
  auto NumLocationsIdx = Record.size();
3099
0
  Record.emplace_back();
3100
3101
  // Emit the state transitions.
3102
0
  unsigned NumLocations = 0;
3103
0
  for (auto &FileIDAndFile : Diag.DiagStatesByLoc.Files) {
3104
0
    if (!FileIDAndFile.first.isValid() ||
3105
0
        !FileIDAndFile.second.HasLocalTransitions)
3106
0
      continue;
3107
0
    ++NumLocations;
3108
3109
0
    SourceLocation Loc = Diag.SourceMgr->getComposedLoc(FileIDAndFile.first, 0);
3110
0
    assert(!Loc.isInvalid() && "start loc for valid FileID is invalid");
3111
0
    AddSourceLocation(Loc, Record);
3112
3113
0
    Record.push_back(FileIDAndFile.second.StateTransitions.size());
3114
0
    for (auto &StatePoint : FileIDAndFile.second.StateTransitions) {
3115
0
      Record.push_back(getAdjustedOffset(StatePoint.Offset));
3116
0
      AddDiagState(StatePoint.State, false);
3117
0
    }
3118
0
  }
3119
3120
  // Backpatch the number of locations.
3121
0
  Record[NumLocationsIdx] = NumLocations;
3122
3123
  // Emit CurDiagStateLoc.  Do it last in order to match source order.
3124
  //
3125
  // This also protects against a hypothetical corner case with simulating
3126
  // -Werror settings for implicit modules in the ASTReader, where reading
3127
  // CurDiagState out of context could change whether warning pragmas are
3128
  // treated as errors.
3129
0
  AddSourceLocation(Diag.DiagStatesByLoc.CurDiagStateLoc, Record);
3130
0
  AddDiagState(Diag.DiagStatesByLoc.CurDiagState, false);
3131
3132
0
  Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
3133
0
}
3134
3135
//===----------------------------------------------------------------------===//
3136
// Type Serialization
3137
//===----------------------------------------------------------------------===//
3138
3139
/// Write the representation of a type to the AST stream.
3140
0
void ASTWriter::WriteType(QualType T) {
3141
0
  TypeIdx &IdxRef = TypeIdxs[T];
3142
0
  if (IdxRef.getIndex() == 0) // we haven't seen this type before.
3143
0
    IdxRef = TypeIdx(NextTypeID++);
3144
0
  TypeIdx Idx = IdxRef;
3145
3146
0
  assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
3147
3148
  // Emit the type's representation.
3149
0
  uint64_t Offset = ASTTypeWriter(*this).write(T) - DeclTypesBlockStartOffset;
3150
3151
  // Record the offset for this type.
3152
0
  unsigned Index = Idx.getIndex() - FirstTypeID;
3153
0
  if (TypeOffsets.size() == Index)
3154
0
    TypeOffsets.emplace_back(Offset);
3155
0
  else if (TypeOffsets.size() < Index) {
3156
0
    TypeOffsets.resize(Index + 1);
3157
0
    TypeOffsets[Index].setBitOffset(Offset);
3158
0
  } else {
3159
0
    llvm_unreachable("Types emitted in wrong order");
3160
0
  }
3161
0
}
3162
3163
//===----------------------------------------------------------------------===//
3164
// Declaration Serialization
3165
//===----------------------------------------------------------------------===//
3166
3167
/// Write the block containing all of the declaration IDs
3168
/// lexically declared within the given DeclContext.
3169
///
3170
/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
3171
/// bitstream, or 0 if no block was written.
3172
uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
3173
0
                                                 DeclContext *DC) {
3174
0
  if (DC->decls_empty())
3175
0
    return 0;
3176
3177
0
  uint64_t Offset = Stream.GetCurrentBitNo();
3178
0
  SmallVector<uint32_t, 128> KindDeclPairs;
3179
0
  for (const auto *D : DC->decls()) {
3180
0
    KindDeclPairs.push_back(D->getKind());
3181
0
    KindDeclPairs.push_back(GetDeclRef(D));
3182
0
  }
3183
3184
0
  ++NumLexicalDeclContexts;
3185
0
  RecordData::value_type Record[] = {DECL_CONTEXT_LEXICAL};
3186
0
  Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record,
3187
0
                            bytes(KindDeclPairs));
3188
0
  return Offset;
3189
0
}
3190
3191
0
void ASTWriter::WriteTypeDeclOffsets() {
3192
0
  using namespace llvm;
3193
3194
  // Write the type offsets array
3195
0
  auto Abbrev = std::make_shared<BitCodeAbbrev>();
3196
0
  Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
3197
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
3198
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index
3199
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
3200
0
  unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3201
0
  {
3202
0
    RecordData::value_type Record[] = {TYPE_OFFSET, TypeOffsets.size(),
3203
0
                                       FirstTypeID - NUM_PREDEF_TYPE_IDS};
3204
0
    Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, bytes(TypeOffsets));
3205
0
  }
3206
3207
  // Write the declaration offsets array
3208
0
  Abbrev = std::make_shared<BitCodeAbbrev>();
3209
0
  Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
3210
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
3211
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID
3212
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
3213
0
  unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3214
0
  {
3215
0
    RecordData::value_type Record[] = {DECL_OFFSET, DeclOffsets.size(),
3216
0
                                       FirstDeclID - NUM_PREDEF_DECL_IDS};
3217
0
    Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, bytes(DeclOffsets));
3218
0
  }
3219
0
}
3220
3221
0
void ASTWriter::WriteFileDeclIDsMap() {
3222
0
  using namespace llvm;
3223
3224
0
  SmallVector<std::pair<FileID, DeclIDInFileInfo *>, 64> SortedFileDeclIDs;
3225
0
  SortedFileDeclIDs.reserve(FileDeclIDs.size());
3226
0
  for (const auto &P : FileDeclIDs)
3227
0
    SortedFileDeclIDs.push_back(std::make_pair(P.first, P.second.get()));
3228
0
  llvm::sort(SortedFileDeclIDs, llvm::less_first());
3229
3230
  // Join the vectors of DeclIDs from all files.
3231
0
  SmallVector<DeclID, 256> FileGroupedDeclIDs;
3232
0
  for (auto &FileDeclEntry : SortedFileDeclIDs) {
3233
0
    DeclIDInFileInfo &Info = *FileDeclEntry.second;
3234
0
    Info.FirstDeclIndex = FileGroupedDeclIDs.size();
3235
0
    llvm::stable_sort(Info.DeclIDs);
3236
0
    for (auto &LocDeclEntry : Info.DeclIDs)
3237
0
      FileGroupedDeclIDs.push_back(LocDeclEntry.second);
3238
0
  }
3239
3240
0
  auto Abbrev = std::make_shared<BitCodeAbbrev>();
3241
0
  Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
3242
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3243
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3244
0
  unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
3245
0
  RecordData::value_type Record[] = {FILE_SORTED_DECLS,
3246
0
                                     FileGroupedDeclIDs.size()};
3247
0
  Stream.EmitRecordWithBlob(AbbrevCode, Record, bytes(FileGroupedDeclIDs));
3248
0
}
3249
3250
0
void ASTWriter::WriteComments() {
3251
0
  Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
3252
0
  auto _ = llvm::make_scope_exit([this] { Stream.ExitBlock(); });
3253
0
  if (!PP->getPreprocessorOpts().WriteCommentListToPCH)
3254
0
    return;
3255
3256
  // Don't write comments to BMI to reduce the size of BMI.
3257
  // If language services (e.g., clangd) want such abilities,
3258
  // we can offer a special option then.
3259
0
  if (isWritingStdCXXNamedModules())
3260
0
    return;
3261
3262
0
  RecordData Record;
3263
0
  for (const auto &FO : Context->Comments.OrderedComments) {
3264
0
    for (const auto &OC : FO.second) {
3265
0
      const RawComment *I = OC.second;
3266
0
      Record.clear();
3267
0
      AddSourceRange(I->getSourceRange(), Record);
3268
0
      Record.push_back(I->getKind());
3269
0
      Record.push_back(I->isTrailingComment());
3270
0
      Record.push_back(I->isAlmostTrailingComment());
3271
0
      Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
3272
0
    }
3273
0
  }
3274
0
}
3275
3276
//===----------------------------------------------------------------------===//
3277
// Global Method Pool and Selector Serialization
3278
//===----------------------------------------------------------------------===//
3279
3280
namespace {
3281
3282
// Trait used for the on-disk hash table used in the method pool.
3283
class ASTMethodPoolTrait {
3284
  ASTWriter &Writer;
3285
3286
public:
3287
  using key_type = Selector;
3288
  using key_type_ref = key_type;
3289
3290
  struct data_type {
3291
    SelectorID ID;
3292
    ObjCMethodList Instance, Factory;
3293
  };
3294
  using data_type_ref = const data_type &;
3295
3296
  using hash_value_type = unsigned;
3297
  using offset_type = unsigned;
3298
3299
0
  explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) {}
3300
3301
0
  static hash_value_type ComputeHash(Selector Sel) {
3302
0
    return serialization::ComputeHash(Sel);
3303
0
  }
3304
3305
  std::pair<unsigned, unsigned>
3306
    EmitKeyDataLength(raw_ostream& Out, Selector Sel,
3307
0
                      data_type_ref Methods) {
3308
0
    unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
3309
0
    unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
3310
0
    for (const ObjCMethodList *Method = &Methods.Instance; Method;
3311
0
         Method = Method->getNext())
3312
0
      if (ShouldWriteMethodListNode(Method))
3313
0
        DataLen += 4;
3314
0
    for (const ObjCMethodList *Method = &Methods.Factory; Method;
3315
0
         Method = Method->getNext())
3316
0
      if (ShouldWriteMethodListNode(Method))
3317
0
        DataLen += 4;
3318
0
    return emitULEBKeyDataLength(KeyLen, DataLen, Out);
3319
0
  }
3320
3321
0
  void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
3322
0
    using namespace llvm::support;
3323
3324
0
    endian::Writer LE(Out, llvm::endianness::little);
3325
0
    uint64_t Start = Out.tell();
3326
0
    assert((Start >> 32) == 0 && "Selector key offset too large");
3327
0
    Writer.SetSelectorOffset(Sel, Start);
3328
0
    unsigned N = Sel.getNumArgs();
3329
0
    LE.write<uint16_t>(N);
3330
0
    if (N == 0)
3331
0
      N = 1;
3332
0
    for (unsigned I = 0; I != N; ++I)
3333
0
      LE.write<uint32_t>(
3334
0
          Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
3335
0
  }
3336
3337
  void EmitData(raw_ostream& Out, key_type_ref,
3338
0
                data_type_ref Methods, unsigned DataLen) {
3339
0
    using namespace llvm::support;
3340
3341
0
    endian::Writer LE(Out, llvm::endianness::little);
3342
0
    uint64_t Start = Out.tell(); (void)Start;
3343
0
    LE.write<uint32_t>(Methods.ID);
3344
0
    unsigned NumInstanceMethods = 0;
3345
0
    for (const ObjCMethodList *Method = &Methods.Instance; Method;
3346
0
         Method = Method->getNext())
3347
0
      if (ShouldWriteMethodListNode(Method))
3348
0
        ++NumInstanceMethods;
3349
3350
0
    unsigned NumFactoryMethods = 0;
3351
0
    for (const ObjCMethodList *Method = &Methods.Factory; Method;
3352
0
         Method = Method->getNext())
3353
0
      if (ShouldWriteMethodListNode(Method))
3354
0
        ++NumFactoryMethods;
3355
3356
0
    unsigned InstanceBits = Methods.Instance.getBits();
3357
0
    assert(InstanceBits < 4);
3358
0
    unsigned InstanceHasMoreThanOneDeclBit =
3359
0
        Methods.Instance.hasMoreThanOneDecl();
3360
0
    unsigned FullInstanceBits = (NumInstanceMethods << 3) |
3361
0
                                (InstanceHasMoreThanOneDeclBit << 2) |
3362
0
                                InstanceBits;
3363
0
    unsigned FactoryBits = Methods.Factory.getBits();
3364
0
    assert(FactoryBits < 4);
3365
0
    unsigned FactoryHasMoreThanOneDeclBit =
3366
0
        Methods.Factory.hasMoreThanOneDecl();
3367
0
    unsigned FullFactoryBits = (NumFactoryMethods << 3) |
3368
0
                               (FactoryHasMoreThanOneDeclBit << 2) |
3369
0
                               FactoryBits;
3370
0
    LE.write<uint16_t>(FullInstanceBits);
3371
0
    LE.write<uint16_t>(FullFactoryBits);
3372
0
    for (const ObjCMethodList *Method = &Methods.Instance; Method;
3373
0
         Method = Method->getNext())
3374
0
      if (ShouldWriteMethodListNode(Method))
3375
0
        LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
3376
0
    for (const ObjCMethodList *Method = &Methods.Factory; Method;
3377
0
         Method = Method->getNext())
3378
0
      if (ShouldWriteMethodListNode(Method))
3379
0
        LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
3380
3381
0
    assert(Out.tell() - Start == DataLen && "Data length is wrong");
3382
0
  }
3383
3384
private:
3385
0
  static bool ShouldWriteMethodListNode(const ObjCMethodList *Node) {
3386
0
    return (Node->getMethod() && !Node->getMethod()->isFromASTFile());
3387
0
  }
3388
};
3389
3390
} // namespace
3391
3392
/// Write ObjC data: selectors and the method pool.
3393
///
3394
/// The method pool contains both instance and factory methods, stored
3395
/// in an on-disk hash table indexed by the selector. The hash table also
3396
/// contains an empty entry for every other selector known to Sema.
3397
0
void ASTWriter::WriteSelectors(Sema &SemaRef) {
3398
0
  using namespace llvm;
3399
3400
  // Do we have to do anything at all?
3401
0
  if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
3402
0
    return;
3403
0
  unsigned NumTableEntries = 0;
3404
  // Create and write out the blob that contains selectors and the method pool.
3405
0
  {
3406
0
    llvm::OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
3407
0
    ASTMethodPoolTrait Trait(*this);
3408
3409
    // Create the on-disk hash table representation. We walk through every
3410
    // selector we've seen and look it up in the method pool.
3411
0
    SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
3412
0
    for (auto &SelectorAndID : SelectorIDs) {
3413
0
      Selector S = SelectorAndID.first;
3414
0
      SelectorID ID = SelectorAndID.second;
3415
0
      Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
3416
0
      ASTMethodPoolTrait::data_type Data = {
3417
0
        ID,
3418
0
        ObjCMethodList(),
3419
0
        ObjCMethodList()
3420
0
      };
3421
0
      if (F != SemaRef.MethodPool.end()) {
3422
0
        Data.Instance = F->second.first;
3423
0
        Data.Factory = F->second.second;
3424
0
      }
3425
      // Only write this selector if it's not in an existing AST or something
3426
      // changed.
3427
0
      if (Chain && ID < FirstSelectorID) {
3428
        // Selector already exists. Did it change?
3429
0
        bool changed = false;
3430
0
        for (ObjCMethodList *M = &Data.Instance; M && M->getMethod();
3431
0
             M = M->getNext()) {
3432
0
          if (!M->getMethod()->isFromASTFile()) {
3433
0
            changed = true;
3434
0
            Data.Instance = *M;
3435
0
            break;
3436
0
          }
3437
0
        }
3438
0
        for (ObjCMethodList *M = &Data.Factory; M && M->getMethod();
3439
0
             M = M->getNext()) {
3440
0
          if (!M->getMethod()->isFromASTFile()) {
3441
0
            changed = true;
3442
0
            Data.Factory = *M;
3443
0
            break;
3444
0
          }
3445
0
        }
3446
0
        if (!changed)
3447
0
          continue;
3448
0
      } else if (Data.Instance.getMethod() || Data.Factory.getMethod()) {
3449
        // A new method pool entry.
3450
0
        ++NumTableEntries;
3451
0
      }
3452
0
      Generator.insert(S, Data, Trait);
3453
0
    }
3454
3455
    // Create the on-disk hash table in a buffer.
3456
0
    SmallString<4096> MethodPool;
3457
0
    uint32_t BucketOffset;
3458
0
    {
3459
0
      using namespace llvm::support;
3460
3461
0
      ASTMethodPoolTrait Trait(*this);
3462
0
      llvm::raw_svector_ostream Out(MethodPool);
3463
      // Make sure that no bucket is at offset 0
3464
0
      endian::write<uint32_t>(Out, 0, llvm::endianness::little);
3465
0
      BucketOffset = Generator.Emit(Out, Trait);
3466
0
    }
3467
3468
    // Create a blob abbreviation
3469
0
    auto Abbrev = std::make_shared<BitCodeAbbrev>();
3470
0
    Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
3471
0
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3472
0
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3473
0
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3474
0
    unsigned MethodPoolAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3475
3476
    // Write the method pool
3477
0
    {
3478
0
      RecordData::value_type Record[] = {METHOD_POOL, BucketOffset,
3479
0
                                         NumTableEntries};
3480
0
      Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool);
3481
0
    }
3482
3483
    // Create a blob abbreviation for the selector table offsets.
3484
0
    Abbrev = std::make_shared<BitCodeAbbrev>();
3485
0
    Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
3486
0
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
3487
0
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
3488
0
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3489
0
    unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3490
3491
    // Write the selector offsets table.
3492
0
    {
3493
0
      RecordData::value_type Record[] = {
3494
0
          SELECTOR_OFFSETS, SelectorOffsets.size(),
3495
0
          FirstSelectorID - NUM_PREDEF_SELECTOR_IDS};
3496
0
      Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
3497
0
                                bytes(SelectorOffsets));
3498
0
    }
3499
0
  }
3500
0
}
3501
3502
/// Write the selectors referenced in @selector expression into AST file.
3503
0
void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
3504
0
  using namespace llvm;
3505
3506
0
  if (SemaRef.ReferencedSelectors.empty())
3507
0
    return;
3508
3509
0
  RecordData Record;
3510
0
  ASTRecordWriter Writer(*this, Record);
3511
3512
  // Note: this writes out all references even for a dependent AST. But it is
3513
  // very tricky to fix, and given that @selector shouldn't really appear in
3514
  // headers, probably not worth it. It's not a correctness issue.
3515
0
  for (auto &SelectorAndLocation : SemaRef.ReferencedSelectors) {
3516
0
    Selector Sel = SelectorAndLocation.first;
3517
0
    SourceLocation Loc = SelectorAndLocation.second;
3518
0
    Writer.AddSelectorRef(Sel);
3519
0
    Writer.AddSourceLocation(Loc);
3520
0
  }
3521
0
  Writer.Emit(REFERENCED_SELECTOR_POOL);
3522
0
}
3523
3524
//===----------------------------------------------------------------------===//
3525
// Identifier Table Serialization
3526
//===----------------------------------------------------------------------===//
3527
3528
/// Determine the declaration that should be put into the name lookup table to
3529
/// represent the given declaration in this module. This is usually D itself,
3530
/// but if D was imported and merged into a local declaration, we want the most
3531
/// recent local declaration instead. The chosen declaration will be the most
3532
/// recent declaration in any module that imports this one.
3533
static NamedDecl *getDeclForLocalLookup(const LangOptions &LangOpts,
3534
0
                                        NamedDecl *D) {
3535
0
  if (!LangOpts.Modules || !D->isFromASTFile())
3536
0
    return D;
3537
3538
0
  if (Decl *Redecl = D->getPreviousDecl()) {
3539
    // For Redeclarable decls, a prior declaration might be local.
3540
0
    for (; Redecl; Redecl = Redecl->getPreviousDecl()) {
3541
      // If we find a local decl, we're done.
3542
0
      if (!Redecl->isFromASTFile()) {
3543
        // Exception: in very rare cases (for injected-class-names), not all
3544
        // redeclarations are in the same semantic context. Skip ones in a
3545
        // different context. They don't go in this lookup table at all.
3546
0
        if (!Redecl->getDeclContext()->getRedeclContext()->Equals(
3547
0
                D->getDeclContext()->getRedeclContext()))
3548
0
          continue;
3549
0
        return cast<NamedDecl>(Redecl);
3550
0
      }
3551
3552
      // If we find a decl from a (chained-)PCH stop since we won't find a
3553
      // local one.
3554
0
      if (Redecl->getOwningModuleID() == 0)
3555
0
        break;
3556
0
    }
3557
0
  } else if (Decl *First = D->getCanonicalDecl()) {
3558
    // For Mergeable decls, the first decl might be local.
3559
0
    if (!First->isFromASTFile())
3560
0
      return cast<NamedDecl>(First);
3561
0
  }
3562
3563
  // All declarations are imported. Our most recent declaration will also be
3564
  // the most recent one in anyone who imports us.
3565
0
  return D;
3566
0
}
3567
3568
namespace {
3569
3570
class ASTIdentifierTableTrait {
3571
  ASTWriter &Writer;
3572
  Preprocessor &PP;
3573
  IdentifierResolver &IdResolver;
3574
  bool IsModule;
3575
  bool NeedDecls;
3576
  ASTWriter::RecordData *InterestingIdentifierOffsets;
3577
3578
  /// Determines whether this is an "interesting" identifier that needs a
3579
  /// full IdentifierInfo structure written into the hash table. Notably, this
3580
  /// doesn't check whether the name has macros defined; use PublicMacroIterator
3581
  /// to check that.
3582
0
  bool isInterestingIdentifier(const IdentifierInfo *II, uint64_t MacroOffset) {
3583
0
    if (MacroOffset || II->isPoisoned() ||
3584
0
        (!IsModule && II->getObjCOrBuiltinID()) ||
3585
0
        II->hasRevertedTokenIDToIdentifier() ||
3586
0
        (NeedDecls && II->getFETokenInfo()))
3587
0
      return true;
3588
3589
0
    return false;
3590
0
  }
3591
3592
public:
3593
  using key_type = IdentifierInfo *;
3594
  using key_type_ref = key_type;
3595
3596
  using data_type = IdentID;
3597
  using data_type_ref = data_type;
3598
3599
  using hash_value_type = unsigned;
3600
  using offset_type = unsigned;
3601
3602
  ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
3603
                          IdentifierResolver &IdResolver, bool IsModule,
3604
                          ASTWriter::RecordData *InterestingIdentifierOffsets)
3605
      : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule),
3606
        NeedDecls(!IsModule || !Writer.getLangOpts().CPlusPlus),
3607
0
        InterestingIdentifierOffsets(InterestingIdentifierOffsets) {}
3608
3609
0
  bool needDecls() const { return NeedDecls; }
3610
3611
0
  static hash_value_type ComputeHash(const IdentifierInfo* II) {
3612
0
    return llvm::djbHash(II->getName());
3613
0
  }
3614
3615
0
  bool isInterestingIdentifier(const IdentifierInfo *II) {
3616
0
    auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3617
0
    return isInterestingIdentifier(II, MacroOffset);
3618
0
  }
3619
3620
0
  bool isInterestingNonMacroIdentifier(const IdentifierInfo *II) {
3621
0
    return isInterestingIdentifier(II, 0);
3622
0
  }
3623
3624
  std::pair<unsigned, unsigned>
3625
0
  EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
3626
    // Record the location of the identifier data. This is used when generating
3627
    // the mapping from persistent IDs to strings.
3628
0
    Writer.SetIdentifierOffset(II, Out.tell());
3629
3630
0
    auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3631
3632
    // Emit the offset of the key/data length information to the interesting
3633
    // identifiers table if necessary.
3634
0
    if (InterestingIdentifierOffsets &&
3635
0
        isInterestingIdentifier(II, MacroOffset))
3636
0
      InterestingIdentifierOffsets->push_back(Out.tell());
3637
3638
0
    unsigned KeyLen = II->getLength() + 1;
3639
0
    unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
3640
0
    if (isInterestingIdentifier(II, MacroOffset)) {
3641
0
      DataLen += 2; // 2 bytes for builtin ID
3642
0
      DataLen += 2; // 2 bytes for flags
3643
0
      if (MacroOffset)
3644
0
        DataLen += 4; // MacroDirectives offset.
3645
3646
0
      if (NeedDecls)
3647
0
        DataLen += std::distance(IdResolver.begin(II), IdResolver.end()) * 4;
3648
0
    }
3649
0
    return emitULEBKeyDataLength(KeyLen, DataLen, Out);
3650
0
  }
3651
3652
  void EmitKey(raw_ostream& Out, const IdentifierInfo* II,
3653
0
               unsigned KeyLen) {
3654
0
    Out.write(II->getNameStart(), KeyLen);
3655
0
  }
3656
3657
  void EmitData(raw_ostream& Out, IdentifierInfo* II,
3658
0
                IdentID ID, unsigned) {
3659
0
    using namespace llvm::support;
3660
3661
0
    endian::Writer LE(Out, llvm::endianness::little);
3662
3663
0
    auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3664
0
    if (!isInterestingIdentifier(II, MacroOffset)) {
3665
0
      LE.write<uint32_t>(ID << 1);
3666
0
      return;
3667
0
    }
3668
3669
0
    LE.write<uint32_t>((ID << 1) | 0x01);
3670
0
    uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID();
3671
0
    assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader.");
3672
0
    LE.write<uint16_t>(Bits);
3673
0
    Bits = 0;
3674
0
    bool HadMacroDefinition = MacroOffset != 0;
3675
0
    Bits = (Bits << 1) | unsigned(HadMacroDefinition);
3676
0
    Bits = (Bits << 1) | unsigned(II->isExtensionToken());
3677
0
    Bits = (Bits << 1) | unsigned(II->isPoisoned());
3678
0
    Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
3679
0
    Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
3680
0
    LE.write<uint16_t>(Bits);
3681
3682
0
    if (HadMacroDefinition)
3683
0
      LE.write<uint32_t>(MacroOffset);
3684
3685
0
    if (NeedDecls) {
3686
      // Emit the declaration IDs in reverse order, because the
3687
      // IdentifierResolver provides the declarations as they would be
3688
      // visible (e.g., the function "stat" would come before the struct
3689
      // "stat"), but the ASTReader adds declarations to the end of the list
3690
      // (so we need to see the struct "stat" before the function "stat").
3691
      // Only emit declarations that aren't from a chained PCH, though.
3692
0
      SmallVector<NamedDecl *, 16> Decls(IdResolver.decls(II));
3693
0
      for (NamedDecl *D : llvm::reverse(Decls))
3694
0
        LE.write<uint32_t>(
3695
0
            Writer.getDeclID(getDeclForLocalLookup(PP.getLangOpts(), D)));
3696
0
    }
3697
0
  }
3698
};
3699
3700
} // namespace
3701
3702
/// Write the identifier table into the AST file.
3703
///
3704
/// The identifier table consists of a blob containing string data
3705
/// (the actual identifiers themselves) and a separate "offsets" index
3706
/// that maps identifier IDs to locations within the blob.
3707
void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
3708
                                     IdentifierResolver &IdResolver,
3709
0
                                     bool IsModule) {
3710
0
  using namespace llvm;
3711
3712
0
  RecordData InterestingIdents;
3713
3714
  // Create and write out the blob that contains the identifier
3715
  // strings.
3716
0
  {
3717
0
    llvm::OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
3718
0
    ASTIdentifierTableTrait Trait(*this, PP, IdResolver, IsModule,
3719
0
                                  IsModule ? &InterestingIdents : nullptr);
3720
3721
    // Look for any identifiers that were named while processing the
3722
    // headers, but are otherwise not needed. We add these to the hash
3723
    // table to enable checking of the predefines buffer in the case
3724
    // where the user adds new macro definitions when building the AST
3725
    // file.
3726
0
    SmallVector<const IdentifierInfo *, 128> IIs;
3727
0
    for (const auto &ID : PP.getIdentifierTable())
3728
0
      if (Trait.isInterestingNonMacroIdentifier(ID.second))
3729
0
        IIs.push_back(ID.second);
3730
    // Sort the identifiers lexicographically before getting the references so
3731
    // that their order is stable.
3732
0
    llvm::sort(IIs, llvm::deref<std::less<>>());
3733
0
    for (const IdentifierInfo *II : IIs)
3734
0
      getIdentifierRef(II);
3735
3736
    // Create the on-disk hash table representation. We only store offsets
3737
    // for identifiers that appear here for the first time.
3738
0
    IdentifierOffsets.resize(NextIdentID - FirstIdentID);
3739
0
    for (auto IdentIDPair : IdentifierIDs) {
3740
0
      auto *II = const_cast<IdentifierInfo *>(IdentIDPair.first);
3741
0
      IdentID ID = IdentIDPair.second;
3742
0
      assert(II && "NULL identifier in identifier table");
3743
      // Write out identifiers if either the ID is local or the identifier has
3744
      // changed since it was loaded.
3745
0
      if (ID >= FirstIdentID || !Chain || !II->isFromAST()
3746
0
          || II->hasChangedSinceDeserialization() ||
3747
0
          (Trait.needDecls() &&
3748
0
           II->hasFETokenInfoChangedSinceDeserialization()))
3749
0
        Generator.insert(II, ID, Trait);
3750
0
    }
3751
3752
    // Create the on-disk hash table in a buffer.
3753
0
    SmallString<4096> IdentifierTable;
3754
0
    uint32_t BucketOffset;
3755
0
    {
3756
0
      using namespace llvm::support;
3757
3758
0
      llvm::raw_svector_ostream Out(IdentifierTable);
3759
      // Make sure that no bucket is at offset 0
3760
0
      endian::write<uint32_t>(Out, 0, llvm::endianness::little);
3761
0
      BucketOffset = Generator.Emit(Out, Trait);
3762
0
    }
3763
3764
    // Create a blob abbreviation
3765
0
    auto Abbrev = std::make_shared<BitCodeAbbrev>();
3766
0
    Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
3767
0
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3768
0
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3769
0
    unsigned IDTableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3770
3771
    // Write the identifier table
3772
0
    RecordData::value_type Record[] = {IDENTIFIER_TABLE, BucketOffset};
3773
0
    Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable);
3774
0
  }
3775
3776
  // Write the offsets table for identifier IDs.
3777
0
  auto Abbrev = std::make_shared<BitCodeAbbrev>();
3778
0
  Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
3779
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
3780
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
3781
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3782
0
  unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3783
3784
0
#ifndef NDEBUG
3785
0
  for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I)
3786
0
    assert(IdentifierOffsets[I] && "Missing identifier offset?");
3787
0
#endif
3788
3789
0
  RecordData::value_type Record[] = {IDENTIFIER_OFFSET,
3790
0
                                     IdentifierOffsets.size(),
3791
0
                                     FirstIdentID - NUM_PREDEF_IDENT_IDS};
3792
0
  Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
3793
0
                            bytes(IdentifierOffsets));
3794
3795
  // In C++, write the list of interesting identifiers (those that are
3796
  // defined as macros, poisoned, or similar unusual things).
3797
0
  if (!InterestingIdents.empty())
3798
0
    Stream.EmitRecord(INTERESTING_IDENTIFIERS, InterestingIdents);
3799
0
}
3800
3801
//===----------------------------------------------------------------------===//
3802
// DeclContext's Name Lookup Table Serialization
3803
//===----------------------------------------------------------------------===//
3804
3805
namespace {
3806
3807
// Trait used for the on-disk hash table used in the method pool.
3808
class ASTDeclContextNameLookupTrait {
3809
  ASTWriter &Writer;
3810
  llvm::SmallVector<DeclID, 64> DeclIDs;
3811
3812
public:
3813
  using key_type = DeclarationNameKey;
3814
  using key_type_ref = key_type;
3815
3816
  /// A start and end index into DeclIDs, representing a sequence of decls.
3817
  using data_type = std::pair<unsigned, unsigned>;
3818
  using data_type_ref = const data_type &;
3819
3820
  using hash_value_type = unsigned;
3821
  using offset_type = unsigned;
3822
3823
0
  explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) {}
3824
3825
  template<typename Coll>
3826
0
  data_type getData(const Coll &Decls) {
3827
0
    unsigned Start = DeclIDs.size();
3828
0
    for (NamedDecl *D : Decls) {
3829
0
      DeclIDs.push_back(
3830
0
          Writer.GetDeclRef(getDeclForLocalLookup(Writer.getLangOpts(), D)));
3831
0
    }
3832
0
    return std::make_pair(Start, DeclIDs.size());
3833
0
  }
Unexecuted instantiation: ASTWriter.cpp:std::__1::pair<unsigned int, unsigned int> (anonymous namespace)::ASTDeclContextNameLookupTrait::getData<clang::DeclContextLookupResult>(clang::DeclContextLookupResult const&)
Unexecuted instantiation: ASTWriter.cpp:std::__1::pair<unsigned int, unsigned int> (anonymous namespace)::ASTDeclContextNameLookupTrait::getData<llvm::SmallVector<clang::NamedDecl*, 8u> >(llvm::SmallVector<clang::NamedDecl*, 8u> const&)
3834
3835
0
  data_type ImportData(const reader::ASTDeclContextNameLookupTrait::data_type &FromReader) {
3836
0
    unsigned Start = DeclIDs.size();
3837
0
    llvm::append_range(DeclIDs, FromReader);
3838
0
    return std::make_pair(Start, DeclIDs.size());
3839
0
  }
3840
3841
0
  static bool EqualKey(key_type_ref a, key_type_ref b) {
3842
0
    return a == b;
3843
0
  }
3844
3845
0
  hash_value_type ComputeHash(DeclarationNameKey Name) {
3846
0
    return Name.getHash();
3847
0
  }
3848
3849
0
  void EmitFileRef(raw_ostream &Out, ModuleFile *F) const {
3850
0
    assert(Writer.hasChain() &&
3851
0
           "have reference to loaded module file but no chain?");
3852
3853
0
    using namespace llvm::support;
3854
3855
0
    endian::write<uint32_t>(Out, Writer.getChain()->getModuleFileID(F),
3856
0
                            llvm::endianness::little);
3857
0
  }
3858
3859
  std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &Out,
3860
                                                  DeclarationNameKey Name,
3861
0
                                                  data_type_ref Lookup) {
3862
0
    unsigned KeyLen = 1;
3863
0
    switch (Name.getKind()) {
3864
0
    case DeclarationName::Identifier:
3865
0
    case DeclarationName::ObjCZeroArgSelector:
3866
0
    case DeclarationName::ObjCOneArgSelector:
3867
0
    case DeclarationName::ObjCMultiArgSelector:
3868
0
    case DeclarationName::CXXLiteralOperatorName:
3869
0
    case DeclarationName::CXXDeductionGuideName:
3870
0
      KeyLen += 4;
3871
0
      break;
3872
0
    case DeclarationName::CXXOperatorName:
3873
0
      KeyLen += 1;
3874
0
      break;
3875
0
    case DeclarationName::CXXConstructorName:
3876
0
    case DeclarationName::CXXDestructorName:
3877
0
    case DeclarationName::CXXConversionFunctionName:
3878
0
    case DeclarationName::CXXUsingDirective:
3879
0
      break;
3880
0
    }
3881
3882
    // 4 bytes for each DeclID.
3883
0
    unsigned DataLen = 4 * (Lookup.second - Lookup.first);
3884
3885
0
    return emitULEBKeyDataLength(KeyLen, DataLen, Out);
3886
0
  }
3887
3888
0
  void EmitKey(raw_ostream &Out, DeclarationNameKey Name, unsigned) {
3889
0
    using namespace llvm::support;
3890
3891
0
    endian::Writer LE(Out, llvm::endianness::little);
3892
0
    LE.write<uint8_t>(Name.getKind());
3893
0
    switch (Name.getKind()) {
3894
0
    case DeclarationName::Identifier:
3895
0
    case DeclarationName::CXXLiteralOperatorName:
3896
0
    case DeclarationName::CXXDeductionGuideName:
3897
0
      LE.write<uint32_t>(Writer.getIdentifierRef(Name.getIdentifier()));
3898
0
      return;
3899
0
    case DeclarationName::ObjCZeroArgSelector:
3900
0
    case DeclarationName::ObjCOneArgSelector:
3901
0
    case DeclarationName::ObjCMultiArgSelector:
3902
0
      LE.write<uint32_t>(Writer.getSelectorRef(Name.getSelector()));
3903
0
      return;
3904
0
    case DeclarationName::CXXOperatorName:
3905
0
      assert(Name.getOperatorKind() < NUM_OVERLOADED_OPERATORS &&
3906
0
             "Invalid operator?");
3907
0
      LE.write<uint8_t>(Name.getOperatorKind());
3908
0
      return;
3909
0
    case DeclarationName::CXXConstructorName:
3910
0
    case DeclarationName::CXXDestructorName:
3911
0
    case DeclarationName::CXXConversionFunctionName:
3912
0
    case DeclarationName::CXXUsingDirective:
3913
0
      return;
3914
0
    }
3915
3916
0
    llvm_unreachable("Invalid name kind?");
3917
0
  }
3918
3919
  void EmitData(raw_ostream &Out, key_type_ref, data_type Lookup,
3920
0
                unsigned DataLen) {
3921
0
    using namespace llvm::support;
3922
3923
0
    endian::Writer LE(Out, llvm::endianness::little);
3924
0
    uint64_t Start = Out.tell(); (void)Start;
3925
0
    for (unsigned I = Lookup.first, N = Lookup.second; I != N; ++I)
3926
0
      LE.write<uint32_t>(DeclIDs[I]);
3927
0
    assert(Out.tell() - Start == DataLen && "Data length is wrong");
3928
0
  }
3929
};
3930
3931
} // namespace
3932
3933
bool ASTWriter::isLookupResultExternal(StoredDeclsList &Result,
3934
0
                                       DeclContext *DC) {
3935
0
  return Result.hasExternalDecls() &&
3936
0
         DC->hasNeedToReconcileExternalVisibleStorage();
3937
0
}
3938
3939
bool ASTWriter::isLookupResultEntirelyExternal(StoredDeclsList &Result,
3940
0
                                               DeclContext *DC) {
3941
0
  for (auto *D : Result.getLookupResult())
3942
0
    if (!getDeclForLocalLookup(getLangOpts(), D)->isFromASTFile())
3943
0
      return false;
3944
3945
0
  return true;
3946
0
}
3947
3948
void
3949
ASTWriter::GenerateNameLookupTable(const DeclContext *ConstDC,
3950
0
                                   llvm::SmallVectorImpl<char> &LookupTable) {
3951
0
  assert(!ConstDC->hasLazyLocalLexicalLookups() &&
3952
0
         !ConstDC->hasLazyExternalLexicalLookups() &&
3953
0
         "must call buildLookups first");
3954
3955
  // FIXME: We need to build the lookups table, which is logically const.
3956
0
  auto *DC = const_cast<DeclContext*>(ConstDC);
3957
0
  assert(DC == DC->getPrimaryContext() && "only primary DC has lookup table");
3958
3959
  // Create the on-disk hash table representation.
3960
0
  MultiOnDiskHashTableGenerator<reader::ASTDeclContextNameLookupTrait,
3961
0
                                ASTDeclContextNameLookupTrait> Generator;
3962
0
  ASTDeclContextNameLookupTrait Trait(*this);
3963
3964
  // The first step is to collect the declaration names which we need to
3965
  // serialize into the name lookup table, and to collect them in a stable
3966
  // order.
3967
0
  SmallVector<DeclarationName, 16> Names;
3968
3969
  // We also build up small sets of the constructor and conversion function
3970
  // names which are visible.
3971
0
  llvm::SmallPtrSet<DeclarationName, 8> ConstructorNameSet, ConversionNameSet;
3972
3973
0
  for (auto &Lookup : *DC->buildLookup()) {
3974
0
    auto &Name = Lookup.first;
3975
0
    auto &Result = Lookup.second;
3976
3977
    // If there are no local declarations in our lookup result, we
3978
    // don't need to write an entry for the name at all. If we can't
3979
    // write out a lookup set without performing more deserialization,
3980
    // just skip this entry.
3981
0
    if (isLookupResultExternal(Result, DC) &&
3982
0
        isLookupResultEntirelyExternal(Result, DC))
3983
0
      continue;
3984
3985
    // We also skip empty results. If any of the results could be external and
3986
    // the currently available results are empty, then all of the results are
3987
    // external and we skip it above. So the only way we get here with an empty
3988
    // results is when no results could have been external *and* we have
3989
    // external results.
3990
    //
3991
    // FIXME: While we might want to start emitting on-disk entries for negative
3992
    // lookups into a decl context as an optimization, today we *have* to skip
3993
    // them because there are names with empty lookup results in decl contexts
3994
    // which we can't emit in any stable ordering: we lookup constructors and
3995
    // conversion functions in the enclosing namespace scope creating empty
3996
    // results for them. This in almost certainly a bug in Clang's name lookup,
3997
    // but that is likely to be hard or impossible to fix and so we tolerate it
3998
    // here by omitting lookups with empty results.
3999
0
    if (Lookup.second.getLookupResult().empty())
4000
0
      continue;
4001
4002
0
    switch (Lookup.first.getNameKind()) {
4003
0
    default:
4004
0
      Names.push_back(Lookup.first);
4005
0
      break;
4006
4007
0
    case DeclarationName::CXXConstructorName:
4008
0
      assert(isa<CXXRecordDecl>(DC) &&
4009
0
             "Cannot have a constructor name outside of a class!");
4010
0
      ConstructorNameSet.insert(Name);
4011
0
      break;
4012
4013
0
    case DeclarationName::CXXConversionFunctionName:
4014
0
      assert(isa<CXXRecordDecl>(DC) &&
4015
0
             "Cannot have a conversion function name outside of a class!");
4016
0
      ConversionNameSet.insert(Name);
4017
0
      break;
4018
0
    }
4019
0
  }
4020
4021
  // Sort the names into a stable order.
4022
0
  llvm::sort(Names);
4023
4024
0
  if (auto *D = dyn_cast<CXXRecordDecl>(DC)) {
4025
    // We need to establish an ordering of constructor and conversion function
4026
    // names, and they don't have an intrinsic ordering.
4027
4028
    // First we try the easy case by forming the current context's constructor
4029
    // name and adding that name first. This is a very useful optimization to
4030
    // avoid walking the lexical declarations in many cases, and it also
4031
    // handles the only case where a constructor name can come from some other
4032
    // lexical context -- when that name is an implicit constructor merged from
4033
    // another declaration in the redecl chain. Any non-implicit constructor or
4034
    // conversion function which doesn't occur in all the lexical contexts
4035
    // would be an ODR violation.
4036
0
    auto ImplicitCtorName = Context->DeclarationNames.getCXXConstructorName(
4037
0
        Context->getCanonicalType(Context->getRecordType(D)));
4038
0
    if (ConstructorNameSet.erase(ImplicitCtorName))
4039
0
      Names.push_back(ImplicitCtorName);
4040
4041
    // If we still have constructors or conversion functions, we walk all the
4042
    // names in the decl and add the constructors and conversion functions
4043
    // which are visible in the order they lexically occur within the context.
4044
0
    if (!ConstructorNameSet.empty() || !ConversionNameSet.empty())
4045
0
      for (Decl *ChildD : cast<CXXRecordDecl>(DC)->decls())
4046
0
        if (auto *ChildND = dyn_cast<NamedDecl>(ChildD)) {
4047
0
          auto Name = ChildND->getDeclName();
4048
0
          switch (Name.getNameKind()) {
4049
0
          default:
4050
0
            continue;
4051
4052
0
          case DeclarationName::CXXConstructorName:
4053
0
            if (ConstructorNameSet.erase(Name))
4054
0
              Names.push_back(Name);
4055
0
            break;
4056
4057
0
          case DeclarationName::CXXConversionFunctionName:
4058
0
            if (ConversionNameSet.erase(Name))
4059
0
              Names.push_back(Name);
4060
0
            break;
4061
0
          }
4062
4063
0
          if (ConstructorNameSet.empty() && ConversionNameSet.empty())
4064
0
            break;
4065
0
        }
4066
4067
0
    assert(ConstructorNameSet.empty() && "Failed to find all of the visible "
4068
0
                                         "constructors by walking all the "
4069
0
                                         "lexical members of the context.");
4070
0
    assert(ConversionNameSet.empty() && "Failed to find all of the visible "
4071
0
                                        "conversion functions by walking all "
4072
0
                                        "the lexical members of the context.");
4073
0
  }
4074
4075
  // Next we need to do a lookup with each name into this decl context to fully
4076
  // populate any results from external sources. We don't actually use the
4077
  // results of these lookups because we only want to use the results after all
4078
  // results have been loaded and the pointers into them will be stable.
4079
0
  for (auto &Name : Names)
4080
0
    DC->lookup(Name);
4081
4082
  // Now we need to insert the results for each name into the hash table. For
4083
  // constructor names and conversion function names, we actually need to merge
4084
  // all of the results for them into one list of results each and insert
4085
  // those.
4086
0
  SmallVector<NamedDecl *, 8> ConstructorDecls;
4087
0
  SmallVector<NamedDecl *, 8> ConversionDecls;
4088
4089
  // Now loop over the names, either inserting them or appending for the two
4090
  // special cases.
4091
0
  for (auto &Name : Names) {
4092
0
    DeclContext::lookup_result Result = DC->noload_lookup(Name);
4093
4094
0
    switch (Name.getNameKind()) {
4095
0
    default:
4096
0
      Generator.insert(Name, Trait.getData(Result), Trait);
4097
0
      break;
4098
4099
0
    case DeclarationName::CXXConstructorName:
4100
0
      ConstructorDecls.append(Result.begin(), Result.end());
4101
0
      break;
4102
4103
0
    case DeclarationName::CXXConversionFunctionName:
4104
0
      ConversionDecls.append(Result.begin(), Result.end());
4105
0
      break;
4106
0
    }
4107
0
  }
4108
4109
  // Handle our two special cases if we ended up having any. We arbitrarily use
4110
  // the first declaration's name here because the name itself isn't part of
4111
  // the key, only the kind of name is used.
4112
0
  if (!ConstructorDecls.empty())
4113
0
    Generator.insert(ConstructorDecls.front()->getDeclName(),
4114
0
                     Trait.getData(ConstructorDecls), Trait);
4115
0
  if (!ConversionDecls.empty())
4116
0
    Generator.insert(ConversionDecls.front()->getDeclName(),
4117
0
                     Trait.getData(ConversionDecls), Trait);
4118
4119
  // Create the on-disk hash table. Also emit the existing imported and
4120
  // merged table if there is one.
4121
0
  auto *Lookups = Chain ? Chain->getLoadedLookupTables(DC) : nullptr;
4122
0
  Generator.emit(LookupTable, Trait, Lookups ? &Lookups->Table : nullptr);
4123
0
}
4124
4125
/// Write the block containing all of the declaration IDs
4126
/// visible from the given DeclContext.
4127
///
4128
/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
4129
/// bitstream, or 0 if no block was written.
4130
uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
4131
0
                                                 DeclContext *DC) {
4132
  // If we imported a key declaration of this namespace, write the visible
4133
  // lookup results as an update record for it rather than including them
4134
  // on this declaration. We will only look at key declarations on reload.
4135
0
  if (isa<NamespaceDecl>(DC) && Chain &&
4136
0
      Chain->getKeyDeclaration(cast<Decl>(DC))->isFromASTFile()) {
4137
    // Only do this once, for the first local declaration of the namespace.
4138
0
    for (auto *Prev = cast<NamespaceDecl>(DC)->getPreviousDecl(); Prev;
4139
0
         Prev = Prev->getPreviousDecl())
4140
0
      if (!Prev->isFromASTFile())
4141
0
        return 0;
4142
4143
    // Note that we need to emit an update record for the primary context.
4144
0
    UpdatedDeclContexts.insert(DC->getPrimaryContext());
4145
4146
    // Make sure all visible decls are written. They will be recorded later. We
4147
    // do this using a side data structure so we can sort the names into
4148
    // a deterministic order.
4149
0
    StoredDeclsMap *Map = DC->getPrimaryContext()->buildLookup();
4150
0
    SmallVector<std::pair<DeclarationName, DeclContext::lookup_result>, 16>
4151
0
        LookupResults;
4152
0
    if (Map) {
4153
0
      LookupResults.reserve(Map->size());
4154
0
      for (auto &Entry : *Map)
4155
0
        LookupResults.push_back(
4156
0
            std::make_pair(Entry.first, Entry.second.getLookupResult()));
4157
0
    }
4158
4159
0
    llvm::sort(LookupResults, llvm::less_first());
4160
0
    for (auto &NameAndResult : LookupResults) {
4161
0
      DeclarationName Name = NameAndResult.first;
4162
0
      DeclContext::lookup_result Result = NameAndResult.second;
4163
0
      if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
4164
0
          Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
4165
        // We have to work around a name lookup bug here where negative lookup
4166
        // results for these names get cached in namespace lookup tables (these
4167
        // names should never be looked up in a namespace).
4168
0
        assert(Result.empty() && "Cannot have a constructor or conversion "
4169
0
                                 "function name in a namespace!");
4170
0
        continue;
4171
0
      }
4172
4173
0
      for (NamedDecl *ND : Result)
4174
0
        if (!ND->isFromASTFile())
4175
0
          GetDeclRef(ND);
4176
0
    }
4177
4178
0
    return 0;
4179
0
  }
4180
4181
0
  if (DC->getPrimaryContext() != DC)
4182
0
    return 0;
4183
4184
  // Skip contexts which don't support name lookup.
4185
0
  if (!DC->isLookupContext())
4186
0
    return 0;
4187
4188
  // If not in C++, we perform name lookup for the translation unit via the
4189
  // IdentifierInfo chains, don't bother to build a visible-declarations table.
4190
0
  if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
4191
0
    return 0;
4192
4193
  // Serialize the contents of the mapping used for lookup. Note that,
4194
  // although we have two very different code paths, the serialized
4195
  // representation is the same for both cases: a declaration name,
4196
  // followed by a size, followed by references to the visible
4197
  // declarations that have that name.
4198
0
  uint64_t Offset = Stream.GetCurrentBitNo();
4199
0
  StoredDeclsMap *Map = DC->buildLookup();
4200
0
  if (!Map || Map->empty())
4201
0
    return 0;
4202
4203
  // Create the on-disk hash table in a buffer.
4204
0
  SmallString<4096> LookupTable;
4205
0
  GenerateNameLookupTable(DC, LookupTable);
4206
4207
  // Write the lookup table
4208
0
  RecordData::value_type Record[] = {DECL_CONTEXT_VISIBLE};
4209
0
  Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
4210
0
                            LookupTable);
4211
0
  ++NumVisibleDeclContexts;
4212
0
  return Offset;
4213
0
}
4214
4215
/// Write an UPDATE_VISIBLE block for the given context.
4216
///
4217
/// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
4218
/// DeclContext in a dependent AST file. As such, they only exist for the TU
4219
/// (in C++), for namespaces, and for classes with forward-declared unscoped
4220
/// enumeration members (in C++11).
4221
0
void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
4222
0
  StoredDeclsMap *Map = DC->getLookupPtr();
4223
0
  if (!Map || Map->empty())
4224
0
    return;
4225
4226
  // Create the on-disk hash table in a buffer.
4227
0
  SmallString<4096> LookupTable;
4228
0
  GenerateNameLookupTable(DC, LookupTable);
4229
4230
  // If we're updating a namespace, select a key declaration as the key for the
4231
  // update record; those are the only ones that will be checked on reload.
4232
0
  if (isa<NamespaceDecl>(DC))
4233
0
    DC = cast<DeclContext>(Chain->getKeyDeclaration(cast<Decl>(DC)));
4234
4235
  // Write the lookup table
4236
0
  RecordData::value_type Record[] = {UPDATE_VISIBLE, getDeclID(cast<Decl>(DC))};
4237
0
  Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable);
4238
0
}
4239
4240
/// Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
4241
0
void ASTWriter::WriteFPPragmaOptions(const FPOptionsOverride &Opts) {
4242
0
  RecordData::value_type Record[] = {Opts.getAsOpaqueInt()};
4243
0
  Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
4244
0
}
4245
4246
/// Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
4247
0
void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
4248
0
  if (!SemaRef.Context.getLangOpts().OpenCL)
4249
0
    return;
4250
4251
0
  const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
4252
0
  RecordData Record;
4253
0
  for (const auto &I:Opts.OptMap) {
4254
0
    AddString(I.getKey(), Record);
4255
0
    auto V = I.getValue();
4256
0
    Record.push_back(V.Supported ? 1 : 0);
4257
0
    Record.push_back(V.Enabled ? 1 : 0);
4258
0
    Record.push_back(V.WithPragma ? 1 : 0);
4259
0
    Record.push_back(V.Avail);
4260
0
    Record.push_back(V.Core);
4261
0
    Record.push_back(V.Opt);
4262
0
  }
4263
0
  Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
4264
0
}
4265
0
void ASTWriter::WriteCUDAPragmas(Sema &SemaRef) {
4266
0
  if (SemaRef.ForceCUDAHostDeviceDepth > 0) {
4267
0
    RecordData::value_type Record[] = {SemaRef.ForceCUDAHostDeviceDepth};
4268
0
    Stream.EmitRecord(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH, Record);
4269
0
  }
4270
0
}
4271
4272
0
void ASTWriter::WriteObjCCategories() {
4273
0
  SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
4274
0
  RecordData Categories;
4275
4276
0
  for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
4277
0
    unsigned Size = 0;
4278
0
    unsigned StartIndex = Categories.size();
4279
4280
0
    ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
4281
4282
    // Allocate space for the size.
4283
0
    Categories.push_back(0);
4284
4285
    // Add the categories.
4286
0
    for (ObjCInterfaceDecl::known_categories_iterator
4287
0
           Cat = Class->known_categories_begin(),
4288
0
           CatEnd = Class->known_categories_end();
4289
0
         Cat != CatEnd; ++Cat, ++Size) {
4290
0
      assert(getDeclID(*Cat) != 0 && "Bogus category");
4291
0
      AddDeclRef(*Cat, Categories);
4292
0
    }
4293
4294
    // Update the size.
4295
0
    Categories[StartIndex] = Size;
4296
4297
    // Record this interface -> category map.
4298
0
    ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
4299
0
    CategoriesMap.push_back(CatInfo);
4300
0
  }
4301
4302
  // Sort the categories map by the definition ID, since the reader will be
4303
  // performing binary searches on this information.
4304
0
  llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
4305
4306
  // Emit the categories map.
4307
0
  using namespace llvm;
4308
4309
0
  auto Abbrev = std::make_shared<BitCodeAbbrev>();
4310
0
  Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
4311
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
4312
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4313
0
  unsigned AbbrevID = Stream.EmitAbbrev(std::move(Abbrev));
4314
4315
0
  RecordData::value_type Record[] = {OBJC_CATEGORIES_MAP, CategoriesMap.size()};
4316
0
  Stream.EmitRecordWithBlob(AbbrevID, Record,
4317
0
                            reinterpret_cast<char *>(CategoriesMap.data()),
4318
0
                            CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
4319
4320
  // Emit the category lists.
4321
0
  Stream.EmitRecord(OBJC_CATEGORIES, Categories);
4322
0
}
4323
4324
0
void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) {
4325
0
  Sema::LateParsedTemplateMapT &LPTMap = SemaRef.LateParsedTemplateMap;
4326
4327
0
  if (LPTMap.empty())
4328
0
    return;
4329
4330
0
  RecordData Record;
4331
0
  for (auto &LPTMapEntry : LPTMap) {
4332
0
    const FunctionDecl *FD = LPTMapEntry.first;
4333
0
    LateParsedTemplate &LPT = *LPTMapEntry.second;
4334
0
    AddDeclRef(FD, Record);
4335
0
    AddDeclRef(LPT.D, Record);
4336
0
    Record.push_back(LPT.FPO.getAsOpaqueInt());
4337
0
    Record.push_back(LPT.Toks.size());
4338
4339
0
    for (const auto &Tok : LPT.Toks) {
4340
0
      AddToken(Tok, Record);
4341
0
    }
4342
0
  }
4343
0
  Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record);
4344
0
}
4345
4346
/// Write the state of 'pragma clang optimize' at the end of the module.
4347
0
void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) {
4348
0
  RecordData Record;
4349
0
  SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation();
4350
0
  AddSourceLocation(PragmaLoc, Record);
4351
0
  Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record);
4352
0
}
4353
4354
/// Write the state of 'pragma ms_struct' at the end of the module.
4355
0
void ASTWriter::WriteMSStructPragmaOptions(Sema &SemaRef) {
4356
0
  RecordData Record;
4357
0
  Record.push_back(SemaRef.MSStructPragmaOn ? PMSST_ON : PMSST_OFF);
4358
0
  Stream.EmitRecord(MSSTRUCT_PRAGMA_OPTIONS, Record);
4359
0
}
4360
4361
/// Write the state of 'pragma pointers_to_members' at the end of the
4362
//module.
4363
0
void ASTWriter::WriteMSPointersToMembersPragmaOptions(Sema &SemaRef) {
4364
0
  RecordData Record;
4365
0
  Record.push_back(SemaRef.MSPointerToMemberRepresentationMethod);
4366
0
  AddSourceLocation(SemaRef.ImplicitMSInheritanceAttrLoc, Record);
4367
0
  Stream.EmitRecord(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS, Record);
4368
0
}
4369
4370
/// Write the state of 'pragma align/pack' at the end of the module.
4371
0
void ASTWriter::WritePackPragmaOptions(Sema &SemaRef) {
4372
  // Don't serialize pragma align/pack state for modules, since it should only
4373
  // take effect on a per-submodule basis.
4374
0
  if (WritingModule)
4375
0
    return;
4376
4377
0
  RecordData Record;
4378
0
  AddAlignPackInfo(SemaRef.AlignPackStack.CurrentValue, Record);
4379
0
  AddSourceLocation(SemaRef.AlignPackStack.CurrentPragmaLocation, Record);
4380
0
  Record.push_back(SemaRef.AlignPackStack.Stack.size());
4381
0
  for (const auto &StackEntry : SemaRef.AlignPackStack.Stack) {
4382
0
    AddAlignPackInfo(StackEntry.Value, Record);
4383
0
    AddSourceLocation(StackEntry.PragmaLocation, Record);
4384
0
    AddSourceLocation(StackEntry.PragmaPushLocation, Record);
4385
0
    AddString(StackEntry.StackSlotLabel, Record);
4386
0
  }
4387
0
  Stream.EmitRecord(ALIGN_PACK_PRAGMA_OPTIONS, Record);
4388
0
}
4389
4390
/// Write the state of 'pragma float_control' at the end of the module.
4391
0
void ASTWriter::WriteFloatControlPragmaOptions(Sema &SemaRef) {
4392
  // Don't serialize pragma float_control state for modules,
4393
  // since it should only take effect on a per-submodule basis.
4394
0
  if (WritingModule)
4395
0
    return;
4396
4397
0
  RecordData Record;
4398
0
  Record.push_back(SemaRef.FpPragmaStack.CurrentValue.getAsOpaqueInt());
4399
0
  AddSourceLocation(SemaRef.FpPragmaStack.CurrentPragmaLocation, Record);
4400
0
  Record.push_back(SemaRef.FpPragmaStack.Stack.size());
4401
0
  for (const auto &StackEntry : SemaRef.FpPragmaStack.Stack) {
4402
0
    Record.push_back(StackEntry.Value.getAsOpaqueInt());
4403
0
    AddSourceLocation(StackEntry.PragmaLocation, Record);
4404
0
    AddSourceLocation(StackEntry.PragmaPushLocation, Record);
4405
0
    AddString(StackEntry.StackSlotLabel, Record);
4406
0
  }
4407
0
  Stream.EmitRecord(FLOAT_CONTROL_PRAGMA_OPTIONS, Record);
4408
0
}
4409
4410
void ASTWriter::WriteModuleFileExtension(Sema &SemaRef,
4411
0
                                         ModuleFileExtensionWriter &Writer) {
4412
  // Enter the extension block.
4413
0
  Stream.EnterSubblock(EXTENSION_BLOCK_ID, 4);
4414
4415
  // Emit the metadata record abbreviation.
4416
0
  auto Abv = std::make_shared<llvm::BitCodeAbbrev>();
4417
0
  Abv->Add(llvm::BitCodeAbbrevOp(EXTENSION_METADATA));
4418
0
  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4419
0
  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4420
0
  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4421
0
  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4422
0
  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4423
0
  unsigned Abbrev = Stream.EmitAbbrev(std::move(Abv));
4424
4425
  // Emit the metadata record.
4426
0
  RecordData Record;
4427
0
  auto Metadata = Writer.getExtension()->getExtensionMetadata();
4428
0
  Record.push_back(EXTENSION_METADATA);
4429
0
  Record.push_back(Metadata.MajorVersion);
4430
0
  Record.push_back(Metadata.MinorVersion);
4431
0
  Record.push_back(Metadata.BlockName.size());
4432
0
  Record.push_back(Metadata.UserInfo.size());
4433
0
  SmallString<64> Buffer;
4434
0
  Buffer += Metadata.BlockName;
4435
0
  Buffer += Metadata.UserInfo;
4436
0
  Stream.EmitRecordWithBlob(Abbrev, Record, Buffer);
4437
4438
  // Emit the contents of the extension block.
4439
0
  Writer.writeExtensionContents(SemaRef, Stream);
4440
4441
  // Exit the extension block.
4442
0
  Stream.ExitBlock();
4443
0
}
4444
4445
//===----------------------------------------------------------------------===//
4446
// General Serialization Routines
4447
//===----------------------------------------------------------------------===//
4448
4449
0
void ASTRecordWriter::AddAttr(const Attr *A) {
4450
0
  auto &Record = *this;
4451
  // FIXME: Clang can't handle the serialization/deserialization of
4452
  // preferred_name properly now. See
4453
  // https://github.com/llvm/llvm-project/issues/56490 for example.
4454
0
  if (!A || (isa<PreferredNameAttr>(A) &&
4455
0
             Writer->isWritingStdCXXNamedModules()))
4456
0
    return Record.push_back(0);
4457
4458
0
  Record.push_back(A->getKind() + 1); // FIXME: stable encoding, target attrs
4459
4460
0
  Record.AddIdentifierRef(A->getAttrName());
4461
0
  Record.AddIdentifierRef(A->getScopeName());
4462
0
  Record.AddSourceRange(A->getRange());
4463
0
  Record.AddSourceLocation(A->getScopeLoc());
4464
0
  Record.push_back(A->getParsedKind());
4465
0
  Record.push_back(A->getSyntax());
4466
0
  Record.push_back(A->getAttributeSpellingListIndexRaw());
4467
0
  Record.push_back(A->isRegularKeywordAttribute());
4468
4469
0
#include "clang/Serialization/AttrPCHWrite.inc"
4470
0
}
4471
4472
/// Emit the list of attributes to the specified record.
4473
0
void ASTRecordWriter::AddAttributes(ArrayRef<const Attr *> Attrs) {
4474
0
  push_back(Attrs.size());
4475
0
  for (const auto *A : Attrs)
4476
0
    AddAttr(A);
4477
0
}
4478
4479
0
void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) {
4480
0
  AddSourceLocation(Tok.getLocation(), Record);
4481
  // FIXME: Should translate token kind to a stable encoding.
4482
0
  Record.push_back(Tok.getKind());
4483
  // FIXME: Should translate token flags to a stable encoding.
4484
0
  Record.push_back(Tok.getFlags());
4485
4486
0
  if (Tok.isAnnotation()) {
4487
0
    AddSourceLocation(Tok.getAnnotationEndLoc(), Record);
4488
0
    switch (Tok.getKind()) {
4489
0
    case tok::annot_pragma_loop_hint: {
4490
0
      auto *Info = static_cast<PragmaLoopHintInfo *>(Tok.getAnnotationValue());
4491
0
      AddToken(Info->PragmaName, Record);
4492
0
      AddToken(Info->Option, Record);
4493
0
      Record.push_back(Info->Toks.size());
4494
0
      for (const auto &T : Info->Toks)
4495
0
        AddToken(T, Record);
4496
0
      break;
4497
0
    }
4498
0
    case tok::annot_pragma_pack: {
4499
0
      auto *Info =
4500
0
          static_cast<Sema::PragmaPackInfo *>(Tok.getAnnotationValue());
4501
0
      Record.push_back(static_cast<unsigned>(Info->Action));
4502
0
      AddString(Info->SlotLabel, Record);
4503
0
      AddToken(Info->Alignment, Record);
4504
0
      break;
4505
0
    }
4506
    // Some annotation tokens do not use the PtrData field.
4507
0
    case tok::annot_pragma_openmp:
4508
0
    case tok::annot_pragma_openmp_end:
4509
0
    case tok::annot_pragma_unused:
4510
0
    case tok::annot_pragma_openacc:
4511
0
    case tok::annot_pragma_openacc_end:
4512
0
      break;
4513
0
    default:
4514
0
      llvm_unreachable("missing serialization code for annotation token");
4515
0
    }
4516
0
  } else {
4517
0
    Record.push_back(Tok.getLength());
4518
    // FIXME: When reading literal tokens, reconstruct the literal pointer if it
4519
    // is needed.
4520
0
    AddIdentifierRef(Tok.getIdentifierInfo(), Record);
4521
0
  }
4522
0
}
4523
4524
0
void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
4525
0
  Record.push_back(Str.size());
4526
0
  Record.insert(Record.end(), Str.begin(), Str.end());
4527
0
}
4528
4529
0
bool ASTWriter::PreparePathForOutput(SmallVectorImpl<char> &Path) {
4530
0
  assert(Context && "should have context when outputting path");
4531
4532
  // Leave special file names as they are.
4533
0
  StringRef PathStr(Path.data(), Path.size());
4534
0
  if (PathStr == "<built-in>" || PathStr == "<command line>")
4535
0
    return false;
4536
4537
0
  bool Changed =
4538
0
      cleanPathForOutput(Context->getSourceManager().getFileManager(), Path);
4539
4540
  // Remove a prefix to make the path relative, if relevant.
4541
0
  const char *PathBegin = Path.data();
4542
0
  const char *PathPtr =
4543
0
      adjustFilenameForRelocatableAST(PathBegin, BaseDirectory);
4544
0
  if (PathPtr != PathBegin) {
4545
0
    Path.erase(Path.begin(), Path.begin() + (PathPtr - PathBegin));
4546
0
    Changed = true;
4547
0
  }
4548
4549
0
  return Changed;
4550
0
}
4551
4552
0
void ASTWriter::AddPath(StringRef Path, RecordDataImpl &Record) {
4553
0
  SmallString<128> FilePath(Path);
4554
0
  PreparePathForOutput(FilePath);
4555
0
  AddString(FilePath, Record);
4556
0
}
4557
4558
void ASTWriter::EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record,
4559
0
                                   StringRef Path) {
4560
0
  SmallString<128> FilePath(Path);
4561
0
  PreparePathForOutput(FilePath);
4562
0
  Stream.EmitRecordWithBlob(Abbrev, Record, FilePath);
4563
0
}
4564
4565
void ASTWriter::AddVersionTuple(const VersionTuple &Version,
4566
0
                                RecordDataImpl &Record) {
4567
0
  Record.push_back(Version.getMajor());
4568
0
  if (std::optional<unsigned> Minor = Version.getMinor())
4569
0
    Record.push_back(*Minor + 1);
4570
0
  else
4571
0
    Record.push_back(0);
4572
0
  if (std::optional<unsigned> Subminor = Version.getSubminor())
4573
0
    Record.push_back(*Subminor + 1);
4574
0
  else
4575
0
    Record.push_back(0);
4576
0
}
4577
4578
/// Note that the identifier II occurs at the given offset
4579
/// within the identifier table.
4580
0
void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
4581
0
  IdentID ID = IdentifierIDs[II];
4582
  // Only store offsets new to this AST file. Other identifier names are looked
4583
  // up earlier in the chain and thus don't need an offset.
4584
0
  if (ID >= FirstIdentID)
4585
0
    IdentifierOffsets[ID - FirstIdentID] = Offset;
4586
0
}
4587
4588
/// Note that the selector Sel occurs at the given offset
4589
/// within the method pool/selector table.
4590
0
void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
4591
0
  unsigned ID = SelectorIDs[Sel];
4592
0
  assert(ID && "Unknown selector");
4593
  // Don't record offsets for selectors that are also available in a different
4594
  // file.
4595
0
  if (ID < FirstSelectorID)
4596
0
    return;
4597
0
  SelectorOffsets[ID - FirstSelectorID] = Offset;
4598
0
}
4599
4600
ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream,
4601
                     SmallVectorImpl<char> &Buffer,
4602
                     InMemoryModuleCache &ModuleCache,
4603
                     ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
4604
                     bool IncludeTimestamps, bool BuildingImplicitModule)
4605
    : Stream(Stream), Buffer(Buffer), ModuleCache(ModuleCache),
4606
      IncludeTimestamps(IncludeTimestamps),
4607
0
      BuildingImplicitModule(BuildingImplicitModule) {
4608
0
  for (const auto &Ext : Extensions) {
4609
0
    if (auto Writer = Ext->createExtensionWriter(*this))
4610
0
      ModuleFileExtensionWriters.push_back(std::move(Writer));
4611
0
  }
4612
0
}
4613
4614
0
ASTWriter::~ASTWriter() = default;
4615
4616
0
const LangOptions &ASTWriter::getLangOpts() const {
4617
0
  assert(WritingAST && "can't determine lang opts when not writing AST");
4618
0
  return Context->getLangOpts();
4619
0
}
4620
4621
0
time_t ASTWriter::getTimestampForOutput(const FileEntry *E) const {
4622
0
  return IncludeTimestamps ? E->getModificationTime() : 0;
4623
0
}
4624
4625
ASTFileSignature ASTWriter::WriteAST(Sema &SemaRef, StringRef OutputFile,
4626
                                     Module *WritingModule, StringRef isysroot,
4627
0
                                     bool ShouldCacheASTInMemory) {
4628
0
  llvm::TimeTraceScope scope("WriteAST", OutputFile);
4629
0
  WritingAST = true;
4630
4631
0
  ASTHasCompilerErrors =
4632
0
      SemaRef.PP.getDiagnostics().hasUncompilableErrorOccurred();
4633
4634
  // Emit the file header.
4635
0
  Stream.Emit((unsigned)'C', 8);
4636
0
  Stream.Emit((unsigned)'P', 8);
4637
0
  Stream.Emit((unsigned)'C', 8);
4638
0
  Stream.Emit((unsigned)'H', 8);
4639
4640
0
  WriteBlockInfoBlock();
4641
4642
0
  Context = &SemaRef.Context;
4643
0
  PP = &SemaRef.PP;
4644
0
  this->WritingModule = WritingModule;
4645
0
  ASTFileSignature Signature = WriteASTCore(SemaRef, isysroot, WritingModule);
4646
0
  Context = nullptr;
4647
0
  PP = nullptr;
4648
0
  this->WritingModule = nullptr;
4649
0
  this->BaseDirectory.clear();
4650
4651
0
  WritingAST = false;
4652
0
  if (ShouldCacheASTInMemory) {
4653
    // Construct MemoryBuffer and update buffer manager.
4654
0
    ModuleCache.addBuiltPCM(OutputFile,
4655
0
                            llvm::MemoryBuffer::getMemBufferCopy(
4656
0
                                StringRef(Buffer.begin(), Buffer.size())));
4657
0
  }
4658
0
  return Signature;
4659
0
}
4660
4661
template<typename Vector>
4662
static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
4663
0
                               ASTWriter::RecordData &Record) {
4664
0
  for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
4665
0
       I != E; ++I) {
4666
0
    Writer.AddDeclRef(*I, Record);
4667
0
  }
4668
0
}
Unexecuted instantiation: ASTWriter.cpp:void AddLazyVectorDecls<clang::LazyVector<clang::VarDecl*, clang::ExternalSemaSource, &clang::ExternalSemaSource::ReadTentativeDefinitions, 2u, 2u> >(clang::ASTWriter&, clang::LazyVector<clang::VarDecl*, clang::ExternalSemaSource, &clang::ExternalSemaSource::ReadTentativeDefinitions, 2u, 2u>&, llvm::SmallVector<unsigned long, 64u>&)
Unexecuted instantiation: ASTWriter.cpp:void AddLazyVectorDecls<clang::LazyVector<clang::DeclaratorDecl const*, clang::ExternalSemaSource, &clang::ExternalSemaSource::ReadUnusedFileScopedDecls, 2u, 2u> >(clang::ASTWriter&, clang::LazyVector<clang::DeclaratorDecl const*, clang::ExternalSemaSource, &clang::ExternalSemaSource::ReadUnusedFileScopedDecls, 2u, 2u>&, llvm::SmallVector<unsigned long, 64u>&)
Unexecuted instantiation: ASTWriter.cpp:void AddLazyVectorDecls<clang::LazyVector<clang::CXXConstructorDecl*, clang::ExternalSemaSource, &clang::ExternalSemaSource::ReadDelegatingConstructors, 2u, 2u> >(clang::ASTWriter&, clang::LazyVector<clang::CXXConstructorDecl*, clang::ExternalSemaSource, &clang::ExternalSemaSource::ReadDelegatingConstructors, 2u, 2u>&, llvm::SmallVector<unsigned long, 64u>&)
Unexecuted instantiation: ASTWriter.cpp:void AddLazyVectorDecls<clang::LazyVector<clang::TypedefNameDecl*, clang::ExternalSemaSource, &clang::ExternalSemaSource::ReadExtVectorDecls, 2u, 2u> >(clang::ASTWriter&, clang::LazyVector<clang::TypedefNameDecl*, clang::ExternalSemaSource, &clang::ExternalSemaSource::ReadExtVectorDecls, 2u, 2u>&, llvm::SmallVector<unsigned long, 64u>&)
4669
4670
0
void ASTWriter::collectNonAffectingInputFiles() {
4671
0
  SourceManager &SrcMgr = PP->getSourceManager();
4672
0
  unsigned N = SrcMgr.local_sloc_entry_size();
4673
4674
0
  IsSLocAffecting.resize(N, true);
4675
4676
0
  if (!WritingModule)
4677
0
    return;
4678
4679
0
  auto AffectingModuleMaps = GetAffectingModuleMaps(*PP, WritingModule);
4680
4681
0
  unsigned FileIDAdjustment = 0;
4682
0
  unsigned OffsetAdjustment = 0;
4683
4684
0
  NonAffectingFileIDAdjustments.reserve(N);
4685
0
  NonAffectingOffsetAdjustments.reserve(N);
4686
4687
0
  NonAffectingFileIDAdjustments.push_back(FileIDAdjustment);
4688
0
  NonAffectingOffsetAdjustments.push_back(OffsetAdjustment);
4689
4690
0
  for (unsigned I = 1; I != N; ++I) {
4691
0
    const SrcMgr::SLocEntry *SLoc = &SrcMgr.getLocalSLocEntry(I);
4692
0
    FileID FID = FileID::get(I);
4693
0
    assert(&SrcMgr.getSLocEntry(FID) == SLoc);
4694
4695
0
    if (!SLoc->isFile())
4696
0
      continue;
4697
0
    const SrcMgr::FileInfo &File = SLoc->getFile();
4698
0
    const SrcMgr::ContentCache *Cache = &File.getContentCache();
4699
0
    if (!Cache->OrigEntry)
4700
0
      continue;
4701
4702
0
    if (!isModuleMap(File.getFileCharacteristic()) ||
4703
0
        AffectingModuleMaps.empty() ||
4704
0
        llvm::is_contained(AffectingModuleMaps, *Cache->OrigEntry))
4705
0
      continue;
4706
4707
0
    IsSLocAffecting[I] = false;
4708
4709
0
    FileIDAdjustment += 1;
4710
    // Even empty files take up one element in the offset table.
4711
0
    OffsetAdjustment += SrcMgr.getFileIDSize(FID) + 1;
4712
4713
    // If the previous file was non-affecting as well, just extend its entry
4714
    // with our information.
4715
0
    if (!NonAffectingFileIDs.empty() &&
4716
0
        NonAffectingFileIDs.back().ID == FID.ID - 1) {
4717
0
      NonAffectingFileIDs.back() = FID;
4718
0
      NonAffectingRanges.back().setEnd(SrcMgr.getLocForEndOfFile(FID));
4719
0
      NonAffectingFileIDAdjustments.back() = FileIDAdjustment;
4720
0
      NonAffectingOffsetAdjustments.back() = OffsetAdjustment;
4721
0
      continue;
4722
0
    }
4723
4724
0
    NonAffectingFileIDs.push_back(FID);
4725
0
    NonAffectingRanges.emplace_back(SrcMgr.getLocForStartOfFile(FID),
4726
0
                                    SrcMgr.getLocForEndOfFile(FID));
4727
0
    NonAffectingFileIDAdjustments.push_back(FileIDAdjustment);
4728
0
    NonAffectingOffsetAdjustments.push_back(OffsetAdjustment);
4729
0
  }
4730
0
}
4731
4732
ASTFileSignature ASTWriter::WriteASTCore(Sema &SemaRef, StringRef isysroot,
4733
0
                                         Module *WritingModule) {
4734
0
  using namespace llvm;
4735
4736
0
  bool isModule = WritingModule != nullptr;
4737
4738
  // Make sure that the AST reader knows to finalize itself.
4739
0
  if (Chain)
4740
0
    Chain->finalizeForWriting();
4741
4742
0
  ASTContext &Context = SemaRef.Context;
4743
0
  Preprocessor &PP = SemaRef.PP;
4744
4745
  // This needs to be done very early, since everything that writes
4746
  // SourceLocations or FileIDs depends on it.
4747
0
  collectNonAffectingInputFiles();
4748
4749
0
  writeUnhashedControlBlock(PP, Context);
4750
4751
  // Set up predefined declaration IDs.
4752
0
  auto RegisterPredefDecl = [&] (Decl *D, PredefinedDeclIDs ID) {
4753
0
    if (D) {
4754
0
      assert(D->isCanonicalDecl() && "predefined decl is not canonical");
4755
0
      DeclIDs[D] = ID;
4756
0
    }
4757
0
  };
4758
0
  RegisterPredefDecl(Context.getTranslationUnitDecl(),
4759
0
                     PREDEF_DECL_TRANSLATION_UNIT_ID);
4760
0
  RegisterPredefDecl(Context.ObjCIdDecl, PREDEF_DECL_OBJC_ID_ID);
4761
0
  RegisterPredefDecl(Context.ObjCSelDecl, PREDEF_DECL_OBJC_SEL_ID);
4762
0
  RegisterPredefDecl(Context.ObjCClassDecl, PREDEF_DECL_OBJC_CLASS_ID);
4763
0
  RegisterPredefDecl(Context.ObjCProtocolClassDecl,
4764
0
                     PREDEF_DECL_OBJC_PROTOCOL_ID);
4765
0
  RegisterPredefDecl(Context.Int128Decl, PREDEF_DECL_INT_128_ID);
4766
0
  RegisterPredefDecl(Context.UInt128Decl, PREDEF_DECL_UNSIGNED_INT_128_ID);
4767
0
  RegisterPredefDecl(Context.ObjCInstanceTypeDecl,
4768
0
                     PREDEF_DECL_OBJC_INSTANCETYPE_ID);
4769
0
  RegisterPredefDecl(Context.BuiltinVaListDecl, PREDEF_DECL_BUILTIN_VA_LIST_ID);
4770
0
  RegisterPredefDecl(Context.VaListTagDecl, PREDEF_DECL_VA_LIST_TAG);
4771
0
  RegisterPredefDecl(Context.BuiltinMSVaListDecl,
4772
0
                     PREDEF_DECL_BUILTIN_MS_VA_LIST_ID);
4773
0
  RegisterPredefDecl(Context.MSGuidTagDecl,
4774
0
                     PREDEF_DECL_BUILTIN_MS_GUID_ID);
4775
0
  RegisterPredefDecl(Context.ExternCContext, PREDEF_DECL_EXTERN_C_CONTEXT_ID);
4776
0
  RegisterPredefDecl(Context.MakeIntegerSeqDecl,
4777
0
                     PREDEF_DECL_MAKE_INTEGER_SEQ_ID);
4778
0
  RegisterPredefDecl(Context.CFConstantStringTypeDecl,
4779
0
                     PREDEF_DECL_CF_CONSTANT_STRING_ID);
4780
0
  RegisterPredefDecl(Context.CFConstantStringTagDecl,
4781
0
                     PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID);
4782
0
  RegisterPredefDecl(Context.TypePackElementDecl,
4783
0
                     PREDEF_DECL_TYPE_PACK_ELEMENT_ID);
4784
4785
  // Build a record containing all of the tentative definitions in this file, in
4786
  // TentativeDefinitions order.  Generally, this record will be empty for
4787
  // headers.
4788
0
  RecordData TentativeDefinitions;
4789
0
  AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
4790
4791
  // Build a record containing all of the file scoped decls in this file.
4792
0
  RecordData UnusedFileScopedDecls;
4793
0
  if (!isModule)
4794
0
    AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls,
4795
0
                       UnusedFileScopedDecls);
4796
4797
  // Build a record containing all of the delegating constructors we still need
4798
  // to resolve.
4799
0
  RecordData DelegatingCtorDecls;
4800
0
  if (!isModule)
4801
0
    AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
4802
4803
  // Write the set of weak, undeclared identifiers. We always write the
4804
  // entire table, since later PCH files in a PCH chain are only interested in
4805
  // the results at the end of the chain.
4806
0
  RecordData WeakUndeclaredIdentifiers;
4807
0
  for (const auto &WeakUndeclaredIdentifierList :
4808
0
       SemaRef.WeakUndeclaredIdentifiers) {
4809
0
    const IdentifierInfo *const II = WeakUndeclaredIdentifierList.first;
4810
0
    for (const auto &WI : WeakUndeclaredIdentifierList.second) {
4811
0
      AddIdentifierRef(II, WeakUndeclaredIdentifiers);
4812
0
      AddIdentifierRef(WI.getAlias(), WeakUndeclaredIdentifiers);
4813
0
      AddSourceLocation(WI.getLocation(), WeakUndeclaredIdentifiers);
4814
0
    }
4815
0
  }
4816
4817
  // Build a record containing all of the ext_vector declarations.
4818
0
  RecordData ExtVectorDecls;
4819
0
  AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
4820
4821
  // Build a record containing all of the VTable uses information.
4822
0
  RecordData VTableUses;
4823
0
  if (!SemaRef.VTableUses.empty()) {
4824
0
    for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
4825
0
      AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
4826
0
      AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
4827
0
      VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
4828
0
    }
4829
0
  }
4830
4831
  // Build a record containing all of the UnusedLocalTypedefNameCandidates.
4832
0
  RecordData UnusedLocalTypedefNameCandidates;
4833
0
  for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates)
4834
0
    AddDeclRef(TD, UnusedLocalTypedefNameCandidates);
4835
4836
  // Build a record containing all of pending implicit instantiations.
4837
0
  RecordData PendingInstantiations;
4838
0
  for (const auto &I : SemaRef.PendingInstantiations) {
4839
0
    AddDeclRef(I.first, PendingInstantiations);
4840
0
    AddSourceLocation(I.second, PendingInstantiations);
4841
0
  }
4842
0
  assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
4843
0
         "There are local ones at end of translation unit!");
4844
4845
  // Build a record containing some declaration references.
4846
0
  RecordData SemaDeclRefs;
4847
0
  if (SemaRef.StdNamespace || SemaRef.StdBadAlloc || SemaRef.StdAlignValT) {
4848
0
    AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
4849
0
    AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
4850
0
    AddDeclRef(SemaRef.getStdAlignValT(), SemaDeclRefs);
4851
0
  }
4852
4853
0
  RecordData CUDASpecialDeclRefs;
4854
0
  if (Context.getcudaConfigureCallDecl()) {
4855
0
    AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
4856
0
  }
4857
4858
  // Build a record containing all of the known namespaces.
4859
0
  RecordData KnownNamespaces;
4860
0
  for (const auto &I : SemaRef.KnownNamespaces) {
4861
0
    if (!I.second)
4862
0
      AddDeclRef(I.first, KnownNamespaces);
4863
0
  }
4864
4865
  // Build a record of all used, undefined objects that require definitions.
4866
0
  RecordData UndefinedButUsed;
4867
4868
0
  SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
4869
0
  SemaRef.getUndefinedButUsed(Undefined);
4870
0
  for (const auto &I : Undefined) {
4871
0
    AddDeclRef(I.first, UndefinedButUsed);
4872
0
    AddSourceLocation(I.second, UndefinedButUsed);
4873
0
  }
4874
4875
  // Build a record containing all delete-expressions that we would like to
4876
  // analyze later in AST.
4877
0
  RecordData DeleteExprsToAnalyze;
4878
4879
0
  if (!isModule) {
4880
0
    for (const auto &DeleteExprsInfo :
4881
0
         SemaRef.getMismatchingDeleteExpressions()) {
4882
0
      AddDeclRef(DeleteExprsInfo.first, DeleteExprsToAnalyze);
4883
0
      DeleteExprsToAnalyze.push_back(DeleteExprsInfo.second.size());
4884
0
      for (const auto &DeleteLoc : DeleteExprsInfo.second) {
4885
0
        AddSourceLocation(DeleteLoc.first, DeleteExprsToAnalyze);
4886
0
        DeleteExprsToAnalyze.push_back(DeleteLoc.second);
4887
0
      }
4888
0
    }
4889
0
  }
4890
4891
  // Write the control block
4892
0
  WriteControlBlock(PP, Context, isysroot);
4893
4894
  // Write the remaining AST contents.
4895
0
  Stream.FlushToWord();
4896
0
  ASTBlockRange.first = Stream.GetCurrentBitNo() >> 3;
4897
0
  Stream.EnterSubblock(AST_BLOCK_ID, 5);
4898
0
  ASTBlockStartOffset = Stream.GetCurrentBitNo();
4899
4900
  // This is so that older clang versions, before the introduction
4901
  // of the control block, can read and reject the newer PCH format.
4902
0
  {
4903
0
    RecordData Record = {VERSION_MAJOR};
4904
0
    Stream.EmitRecord(METADATA_OLD_FORMAT, Record);
4905
0
  }
4906
4907
  // Create a lexical update block containing all of the declarations in the
4908
  // translation unit that do not come from other AST files.
4909
0
  const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
4910
0
  SmallVector<uint32_t, 128> NewGlobalKindDeclPairs;
4911
0
  for (const auto *D : TU->noload_decls()) {
4912
0
    if (!D->isFromASTFile()) {
4913
0
      NewGlobalKindDeclPairs.push_back(D->getKind());
4914
0
      NewGlobalKindDeclPairs.push_back(GetDeclRef(D));
4915
0
    }
4916
0
  }
4917
4918
0
  auto Abv = std::make_shared<BitCodeAbbrev>();
4919
0
  Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
4920
0
  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4921
0
  unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(std::move(Abv));
4922
0
  {
4923
0
    RecordData::value_type Record[] = {TU_UPDATE_LEXICAL};
4924
0
    Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
4925
0
                              bytes(NewGlobalKindDeclPairs));
4926
0
  }
4927
4928
  // And a visible updates block for the translation unit.
4929
0
  Abv = std::make_shared<BitCodeAbbrev>();
4930
0
  Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
4931
0
  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4932
0
  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4933
0
  UpdateVisibleAbbrev = Stream.EmitAbbrev(std::move(Abv));
4934
0
  WriteDeclContextVisibleUpdate(TU);
4935
4936
  // If we have any extern "C" names, write out a visible update for them.
4937
0
  if (Context.ExternCContext)
4938
0
    WriteDeclContextVisibleUpdate(Context.ExternCContext);
4939
4940
  // If the translation unit has an anonymous namespace, and we don't already
4941
  // have an update block for it, write it as an update block.
4942
  // FIXME: Why do we not do this if there's already an update block?
4943
0
  if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
4944
0
    ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
4945
0
    if (Record.empty())
4946
0
      Record.push_back(DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, NS));
4947
0
  }
4948
4949
  // Add update records for all mangling numbers and static local numbers.
4950
  // These aren't really update records, but this is a convenient way of
4951
  // tagging this rare extra data onto the declarations.
4952
0
  for (const auto &Number : Context.MangleNumbers)
4953
0
    if (!Number.first->isFromASTFile())
4954
0
      DeclUpdates[Number.first].push_back(DeclUpdate(UPD_MANGLING_NUMBER,
4955
0
                                                     Number.second));
4956
0
  for (const auto &Number : Context.StaticLocalNumbers)
4957
0
    if (!Number.first->isFromASTFile())
4958
0
      DeclUpdates[Number.first].push_back(DeclUpdate(UPD_STATIC_LOCAL_NUMBER,
4959
0
                                                     Number.second));
4960
4961
  // Make sure visible decls, added to DeclContexts previously loaded from
4962
  // an AST file, are registered for serialization. Likewise for template
4963
  // specializations added to imported templates.
4964
0
  for (const auto *I : DeclsToEmitEvenIfUnreferenced) {
4965
0
    GetDeclRef(I);
4966
0
  }
4967
4968
  // Make sure all decls associated with an identifier are registered for
4969
  // serialization, if we're storing decls with identifiers.
4970
0
  if (!WritingModule || !getLangOpts().CPlusPlus) {
4971
0
    llvm::SmallVector<const IdentifierInfo*, 256> IIs;
4972
0
    for (const auto &ID : PP.getIdentifierTable()) {
4973
0
      const IdentifierInfo *II = ID.second;
4974
0
      if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization())
4975
0
        IIs.push_back(II);
4976
0
    }
4977
    // Sort the identifiers to visit based on their name.
4978
0
    llvm::sort(IIs, llvm::deref<std::less<>>());
4979
0
    for (const IdentifierInfo *II : IIs)
4980
0
      for (const Decl *D : SemaRef.IdResolver.decls(II))
4981
0
        GetDeclRef(D);
4982
0
  }
4983
4984
  // For method pool in the module, if it contains an entry for a selector,
4985
  // the entry should be complete, containing everything introduced by that
4986
  // module and all modules it imports. It's possible that the entry is out of
4987
  // date, so we need to pull in the new content here.
4988
4989
  // It's possible that updateOutOfDateSelector can update SelectorIDs. To be
4990
  // safe, we copy all selectors out.
4991
0
  llvm::SmallVector<Selector, 256> AllSelectors;
4992
0
  for (auto &SelectorAndID : SelectorIDs)
4993
0
    AllSelectors.push_back(SelectorAndID.first);
4994
0
  for (auto &Selector : AllSelectors)
4995
0
    SemaRef.updateOutOfDateSelector(Selector);
4996
4997
  // Form the record of special types.
4998
0
  RecordData SpecialTypes;
4999
0
  AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
5000
0
  AddTypeRef(Context.getFILEType(), SpecialTypes);
5001
0
  AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
5002
0
  AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
5003
0
  AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
5004
0
  AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
5005
0
  AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
5006
0
  AddTypeRef(Context.getucontext_tType(), SpecialTypes);
5007
5008
0
  if (Chain) {
5009
    // Write the mapping information describing our module dependencies and how
5010
    // each of those modules were mapped into our own offset/ID space, so that
5011
    // the reader can build the appropriate mapping to its own offset/ID space.
5012
    // The map consists solely of a blob with the following format:
5013
    // *(module-kind:i8
5014
    //   module-name-len:i16 module-name:len*i8
5015
    //   source-location-offset:i32
5016
    //   identifier-id:i32
5017
    //   preprocessed-entity-id:i32
5018
    //   macro-definition-id:i32
5019
    //   submodule-id:i32
5020
    //   selector-id:i32
5021
    //   declaration-id:i32
5022
    //   c++-base-specifiers-id:i32
5023
    //   type-id:i32)
5024
    //
5025
    // module-kind is the ModuleKind enum value. If it is MK_PrebuiltModule,
5026
    // MK_ExplicitModule or MK_ImplicitModule, then the module-name is the
5027
    // module name. Otherwise, it is the module file name.
5028
0
    auto Abbrev = std::make_shared<BitCodeAbbrev>();
5029
0
    Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
5030
0
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
5031
0
    unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
5032
0
    SmallString<2048> Buffer;
5033
0
    {
5034
0
      llvm::raw_svector_ostream Out(Buffer);
5035
0
      for (ModuleFile &M : Chain->ModuleMgr) {
5036
0
        using namespace llvm::support;
5037
5038
0
        endian::Writer LE(Out, llvm::endianness::little);
5039
0
        LE.write<uint8_t>(static_cast<uint8_t>(M.Kind));
5040
0
        StringRef Name = M.isModule() ? M.ModuleName : M.FileName;
5041
0
        LE.write<uint16_t>(Name.size());
5042
0
        Out.write(Name.data(), Name.size());
5043
5044
        // Note: if a base ID was uint max, it would not be possible to load
5045
        // another module after it or have more than one entity inside it.
5046
0
        uint32_t None = std::numeric_limits<uint32_t>::max();
5047
5048
0
        auto writeBaseIDOrNone = [&](auto BaseID, bool ShouldWrite) {
5049
0
          assert(BaseID < std::numeric_limits<uint32_t>::max() && "base id too high");
5050
0
          if (ShouldWrite)
5051
0
            LE.write<uint32_t>(BaseID);
5052
0
          else
5053
0
            LE.write<uint32_t>(None);
5054
0
        };
5055
5056
        // These values should be unique within a chain, since they will be read
5057
        // as keys into ContinuousRangeMaps.
5058
0
        writeBaseIDOrNone(M.SLocEntryBaseOffset, M.LocalNumSLocEntries);
5059
0
        writeBaseIDOrNone(M.BaseIdentifierID, M.LocalNumIdentifiers);
5060
0
        writeBaseIDOrNone(M.BaseMacroID, M.LocalNumMacros);
5061
0
        writeBaseIDOrNone(M.BasePreprocessedEntityID,
5062
0
                          M.NumPreprocessedEntities);
5063
0
        writeBaseIDOrNone(M.BaseSubmoduleID, M.LocalNumSubmodules);
5064
0
        writeBaseIDOrNone(M.BaseSelectorID, M.LocalNumSelectors);
5065
0
        writeBaseIDOrNone(M.BaseDeclID, M.LocalNumDecls);
5066
0
        writeBaseIDOrNone(M.BaseTypeIndex, M.LocalNumTypes);
5067
0
      }
5068
0
    }
5069
0
    RecordData::value_type Record[] = {MODULE_OFFSET_MAP};
5070
0
    Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
5071
0
                              Buffer.data(), Buffer.size());
5072
0
  }
5073
5074
  // Build a record containing all of the DeclsToCheckForDeferredDiags.
5075
0
  SmallVector<serialization::DeclID, 64> DeclsToCheckForDeferredDiags;
5076
0
  for (auto *D : SemaRef.DeclsToCheckForDeferredDiags)
5077
0
    DeclsToCheckForDeferredDiags.push_back(GetDeclRef(D));
5078
5079
0
  RecordData DeclUpdatesOffsetsRecord;
5080
5081
  // Keep writing types, declarations, and declaration update records
5082
  // until we've emitted all of them.
5083
0
  Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/5);
5084
0
  DeclTypesBlockStartOffset = Stream.GetCurrentBitNo();
5085
0
  WriteTypeAbbrevs();
5086
0
  WriteDeclAbbrevs();
5087
0
  do {
5088
0
    WriteDeclUpdatesBlocks(DeclUpdatesOffsetsRecord);
5089
0
    while (!DeclTypesToEmit.empty()) {
5090
0
      DeclOrType DOT = DeclTypesToEmit.front();
5091
0
      DeclTypesToEmit.pop();
5092
0
      if (DOT.isType())
5093
0
        WriteType(DOT.getType());
5094
0
      else
5095
0
        WriteDecl(Context, DOT.getDecl());
5096
0
    }
5097
0
  } while (!DeclUpdates.empty());
5098
0
  Stream.ExitBlock();
5099
5100
0
  DoneWritingDeclsAndTypes = true;
5101
5102
  // These things can only be done once we've written out decls and types.
5103
0
  WriteTypeDeclOffsets();
5104
0
  if (!DeclUpdatesOffsetsRecord.empty())
5105
0
    Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord);
5106
0
  WriteFileDeclIDsMap();
5107
0
  WriteSourceManagerBlock(Context.getSourceManager(), PP);
5108
0
  WriteComments();
5109
0
  WritePreprocessor(PP, isModule);
5110
0
  WriteHeaderSearch(PP.getHeaderSearchInfo());
5111
0
  WriteSelectors(SemaRef);
5112
0
  WriteReferencedSelectorsPool(SemaRef);
5113
0
  WriteLateParsedTemplates(SemaRef);
5114
0
  WriteIdentifierTable(PP, SemaRef.IdResolver, isModule);
5115
0
  WriteFPPragmaOptions(SemaRef.CurFPFeatureOverrides());
5116
0
  WriteOpenCLExtensions(SemaRef);
5117
0
  WriteCUDAPragmas(SemaRef);
5118
5119
  // If we're emitting a module, write out the submodule information.
5120
0
  if (WritingModule)
5121
0
    WriteSubmodules(WritingModule);
5122
5123
0
  Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
5124
5125
  // Write the record containing external, unnamed definitions.
5126
0
  if (!EagerlyDeserializedDecls.empty())
5127
0
    Stream.EmitRecord(EAGERLY_DESERIALIZED_DECLS, EagerlyDeserializedDecls);
5128
5129
0
  if (!ModularCodegenDecls.empty())
5130
0
    Stream.EmitRecord(MODULAR_CODEGEN_DECLS, ModularCodegenDecls);
5131
5132
  // Write the record containing tentative definitions.
5133
0
  if (!TentativeDefinitions.empty())
5134
0
    Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
5135
5136
  // Write the record containing unused file scoped decls.
5137
0
  if (!UnusedFileScopedDecls.empty())
5138
0
    Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
5139
5140
  // Write the record containing weak undeclared identifiers.
5141
0
  if (!WeakUndeclaredIdentifiers.empty())
5142
0
    Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
5143
0
                      WeakUndeclaredIdentifiers);
5144
5145
  // Write the record containing ext_vector type names.
5146
0
  if (!ExtVectorDecls.empty())
5147
0
    Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
5148
5149
  // Write the record containing VTable uses information.
5150
0
  if (!VTableUses.empty())
5151
0
    Stream.EmitRecord(VTABLE_USES, VTableUses);
5152
5153
  // Write the record containing potentially unused local typedefs.
5154
0
  if (!UnusedLocalTypedefNameCandidates.empty())
5155
0
    Stream.EmitRecord(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES,
5156
0
                      UnusedLocalTypedefNameCandidates);
5157
5158
  // Write the record containing pending implicit instantiations.
5159
0
  if (!PendingInstantiations.empty())
5160
0
    Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
5161
5162
  // Write the record containing declaration references of Sema.
5163
0
  if (!SemaDeclRefs.empty())
5164
0
    Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
5165
5166
  // Write the record containing decls to be checked for deferred diags.
5167
0
  if (!DeclsToCheckForDeferredDiags.empty())
5168
0
    Stream.EmitRecord(DECLS_TO_CHECK_FOR_DEFERRED_DIAGS,
5169
0
        DeclsToCheckForDeferredDiags);
5170
5171
  // Write the record containing CUDA-specific declaration references.
5172
0
  if (!CUDASpecialDeclRefs.empty())
5173
0
    Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
5174
5175
  // Write the delegating constructors.
5176
0
  if (!DelegatingCtorDecls.empty())
5177
0
    Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
5178
5179
  // Write the known namespaces.
5180
0
  if (!KnownNamespaces.empty())
5181
0
    Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
5182
5183
  // Write the undefined internal functions and variables, and inline functions.
5184
0
  if (!UndefinedButUsed.empty())
5185
0
    Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed);
5186
5187
0
  if (!DeleteExprsToAnalyze.empty())
5188
0
    Stream.EmitRecord(DELETE_EXPRS_TO_ANALYZE, DeleteExprsToAnalyze);
5189
5190
  // Write the visible updates to DeclContexts.
5191
0
  for (auto *DC : UpdatedDeclContexts)
5192
0
    WriteDeclContextVisibleUpdate(DC);
5193
5194
0
  if (!WritingModule) {
5195
    // Write the submodules that were imported, if any.
5196
0
    struct ModuleInfo {
5197
0
      uint64_t ID;
5198
0
      Module *M;
5199
0
      ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {}
5200
0
    };
5201
0
    llvm::SmallVector<ModuleInfo, 64> Imports;
5202
0
    for (const auto *I : Context.local_imports()) {
5203
0
      assert(SubmoduleIDs.contains(I->getImportedModule()));
5204
0
      Imports.push_back(ModuleInfo(SubmoduleIDs[I->getImportedModule()],
5205
0
                         I->getImportedModule()));
5206
0
    }
5207
5208
0
    if (!Imports.empty()) {
5209
0
      auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) {
5210
0
        return A.ID < B.ID;
5211
0
      };
5212
0
      auto Eq = [](const ModuleInfo &A, const ModuleInfo &B) {
5213
0
        return A.ID == B.ID;
5214
0
      };
5215
5216
      // Sort and deduplicate module IDs.
5217
0
      llvm::sort(Imports, Cmp);
5218
0
      Imports.erase(std::unique(Imports.begin(), Imports.end(), Eq),
5219
0
                    Imports.end());
5220
5221
0
      RecordData ImportedModules;
5222
0
      for (const auto &Import : Imports) {
5223
0
        ImportedModules.push_back(Import.ID);
5224
        // FIXME: If the module has macros imported then later has declarations
5225
        // imported, this location won't be the right one as a location for the
5226
        // declaration imports.
5227
0
        AddSourceLocation(PP.getModuleImportLoc(Import.M), ImportedModules);
5228
0
      }
5229
5230
0
      Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
5231
0
    }
5232
0
  }
5233
5234
0
  WriteObjCCategories();
5235
0
  if(!WritingModule) {
5236
0
    WriteOptimizePragmaOptions(SemaRef);
5237
0
    WriteMSStructPragmaOptions(SemaRef);
5238
0
    WriteMSPointersToMembersPragmaOptions(SemaRef);
5239
0
  }
5240
0
  WritePackPragmaOptions(SemaRef);
5241
0
  WriteFloatControlPragmaOptions(SemaRef);
5242
5243
  // Some simple statistics
5244
0
  RecordData::value_type Record[] = {
5245
0
      NumStatements, NumMacros, NumLexicalDeclContexts, NumVisibleDeclContexts};
5246
0
  Stream.EmitRecord(STATISTICS, Record);
5247
0
  Stream.ExitBlock();
5248
0
  Stream.FlushToWord();
5249
0
  ASTBlockRange.second = Stream.GetCurrentBitNo() >> 3;
5250
5251
  // Write the module file extension blocks.
5252
0
  for (const auto &ExtWriter : ModuleFileExtensionWriters)
5253
0
    WriteModuleFileExtension(SemaRef, *ExtWriter);
5254
5255
0
  return backpatchSignature();
5256
0
}
5257
5258
0
void ASTWriter::WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord) {
5259
0
  if (DeclUpdates.empty())
5260
0
    return;
5261
5262
0
  DeclUpdateMap LocalUpdates;
5263
0
  LocalUpdates.swap(DeclUpdates);
5264
5265
0
  for (auto &DeclUpdate : LocalUpdates) {
5266
0
    const Decl *D = DeclUpdate.first;
5267
5268
0
    bool HasUpdatedBody = false;
5269
0
    bool HasAddedVarDefinition = false;
5270
0
    RecordData RecordData;
5271
0
    ASTRecordWriter Record(*this, RecordData);
5272
0
    for (auto &Update : DeclUpdate.second) {
5273
0
      DeclUpdateKind Kind = (DeclUpdateKind)Update.getKind();
5274
5275
      // An updated body is emitted last, so that the reader doesn't need
5276
      // to skip over the lazy body to reach statements for other records.
5277
0
      if (Kind == UPD_CXX_ADDED_FUNCTION_DEFINITION)
5278
0
        HasUpdatedBody = true;
5279
0
      else if (Kind == UPD_CXX_ADDED_VAR_DEFINITION)
5280
0
        HasAddedVarDefinition = true;
5281
0
      else
5282
0
        Record.push_back(Kind);
5283
5284
0
      switch (Kind) {
5285
0
      case UPD_CXX_ADDED_IMPLICIT_MEMBER:
5286
0
      case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
5287
0
      case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE:
5288
0
        assert(Update.getDecl() && "no decl to add?");
5289
0
        Record.push_back(GetDeclRef(Update.getDecl()));
5290
0
        break;
5291
5292
0
      case UPD_CXX_ADDED_FUNCTION_DEFINITION:
5293
0
      case UPD_CXX_ADDED_VAR_DEFINITION:
5294
0
        break;
5295
5296
0
      case UPD_CXX_POINT_OF_INSTANTIATION:
5297
        // FIXME: Do we need to also save the template specialization kind here?
5298
0
        Record.AddSourceLocation(Update.getLoc());
5299
0
        break;
5300
5301
0
      case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT:
5302
0
        Record.AddStmt(const_cast<Expr *>(
5303
0
            cast<ParmVarDecl>(Update.getDecl())->getDefaultArg()));
5304
0
        break;
5305
5306
0
      case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER:
5307
0
        Record.AddStmt(
5308
0
            cast<FieldDecl>(Update.getDecl())->getInClassInitializer());
5309
0
        break;
5310
5311
0
      case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
5312
0
        auto *RD = cast<CXXRecordDecl>(D);
5313
0
        UpdatedDeclContexts.insert(RD->getPrimaryContext());
5314
0
        Record.push_back(RD->isParamDestroyedInCallee());
5315
0
        Record.push_back(llvm::to_underlying(RD->getArgPassingRestrictions()));
5316
0
        Record.AddCXXDefinitionData(RD);
5317
0
        Record.AddOffset(WriteDeclContextLexicalBlock(
5318
0
            *Context, const_cast<CXXRecordDecl *>(RD)));
5319
5320
        // This state is sometimes updated by template instantiation, when we
5321
        // switch from the specialization referring to the template declaration
5322
        // to it referring to the template definition.
5323
0
        if (auto *MSInfo = RD->getMemberSpecializationInfo()) {
5324
0
          Record.push_back(MSInfo->getTemplateSpecializationKind());
5325
0
          Record.AddSourceLocation(MSInfo->getPointOfInstantiation());
5326
0
        } else {
5327
0
          auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
5328
0
          Record.push_back(Spec->getTemplateSpecializationKind());
5329
0
          Record.AddSourceLocation(Spec->getPointOfInstantiation());
5330
5331
          // The instantiation might have been resolved to a partial
5332
          // specialization. If so, record which one.
5333
0
          auto From = Spec->getInstantiatedFrom();
5334
0
          if (auto PartialSpec =
5335
0
                From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) {
5336
0
            Record.push_back(true);
5337
0
            Record.AddDeclRef(PartialSpec);
5338
0
            Record.AddTemplateArgumentList(
5339
0
                &Spec->getTemplateInstantiationArgs());
5340
0
          } else {
5341
0
            Record.push_back(false);
5342
0
          }
5343
0
        }
5344
0
        Record.push_back(llvm::to_underlying(RD->getTagKind()));
5345
0
        Record.AddSourceLocation(RD->getLocation());
5346
0
        Record.AddSourceLocation(RD->getBeginLoc());
5347
0
        Record.AddSourceRange(RD->getBraceRange());
5348
5349
        // Instantiation may change attributes; write them all out afresh.
5350
0
        Record.push_back(D->hasAttrs());
5351
0
        if (D->hasAttrs())
5352
0
          Record.AddAttributes(D->getAttrs());
5353
5354
        // FIXME: Ensure we don't get here for explicit instantiations.
5355
0
        break;
5356
0
      }
5357
5358
0
      case UPD_CXX_RESOLVED_DTOR_DELETE:
5359
0
        Record.AddDeclRef(Update.getDecl());
5360
0
        Record.AddStmt(cast<CXXDestructorDecl>(D)->getOperatorDeleteThisArg());
5361
0
        break;
5362
5363
0
      case UPD_CXX_RESOLVED_EXCEPTION_SPEC: {
5364
0
        auto prototype =
5365
0
          cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>();
5366
0
        Record.writeExceptionSpecInfo(prototype->getExceptionSpecInfo());
5367
0
        break;
5368
0
      }
5369
5370
0
      case UPD_CXX_DEDUCED_RETURN_TYPE:
5371
0
        Record.push_back(GetOrCreateTypeID(Update.getType()));
5372
0
        break;
5373
5374
0
      case UPD_DECL_MARKED_USED:
5375
0
        break;
5376
5377
0
      case UPD_MANGLING_NUMBER:
5378
0
      case UPD_STATIC_LOCAL_NUMBER:
5379
0
        Record.push_back(Update.getNumber());
5380
0
        break;
5381
5382
0
      case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
5383
0
        Record.AddSourceRange(
5384
0
            D->getAttr<OMPThreadPrivateDeclAttr>()->getRange());
5385
0
        break;
5386
5387
0
      case UPD_DECL_MARKED_OPENMP_ALLOCATE: {
5388
0
        auto *A = D->getAttr<OMPAllocateDeclAttr>();
5389
0
        Record.push_back(A->getAllocatorType());
5390
0
        Record.AddStmt(A->getAllocator());
5391
0
        Record.AddStmt(A->getAlignment());
5392
0
        Record.AddSourceRange(A->getRange());
5393
0
        break;
5394
0
      }
5395
5396
0
      case UPD_DECL_MARKED_OPENMP_DECLARETARGET:
5397
0
        Record.push_back(D->getAttr<OMPDeclareTargetDeclAttr>()->getMapType());
5398
0
        Record.AddSourceRange(
5399
0
            D->getAttr<OMPDeclareTargetDeclAttr>()->getRange());
5400
0
        break;
5401
5402
0
      case UPD_DECL_EXPORTED:
5403
0
        Record.push_back(getSubmoduleID(Update.getModule()));
5404
0
        break;
5405
5406
0
      case UPD_ADDED_ATTR_TO_RECORD:
5407
0
        Record.AddAttributes(llvm::ArrayRef(Update.getAttr()));
5408
0
        break;
5409
0
      }
5410
0
    }
5411
5412
    // Add a trailing update record, if any. These must go last because we
5413
    // lazily load their attached statement.
5414
0
    if (HasUpdatedBody) {
5415
0
      const auto *Def = cast<FunctionDecl>(D);
5416
0
      Record.push_back(UPD_CXX_ADDED_FUNCTION_DEFINITION);
5417
0
      Record.push_back(Def->isInlined());
5418
0
      Record.AddSourceLocation(Def->getInnerLocStart());
5419
0
      Record.AddFunctionDefinition(Def);
5420
0
    } else if (HasAddedVarDefinition) {
5421
0
      const auto *VD = cast<VarDecl>(D);
5422
0
      Record.push_back(UPD_CXX_ADDED_VAR_DEFINITION);
5423
0
      Record.push_back(VD->isInline());
5424
0
      Record.push_back(VD->isInlineSpecified());
5425
0
      Record.AddVarDeclInit(VD);
5426
0
    }
5427
5428
0
    OffsetsRecord.push_back(GetDeclRef(D));
5429
0
    OffsetsRecord.push_back(Record.Emit(DECL_UPDATES));
5430
0
  }
5431
0
}
5432
5433
void ASTWriter::AddAlignPackInfo(const Sema::AlignPackInfo &Info,
5434
0
                                 RecordDataImpl &Record) {
5435
0
  uint32_t Raw = Sema::AlignPackInfo::getRawEncoding(Info);
5436
0
  Record.push_back(Raw);
5437
0
}
5438
5439
0
FileID ASTWriter::getAdjustedFileID(FileID FID) const {
5440
0
  if (FID.isInvalid() || PP->getSourceManager().isLoadedFileID(FID) ||
5441
0
      NonAffectingFileIDs.empty())
5442
0
    return FID;
5443
0
  auto It = llvm::lower_bound(NonAffectingFileIDs, FID);
5444
0
  unsigned Idx = std::distance(NonAffectingFileIDs.begin(), It);
5445
0
  unsigned Offset = NonAffectingFileIDAdjustments[Idx];
5446
0
  return FileID::get(FID.getOpaqueValue() - Offset);
5447
0
}
5448
5449
0
unsigned ASTWriter::getAdjustedNumCreatedFIDs(FileID FID) const {
5450
0
  unsigned NumCreatedFIDs = PP->getSourceManager()
5451
0
                                .getLocalSLocEntry(FID.ID)
5452
0
                                .getFile()
5453
0
                                .NumCreatedFIDs;
5454
5455
0
  unsigned AdjustedNumCreatedFIDs = 0;
5456
0
  for (unsigned I = FID.ID, N = I + NumCreatedFIDs; I != N; ++I)
5457
0
    if (IsSLocAffecting[I])
5458
0
      ++AdjustedNumCreatedFIDs;
5459
0
  return AdjustedNumCreatedFIDs;
5460
0
}
5461
5462
0
SourceLocation ASTWriter::getAdjustedLocation(SourceLocation Loc) const {
5463
0
  if (Loc.isInvalid())
5464
0
    return Loc;
5465
0
  return Loc.getLocWithOffset(-getAdjustment(Loc.getOffset()));
5466
0
}
5467
5468
0
SourceRange ASTWriter::getAdjustedRange(SourceRange Range) const {
5469
0
  return SourceRange(getAdjustedLocation(Range.getBegin()),
5470
0
                     getAdjustedLocation(Range.getEnd()));
5471
0
}
5472
5473
SourceLocation::UIntTy
5474
0
ASTWriter::getAdjustedOffset(SourceLocation::UIntTy Offset) const {
5475
0
  return Offset - getAdjustment(Offset);
5476
0
}
5477
5478
SourceLocation::UIntTy
5479
0
ASTWriter::getAdjustment(SourceLocation::UIntTy Offset) const {
5480
0
  if (NonAffectingRanges.empty())
5481
0
    return 0;
5482
5483
0
  if (PP->getSourceManager().isLoadedOffset(Offset))
5484
0
    return 0;
5485
5486
0
  if (Offset > NonAffectingRanges.back().getEnd().getOffset())
5487
0
    return NonAffectingOffsetAdjustments.back();
5488
5489
0
  if (Offset < NonAffectingRanges.front().getBegin().getOffset())
5490
0
    return 0;
5491
5492
0
  auto Contains = [](const SourceRange &Range, SourceLocation::UIntTy Offset) {
5493
0
    return Range.getEnd().getOffset() < Offset;
5494
0
  };
5495
5496
0
  auto It = llvm::lower_bound(NonAffectingRanges, Offset, Contains);
5497
0
  unsigned Idx = std::distance(NonAffectingRanges.begin(), It);
5498
0
  return NonAffectingOffsetAdjustments[Idx];
5499
0
}
5500
5501
0
void ASTWriter::AddFileID(FileID FID, RecordDataImpl &Record) {
5502
0
  Record.push_back(getAdjustedFileID(FID).getOpaqueValue());
5503
0
}
5504
5505
void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record,
5506
0
                                  SourceLocationSequence *Seq) {
5507
0
  Loc = getAdjustedLocation(Loc);
5508
0
  Record.push_back(SourceLocationEncoding::encode(Loc, Seq));
5509
0
}
5510
5511
void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record,
5512
0
                               SourceLocationSequence *Seq) {
5513
0
  AddSourceLocation(Range.getBegin(), Record, Seq);
5514
0
  AddSourceLocation(Range.getEnd(), Record, Seq);
5515
0
}
5516
5517
0
void ASTRecordWriter::AddAPFloat(const llvm::APFloat &Value) {
5518
0
  AddAPInt(Value.bitcastToAPInt());
5519
0
}
5520
5521
0
void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
5522
0
  Record.push_back(getIdentifierRef(II));
5523
0
}
5524
5525
0
IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
5526
0
  if (!II)
5527
0
    return 0;
5528
5529
0
  IdentID &ID = IdentifierIDs[II];
5530
0
  if (ID == 0)
5531
0
    ID = NextIdentID++;
5532
0
  return ID;
5533
0
}
5534
5535
0
MacroID ASTWriter::getMacroRef(MacroInfo *MI, const IdentifierInfo *Name) {
5536
  // Don't emit builtin macros like __LINE__ to the AST file unless they
5537
  // have been redefined by the header (in which case they are not
5538
  // isBuiltinMacro).
5539
0
  if (!MI || MI->isBuiltinMacro())
5540
0
    return 0;
5541
5542
0
  MacroID &ID = MacroIDs[MI];
5543
0
  if (ID == 0) {
5544
0
    ID = NextMacroID++;
5545
0
    MacroInfoToEmitData Info = { Name, MI, ID };
5546
0
    MacroInfosToEmit.push_back(Info);
5547
0
  }
5548
0
  return ID;
5549
0
}
5550
5551
0
MacroID ASTWriter::getMacroID(MacroInfo *MI) {
5552
0
  if (!MI || MI->isBuiltinMacro())
5553
0
    return 0;
5554
5555
0
  assert(MacroIDs.contains(MI) && "Macro not emitted!");
5556
0
  return MacroIDs[MI];
5557
0
}
5558
5559
0
uint32_t ASTWriter::getMacroDirectivesOffset(const IdentifierInfo *Name) {
5560
0
  return IdentMacroDirectivesOffsetMap.lookup(Name);
5561
0
}
5562
5563
0
void ASTRecordWriter::AddSelectorRef(const Selector SelRef) {
5564
0
  Record->push_back(Writer->getSelectorRef(SelRef));
5565
0
}
5566
5567
0
SelectorID ASTWriter::getSelectorRef(Selector Sel) {
5568
0
  if (Sel.getAsOpaquePtr() == nullptr) {
5569
0
    return 0;
5570
0
  }
5571
5572
0
  SelectorID SID = SelectorIDs[Sel];
5573
0
  if (SID == 0 && Chain) {
5574
    // This might trigger a ReadSelector callback, which will set the ID for
5575
    // this selector.
5576
0
    Chain->LoadSelector(Sel);
5577
0
    SID = SelectorIDs[Sel];
5578
0
  }
5579
0
  if (SID == 0) {
5580
0
    SID = NextSelectorID++;
5581
0
    SelectorIDs[Sel] = SID;
5582
0
  }
5583
0
  return SID;
5584
0
}
5585
5586
0
void ASTRecordWriter::AddCXXTemporary(const CXXTemporary *Temp) {
5587
0
  AddDeclRef(Temp->getDestructor());
5588
0
}
5589
5590
void ASTRecordWriter::AddTemplateArgumentLocInfo(
5591
0
    TemplateArgument::ArgKind Kind, const TemplateArgumentLocInfo &Arg) {
5592
0
  switch (Kind) {
5593
0
  case TemplateArgument::Expression:
5594
0
    AddStmt(Arg.getAsExpr());
5595
0
    break;
5596
0
  case TemplateArgument::Type:
5597
0
    AddTypeSourceInfo(Arg.getAsTypeSourceInfo());
5598
0
    break;
5599
0
  case TemplateArgument::Template:
5600
0
    AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
5601
0
    AddSourceLocation(Arg.getTemplateNameLoc());
5602
0
    break;
5603
0
  case TemplateArgument::TemplateExpansion:
5604
0
    AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
5605
0
    AddSourceLocation(Arg.getTemplateNameLoc());
5606
0
    AddSourceLocation(Arg.getTemplateEllipsisLoc());
5607
0
    break;
5608
0
  case TemplateArgument::Null:
5609
0
  case TemplateArgument::Integral:
5610
0
  case TemplateArgument::Declaration:
5611
0
  case TemplateArgument::NullPtr:
5612
0
  case TemplateArgument::Pack:
5613
    // FIXME: Is this right?
5614
0
    break;
5615
0
  }
5616
0
}
5617
5618
0
void ASTRecordWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg) {
5619
0
  AddTemplateArgument(Arg.getArgument());
5620
5621
0
  if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
5622
0
    bool InfoHasSameExpr
5623
0
      = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
5624
0
    Record->push_back(InfoHasSameExpr);
5625
0
    if (InfoHasSameExpr)
5626
0
      return; // Avoid storing the same expr twice.
5627
0
  }
5628
0
  AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo());
5629
0
}
5630
5631
0
void ASTRecordWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo) {
5632
0
  if (!TInfo) {
5633
0
    AddTypeRef(QualType());
5634
0
    return;
5635
0
  }
5636
5637
0
  AddTypeRef(TInfo->getType());
5638
0
  AddTypeLoc(TInfo->getTypeLoc());
5639
0
}
5640
5641
0
void ASTRecordWriter::AddTypeLoc(TypeLoc TL, LocSeq *OuterSeq) {
5642
0
  LocSeq::State Seq(OuterSeq);
5643
0
  TypeLocWriter TLW(*this, Seq);
5644
0
  for (; !TL.isNull(); TL = TL.getNextTypeLoc())
5645
0
    TLW.Visit(TL);
5646
0
}
5647
5648
0
void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
5649
0
  Record.push_back(GetOrCreateTypeID(T));
5650
0
}
5651
5652
0
TypeID ASTWriter::GetOrCreateTypeID(QualType T) {
5653
0
  assert(Context);
5654
0
  return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
5655
0
    if (T.isNull())
5656
0
      return TypeIdx();
5657
0
    assert(!T.getLocalFastQualifiers());
5658
5659
0
    TypeIdx &Idx = TypeIdxs[T];
5660
0
    if (Idx.getIndex() == 0) {
5661
0
      if (DoneWritingDeclsAndTypes) {
5662
0
        assert(0 && "New type seen after serializing all the types to emit!");
5663
0
        return TypeIdx();
5664
0
      }
5665
5666
      // We haven't seen this type before. Assign it a new ID and put it
5667
      // into the queue of types to emit.
5668
0
      Idx = TypeIdx(NextTypeID++);
5669
0
      DeclTypesToEmit.push(T);
5670
0
    }
5671
0
    return Idx;
5672
0
  });
5673
0
}
5674
5675
0
TypeID ASTWriter::getTypeID(QualType T) const {
5676
0
  assert(Context);
5677
0
  return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
5678
0
    if (T.isNull())
5679
0
      return TypeIdx();
5680
0
    assert(!T.getLocalFastQualifiers());
5681
5682
0
    TypeIdxMap::const_iterator I = TypeIdxs.find(T);
5683
0
    assert(I != TypeIdxs.end() && "Type not emitted!");
5684
0
    return I->second;
5685
0
  });
5686
0
}
5687
5688
0
void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
5689
0
  Record.push_back(GetDeclRef(D));
5690
0
}
5691
5692
0
DeclID ASTWriter::GetDeclRef(const Decl *D) {
5693
0
  assert(WritingAST && "Cannot request a declaration ID before AST writing");
5694
5695
0
  if (!D) {
5696
0
    return 0;
5697
0
  }
5698
5699
  // If D comes from an AST file, its declaration ID is already known and
5700
  // fixed.
5701
0
  if (D->isFromASTFile())
5702
0
    return D->getGlobalID();
5703
5704
0
  assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
5705
0
  DeclID &ID = DeclIDs[D];
5706
0
  if (ID == 0) {
5707
0
    if (DoneWritingDeclsAndTypes) {
5708
0
      assert(0 && "New decl seen after serializing all the decls to emit!");
5709
0
      return 0;
5710
0
    }
5711
5712
    // We haven't seen this declaration before. Give it a new ID and
5713
    // enqueue it in the list of declarations to emit.
5714
0
    ID = NextDeclID++;
5715
0
    DeclTypesToEmit.push(const_cast<Decl *>(D));
5716
0
  }
5717
5718
0
  return ID;
5719
0
}
5720
5721
0
DeclID ASTWriter::getDeclID(const Decl *D) {
5722
0
  if (!D)
5723
0
    return 0;
5724
5725
  // If D comes from an AST file, its declaration ID is already known and
5726
  // fixed.
5727
0
  if (D->isFromASTFile())
5728
0
    return D->getGlobalID();
5729
5730
0
  assert(DeclIDs.contains(D) && "Declaration not emitted!");
5731
0
  return DeclIDs[D];
5732
0
}
5733
5734
0
void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) {
5735
0
  assert(ID);
5736
0
  assert(D);
5737
5738
0
  SourceLocation Loc = D->getLocation();
5739
0
  if (Loc.isInvalid())
5740
0
    return;
5741
5742
  // We only keep track of the file-level declarations of each file.
5743
0
  if (!D->getLexicalDeclContext()->isFileContext())
5744
0
    return;
5745
  // FIXME: ParmVarDecls that are part of a function type of a parameter of
5746
  // a function/objc method, should not have TU as lexical context.
5747
  // TemplateTemplateParmDecls that are part of an alias template, should not
5748
  // have TU as lexical context.
5749
0
  if (isa<ParmVarDecl, TemplateTemplateParmDecl>(D))
5750
0
    return;
5751
5752
0
  SourceManager &SM = Context->getSourceManager();
5753
0
  SourceLocation FileLoc = SM.getFileLoc(Loc);
5754
0
  assert(SM.isLocalSourceLocation(FileLoc));
5755
0
  FileID FID;
5756
0
  unsigned Offset;
5757
0
  std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
5758
0
  if (FID.isInvalid())
5759
0
    return;
5760
0
  assert(SM.getSLocEntry(FID).isFile());
5761
0
  assert(IsSLocAffecting[FID.ID]);
5762
5763
0
  std::unique_ptr<DeclIDInFileInfo> &Info = FileDeclIDs[FID];
5764
0
  if (!Info)
5765
0
    Info = std::make_unique<DeclIDInFileInfo>();
5766
5767
0
  std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID);
5768
0
  LocDeclIDsTy &Decls = Info->DeclIDs;
5769
0
  Decls.push_back(LocDecl);
5770
0
}
5771
5772
0
unsigned ASTWriter::getAnonymousDeclarationNumber(const NamedDecl *D) {
5773
0
  assert(needsAnonymousDeclarationNumber(D) &&
5774
0
         "expected an anonymous declaration");
5775
5776
  // Number the anonymous declarations within this context, if we've not
5777
  // already done so.
5778
0
  auto It = AnonymousDeclarationNumbers.find(D);
5779
0
  if (It == AnonymousDeclarationNumbers.end()) {
5780
0
    auto *DC = D->getLexicalDeclContext();
5781
0
    numberAnonymousDeclsWithin(DC, [&](const NamedDecl *ND, unsigned Number) {
5782
0
      AnonymousDeclarationNumbers[ND] = Number;
5783
0
    });
5784
5785
0
    It = AnonymousDeclarationNumbers.find(D);
5786
0
    assert(It != AnonymousDeclarationNumbers.end() &&
5787
0
           "declaration not found within its lexical context");
5788
0
  }
5789
5790
0
  return It->second;
5791
0
}
5792
5793
void ASTRecordWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
5794
0
                                            DeclarationName Name) {
5795
0
  switch (Name.getNameKind()) {
5796
0
  case DeclarationName::CXXConstructorName:
5797
0
  case DeclarationName::CXXDestructorName:
5798
0
  case DeclarationName::CXXConversionFunctionName:
5799
0
    AddTypeSourceInfo(DNLoc.getNamedTypeInfo());
5800
0
    break;
5801
5802
0
  case DeclarationName::CXXOperatorName:
5803
0
    AddSourceRange(DNLoc.getCXXOperatorNameRange());
5804
0
    break;
5805
5806
0
  case DeclarationName::CXXLiteralOperatorName:
5807
0
    AddSourceLocation(DNLoc.getCXXLiteralOperatorNameLoc());
5808
0
    break;
5809
5810
0
  case DeclarationName::Identifier:
5811
0
  case DeclarationName::ObjCZeroArgSelector:
5812
0
  case DeclarationName::ObjCOneArgSelector:
5813
0
  case DeclarationName::ObjCMultiArgSelector:
5814
0
  case DeclarationName::CXXUsingDirective:
5815
0
  case DeclarationName::CXXDeductionGuideName:
5816
0
    break;
5817
0
  }
5818
0
}
5819
5820
void ASTRecordWriter::AddDeclarationNameInfo(
5821
0
    const DeclarationNameInfo &NameInfo) {
5822
0
  AddDeclarationName(NameInfo.getName());
5823
0
  AddSourceLocation(NameInfo.getLoc());
5824
0
  AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName());
5825
0
}
5826
5827
0
void ASTRecordWriter::AddQualifierInfo(const QualifierInfo &Info) {
5828
0
  AddNestedNameSpecifierLoc(Info.QualifierLoc);
5829
0
  Record->push_back(Info.NumTemplParamLists);
5830
0
  for (unsigned i = 0, e = Info.NumTemplParamLists; i != e; ++i)
5831
0
    AddTemplateParameterList(Info.TemplParamLists[i]);
5832
0
}
5833
5834
0
void ASTRecordWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
5835
  // Nested name specifiers usually aren't too long. I think that 8 would
5836
  // typically accommodate the vast majority.
5837
0
  SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
5838
5839
  // Push each of the nested-name-specifiers's onto a stack for
5840
  // serialization in reverse order.
5841
0
  while (NNS) {
5842
0
    NestedNames.push_back(NNS);
5843
0
    NNS = NNS.getPrefix();
5844
0
  }
5845
5846
0
  Record->push_back(NestedNames.size());
5847
0
  while(!NestedNames.empty()) {
5848
0
    NNS = NestedNames.pop_back_val();
5849
0
    NestedNameSpecifier::SpecifierKind Kind
5850
0
      = NNS.getNestedNameSpecifier()->getKind();
5851
0
    Record->push_back(Kind);
5852
0
    switch (Kind) {
5853
0
    case NestedNameSpecifier::Identifier:
5854
0
      AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier());
5855
0
      AddSourceRange(NNS.getLocalSourceRange());
5856
0
      break;
5857
5858
0
    case NestedNameSpecifier::Namespace:
5859
0
      AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace());
5860
0
      AddSourceRange(NNS.getLocalSourceRange());
5861
0
      break;
5862
5863
0
    case NestedNameSpecifier::NamespaceAlias:
5864
0
      AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias());
5865
0
      AddSourceRange(NNS.getLocalSourceRange());
5866
0
      break;
5867
5868
0
    case NestedNameSpecifier::TypeSpec:
5869
0
    case NestedNameSpecifier::TypeSpecWithTemplate:
5870
0
      Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5871
0
      AddTypeRef(NNS.getTypeLoc().getType());
5872
0
      AddTypeLoc(NNS.getTypeLoc());
5873
0
      AddSourceLocation(NNS.getLocalSourceRange().getEnd());
5874
0
      break;
5875
5876
0
    case NestedNameSpecifier::Global:
5877
0
      AddSourceLocation(NNS.getLocalSourceRange().getEnd());
5878
0
      break;
5879
5880
0
    case NestedNameSpecifier::Super:
5881
0
      AddDeclRef(NNS.getNestedNameSpecifier()->getAsRecordDecl());
5882
0
      AddSourceRange(NNS.getLocalSourceRange());
5883
0
      break;
5884
0
    }
5885
0
  }
5886
0
}
5887
5888
void ASTRecordWriter::AddTemplateParameterList(
5889
0
    const TemplateParameterList *TemplateParams) {
5890
0
  assert(TemplateParams && "No TemplateParams!");
5891
0
  AddSourceLocation(TemplateParams->getTemplateLoc());
5892
0
  AddSourceLocation(TemplateParams->getLAngleLoc());
5893
0
  AddSourceLocation(TemplateParams->getRAngleLoc());
5894
5895
0
  Record->push_back(TemplateParams->size());
5896
0
  for (const auto &P : *TemplateParams)
5897
0
    AddDeclRef(P);
5898
0
  if (const Expr *RequiresClause = TemplateParams->getRequiresClause()) {
5899
0
    Record->push_back(true);
5900
0
    AddStmt(const_cast<Expr*>(RequiresClause));
5901
0
  } else {
5902
0
    Record->push_back(false);
5903
0
  }
5904
0
}
5905
5906
/// Emit a template argument list.
5907
void ASTRecordWriter::AddTemplateArgumentList(
5908
0
    const TemplateArgumentList *TemplateArgs) {
5909
0
  assert(TemplateArgs && "No TemplateArgs!");
5910
0
  Record->push_back(TemplateArgs->size());
5911
0
  for (int i = 0, e = TemplateArgs->size(); i != e; ++i)
5912
0
    AddTemplateArgument(TemplateArgs->get(i));
5913
0
}
5914
5915
void ASTRecordWriter::AddASTTemplateArgumentListInfo(
5916
0
    const ASTTemplateArgumentListInfo *ASTTemplArgList) {
5917
0
  assert(ASTTemplArgList && "No ASTTemplArgList!");
5918
0
  AddSourceLocation(ASTTemplArgList->LAngleLoc);
5919
0
  AddSourceLocation(ASTTemplArgList->RAngleLoc);
5920
0
  Record->push_back(ASTTemplArgList->NumTemplateArgs);
5921
0
  const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs();
5922
0
  for (int i = 0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i)
5923
0
    AddTemplateArgumentLoc(TemplArgs[i]);
5924
0
}
5925
5926
0
void ASTRecordWriter::AddUnresolvedSet(const ASTUnresolvedSet &Set) {
5927
0
  Record->push_back(Set.size());
5928
0
  for (ASTUnresolvedSet::const_iterator
5929
0
         I = Set.begin(), E = Set.end(); I != E; ++I) {
5930
0
    AddDeclRef(I.getDecl());
5931
0
    Record->push_back(I.getAccess());
5932
0
  }
5933
0
}
5934
5935
// FIXME: Move this out of the main ASTRecordWriter interface.
5936
0
void ASTRecordWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base) {
5937
0
  Record->push_back(Base.isVirtual());
5938
0
  Record->push_back(Base.isBaseOfClass());
5939
0
  Record->push_back(Base.getAccessSpecifierAsWritten());
5940
0
  Record->push_back(Base.getInheritConstructors());
5941
0
  AddTypeSourceInfo(Base.getTypeSourceInfo());
5942
0
  AddSourceRange(Base.getSourceRange());
5943
0
  AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
5944
0
                                          : SourceLocation());
5945
0
}
5946
5947
static uint64_t EmitCXXBaseSpecifiers(ASTWriter &W,
5948
0
                                      ArrayRef<CXXBaseSpecifier> Bases) {
5949
0
  ASTWriter::RecordData Record;
5950
0
  ASTRecordWriter Writer(W, Record);
5951
0
  Writer.push_back(Bases.size());
5952
5953
0
  for (auto &Base : Bases)
5954
0
    Writer.AddCXXBaseSpecifier(Base);
5955
5956
0
  return Writer.Emit(serialization::DECL_CXX_BASE_SPECIFIERS);
5957
0
}
5958
5959
// FIXME: Move this out of the main ASTRecordWriter interface.
5960
0
void ASTRecordWriter::AddCXXBaseSpecifiers(ArrayRef<CXXBaseSpecifier> Bases) {
5961
0
  AddOffset(EmitCXXBaseSpecifiers(*Writer, Bases));
5962
0
}
5963
5964
static uint64_t
5965
EmitCXXCtorInitializers(ASTWriter &W,
5966
0
                        ArrayRef<CXXCtorInitializer *> CtorInits) {
5967
0
  ASTWriter::RecordData Record;
5968
0
  ASTRecordWriter Writer(W, Record);
5969
0
  Writer.push_back(CtorInits.size());
5970
5971
0
  for (auto *Init : CtorInits) {
5972
0
    if (Init->isBaseInitializer()) {
5973
0
      Writer.push_back(CTOR_INITIALIZER_BASE);
5974
0
      Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
5975
0
      Writer.push_back(Init->isBaseVirtual());
5976
0
    } else if (Init->isDelegatingInitializer()) {
5977
0
      Writer.push_back(CTOR_INITIALIZER_DELEGATING);
5978
0
      Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
5979
0
    } else if (Init->isMemberInitializer()){
5980
0
      Writer.push_back(CTOR_INITIALIZER_MEMBER);
5981
0
      Writer.AddDeclRef(Init->getMember());
5982
0
    } else {
5983
0
      Writer.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
5984
0
      Writer.AddDeclRef(Init->getIndirectMember());
5985
0
    }
5986
5987
0
    Writer.AddSourceLocation(Init->getMemberLocation());
5988
0
    Writer.AddStmt(Init->getInit());
5989
0
    Writer.AddSourceLocation(Init->getLParenLoc());
5990
0
    Writer.AddSourceLocation(Init->getRParenLoc());
5991
0
    Writer.push_back(Init->isWritten());
5992
0
    if (Init->isWritten())
5993
0
      Writer.push_back(Init->getSourceOrder());
5994
0
  }
5995
5996
0
  return Writer.Emit(serialization::DECL_CXX_CTOR_INITIALIZERS);
5997
0
}
5998
5999
// FIXME: Move this out of the main ASTRecordWriter interface.
6000
void ASTRecordWriter::AddCXXCtorInitializers(
6001
0
    ArrayRef<CXXCtorInitializer *> CtorInits) {
6002
0
  AddOffset(EmitCXXCtorInitializers(*Writer, CtorInits));
6003
0
}
6004
6005
0
void ASTRecordWriter::AddCXXDefinitionData(const CXXRecordDecl *D) {
6006
0
  auto &Data = D->data();
6007
6008
0
  Record->push_back(Data.IsLambda);
6009
6010
0
  BitsPacker DefinitionBits;
6011
6012
0
#define FIELD(Name, Width, Merge)                                              \
6013
0
  if (!DefinitionBits.canWriteNextNBits(Width)) {                              \
6014
0
    Record->push_back(DefinitionBits);                                         \
6015
0
    DefinitionBits.reset(0);                                                   \
6016
0
  }                                                                            \
6017
0
  DefinitionBits.addBits(Data.Name, Width);
6018
6019
0
#include "clang/AST/CXXRecordDeclDefinitionBits.def"
6020
0
#undef FIELD
6021
6022
0
  Record->push_back(DefinitionBits);
6023
6024
  // getODRHash will compute the ODRHash if it has not been previously computed.
6025
0
  Record->push_back(D->getODRHash());
6026
6027
0
  bool ModulesDebugInfo =
6028
0
      Writer->Context->getLangOpts().ModulesDebugInfo && !D->isDependentType();
6029
0
  Record->push_back(ModulesDebugInfo);
6030
0
  if (ModulesDebugInfo)
6031
0
    Writer->ModularCodegenDecls.push_back(Writer->GetDeclRef(D));
6032
6033
  // IsLambda bit is already saved.
6034
6035
0
  AddUnresolvedSet(Data.Conversions.get(*Writer->Context));
6036
0
  Record->push_back(Data.ComputedVisibleConversions);
6037
0
  if (Data.ComputedVisibleConversions)
6038
0
    AddUnresolvedSet(Data.VisibleConversions.get(*Writer->Context));
6039
  // Data.Definition is the owning decl, no need to write it.
6040
6041
0
  if (!Data.IsLambda) {
6042
0
    Record->push_back(Data.NumBases);
6043
0
    if (Data.NumBases > 0)
6044
0
      AddCXXBaseSpecifiers(Data.bases());
6045
6046
    // FIXME: Make VBases lazily computed when needed to avoid storing them.
6047
0
    Record->push_back(Data.NumVBases);
6048
0
    if (Data.NumVBases > 0)
6049
0
      AddCXXBaseSpecifiers(Data.vbases());
6050
6051
0
    AddDeclRef(D->getFirstFriend());
6052
0
  } else {
6053
0
    auto &Lambda = D->getLambdaData();
6054
6055
0
    BitsPacker LambdaBits;
6056
0
    LambdaBits.addBits(Lambda.DependencyKind, /*Width=*/2);
6057
0
    LambdaBits.addBit(Lambda.IsGenericLambda);
6058
0
    LambdaBits.addBits(Lambda.CaptureDefault, /*Width=*/2);
6059
0
    LambdaBits.addBits(Lambda.NumCaptures, /*Width=*/15);
6060
0
    LambdaBits.addBit(Lambda.HasKnownInternalLinkage);
6061
0
    Record->push_back(LambdaBits);
6062
6063
0
    Record->push_back(Lambda.NumExplicitCaptures);
6064
0
    Record->push_back(Lambda.ManglingNumber);
6065
0
    Record->push_back(D->getDeviceLambdaManglingNumber());
6066
    // The lambda context declaration and index within the context are provided
6067
    // separately, so that they can be used for merging.
6068
0
    AddTypeSourceInfo(Lambda.MethodTyInfo);
6069
0
    for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
6070
0
      const LambdaCapture &Capture = Lambda.Captures.front()[I];
6071
0
      AddSourceLocation(Capture.getLocation());
6072
6073
0
      BitsPacker CaptureBits;
6074
0
      CaptureBits.addBit(Capture.isImplicit());
6075
0
      CaptureBits.addBits(Capture.getCaptureKind(), /*Width=*/3);
6076
0
      Record->push_back(CaptureBits);
6077
6078
0
      switch (Capture.getCaptureKind()) {
6079
0
      case LCK_StarThis:
6080
0
      case LCK_This:
6081
0
      case LCK_VLAType:
6082
0
        break;
6083
0
      case LCK_ByCopy:
6084
0
      case LCK_ByRef:
6085
0
        ValueDecl *Var =
6086
0
            Capture.capturesVariable() ? Capture.getCapturedVar() : nullptr;
6087
0
        AddDeclRef(Var);
6088
0
        AddSourceLocation(Capture.isPackExpansion() ? Capture.getEllipsisLoc()
6089
0
                                                    : SourceLocation());
6090
0
        break;
6091
0
      }
6092
0
    }
6093
0
  }
6094
0
}
6095
6096
0
void ASTRecordWriter::AddVarDeclInit(const VarDecl *VD) {
6097
0
  const Expr *Init = VD->getInit();
6098
0
  if (!Init) {
6099
0
    push_back(0);
6100
0
    return;
6101
0
  }
6102
6103
0
  uint64_t Val = 1;
6104
0
  if (EvaluatedStmt *ES = VD->getEvaluatedStmt()) {
6105
0
    Val |= (ES->HasConstantInitialization ? 2 : 0);
6106
0
    Val |= (ES->HasConstantDestruction ? 4 : 0);
6107
0
    APValue *Evaluated = VD->getEvaluatedValue();
6108
    // If the evaluated result is constant, emit it.
6109
0
    if (Evaluated && (Evaluated->isInt() || Evaluated->isFloat()))
6110
0
      Val |= 8;
6111
0
  }
6112
0
  push_back(Val);
6113
0
  if (Val & 8) {
6114
0
    AddAPValue(*VD->getEvaluatedValue());
6115
0
  }
6116
6117
0
  writeStmtRef(Init);
6118
0
}
6119
6120
0
void ASTWriter::ReaderInitialized(ASTReader *Reader) {
6121
0
  assert(Reader && "Cannot remove chain");
6122
0
  assert((!Chain || Chain == Reader) && "Cannot replace chain");
6123
0
  assert(FirstDeclID == NextDeclID &&
6124
0
         FirstTypeID == NextTypeID &&
6125
0
         FirstIdentID == NextIdentID &&
6126
0
         FirstMacroID == NextMacroID &&
6127
0
         FirstSubmoduleID == NextSubmoduleID &&
6128
0
         FirstSelectorID == NextSelectorID &&
6129
0
         "Setting chain after writing has started.");
6130
6131
0
  Chain = Reader;
6132
6133
  // Note, this will get called multiple times, once one the reader starts up
6134
  // and again each time it's done reading a PCH or module.
6135
0
  FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls();
6136
0
  FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes();
6137
0
  FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers();
6138
0
  FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros();
6139
0
  FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
6140
0
  FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
6141
0
  NextDeclID = FirstDeclID;
6142
0
  NextTypeID = FirstTypeID;
6143
0
  NextIdentID = FirstIdentID;
6144
0
  NextMacroID = FirstMacroID;
6145
0
  NextSelectorID = FirstSelectorID;
6146
0
  NextSubmoduleID = FirstSubmoduleID;
6147
0
}
6148
6149
0
void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
6150
  // Always keep the highest ID. See \p TypeRead() for more information.
6151
0
  IdentID &StoredID = IdentifierIDs[II];
6152
0
  if (ID > StoredID)
6153
0
    StoredID = ID;
6154
0
}
6155
6156
0
void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) {
6157
  // Always keep the highest ID. See \p TypeRead() for more information.
6158
0
  MacroID &StoredID = MacroIDs[MI];
6159
0
  if (ID > StoredID)
6160
0
    StoredID = ID;
6161
0
}
6162
6163
0
void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
6164
  // Always take the highest-numbered type index. This copes with an interesting
6165
  // case for chained AST writing where we schedule writing the type and then,
6166
  // later, deserialize the type from another AST. In this case, we want to
6167
  // keep the higher-numbered entry so that we can properly write it out to
6168
  // the AST file.
6169
0
  TypeIdx &StoredIdx = TypeIdxs[T];
6170
0
  if (Idx.getIndex() >= StoredIdx.getIndex())
6171
0
    StoredIdx = Idx;
6172
0
}
6173
6174
0
void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
6175
  // Always keep the highest ID. See \p TypeRead() for more information.
6176
0
  SelectorID &StoredID = SelectorIDs[S];
6177
0
  if (ID > StoredID)
6178
0
    StoredID = ID;
6179
0
}
6180
6181
void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
6182
0
                                    MacroDefinitionRecord *MD) {
6183
0
  assert(!MacroDefinitions.contains(MD));
6184
0
  MacroDefinitions[MD] = ID;
6185
0
}
6186
6187
0
void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
6188
0
  assert(!SubmoduleIDs.contains(Mod));
6189
0
  SubmoduleIDs[Mod] = ID;
6190
0
}
6191
6192
0
void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
6193
0
  if (Chain && Chain->isProcessingUpdateRecords()) return;
6194
0
  assert(D->isCompleteDefinition());
6195
0
  assert(!WritingAST && "Already writing the AST!");
6196
0
  if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6197
    // We are interested when a PCH decl is modified.
6198
0
    if (RD->isFromASTFile()) {
6199
      // A forward reference was mutated into a definition. Rewrite it.
6200
      // FIXME: This happens during template instantiation, should we
6201
      // have created a new definition decl instead ?
6202
0
      assert(isTemplateInstantiation(RD->getTemplateSpecializationKind()) &&
6203
0
             "completed a tag from another module but not by instantiation?");
6204
0
      DeclUpdates[RD].push_back(
6205
0
          DeclUpdate(UPD_CXX_INSTANTIATED_CLASS_DEFINITION));
6206
0
    }
6207
0
  }
6208
0
}
6209
6210
0
static bool isImportedDeclContext(ASTReader *Chain, const Decl *D) {
6211
0
  if (D->isFromASTFile())
6212
0
    return true;
6213
6214
  // The predefined __va_list_tag struct is imported if we imported any decls.
6215
  // FIXME: This is a gross hack.
6216
0
  return D == D->getASTContext().getVaListTagDecl();
6217
0
}
6218
6219
0
void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
6220
0
  if (Chain && Chain->isProcessingUpdateRecords()) return;
6221
0
  assert(DC->isLookupContext() &&
6222
0
          "Should not add lookup results to non-lookup contexts!");
6223
6224
  // TU is handled elsewhere.
6225
0
  if (isa<TranslationUnitDecl>(DC))
6226
0
    return;
6227
6228
  // Namespaces are handled elsewhere, except for template instantiations of
6229
  // FunctionTemplateDecls in namespaces. We are interested in cases where the
6230
  // local instantiations are added to an imported context. Only happens when
6231
  // adding ADL lookup candidates, for example templated friends.
6232
0
  if (isa<NamespaceDecl>(DC) && D->getFriendObjectKind() == Decl::FOK_None &&
6233
0
      !isa<FunctionTemplateDecl>(D))
6234
0
    return;
6235
6236
  // We're only interested in cases where a local declaration is added to an
6237
  // imported context.
6238
0
  if (D->isFromASTFile() || !isImportedDeclContext(Chain, cast<Decl>(DC)))
6239
0
    return;
6240
6241
0
  assert(DC == DC->getPrimaryContext() && "added to non-primary context");
6242
0
  assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!");
6243
0
  assert(!WritingAST && "Already writing the AST!");
6244
0
  if (UpdatedDeclContexts.insert(DC) && !cast<Decl>(DC)->isFromASTFile()) {
6245
    // We're adding a visible declaration to a predefined decl context. Ensure
6246
    // that we write out all of its lookup results so we don't get a nasty
6247
    // surprise when we try to emit its lookup table.
6248
0
    llvm::append_range(DeclsToEmitEvenIfUnreferenced, DC->decls());
6249
0
  }
6250
0
  DeclsToEmitEvenIfUnreferenced.push_back(D);
6251
0
}
6252
6253
0
void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
6254
0
  if (Chain && Chain->isProcessingUpdateRecords()) return;
6255
0
  assert(D->isImplicit());
6256
6257
  // We're only interested in cases where a local declaration is added to an
6258
  // imported context.
6259
0
  if (D->isFromASTFile() || !isImportedDeclContext(Chain, RD))
6260
0
    return;
6261
6262
0
  if (!isa<CXXMethodDecl>(D))
6263
0
    return;
6264
6265
  // A decl coming from PCH was modified.
6266
0
  assert(RD->isCompleteDefinition());
6267
0
  assert(!WritingAST && "Already writing the AST!");
6268
0
  DeclUpdates[RD].push_back(DeclUpdate(UPD_CXX_ADDED_IMPLICIT_MEMBER, D));
6269
0
}
6270
6271
0
void ASTWriter::ResolvedExceptionSpec(const FunctionDecl *FD) {
6272
0
  if (Chain && Chain->isProcessingUpdateRecords()) return;
6273
0
  assert(!DoneWritingDeclsAndTypes && "Already done writing updates!");
6274
0
  if (!Chain) return;
6275
0
  Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
6276
    // If we don't already know the exception specification for this redecl
6277
    // chain, add an update record for it.
6278
0
    if (isUnresolvedExceptionSpec(cast<FunctionDecl>(D)
6279
0
                                      ->getType()
6280
0
                                      ->castAs<FunctionProtoType>()
6281
0
                                      ->getExceptionSpecType()))
6282
0
      DeclUpdates[D].push_back(UPD_CXX_RESOLVED_EXCEPTION_SPEC);
6283
0
  });
6284
0
}
6285
6286
0
void ASTWriter::DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) {
6287
0
  if (Chain && Chain->isProcessingUpdateRecords()) return;
6288
0
  assert(!WritingAST && "Already writing the AST!");
6289
0
  if (!Chain) return;
6290
0
  Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
6291
0
    DeclUpdates[D].push_back(
6292
0
        DeclUpdate(UPD_CXX_DEDUCED_RETURN_TYPE, ReturnType));
6293
0
  });
6294
0
}
6295
6296
void ASTWriter::ResolvedOperatorDelete(const CXXDestructorDecl *DD,
6297
                                       const FunctionDecl *Delete,
6298
0
                                       Expr *ThisArg) {
6299
0
  if (Chain && Chain->isProcessingUpdateRecords()) return;
6300
0
  assert(!WritingAST && "Already writing the AST!");
6301
0
  assert(Delete && "Not given an operator delete");
6302
0
  if (!Chain) return;
6303
0
  Chain->forEachImportedKeyDecl(DD, [&](const Decl *D) {
6304
0
    DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_RESOLVED_DTOR_DELETE, Delete));
6305
0
  });
6306
0
}
6307
6308
0
void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
6309
0
  if (Chain && Chain->isProcessingUpdateRecords()) return;
6310
0
  assert(!WritingAST && "Already writing the AST!");
6311
0
  if (!D->isFromASTFile())
6312
0
    return; // Declaration not imported from PCH.
6313
6314
  // Implicit function decl from a PCH was defined.
6315
0
  DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
6316
0
}
6317
6318
0
void ASTWriter::VariableDefinitionInstantiated(const VarDecl *D) {
6319
0
  if (Chain && Chain->isProcessingUpdateRecords()) return;
6320
0
  assert(!WritingAST && "Already writing the AST!");
6321
0
  if (!D->isFromASTFile())
6322
0
    return;
6323
6324
0
  DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_VAR_DEFINITION));
6325
0
}
6326
6327
0
void ASTWriter::FunctionDefinitionInstantiated(const FunctionDecl *D) {
6328
0
  if (Chain && Chain->isProcessingUpdateRecords()) return;
6329
0
  assert(!WritingAST && "Already writing the AST!");
6330
0
  if (!D->isFromASTFile())
6331
0
    return;
6332
6333
0
  DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
6334
0
}
6335
6336
0
void ASTWriter::InstantiationRequested(const ValueDecl *D) {
6337
0
  if (Chain && Chain->isProcessingUpdateRecords()) return;
6338
0
  assert(!WritingAST && "Already writing the AST!");
6339
0
  if (!D->isFromASTFile())
6340
0
    return;
6341
6342
  // Since the actual instantiation is delayed, this really means that we need
6343
  // to update the instantiation location.
6344
0
  SourceLocation POI;
6345
0
  if (auto *VD = dyn_cast<VarDecl>(D))
6346
0
    POI = VD->getPointOfInstantiation();
6347
0
  else
6348
0
    POI = cast<FunctionDecl>(D)->getPointOfInstantiation();
6349
0
  DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_POINT_OF_INSTANTIATION, POI));
6350
0
}
6351
6352
0
void ASTWriter::DefaultArgumentInstantiated(const ParmVarDecl *D) {
6353
0
  if (Chain && Chain->isProcessingUpdateRecords()) return;
6354
0
  assert(!WritingAST && "Already writing the AST!");
6355
0
  if (!D->isFromASTFile())
6356
0
    return;
6357
6358
0
  DeclUpdates[D].push_back(
6359
0
      DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT, D));
6360
0
}
6361
6362
0
void ASTWriter::DefaultMemberInitializerInstantiated(const FieldDecl *D) {
6363
0
  assert(!WritingAST && "Already writing the AST!");
6364
0
  if (!D->isFromASTFile())
6365
0
    return;
6366
6367
0
  DeclUpdates[D].push_back(
6368
0
      DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER, D));
6369
0
}
6370
6371
void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
6372
0
                                             const ObjCInterfaceDecl *IFD) {
6373
0
  if (Chain && Chain->isProcessingUpdateRecords()) return;
6374
0
  assert(!WritingAST && "Already writing the AST!");
6375
0
  if (!IFD->isFromASTFile())
6376
0
    return; // Declaration not imported from PCH.
6377
6378
0
  assert(IFD->getDefinition() && "Category on a class without a definition?");
6379
0
  ObjCClassesWithCategories.insert(
6380
0
    const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
6381
0
}
6382
6383
0
void ASTWriter::DeclarationMarkedUsed(const Decl *D) {
6384
0
  if (Chain && Chain->isProcessingUpdateRecords()) return;
6385
0
  assert(!WritingAST && "Already writing the AST!");
6386
6387
  // If there is *any* declaration of the entity that's not from an AST file,
6388
  // we can skip writing the update record. We make sure that isUsed() triggers
6389
  // completion of the redeclaration chain of the entity.
6390
0
  for (auto Prev = D->getMostRecentDecl(); Prev; Prev = Prev->getPreviousDecl())
6391
0
    if (IsLocalDecl(Prev))
6392
0
      return;
6393
6394
0
  DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_USED));
6395
0
}
6396
6397
0
void ASTWriter::DeclarationMarkedOpenMPThreadPrivate(const Decl *D) {
6398
0
  if (Chain && Chain->isProcessingUpdateRecords()) return;
6399
0
  assert(!WritingAST && "Already writing the AST!");
6400
0
  if (!D->isFromASTFile())
6401
0
    return;
6402
6403
0
  DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_THREADPRIVATE));
6404
0
}
6405
6406
0
void ASTWriter::DeclarationMarkedOpenMPAllocate(const Decl *D, const Attr *A) {
6407
0
  if (Chain && Chain->isProcessingUpdateRecords()) return;
6408
0
  assert(!WritingAST && "Already writing the AST!");
6409
0
  if (!D->isFromASTFile())
6410
0
    return;
6411
6412
0
  DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_ALLOCATE, A));
6413
0
}
6414
6415
void ASTWriter::DeclarationMarkedOpenMPDeclareTarget(const Decl *D,
6416
0
                                                     const Attr *Attr) {
6417
0
  if (Chain && Chain->isProcessingUpdateRecords()) return;
6418
0
  assert(!WritingAST && "Already writing the AST!");
6419
0
  if (!D->isFromASTFile())
6420
0
    return;
6421
6422
0
  DeclUpdates[D].push_back(
6423
0
      DeclUpdate(UPD_DECL_MARKED_OPENMP_DECLARETARGET, Attr));
6424
0
}
6425
6426
0
void ASTWriter::RedefinedHiddenDefinition(const NamedDecl *D, Module *M) {
6427
0
  if (Chain && Chain->isProcessingUpdateRecords()) return;
6428
0
  assert(!WritingAST && "Already writing the AST!");
6429
0
  assert(!D->isUnconditionallyVisible() && "expected a hidden declaration");
6430
0
  DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_EXPORTED, M));
6431
0
}
6432
6433
void ASTWriter::AddedAttributeToRecord(const Attr *Attr,
6434
0
                                       const RecordDecl *Record) {
6435
0
  if (Chain && Chain->isProcessingUpdateRecords()) return;
6436
0
  assert(!WritingAST && "Already writing the AST!");
6437
0
  if (!Record->isFromASTFile())
6438
0
    return;
6439
0
  DeclUpdates[Record].push_back(DeclUpdate(UPD_ADDED_ATTR_TO_RECORD, Attr));
6440
0
}
6441
6442
void ASTWriter::AddedCXXTemplateSpecialization(
6443
0
    const ClassTemplateDecl *TD, const ClassTemplateSpecializationDecl *D) {
6444
0
  assert(!WritingAST && "Already writing the AST!");
6445
6446
0
  if (!TD->getFirstDecl()->isFromASTFile())
6447
0
    return;
6448
0
  if (Chain && Chain->isProcessingUpdateRecords())
6449
0
    return;
6450
6451
0
  DeclsToEmitEvenIfUnreferenced.push_back(D);
6452
0
}
6453
6454
void ASTWriter::AddedCXXTemplateSpecialization(
6455
0
    const VarTemplateDecl *TD, const VarTemplateSpecializationDecl *D) {
6456
0
  assert(!WritingAST && "Already writing the AST!");
6457
6458
0
  if (!TD->getFirstDecl()->isFromASTFile())
6459
0
    return;
6460
0
  if (Chain && Chain->isProcessingUpdateRecords())
6461
0
    return;
6462
6463
0
  DeclsToEmitEvenIfUnreferenced.push_back(D);
6464
0
}
6465
6466
void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
6467
0
                                               const FunctionDecl *D) {
6468
0
  assert(!WritingAST && "Already writing the AST!");
6469
6470
0
  if (!TD->getFirstDecl()->isFromASTFile())
6471
0
    return;
6472
0
  if (Chain && Chain->isProcessingUpdateRecords())
6473
0
    return;
6474
6475
0
  DeclsToEmitEvenIfUnreferenced.push_back(D);
6476
0
}
6477
6478
//===----------------------------------------------------------------------===//
6479
//// OMPClause Serialization
6480
////===----------------------------------------------------------------------===//
6481
6482
namespace {
6483
6484
class OMPClauseWriter : public OMPClauseVisitor<OMPClauseWriter> {
6485
  ASTRecordWriter &Record;
6486
6487
public:
6488
0
  OMPClauseWriter(ASTRecordWriter &Record) : Record(Record) {}
6489
#define GEN_CLANG_CLAUSE_CLASS
6490
#define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *S);
6491
#include "llvm/Frontend/OpenMP/OMP.inc"
6492
  void writeClause(OMPClause *C);
6493
  void VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C);
6494
  void VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C);
6495
};
6496
6497
}
6498
6499
0
void ASTRecordWriter::writeOMPClause(OMPClause *C) {
6500
0
  OMPClauseWriter(*this).writeClause(C);
6501
0
}
6502
6503
0
void OMPClauseWriter::writeClause(OMPClause *C) {
6504
0
  Record.push_back(unsigned(C->getClauseKind()));
6505
0
  Visit(C);
6506
0
  Record.AddSourceLocation(C->getBeginLoc());
6507
0
  Record.AddSourceLocation(C->getEndLoc());
6508
0
}
6509
6510
0
void OMPClauseWriter::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) {
6511
0
  Record.push_back(uint64_t(C->getCaptureRegion()));
6512
0
  Record.AddStmt(C->getPreInitStmt());
6513
0
}
6514
6515
0
void OMPClauseWriter::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) {
6516
0
  VisitOMPClauseWithPreInit(C);
6517
0
  Record.AddStmt(C->getPostUpdateExpr());
6518
0
}
6519
6520
0
void OMPClauseWriter::VisitOMPIfClause(OMPIfClause *C) {
6521
0
  VisitOMPClauseWithPreInit(C);
6522
0
  Record.push_back(uint64_t(C->getNameModifier()));
6523
0
  Record.AddSourceLocation(C->getNameModifierLoc());
6524
0
  Record.AddSourceLocation(C->getColonLoc());
6525
0
  Record.AddStmt(C->getCondition());
6526
0
  Record.AddSourceLocation(C->getLParenLoc());
6527
0
}
6528
6529
0
void OMPClauseWriter::VisitOMPFinalClause(OMPFinalClause *C) {
6530
0
  VisitOMPClauseWithPreInit(C);
6531
0
  Record.AddStmt(C->getCondition());
6532
0
  Record.AddSourceLocation(C->getLParenLoc());
6533
0
}
6534
6535
0
void OMPClauseWriter::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
6536
0
  VisitOMPClauseWithPreInit(C);
6537
0
  Record.AddStmt(C->getNumThreads());
6538
0
  Record.AddSourceLocation(C->getLParenLoc());
6539
0
}
6540
6541
0
void OMPClauseWriter::VisitOMPSafelenClause(OMPSafelenClause *C) {
6542
0
  Record.AddStmt(C->getSafelen());
6543
0
  Record.AddSourceLocation(C->getLParenLoc());
6544
0
}
6545
6546
0
void OMPClauseWriter::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
6547
0
  Record.AddStmt(C->getSimdlen());
6548
0
  Record.AddSourceLocation(C->getLParenLoc());
6549
0
}
6550
6551
0
void OMPClauseWriter::VisitOMPSizesClause(OMPSizesClause *C) {
6552
0
  Record.push_back(C->getNumSizes());
6553
0
  for (Expr *Size : C->getSizesRefs())
6554
0
    Record.AddStmt(Size);
6555
0
  Record.AddSourceLocation(C->getLParenLoc());
6556
0
}
6557
6558
0
void OMPClauseWriter::VisitOMPFullClause(OMPFullClause *C) {}
6559
6560
0
void OMPClauseWriter::VisitOMPPartialClause(OMPPartialClause *C) {
6561
0
  Record.AddStmt(C->getFactor());
6562
0
  Record.AddSourceLocation(C->getLParenLoc());
6563
0
}
6564
6565
0
void OMPClauseWriter::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
6566
0
  Record.AddStmt(C->getAllocator());
6567
0
  Record.AddSourceLocation(C->getLParenLoc());
6568
0
}
6569
6570
0
void OMPClauseWriter::VisitOMPCollapseClause(OMPCollapseClause *C) {
6571
0
  Record.AddStmt(C->getNumForLoops());
6572
0
  Record.AddSourceLocation(C->getLParenLoc());
6573
0
}
6574
6575
0
void OMPClauseWriter::VisitOMPDetachClause(OMPDetachClause *C) {
6576
0
  Record.AddStmt(C->getEventHandler());
6577
0
  Record.AddSourceLocation(C->getLParenLoc());
6578
0
}
6579
6580
0
void OMPClauseWriter::VisitOMPDefaultClause(OMPDefaultClause *C) {
6581
0
  Record.push_back(unsigned(C->getDefaultKind()));
6582
0
  Record.AddSourceLocation(C->getLParenLoc());
6583
0
  Record.AddSourceLocation(C->getDefaultKindKwLoc());
6584
0
}
6585
6586
0
void OMPClauseWriter::VisitOMPProcBindClause(OMPProcBindClause *C) {
6587
0
  Record.push_back(unsigned(C->getProcBindKind()));
6588
0
  Record.AddSourceLocation(C->getLParenLoc());
6589
0
  Record.AddSourceLocation(C->getProcBindKindKwLoc());
6590
0
}
6591
6592
0
void OMPClauseWriter::VisitOMPScheduleClause(OMPScheduleClause *C) {
6593
0
  VisitOMPClauseWithPreInit(C);
6594
0
  Record.push_back(C->getScheduleKind());
6595
0
  Record.push_back(C->getFirstScheduleModifier());
6596
0
  Record.push_back(C->getSecondScheduleModifier());
6597
0
  Record.AddStmt(C->getChunkSize());
6598
0
  Record.AddSourceLocation(C->getLParenLoc());
6599
0
  Record.AddSourceLocation(C->getFirstScheduleModifierLoc());
6600
0
  Record.AddSourceLocation(C->getSecondScheduleModifierLoc());
6601
0
  Record.AddSourceLocation(C->getScheduleKindLoc());
6602
0
  Record.AddSourceLocation(C->getCommaLoc());
6603
0
}
6604
6605
0
void OMPClauseWriter::VisitOMPOrderedClause(OMPOrderedClause *C) {
6606
0
  Record.push_back(C->getLoopNumIterations().size());
6607
0
  Record.AddStmt(C->getNumForLoops());
6608
0
  for (Expr *NumIter : C->getLoopNumIterations())
6609
0
    Record.AddStmt(NumIter);
6610
0
  for (unsigned I = 0, E = C->getLoopNumIterations().size(); I <E; ++I)
6611
0
    Record.AddStmt(C->getLoopCounter(I));
6612
0
  Record.AddSourceLocation(C->getLParenLoc());
6613
0
}
6614
6615
0
void OMPClauseWriter::VisitOMPNowaitClause(OMPNowaitClause *) {}
6616
6617
0
void OMPClauseWriter::VisitOMPUntiedClause(OMPUntiedClause *) {}
6618
6619
0
void OMPClauseWriter::VisitOMPMergeableClause(OMPMergeableClause *) {}
6620
6621
0
void OMPClauseWriter::VisitOMPReadClause(OMPReadClause *) {}
6622
6623
0
void OMPClauseWriter::VisitOMPWriteClause(OMPWriteClause *) {}
6624
6625
0
void OMPClauseWriter::VisitOMPUpdateClause(OMPUpdateClause *C) {
6626
0
  Record.push_back(C->isExtended() ? 1 : 0);
6627
0
  if (C->isExtended()) {
6628
0
    Record.AddSourceLocation(C->getLParenLoc());
6629
0
    Record.AddSourceLocation(C->getArgumentLoc());
6630
0
    Record.writeEnum(C->getDependencyKind());
6631
0
  }
6632
0
}
6633
6634
0
void OMPClauseWriter::VisitOMPCaptureClause(OMPCaptureClause *) {}
6635
6636
0
void OMPClauseWriter::VisitOMPCompareClause(OMPCompareClause *) {}
6637
6638
// Save the parameter of fail clause.
6639
0
void OMPClauseWriter::VisitOMPFailClause(OMPFailClause *C) {
6640
0
  Record.AddSourceLocation(C->getLParenLoc());
6641
0
  Record.AddSourceLocation(C->getFailParameterLoc());
6642
0
  Record.writeEnum(C->getFailParameter());
6643
0
}
6644
6645
0
void OMPClauseWriter::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
6646
6647
0
void OMPClauseWriter::VisitOMPAcqRelClause(OMPAcqRelClause *) {}
6648
6649
0
void OMPClauseWriter::VisitOMPAcquireClause(OMPAcquireClause *) {}
6650
6651
0
void OMPClauseWriter::VisitOMPReleaseClause(OMPReleaseClause *) {}
6652
6653
0
void OMPClauseWriter::VisitOMPRelaxedClause(OMPRelaxedClause *) {}
6654
6655
0
void OMPClauseWriter::VisitOMPThreadsClause(OMPThreadsClause *) {}
6656
6657
0
void OMPClauseWriter::VisitOMPSIMDClause(OMPSIMDClause *) {}
6658
6659
0
void OMPClauseWriter::VisitOMPNogroupClause(OMPNogroupClause *) {}
6660
6661
0
void OMPClauseWriter::VisitOMPInitClause(OMPInitClause *C) {
6662
0
  Record.push_back(C->varlist_size());
6663
0
  for (Expr *VE : C->varlists())
6664
0
    Record.AddStmt(VE);
6665
0
  Record.writeBool(C->getIsTarget());
6666
0
  Record.writeBool(C->getIsTargetSync());
6667
0
  Record.AddSourceLocation(C->getLParenLoc());
6668
0
  Record.AddSourceLocation(C->getVarLoc());
6669
0
}
6670
6671
0
void OMPClauseWriter::VisitOMPUseClause(OMPUseClause *C) {
6672
0
  Record.AddStmt(C->getInteropVar());
6673
0
  Record.AddSourceLocation(C->getLParenLoc());
6674
0
  Record.AddSourceLocation(C->getVarLoc());
6675
0
}
6676
6677
0
void OMPClauseWriter::VisitOMPDestroyClause(OMPDestroyClause *C) {
6678
0
  Record.AddStmt(C->getInteropVar());
6679
0
  Record.AddSourceLocation(C->getLParenLoc());
6680
0
  Record.AddSourceLocation(C->getVarLoc());
6681
0
}
6682
6683
0
void OMPClauseWriter::VisitOMPNovariantsClause(OMPNovariantsClause *C) {
6684
0
  VisitOMPClauseWithPreInit(C);
6685
0
  Record.AddStmt(C->getCondition());
6686
0
  Record.AddSourceLocation(C->getLParenLoc());
6687
0
}
6688
6689
0
void OMPClauseWriter::VisitOMPNocontextClause(OMPNocontextClause *C) {
6690
0
  VisitOMPClauseWithPreInit(C);
6691
0
  Record.AddStmt(C->getCondition());
6692
0
  Record.AddSourceLocation(C->getLParenLoc());
6693
0
}
6694
6695
0
void OMPClauseWriter::VisitOMPFilterClause(OMPFilterClause *C) {
6696
0
  VisitOMPClauseWithPreInit(C);
6697
0
  Record.AddStmt(C->getThreadID());
6698
0
  Record.AddSourceLocation(C->getLParenLoc());
6699
0
}
6700
6701
0
void OMPClauseWriter::VisitOMPAlignClause(OMPAlignClause *C) {
6702
0
  Record.AddStmt(C->getAlignment());
6703
0
  Record.AddSourceLocation(C->getLParenLoc());
6704
0
}
6705
6706
0
void OMPClauseWriter::VisitOMPPrivateClause(OMPPrivateClause *C) {
6707
0
  Record.push_back(C->varlist_size());
6708
0
  Record.AddSourceLocation(C->getLParenLoc());
6709
0
  for (auto *VE : C->varlists()) {
6710
0
    Record.AddStmt(VE);
6711
0
  }
6712
0
  for (auto *VE : C->private_copies()) {
6713
0
    Record.AddStmt(VE);
6714
0
  }
6715
0
}
6716
6717
0
void OMPClauseWriter::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
6718
0
  Record.push_back(C->varlist_size());
6719
0
  VisitOMPClauseWithPreInit(C);
6720
0
  Record.AddSourceLocation(C->getLParenLoc());
6721
0
  for (auto *VE : C->varlists()) {
6722
0
    Record.AddStmt(VE);
6723
0
  }
6724
0
  for (auto *VE : C->private_copies()) {
6725
0
    Record.AddStmt(VE);
6726
0
  }
6727
0
  for (auto *VE : C->inits()) {
6728
0
    Record.AddStmt(VE);
6729
0
  }
6730
0
}
6731
6732
0
void OMPClauseWriter::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
6733
0
  Record.push_back(C->varlist_size());
6734
0
  VisitOMPClauseWithPostUpdate(C);
6735
0
  Record.AddSourceLocation(C->getLParenLoc());
6736
0
  Record.writeEnum(C->getKind());
6737
0
  Record.AddSourceLocation(C->getKindLoc());
6738
0
  Record.AddSourceLocation(C->getColonLoc());
6739
0
  for (auto *VE : C->varlists())
6740
0
    Record.AddStmt(VE);
6741
0
  for (auto *E : C->private_copies())
6742
0
    Record.AddStmt(E);
6743
0
  for (auto *E : C->source_exprs())
6744
0
    Record.AddStmt(E);
6745
0
  for (auto *E : C->destination_exprs())
6746
0
    Record.AddStmt(E);
6747
0
  for (auto *E : C->assignment_ops())
6748
0
    Record.AddStmt(E);
6749
0
}
6750
6751
0
void OMPClauseWriter::VisitOMPSharedClause(OMPSharedClause *C) {
6752
0
  Record.push_back(C->varlist_size());
6753
0
  Record.AddSourceLocation(C->getLParenLoc());
6754
0
  for (auto *VE : C->varlists())
6755
0
    Record.AddStmt(VE);
6756
0
}
6757
6758
0
void OMPClauseWriter::VisitOMPReductionClause(OMPReductionClause *C) {
6759
0
  Record.push_back(C->varlist_size());
6760
0
  Record.writeEnum(C->getModifier());
6761
0
  VisitOMPClauseWithPostUpdate(C);
6762
0
  Record.AddSourceLocation(C->getLParenLoc());
6763
0
  Record.AddSourceLocation(C->getModifierLoc());
6764
0
  Record.AddSourceLocation(C->getColonLoc());
6765
0
  Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
6766
0
  Record.AddDeclarationNameInfo(C->getNameInfo());
6767
0
  for (auto *VE : C->varlists())
6768
0
    Record.AddStmt(VE);
6769
0
  for (auto *VE : C->privates())
6770
0
    Record.AddStmt(VE);
6771
0
  for (auto *E : C->lhs_exprs())
6772
0
    Record.AddStmt(E);
6773
0
  for (auto *E : C->rhs_exprs())
6774
0
    Record.AddStmt(E);
6775
0
  for (auto *E : C->reduction_ops())
6776
0
    Record.AddStmt(E);
6777
0
  if (C->getModifier() == clang::OMPC_REDUCTION_inscan) {
6778
0
    for (auto *E : C->copy_ops())
6779
0
      Record.AddStmt(E);
6780
0
    for (auto *E : C->copy_array_temps())
6781
0
      Record.AddStmt(E);
6782
0
    for (auto *E : C->copy_array_elems())
6783
0
      Record.AddStmt(E);
6784
0
  }
6785
0
}
6786
6787
0
void OMPClauseWriter::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
6788
0
  Record.push_back(C->varlist_size());
6789
0
  VisitOMPClauseWithPostUpdate(C);
6790
0
  Record.AddSourceLocation(C->getLParenLoc());
6791
0
  Record.AddSourceLocation(C->getColonLoc());
6792
0
  Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
6793
0
  Record.AddDeclarationNameInfo(C->getNameInfo());
6794
0
  for (auto *VE : C->varlists())
6795
0
    Record.AddStmt(VE);
6796
0
  for (auto *VE : C->privates())
6797
0
    Record.AddStmt(VE);
6798
0
  for (auto *E : C->lhs_exprs())
6799
0
    Record.AddStmt(E);
6800
0
  for (auto *E : C->rhs_exprs())
6801
0
    Record.AddStmt(E);
6802
0
  for (auto *E : C->reduction_ops())
6803
0
    Record.AddStmt(E);
6804
0
}
6805
6806
0
void OMPClauseWriter::VisitOMPInReductionClause(OMPInReductionClause *C) {
6807
0
  Record.push_back(C->varlist_size());
6808
0
  VisitOMPClauseWithPostUpdate(C);
6809
0
  Record.AddSourceLocation(C->getLParenLoc());
6810
0
  Record.AddSourceLocation(C->getColonLoc());
6811
0
  Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
6812
0
  Record.AddDeclarationNameInfo(C->getNameInfo());
6813
0
  for (auto *VE : C->varlists())
6814
0
    Record.AddStmt(VE);
6815
0
  for (auto *VE : C->privates())
6816
0
    Record.AddStmt(VE);
6817
0
  for (auto *E : C->lhs_exprs())
6818
0
    Record.AddStmt(E);
6819
0
  for (auto *E : C->rhs_exprs())
6820
0
    Record.AddStmt(E);
6821
0
  for (auto *E : C->reduction_ops())
6822
0
    Record.AddStmt(E);
6823
0
  for (auto *E : C->taskgroup_descriptors())
6824
0
    Record.AddStmt(E);
6825
0
}
6826
6827
0
void OMPClauseWriter::VisitOMPLinearClause(OMPLinearClause *C) {
6828
0
  Record.push_back(C->varlist_size());
6829
0
  VisitOMPClauseWithPostUpdate(C);
6830
0
  Record.AddSourceLocation(C->getLParenLoc());
6831
0
  Record.AddSourceLocation(C->getColonLoc());
6832
0
  Record.push_back(C->getModifier());
6833
0
  Record.AddSourceLocation(C->getModifierLoc());
6834
0
  for (auto *VE : C->varlists()) {
6835
0
    Record.AddStmt(VE);
6836
0
  }
6837
0
  for (auto *VE : C->privates()) {
6838
0
    Record.AddStmt(VE);
6839
0
  }
6840
0
  for (auto *VE : C->inits()) {
6841
0
    Record.AddStmt(VE);
6842
0
  }
6843
0
  for (auto *VE : C->updates()) {
6844
0
    Record.AddStmt(VE);
6845
0
  }
6846
0
  for (auto *VE : C->finals()) {
6847
0
    Record.AddStmt(VE);
6848
0
  }
6849
0
  Record.AddStmt(C->getStep());
6850
0
  Record.AddStmt(C->getCalcStep());
6851
0
  for (auto *VE : C->used_expressions())
6852
0
    Record.AddStmt(VE);
6853
0
}
6854
6855
0
void OMPClauseWriter::VisitOMPAlignedClause(OMPAlignedClause *C) {
6856
0
  Record.push_back(C->varlist_size());
6857
0
  Record.AddSourceLocation(C->getLParenLoc());
6858
0
  Record.AddSourceLocation(C->getColonLoc());
6859
0
  for (auto *VE : C->varlists())
6860
0
    Record.AddStmt(VE);
6861
0
  Record.AddStmt(C->getAlignment());
6862
0
}
6863
6864
0
void OMPClauseWriter::VisitOMPCopyinClause(OMPCopyinClause *C) {
6865
0
  Record.push_back(C->varlist_size());
6866
0
  Record.AddSourceLocation(C->getLParenLoc());
6867
0
  for (auto *VE : C->varlists())
6868
0
    Record.AddStmt(VE);
6869
0
  for (auto *E : C->source_exprs())
6870
0
    Record.AddStmt(E);
6871
0
  for (auto *E : C->destination_exprs())
6872
0
    Record.AddStmt(E);
6873
0
  for (auto *E : C->assignment_ops())
6874
0
    Record.AddStmt(E);
6875
0
}
6876
6877
0
void OMPClauseWriter::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
6878
0
  Record.push_back(C->varlist_size());
6879
0
  Record.AddSourceLocation(C->getLParenLoc());
6880
0
  for (auto *VE : C->varlists())
6881
0
    Record.AddStmt(VE);
6882
0
  for (auto *E : C->source_exprs())
6883
0
    Record.AddStmt(E);
6884
0
  for (auto *E : C->destination_exprs())
6885
0
    Record.AddStmt(E);
6886
0
  for (auto *E : C->assignment_ops())
6887
0
    Record.AddStmt(E);
6888
0
}
6889
6890
0
void OMPClauseWriter::VisitOMPFlushClause(OMPFlushClause *C) {
6891
0
  Record.push_back(C->varlist_size());
6892
0
  Record.AddSourceLocation(C->getLParenLoc());
6893
0
  for (auto *VE : C->varlists())
6894
0
    Record.AddStmt(VE);
6895
0
}
6896
6897
0
void OMPClauseWriter::VisitOMPDepobjClause(OMPDepobjClause *C) {
6898
0
  Record.AddStmt(C->getDepobj());
6899
0
  Record.AddSourceLocation(C->getLParenLoc());
6900
0
}
6901
6902
0
void OMPClauseWriter::VisitOMPDependClause(OMPDependClause *C) {
6903
0
  Record.push_back(C->varlist_size());
6904
0
  Record.push_back(C->getNumLoops());
6905
0
  Record.AddSourceLocation(C->getLParenLoc());
6906
0
  Record.AddStmt(C->getModifier());
6907
0
  Record.push_back(C->getDependencyKind());
6908
0
  Record.AddSourceLocation(C->getDependencyLoc());
6909
0
  Record.AddSourceLocation(C->getColonLoc());
6910
0
  Record.AddSourceLocation(C->getOmpAllMemoryLoc());
6911
0
  for (auto *VE : C->varlists())
6912
0
    Record.AddStmt(VE);
6913
0
  for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
6914
0
    Record.AddStmt(C->getLoopData(I));
6915
0
}
6916
6917
0
void OMPClauseWriter::VisitOMPDeviceClause(OMPDeviceClause *C) {
6918
0
  VisitOMPClauseWithPreInit(C);
6919
0
  Record.writeEnum(C->getModifier());
6920
0
  Record.AddStmt(C->getDevice());
6921
0
  Record.AddSourceLocation(C->getModifierLoc());
6922
0
  Record.AddSourceLocation(C->getLParenLoc());
6923
0
}
6924
6925
0
void OMPClauseWriter::VisitOMPMapClause(OMPMapClause *C) {
6926
0
  Record.push_back(C->varlist_size());
6927
0
  Record.push_back(C->getUniqueDeclarationsNum());
6928
0
  Record.push_back(C->getTotalComponentListNum());
6929
0
  Record.push_back(C->getTotalComponentsNum());
6930
0
  Record.AddSourceLocation(C->getLParenLoc());
6931
0
  bool HasIteratorModifier = false;
6932
0
  for (unsigned I = 0; I < NumberOfOMPMapClauseModifiers; ++I) {
6933
0
    Record.push_back(C->getMapTypeModifier(I));
6934
0
    Record.AddSourceLocation(C->getMapTypeModifierLoc(I));
6935
0
    if (C->getMapTypeModifier(I) == OMPC_MAP_MODIFIER_iterator)
6936
0
      HasIteratorModifier = true;
6937
0
  }
6938
0
  Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc());
6939
0
  Record.AddDeclarationNameInfo(C->getMapperIdInfo());
6940
0
  Record.push_back(C->getMapType());
6941
0
  Record.AddSourceLocation(C->getMapLoc());
6942
0
  Record.AddSourceLocation(C->getColonLoc());
6943
0
  for (auto *E : C->varlists())
6944
0
    Record.AddStmt(E);
6945
0
  for (auto *E : C->mapperlists())
6946
0
    Record.AddStmt(E);
6947
0
  if (HasIteratorModifier)
6948
0
    Record.AddStmt(C->getIteratorModifier());
6949
0
  for (auto *D : C->all_decls())
6950
0
    Record.AddDeclRef(D);
6951
0
  for (auto N : C->all_num_lists())
6952
0
    Record.push_back(N);
6953
0
  for (auto N : C->all_lists_sizes())
6954
0
    Record.push_back(N);
6955
0
  for (auto &M : C->all_components()) {
6956
0
    Record.AddStmt(M.getAssociatedExpression());
6957
0
    Record.AddDeclRef(M.getAssociatedDeclaration());
6958
0
  }
6959
0
}
6960
6961
0
void OMPClauseWriter::VisitOMPAllocateClause(OMPAllocateClause *C) {
6962
0
  Record.push_back(C->varlist_size());
6963
0
  Record.AddSourceLocation(C->getLParenLoc());
6964
0
  Record.AddSourceLocation(C->getColonLoc());
6965
0
  Record.AddStmt(C->getAllocator());
6966
0
  for (auto *VE : C->varlists())
6967
0
    Record.AddStmt(VE);
6968
0
}
6969
6970
0
void OMPClauseWriter::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
6971
0
  VisitOMPClauseWithPreInit(C);
6972
0
  Record.AddStmt(C->getNumTeams());
6973
0
  Record.AddSourceLocation(C->getLParenLoc());
6974
0
}
6975
6976
0
void OMPClauseWriter::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
6977
0
  VisitOMPClauseWithPreInit(C);
6978
0
  Record.AddStmt(C->getThreadLimit());
6979
0
  Record.AddSourceLocation(C->getLParenLoc());
6980
0
}
6981
6982
0
void OMPClauseWriter::VisitOMPPriorityClause(OMPPriorityClause *C) {
6983
0
  VisitOMPClauseWithPreInit(C);
6984
0
  Record.AddStmt(C->getPriority());
6985
0
  Record.AddSourceLocation(C->getLParenLoc());
6986
0
}
6987
6988
0
void OMPClauseWriter::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
6989
0
  VisitOMPClauseWithPreInit(C);
6990
0
  Record.writeEnum(C->getModifier());
6991
0
  Record.AddStmt(C->getGrainsize());
6992
0
  Record.AddSourceLocation(C->getModifierLoc());
6993
0
  Record.AddSourceLocation(C->getLParenLoc());
6994
0
}
6995
6996
0
void OMPClauseWriter::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
6997
0
  VisitOMPClauseWithPreInit(C);
6998
0
  Record.writeEnum(C->getModifier());
6999
0
  Record.AddStmt(C->getNumTasks());
7000
0
  Record.AddSourceLocation(C->getModifierLoc());
7001
0
  Record.AddSourceLocation(C->getLParenLoc());
7002
0
}
7003
7004
0
void OMPClauseWriter::VisitOMPHintClause(OMPHintClause *C) {
7005
0
  Record.AddStmt(C->getHint());
7006
0
  Record.AddSourceLocation(C->getLParenLoc());
7007
0
}
7008
7009
0
void OMPClauseWriter::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
7010
0
  VisitOMPClauseWithPreInit(C);
7011
0
  Record.push_back(C->getDistScheduleKind());
7012
0
  Record.AddStmt(C->getChunkSize());
7013
0
  Record.AddSourceLocation(C->getLParenLoc());
7014
0
  Record.AddSourceLocation(C->getDistScheduleKindLoc());
7015
0
  Record.AddSourceLocation(C->getCommaLoc());
7016
0
}
7017
7018
0
void OMPClauseWriter::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
7019
0
  Record.push_back(C->getDefaultmapKind());
7020
0
  Record.push_back(C->getDefaultmapModifier());
7021
0
  Record.AddSourceLocation(C->getLParenLoc());
7022
0
  Record.AddSourceLocation(C->getDefaultmapModifierLoc());
7023
0
  Record.AddSourceLocation(C->getDefaultmapKindLoc());
7024
0
}
7025
7026
0
void OMPClauseWriter::VisitOMPToClause(OMPToClause *C) {
7027
0
  Record.push_back(C->varlist_size());
7028
0
  Record.push_back(C->getUniqueDeclarationsNum());
7029
0
  Record.push_back(C->getTotalComponentListNum());
7030
0
  Record.push_back(C->getTotalComponentsNum());
7031
0
  Record.AddSourceLocation(C->getLParenLoc());
7032
0
  for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
7033
0
    Record.push_back(C->getMotionModifier(I));
7034
0
    Record.AddSourceLocation(C->getMotionModifierLoc(I));
7035
0
  }
7036
0
  Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc());
7037
0
  Record.AddDeclarationNameInfo(C->getMapperIdInfo());
7038
0
  Record.AddSourceLocation(C->getColonLoc());
7039
0
  for (auto *E : C->varlists())
7040
0
    Record.AddStmt(E);
7041
0
  for (auto *E : C->mapperlists())
7042
0
    Record.AddStmt(E);
7043
0
  for (auto *D : C->all_decls())
7044
0
    Record.AddDeclRef(D);
7045
0
  for (auto N : C->all_num_lists())
7046
0
    Record.push_back(N);
7047
0
  for (auto N : C->all_lists_sizes())
7048
0
    Record.push_back(N);
7049
0
  for (auto &M : C->all_components()) {
7050
0
    Record.AddStmt(M.getAssociatedExpression());
7051
0
    Record.writeBool(M.isNonContiguous());
7052
0
    Record.AddDeclRef(M.getAssociatedDeclaration());
7053
0
  }
7054
0
}
7055
7056
0
void OMPClauseWriter::VisitOMPFromClause(OMPFromClause *C) {
7057
0
  Record.push_back(C->varlist_size());
7058
0
  Record.push_back(C->getUniqueDeclarationsNum());
7059
0
  Record.push_back(C->getTotalComponentListNum());
7060
0
  Record.push_back(C->getTotalComponentsNum());
7061
0
  Record.AddSourceLocation(C->getLParenLoc());
7062
0
  for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
7063
0
    Record.push_back(C->getMotionModifier(I));
7064
0
    Record.AddSourceLocation(C->getMotionModifierLoc(I));
7065
0
  }
7066
0
  Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc());
7067
0
  Record.AddDeclarationNameInfo(C->getMapperIdInfo());
7068
0
  Record.AddSourceLocation(C->getColonLoc());
7069
0
  for (auto *E : C->varlists())
7070
0
    Record.AddStmt(E);
7071
0
  for (auto *E : C->mapperlists())
7072
0
    Record.AddStmt(E);
7073
0
  for (auto *D : C->all_decls())
7074
0
    Record.AddDeclRef(D);
7075
0
  for (auto N : C->all_num_lists())
7076
0
    Record.push_back(N);
7077
0
  for (auto N : C->all_lists_sizes())
7078
0
    Record.push_back(N);
7079
0
  for (auto &M : C->all_components()) {
7080
0
    Record.AddStmt(M.getAssociatedExpression());
7081
0
    Record.writeBool(M.isNonContiguous());
7082
0
    Record.AddDeclRef(M.getAssociatedDeclaration());
7083
0
  }
7084
0
}
7085
7086
0
void OMPClauseWriter::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
7087
0
  Record.push_back(C->varlist_size());
7088
0
  Record.push_back(C->getUniqueDeclarationsNum());
7089
0
  Record.push_back(C->getTotalComponentListNum());
7090
0
  Record.push_back(C->getTotalComponentsNum());
7091
0
  Record.AddSourceLocation(C->getLParenLoc());
7092
0
  for (auto *E : C->varlists())
7093
0
    Record.AddStmt(E);
7094
0
  for (auto *VE : C->private_copies())
7095
0
    Record.AddStmt(VE);
7096
0
  for (auto *VE : C->inits())
7097
0
    Record.AddStmt(VE);
7098
0
  for (auto *D : C->all_decls())
7099
0
    Record.AddDeclRef(D);
7100
0
  for (auto N : C->all_num_lists())
7101
0
    Record.push_back(N);
7102
0
  for (auto N : C->all_lists_sizes())
7103
0
    Record.push_back(N);
7104
0
  for (auto &M : C->all_components()) {
7105
0
    Record.AddStmt(M.getAssociatedExpression());
7106
0
    Record.AddDeclRef(M.getAssociatedDeclaration());
7107
0
  }
7108
0
}
7109
7110
0
void OMPClauseWriter::VisitOMPUseDeviceAddrClause(OMPUseDeviceAddrClause *C) {
7111
0
  Record.push_back(C->varlist_size());
7112
0
  Record.push_back(C->getUniqueDeclarationsNum());
7113
0
  Record.push_back(C->getTotalComponentListNum());
7114
0
  Record.push_back(C->getTotalComponentsNum());
7115
0
  Record.AddSourceLocation(C->getLParenLoc());
7116
0
  for (auto *E : C->varlists())
7117
0
    Record.AddStmt(E);
7118
0
  for (auto *D : C->all_decls())
7119
0
    Record.AddDeclRef(D);
7120
0
  for (auto N : C->all_num_lists())
7121
0
    Record.push_back(N);
7122
0
  for (auto N : C->all_lists_sizes())
7123
0
    Record.push_back(N);
7124
0
  for (auto &M : C->all_components()) {
7125
0
    Record.AddStmt(M.getAssociatedExpression());
7126
0
    Record.AddDeclRef(M.getAssociatedDeclaration());
7127
0
  }
7128
0
}
7129
7130
0
void OMPClauseWriter::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
7131
0
  Record.push_back(C->varlist_size());
7132
0
  Record.push_back(C->getUniqueDeclarationsNum());
7133
0
  Record.push_back(C->getTotalComponentListNum());
7134
0
  Record.push_back(C->getTotalComponentsNum());
7135
0
  Record.AddSourceLocation(C->getLParenLoc());
7136
0
  for (auto *E : C->varlists())
7137
0
    Record.AddStmt(E);
7138
0
  for (auto *D : C->all_decls())
7139
0
    Record.AddDeclRef(D);
7140
0
  for (auto N : C->all_num_lists())
7141
0
    Record.push_back(N);
7142
0
  for (auto N : C->all_lists_sizes())
7143
0
    Record.push_back(N);
7144
0
  for (auto &M : C->all_components()) {
7145
0
    Record.AddStmt(M.getAssociatedExpression());
7146
0
    Record.AddDeclRef(M.getAssociatedDeclaration());
7147
0
  }
7148
0
}
7149
7150
0
void OMPClauseWriter::VisitOMPHasDeviceAddrClause(OMPHasDeviceAddrClause *C) {
7151
0
  Record.push_back(C->varlist_size());
7152
0
  Record.push_back(C->getUniqueDeclarationsNum());
7153
0
  Record.push_back(C->getTotalComponentListNum());
7154
0
  Record.push_back(C->getTotalComponentsNum());
7155
0
  Record.AddSourceLocation(C->getLParenLoc());
7156
0
  for (auto *E : C->varlists())
7157
0
    Record.AddStmt(E);
7158
0
  for (auto *D : C->all_decls())
7159
0
    Record.AddDeclRef(D);
7160
0
  for (auto N : C->all_num_lists())
7161
0
    Record.push_back(N);
7162
0
  for (auto N : C->all_lists_sizes())
7163
0
    Record.push_back(N);
7164
0
  for (auto &M : C->all_components()) {
7165
0
    Record.AddStmt(M.getAssociatedExpression());
7166
0
    Record.AddDeclRef(M.getAssociatedDeclaration());
7167
0
  }
7168
0
}
7169
7170
0
void OMPClauseWriter::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
7171
7172
void OMPClauseWriter::VisitOMPUnifiedSharedMemoryClause(
7173
0
    OMPUnifiedSharedMemoryClause *) {}
7174
7175
0
void OMPClauseWriter::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
7176
7177
void
7178
0
OMPClauseWriter::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
7179
0
}
7180
7181
void OMPClauseWriter::VisitOMPAtomicDefaultMemOrderClause(
7182
0
    OMPAtomicDefaultMemOrderClause *C) {
7183
0
  Record.push_back(C->getAtomicDefaultMemOrderKind());
7184
0
  Record.AddSourceLocation(C->getLParenLoc());
7185
0
  Record.AddSourceLocation(C->getAtomicDefaultMemOrderKindKwLoc());
7186
0
}
7187
7188
0
void OMPClauseWriter::VisitOMPAtClause(OMPAtClause *C) {
7189
0
  Record.push_back(C->getAtKind());
7190
0
  Record.AddSourceLocation(C->getLParenLoc());
7191
0
  Record.AddSourceLocation(C->getAtKindKwLoc());
7192
0
}
7193
7194
0
void OMPClauseWriter::VisitOMPSeverityClause(OMPSeverityClause *C) {
7195
0
  Record.push_back(C->getSeverityKind());
7196
0
  Record.AddSourceLocation(C->getLParenLoc());
7197
0
  Record.AddSourceLocation(C->getSeverityKindKwLoc());
7198
0
}
7199
7200
0
void OMPClauseWriter::VisitOMPMessageClause(OMPMessageClause *C) {
7201
0
  Record.AddStmt(C->getMessageString());
7202
0
  Record.AddSourceLocation(C->getLParenLoc());
7203
0
}
7204
7205
0
void OMPClauseWriter::VisitOMPNontemporalClause(OMPNontemporalClause *C) {
7206
0
  Record.push_back(C->varlist_size());
7207
0
  Record.AddSourceLocation(C->getLParenLoc());
7208
0
  for (auto *VE : C->varlists())
7209
0
    Record.AddStmt(VE);
7210
0
  for (auto *E : C->private_refs())
7211
0
    Record.AddStmt(E);
7212
0
}
7213
7214
0
void OMPClauseWriter::VisitOMPInclusiveClause(OMPInclusiveClause *C) {
7215
0
  Record.push_back(C->varlist_size());
7216
0
  Record.AddSourceLocation(C->getLParenLoc());
7217
0
  for (auto *VE : C->varlists())
7218
0
    Record.AddStmt(VE);
7219
0
}
7220
7221
0
void OMPClauseWriter::VisitOMPExclusiveClause(OMPExclusiveClause *C) {
7222
0
  Record.push_back(C->varlist_size());
7223
0
  Record.AddSourceLocation(C->getLParenLoc());
7224
0
  for (auto *VE : C->varlists())
7225
0
    Record.AddStmt(VE);
7226
0
}
7227
7228
0
void OMPClauseWriter::VisitOMPOrderClause(OMPOrderClause *C) {
7229
0
  Record.writeEnum(C->getKind());
7230
0
  Record.writeEnum(C->getModifier());
7231
0
  Record.AddSourceLocation(C->getLParenLoc());
7232
0
  Record.AddSourceLocation(C->getKindKwLoc());
7233
0
  Record.AddSourceLocation(C->getModifierKwLoc());
7234
0
}
7235
7236
0
void OMPClauseWriter::VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause *C) {
7237
0
  Record.push_back(C->getNumberOfAllocators());
7238
0
  Record.AddSourceLocation(C->getLParenLoc());
7239
0
  for (unsigned I = 0, E = C->getNumberOfAllocators(); I < E; ++I) {
7240
0
    OMPUsesAllocatorsClause::Data Data = C->getAllocatorData(I);
7241
0
    Record.AddStmt(Data.Allocator);
7242
0
    Record.AddStmt(Data.AllocatorTraits);
7243
0
    Record.AddSourceLocation(Data.LParenLoc);
7244
0
    Record.AddSourceLocation(Data.RParenLoc);
7245
0
  }
7246
0
}
7247
7248
0
void OMPClauseWriter::VisitOMPAffinityClause(OMPAffinityClause *C) {
7249
0
  Record.push_back(C->varlist_size());
7250
0
  Record.AddSourceLocation(C->getLParenLoc());
7251
0
  Record.AddStmt(C->getModifier());
7252
0
  Record.AddSourceLocation(C->getColonLoc());
7253
0
  for (Expr *E : C->varlists())
7254
0
    Record.AddStmt(E);
7255
0
}
7256
7257
0
void OMPClauseWriter::VisitOMPBindClause(OMPBindClause *C) {
7258
0
  Record.writeEnum(C->getBindKind());
7259
0
  Record.AddSourceLocation(C->getLParenLoc());
7260
0
  Record.AddSourceLocation(C->getBindKindLoc());
7261
0
}
7262
7263
0
void OMPClauseWriter::VisitOMPXDynCGroupMemClause(OMPXDynCGroupMemClause *C) {
7264
0
  VisitOMPClauseWithPreInit(C);
7265
0
  Record.AddStmt(C->getSize());
7266
0
  Record.AddSourceLocation(C->getLParenLoc());
7267
0
}
7268
7269
0
void OMPClauseWriter::VisitOMPDoacrossClause(OMPDoacrossClause *C) {
7270
0
  Record.push_back(C->varlist_size());
7271
0
  Record.push_back(C->getNumLoops());
7272
0
  Record.AddSourceLocation(C->getLParenLoc());
7273
0
  Record.push_back(C->getDependenceType());
7274
0
  Record.AddSourceLocation(C->getDependenceLoc());
7275
0
  Record.AddSourceLocation(C->getColonLoc());
7276
0
  for (auto *VE : C->varlists())
7277
0
    Record.AddStmt(VE);
7278
0
  for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
7279
0
    Record.AddStmt(C->getLoopData(I));
7280
0
}
7281
7282
0
void OMPClauseWriter::VisitOMPXAttributeClause(OMPXAttributeClause *C) {
7283
0
  Record.AddAttributes(C->getAttrs());
7284
0
  Record.AddSourceLocation(C->getBeginLoc());
7285
0
  Record.AddSourceLocation(C->getLParenLoc());
7286
0
  Record.AddSourceLocation(C->getEndLoc());
7287
0
}
7288
7289
0
void OMPClauseWriter::VisitOMPXBareClause(OMPXBareClause *C) {}
7290
7291
0
void ASTRecordWriter::writeOMPTraitInfo(const OMPTraitInfo *TI) {
7292
0
  writeUInt32(TI->Sets.size());
7293
0
  for (const auto &Set : TI->Sets) {
7294
0
    writeEnum(Set.Kind);
7295
0
    writeUInt32(Set.Selectors.size());
7296
0
    for (const auto &Selector : Set.Selectors) {
7297
0
      writeEnum(Selector.Kind);
7298
0
      writeBool(Selector.ScoreOrCondition);
7299
0
      if (Selector.ScoreOrCondition)
7300
0
        writeExprRef(Selector.ScoreOrCondition);
7301
0
      writeUInt32(Selector.Properties.size());
7302
0
      for (const auto &Property : Selector.Properties)
7303
0
        writeEnum(Property.Kind);
7304
0
    }
7305
0
  }
7306
0
}
7307
7308
0
void ASTRecordWriter::writeOMPChildren(OMPChildren *Data) {
7309
0
  if (!Data)
7310
0
    return;
7311
0
  writeUInt32(Data->getNumClauses());
7312
0
  writeUInt32(Data->getNumChildren());
7313
0
  writeBool(Data->hasAssociatedStmt());
7314
0
  for (unsigned I = 0, E = Data->getNumClauses(); I < E; ++I)
7315
0
    writeOMPClause(Data->getClauses()[I]);
7316
0
  if (Data->hasAssociatedStmt())
7317
0
    AddStmt(Data->getAssociatedStmt());
7318
0
  for (unsigned I = 0, E = Data->getNumChildren(); I < E; ++I)
7319
0
    AddStmt(Data->getChildren()[I]);
7320
0
}