Bug Summary

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