Bug Summary

File:tools/clang/lib/Serialization/ASTWriter.cpp
Warning:line 2108, column 19
Potential memory leak

Annotated Source Code

Press '?' to see keyboard shortcuts

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