Bug Summary

File:build/source/clang/lib/Serialization/ASTWriter.cpp
Warning:line 1905, column 9
Potential memory leak

Annotated Source Code

Press '?' to see keyboard shortcuts

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