Bug Summary

File:tools/clang/lib/Serialization/ASTWriter.cpp
Warning:line 2106, 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 -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-9/lib/clang/9.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-9~svn362543/build-llvm/tools/clang/lib/Serialization -I /build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Serialization -I /build/llvm-toolchain-snapshot-9~svn362543/tools/clang/include -I /build/llvm-toolchain-snapshot-9~svn362543/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-9~svn362543/build-llvm/include -I /build/llvm-toolchain-snapshot-9~svn362543/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/include/clang/9.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-9/lib/clang/9.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++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-9~svn362543/build-llvm/tools/clang/lib/Serialization -fdebug-prefix-map=/build/llvm-toolchain-snapshot-9~svn362543=. -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 -o /tmp/scan-build-2019-06-05-060531-1271-1 -x c++ /build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp -faddrsig
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/Bitcode/BitCodes.h"
87#include "llvm/Bitcode/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-9~svn362543/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-9~svn362543/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-9~svn362543/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-9~svn362543/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_TYPE_ALIAS_TEMPLATE);
1297 RECORD(DECL_STATIC_ASSERT);
1298 RECORD(DECL_CXX_BASE_SPECIFIERS);
1299 RECORD(DECL_CXX_CTOR_INITIALIZERS);
1300 RECORD(DECL_INDIRECTFIELD);
1301 RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
1302 RECORD(DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK);
1303 RECORD(DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION);
1304 RECORD(DECL_IMPORT);
1305 RECORD(DECL_OMP_THREADPRIVATE);
1306 RECORD(DECL_EMPTY);
1307 RECORD(DECL_OBJC_TYPE_PARAM);
1308 RECORD(DECL_OMP_CAPTUREDEXPR);
1309 RECORD(DECL_PRAGMA_COMMENT);
1310 RECORD(DECL_PRAGMA_DETECT_MISMATCH);
1311 RECORD(DECL_OMP_DECLARE_REDUCTION);
1312 RECORD(DECL_OMP_ALLOCATE);
1313
1314 // Statements and Exprs can occur in the Decls and Types block.
1315 AddStmtsExprs(Stream, Record);
1316
1317 BLOCK(PREPROCESSOR_DETAIL_BLOCK);
1318 RECORD(PPD_MACRO_EXPANSION);
1319 RECORD(PPD_MACRO_DEFINITION);
1320 RECORD(PPD_INCLUSION_DIRECTIVE);
1321
1322 // Decls and Types block.
1323 BLOCK(EXTENSION_BLOCK);
1324 RECORD(EXTENSION_METADATA);
1325
1326 BLOCK(UNHASHED_CONTROL_BLOCK);
1327 RECORD(SIGNATURE);
1328 RECORD(DIAGNOSTIC_OPTIONS);
1329 RECORD(DIAG_PRAGMA_MAPPINGS);
1330
1331#undef RECORD
1332#undef BLOCK
1333 Stream.ExitBlock();
1334}
1335
1336/// Prepares a path for being written to an AST file by converting it
1337/// to an absolute path and removing nested './'s.
1338///
1339/// \return \c true if the path was changed.
1340static bool cleanPathForOutput(FileManager &FileMgr,
1341 SmallVectorImpl<char> &Path) {
1342 bool Changed = FileMgr.makeAbsolutePath(Path);
1343 return Changed | llvm::sys::path::remove_dots(Path);
1344}
1345
1346/// Adjusts the given filename to only write out the portion of the
1347/// filename that is not part of the system root directory.
1348///
1349/// \param Filename the file name to adjust.
1350///
1351/// \param BaseDir When non-NULL, the PCH file is a relocatable AST file and
1352/// the returned filename will be adjusted by this root directory.
1353///
1354/// \returns either the original filename (if it needs no adjustment) or the
1355/// adjusted filename (which points into the @p Filename parameter).
1356static const char *
1357adjustFilenameForRelocatableAST(const char *Filename, StringRef BaseDir) {
1358 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 1358, __PRETTY_FUNCTION__))
;
1359
1360 if (BaseDir.empty())
1361 return Filename;
1362
1363 // Verify that the filename and the system root have the same prefix.
1364 unsigned Pos = 0;
1365 for (; Filename[Pos] && Pos < BaseDir.size(); ++Pos)
1366 if (Filename[Pos] != BaseDir[Pos])
1367 return Filename; // Prefixes don't match.
1368
1369 // We hit the end of the filename before we hit the end of the system root.
1370 if (!Filename[Pos])
1371 return Filename;
1372
1373 // If there's not a path separator at the end of the base directory nor
1374 // immediately after it, then this isn't within the base directory.
1375 if (!llvm::sys::path::is_separator(Filename[Pos])) {
1376 if (!llvm::sys::path::is_separator(BaseDir.back()))
1377 return Filename;
1378 } else {
1379 // If the file name has a '/' at the current position, skip over the '/'.
1380 // We distinguish relative paths from absolute paths by the
1381 // absence of '/' at the beginning of relative paths.
1382 //
1383 // FIXME: This is wrong. We distinguish them by asking if the path is
1384 // absolute, which isn't the same thing. And there might be multiple '/'s
1385 // in a row. Use a better mechanism to indicate whether we have emitted an
1386 // absolute or relative path.
1387 ++Pos;
1388 }
1389
1390 return Filename + Pos;
1391}
1392
1393ASTFileSignature ASTWriter::createSignature(StringRef Bytes) {
1394 // Calculate the hash till start of UNHASHED_CONTROL_BLOCK.
1395 llvm::SHA1 Hasher;
1396 Hasher.update(ArrayRef<uint8_t>(Bytes.bytes_begin(), Bytes.size()));
1397 auto Hash = Hasher.result();
1398
1399 // Convert to an array [5*i32].
1400 ASTFileSignature Signature;
1401 auto LShift = [&](unsigned char Val, unsigned Shift) {
1402 return (uint32_t)Val << Shift;
1403 };
1404 for (int I = 0; I != 5; ++I)
1405 Signature[I] = LShift(Hash[I * 4 + 0], 24) | LShift(Hash[I * 4 + 1], 16) |
1406 LShift(Hash[I * 4 + 2], 8) | LShift(Hash[I * 4 + 3], 0);
1407
1408 return Signature;
1409}
1410
1411ASTFileSignature ASTWriter::writeUnhashedControlBlock(Preprocessor &PP,
1412 ASTContext &Context) {
1413 // Flush first to prepare the PCM hash (signature).
1414 Stream.FlushToWord();
1415 auto StartOfUnhashedControl = Stream.GetCurrentBitNo() >> 3;
1416
1417 // Enter the block and prepare to write records.
1418 RecordData Record;
1419 Stream.EnterSubblock(UNHASHED_CONTROL_BLOCK_ID, 5);
1420
1421 // For implicit modules, write the hash of the PCM as its signature.
1422 ASTFileSignature Signature;
1423 if (WritingModule &&
1424 PP.getHeaderSearchInfo().getHeaderSearchOpts().ModulesHashContent) {
1425 Signature = createSignature(StringRef(Buffer.begin(), StartOfUnhashedControl));
1426 Record.append(Signature.begin(), Signature.end());
1427 Stream.EmitRecord(SIGNATURE, Record);
1428 Record.clear();
1429 }
1430
1431 // Diagnostic options.
1432 const auto &Diags = Context.getDiagnostics();
1433 const DiagnosticOptions &DiagOpts = Diags.getDiagnosticOptions();
1434#define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name);
1435#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
1436 Record.push_back(static_cast<unsigned>(DiagOpts.get##Name()));
1437#include "clang/Basic/DiagnosticOptions.def"
1438 Record.push_back(DiagOpts.Warnings.size());
1439 for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; ++I)
1440 AddString(DiagOpts.Warnings[I], Record);
1441 Record.push_back(DiagOpts.Remarks.size());
1442 for (unsigned I = 0, N = DiagOpts.Remarks.size(); I != N; ++I)
1443 AddString(DiagOpts.Remarks[I], Record);
1444 // Note: we don't serialize the log or serialization file names, because they
1445 // are generally transient files and will almost always be overridden.
1446 Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record);
1447
1448 // Write out the diagnostic/pragma mappings.
1449 WritePragmaDiagnosticMappings(Diags, /* IsModule = */ WritingModule);
1450
1451 // Leave the options block.
1452 Stream.ExitBlock();
1453 return Signature;
1454}
1455
1456/// Write the control block.
1457void ASTWriter::WriteControlBlock(Preprocessor &PP, ASTContext &Context,
1458 StringRef isysroot,
1459 const std::string &OutputFile) {
1460 using namespace llvm;
1461
1462 Stream.EnterSubblock(CONTROL_BLOCK_ID, 5);
1463 RecordData Record;
1464
1465 // Metadata
1466 auto MetadataAbbrev = std::make_shared<BitCodeAbbrev>();
1467 MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA));
1468 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major
1469 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor
1470 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj.
1471 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min.
1472 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
1473 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Timestamps
1474 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // PCHHasObjectFile
1475 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors
1476 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
1477 unsigned MetadataAbbrevCode = Stream.EmitAbbrev(std::move(MetadataAbbrev));
1478 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 1479, __PRETTY_FUNCTION__))
1479 "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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 1479, __PRETTY_FUNCTION__))
;
1480 {
1481 RecordData::value_type Record[] = {
1482 METADATA,
1483 VERSION_MAJOR,
1484 VERSION_MINOR,
1485 CLANG_VERSION_MAJOR9,
1486 CLANG_VERSION_MINOR0,
1487 !isysroot.empty(),
1488 IncludeTimestamps,
1489 Context.getLangOpts().BuildingPCHWithObjectFile,
1490 ASTHasCompilerErrors};
1491 Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record,
1492 getClangFullRepositoryVersion());
1493 }
1494
1495 if (WritingModule) {
1496 // Module name
1497 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1498 Abbrev->Add(BitCodeAbbrevOp(MODULE_NAME));
1499 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
1500 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1501 RecordData::value_type Record[] = {MODULE_NAME};
1502 Stream.EmitRecordWithBlob(AbbrevCode, Record, WritingModule->Name);
1503 }
1504
1505 if (WritingModule && WritingModule->Directory) {
1506 SmallString<128> BaseDir(WritingModule->Directory->getName());
1507 cleanPathForOutput(Context.getSourceManager().getFileManager(), BaseDir);
1508
1509 // If the home of the module is the current working directory, then we
1510 // want to pick up the cwd of the build process loading the module, not
1511 // our cwd, when we load this module.
1512 if (!PP.getHeaderSearchInfo()
1513 .getHeaderSearchOpts()
1514 .ModuleMapFileHomeIsCwd ||
1515 WritingModule->Directory->getName() != StringRef(".")) {
1516 // Module directory.
1517 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1518 Abbrev->Add(BitCodeAbbrevOp(MODULE_DIRECTORY));
1519 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Directory
1520 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1521
1522 RecordData::value_type Record[] = {MODULE_DIRECTORY};
1523 Stream.EmitRecordWithBlob(AbbrevCode, Record, BaseDir);
1524 }
1525
1526 // Write out all other paths relative to the base directory if possible.
1527 BaseDirectory.assign(BaseDir.begin(), BaseDir.end());
1528 } else if (!isysroot.empty()) {
1529 // Write out paths relative to the sysroot if possible.
1530 BaseDirectory = isysroot;
1531 }
1532
1533 // Module map file
1534 if (WritingModule && WritingModule->Kind == Module::ModuleMapModule) {
1535 Record.clear();
1536
1537 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
1538 AddPath(WritingModule->PresumedModuleMapFile.empty()
1539 ? Map.getModuleMapFileForUniquing(WritingModule)->getName()
1540 : StringRef(WritingModule->PresumedModuleMapFile),
1541 Record);
1542
1543 // Additional module map files.
1544 if (auto *AdditionalModMaps =
1545 Map.getAdditionalModuleMapFiles(WritingModule)) {
1546 Record.push_back(AdditionalModMaps->size());
1547 for (const FileEntry *F : *AdditionalModMaps)
1548 AddPath(F->getName(), Record);
1549 } else {
1550 Record.push_back(0);
1551 }
1552
1553 Stream.EmitRecord(MODULE_MAP_FILE, Record);
1554 }
1555
1556 // Imports
1557 if (Chain) {
1558 serialization::ModuleManager &Mgr = Chain->getModuleManager();
1559 Record.clear();
1560
1561 for (ModuleFile &M : Mgr) {
1562 // Skip modules that weren't directly imported.
1563 if (!M.isDirectlyImported())
1564 continue;
1565
1566 Record.push_back((unsigned)M.Kind); // FIXME: Stable encoding
1567 AddSourceLocation(M.ImportLoc, Record);
1568
1569 // If we have calculated signature, there is no need to store
1570 // the size or timestamp.
1571 Record.push_back(M.Signature ? 0 : M.File->getSize());
1572 Record.push_back(M.Signature ? 0 : getTimestampForOutput(M.File));
1573
1574 for (auto I : M.Signature)
1575 Record.push_back(I);
1576
1577 AddString(M.ModuleName, Record);
1578 AddPath(M.FileName, Record);
1579 }
1580 Stream.EmitRecord(IMPORTS, Record);
1581 }
1582
1583 // Write the options block.
1584 Stream.EnterSubblock(OPTIONS_BLOCK_ID, 4);
1585
1586 // Language options.
1587 Record.clear();
1588 const LangOptions &LangOpts = Context.getLangOpts();
1589#define LANGOPT(Name, Bits, Default, Description) \
1590 Record.push_back(LangOpts.Name);
1591#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
1592 Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
1593#include "clang/Basic/LangOptions.def"
1594#define SANITIZER(NAME, ID) \
1595 Record.push_back(LangOpts.Sanitize.has(SanitizerKind::ID));
1596#include "clang/Basic/Sanitizers.def"
1597
1598 Record.push_back(LangOpts.ModuleFeatures.size());
1599 for (StringRef Feature : LangOpts.ModuleFeatures)
1600 AddString(Feature, Record);
1601
1602 Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind());
1603 AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record);
1604
1605 AddString(LangOpts.CurrentModule, Record);
1606
1607 // Comment options.
1608 Record.push_back(LangOpts.CommentOpts.BlockCommandNames.size());
1609 for (const auto &I : LangOpts.CommentOpts.BlockCommandNames) {
1610 AddString(I, Record);
1611 }
1612 Record.push_back(LangOpts.CommentOpts.ParseAllComments);
1613
1614 // OpenMP offloading options.
1615 Record.push_back(LangOpts.OMPTargetTriples.size());
1616 for (auto &T : LangOpts.OMPTargetTriples)
1617 AddString(T.getTriple(), Record);
1618
1619 AddString(LangOpts.OMPHostIRFile, Record);
1620
1621 Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1622
1623 // Target options.
1624 Record.clear();
1625 const TargetInfo &Target = Context.getTargetInfo();
1626 const TargetOptions &TargetOpts = Target.getTargetOpts();
1627 AddString(TargetOpts.Triple, Record);
1628 AddString(TargetOpts.CPU, Record);
1629 AddString(TargetOpts.ABI, Record);
1630 Record.push_back(TargetOpts.FeaturesAsWritten.size());
1631 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; ++I) {
1632 AddString(TargetOpts.FeaturesAsWritten[I], Record);
1633 }
1634 Record.push_back(TargetOpts.Features.size());
1635 for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; ++I) {
1636 AddString(TargetOpts.Features[I], Record);
1637 }
1638 Stream.EmitRecord(TARGET_OPTIONS, Record);
1639
1640 // File system options.
1641 Record.clear();
1642 const FileSystemOptions &FSOpts =
1643 Context.getSourceManager().getFileManager().getFileSystemOpts();
1644 AddString(FSOpts.WorkingDir, Record);
1645 Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record);
1646
1647 // Header search options.
1648 Record.clear();
1649 const HeaderSearchOptions &HSOpts
1650 = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1651 AddString(HSOpts.Sysroot, Record);
1652
1653 // Include entries.
1654 Record.push_back(HSOpts.UserEntries.size());
1655 for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; ++I) {
1656 const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I];
1657 AddString(Entry.Path, Record);
1658 Record.push_back(static_cast<unsigned>(Entry.Group));
1659 Record.push_back(Entry.IsFramework);
1660 Record.push_back(Entry.IgnoreSysRoot);
1661 }
1662
1663 // System header prefixes.
1664 Record.push_back(HSOpts.SystemHeaderPrefixes.size());
1665 for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; ++I) {
1666 AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record);
1667 Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader);
1668 }
1669
1670 AddString(HSOpts.ResourceDir, Record);
1671 AddString(HSOpts.ModuleCachePath, Record);
1672 AddString(HSOpts.ModuleUserBuildPath, Record);
1673 Record.push_back(HSOpts.DisableModuleHash);
1674 Record.push_back(HSOpts.ImplicitModuleMaps);
1675 Record.push_back(HSOpts.ModuleMapFileHomeIsCwd);
1676 Record.push_back(HSOpts.UseBuiltinIncludes);
1677 Record.push_back(HSOpts.UseStandardSystemIncludes);
1678 Record.push_back(HSOpts.UseStandardCXXIncludes);
1679 Record.push_back(HSOpts.UseLibcxx);
1680 // Write out the specific module cache path that contains the module files.
1681 AddString(PP.getHeaderSearchInfo().getModuleCachePath(), Record);
1682 Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record);
1683
1684 // Preprocessor options.
1685 Record.clear();
1686 const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts();
1687
1688 // Macro definitions.
1689 Record.push_back(PPOpts.Macros.size());
1690 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
1691 AddString(PPOpts.Macros[I].first, Record);
1692 Record.push_back(PPOpts.Macros[I].second);
1693 }
1694
1695 // Includes
1696 Record.push_back(PPOpts.Includes.size());
1697 for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I)
1698 AddString(PPOpts.Includes[I], Record);
1699
1700 // Macro includes
1701 Record.push_back(PPOpts.MacroIncludes.size());
1702 for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; ++I)
1703 AddString(PPOpts.MacroIncludes[I], Record);
1704
1705 Record.push_back(PPOpts.UsePredefines);
1706 // Detailed record is important since it is used for the module cache hash.
1707 Record.push_back(PPOpts.DetailedRecord);
1708 AddString(PPOpts.ImplicitPCHInclude, Record);
1709 Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary));
1710 Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record);
1711
1712 // Leave the options block.
1713 Stream.ExitBlock();
1714
1715 // Original file name and file ID
1716 SourceManager &SM = Context.getSourceManager();
1717 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1718 auto FileAbbrev = std::make_shared<BitCodeAbbrev>();
1719 FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE));
1720 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID
1721 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1722 unsigned FileAbbrevCode = Stream.EmitAbbrev(std::move(FileAbbrev));
1723
1724 Record.clear();
1725 Record.push_back(ORIGINAL_FILE);
1726 Record.push_back(SM.getMainFileID().getOpaqueValue());
1727 EmitRecordWithPath(FileAbbrevCode, Record, MainFile->getName());
1728 }
1729
1730 Record.clear();
1731 Record.push_back(SM.getMainFileID().getOpaqueValue());
1732 Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
1733
1734 // Original PCH directory
1735 if (!OutputFile.empty() && OutputFile != "-") {
1736 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1737 Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR));
1738 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1739 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1740
1741 SmallString<128> OutputPath(OutputFile);
1742
1743 SM.getFileManager().makeAbsolutePath(OutputPath);
1744 StringRef origDir = llvm::sys::path::parent_path(OutputPath);
1745
1746 RecordData::value_type Record[] = {ORIGINAL_PCH_DIR};
1747 Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir);
1748 }
1749
1750 WriteInputFiles(Context.SourceMgr,
1751 PP.getHeaderSearchInfo().getHeaderSearchOpts(),
1752 PP.getLangOpts().Modules);
1753 Stream.ExitBlock();
1754}
1755
1756namespace {
1757
1758/// An input file.
1759struct InputFileEntry {
1760 const FileEntry *File;
1761 bool IsSystemFile;
1762 bool IsTransient;
1763 bool BufferOverridden;
1764 bool IsTopLevelModuleMap;
1765};
1766
1767} // namespace
1768
1769void ASTWriter::WriteInputFiles(SourceManager &SourceMgr,
1770 HeaderSearchOptions &HSOpts,
1771 bool Modules) {
1772 using namespace llvm;
1773
1774 Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4);
1775
1776 // Create input-file abbreviation.
1777 auto IFAbbrev = std::make_shared<BitCodeAbbrev>();
1778 IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE));
1779 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
1780 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1781 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
1782 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden
1783 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Transient
1784 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Module map
1785 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1786 unsigned IFAbbrevCode = Stream.EmitAbbrev(std::move(IFAbbrev));
1787
1788 // Get all ContentCache objects for files, sorted by whether the file is a
1789 // system one or not. System files go at the back, users files at the front.
1790 std::deque<InputFileEntry> SortedFiles;
1791 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) {
1792 // Get this source location entry.
1793 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
1794 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 1794, __PRETTY_FUNCTION__))
;
1795
1796 // We only care about file entries that were not overridden.
1797 if (!SLoc->isFile())
1798 continue;
1799 const SrcMgr::FileInfo &File = SLoc->getFile();
1800 const SrcMgr::ContentCache *Cache = File.getContentCache();
1801 if (!Cache->OrigEntry)
1802 continue;
1803
1804 InputFileEntry Entry;
1805 Entry.File = Cache->OrigEntry;
1806 Entry.IsSystemFile = Cache->IsSystemFile;
1807 Entry.IsTransient = Cache->IsTransient;
1808 Entry.BufferOverridden = Cache->BufferOverridden;
1809 Entry.IsTopLevelModuleMap = isModuleMap(File.getFileCharacteristic()) &&
1810 File.getIncludeLoc().isInvalid();
1811 if (Cache->IsSystemFile)
1812 SortedFiles.push_back(Entry);
1813 else
1814 SortedFiles.push_front(Entry);
1815 }
1816
1817 unsigned UserFilesNum = 0;
1818 // Write out all of the input files.
1819 std::vector<uint64_t> InputFileOffsets;
1820 for (const auto &Entry : SortedFiles) {
1821 uint32_t &InputFileID = InputFileIDs[Entry.File];
1822 if (InputFileID != 0)
1823 continue; // already recorded this file.
1824
1825 // Record this entry's offset.
1826 InputFileOffsets.push_back(Stream.GetCurrentBitNo());
1827
1828 InputFileID = InputFileOffsets.size();
1829
1830 if (!Entry.IsSystemFile)
1831 ++UserFilesNum;
1832
1833 // Emit size/modification time for this file.
1834 // And whether this file was overridden.
1835 RecordData::value_type Record[] = {
1836 INPUT_FILE,
1837 InputFileOffsets.size(),
1838 (uint64_t)Entry.File->getSize(),
1839 (uint64_t)getTimestampForOutput(Entry.File),
1840 Entry.BufferOverridden,
1841 Entry.IsTransient,
1842 Entry.IsTopLevelModuleMap};
1843
1844 EmitRecordWithPath(IFAbbrevCode, Record, Entry.File->getName());
1845 }
1846
1847 Stream.ExitBlock();
1848
1849 // Create input file offsets abbreviation.
1850 auto OffsetsAbbrev = std::make_shared<BitCodeAbbrev>();
1851 OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS));
1852 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files
1853 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system
1854 // input files
1855 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Array
1856 unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(std::move(OffsetsAbbrev));
1857
1858 // Write input file offsets.
1859 RecordData::value_type Record[] = {INPUT_FILE_OFFSETS,
1860 InputFileOffsets.size(), UserFilesNum};
1861 Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, bytes(InputFileOffsets));
1862}
1863
1864//===----------------------------------------------------------------------===//
1865// Source Manager Serialization
1866//===----------------------------------------------------------------------===//
1867
1868/// Create an abbreviation for the SLocEntry that refers to a
1869/// file.
1870static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
1871 using namespace llvm;
1872
1873 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1874 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
1875 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1876 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1877 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
1878 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1879 // FileEntry fields.
1880 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID
1881 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
1882 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
1883 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
1884 return Stream.EmitAbbrev(std::move(Abbrev));
1885}
1886
1887/// Create an abbreviation for the SLocEntry that refers to a
1888/// buffer.
1889static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
1890 using namespace llvm;
1891
1892 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1893 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
1894 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1895 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1896 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
1897 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1898 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
1899 return Stream.EmitAbbrev(std::move(Abbrev));
1900}
1901
1902/// Create an abbreviation for the SLocEntry that refers to a
1903/// buffer's blob.
1904static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream,
1905 bool Compressed) {
1906 using namespace llvm;
1907
1908 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1909 Abbrev->Add(BitCodeAbbrevOp(Compressed ? SM_SLOC_BUFFER_BLOB_COMPRESSED
1910 : SM_SLOC_BUFFER_BLOB));
1911 if (Compressed)
1912 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Uncompressed size
1913 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
1914 return Stream.EmitAbbrev(std::move(Abbrev));
1915}
1916
1917/// Create an abbreviation for the SLocEntry that refers to a macro
1918/// expansion.
1919static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
1920 using namespace llvm;
1921
1922 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1923 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
1924 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1925 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1926 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
1927 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
1928 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Is token range
1929 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
1930 return Stream.EmitAbbrev(std::move(Abbrev));
1931}
1932
1933namespace {
1934
1935 // Trait used for the on-disk hash table of header search information.
1936 class HeaderFileInfoTrait {
1937 ASTWriter &Writer;
1938
1939 // Keep track of the framework names we've used during serialization.
1940 SmallVector<char, 128> FrameworkStringData;
1941 llvm::StringMap<unsigned> FrameworkNameOffset;
1942
1943 public:
1944 HeaderFileInfoTrait(ASTWriter &Writer) : Writer(Writer) {}
1945
1946 struct key_type {
1947 StringRef Filename;
1948 off_t Size;
1949 time_t ModTime;
1950 };
1951 using key_type_ref = const key_type &;
1952
1953 using UnresolvedModule =
1954 llvm::PointerIntPair<Module *, 2, ModuleMap::ModuleHeaderRole>;
1955
1956 struct data_type {
1957 const HeaderFileInfo &HFI;
1958 ArrayRef<ModuleMap::KnownHeader> KnownHeaders;
1959 UnresolvedModule Unresolved;
1960 };
1961 using data_type_ref = const data_type &;
1962
1963 using hash_value_type = unsigned;
1964 using offset_type = unsigned;
1965
1966 hash_value_type ComputeHash(key_type_ref key) {
1967 // The hash is based only on size/time of the file, so that the reader can
1968 // match even when symlinking or excess path elements ("foo/../", "../")
1969 // change the form of the name. However, complete path is still the key.
1970 return llvm::hash_combine(key.Size, key.ModTime);
1971 }
1972
1973 std::pair<unsigned, unsigned>
1974 EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) {
1975 using namespace llvm::support;
1976
1977 endian::Writer LE(Out, little);
1978 unsigned KeyLen = key.Filename.size() + 1 + 8 + 8;
1979 LE.write<uint16_t>(KeyLen);
1980 unsigned DataLen = 1 + 2 + 4 + 4;
1981 for (auto ModInfo : Data.KnownHeaders)
1982 if (Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule()))
1983 DataLen += 4;
1984 if (Data.Unresolved.getPointer())
1985 DataLen += 4;
1986 LE.write<uint8_t>(DataLen);
1987 return std::make_pair(KeyLen, DataLen);
1988 }
1989
1990 void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) {
1991 using namespace llvm::support;
1992
1993 endian::Writer LE(Out, little);
1994 LE.write<uint64_t>(key.Size);
1995 KeyLen -= 8;
1996 LE.write<uint64_t>(key.ModTime);
1997 KeyLen -= 8;
1998 Out.write(key.Filename.data(), KeyLen);
1999 }
2000
2001 void EmitData(raw_ostream &Out, key_type_ref key,
2002 data_type_ref Data, unsigned DataLen) {
2003 using namespace llvm::support;
2004
2005 endian::Writer LE(Out, little);
2006 uint64_t Start = Out.tell(); (void)Start;
2007
2008 unsigned char Flags = (Data.HFI.isImport << 5)
2009 | (Data.HFI.isPragmaOnce << 4)
2010 | (Data.HFI.DirInfo << 1)
2011 | Data.HFI.IndexHeaderMapHeader;
2012 LE.write<uint8_t>(Flags);
2013 LE.write<uint16_t>(Data.HFI.NumIncludes);
2014
2015 if (!Data.HFI.ControllingMacro)
2016 LE.write<uint32_t>(Data.HFI.ControllingMacroID);
2017 else
2018 LE.write<uint32_t>(Writer.getIdentifierRef(Data.HFI.ControllingMacro));
2019
2020 unsigned Offset = 0;
2021 if (!Data.HFI.Framework.empty()) {
2022 // If this header refers into a framework, save the framework name.
2023 llvm::StringMap<unsigned>::iterator Pos
2024 = FrameworkNameOffset.find(Data.HFI.Framework);
2025 if (Pos == FrameworkNameOffset.end()) {
2026 Offset = FrameworkStringData.size() + 1;
2027 FrameworkStringData.append(Data.HFI.Framework.begin(),
2028 Data.HFI.Framework.end());
2029 FrameworkStringData.push_back(0);
2030
2031 FrameworkNameOffset[Data.HFI.Framework] = Offset;
2032 } else
2033 Offset = Pos->second;
2034 }
2035 LE.write<uint32_t>(Offset);
2036
2037 auto EmitModule = [&](Module *M, ModuleMap::ModuleHeaderRole Role) {
2038 if (uint32_t ModID = Writer.getLocalOrImportedSubmoduleID(M)) {
2039 uint32_t Value = (ModID << 2) | (unsigned)Role;
2040 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 2040, __PRETTY_FUNCTION__))
;
2041 LE.write<uint32_t>(Value);
2042 }
2043 };
2044
2045 // FIXME: If the header is excluded, we should write out some
2046 // record of that fact.
2047 for (auto ModInfo : Data.KnownHeaders)
2048 EmitModule(ModInfo.getModule(), ModInfo.getRole());
2049 if (Data.Unresolved.getPointer())
2050 EmitModule(Data.Unresolved.getPointer(), Data.Unresolved.getInt());
2051
2052 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 2052, __PRETTY_FUNCTION__))
;
2053 }
2054
2055 const char *strings_begin() const { return FrameworkStringData.begin(); }
2056 const char *strings_end() const { return FrameworkStringData.end(); }
2057 };
2058
2059} // namespace
2060
2061/// Write the header search block for the list of files that
2062///
2063/// \param HS The header search structure to save.
2064void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS) {
2065 HeaderFileInfoTrait GeneratorTrait(*this);
2066 llvm::OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
2067 SmallVector<const char *, 4> SavedStrings;
2068 unsigned NumHeaderSearchEntries = 0;
2069
2070 // Find all unresolved headers for the current module. We generally will
2071 // have resolved them before we get here, but not necessarily: we might be
2072 // compiling a preprocessed module, where there is no requirement for the
2073 // original files to exist any more.
2074 const HeaderFileInfo Empty; // So we can take a reference.
2075 if (WritingModule) {
1
Assuming the condition is true
2
Taking true branch
2076 llvm::SmallVector<Module *, 16> Worklist(1, WritingModule);
2077 while (!Worklist.empty()) {
3
Loop condition is true. Entering loop body
2078 Module *M = Worklist.pop_back_val();
2079 if (!M->isAvailable())
4
Assuming the condition is false
5
Taking false branch
2080 continue;
2081
2082 // Map to disk files where possible, to pick up any missing stat
2083 // information. This also means we don't need to check the unresolved
2084 // headers list when emitting resolved headers in the first loop below.
2085 // FIXME: It'd be preferable to avoid doing this if we were given
2086 // sufficient stat information in the module map.
2087 HS.getModuleMap().resolveHeaderDirectives(M);
2088
2089 // If the file didn't exist, we can still create a module if we were given
2090 // enough information in the module map.
2091 for (auto U : M->MissingHeaders) {
6
Assuming '__begin3' is not equal to '__end3'
2092 // Check that we were given enough information to build a module
2093 // without this file existing on disk.
2094 if (!U.Size || (!U.ModTime && IncludeTimestamps)) {
7
Assuming the condition is false
8
Assuming the condition is false
2095 PP->Diag(U.FileNameLoc, diag::err_module_no_size_mtime_for_header)
2096 << WritingModule->getFullModuleName() << U.Size.hasValue()
2097 << U.FileName;
2098 continue;
2099 }
2100
2101 // Form the effective relative pathname for the file.
2102 SmallString<128> Filename(M->Directory->getName());
2103 llvm::sys::path::append(Filename, U.FileName);
2104 PreparePathForOutput(Filename);
2105
2106 StringRef FilenameDup = strdup(Filename.c_str());
9
Memory is allocated
10
Potential memory leak
2107 SavedStrings.push_back(FilenameDup.data());
2108
2109 HeaderFileInfoTrait::key_type Key = {
2110 FilenameDup, *U.Size, IncludeTimestamps ? *U.ModTime : 0
2111 };
2112 HeaderFileInfoTrait::data_type Data = {
2113 Empty, {}, {M, ModuleMap::headerKindToRole(U.Kind)}
2114 };
2115 // FIXME: Deal with cases where there are multiple unresolved header
2116 // directives in different submodules for the same header.
2117 Generator.insert(Key, Data, GeneratorTrait);
2118 ++NumHeaderSearchEntries;
2119 }
2120
2121 Worklist.append(M->submodule_begin(), M->submodule_end());
2122 }
2123 }
2124
2125 SmallVector<const FileEntry *, 16> FilesByUID;
2126 HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
2127
2128 if (FilesByUID.size() > HS.header_file_size())
2129 FilesByUID.resize(HS.header_file_size());
2130
2131 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
2132 const FileEntry *File = FilesByUID[UID];
2133 if (!File)
2134 continue;
2135
2136 // Get the file info. This will load info from the external source if
2137 // necessary. Skip emitting this file if we have no information on it
2138 // as a header file (in which case HFI will be null) or if it hasn't
2139 // changed since it was loaded. Also skip it if it's for a modular header
2140 // from a different module; in that case, we rely on the module(s)
2141 // containing the header to provide this information.
2142 const HeaderFileInfo *HFI =
2143 HS.getExistingFileInfo(File, /*WantExternal*/!Chain);
2144 if (!HFI || (HFI->isModuleHeader && !HFI->isCompilingModuleHeader))
2145 continue;
2146
2147 // Massage the file path into an appropriate form.
2148 StringRef Filename = File->getName();
2149 SmallString<128> FilenameTmp(Filename);
2150 if (PreparePathForOutput(FilenameTmp)) {
2151 // If we performed any translation on the file name at all, we need to
2152 // save this string, since the generator will refer to it later.
2153 Filename = StringRef(strdup(FilenameTmp.c_str()));
2154 SavedStrings.push_back(Filename.data());
2155 }
2156
2157 HeaderFileInfoTrait::key_type Key = {
2158 Filename, File->getSize(), getTimestampForOutput(File)
2159 };
2160 HeaderFileInfoTrait::data_type Data = {
2161 *HFI, HS.getModuleMap().findAllModulesForHeader(File), {}
2162 };
2163 Generator.insert(Key, Data, GeneratorTrait);
2164 ++NumHeaderSearchEntries;
2165 }
2166
2167 // Create the on-disk hash table in a buffer.
2168 SmallString<4096> TableData;
2169 uint32_t BucketOffset;
2170 {
2171 using namespace llvm::support;
2172
2173 llvm::raw_svector_ostream Out(TableData);
2174 // Make sure that no bucket is at offset 0
2175 endian::write<uint32_t>(Out, 0, little);
2176 BucketOffset = Generator.Emit(Out, GeneratorTrait);
2177 }
2178
2179 // Create a blob abbreviation
2180 using namespace llvm;
2181
2182 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2183 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
2184 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2185 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2186 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2187 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2188 unsigned TableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2189
2190 // Write the header search table
2191 RecordData::value_type Record[] = {HEADER_SEARCH_TABLE, BucketOffset,
2192 NumHeaderSearchEntries, TableData.size()};
2193 TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end());
2194 Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData);
2195
2196 // Free all of the strings we had to duplicate.
2197 for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
2198 free(const_cast<char *>(SavedStrings[I]));
2199}
2200
2201static void emitBlob(llvm::BitstreamWriter &Stream, StringRef Blob,
2202 unsigned SLocBufferBlobCompressedAbbrv,
2203 unsigned SLocBufferBlobAbbrv) {
2204 using RecordDataType = ASTWriter::RecordData::value_type;
2205
2206 // Compress the buffer if possible. We expect that almost all PCM
2207 // consumers will not want its contents.
2208 SmallString<0> CompressedBuffer;
2209 if (llvm::zlib::isAvailable()) {
2210 llvm::Error E = llvm::zlib::compress(Blob.drop_back(1), CompressedBuffer);
2211 if (!E) {
2212 RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB_COMPRESSED,
2213 Blob.size() - 1};
2214 Stream.EmitRecordWithBlob(SLocBufferBlobCompressedAbbrv, Record,
2215 CompressedBuffer);
2216 return;
2217 }
2218 llvm::consumeError(std::move(E));
2219 }
2220
2221 RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB};
2222 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, Blob);
2223}
2224
2225/// Writes the block containing the serialized form of the
2226/// source manager.
2227///
2228/// TODO: We should probably use an on-disk hash table (stored in a
2229/// blob), indexed based on the file name, so that we only create
2230/// entries for files that we actually need. In the common case (no
2231/// errors), we probably won't have to create file entries for any of
2232/// the files in the AST.
2233void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
2234 const Preprocessor &PP) {
2235 RecordData Record;
2236
2237 // Enter the source manager block.
2238 Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 4);
2239
2240 // Abbreviations for the various kinds of source-location entries.
2241 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
2242 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
2243 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream, false);
2244 unsigned SLocBufferBlobCompressedAbbrv =
2245 CreateSLocBufferBlobAbbrev(Stream, true);
2246 unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
2247
2248 // Write out the source location entry table. We skip the first
2249 // entry, which is always the same dummy entry.
2250 std::vector<uint32_t> SLocEntryOffsets;
2251 RecordData PreloadSLocs;
2252 SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
2253 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
2254 I != N; ++I) {
2255 // Get this source location entry.
2256 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
2257 FileID FID = FileID::get(I);
2258 assert(&SourceMgr.getSLocEntry(FID) == SLoc)((&SourceMgr.getSLocEntry(FID) == SLoc) ? static_cast<
void> (0) : __assert_fail ("&SourceMgr.getSLocEntry(FID) == SLoc"
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 2258, __PRETTY_FUNCTION__))
;
2259
2260 // Record the offset of this source-location entry.
2261 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
2262
2263 // Figure out which record code to use.
2264 unsigned Code;
2265 if (SLoc->isFile()) {
2266 const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
2267 if (Cache->OrigEntry) {
2268 Code = SM_SLOC_FILE_ENTRY;
2269 } else
2270 Code = SM_SLOC_BUFFER_ENTRY;
2271 } else
2272 Code = SM_SLOC_EXPANSION_ENTRY;
2273 Record.clear();
2274 Record.push_back(Code);
2275
2276 // Starting offset of this entry within this module, so skip the dummy.
2277 Record.push_back(SLoc->getOffset() - 2);
2278 if (SLoc->isFile()) {
2279 const SrcMgr::FileInfo &File = SLoc->getFile();
2280 AddSourceLocation(File.getIncludeLoc(), Record);
2281 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
2282 Record.push_back(File.hasLineDirectives());
2283
2284 const SrcMgr::ContentCache *Content = File.getContentCache();
2285 bool EmitBlob = false;
2286 if (Content->OrigEntry) {
2287 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 2288, __PRETTY_FUNCTION__))
2288 "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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 2288, __PRETTY_FUNCTION__))
;
2289
2290 // The source location entry is a file. Emit input file ID.
2291 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 2291, __PRETTY_FUNCTION__))
;
2292 Record.push_back(InputFileIDs[Content->OrigEntry]);
2293
2294 Record.push_back(File.NumCreatedFIDs);
2295
2296 FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID);
2297 if (FDI != FileDeclIDs.end()) {
2298 Record.push_back(FDI->second->FirstDeclIndex);
2299 Record.push_back(FDI->second->DeclIDs.size());
2300 } else {
2301 Record.push_back(0);
2302 Record.push_back(0);
2303 }
2304
2305 Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record);
2306
2307 if (Content->BufferOverridden || Content->IsTransient)
2308 EmitBlob = true;
2309 } else {
2310 // The source location entry is a buffer. The blob associated
2311 // with this entry contains the contents of the buffer.
2312
2313 // We add one to the size so that we capture the trailing NULL
2314 // that is required by llvm::MemoryBuffer::getMemBuffer (on
2315 // the reader side).
2316 const llvm::MemoryBuffer *Buffer
2317 = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
2318 StringRef Name = Buffer->getBufferIdentifier();
2319 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
2320 StringRef(Name.data(), Name.size() + 1));
2321 EmitBlob = true;
2322
2323 if (Name == "<built-in>")
2324 PreloadSLocs.push_back(SLocEntryOffsets.size());
2325 }
2326
2327 if (EmitBlob) {
2328 // Include the implicit terminating null character in the on-disk buffer
2329 // if we're writing it uncompressed.
2330 const llvm::MemoryBuffer *Buffer =
2331 Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
2332 StringRef Blob(Buffer->getBufferStart(), Buffer->getBufferSize() + 1);
2333 emitBlob(Stream, Blob, SLocBufferBlobCompressedAbbrv,
2334 SLocBufferBlobAbbrv);
2335 }
2336 } else {
2337 // The source location entry is a macro expansion.
2338 const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
2339 AddSourceLocation(Expansion.getSpellingLoc(), Record);
2340 AddSourceLocation(Expansion.getExpansionLocStart(), Record);
2341 AddSourceLocation(Expansion.isMacroArgExpansion()
2342 ? SourceLocation()
2343 : Expansion.getExpansionLocEnd(),
2344 Record);
2345 Record.push_back(Expansion.isExpansionTokenRange());
2346
2347 // Compute the token length for this macro expansion.
2348 unsigned NextOffset = SourceMgr.getNextLocalOffset();
2349 if (I + 1 != N)
2350 NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
2351 Record.push_back(NextOffset - SLoc->getOffset() - 1);
2352 Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
2353 }
2354 }
2355
2356 Stream.ExitBlock();
2357
2358 if (SLocEntryOffsets.empty())
2359 return;
2360
2361 // Write the source-location offsets table into the AST block. This
2362 // table is used for lazily loading source-location information.
2363 using namespace llvm;
2364
2365 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2366 Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
2367 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
2368 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
2369 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
2370 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2371 {
2372 RecordData::value_type Record[] = {
2373 SOURCE_LOCATION_OFFSETS, SLocEntryOffsets.size(),
2374 SourceMgr.getNextLocalOffset() - 1 /* skip dummy */};
2375 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
2376 bytes(SLocEntryOffsets));
2377 }
2378 // Write the source location entry preloads array, telling the AST
2379 // reader which source locations entries it should load eagerly.
2380 Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
2381
2382 // Write the line table. It depends on remapping working, so it must come
2383 // after the source location offsets.
2384 if (SourceMgr.hasLineTable()) {
2385 LineTableInfo &LineTable = SourceMgr.getLineTable();
2386
2387 Record.clear();
2388
2389 // Emit the needed file names.
2390 llvm::DenseMap<int, int> FilenameMap;
2391 FilenameMap[-1] = -1; // For unspecified filenames.
2392 for (const auto &L : LineTable) {
2393 if (L.first.ID < 0)
2394 continue;
2395 for (auto &LE : L.second) {
2396 if (FilenameMap.insert(std::make_pair(LE.FilenameID,
2397 FilenameMap.size() - 1)).second)
2398 AddPath(LineTable.getFilename(LE.FilenameID), Record);
2399 }
2400 }
2401 Record.push_back(0);
2402
2403 // Emit the line entries
2404 for (const auto &L : LineTable) {
2405 // Only emit entries for local files.
2406 if (L.first.ID < 0)
2407 continue;
2408
2409 // Emit the file ID
2410 Record.push_back(L.first.ID);
2411
2412 // Emit the line entries
2413 Record.push_back(L.second.size());
2414 for (const auto &LE : L.second) {
2415 Record.push_back(LE.FileOffset);
2416 Record.push_back(LE.LineNo);
2417 Record.push_back(FilenameMap[LE.FilenameID]);
2418 Record.push_back((unsigned)LE.FileKind);
2419 Record.push_back(LE.IncludeOffset);
2420 }
2421 }
2422
2423 Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
2424 }
2425}
2426
2427//===----------------------------------------------------------------------===//
2428// Preprocessor Serialization
2429//===----------------------------------------------------------------------===//
2430
2431static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule,
2432 const Preprocessor &PP) {
2433 if (MacroInfo *MI = MD->getMacroInfo())
2434 if (MI->isBuiltinMacro())
2435 return true;
2436
2437 if (IsModule) {
2438 SourceLocation Loc = MD->getLocation();
2439 if (Loc.isInvalid())
2440 return true;
2441 if (PP.getSourceManager().getFileID(Loc) == PP.getPredefinesFileID())
2442 return true;
2443 }
2444
2445 return false;
2446}
2447
2448/// Writes the block containing the serialized form of the
2449/// preprocessor.
2450void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
2451 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
2452 if (PPRec)
2453 WritePreprocessorDetail(*PPRec);
2454
2455 RecordData Record;
2456 RecordData ModuleMacroRecord;
2457
2458 // If the preprocessor __COUNTER__ value has been bumped, remember it.
2459 if (PP.getCounterValue() != 0) {
2460 RecordData::value_type Record[] = {PP.getCounterValue()};
2461 Stream.EmitRecord(PP_COUNTER_VALUE, Record);
2462 }
2463
2464 if (PP.isRecordingPreamble() && PP.hasRecordedPreamble()) {
2465 assert(!IsModule)((!IsModule) ? static_cast<void> (0) : __assert_fail ("!IsModule"
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 2465, __PRETTY_FUNCTION__))
;
2466 auto SkipInfo = PP.getPreambleSkipInfo();
2467 if (SkipInfo.hasValue()) {
2468 Record.push_back(true);
2469 AddSourceLocation(SkipInfo->HashTokenLoc, Record);
2470 AddSourceLocation(SkipInfo->IfTokenLoc, Record);
2471 Record.push_back(SkipInfo->FoundNonSkipPortion);
2472 Record.push_back(SkipInfo->FoundElse);
2473 AddSourceLocation(SkipInfo->ElseLoc, Record);
2474 } else {
2475 Record.push_back(false);
2476 }
2477 for (const auto &Cond : PP.getPreambleConditionalStack()) {
2478 AddSourceLocation(Cond.IfLoc, Record);
2479 Record.push_back(Cond.WasSkipping);
2480 Record.push_back(Cond.FoundNonSkip);
2481 Record.push_back(Cond.FoundElse);
2482 }
2483 Stream.EmitRecord(PP_CONDITIONAL_STACK, Record);
2484 Record.clear();
2485 }
2486
2487 // Enter the preprocessor block.
2488 Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
2489
2490 // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
2491 // FIXME: Include a location for the use, and say which one was used.
2492 if (PP.SawDateOrTime())
2493 PP.Diag(SourceLocation(), diag::warn_module_uses_date_time) << IsModule;
2494
2495 // Loop over all the macro directives that are live at the end of the file,
2496 // emitting each to the PP section.
2497
2498 // Construct the list of identifiers with macro directives that need to be
2499 // serialized.
2500 SmallVector<const IdentifierInfo *, 128> MacroIdentifiers;
2501 for (auto &Id : PP.getIdentifierTable())
2502 if (Id.second->hadMacroDefinition() &&
2503 (!Id.second->isFromAST() ||
2504 Id.second->hasChangedSinceDeserialization()))
2505 MacroIdentifiers.push_back(Id.second);
2506 // Sort the set of macro definitions that need to be serialized by the
2507 // name of the macro, to provide a stable ordering.
2508 llvm::sort(MacroIdentifiers, llvm::less_ptr<IdentifierInfo>());
2509
2510 // Emit the macro directives as a list and associate the offset with the
2511 // identifier they belong to.
2512 for (const IdentifierInfo *Name : MacroIdentifiers) {
2513 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(Name);
2514 auto StartOffset = Stream.GetCurrentBitNo();
2515
2516 // Emit the macro directives in reverse source order.
2517 for (; MD; MD = MD->getPrevious()) {
2518 // Once we hit an ignored macro, we're done: the rest of the chain
2519 // will all be ignored macros.
2520 if (shouldIgnoreMacro(MD, IsModule, PP))
2521 break;
2522
2523 AddSourceLocation(MD->getLocation(), Record);
2524 Record.push_back(MD->getKind());
2525 if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) {
2526 Record.push_back(getMacroRef(DefMD->getInfo(), Name));
2527 } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
2528 Record.push_back(VisMD->isPublic());
2529 }
2530 }
2531
2532 // Write out any exported module macros.
2533 bool EmittedModuleMacros = false;
2534 // We write out exported module macros for PCH as well.
2535 auto Leafs = PP.getLeafModuleMacros(Name);
2536 SmallVector<ModuleMacro*, 8> Worklist(Leafs.begin(), Leafs.end());
2537 llvm::DenseMap<ModuleMacro*, unsigned> Visits;
2538 while (!Worklist.empty()) {
2539 auto *Macro = Worklist.pop_back_val();
2540
2541 // Emit a record indicating this submodule exports this macro.
2542 ModuleMacroRecord.push_back(
2543 getSubmoduleID(Macro->getOwningModule()));
2544 ModuleMacroRecord.push_back(getMacroRef(Macro->getMacroInfo(), Name));
2545 for (auto *M : Macro->overrides())
2546 ModuleMacroRecord.push_back(getSubmoduleID(M->getOwningModule()));
2547
2548 Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord);
2549 ModuleMacroRecord.clear();
2550
2551 // Enqueue overridden macros once we've visited all their ancestors.
2552 for (auto *M : Macro->overrides())
2553 if (++Visits[M] == M->getNumOverridingMacros())
2554 Worklist.push_back(M);
2555
2556 EmittedModuleMacros = true;
2557 }
2558
2559 if (Record.empty() && !EmittedModuleMacros)
2560 continue;
2561
2562 IdentMacroDirectivesOffsetMap[Name] = StartOffset;
2563 Stream.EmitRecord(PP_MACRO_DIRECTIVE_HISTORY, Record);
2564 Record.clear();
2565 }
2566
2567 /// Offsets of each of the macros into the bitstream, indexed by
2568 /// the local macro ID
2569 ///
2570 /// For each identifier that is associated with a macro, this map
2571 /// provides the offset into the bitstream where that macro is
2572 /// defined.
2573 std::vector<uint32_t> MacroOffsets;
2574
2575 for (unsigned I = 0, N = MacroInfosToEmit.size(); I != N; ++I) {
2576 const IdentifierInfo *Name = MacroInfosToEmit[I].Name;
2577 MacroInfo *MI = MacroInfosToEmit[I].MI;
2578 MacroID ID = MacroInfosToEmit[I].ID;
2579
2580 if (ID < FirstMacroID) {
2581 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 2581, __PRETTY_FUNCTION__))
;
2582 continue;
2583 }
2584
2585 // Record the local offset of this macro.
2586 unsigned Index = ID - FirstMacroID;
2587 if (Index == MacroOffsets.size())
2588 MacroOffsets.push_back(Stream.GetCurrentBitNo());
2589 else {
2590 if (Index > MacroOffsets.size())
2591 MacroOffsets.resize(Index + 1);
2592
2593 MacroOffsets[Index] = Stream.GetCurrentBitNo();
2594 }
2595
2596 AddIdentifierRef(Name, Record);
2597 AddSourceLocation(MI->getDefinitionLoc(), Record);
2598 AddSourceLocation(MI->getDefinitionEndLoc(), Record);
2599 Record.push_back(MI->isUsed());
2600 Record.push_back(MI->isUsedForHeaderGuard());
2601 unsigned Code;
2602 if (MI->isObjectLike()) {
2603 Code = PP_MACRO_OBJECT_LIKE;
2604 } else {
2605 Code = PP_MACRO_FUNCTION_LIKE;
2606
2607 Record.push_back(MI->isC99Varargs());
2608 Record.push_back(MI->isGNUVarargs());
2609 Record.push_back(MI->hasCommaPasting());
2610 Record.push_back(MI->getNumParams());
2611 for (const IdentifierInfo *Param : MI->params())
2612 AddIdentifierRef(Param, Record);
2613 }
2614
2615 // If we have a detailed preprocessing record, record the macro definition
2616 // ID that corresponds to this macro.
2617 if (PPRec)
2618 Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
2619
2620 Stream.EmitRecord(Code, Record);
2621 Record.clear();
2622
2623 // Emit the tokens array.
2624 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
2625 // Note that we know that the preprocessor does not have any annotation
2626 // tokens in it because they are created by the parser, and thus can't
2627 // be in a macro definition.
2628 const Token &Tok = MI->getReplacementToken(TokNo);
2629 AddToken(Tok, Record);
2630 Stream.EmitRecord(PP_TOKEN, Record);
2631 Record.clear();
2632 }
2633 ++NumMacros;
2634 }
2635
2636 Stream.ExitBlock();
2637
2638 // Write the offsets table for macro IDs.
2639 using namespace llvm;
2640
2641 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2642 Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET));
2643 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros
2644 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
2645 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2646
2647 unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2648 {
2649 RecordData::value_type Record[] = {MACRO_OFFSET, MacroOffsets.size(),
2650 FirstMacroID - NUM_PREDEF_MACRO_IDS};
2651 Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record, bytes(MacroOffsets));
2652 }
2653}
2654
2655void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) {
2656 if (PPRec.local_begin() == PPRec.local_end())
2657 return;
2658
2659 SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
2660
2661 // Enter the preprocessor block.
2662 Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
2663
2664 // If the preprocessor has a preprocessing record, emit it.
2665 unsigned NumPreprocessingRecords = 0;
2666 using namespace llvm;
2667
2668 // Set up the abbreviation for
2669 unsigned InclusionAbbrev = 0;
2670 {
2671 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2672 Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
2673 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
2674 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
2675 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
2676 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module
2677 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2678 InclusionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2679 }
2680
2681 unsigned FirstPreprocessorEntityID
2682 = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0)
2683 + NUM_PREDEF_PP_ENTITY_IDS;
2684 unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
2685 RecordData Record;
2686 for (PreprocessingRecord::iterator E = PPRec.local_begin(),
2687 EEnd = PPRec.local_end();
2688 E != EEnd;
2689 (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
2690 Record.clear();
2691
2692 PreprocessedEntityOffsets.push_back(
2693 PPEntityOffset((*E)->getSourceRange(), Stream.GetCurrentBitNo()));
2694
2695 if (auto *MD = dyn_cast<MacroDefinitionRecord>(*E)) {
2696 // Record this macro definition's ID.
2697 MacroDefinitions[MD] = NextPreprocessorEntityID;
2698
2699 AddIdentifierRef(MD->getName(), Record);
2700 Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
2701 continue;
2702 }
2703
2704 if (auto *ME = dyn_cast<MacroExpansion>(*E)) {
2705 Record.push_back(ME->isBuiltinMacro());
2706 if (ME->isBuiltinMacro())
2707 AddIdentifierRef(ME->getName(), Record);
2708 else
2709 Record.push_back(MacroDefinitions[ME->getDefinition()]);
2710 Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
2711 continue;
2712 }
2713
2714 if (auto *ID = dyn_cast<InclusionDirective>(*E)) {
2715 Record.push_back(PPD_INCLUSION_DIRECTIVE);
2716 Record.push_back(ID->getFileName().size());
2717 Record.push_back(ID->wasInQuotes());
2718 Record.push_back(static_cast<unsigned>(ID->getKind()));
2719 Record.push_back(ID->importedModule());
2720 SmallString<64> Buffer;
2721 Buffer += ID->getFileName();
2722 // Check that the FileEntry is not null because it was not resolved and
2723 // we create a PCH even with compiler errors.
2724 if (ID->getFile())
2725 Buffer += ID->getFile()->getName();
2726 Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
2727 continue;
2728 }
2729
2730 llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter")::llvm::llvm_unreachable_internal("Unhandled PreprocessedEntity in ASTWriter"
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 2730)
;
2731 }
2732 Stream.ExitBlock();
2733
2734 // Write the offsets table for the preprocessing record.
2735 if (NumPreprocessingRecords > 0) {
2736 assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords)((PreprocessedEntityOffsets.size() == NumPreprocessingRecords
) ? static_cast<void> (0) : __assert_fail ("PreprocessedEntityOffsets.size() == NumPreprocessingRecords"
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 2736, __PRETTY_FUNCTION__))
;
2737
2738 // Write the offsets table for identifier IDs.
2739 using namespace llvm;
2740
2741 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2742 Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
2743 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
2744 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2745 unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2746
2747 RecordData::value_type Record[] = {PPD_ENTITIES_OFFSETS,
2748 FirstPreprocessorEntityID -
2749 NUM_PREDEF_PP_ENTITY_IDS};
2750 Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
2751 bytes(PreprocessedEntityOffsets));
2752 }
2753
2754 // Write the skipped region table for the preprocessing record.
2755 ArrayRef<SourceRange> SkippedRanges = PPRec.getSkippedRanges();
2756 if (SkippedRanges.size() > 0) {
2757 std::vector<PPSkippedRange> SerializedSkippedRanges;
2758 SerializedSkippedRanges.reserve(SkippedRanges.size());
2759 for (auto const& Range : SkippedRanges)
2760 SerializedSkippedRanges.emplace_back(Range);
2761
2762 using namespace llvm;
2763 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2764 Abbrev->Add(BitCodeAbbrevOp(PPD_SKIPPED_RANGES));
2765 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2766 unsigned PPESkippedRangeAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2767
2768 Record.clear();
2769 Record.push_back(PPD_SKIPPED_RANGES);
2770 Stream.EmitRecordWithBlob(PPESkippedRangeAbbrev, Record,
2771 bytes(SerializedSkippedRanges));
2772 }
2773}
2774
2775unsigned ASTWriter::getLocalOrImportedSubmoduleID(Module *Mod) {
2776 if (!Mod)
2777 return 0;
2778
2779 llvm::DenseMap<Module *, unsigned>::iterator Known = SubmoduleIDs.find(Mod);
2780 if (Known != SubmoduleIDs.end())
2781 return Known->second;
2782
2783 auto *Top = Mod->getTopLevelModule();
2784 if (Top != WritingModule &&
2785 (getLangOpts().CompilingPCH ||
2786 !Top->fullModuleNameIs(StringRef(getLangOpts().CurrentModule))))
2787 return 0;
2788
2789 return SubmoduleIDs[Mod] = NextSubmoduleID++;
2790}
2791
2792unsigned ASTWriter::getSubmoduleID(Module *Mod) {
2793 // FIXME: This can easily happen, if we have a reference to a submodule that
2794 // did not result in us loading a module file for that submodule. For
2795 // instance, a cross-top-level-module 'conflict' declaration will hit this.
2796 unsigned ID = getLocalOrImportedSubmoduleID(Mod);
2797 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 2798, __PRETTY_FUNCTION__))
2798 "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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 2798, __PRETTY_FUNCTION__))
;
2799 return ID;
2800}
2801
2802/// Compute the number of modules within the given tree (including the
2803/// given module).
2804static unsigned getNumberOfModules(Module *Mod) {
2805 unsigned ChildModules = 0;
2806 for (auto Sub = Mod->submodule_begin(), SubEnd = Mod->submodule_end();
2807 Sub != SubEnd; ++Sub)
2808 ChildModules += getNumberOfModules(*Sub);
2809
2810 return ChildModules + 1;
2811}
2812
2813void ASTWriter::WriteSubmodules(Module *WritingModule) {
2814 // Enter the submodule description block.
2815 Stream.EnterSubblock(SUBMODULE_BLOCK_ID, /*bits for abbreviations*/5);
2816
2817 // Write the abbreviations needed for the submodules block.
2818 using namespace llvm;
2819
2820 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2821 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
2822 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
2823 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
2824 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Kind
2825 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2826 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
2827 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem
2828 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExternC
2829 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules...
2830 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
2831 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
2832 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ConfigMacrosExh...
2833 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ModuleMapIsPriv...
2834 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2835 unsigned DefinitionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2836
2837 Abbrev = std::make_shared<BitCodeAbbrev>();
2838 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
2839 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2840 unsigned UmbrellaAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2841
2842 Abbrev = std::make_shared<BitCodeAbbrev>();
2843 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
2844 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2845 unsigned HeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2846
2847 Abbrev = std::make_shared<BitCodeAbbrev>();
2848 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TOPHEADER));
2849 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2850 unsigned TopHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2851
2852 Abbrev = std::make_shared<BitCodeAbbrev>();
2853 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
2854 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2855 unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2856
2857 Abbrev = std::make_shared<BitCodeAbbrev>();
2858 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES));
2859 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // State
2860 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Feature
2861 unsigned RequiresAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2862
2863 Abbrev = std::make_shared<BitCodeAbbrev>();
2864 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXCLUDED_HEADER));
2865 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2866 unsigned ExcludedHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2867
2868 Abbrev = std::make_shared<BitCodeAbbrev>();
2869 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TEXTUAL_HEADER));
2870 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2871 unsigned TextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2872
2873 Abbrev = std::make_shared<BitCodeAbbrev>();
2874 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_HEADER));
2875 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2876 unsigned PrivateHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2877
2878 Abbrev = std::make_shared<BitCodeAbbrev>();
2879 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_TEXTUAL_HEADER));
2880 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2881 unsigned PrivateTextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2882
2883 Abbrev = std::make_shared<BitCodeAbbrev>();
2884 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_LINK_LIBRARY));
2885 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2886 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2887 unsigned LinkLibraryAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2888
2889 Abbrev = std::make_shared<BitCodeAbbrev>();
2890 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFIG_MACRO));
2891 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
2892 unsigned ConfigMacroAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2893
2894 Abbrev = std::make_shared<BitCodeAbbrev>();
2895 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFLICT));
2896 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Other module
2897 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Message
2898 unsigned ConflictAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2899
2900 Abbrev = std::make_shared<BitCodeAbbrev>();
2901 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXPORT_AS));
2902 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
2903 unsigned ExportAsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2904
2905 // Write the submodule metadata block.
2906 RecordData::value_type Record[] = {
2907 getNumberOfModules(WritingModule),
2908 FirstSubmoduleID - NUM_PREDEF_SUBMODULE_IDS};
2909 Stream.EmitRecord(SUBMODULE_METADATA, Record);
2910
2911 // Write all of the submodules.
2912 std::queue<Module *> Q;
2913 Q.push(WritingModule);
2914 while (!Q.empty()) {
2915 Module *Mod = Q.front();
2916 Q.pop();
2917 unsigned ID = getSubmoduleID(Mod);
2918
2919 uint64_t ParentID = 0;
2920 if (Mod->Parent) {
2921 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 2921, __PRETTY_FUNCTION__))
;
2922 ParentID = SubmoduleIDs[Mod->Parent];
2923 }
2924
2925 // Emit the definition of the block.
2926 {
2927 RecordData::value_type Record[] = {SUBMODULE_DEFINITION,
2928 ID,
2929 ParentID,
2930 (RecordData::value_type)Mod->Kind,
2931 Mod->IsFramework,
2932 Mod->IsExplicit,
2933 Mod->IsSystem,
2934 Mod->IsExternC,
2935 Mod->InferSubmodules,
2936 Mod->InferExplicitSubmodules,
2937 Mod->InferExportWildcard,
2938 Mod->ConfigMacrosExhaustive,
2939 Mod->ModuleMapIsPrivate};
2940 Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
2941 }
2942
2943 // Emit the requirements.
2944 for (const auto &R : Mod->Requirements) {
2945 RecordData::value_type Record[] = {SUBMODULE_REQUIRES, R.second};
2946 Stream.EmitRecordWithBlob(RequiresAbbrev, Record, R.first);
2947 }
2948
2949 // Emit the umbrella header, if there is one.
2950 if (auto UmbrellaHeader = Mod->getUmbrellaHeader()) {
2951 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_HEADER};
2952 Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
2953 UmbrellaHeader.NameAsWritten);
2954 } else if (auto UmbrellaDir = Mod->getUmbrellaDir()) {
2955 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_DIR};
2956 Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,
2957 UmbrellaDir.NameAsWritten);
2958 }
2959
2960 // Emit the headers.
2961 struct {
2962 unsigned RecordKind;
2963 unsigned Abbrev;
2964 Module::HeaderKind HeaderKind;
2965 } HeaderLists[] = {
2966 {SUBMODULE_HEADER, HeaderAbbrev, Module::HK_Normal},
2967 {SUBMODULE_TEXTUAL_HEADER, TextualHeaderAbbrev, Module::HK_Textual},
2968 {SUBMODULE_PRIVATE_HEADER, PrivateHeaderAbbrev, Module::HK_Private},
2969 {SUBMODULE_PRIVATE_TEXTUAL_HEADER, PrivateTextualHeaderAbbrev,
2970 Module::HK_PrivateTextual},
2971 {SUBMODULE_EXCLUDED_HEADER, ExcludedHeaderAbbrev, Module::HK_Excluded}
2972 };
2973 for (auto &HL : HeaderLists) {
2974 RecordData::value_type Record[] = {HL.RecordKind};
2975 for (auto &H : Mod->Headers[HL.HeaderKind])
2976 Stream.EmitRecordWithBlob(HL.Abbrev, Record, H.NameAsWritten);
2977 }
2978
2979 // Emit the top headers.
2980 {
2981 auto TopHeaders = Mod->getTopHeaders(PP->getFileManager());
2982 RecordData::value_type Record[] = {SUBMODULE_TOPHEADER};
2983 for (auto *H : TopHeaders)
2984 Stream.EmitRecordWithBlob(TopHeaderAbbrev, Record, H->getName());
2985 }
2986
2987 // Emit the imports.
2988 if (!Mod->Imports.empty()) {
2989 RecordData Record;
2990 for (auto *I : Mod->Imports)
2991 Record.push_back(getSubmoduleID(I));
2992 Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
2993 }
2994
2995 // Emit the exports.
2996 if (!Mod->Exports.empty()) {
2997 RecordData Record;
2998 for (const auto &E : Mod->Exports) {
2999 // FIXME: This may fail; we don't require that all exported modules
3000 // are local or imported.
3001 Record.push_back(getSubmoduleID(E.getPointer()));
3002 Record.push_back(E.getInt());
3003 }
3004 Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
3005 }
3006
3007 //FIXME: How do we emit the 'use'd modules? They may not be submodules.
3008 // Might be unnecessary as use declarations are only used to build the
3009 // module itself.
3010
3011 // Emit the link libraries.
3012 for (const auto &LL : Mod->LinkLibraries) {
3013 RecordData::value_type Record[] = {SUBMODULE_LINK_LIBRARY,
3014 LL.IsFramework};
3015 Stream.EmitRecordWithBlob(LinkLibraryAbbrev, Record, LL.Library);
3016 }
3017
3018 // Emit the conflicts.
3019 for (const auto &C : Mod->Conflicts) {
3020 // FIXME: This may fail; we don't require that all conflicting modules
3021 // are local or imported.
3022 RecordData::value_type Record[] = {SUBMODULE_CONFLICT,
3023 getSubmoduleID(C.Other)};
3024 Stream.EmitRecordWithBlob(ConflictAbbrev, Record, C.Message);
3025 }
3026
3027 // Emit the configuration macros.
3028 for (const auto &CM : Mod->ConfigMacros) {
3029 RecordData::value_type Record[] = {SUBMODULE_CONFIG_MACRO};
3030 Stream.EmitRecordWithBlob(ConfigMacroAbbrev, Record, CM);
3031 }
3032
3033 // Emit the initializers, if any.
3034 RecordData Inits;
3035 for (Decl *D : Context->getModuleInitializers(Mod))
3036 Inits.push_back(GetDeclRef(D));
3037 if (!Inits.empty())
3038 Stream.EmitRecord(SUBMODULE_INITIALIZERS, Inits);
3039
3040 // Emit the name of the re-exported module, if any.
3041 if (!Mod->ExportAsModule.empty()) {
3042 RecordData::value_type Record[] = {SUBMODULE_EXPORT_AS};
3043 Stream.EmitRecordWithBlob(ExportAsAbbrev, Record, Mod->ExportAsModule);
3044 }
3045
3046 // Queue up the submodules of this module.
3047 for (auto *M : Mod->submodules())
3048 Q.push(M);
3049 }
3050
3051 Stream.ExitBlock();
3052
3053 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 3056, __PRETTY_FUNCTION__))
3054 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 3056, __PRETTY_FUNCTION__))
3055 "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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 3056, __PRETTY_FUNCTION__))
3056 "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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 3056, __PRETTY_FUNCTION__))
;
3057}
3058
3059void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
3060 bool isModule) {
3061 llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64>
3062 DiagStateIDMap;
3063 unsigned CurrID = 0;
3064 RecordData Record;
3065
3066 auto EncodeDiagStateFlags =
3067 [](const DiagnosticsEngine::DiagState *DS) -> unsigned {
3068 unsigned Result = (unsigned)DS->ExtBehavior;
3069 for (unsigned Val :
3070 {(unsigned)DS->IgnoreAllWarnings, (unsigned)DS->EnableAllWarnings,
3071 (unsigned)DS->WarningsAsErrors, (unsigned)DS->ErrorsAsFatal,
3072 (unsigned)DS->SuppressSystemWarnings})
3073 Result = (Result << 1) | Val;
3074 return Result;
3075 };
3076
3077 unsigned Flags = EncodeDiagStateFlags(Diag.DiagStatesByLoc.FirstDiagState);
3078 Record.push_back(Flags);
3079
3080 auto AddDiagState = [&](const DiagnosticsEngine::DiagState *State,
3081 bool IncludeNonPragmaStates) {
3082 // Ensure that the diagnostic state wasn't modified since it was created.
3083 // We will not correctly round-trip this information otherwise.
3084 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 3085, __PRETTY_FUNCTION__))
3085 "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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 3085, __PRETTY_FUNCTION__))
;
3086
3087 unsigned &DiagStateID = DiagStateIDMap[State];
3088 Record.push_back(DiagStateID);
3089
3090 if (DiagStateID == 0) {
3091 DiagStateID = ++CurrID;
3092
3093 // Add a placeholder for the number of mappings.
3094 auto SizeIdx = Record.size();
3095 Record.emplace_back();
3096 for (const auto &I : *State) {
3097 if (I.second.isPragma() || IncludeNonPragmaStates) {
3098 Record.push_back(I.first);
3099 Record.push_back(I.second.serialize());
3100 }
3101 }
3102 // Update the placeholder.
3103 Record[SizeIdx] = (Record.size() - SizeIdx) / 2;
3104 }
3105 };
3106
3107 AddDiagState(Diag.DiagStatesByLoc.FirstDiagState, isModule);
3108
3109 // Reserve a spot for the number of locations with state transitions.
3110 auto NumLocationsIdx = Record.size();
3111 Record.emplace_back();
3112
3113 // Emit the state transitions.
3114 unsigned NumLocations = 0;
3115 for (auto &FileIDAndFile : Diag.DiagStatesByLoc.Files) {
3116 if (!FileIDAndFile.first.isValid() ||
3117 !FileIDAndFile.second.HasLocalTransitions)
3118 continue;
3119 ++NumLocations;
3120
3121 SourceLocation Loc = Diag.SourceMgr->getComposedLoc(FileIDAndFile.first, 0);
3122 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 3122, __PRETTY_FUNCTION__))
;
3123 AddSourceLocation(Loc, Record);
3124
3125 Record.push_back(FileIDAndFile.second.StateTransitions.size());
3126 for (auto &StatePoint : FileIDAndFile.second.StateTransitions) {
3127 Record.push_back(StatePoint.Offset);
3128 AddDiagState(StatePoint.State, false);
3129 }
3130 }
3131
3132 // Backpatch the number of locations.
3133 Record[NumLocationsIdx] = NumLocations;
3134
3135 // Emit CurDiagStateLoc. Do it last in order to match source order.
3136 //
3137 // This also protects against a hypothetical corner case with simulating
3138 // -Werror settings for implicit modules in the ASTReader, where reading
3139 // CurDiagState out of context could change whether warning pragmas are
3140 // treated as errors.
3141 AddSourceLocation(Diag.DiagStatesByLoc.CurDiagStateLoc, Record);
3142 AddDiagState(Diag.DiagStatesByLoc.CurDiagState, false);
3143
3144 Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
3145}
3146
3147//===----------------------------------------------------------------------===//
3148// Type Serialization
3149//===----------------------------------------------------------------------===//
3150
3151/// Write the representation of a type to the AST stream.
3152void ASTWriter::WriteType(QualType T) {
3153 TypeIdx &IdxRef = TypeIdxs[T];
3154 if (IdxRef.getIndex() == 0) // we haven't seen this type before.
3155 IdxRef = TypeIdx(NextTypeID++);
3156 TypeIdx Idx = IdxRef;
3157
3158 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 3158, __PRETTY_FUNCTION__))
;
3159
3160 RecordData Record;
3161
3162 // Emit the type's representation.
3163 ASTTypeWriter W(*this, Record);
3164 W.Visit(T);
3165 uint64_t Offset = W.Emit();
3166
3167 // Record the offset for this type.
3168 unsigned Index = Idx.getIndex() - FirstTypeID;
3169 if (TypeOffsets.size() == Index)
3170 TypeOffsets.push_back(Offset);
3171 else if (TypeOffsets.size() < Index) {
3172 TypeOffsets.resize(Index + 1);
3173 TypeOffsets[Index] = Offset;
3174 } else {
3175 llvm_unreachable("Types emitted in wrong order")::llvm::llvm_unreachable_internal("Types emitted in wrong order"
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 3175)
;
3176 }
3177}
3178
3179//===----------------------------------------------------------------------===//
3180// Declaration Serialization
3181//===----------------------------------------------------------------------===//
3182
3183/// Write the block containing all of the declaration IDs
3184/// lexically declared within the given DeclContext.
3185///
3186/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
3187/// bitstream, or 0 if no block was written.
3188uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
3189 DeclContext *DC) {
3190 if (DC->decls_empty())
3191 return 0;
3192
3193 uint64_t Offset = Stream.GetCurrentBitNo();
3194 SmallVector<uint32_t, 128> KindDeclPairs;
3195 for (const auto *D : DC->decls()) {
3196 KindDeclPairs.push_back(D->getKind());
3197 KindDeclPairs.push_back(GetDeclRef(D));
3198 }
3199
3200 ++NumLexicalDeclContexts;
3201 RecordData::value_type Record[] = {DECL_CONTEXT_LEXICAL};
3202 Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record,
3203 bytes(KindDeclPairs));
3204 return Offset;
3205}
3206
3207void ASTWriter::WriteTypeDeclOffsets() {
3208 using namespace llvm;
3209
3210 // Write the type offsets array
3211 auto Abbrev = std::make_shared<BitCodeAbbrev>();
3212 Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
3213 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
3214 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index
3215 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
3216 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3217 {
3218 RecordData::value_type Record[] = {TYPE_OFFSET, TypeOffsets.size(),
3219 FirstTypeID - NUM_PREDEF_TYPE_IDS};
3220 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, bytes(TypeOffsets));
3221 }
3222
3223 // Write the declaration offsets array
3224 Abbrev = std::make_shared<BitCodeAbbrev>();
3225 Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
3226 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
3227 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID
3228 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
3229 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3230 {
3231 RecordData::value_type Record[] = {DECL_OFFSET, DeclOffsets.size(),
3232 FirstDeclID - NUM_PREDEF_DECL_IDS};
3233 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, bytes(DeclOffsets));
3234 }
3235}
3236
3237void ASTWriter::WriteFileDeclIDsMap() {
3238 using namespace llvm;
3239
3240 SmallVector<std::pair<FileID, DeclIDInFileInfo *>, 64> SortedFileDeclIDs(
3241 FileDeclIDs.begin(), FileDeclIDs.end());
3242 llvm::sort(SortedFileDeclIDs, llvm::less_first());
3243
3244 // Join the vectors of DeclIDs from all files.
3245 SmallVector<DeclID, 256> FileGroupedDeclIDs;
3246 for (auto &FileDeclEntry : SortedFileDeclIDs) {
3247 DeclIDInFileInfo &Info = *FileDeclEntry.second;
3248 Info.FirstDeclIndex = FileGroupedDeclIDs.size();
3249 for (auto &LocDeclEntry : Info.DeclIDs)
3250 FileGroupedDeclIDs.push_back(LocDeclEntry.second);
3251 }
3252
3253 auto Abbrev = std::make_shared<BitCodeAbbrev>();
3254 Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
3255 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3256 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3257 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
3258 RecordData::value_type Record[] = {FILE_SORTED_DECLS,
3259 FileGroupedDeclIDs.size()};
3260 Stream.EmitRecordWithBlob(AbbrevCode, Record, bytes(FileGroupedDeclIDs));
3261}
3262
3263void ASTWriter::WriteComments() {
3264 Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
3265 auto _ = llvm::make_scope_exit([this] { Stream.ExitBlock(); });
3266 if (!PP->getPreprocessorOpts().WriteCommentListToPCH)
3267 return;
3268 ArrayRef<RawComment *> RawComments = Context->Comments.getComments();
3269 RecordData Record;
3270 for (const auto *I : RawComments) {
3271 Record.clear();
3272 AddSourceRange(I->getSourceRange(), Record);
3273 Record.push_back(I->getKind());
3274 Record.push_back(I->isTrailingComment());
3275 Record.push_back(I->isAlmostTrailingComment());
3276 Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
3277 }
3278}
3279
3280//===----------------------------------------------------------------------===//
3281// Global Method Pool and Selector Serialization
3282//===----------------------------------------------------------------------===//
3283
3284namespace {
3285
3286// Trait used for the on-disk hash table used in the method pool.
3287class ASTMethodPoolTrait {
3288 ASTWriter &Writer;
3289
3290public:
3291 using key_type = Selector;
3292 using key_type_ref = key_type;
3293
3294 struct data_type {
3295 SelectorID ID;
3296 ObjCMethodList Instance, Factory;
3297 };
3298 using data_type_ref = const data_type &;
3299
3300 using hash_value_type = unsigned;
3301 using offset_type = unsigned;
3302
3303 explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) {}
3304
3305 static hash_value_type ComputeHash(Selector Sel) {
3306 return serialization::ComputeHash(Sel);
3307 }
3308
3309 std::pair<unsigned, unsigned>
3310 EmitKeyDataLength(raw_ostream& Out, Selector Sel,
3311 data_type_ref Methods) {
3312 using namespace llvm::support;
3313
3314 endian::Writer LE(Out, little);
3315 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
3316 LE.write<uint16_t>(KeyLen);
3317 unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
3318 for (const ObjCMethodList *Method = &Methods.Instance; Method;
3319 Method = Method->getNext())
3320 if (Method->getMethod())
3321 DataLen += 4;
3322 for (const ObjCMethodList *Method = &Methods.Factory; Method;
3323 Method = Method->getNext())
3324 if (Method->getMethod())
3325 DataLen += 4;
3326 LE.write<uint16_t>(DataLen);
3327 return std::make_pair(KeyLen, DataLen);
3328 }
3329
3330 void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
3331 using namespace llvm::support;
3332
3333 endian::Writer LE(Out, little);
3334 uint64_t Start = Out.tell();
3335 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 3335, __PRETTY_FUNCTION__))
;
3336 Writer.SetSelectorOffset(Sel, Start);
3337 unsigned N = Sel.getNumArgs();
3338 LE.write<uint16_t>(N);
3339 if (N == 0)
3340 N = 1;
3341 for (unsigned I = 0; I != N; ++I)
3342 LE.write<uint32_t>(
3343 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
3344 }
3345
3346 void EmitData(raw_ostream& Out, key_type_ref,
3347 data_type_ref Methods, unsigned DataLen) {
3348 using namespace llvm::support;
3349
3350 endian::Writer LE(Out, little);
3351 uint64_t Start = Out.tell(); (void)Start;
3352 LE.write<uint32_t>(Methods.ID);
3353 unsigned NumInstanceMethods = 0;
3354 for (const ObjCMethodList *Method = &Methods.Instance; Method;
3355 Method = Method->getNext())
3356 if (Method->getMethod())
3357 ++NumInstanceMethods;
3358
3359 unsigned NumFactoryMethods = 0;
3360 for (const ObjCMethodList *Method = &Methods.Factory; Method;
3361 Method = Method->getNext())
3362 if (Method->getMethod())
3363 ++NumFactoryMethods;
3364
3365 unsigned InstanceBits = Methods.Instance.getBits();
3366 assert(InstanceBits < 4)((InstanceBits < 4) ? static_cast<void> (0) : __assert_fail
("InstanceBits < 4", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 3366, __PRETTY_FUNCTION__))
;
3367 unsigned InstanceHasMoreThanOneDeclBit =
3368 Methods.Instance.hasMoreThanOneDecl();
3369 unsigned FullInstanceBits = (NumInstanceMethods << 3) |
3370 (InstanceHasMoreThanOneDeclBit << 2) |
3371 InstanceBits;
3372 unsigned FactoryBits = Methods.Factory.getBits();
3373 assert(FactoryBits < 4)((FactoryBits < 4) ? static_cast<void> (0) : __assert_fail
("FactoryBits < 4", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 3373, __PRETTY_FUNCTION__))
;
3374 unsigned FactoryHasMoreThanOneDeclBit =
3375 Methods.Factory.hasMoreThanOneDecl();
3376 unsigned FullFactoryBits = (NumFactoryMethods << 3) |
3377 (FactoryHasMoreThanOneDeclBit << 2) |
3378 FactoryBits;
3379 LE.write<uint16_t>(FullInstanceBits);
3380 LE.write<uint16_t>(FullFactoryBits);
3381 for (const ObjCMethodList *Method = &Methods.Instance; Method;
3382 Method = Method->getNext())
3383 if (Method->getMethod())
3384 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
3385 for (const ObjCMethodList *Method = &Methods.Factory; Method;
3386 Method = Method->getNext())
3387 if (Method->getMethod())
3388 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
3389
3390 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 3390, __PRETTY_FUNCTION__))
;
3391 }
3392};
3393
3394} // namespace
3395
3396/// Write ObjC data: selectors and the method pool.
3397///
3398/// The method pool contains both instance and factory methods, stored
3399/// in an on-disk hash table indexed by the selector. The hash table also
3400/// contains an empty entry for every other selector known to Sema.
3401void ASTWriter::WriteSelectors(Sema &SemaRef) {
3402 using namespace llvm;
3403
3404 // Do we have to do anything at all?
3405 if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
3406 return;
3407 unsigned NumTableEntries = 0;
3408 // Create and write out the blob that contains selectors and the method pool.
3409 {
3410 llvm::OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
3411 ASTMethodPoolTrait Trait(*this);
3412
3413 // Create the on-disk hash table representation. We walk through every
3414 // selector we've seen and look it up in the method pool.
3415 SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
3416 for (auto &SelectorAndID : SelectorIDs) {
3417 Selector S = SelectorAndID.first;
3418 SelectorID ID = SelectorAndID.second;
3419 Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
3420 ASTMethodPoolTrait::data_type Data = {
3421 ID,
3422 ObjCMethodList(),
3423 ObjCMethodList()
3424 };
3425 if (F != SemaRef.MethodPool.end()) {
3426 Data.Instance = F->second.first;
3427 Data.Factory = F->second.second;
3428 }
3429 // Only write this selector if it's not in an existing AST or something
3430 // changed.
3431 if (Chain && ID < FirstSelectorID) {
3432 // Selector already exists. Did it change?
3433 bool changed = false;
3434 for (ObjCMethodList *M = &Data.Instance;
3435 !changed && M && M->getMethod(); M = M->getNext()) {
3436 if (!M->getMethod()->isFromASTFile())
3437 changed = true;
3438 }
3439 for (ObjCMethodList *M = &Data.Factory; !changed && M && M->getMethod();
3440 M = M->getNext()) {
3441 if (!M->getMethod()->isFromASTFile())
3442 changed = true;
3443 }
3444 if (!changed)
3445 continue;
3446 } else if (Data.Instance.getMethod() || Data.Factory.getMethod()) {
3447 // A new method pool entry.
3448 ++NumTableEntries;
3449 }
3450 Generator.insert(S, Data, Trait);
3451 }
3452
3453 // Create the on-disk hash table in a buffer.
3454 SmallString<4096> MethodPool;
3455 uint32_t BucketOffset;
3456 {
3457 using namespace llvm::support;
3458
3459 ASTMethodPoolTrait Trait(*this);
3460 llvm::raw_svector_ostream Out(MethodPool);
3461 // Make sure that no bucket is at offset 0
3462 endian::write<uint32_t>(Out, 0, little);
3463 BucketOffset = Generator.Emit(Out, Trait);
3464 }
3465
3466 // Create a blob abbreviation
3467 auto Abbrev = std::make_shared<BitCodeAbbrev>();
3468 Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
3469 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3470 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3471 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3472 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3473
3474 // Write the method pool
3475 {
3476 RecordData::value_type Record[] = {METHOD_POOL, BucketOffset,
3477 NumTableEntries};
3478 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool);
3479 }
3480
3481 // Create a blob abbreviation for the selector table offsets.
3482 Abbrev = std::make_shared<BitCodeAbbrev>();
3483 Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
3484 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
3485 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
3486 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3487 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3488
3489 // Write the selector offsets table.
3490 {
3491 RecordData::value_type Record[] = {
3492 SELECTOR_OFFSETS, SelectorOffsets.size(),
3493 FirstSelectorID - NUM_PREDEF_SELECTOR_IDS};
3494 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
3495 bytes(SelectorOffsets));
3496 }
3497 }
3498}
3499
3500/// Write the selectors referenced in @selector expression into AST file.
3501void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
3502 using namespace llvm;
3503
3504 if (SemaRef.ReferencedSelectors.empty())
3505 return;
3506
3507 RecordData Record;
3508 ASTRecordWriter Writer(*this, Record);
3509
3510 // Note: this writes out all references even for a dependent AST. But it is
3511 // very tricky to fix, and given that @selector shouldn't really appear in
3512 // headers, probably not worth it. It's not a correctness issue.
3513 for (auto &SelectorAndLocation : SemaRef.ReferencedSelectors) {
3514 Selector Sel = SelectorAndLocation.first;
3515 SourceLocation Loc = SelectorAndLocation.second;
3516 Writer.AddSelectorRef(Sel);
3517 Writer.AddSourceLocation(Loc);
3518 }
3519 Writer.Emit(REFERENCED_SELECTOR_POOL);
3520}
3521
3522//===----------------------------------------------------------------------===//
3523// Identifier Table Serialization
3524//===----------------------------------------------------------------------===//
3525
3526/// Determine the declaration that should be put into the name lookup table to
3527/// represent the given declaration in this module. This is usually D itself,
3528/// but if D was imported and merged into a local declaration, we want the most
3529/// recent local declaration instead. The chosen declaration will be the most
3530/// recent declaration in any module that imports this one.
3531static NamedDecl *getDeclForLocalLookup(const LangOptions &LangOpts,
3532 NamedDecl *D) {
3533 if (!LangOpts.Modules || !D->isFromASTFile())
3534 return D;
3535
3536 if (Decl *Redecl = D->getPreviousDecl()) {
3537 // For Redeclarable decls, a prior declaration might be local.
3538 for (; Redecl; Redecl = Redecl->getPreviousDecl()) {
3539 // If we find a local decl, we're done.
3540 if (!Redecl->isFromASTFile()) {
3541 // Exception: in very rare cases (for injected-class-names), not all
3542 // redeclarations are in the same semantic context. Skip ones in a
3543 // different context. They don't go in this lookup table at all.
3544 if (!Redecl->getDeclContext()->getRedeclContext()->Equals(
3545 D->getDeclContext()->getRedeclContext()))
3546 continue;
3547 return cast<NamedDecl>(Redecl);
3548 }
3549
3550 // If we find a decl from a (chained-)PCH stop since we won't find a
3551 // local one.
3552 if (Redecl->getOwningModuleID() == 0)
3553 break;
3554 }
3555 } else if (Decl *First = D->getCanonicalDecl()) {
3556 // For Mergeable decls, the first decl might be local.
3557 if (!First->isFromASTFile())
3558 return cast<NamedDecl>(First);
3559 }
3560
3561 // All declarations are imported. Our most recent declaration will also be
3562 // the most recent one in anyone who imports us.
3563 return D;
3564}
3565
3566namespace {
3567
3568class ASTIdentifierTableTrait {
3569 ASTWriter &Writer;
3570 Preprocessor &PP;
3571 IdentifierResolver &IdResolver;
3572 bool IsModule;
3573 bool NeedDecls;
3574 ASTWriter::RecordData *InterestingIdentifierOffsets;
3575
3576 /// Determines whether this is an "interesting" identifier that needs a
3577 /// full IdentifierInfo structure written into the hash table. Notably, this
3578 /// doesn't check whether the name has macros defined; use PublicMacroIterator
3579 /// to check that.
3580 bool isInterestingIdentifier(const IdentifierInfo *II, uint64_t MacroOffset) {
3581 if (MacroOffset ||
3582 II->isPoisoned() ||
3583 (IsModule ? II->hasRevertedBuiltin() : II->getObjCOrBuiltinID()) ||
3584 II->hasRevertedTokenIDToIdentifier() ||
3585 (NeedDecls && II->getFETokenInfo()))
3586 return true;
3587
3588 return false;
3589 }
3590
3591public:
3592 using key_type = IdentifierInfo *;
3593 using key_type_ref = key_type;
3594
3595 using data_type = IdentID;
3596 using data_type_ref = data_type;
3597
3598 using hash_value_type = unsigned;
3599 using offset_type = unsigned;
3600
3601 ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
3602 IdentifierResolver &IdResolver, bool IsModule,
3603 ASTWriter::RecordData *InterestingIdentifierOffsets)
3604 : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule),
3605 NeedDecls(!IsModule || !Writer.getLangOpts().CPlusPlus),
3606 InterestingIdentifierOffsets(InterestingIdentifierOffsets) {}
3607
3608 bool needDecls() const { return NeedDecls; }
3609
3610 static hash_value_type ComputeHash(const IdentifierInfo* II) {
3611 return llvm::djbHash(II->getName());
3612 }
3613
3614 bool isInterestingIdentifier(const IdentifierInfo *II) {
3615 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3616 return isInterestingIdentifier(II, MacroOffset);
3617 }
3618
3619 bool isInterestingNonMacroIdentifier(const IdentifierInfo *II) {
3620 return isInterestingIdentifier(II, 0);
3621 }
3622
3623 std::pair<unsigned, unsigned>
3624 EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
3625 unsigned KeyLen = II->getLength() + 1;
3626 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
3627 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3628 if (isInterestingIdentifier(II, MacroOffset)) {
3629 DataLen += 2; // 2 bytes for builtin ID
3630 DataLen += 2; // 2 bytes for flags
3631 if (MacroOffset)
3632 DataLen += 4; // MacroDirectives offset.
3633
3634 if (NeedDecls) {
3635 for (IdentifierResolver::iterator D = IdResolver.begin(II),
3636 DEnd = IdResolver.end();
3637 D != DEnd; ++D)
3638 DataLen += 4;
3639 }
3640 }
3641
3642 using namespace llvm::support;
3643
3644 endian::Writer LE(Out, little);
3645
3646 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 3646, __PRETTY_FUNCTION__))
;
3647 LE.write<uint16_t>(DataLen);
3648 // We emit the key length after the data length so that every
3649 // string is preceded by a 16-bit length. This matches the PTH
3650 // format for storing identifiers.
3651 LE.write<uint16_t>(KeyLen);
3652 return std::make_pair(KeyLen, DataLen);
3653 }
3654
3655 void EmitKey(raw_ostream& Out, const IdentifierInfo* II,
3656 unsigned KeyLen) {
3657 // Record the location of the key data. This is used when generating
3658 // the mapping from persistent IDs to strings.
3659 Writer.SetIdentifierOffset(II, Out.tell());
3660
3661 // Emit the offset of the key/data length information to the interesting
3662 // identifiers table if necessary.
3663 if (InterestingIdentifierOffsets && isInterestingIdentifier(II))
3664 InterestingIdentifierOffsets->push_back(Out.tell() - 4);
3665
3666 Out.write(II->getNameStart(), KeyLen);
3667 }
3668
3669 void EmitData(raw_ostream& Out, IdentifierInfo* II,
3670 IdentID ID, unsigned) {
3671 using namespace llvm::support;
3672
3673 endian::Writer LE(Out, little);
3674
3675 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3676 if (!isInterestingIdentifier(II, MacroOffset)) {
3677 LE.write<uint32_t>(ID << 1);
3678 return;
3679 }
3680
3681 LE.write<uint32_t>((ID << 1) | 0x01);
3682 uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID();
3683 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 3683, __PRETTY_FUNCTION__))
;
3684 LE.write<uint16_t>(Bits);
3685 Bits = 0;
3686 bool HadMacroDefinition = MacroOffset != 0;
3687 Bits = (Bits << 1) | unsigned(HadMacroDefinition);
3688 Bits = (Bits << 1) | unsigned(II->isExtensionToken());
3689 Bits = (Bits << 1) | unsigned(II->isPoisoned());
3690 Bits = (Bits << 1) | unsigned(II->hasRevertedBuiltin());
3691 Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
3692 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
3693 LE.write<uint16_t>(Bits);
3694
3695 if (HadMacroDefinition)
3696 LE.write<uint32_t>(MacroOffset);
3697
3698 if (NeedDecls) {
3699 // Emit the declaration IDs in reverse order, because the
3700 // IdentifierResolver provides the declarations as they would be
3701 // visible (e.g., the function "stat" would come before the struct
3702 // "stat"), but the ASTReader adds declarations to the end of the list
3703 // (so we need to see the struct "stat" before the function "stat").
3704 // Only emit declarations that aren't from a chained PCH, though.
3705 SmallVector<NamedDecl *, 16> Decls(IdResolver.begin(II),
3706 IdResolver.end());
3707 for (SmallVectorImpl<NamedDecl *>::reverse_iterator D = Decls.rbegin(),
3708 DEnd = Decls.rend();
3709 D != DEnd; ++D)
3710 LE.write<uint32_t>(
3711 Writer.getDeclID(getDeclForLocalLookup(PP.getLangOpts(), *D)));
3712 }
3713 }
3714};
3715
3716} // namespace
3717
3718/// Write the identifier table into the AST file.
3719///
3720/// The identifier table consists of a blob containing string data
3721/// (the actual identifiers themselves) and a separate "offsets" index
3722/// that maps identifier IDs to locations within the blob.
3723void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
3724 IdentifierResolver &IdResolver,
3725 bool IsModule) {
3726 using namespace llvm;
3727
3728 RecordData InterestingIdents;
3729
3730 // Create and write out the blob that contains the identifier
3731 // strings.
3732 {
3733 llvm::OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
3734 ASTIdentifierTableTrait Trait(
3735 *this, PP, IdResolver, IsModule,
3736 (getLangOpts().CPlusPlus && IsModule) ? &InterestingIdents : nullptr);
3737
3738 // Look for any identifiers that were named while processing the
3739 // headers, but are otherwise not needed. We add these to the hash
3740 // table to enable checking of the predefines buffer in the case
3741 // where the user adds new macro definitions when building the AST
3742 // file.
3743 SmallVector<const IdentifierInfo *, 128> IIs;
3744 for (const auto &ID : PP.getIdentifierTable())
3745 IIs.push_back(ID.second);
3746 // Sort the identifiers lexicographically before getting them references so
3747 // that their order is stable.
3748 llvm::sort(IIs, llvm::less_ptr<IdentifierInfo>());
3749 for (const IdentifierInfo *II : IIs)
3750 if (Trait.isInterestingNonMacroIdentifier(II))
3751 getIdentifierRef(II);
3752
3753 // Create the on-disk hash table representation. We only store offsets
3754 // for identifiers that appear here for the first time.
3755 IdentifierOffsets.resize(NextIdentID - FirstIdentID);
3756 for (auto IdentIDPair : IdentifierIDs) {
3757 auto *II = const_cast<IdentifierInfo *>(IdentIDPair.first);
3758 IdentID ID = IdentIDPair.second;
3759 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 3759, __PRETTY_FUNCTION__))
;
3760 // Write out identifiers if either the ID is local or the identifier has
3761 // changed since it was loaded.
3762 if (ID >= FirstIdentID || !Chain || !II->isFromAST()
3763 || II->hasChangedSinceDeserialization() ||
3764 (Trait.needDecls() &&
3765 II->hasFETokenInfoChangedSinceDeserialization()))
3766 Generator.insert(II, ID, Trait);
3767 }
3768
3769 // Create the on-disk hash table in a buffer.
3770 SmallString<4096> IdentifierTable;
3771 uint32_t BucketOffset;
3772 {
3773 using namespace llvm::support;
3774
3775 llvm::raw_svector_ostream Out(IdentifierTable);
3776 // Make sure that no bucket is at offset 0
3777 endian::write<uint32_t>(Out, 0, little);
3778 BucketOffset = Generator.Emit(Out, Trait);
3779 }
3780
3781 // Create a blob abbreviation
3782 auto Abbrev = std::make_shared<BitCodeAbbrev>();
3783 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
3784 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3785 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3786 unsigned IDTableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3787
3788 // Write the identifier table
3789 RecordData::value_type Record[] = {IDENTIFIER_TABLE, BucketOffset};
3790 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable);
3791 }
3792
3793 // Write the offsets table for identifier IDs.
3794 auto Abbrev = std::make_shared<BitCodeAbbrev>();
3795 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
3796 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
3797 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
3798 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3799 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3800
3801#ifndef NDEBUG
3802 for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I)
3803 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 3803, __PRETTY_FUNCTION__))
;
3804#endif
3805
3806 RecordData::value_type Record[] = {IDENTIFIER_OFFSET,
3807 IdentifierOffsets.size(),
3808 FirstIdentID - NUM_PREDEF_IDENT_IDS};
3809 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
3810 bytes(IdentifierOffsets));
3811
3812 // In C++, write the list of interesting identifiers (those that are
3813 // defined as macros, poisoned, or similar unusual things).
3814 if (!InterestingIdents.empty())
3815 Stream.EmitRecord(INTERESTING_IDENTIFIERS, InterestingIdents);
3816}
3817
3818//===----------------------------------------------------------------------===//
3819// DeclContext's Name Lookup Table Serialization
3820//===----------------------------------------------------------------------===//
3821
3822namespace {
3823
3824// Trait used for the on-disk hash table used in the method pool.
3825class ASTDeclContextNameLookupTrait {
3826 ASTWriter &Writer;
3827 llvm::SmallVector<DeclID, 64> DeclIDs;
3828
3829public:
3830 using key_type = DeclarationNameKey;
3831 using key_type_ref = key_type;
3832
3833 /// A start and end index into DeclIDs, representing a sequence of decls.
3834 using data_type = std::pair<unsigned, unsigned>;
3835 using data_type_ref = const data_type &;
3836
3837 using hash_value_type = unsigned;
3838 using offset_type = unsigned;
3839
3840 explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) {}
3841
3842 template<typename Coll>
3843 data_type getData(const Coll &Decls) {
3844 unsigned Start = DeclIDs.size();
3845 for (NamedDecl *D : Decls) {
3846 DeclIDs.push_back(
3847 Writer.GetDeclRef(getDeclForLocalLookup(Writer.getLangOpts(), D)));
3848 }
3849 return std::make_pair(Start, DeclIDs.size());
3850 }
3851
3852 data_type ImportData(const reader::ASTDeclContextNameLookupTrait::data_type &FromReader) {
3853 unsigned Start = DeclIDs.size();
3854 for (auto ID : FromReader)
3855 DeclIDs.push_back(ID);
3856 return std::make_pair(Start, DeclIDs.size());
3857 }
3858
3859 static bool EqualKey(key_type_ref a, key_type_ref b) {
3860 return a == b;
3861 }
3862
3863 hash_value_type ComputeHash(DeclarationNameKey Name) {
3864 return Name.getHash();
3865 }
3866
3867 void EmitFileRef(raw_ostream &Out, ModuleFile *F) const {
3868 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 3869, __PRETTY_FUNCTION__))
3869 "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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 3869, __PRETTY_FUNCTION__))
;
3870
3871 using namespace llvm::support;
3872
3873 endian::write<uint32_t>(Out, Writer.getChain()->getModuleFileID(F), little);
3874 }
3875
3876 std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &Out,
3877 DeclarationNameKey Name,
3878 data_type_ref Lookup) {
3879 using namespace llvm::support;
3880
3881 endian::Writer LE(Out, little);
3882 unsigned KeyLen = 1;
3883 switch (Name.getKind()) {
3884 case DeclarationName::Identifier:
3885 case DeclarationName::ObjCZeroArgSelector:
3886 case DeclarationName::ObjCOneArgSelector:
3887 case DeclarationName::ObjCMultiArgSelector:
3888 case DeclarationName::CXXLiteralOperatorName:
3889 case DeclarationName::CXXDeductionGuideName:
3890 KeyLen += 4;
3891 break;
3892 case DeclarationName::CXXOperatorName:
3893 KeyLen += 1;
3894 break;
3895 case DeclarationName::CXXConstructorName:
3896 case DeclarationName::CXXDestructorName:
3897 case DeclarationName::CXXConversionFunctionName:
3898 case DeclarationName::CXXUsingDirective:
3899 break;
3900 }
3901 LE.write<uint16_t>(KeyLen);
3902
3903 // 4 bytes for each DeclID.
3904 unsigned DataLen = 4 * (Lookup.second - Lookup.first);
3905 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 3906, __PRETTY_FUNCTION__))
3906 "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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 3906, __PRETTY_FUNCTION__))
;
3907 LE.write<uint16_t>(DataLen);
3908
3909 return std::make_pair(KeyLen, DataLen);
3910 }
3911
3912 void EmitKey(raw_ostream &Out, DeclarationNameKey Name, unsigned) {
3913 using namespace llvm::support;
3914
3915 endian::Writer LE(Out, little);
3916 LE.write<uint8_t>(Name.getKind());
3917 switch (Name.getKind()) {
3918 case DeclarationName::Identifier:
3919 case DeclarationName::CXXLiteralOperatorName:
3920 case DeclarationName::CXXDeductionGuideName:
3921 LE.write<uint32_t>(Writer.getIdentifierRef(Name.getIdentifier()));
3922 return;
3923 case DeclarationName::ObjCZeroArgSelector:
3924 case DeclarationName::ObjCOneArgSelector:
3925 case DeclarationName::ObjCMultiArgSelector:
3926 LE.write<uint32_t>(Writer.getSelectorRef(Name.getSelector()));
3927 return;
3928 case DeclarationName::CXXOperatorName:
3929 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 3930, __PRETTY_FUNCTION__))
3930 "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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 3930, __PRETTY_FUNCTION__))
;
3931 LE.write<uint8_t>(Name.getOperatorKind());
3932 return;
3933 case DeclarationName::CXXConstructorName:
3934 case DeclarationName::CXXDestructorName:
3935 case DeclarationName::CXXConversionFunctionName:
3936 case DeclarationName::CXXUsingDirective:
3937 return;
3938 }
3939
3940 llvm_unreachable("Invalid name kind?")::llvm::llvm_unreachable_internal("Invalid name kind?", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 3940)
;
3941 }
3942
3943 void EmitData(raw_ostream &Out, key_type_ref, data_type Lookup,
3944 unsigned DataLen) {
3945 using namespace llvm::support;
3946
3947 endian::Writer LE(Out, little);
3948 uint64_t Start = Out.tell(); (void)Start;
3949 for (unsigned I = Lookup.first, N = Lookup.second; I != N; ++I)
3950 LE.write<uint32_t>(DeclIDs[I]);
3951 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 3951, __PRETTY_FUNCTION__))
;
3952 }
3953};
3954
3955} // namespace
3956
3957bool ASTWriter::isLookupResultExternal(StoredDeclsList &Result,
3958 DeclContext *DC) {
3959 return Result.hasExternalDecls() &&
3960 DC->hasNeedToReconcileExternalVisibleStorage();
3961}
3962
3963bool ASTWriter::isLookupResultEntirelyExternal(StoredDeclsList &Result,
3964 DeclContext *DC) {
3965 for (auto *D : Result.getLookupResult())
3966 if (!getDeclForLocalLookup(getLangOpts(), D)->isFromASTFile())
3967 return false;
3968
3969 return true;
3970}
3971
3972void
3973ASTWriter::GenerateNameLookupTable(const DeclContext *ConstDC,
3974 llvm::SmallVectorImpl<char> &LookupTable) {
3975 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 3977, __PRETTY_FUNCTION__))
3976 !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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 3977, __PRETTY_FUNCTION__))
3977 "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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 3977, __PRETTY_FUNCTION__))
;
3978
3979 // FIXME: We need to build the lookups table, which is logically const.
3980 auto *DC = const_cast<DeclContext*>(ConstDC);
3981 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 3981, __PRETTY_FUNCTION__))
;
3982
3983 // Create the on-disk hash table representation.
3984 MultiOnDiskHashTableGenerator<reader::ASTDeclContextNameLookupTrait,
3985 ASTDeclContextNameLookupTrait> Generator;
3986 ASTDeclContextNameLookupTrait Trait(*this);
3987
3988 // The first step is to collect the declaration names which we need to
3989 // serialize into the name lookup table, and to collect them in a stable
3990 // order.
3991 SmallVector<DeclarationName, 16> Names;
3992
3993 // We also build up small sets of the constructor and conversion function
3994 // names which are visible.
3995 llvm::SmallSet<DeclarationName, 8> ConstructorNameSet, ConversionNameSet;
3996
3997 for (auto &Lookup : *DC->buildLookup()) {
3998 auto &Name = Lookup.first;
3999 auto &Result = Lookup.second;
4000
4001 // If there are no local declarations in our lookup result, we
4002 // don't need to write an entry for the name at all. If we can't
4003 // write out a lookup set without performing more deserialization,
4004 // just skip this entry.
4005 if (isLookupResultExternal(Result, DC) &&
4006 isLookupResultEntirelyExternal(Result, DC))
4007 continue;
4008
4009 // We also skip empty results. If any of the results could be external and
4010 // the currently available results are empty, then all of the results are
4011 // external and we skip it above. So the only way we get here with an empty
4012 // results is when no results could have been external *and* we have
4013 // external results.
4014 //
4015 // FIXME: While we might want to start emitting on-disk entries for negative
4016 // lookups into a decl context as an optimization, today we *have* to skip
4017 // them because there are names with empty lookup results in decl contexts
4018 // which we can't emit in any stable ordering: we lookup constructors and
4019 // conversion functions in the enclosing namespace scope creating empty
4020 // results for them. This in almost certainly a bug in Clang's name lookup,
4021 // but that is likely to be hard or impossible to fix and so we tolerate it
4022 // here by omitting lookups with empty results.
4023 if (Lookup.second.getLookupResult().empty())
4024 continue;
4025
4026 switch (Lookup.first.getNameKind()) {
4027 default:
4028 Names.push_back(Lookup.first);
4029 break;
4030
4031 case DeclarationName::CXXConstructorName:
4032 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 4033, __PRETTY_FUNCTION__))
4033 "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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 4033, __PRETTY_FUNCTION__))
;
4034 ConstructorNameSet.insert(Name);
4035 break;
4036
4037 case DeclarationName::CXXConversionFunctionName:
4038 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 4039, __PRETTY_FUNCTION__))
4039 "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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 4039, __PRETTY_FUNCTION__))
;
4040 ConversionNameSet.insert(Name);
4041 break;
4042 }
4043 }
4044
4045 // Sort the names into a stable order.
4046 llvm::sort(Names);
4047
4048 if (auto *D = dyn_cast<CXXRecordDecl>(DC)) {
4049 // We need to establish an ordering of constructor and conversion function
4050 // names, and they don't have an intrinsic ordering.
4051
4052 // First we try the easy case by forming the current context's constructor
4053 // name and adding that name first. This is a very useful optimization to
4054 // avoid walking the lexical declarations in many cases, and it also
4055 // handles the only case where a constructor name can come from some other
4056 // lexical context -- when that name is an implicit constructor merged from
4057 // another declaration in the redecl chain. Any non-implicit constructor or
4058 // conversion function which doesn't occur in all the lexical contexts
4059 // would be an ODR violation.
4060 auto ImplicitCtorName = Context->DeclarationNames.getCXXConstructorName(
4061 Context->getCanonicalType(Context->getRecordType(D)));
4062 if (ConstructorNameSet.erase(ImplicitCtorName))
4063 Names.push_back(ImplicitCtorName);
4064
4065 // If we still have constructors or conversion functions, we walk all the
4066 // names in the decl and add the constructors and conversion functions
4067 // which are visible in the order they lexically occur within the context.
4068 if (!ConstructorNameSet.empty() || !ConversionNameSet.empty())
4069 for (Decl *ChildD : cast<CXXRecordDecl>(DC)->decls())
4070 if (auto *ChildND = dyn_cast<NamedDecl>(ChildD)) {
4071 auto Name = ChildND->getDeclName();
4072 switch (Name.getNameKind()) {
4073 default:
4074 continue;
4075
4076 case DeclarationName::CXXConstructorName:
4077 if (ConstructorNameSet.erase(Name))
4078 Names.push_back(Name);
4079 break;
4080
4081 case DeclarationName::CXXConversionFunctionName:
4082 if (ConversionNameSet.erase(Name))
4083 Names.push_back(Name);
4084 break;
4085 }
4086
4087 if (ConstructorNameSet.empty() && ConversionNameSet.empty())
4088 break;
4089 }
4090
4091 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 4093, __PRETTY_FUNCTION__))
4092 "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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 4093, __PRETTY_FUNCTION__))
4093 "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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 4093, __PRETTY_FUNCTION__))
;
4094 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 4096, __PRETTY_FUNCTION__))
4095 "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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 4096, __PRETTY_FUNCTION__))
4096 "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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 4096, __PRETTY_FUNCTION__))
;
4097 }
4098
4099 // Next we need to do a lookup with each name into this decl context to fully
4100 // populate any results from external sources. We don't actually use the
4101 // results of these lookups because we only want to use the results after all
4102 // results have been loaded and the pointers into them will be stable.
4103 for (auto &Name : Names)
4104 DC->lookup(Name);
4105
4106 // Now we need to insert the results for each name into the hash table. For
4107 // constructor names and conversion function names, we actually need to merge
4108 // all of the results for them into one list of results each and insert
4109 // those.
4110 SmallVector<NamedDecl *, 8> ConstructorDecls;
4111 SmallVector<NamedDecl *, 8> ConversionDecls;
4112
4113 // Now loop over the names, either inserting them or appending for the two
4114 // special cases.
4115 for (auto &Name : Names) {
4116 DeclContext::lookup_result Result = DC->noload_lookup(Name);
4117
4118 switch (Name.getNameKind()) {
4119 default:
4120 Generator.insert(Name, Trait.getData(Result), Trait);
4121 break;
4122
4123 case DeclarationName::CXXConstructorName:
4124 ConstructorDecls.append(Result.begin(), Result.end());
4125 break;
4126
4127 case DeclarationName::CXXConversionFunctionName:
4128 ConversionDecls.append(Result.begin(), Result.end());
4129 break;
4130 }
4131 }
4132
4133 // Handle our two special cases if we ended up having any. We arbitrarily use
4134 // the first declaration's name here because the name itself isn't part of
4135 // the key, only the kind of name is used.
4136 if (!ConstructorDecls.empty())
4137 Generator.insert(ConstructorDecls.front()->getDeclName(),
4138 Trait.getData(ConstructorDecls), Trait);
4139 if (!ConversionDecls.empty())
4140 Generator.insert(ConversionDecls.front()->getDeclName(),
4141 Trait.getData(ConversionDecls), Trait);
4142
4143 // Create the on-disk hash table. Also emit the existing imported and
4144 // merged table if there is one.
4145 auto *Lookups = Chain ? Chain->getLoadedLookupTables(DC) : nullptr;
4146 Generator.emit(LookupTable, Trait, Lookups ? &Lookups->Table : nullptr);
4147}
4148
4149/// Write the block containing all of the declaration IDs
4150/// visible from the given DeclContext.
4151///
4152/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
4153/// bitstream, or 0 if no block was written.
4154uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
4155 DeclContext *DC) {
4156 // If we imported a key declaration of this namespace, write the visible
4157 // lookup results as an update record for it rather than including them
4158 // on this declaration. We will only look at key declarations on reload.
4159 if (isa<NamespaceDecl>(DC) && Chain &&
4160 Chain->getKeyDeclaration(cast<Decl>(DC))->isFromASTFile()) {
4161 // Only do this once, for the first local declaration of the namespace.
4162 for (auto *Prev = cast<NamespaceDecl>(DC)->getPreviousDecl(); Prev;
4163 Prev = Prev->getPreviousDecl())
4164 if (!Prev->isFromASTFile())
4165 return 0;
4166
4167 // Note that we need to emit an update record for the primary context.
4168 UpdatedDeclContexts.insert(DC->getPrimaryContext());
4169
4170 // Make sure all visible decls are written. They will be recorded later. We
4171 // do this using a side data structure so we can sort the names into
4172 // a deterministic order.
4173 StoredDeclsMap *Map = DC->getPrimaryContext()->buildLookup();
4174 SmallVector<std::pair<DeclarationName, DeclContext::lookup_result>, 16>
4175 LookupResults;
4176 if (Map) {
4177 LookupResults.reserve(Map->size());
4178 for (auto &Entry : *Map)
4179 LookupResults.push_back(
4180 std::make_pair(Entry.first, Entry.second.getLookupResult()));
4181 }
4182
4183 llvm::sort(LookupResults, llvm::less_first());
4184 for (auto &NameAndResult : LookupResults) {
4185 DeclarationName Name = NameAndResult.first;
4186 DeclContext::lookup_result Result = NameAndResult.second;
4187 if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
4188 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
4189 // We have to work around a name lookup bug here where negative lookup
4190 // results for these names get cached in namespace lookup tables (these
4191 // names should never be looked up in a namespace).
4192 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 4193, __PRETTY_FUNCTION__))
4193 "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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 4193, __PRETTY_FUNCTION__))
;
4194 continue;
4195 }
4196
4197 for (NamedDecl *ND : Result)
4198 if (!ND->isFromASTFile())
4199 GetDeclRef(ND);
4200 }
4201
4202 return 0;
4203 }
4204
4205 if (DC->getPrimaryContext() != DC)
4206 return 0;
4207
4208 // Skip contexts which don't support name lookup.
4209 if (!DC->isLookupContext())
4210 return 0;
4211
4212 // If not in C++, we perform name lookup for the translation unit via the
4213 // IdentifierInfo chains, don't bother to build a visible-declarations table.
4214 if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
4215 return 0;
4216
4217 // Serialize the contents of the mapping used for lookup. Note that,
4218 // although we have two very different code paths, the serialized
4219 // representation is the same for both cases: a declaration name,
4220 // followed by a size, followed by references to the visible
4221 // declarations that have that name.
4222 uint64_t Offset = Stream.GetCurrentBitNo();
4223 StoredDeclsMap *Map = DC->buildLookup();
4224 if (!Map || Map->empty())
4225 return 0;
4226
4227 // Create the on-disk hash table in a buffer.
4228 SmallString<4096> LookupTable;
4229 GenerateNameLookupTable(DC, LookupTable);
4230
4231 // Write the lookup table
4232 RecordData::value_type Record[] = {DECL_CONTEXT_VISIBLE};
4233 Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
4234 LookupTable);
4235 ++NumVisibleDeclContexts;
4236 return Offset;
4237}
4238
4239/// Write an UPDATE_VISIBLE block for the given context.
4240///
4241/// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
4242/// DeclContext in a dependent AST file. As such, they only exist for the TU
4243/// (in C++), for namespaces, and for classes with forward-declared unscoped
4244/// enumeration members (in C++11).
4245void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
4246 StoredDeclsMap *Map = DC->getLookupPtr();
4247 if (!Map || Map->empty())
4248 return;
4249
4250 // Create the on-disk hash table in a buffer.
4251 SmallString<4096> LookupTable;
4252 GenerateNameLookupTable(DC, LookupTable);
4253
4254 // If we're updating a namespace, select a key declaration as the key for the
4255 // update record; those are the only ones that will be checked on reload.
4256 if (isa<NamespaceDecl>(DC))
4257 DC = cast<DeclContext>(Chain->getKeyDeclaration(cast<Decl>(DC)));
4258
4259 // Write the lookup table
4260 RecordData::value_type Record[] = {UPDATE_VISIBLE, getDeclID(cast<Decl>(DC))};
4261 Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable);
4262}
4263
4264/// Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
4265void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) {
4266 RecordData::value_type Record[] = {Opts.getInt()};
4267 Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
4268}
4269
4270/// Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
4271void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
4272 if (!SemaRef.Context.getLangOpts().OpenCL)
4273 return;
4274
4275 const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
4276 RecordData Record;
4277 for (const auto &I:Opts.OptMap) {
4278 AddString(I.getKey(), Record);
4279 auto V = I.getValue();
4280 Record.push_back(V.Supported ? 1 : 0);
4281 Record.push_back(V.Enabled ? 1 : 0);
4282 Record.push_back(V.Avail);
4283 Record.push_back(V.Core);
4284 }
4285 Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
4286}
4287
4288void ASTWriter::WriteOpenCLExtensionTypes(Sema &SemaRef) {
4289 if (!SemaRef.Context.getLangOpts().OpenCL)
4290 return;
4291
4292 // Sort the elements of the map OpenCLTypeExtMap by TypeIDs,
4293 // without copying them.
4294 const llvm::DenseMap<const Type *, std::set<std::string>> &OpenCLTypeExtMap =
4295 SemaRef.OpenCLTypeExtMap;
4296 using ElementTy = std::pair<TypeID, const std::set<std::string> *>;
4297 llvm::SmallVector<ElementTy, 8> StableOpenCLTypeExtMap;
4298 StableOpenCLTypeExtMap.reserve(OpenCLTypeExtMap.size());
4299
4300 for (const auto &I : OpenCLTypeExtMap)
4301 StableOpenCLTypeExtMap.emplace_back(
4302 getTypeID(I.first->getCanonicalTypeInternal()), &I.second);
4303
4304 auto CompareByTypeID = [](const ElementTy &E1, const ElementTy &E2) -> bool {
4305 return E1.first < E2.first;
4306 };
4307 llvm::sort(StableOpenCLTypeExtMap, CompareByTypeID);
4308
4309 RecordData Record;
4310 for (const ElementTy &E : StableOpenCLTypeExtMap) {
4311 Record.push_back(E.first); // TypeID
4312 const std::set<std::string> *ExtSet = E.second;
4313 Record.push_back(static_cast<unsigned>(ExtSet->size()));
4314 for (const std::string &Ext : *ExtSet)
4315 AddString(Ext, Record);
4316 }
4317
4318 Stream.EmitRecord(OPENCL_EXTENSION_TYPES, Record);
4319}
4320
4321void ASTWriter::WriteOpenCLExtensionDecls(Sema &SemaRef) {
4322 if (!SemaRef.Context.getLangOpts().OpenCL)
4323 return;
4324
4325 // Sort the elements of the map OpenCLDeclExtMap by DeclIDs,
4326 // without copying them.
4327 const llvm::DenseMap<const Decl *, std::set<std::string>> &OpenCLDeclExtMap =
4328 SemaRef.OpenCLDeclExtMap;
4329 using ElementTy = std::pair<DeclID, const std::set<std::string> *>;
4330 llvm::SmallVector<ElementTy, 8> StableOpenCLDeclExtMap;
4331 StableOpenCLDeclExtMap.reserve(OpenCLDeclExtMap.size());
4332
4333 for (const auto &I : OpenCLDeclExtMap)
4334 StableOpenCLDeclExtMap.emplace_back(getDeclID(I.first), &I.second);
4335
4336 auto CompareByDeclID = [](const ElementTy &E1, const ElementTy &E2) -> bool {
4337 return E1.first < E2.first;
4338 };
4339 llvm::sort(StableOpenCLDeclExtMap, CompareByDeclID);
4340
4341 RecordData Record;
4342 for (const ElementTy &E : StableOpenCLDeclExtMap) {
4343 Record.push_back(E.first); // DeclID
4344 const std::set<std::string> *ExtSet = E.second;
4345 Record.push_back(static_cast<unsigned>(ExtSet->size()));
4346 for (const std::string &Ext : *ExtSet)
4347 AddString(Ext, Record);
4348 }
4349
4350 Stream.EmitRecord(OPENCL_EXTENSION_DECLS, Record);
4351}
4352
4353void ASTWriter::WriteCUDAPragmas(Sema &SemaRef) {
4354 if (SemaRef.ForceCUDAHostDeviceDepth > 0) {
4355 RecordData::value_type Record[] = {SemaRef.ForceCUDAHostDeviceDepth};
4356 Stream.EmitRecord(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH, Record);
4357 }
4358}
4359
4360void ASTWriter::WriteObjCCategories() {
4361 SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
4362 RecordData Categories;
4363
4364 for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
4365 unsigned Size = 0;
4366 unsigned StartIndex = Categories.size();
4367
4368 ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
4369
4370 // Allocate space for the size.
4371 Categories.push_back(0);
4372
4373 // Add the categories.
4374 for (ObjCInterfaceDecl::known_categories_iterator
4375 Cat = Class->known_categories_begin(),
4376 CatEnd = Class->known_categories_end();
4377 Cat != CatEnd; ++Cat, ++Size) {
4378 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 4378, __PRETTY_FUNCTION__))
;
4379 AddDeclRef(*Cat, Categories);
4380 }
4381
4382 // Update the size.
4383 Categories[StartIndex] = Size;
4384
4385 // Record this interface -> category map.
4386 ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
4387 CategoriesMap.push_back(CatInfo);
4388 }
4389
4390 // Sort the categories map by the definition ID, since the reader will be
4391 // performing binary searches on this information.
4392 llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
4393
4394 // Emit the categories map.
4395 using namespace llvm;
4396
4397 auto Abbrev = std::make_shared<BitCodeAbbrev>();
4398 Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
4399 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
4400 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4401 unsigned AbbrevID = Stream.EmitAbbrev(std::move(Abbrev));
4402
4403 RecordData::value_type Record[] = {OBJC_CATEGORIES_MAP, CategoriesMap.size()};
4404 Stream.EmitRecordWithBlob(AbbrevID, Record,
4405 reinterpret_cast<char *>(CategoriesMap.data()),
4406 CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
4407
4408 // Emit the category lists.
4409 Stream.EmitRecord(OBJC_CATEGORIES, Categories);
4410}
4411
4412void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) {
4413 Sema::LateParsedTemplateMapT &LPTMap = SemaRef.LateParsedTemplateMap;
4414
4415 if (LPTMap.empty())
4416 return;
4417
4418 RecordData Record;
4419 for (auto &LPTMapEntry : LPTMap) {
4420 const FunctionDecl *FD = LPTMapEntry.first;
4421 LateParsedTemplate &LPT = *LPTMapEntry.second;
4422 AddDeclRef(FD, Record);
4423 AddDeclRef(LPT.D, Record);
4424 Record.push_back(LPT.Toks.size());
4425
4426 for (const auto &Tok : LPT.Toks) {
4427 AddToken(Tok, Record);
4428 }
4429 }
4430 Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record);
4431}
4432
4433/// Write the state of 'pragma clang optimize' at the end of the module.
4434void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) {
4435 RecordData Record;
4436 SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation();
4437 AddSourceLocation(PragmaLoc, Record);
4438 Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record);
4439}
4440
4441/// Write the state of 'pragma ms_struct' at the end of the module.
4442void ASTWriter::WriteMSStructPragmaOptions(Sema &SemaRef) {
4443 RecordData Record;
4444 Record.push_back(SemaRef.MSStructPragmaOn ? PMSST_ON : PMSST_OFF);
4445 Stream.EmitRecord(MSSTRUCT_PRAGMA_OPTIONS, Record);
4446}
4447
4448/// Write the state of 'pragma pointers_to_members' at the end of the
4449//module.
4450void ASTWriter::WriteMSPointersToMembersPragmaOptions(Sema &SemaRef) {
4451 RecordData Record;
4452 Record.push_back(SemaRef.MSPointerToMemberRepresentationMethod);
4453 AddSourceLocation(SemaRef.ImplicitMSInheritanceAttrLoc, Record);
4454 Stream.EmitRecord(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS, Record);
4455}
4456
4457/// Write the state of 'pragma pack' at the end of the module.
4458void ASTWriter::WritePackPragmaOptions(Sema &SemaRef) {
4459 // Don't serialize pragma pack state for modules, since it should only take
4460 // effect on a per-submodule basis.
4461 if (WritingModule)
4462 return;
4463
4464 RecordData Record;
4465 Record.push_back(SemaRef.PackStack.CurrentValue);
4466 AddSourceLocation(SemaRef.PackStack.CurrentPragmaLocation, Record);
4467 Record.push_back(SemaRef.PackStack.Stack.size());
4468 for (const auto &StackEntry : SemaRef.PackStack.Stack) {
4469 Record.push_back(StackEntry.Value);
4470 AddSourceLocation(StackEntry.PragmaLocation, Record);
4471 AddSourceLocation(StackEntry.PragmaPushLocation, Record);
4472 AddString(StackEntry.StackSlotLabel, Record);
4473 }
4474 Stream.EmitRecord(PACK_PRAGMA_OPTIONS, Record);
4475}
4476
4477void ASTWriter::WriteModuleFileExtension(Sema &SemaRef,
4478 ModuleFileExtensionWriter &Writer) {
4479 // Enter the extension block.
4480 Stream.EnterSubblock(EXTENSION_BLOCK_ID, 4);
4481
4482 // Emit the metadata record abbreviation.
4483 auto Abv = std::make_shared<llvm::BitCodeAbbrev>();
4484 Abv->Add(llvm::BitCodeAbbrevOp(EXTENSION_METADATA));
4485 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4486 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4487 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4488 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4489 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4490 unsigned Abbrev = Stream.EmitAbbrev(std::move(Abv));
4491
4492 // Emit the metadata record.
4493 RecordData Record;
4494 auto Metadata = Writer.getExtension()->getExtensionMetadata();
4495 Record.push_back(EXTENSION_METADATA);
4496 Record.push_back(Metadata.MajorVersion);
4497 Record.push_back(Metadata.MinorVersion);
4498 Record.push_back(Metadata.BlockName.size());
4499 Record.push_back(Metadata.UserInfo.size());
4500 SmallString<64> Buffer;
4501 Buffer += Metadata.BlockName;
4502 Buffer += Metadata.UserInfo;
4503 Stream.EmitRecordWithBlob(Abbrev, Record, Buffer);
4504
4505 // Emit the contents of the extension block.
4506 Writer.writeExtensionContents(SemaRef, Stream);
4507
4508 // Exit the extension block.
4509 Stream.ExitBlock();
4510}
4511
4512//===----------------------------------------------------------------------===//
4513// General Serialization Routines
4514//===----------------------------------------------------------------------===//
4515
4516void ASTRecordWriter::AddAttr(const Attr *A) {
4517 auto &Record = *this;
4518 if (!A)
4519 return Record.push_back(0);
4520 Record.push_back(A->getKind() + 1); // FIXME: stable encoding, target attrs
4521 Record.AddSourceRange(A->getRange());
4522
4523#include "clang/Serialization/AttrPCHWrite.inc"
4524}
4525
4526/// Emit the list of attributes to the specified record.
4527void ASTRecordWriter::AddAttributes(ArrayRef<const Attr *> Attrs) {
4528 push_back(Attrs.size());
4529 for (const auto *A : Attrs)
4530 AddAttr(A);
4531}
4532
4533void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) {
4534 AddSourceLocation(Tok.getLocation(), Record);
4535 Record.push_back(Tok.getLength());
4536
4537 // FIXME: When reading literal tokens, reconstruct the literal pointer
4538 // if it is needed.
4539 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
4540 // FIXME: Should translate token kind to a stable encoding.
4541 Record.push_back(Tok.getKind());
4542 // FIXME: Should translate token flags to a stable encoding.
4543 Record.push_back(Tok.getFlags());
4544}
4545
4546void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
4547 Record.push_back(Str.size());
4548 Record.insert(Record.end(), Str.begin(), Str.end());
4549}
4550
4551bool ASTWriter::PreparePathForOutput(SmallVectorImpl<char> &Path) {
4552 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 4552, __PRETTY_FUNCTION__))
;
4553
4554 bool Changed =
4555 cleanPathForOutput(Context->getSourceManager().getFileManager(), Path);
4556
4557 // Remove a prefix to make the path relative, if relevant.
4558 const char *PathBegin = Path.data();
4559 const char *PathPtr =
4560 adjustFilenameForRelocatableAST(PathBegin, BaseDirectory);
4561 if (PathPtr != PathBegin) {
4562 Path.erase(Path.begin(), Path.begin() + (PathPtr - PathBegin));
4563 Changed = true;
4564 }
4565
4566 return Changed;
4567}
4568
4569void ASTWriter::AddPath(StringRef Path, RecordDataImpl &Record) {
4570 SmallString<128> FilePath(Path);
4571 PreparePathForOutput(FilePath);
4572 AddString(FilePath, Record);
4573}
4574
4575void ASTWriter::EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record,
4576 StringRef Path) {
4577 SmallString<128> FilePath(Path);
4578 PreparePathForOutput(FilePath);
4579 Stream.EmitRecordWithBlob(Abbrev, Record, FilePath);
4580}
4581
4582void ASTWriter::AddVersionTuple(const VersionTuple &Version,
4583 RecordDataImpl &Record) {
4584 Record.push_back(Version.getMajor());
4585 if (Optional<unsigned> Minor = Version.getMinor())
4586 Record.push_back(*Minor + 1);
4587 else
4588 Record.push_back(0);
4589 if (Optional<unsigned> Subminor = Version.getSubminor())
4590 Record.push_back(*Subminor + 1);
4591 else
4592 Record.push_back(0);
4593}
4594
4595/// Note that the identifier II occurs at the given offset
4596/// within the identifier table.
4597void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
4598 IdentID ID = IdentifierIDs[II];
4599 // Only store offsets new to this AST file. Other identifier names are looked
4600 // up earlier in the chain and thus don't need an offset.
4601 if (ID >= FirstIdentID)
4602 IdentifierOffsets[ID - FirstIdentID] = Offset;
4603}
4604
4605/// Note that the selector Sel occurs at the given offset
4606/// within the method pool/selector table.
4607void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
4608 unsigned ID = SelectorIDs[Sel];
4609 assert(ID && "Unknown selector")((ID && "Unknown selector") ? static_cast<void>
(0) : __assert_fail ("ID && \"Unknown selector\"", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 4609, __PRETTY_FUNCTION__))
;
4610 // Don't record offsets for selectors that are also available in a different
4611 // file.
4612 if (ID < FirstSelectorID)
4613 return;
4614 SelectorOffsets[ID - FirstSelectorID] = Offset;
4615}
4616
4617ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream,
4618 SmallVectorImpl<char> &Buffer,
4619 InMemoryModuleCache &ModuleCache,
4620 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
4621 bool IncludeTimestamps)
4622 : Stream(Stream), Buffer(Buffer), ModuleCache(ModuleCache),
4623 IncludeTimestamps(IncludeTimestamps) {
4624 for (const auto &Ext : Extensions) {
4625 if (auto Writer = Ext->createExtensionWriter(*this))
4626 ModuleFileExtensionWriters.push_back(std::move(Writer));
4627 }
4628}
4629
4630ASTWriter::~ASTWriter() {
4631 llvm::DeleteContainerSeconds(FileDeclIDs);
4632}
4633
4634const LangOptions &ASTWriter::getLangOpts() const {
4635 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 4635, __PRETTY_FUNCTION__))
;
4636 return Context->getLangOpts();
4637}
4638
4639time_t ASTWriter::getTimestampForOutput(const FileEntry *E) const {
4640 return IncludeTimestamps ? E->getModificationTime() : 0;
4641}
4642
4643ASTFileSignature ASTWriter::WriteAST(Sema &SemaRef,
4644 const std::string &OutputFile,
4645 Module *WritingModule, StringRef isysroot,
4646 bool hasErrors,
4647 bool ShouldCacheASTInMemory) {
4648 WritingAST = true;
4649
4650 ASTHasCompilerErrors = hasErrors;
4651
4652 // Emit the file header.
4653 Stream.Emit((unsigned)'C', 8);
4654 Stream.Emit((unsigned)'P', 8);
4655 Stream.Emit((unsigned)'C', 8);
4656 Stream.Emit((unsigned)'H', 8);
4657
4658 WriteBlockInfoBlock();
4659
4660 Context = &SemaRef.Context;
4661 PP = &SemaRef.PP;
4662 this->WritingModule = WritingModule;
4663 ASTFileSignature Signature =
4664 WriteASTCore(SemaRef, isysroot, OutputFile, WritingModule);
4665 Context = nullptr;
4666 PP = nullptr;
4667 this->WritingModule = nullptr;
4668 this->BaseDirectory.clear();
4669
4670 WritingAST = false;
4671 if (ShouldCacheASTInMemory) {
4672 // Construct MemoryBuffer and update buffer manager.
4673 ModuleCache.addBuiltPCM(OutputFile,
4674 llvm::MemoryBuffer::getMemBufferCopy(
4675 StringRef(Buffer.begin(), Buffer.size())));
4676 }
4677 return Signature;
4678}
4679
4680template<typename Vector>
4681static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
4682 ASTWriter::RecordData &Record) {
4683 for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
4684 I != E; ++I) {
4685 Writer.AddDeclRef(*I, Record);
4686 }
4687}
4688
4689ASTFileSignature ASTWriter::WriteASTCore(Sema &SemaRef, StringRef isysroot,
4690 const std::string &OutputFile,
4691 Module *WritingModule) {
4692 using namespace llvm;
4693
4694 bool isModule = WritingModule != nullptr;
4695
4696 // Make sure that the AST reader knows to finalize itself.
4697 if (Chain)
4698 Chain->finalizeForWriting();
4699
4700 ASTContext &Context = SemaRef.Context;
4701 Preprocessor &PP = SemaRef.PP;
4702
4703 // Set up predefined declaration IDs.
4704 auto RegisterPredefDecl = [&] (Decl *D, PredefinedDeclIDs ID) {
4705 if (D) {
4706 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 4706, __PRETTY_FUNCTION__))
;
4707 DeclIDs[D] = ID;
4708 }
4709 };
4710 RegisterPredefDecl(Context.getTranslationUnitDecl(),
4711 PREDEF_DECL_TRANSLATION_UNIT_ID);
4712 RegisterPredefDecl(Context.ObjCIdDecl, PREDEF_DECL_OBJC_ID_ID);
4713 RegisterPredefDecl(Context.ObjCSelDecl, PREDEF_DECL_OBJC_SEL_ID);
4714 RegisterPredefDecl(Context.ObjCClassDecl, PREDEF_DECL_OBJC_CLASS_ID);
4715 RegisterPredefDecl(Context.ObjCProtocolClassDecl,
4716 PREDEF_DECL_OBJC_PROTOCOL_ID);
4717 RegisterPredefDecl(Context.Int128Decl, PREDEF_DECL_INT_128_ID);
4718 RegisterPredefDecl(Context.UInt128Decl, PREDEF_DECL_UNSIGNED_INT_128_ID);
4719 RegisterPredefDecl(Context.ObjCInstanceTypeDecl,
4720 PREDEF_DECL_OBJC_INSTANCETYPE_ID);
4721 RegisterPredefDecl(Context.BuiltinVaListDecl, PREDEF_DECL_BUILTIN_VA_LIST_ID);
4722 RegisterPredefDecl(Context.VaListTagDecl, PREDEF_DECL_VA_LIST_TAG);
4723 RegisterPredefDecl(Context.BuiltinMSVaListDecl,
4724 PREDEF_DECL_BUILTIN_MS_VA_LIST_ID);
4725 RegisterPredefDecl(Context.ExternCContext, PREDEF_DECL_EXTERN_C_CONTEXT_ID);
4726 RegisterPredefDecl(Context.MakeIntegerSeqDecl,
4727 PREDEF_DECL_MAKE_INTEGER_SEQ_ID);
4728 RegisterPredefDecl(Context.CFConstantStringTypeDecl,
4729 PREDEF_DECL_CF_CONSTANT_STRING_ID);
4730 RegisterPredefDecl(Context.CFConstantStringTagDecl,
4731 PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID);
4732 RegisterPredefDecl(Context.TypePackElementDecl,
4733 PREDEF_DECL_TYPE_PACK_ELEMENT_ID);
4734
4735 // Build a record containing all of the tentative definitions in this file, in
4736 // TentativeDefinitions order. Generally, this record will be empty for
4737 // headers.
4738 RecordData TentativeDefinitions;
4739 AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
4740
4741 // Build a record containing all of the file scoped decls in this file.
4742 RecordData UnusedFileScopedDecls;
4743 if (!isModule)
4744 AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls,
4745 UnusedFileScopedDecls);
4746
4747 // Build a record containing all of the delegating constructors we still need
4748 // to resolve.
4749 RecordData DelegatingCtorDecls;
4750 if (!isModule)
4751 AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
4752
4753 // Write the set of weak, undeclared identifiers. We always write the
4754 // entire table, since later PCH files in a PCH chain are only interested in
4755 // the results at the end of the chain.
4756 RecordData WeakUndeclaredIdentifiers;
4757 for (auto &WeakUndeclaredIdentifier : SemaRef.WeakUndeclaredIdentifiers) {
4758 IdentifierInfo *II = WeakUndeclaredIdentifier.first;
4759 WeakInfo &WI = WeakUndeclaredIdentifier.second;
4760 AddIdentifierRef(II, WeakUndeclaredIdentifiers);
4761 AddIdentifierRef(WI.getAlias(), WeakUndeclaredIdentifiers);
4762 AddSourceLocation(WI.getLocation(), WeakUndeclaredIdentifiers);
4763 WeakUndeclaredIdentifiers.push_back(WI.getUsed());
4764 }
4765
4766 // Build a record containing all of the ext_vector declarations.
4767 RecordData ExtVectorDecls;
4768 AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
4769
4770 // Build a record containing all of the VTable uses information.
4771 RecordData VTableUses;
4772 if (!SemaRef.VTableUses.empty()) {
4773 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
4774 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
4775 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
4776 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
4777 }
4778 }
4779
4780 // Build a record containing all of the UnusedLocalTypedefNameCandidates.
4781 RecordData UnusedLocalTypedefNameCandidates;
4782 for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates)
4783 AddDeclRef(TD, UnusedLocalTypedefNameCandidates);
4784
4785 // Build a record containing all of pending implicit instantiations.
4786 RecordData PendingInstantiations;
4787 for (const auto &I : SemaRef.PendingInstantiations) {
4788 AddDeclRef(I.first, PendingInstantiations);
4789 AddSourceLocation(I.second, PendingInstantiations);
4790 }
4791 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 4792, __PRETTY_FUNCTION__))
4792 "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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 4792, __PRETTY_FUNCTION__))
;
4793
4794 // Build a record containing some declaration references.
4795 RecordData SemaDeclRefs;
4796 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc || SemaRef.StdAlignValT) {
4797 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
4798 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
4799 AddDeclRef(SemaRef.getStdAlignValT(), SemaDeclRefs);
4800 }
4801
4802 RecordData CUDASpecialDeclRefs;
4803 if (Context.getcudaConfigureCallDecl()) {
4804 AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
4805 }
4806
4807 // Build a record containing all of the known namespaces.
4808 RecordData KnownNamespaces;
4809 for (const auto &I : SemaRef.KnownNamespaces) {
4810 if (!I.second)
4811 AddDeclRef(I.first, KnownNamespaces);
4812 }
4813
4814 // Build a record of all used, undefined objects that require definitions.
4815 RecordData UndefinedButUsed;
4816
4817 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
4818 SemaRef.getUndefinedButUsed(Undefined);
4819 for (const auto &I : Undefined) {
4820 AddDeclRef(I.first, UndefinedButUsed);
4821 AddSourceLocation(I.second, UndefinedButUsed);
4822 }
4823
4824 // Build a record containing all delete-expressions that we would like to
4825 // analyze later in AST.
4826 RecordData DeleteExprsToAnalyze;
4827
4828 if (!isModule) {
4829 for (const auto &DeleteExprsInfo :
4830 SemaRef.getMismatchingDeleteExpressions()) {
4831 AddDeclRef(DeleteExprsInfo.first, DeleteExprsToAnalyze);
4832 DeleteExprsToAnalyze.push_back(DeleteExprsInfo.second.size());
4833 for (const auto &DeleteLoc : DeleteExprsInfo.second) {
4834 AddSourceLocation(DeleteLoc.first, DeleteExprsToAnalyze);
4835 DeleteExprsToAnalyze.push_back(DeleteLoc.second);
4836 }
4837 }
4838 }
4839
4840 // Write the control block
4841 WriteControlBlock(PP, Context, isysroot, OutputFile);
4842
4843 // Write the remaining AST contents.
4844 Stream.EnterSubblock(AST_BLOCK_ID, 5);
4845
4846 // This is so that older clang versions, before the introduction
4847 // of the control block, can read and reject the newer PCH format.
4848 {
4849 RecordData Record = {VERSION_MAJOR};
4850 Stream.EmitRecord(METADATA_OLD_FORMAT, Record);
4851 }
4852
4853 // Create a lexical update block containing all of the declarations in the
4854 // translation unit that do not come from other AST files.
4855 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
4856 SmallVector<uint32_t, 128> NewGlobalKindDeclPairs;
4857 for (const auto *D : TU->noload_decls()) {
4858 if (!D->isFromASTFile()) {
4859 NewGlobalKindDeclPairs.push_back(D->getKind());
4860 NewGlobalKindDeclPairs.push_back(GetDeclRef(D));
4861 }
4862 }
4863
4864 auto Abv = std::make_shared<BitCodeAbbrev>();
4865 Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
4866 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4867 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(std::move(Abv));
4868 {
4869 RecordData::value_type Record[] = {TU_UPDATE_LEXICAL};
4870 Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
4871 bytes(NewGlobalKindDeclPairs));
4872 }
4873
4874 // And a visible updates block for the translation unit.
4875 Abv = std::make_shared<BitCodeAbbrev>();
4876 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
4877 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4878 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4879 UpdateVisibleAbbrev = Stream.EmitAbbrev(std::move(Abv));
4880 WriteDeclContextVisibleUpdate(TU);
4881
4882 // If we have any extern "C" names, write out a visible update for them.
4883 if (Context.ExternCContext)
4884 WriteDeclContextVisibleUpdate(Context.ExternCContext);
4885
4886 // If the translation unit has an anonymous namespace, and we don't already
4887 // have an update block for it, write it as an update block.
4888 // FIXME: Why do we not do this if there's already an update block?
4889 if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
4890 ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
4891 if (Record.empty())
4892 Record.push_back(DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, NS));
4893 }
4894
4895 // Add update records for all mangling numbers and static local numbers.
4896 // These aren't really update records, but this is a convenient way of
4897 // tagging this rare extra data onto the declarations.
4898 for (const auto &Number : Context.MangleNumbers)
4899 if (!Number.first->isFromASTFile())
4900 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_MANGLING_NUMBER,
4901 Number.second));
4902 for (const auto &Number : Context.StaticLocalNumbers)
4903 if (!Number.first->isFromASTFile())
4904 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_STATIC_LOCAL_NUMBER,
4905 Number.second));
4906
4907 // Make sure visible decls, added to DeclContexts previously loaded from
4908 // an AST file, are registered for serialization. Likewise for template
4909 // specializations added to imported templates.
4910 for (const auto *I : DeclsToEmitEvenIfUnreferenced) {
4911 GetDeclRef(I);
4912 }
4913
4914 // Make sure all decls associated with an identifier are registered for
4915 // serialization, if we're storing decls with identifiers.
4916 if (!WritingModule || !getLangOpts().CPlusPlus) {
4917 llvm::SmallVector<const IdentifierInfo*, 256> IIs;
4918 for (const auto &ID : PP.getIdentifierTable()) {
4919 const IdentifierInfo *II = ID.second;
4920 if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization())
4921 IIs.push_back(II);
4922 }
4923 // Sort the identifiers to visit based on their name.
4924 llvm::sort(IIs, llvm::less_ptr<IdentifierInfo>());
4925 for (const IdentifierInfo *II : IIs) {
4926 for (IdentifierResolver::iterator D = SemaRef.IdResolver.begin(II),
4927 DEnd = SemaRef.IdResolver.end();
4928 D != DEnd; ++D) {
4929 GetDeclRef(*D);
4930 }
4931 }
4932 }
4933
4934 // For method pool in the module, if it contains an entry for a selector,
4935 // the entry should be complete, containing everything introduced by that
4936 // module and all modules it imports. It's possible that the entry is out of
4937 // date, so we need to pull in the new content here.
4938
4939 // It's possible that updateOutOfDateSelector can update SelectorIDs. To be
4940 // safe, we copy all selectors out.
4941 llvm::SmallVector<Selector, 256> AllSelectors;
4942 for (auto &SelectorAndID : SelectorIDs)
4943 AllSelectors.push_back(SelectorAndID.first);
4944 for (auto &Selector : AllSelectors)
4945 SemaRef.updateOutOfDateSelector(Selector);
4946
4947 // Form the record of special types.
4948 RecordData SpecialTypes;
4949 AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
4950 AddTypeRef(Context.getFILEType(), SpecialTypes);
4951 AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
4952 AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
4953 AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
4954 AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
4955 AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
4956 AddTypeRef(Context.getucontext_tType(), SpecialTypes);
4957
4958 if (Chain) {
4959 // Write the mapping information describing our module dependencies and how
4960 // each of those modules were mapped into our own offset/ID space, so that
4961 // the reader can build the appropriate mapping to its own offset/ID space.
4962 // The map consists solely of a blob with the following format:
4963 // *(module-kind:i8
4964 // module-name-len:i16 module-name:len*i8
4965 // source-location-offset:i32
4966 // identifier-id:i32
4967 // preprocessed-entity-id:i32
4968 // macro-definition-id:i32
4969 // submodule-id:i32
4970 // selector-id:i32
4971 // declaration-id:i32
4972 // c++-base-specifiers-id:i32
4973 // type-id:i32)
4974 //
4975 // module-kind is the ModuleKind enum value. If it is MK_PrebuiltModule or
4976 // MK_ExplicitModule, then the module-name is the module name. Otherwise,
4977 // it is the module file name.
4978 auto Abbrev = std::make_shared<BitCodeAbbrev>();
4979 Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
4980 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4981 unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
4982 SmallString<2048> Buffer;
4983 {
4984 llvm::raw_svector_ostream Out(Buffer);
4985 for (ModuleFile &M : Chain->ModuleMgr) {
4986 using namespace llvm::support;
4987
4988 endian::Writer LE(Out, little);
4989 LE.write<uint8_t>(static_cast<uint8_t>(M.Kind));
4990 StringRef Name =
4991 M.Kind == MK_PrebuiltModule || M.Kind == MK_ExplicitModule
4992 ? M.ModuleName
4993 : M.FileName;
4994 LE.write<uint16_t>(Name.size());
4995 Out.write(Name.data(), Name.size());
4996
4997 // Note: if a base ID was uint max, it would not be possible to load
4998 // another module after it or have more than one entity inside it.
4999 uint32_t None = std::numeric_limits<uint32_t>::max();
5000
5001 auto writeBaseIDOrNone = [&](uint32_t BaseID, bool ShouldWrite) {
5002 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 5002, __PRETTY_FUNCTION__))
;
5003 if (ShouldWrite)
5004 LE.write<uint32_t>(BaseID);
5005 else
5006 LE.write<uint32_t>(None);
5007 };
5008
5009 // These values should be unique within a chain, since they will be read
5010 // as keys into ContinuousRangeMaps.
5011 writeBaseIDOrNone(M.SLocEntryBaseOffset, M.LocalNumSLocEntries);
5012 writeBaseIDOrNone(M.BaseIdentifierID, M.LocalNumIdentifiers);
5013 writeBaseIDOrNone(M.BaseMacroID, M.LocalNumMacros);
5014 writeBaseIDOrNone(M.BasePreprocessedEntityID,
5015 M.NumPreprocessedEntities);
5016 writeBaseIDOrNone(M.BaseSubmoduleID, M.LocalNumSubmodules);
5017 writeBaseIDOrNone(M.BaseSelectorID, M.LocalNumSelectors);
5018 writeBaseIDOrNone(M.BaseDeclID, M.LocalNumDecls);
5019 writeBaseIDOrNone(M.BaseTypeIndex, M.LocalNumTypes);
5020 }
5021 }
5022 RecordData::value_type Record[] = {MODULE_OFFSET_MAP};
5023 Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
5024 Buffer.data(), Buffer.size());
5025 }
5026
5027 RecordData DeclUpdatesOffsetsRecord;
5028
5029 // Keep writing types, declarations, and declaration update records
5030 // until we've emitted all of them.
5031 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/5);
5032 WriteTypeAbbrevs();
5033 WriteDeclAbbrevs();
5034 do {
5035 WriteDeclUpdatesBlocks(DeclUpdatesOffsetsRecord);
5036 while (!DeclTypesToEmit.empty()) {
5037 DeclOrType DOT = DeclTypesToEmit.front();
5038 DeclTypesToEmit.pop();
5039 if (DOT.isType())
5040 WriteType(DOT.getType());
5041 else
5042 WriteDecl(Context, DOT.getDecl());
5043 }
5044 } while (!DeclUpdates.empty());
5045 Stream.ExitBlock();
5046
5047 DoneWritingDeclsAndTypes = true;
5048
5049 // These things can only be done once we've written out decls and types.
5050 WriteTypeDeclOffsets();
5051 if (!DeclUpdatesOffsetsRecord.empty())
5052 Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord);
5053 WriteFileDeclIDsMap();
5054 WriteSourceManagerBlock(Context.getSourceManager(), PP);
5055 WriteComments();
5056 WritePreprocessor(PP, isModule);
5057 WriteHeaderSearch(PP.getHeaderSearchInfo());
5058 WriteSelectors(SemaRef);
5059 WriteReferencedSelectorsPool(SemaRef);
5060 WriteLateParsedTemplates(SemaRef);
5061 WriteIdentifierTable(PP, SemaRef.IdResolver, isModule);
5062 WriteFPPragmaOptions(SemaRef.getFPOptions());
5063 WriteOpenCLExtensions(SemaRef);
5064 WriteOpenCLExtensionTypes(SemaRef);
5065 WriteCUDAPragmas(SemaRef);
5066
5067 // If we're emitting a module, write out the submodule information.
5068 if (WritingModule)
5069 WriteSubmodules(WritingModule);
5070
5071 // We need to have information about submodules to correctly deserialize
5072 // decls from OpenCLExtensionDecls block
5073 WriteOpenCLExtensionDecls(SemaRef);
5074
5075 Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
5076
5077 // Write the record containing external, unnamed definitions.
5078 if (!EagerlyDeserializedDecls.empty())
5079 Stream.EmitRecord(EAGERLY_DESERIALIZED_DECLS, EagerlyDeserializedDecls);
5080
5081 if (!ModularCodegenDecls.empty())
5082 Stream.EmitRecord(MODULAR_CODEGEN_DECLS, ModularCodegenDecls);
5083
5084 // Write the record containing tentative definitions.
5085 if (!TentativeDefinitions.empty())
5086 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
5087
5088 // Write the record containing unused file scoped decls.
5089 if (!UnusedFileScopedDecls.empty())
5090 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
5091
5092 // Write the record containing weak undeclared identifiers.
5093 if (!WeakUndeclaredIdentifiers.empty())
5094 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
5095 WeakUndeclaredIdentifiers);
5096
5097 // Write the record containing ext_vector type names.
5098 if (!ExtVectorDecls.empty())
5099 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
5100
5101 // Write the record containing VTable uses information.
5102 if (!VTableUses.empty())
5103 Stream.EmitRecord(VTABLE_USES, VTableUses);
5104
5105 // Write the record containing potentially unused local typedefs.
5106 if (!UnusedLocalTypedefNameCandidates.empty())
5107 Stream.EmitRecord(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES,
5108 UnusedLocalTypedefNameCandidates);
5109
5110 // Write the record containing pending implicit instantiations.
5111 if (!PendingInstantiations.empty())
5112 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
5113
5114 // Write the record containing declaration references of Sema.
5115 if (!SemaDeclRefs.empty())
5116 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
5117
5118 // Write the record containing CUDA-specific declaration references.
5119 if (!CUDASpecialDeclRefs.empty())
5120 Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
5121
5122 // Write the delegating constructors.
5123 if (!DelegatingCtorDecls.empty())
5124 Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
5125
5126 // Write the known namespaces.
5127 if (!KnownNamespaces.empty())
5128 Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
5129
5130 // Write the undefined internal functions and variables, and inline functions.
5131 if (!UndefinedButUsed.empty())
5132 Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed);
5133
5134 if (!DeleteExprsToAnalyze.empty())
5135 Stream.EmitRecord(DELETE_EXPRS_TO_ANALYZE, DeleteExprsToAnalyze);
5136
5137 // Write the visible updates to DeclContexts.
5138 for (auto *DC : UpdatedDeclContexts)
5139 WriteDeclContextVisibleUpdate(DC);
5140
5141 if (!WritingModule) {
5142 // Write the submodules that were imported, if any.
5143 struct ModuleInfo {
5144 uint64_t ID;
5145 Module *M;
5146 ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {}
5147 };
5148 llvm::SmallVector<ModuleInfo, 64> Imports;
5149 for (const auto *I : Context.local_imports()) {
5150 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 5150, __PRETTY_FUNCTION__))
;
5151 Imports.push_back(ModuleInfo(SubmoduleIDs[I->getImportedModule()],
5152 I->getImportedModule()));
5153 }
5154
5155 if (!Imports.empty()) {
5156 auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) {
5157 return A.ID < B.ID;
5158 };
5159 auto Eq = [](const ModuleInfo &A, const ModuleInfo &B) {
5160 return A.ID == B.ID;
5161 };
5162
5163 // Sort and deduplicate module IDs.
5164 llvm::sort(Imports, Cmp);
5165 Imports.erase(std::unique(Imports.begin(), Imports.end(), Eq),
5166 Imports.end());
5167
5168 RecordData ImportedModules;
5169 for (const auto &Import : Imports) {
5170 ImportedModules.push_back(Import.ID);
5171 // FIXME: If the module has macros imported then later has declarations
5172 // imported, this location won't be the right one as a location for the
5173 // declaration imports.
5174 AddSourceLocation(PP.getModuleImportLoc(Import.M), ImportedModules);
5175 }
5176
5177 Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
5178 }
5179 }
5180
5181 WriteObjCCategories();
5182 if(!WritingModule) {
5183 WriteOptimizePragmaOptions(SemaRef);
5184 WriteMSStructPragmaOptions(SemaRef);
5185 WriteMSPointersToMembersPragmaOptions(SemaRef);
5186 }
5187 WritePackPragmaOptions(SemaRef);
5188
5189 // Some simple statistics
5190 RecordData::value_type Record[] = {
5191 NumStatements, NumMacros, NumLexicalDeclContexts, NumVisibleDeclContexts};
5192 Stream.EmitRecord(STATISTICS, Record);
5193 Stream.ExitBlock();
5194
5195 // Write the module file extension blocks.
5196 for (const auto &ExtWriter : ModuleFileExtensionWriters)
5197 WriteModuleFileExtension(SemaRef, *ExtWriter);
5198
5199 return writeUnhashedControlBlock(PP, Context);
5200}
5201
5202void ASTWriter::WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord) {
5203 if (DeclUpdates.empty())
5204 return;
5205
5206 DeclUpdateMap LocalUpdates;
5207 LocalUpdates.swap(DeclUpdates);
5208
5209 for (auto &DeclUpdate : LocalUpdates) {
5210 const Decl *D = DeclUpdate.first;
5211
5212 bool HasUpdatedBody = false;
5213 RecordData RecordData;
5214 ASTRecordWriter Record(*this, RecordData);
5215 for (auto &Update : DeclUpdate.second) {
5216 DeclUpdateKind Kind = (DeclUpdateKind)Update.getKind();
5217
5218 // An updated body is emitted last, so that the reader doesn't need
5219 // to skip over the lazy body to reach statements for other records.
5220 if (Kind == UPD_CXX_ADDED_FUNCTION_DEFINITION)
5221 HasUpdatedBody = true;
5222 else
5223 Record.push_back(Kind);
5224
5225 switch (Kind) {
5226 case UPD_CXX_ADDED_IMPLICIT_MEMBER:
5227 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
5228 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE:
5229 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 5229, __PRETTY_FUNCTION__))
;
5230 Record.push_back(GetDeclRef(Update.getDecl()));
5231 break;
5232
5233 case UPD_CXX_ADDED_FUNCTION_DEFINITION:
5234 break;
5235
5236 case UPD_CXX_POINT_OF_INSTANTIATION:
5237 // FIXME: Do we need to also save the template specialization kind here?
5238 Record.AddSourceLocation(Update.getLoc());
5239 break;
5240
5241 case UPD_CXX_ADDED_VAR_DEFINITION: {
5242 const VarDecl *VD = cast<VarDecl>(D);
5243 Record.push_back(VD->isInline());
5244 Record.push_back(VD->isInlineSpecified());
5245 if (VD->getInit()) {
5246 Record.push_back(!VD->isInitKnownICE() ? 1
5247 : (VD->isInitICE() ? 3 : 2));
5248 Record.AddStmt(const_cast<Expr*>(VD->getInit()));
5249 } else {
5250 Record.push_back(0);
5251 }
5252 break;
5253 }
5254
5255 case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT:
5256 Record.AddStmt(const_cast<Expr *>(
5257 cast<ParmVarDecl>(Update.getDecl())->getDefaultArg()));
5258 break;
5259
5260 case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER:
5261 Record.AddStmt(
5262 cast<FieldDecl>(Update.getDecl())->getInClassInitializer());
5263 break;
5264
5265 case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
5266 auto *RD = cast<CXXRecordDecl>(D);
5267 UpdatedDeclContexts.insert(RD->getPrimaryContext());
5268 Record.push_back(RD->isParamDestroyedInCallee());
5269 Record.push_back(RD->getArgPassingRestrictions());
5270 Record.AddCXXDefinitionData(RD);
5271 Record.AddOffset(WriteDeclContextLexicalBlock(
5272 *Context, const_cast<CXXRecordDecl *>(RD)));
5273
5274 // This state is sometimes updated by template instantiation, when we
5275 // switch from the specialization referring to the template declaration
5276 // to it referring to the template definition.
5277 if (auto *MSInfo = RD->getMemberSpecializationInfo()) {
5278 Record.push_back(MSInfo->getTemplateSpecializationKind());
5279 Record.AddSourceLocation(MSInfo->getPointOfInstantiation());
5280 } else {
5281 auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
5282 Record.push_back(Spec->getTemplateSpecializationKind());
5283 Record.AddSourceLocation(Spec->getPointOfInstantiation());
5284
5285 // The instantiation might have been resolved to a partial
5286 // specialization. If so, record which one.
5287 auto From = Spec->getInstantiatedFrom();
5288 if (auto PartialSpec =
5289 From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) {
5290 Record.push_back(true);
5291 Record.AddDeclRef(PartialSpec);
5292 Record.AddTemplateArgumentList(
5293 &Spec->getTemplateInstantiationArgs());
5294 } else {
5295 Record.push_back(false);
5296 }
5297 }
5298 Record.push_back(RD->getTagKind());
5299 Record.AddSourceLocation(RD->getLocation());
5300 Record.AddSourceLocation(RD->getBeginLoc());
5301 Record.AddSourceRange(RD->getBraceRange());
5302
5303 // Instantiation may change attributes; write them all out afresh.
5304 Record.push_back(D->hasAttrs());
5305 if (D->hasAttrs())
5306 Record.AddAttributes(D->getAttrs());
5307
5308 // FIXME: Ensure we don't get here for explicit instantiations.
5309 break;
5310 }
5311
5312 case UPD_CXX_RESOLVED_DTOR_DELETE:
5313 Record.AddDeclRef(Update.getDecl());
5314 Record.AddStmt(cast<CXXDestructorDecl>(D)->getOperatorDeleteThisArg());
5315 break;
5316
5317 case UPD_CXX_RESOLVED_EXCEPTION_SPEC:
5318 addExceptionSpec(
5319 cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>(),
5320 Record);
5321 break;
5322
5323 case UPD_CXX_DEDUCED_RETURN_TYPE:
5324 Record.push_back(GetOrCreateTypeID(Update.getType()));
5325 break;
5326
5327 case UPD_DECL_MARKED_USED:
5328 break;
5329
5330 case UPD_MANGLING_NUMBER:
5331 case UPD_STATIC_LOCAL_NUMBER:
5332 Record.push_back(Update.getNumber());
5333 break;
5334
5335 case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
5336 Record.AddSourceRange(
5337 D->getAttr<OMPThreadPrivateDeclAttr>()->getRange());
5338 break;
5339
5340 case UPD_DECL_MARKED_OPENMP_ALLOCATE: {
5341 auto *A = D->getAttr<OMPAllocateDeclAttr>();
5342 Record.push_back(A->getAllocatorType());
5343 Record.AddStmt(A->getAllocator());
5344 Record.AddSourceRange(A->getRange());
5345 break;
5346 }
5347
5348 case UPD_DECL_MARKED_OPENMP_DECLARETARGET:
5349 Record.push_back(D->getAttr<OMPDeclareTargetDeclAttr>()->getMapType());
5350 Record.AddSourceRange(
5351 D->getAttr<OMPDeclareTargetDeclAttr>()->getRange());
5352 break;
5353
5354 case UPD_DECL_EXPORTED:
5355 Record.push_back(getSubmoduleID(Update.getModule()));
5356 break;
5357
5358 case UPD_ADDED_ATTR_TO_RECORD:
5359 Record.AddAttributes(llvm::makeArrayRef(Update.getAttr()));
5360 break;
5361 }
5362 }
5363
5364 if (HasUpdatedBody) {
5365 const auto *Def = cast<FunctionDecl>(D);
5366 Record.push_back(UPD_CXX_ADDED_FUNCTION_DEFINITION);
5367 Record.push_back(Def->isInlined());
5368 Record.AddSourceLocation(Def->getInnerLocStart());
5369 Record.AddFunctionDefinition(Def);
5370 }
5371
5372 OffsetsRecord.push_back(GetDeclRef(D));
5373 OffsetsRecord.push_back(Record.Emit(DECL_UPDATES));
5374 }
5375}
5376
5377void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
5378 uint32_t Raw = Loc.getRawEncoding();
5379 Record.push_back((Raw << 1) | (Raw >> 31));
5380}
5381
5382void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
5383 AddSourceLocation(Range.getBegin(), Record);
5384 AddSourceLocation(Range.getEnd(), Record);
5385}
5386
5387void ASTRecordWriter::AddAPInt(const llvm::APInt &Value) {
5388 Record->push_back(Value.getBitWidth());
5389 const uint64_t *Words = Value.getRawData();
5390 Record->append(Words, Words + Value.getNumWords());
5391}
5392
5393void ASTRecordWriter::AddAPSInt(const llvm::APSInt &Value) {
5394 Record->push_back(Value.isUnsigned());
5395 AddAPInt(Value);
5396}
5397
5398void ASTRecordWriter::AddAPFloat(const llvm::APFloat &Value) {
5399 AddAPInt(Value.bitcastToAPInt());
5400}
5401
5402void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
5403 Record.push_back(getIdentifierRef(II));
5404}
5405
5406IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
5407 if (!II)
5408 return 0;
5409
5410 IdentID &ID = IdentifierIDs[II];
5411 if (ID == 0)
5412 ID = NextIdentID++;
5413 return ID;
5414}
5415
5416MacroID ASTWriter::getMacroRef(MacroInfo *MI, const IdentifierInfo *Name) {
5417 // Don't emit builtin macros like __LINE__ to the AST file unless they
5418 // have been redefined by the header (in which case they are not
5419 // isBuiltinMacro).
5420 if (!MI || MI->isBuiltinMacro())
5421 return 0;
5422
5423 MacroID &ID = MacroIDs[MI];
5424 if (ID == 0) {
5425 ID = NextMacroID++;
5426 MacroInfoToEmitData Info = { Name, MI, ID };
5427 MacroInfosToEmit.push_back(Info);
5428 }
5429 return ID;
5430}
5431
5432MacroID ASTWriter::getMacroID(MacroInfo *MI) {
5433 if (!MI || MI->isBuiltinMacro())
5434 return 0;
5435
5436 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 5436, __PRETTY_FUNCTION__))
;
5437 return MacroIDs[MI];
5438}
5439
5440uint64_t ASTWriter::getMacroDirectivesOffset(const IdentifierInfo *Name) {
5441 return IdentMacroDirectivesOffsetMap.lookup(Name);
5442}
5443
5444void ASTRecordWriter::AddSelectorRef(const Selector SelRef) {
5445 Record->push_back(Writer->getSelectorRef(SelRef));
5446}
5447
5448SelectorID ASTWriter::getSelectorRef(Selector Sel) {
5449 if (Sel.getAsOpaquePtr() == nullptr) {
5450 return 0;
5451 }
5452
5453 SelectorID SID = SelectorIDs[Sel];
5454 if (SID == 0 && Chain) {
5455 // This might trigger a ReadSelector callback, which will set the ID for
5456 // this selector.
5457 Chain->LoadSelector(Sel);
5458 SID = SelectorIDs[Sel];
5459 }
5460 if (SID == 0) {
5461 SID = NextSelectorID++;
5462 SelectorIDs[Sel] = SID;
5463 }
5464 return SID;
5465}
5466
5467void ASTRecordWriter::AddCXXTemporary(const CXXTemporary *Temp) {
5468 AddDeclRef(Temp->getDestructor());
5469}
5470
5471void ASTRecordWriter::AddTemplateArgumentLocInfo(
5472 TemplateArgument::ArgKind Kind, const TemplateArgumentLocInfo &Arg) {
5473 switch (Kind) {
5474 case TemplateArgument::Expression:
5475 AddStmt(Arg.getAsExpr());
5476 break;
5477 case TemplateArgument::Type:
5478 AddTypeSourceInfo(Arg.getAsTypeSourceInfo());
5479 break;
5480 case TemplateArgument::Template:
5481 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
5482 AddSourceLocation(Arg.getTemplateNameLoc());
5483 break;
5484 case TemplateArgument::TemplateExpansion:
5485 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
5486 AddSourceLocation(Arg.getTemplateNameLoc());
5487 AddSourceLocation(Arg.getTemplateEllipsisLoc());
5488 break;
5489 case TemplateArgument::Null:
5490 case TemplateArgument::Integral:
5491 case TemplateArgument::Declaration:
5492 case TemplateArgument::NullPtr:
5493 case TemplateArgument::Pack:
5494 // FIXME: Is this right?
5495 break;
5496 }
5497}
5498
5499void ASTRecordWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg) {
5500 AddTemplateArgument(Arg.getArgument());
5501
5502 if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
5503 bool InfoHasSameExpr
5504 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
5505 Record->push_back(InfoHasSameExpr);
5506 if (InfoHasSameExpr)
5507 return; // Avoid storing the same expr twice.
5508 }
5509 AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo());
5510}
5511
5512void ASTRecordWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo) {
5513 if (!TInfo) {
5514 AddTypeRef(QualType());
5515 return;
5516 }
5517
5518 AddTypeRef(TInfo->getType());
5519 AddTypeLoc(TInfo->getTypeLoc());
5520}
5521
5522void ASTRecordWriter::AddTypeLoc(TypeLoc TL) {
5523 TypeLocWriter TLW(*this);
5524 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
5525 TLW.Visit(TL);
5526}
5527
5528void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
5529 Record.push_back(GetOrCreateTypeID(T));
5530}
5531
5532TypeID ASTWriter::GetOrCreateTypeID(QualType T) {
5533 assert(Context)((Context) ? static_cast<void> (0) : __assert_fail ("Context"
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 5533, __PRETTY_FUNCTION__))
;
5534 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
5535 if (T.isNull())
5536 return TypeIdx();
5537 assert(!T.getLocalFastQualifiers())((!T.getLocalFastQualifiers()) ? static_cast<void> (0) :
__assert_fail ("!T.getLocalFastQualifiers()", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 5537, __PRETTY_FUNCTION__))
;
5538
5539 TypeIdx &Idx = TypeIdxs[T];
5540 if (Idx.getIndex() == 0) {
5541 if (DoneWritingDeclsAndTypes) {
5542 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 5542, __PRETTY_FUNCTION__))
;
5543 return TypeIdx();
5544 }
5545
5546 // We haven't seen this type before. Assign it a new ID and put it
5547 // into the queue of types to emit.
5548 Idx = TypeIdx(NextTypeID++);
5549 DeclTypesToEmit.push(T);
5550 }
5551 return Idx;
5552 });
5553}
5554
5555TypeID ASTWriter::getTypeID(QualType T) const {
5556 assert(Context)((Context) ? static_cast<void> (0) : __assert_fail ("Context"
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 5556, __PRETTY_FUNCTION__))
;
5557 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
5558 if (T.isNull())
5559 return TypeIdx();
5560 assert(!T.getLocalFastQualifiers())((!T.getLocalFastQualifiers()) ? static_cast<void> (0) :
__assert_fail ("!T.getLocalFastQualifiers()", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 5560, __PRETTY_FUNCTION__))
;
5561
5562 TypeIdxMap::const_iterator I = TypeIdxs.find(T);
5563 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 5563, __PRETTY_FUNCTION__))
;
5564 return I->second;
5565 });
5566}
5567
5568void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
5569 Record.push_back(GetDeclRef(D));
5570}
5571
5572DeclID ASTWriter::GetDeclRef(const Decl *D) {
5573 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 5573, __PRETTY_FUNCTION__))
;
5574
5575 if (!D) {
5576 return 0;
5577 }
5578
5579 // If D comes from an AST file, its declaration ID is already known and
5580 // fixed.
5581 if (D->isFromASTFile())
5582 return D->getGlobalID();
5583
5584 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 5584, __PRETTY_FUNCTION__))
;
5585 DeclID &ID = DeclIDs[D];
5586 if (ID == 0) {
5587 if (DoneWritingDeclsAndTypes) {
5588 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 5588, __PRETTY_FUNCTION__))
;
5589 return 0;
5590 }
5591
5592 // We haven't seen this declaration before. Give it a new ID and
5593 // enqueue it in the list of declarations to emit.
5594 ID = NextDeclID++;
5595 DeclTypesToEmit.push(const_cast<Decl *>(D));
5596 }
5597
5598 return ID;
5599}
5600
5601DeclID ASTWriter::getDeclID(const Decl *D) {
5602 if (!D)
5603 return 0;
5604
5605 // If D comes from an AST file, its declaration ID is already known and
5606 // fixed.
5607 if (D->isFromASTFile())
5608 return D->getGlobalID();
5609
5610 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 5610, __PRETTY_FUNCTION__))
;
5611 return DeclIDs[D];
5612}
5613
5614void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) {
5615 assert(ID)((ID) ? static_cast<void> (0) : __assert_fail ("ID", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 5615, __PRETTY_FUNCTION__))
;
5616 assert(D)((D) ? static_cast<void> (0) : __assert_fail ("D", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 5616, __PRETTY_FUNCTION__))
;
5617
5618 SourceLocation Loc = D->getLocation();
5619 if (Loc.isInvalid())
5620 return;
5621
5622 // We only keep track of the file-level declarations of each file.
5623 if (!D->getLexicalDeclContext()->isFileContext())
5624 return;
5625 // FIXME: ParmVarDecls that are part of a function type of a parameter of
5626 // a function/objc method, should not have TU as lexical context.
5627 // TemplateTemplateParmDecls that are part of an alias template, should not
5628 // have TU as lexical context.
5629 if (isa<ParmVarDecl>(D) || isa<TemplateTemplateParmDecl>(D))
5630 return;
5631
5632 SourceManager &SM = Context->getSourceManager();
5633 SourceLocation FileLoc = SM.getFileLoc(Loc);
5634 assert(SM.isLocalSourceLocation(FileLoc))((SM.isLocalSourceLocation(FileLoc)) ? static_cast<void>
(0) : __assert_fail ("SM.isLocalSourceLocation(FileLoc)", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 5634, __PRETTY_FUNCTION__))
;
5635 FileID FID;
5636 unsigned Offset;
5637 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
5638 if (FID.isInvalid())
5639 return;
5640 assert(SM.getSLocEntry(FID).isFile())((SM.getSLocEntry(FID).isFile()) ? static_cast<void> (0
) : __assert_fail ("SM.getSLocEntry(FID).isFile()", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 5640, __PRETTY_FUNCTION__))
;
5641
5642 DeclIDInFileInfo *&Info = FileDeclIDs[FID];
5643 if (!Info)
5644 Info = new DeclIDInFileInfo();
5645
5646 std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID);
5647 LocDeclIDsTy &Decls = Info->DeclIDs;
5648
5649 if (Decls.empty() || Decls.back().first <= Offset) {
5650 Decls.push_back(LocDecl);
5651 return;
5652 }
5653
5654 LocDeclIDsTy::iterator I =
5655 std::upper_bound(Decls.begin(), Decls.end(), LocDecl, llvm::less_first());
5656
5657 Decls.insert(I, LocDecl);
5658}
5659
5660void ASTRecordWriter::AddDeclarationName(DeclarationName Name) {
5661 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
5662 Record->push_back(Name.getNameKind());
5663 switch (Name.getNameKind()) {
5664 case DeclarationName::Identifier:
5665 AddIdentifierRef(Name.getAsIdentifierInfo());
5666 break;
5667
5668 case DeclarationName::ObjCZeroArgSelector:
5669 case DeclarationName::ObjCOneArgSelector:
5670 case DeclarationName::ObjCMultiArgSelector:
5671 AddSelectorRef(Name.getObjCSelector());
5672 break;
5673
5674 case DeclarationName::CXXConstructorName:
5675 case DeclarationName::CXXDestructorName:
5676 case DeclarationName::CXXConversionFunctionName:
5677 AddTypeRef(Name.getCXXNameType());
5678 break;
5679
5680 case DeclarationName::CXXDeductionGuideName:
5681 AddDeclRef(Name.getCXXDeductionGuideTemplate());
5682 break;
5683
5684 case DeclarationName::CXXOperatorName:
5685 Record->push_back(Name.getCXXOverloadedOperator());
5686 break;
5687
5688 case DeclarationName::CXXLiteralOperatorName:
5689 AddIdentifierRef(Name.getCXXLiteralIdentifier());
5690 break;
5691
5692 case DeclarationName::CXXUsingDirective:
5693 // No extra data to emit
5694 break;
5695 }
5696}
5697
5698unsigned ASTWriter::getAnonymousDeclarationNumber(const NamedDecl *D) {
5699 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 5700, __PRETTY_FUNCTION__))
5700 "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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 5700, __PRETTY_FUNCTION__))
;
5701
5702 // Number the anonymous declarations within this context, if we've not
5703 // already done so.
5704 auto It = AnonymousDeclarationNumbers.find(D);
5705 if (It == AnonymousDeclarationNumbers.end()) {
5706 auto *DC = D->getLexicalDeclContext();
5707 numberAnonymousDeclsWithin(DC, [&](const NamedDecl *ND, unsigned Number) {
5708 AnonymousDeclarationNumbers[ND] = Number;
5709 });
5710
5711 It = AnonymousDeclarationNumbers.find(D);
5712 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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 5713, __PRETTY_FUNCTION__))
5713 "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-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 5713, __PRETTY_FUNCTION__))
;
5714 }
5715
5716 return It->second;
5717}
5718
5719void ASTRecordWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
5720 DeclarationName Name) {
5721 switch (Name.getNameKind()) {
5722 case DeclarationName::CXXConstructorName:
5723 case DeclarationName::CXXDestructorName:
5724 case DeclarationName::CXXConversionFunctionName:
5725 AddTypeSourceInfo(DNLoc.NamedType.TInfo);
5726 break;
5727
5728 case DeclarationName::CXXOperatorName:
5729 AddSourceLocation(SourceLocation::getFromRawEncoding(
5730 DNLoc.CXXOperatorName.BeginOpNameLoc));
5731 AddSourceLocation(
5732 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc));
5733 break;
5734
5735 case DeclarationName::CXXLiteralOperatorName:
5736 AddSourceLocation(SourceLocation::getFromRawEncoding(
5737 DNLoc.CXXLiteralOperatorName.OpNameLoc));
5738 break;
5739
5740 case DeclarationName::Identifier:
5741 case DeclarationName::ObjCZeroArgSelector:
5742 case DeclarationName::ObjCOneArgSelector:
5743 case DeclarationName::ObjCMultiArgSelector:
5744 case DeclarationName::CXXUsingDirective:
5745 case DeclarationName::CXXDeductionGuideName:
5746 break;
5747 }
5748}
5749
5750void ASTRecordWriter::AddDeclarationNameInfo(
5751 const DeclarationNameInfo &NameInfo) {
5752 AddDeclarationName(NameInfo.getName());
5753 AddSourceLocation(NameInfo.getLoc());
5754 AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName());
5755}
5756
5757void ASTRecordWriter::AddQualifierInfo(const QualifierInfo &Info) {
5758 AddNestedNameSpecifierLoc(Info.QualifierLoc);
5759 Record->push_back(Info.NumTemplParamLists);
5760 for (unsigned i = 0, e = Info.NumTemplParamLists; i != e; ++i)
5761 AddTemplateParameterList(Info.TemplParamLists[i]);
5762}
5763
5764void ASTRecordWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS) {
5765 // Nested name specifiers usually aren't too long. I think that 8 would
5766 // typically accommodate the vast majority.
5767 SmallVector<NestedNameSpecifier *, 8> NestedNames;
5768
5769 // Push each of the NNS's onto a stack for serialization in reverse order.
5770 while (NNS) {
5771 NestedNames.push_back(NNS);
5772 NNS = NNS->getPrefix();
5773 }
5774
5775 Record->push_back(NestedNames.size());
5776 while(!NestedNames.empty()) {
5777 NNS = NestedNames.pop_back_val();
5778 NestedNameSpecifier::SpecifierKind Kind = NNS->getKind();
5779 Record->push_back(Kind);
5780 switch (Kind) {
5781 case NestedNameSpecifier::Identifier:
5782 AddIdentifierRef(NNS->getAsIdentifier());
5783 break;
5784
5785 case NestedNameSpecifier::Namespace:
5786 AddDeclRef(NNS->getAsNamespace());
5787 break;
5788
5789 case NestedNameSpecifier::NamespaceAlias:
5790 AddDeclRef(NNS->getAsNamespaceAlias());
5791 break;
5792
5793 case NestedNameSpecifier::TypeSpec:
5794 case NestedNameSpecifier::TypeSpecWithTemplate:
5795 AddTypeRef(QualType(NNS->getAsType(), 0));
5796 Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5797 break;
5798
5799 case NestedNameSpecifier::Global:
5800 // Don't need to write an associated value.
5801 break;
5802
5803 case NestedNameSpecifier::Super:
5804 AddDeclRef(NNS->getAsRecordDecl());
5805 break;
5806 }
5807 }
5808}
5809
5810void ASTRecordWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
5811 // Nested name specifiers usually aren't too long. I think that 8 would
5812 // typically accommodate the vast majority.
5813 SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
5814
5815 // Push each of the nested-name-specifiers's onto a stack for
5816 // serialization in reverse order.
5817 while (NNS) {
5818 NestedNames.push_back(NNS);
5819 NNS = NNS.getPrefix();
5820 }
5821
5822 Record->push_back(NestedNames.size());
5823 while(!NestedNames.empty()) {
5824 NNS = NestedNames.pop_back_val();
5825 NestedNameSpecifier::SpecifierKind Kind
5826 = NNS.getNestedNameSpecifier()->getKind();
5827 Record->push_back(Kind);
5828 switch (Kind) {
5829 case NestedNameSpecifier::Identifier:
5830 AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier());
5831 AddSourceRange(NNS.getLocalSourceRange());
5832 break;
5833
5834 case NestedNameSpecifier::Namespace:
5835 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace());
5836 AddSourceRange(NNS.getLocalSourceRange());
5837 break;
5838
5839 case NestedNameSpecifier::NamespaceAlias:
5840 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias());
5841 AddSourceRange(NNS.getLocalSourceRange());
5842 break;
5843
5844 case NestedNameSpecifier::TypeSpec:
5845 case NestedNameSpecifier::TypeSpecWithTemplate:
5846 Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5847 AddTypeRef(NNS.getTypeLoc().getType());
5848 AddTypeLoc(NNS.getTypeLoc());
5849 AddSourceLocation(NNS.getLocalSourceRange().getEnd());
5850 break;
5851
5852 case NestedNameSpecifier::Global:
5853 AddSourceLocation(NNS.getLocalSourceRange().getEnd());
5854 break;
5855
5856 case NestedNameSpecifier::Super:
5857 AddDeclRef(NNS.getNestedNameSpecifier()->getAsRecordDecl());
5858 AddSourceRange(NNS.getLocalSourceRange());
5859 break;
5860 }
5861 }
5862}
5863
5864void ASTRecordWriter::AddTemplateName(TemplateName Name) {
5865 TemplateName::NameKind Kind = Name.getKind();
5866 Record->push_back(Kind);
5867 switch (Kind) {
5868 case TemplateName::Template:
5869 AddDeclRef(Name.getAsTemplateDecl());
5870 break;
5871
5872 case TemplateName::OverloadedTemplate: {
5873 OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate();
5874 Record->push_back(OvT->size());
5875 for (const auto &I : *OvT)
5876 AddDeclRef(I);
5877 break;
5878 }
5879
5880 case TemplateName::AssumedTemplate: {
5881 AssumedTemplateStorage *ADLT = Name.getAsAssumedTemplateName();
5882 AddDeclarationName(ADLT->getDeclName());
5883 break;
5884 }
5885
5886 case TemplateName::QualifiedTemplate: {
5887 QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName();
5888 AddNestedNameSpecifier(QualT->getQualifier());
5889 Record->push_back(QualT->hasTemplateKeyword());
5890 AddDeclRef(QualT->getTemplateDecl());
5891 break;
5892 }
5893
5894 case TemplateName::DependentTemplate: {
5895 DependentTemplateName *DepT = Name.getAsDependentTemplateName();
5896 AddNestedNameSpecifier(DepT->getQualifier());
5897 Record->push_back(DepT->isIdentifier());
5898 if (DepT->isIdentifier())
5899 AddIdentifierRef(DepT->getIdentifier());
5900 else
5901 Record->push_back(DepT->getOperator());
5902 break;
5903 }
5904
5905 case TemplateName::SubstTemplateTemplateParm: {
5906 SubstTemplateTemplateParmStorage *subst
5907 = Name.getAsSubstTemplateTemplateParm();
5908 AddDeclRef(subst->getParameter());
5909 AddTemplateName(subst->getReplacement());
5910 break;
5911 }
5912
5913 case TemplateName::SubstTemplateTemplateParmPack: {
5914 SubstTemplateTemplateParmPackStorage *SubstPack
5915 = Name.getAsSubstTemplateTemplateParmPack();
5916 AddDeclRef(SubstPack->getParameterPack());
5917 AddTemplateArgument(SubstPack->getArgumentPack());
5918 break;
5919 }
5920 }
5921}
5922
5923void ASTRecordWriter::AddTemplateArgument(const TemplateArgument &Arg) {
5924 Record->push_back(Arg.getKind());
5925 switch (Arg.getKind()) {
5926 case TemplateArgument::Null:
5927 break;
5928 case TemplateArgument::Type:
5929 AddTypeRef(Arg.getAsType());
5930 break;
5931 case TemplateArgument::Declaration:
5932 AddDeclRef(Arg.getAsDecl());
5933 AddTypeRef(Arg.getParamTypeForDecl());
5934 break;
5935 case TemplateArgument::NullPtr:
5936 AddTypeRef(Arg.getNullPtrType());
5937 break;
5938 case TemplateArgument::Integral:
5939 AddAPSInt(Arg.getAsIntegral());
5940 AddTypeRef(Arg.getIntegralType());
5941 break;
5942 case TemplateArgument::Template:
5943 AddTemplateName(Arg.getAsTemplateOrTemplatePattern());
5944 break;
5945 case TemplateArgument::TemplateExpansion:
5946 AddTemplateName(Arg.getAsTemplateOrTemplatePattern());
5947 if (Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions())
5948 Record->push_back(*NumExpansions + 1);
5949 else
5950 Record->push_back(0);
5951 break;
5952 case TemplateArgument::Expression:
5953 AddStmt(Arg.getAsExpr());
5954 break;
5955 case TemplateArgument::Pack:
5956 Record->push_back(Arg.pack_size());
5957 for (const auto &P : Arg.pack_elements())
5958 AddTemplateArgument(P);
5959 break;
5960 }
5961}
5962
5963void ASTRecordWriter::AddTemplateParameterList(
5964 const TemplateParameterList *TemplateParams) {
5965 assert(TemplateParams && "No TemplateParams!")((TemplateParams && "No TemplateParams!") ? static_cast
<void> (0) : __assert_fail ("TemplateParams && \"No TemplateParams!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 5965, __PRETTY_FUNCTION__))
;
5966 AddSourceLocation(TemplateParams->getTemplateLoc());
5967 AddSourceLocation(TemplateParams->getLAngleLoc());
5968 AddSourceLocation(TemplateParams->getRAngleLoc());
5969 // TODO: Concepts
5970 Record->push_back(TemplateParams->size());
5971 for (const auto &P : *TemplateParams)
5972 AddDeclRef(P);
5973}
5974
5975/// Emit a template argument list.
5976void ASTRecordWriter::AddTemplateArgumentList(
5977 const TemplateArgumentList *TemplateArgs) {
5978 assert(TemplateArgs && "No TemplateArgs!")((TemplateArgs && "No TemplateArgs!") ? static_cast<
void> (0) : __assert_fail ("TemplateArgs && \"No TemplateArgs!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 5978, __PRETTY_FUNCTION__))
;
5979 Record->push_back(TemplateArgs->size());
5980 for (int i = 0, e = TemplateArgs->size(); i != e; ++i)
5981 AddTemplateArgument(TemplateArgs->get(i));
5982}
5983
5984void ASTRecordWriter::AddASTTemplateArgumentListInfo(
5985 const ASTTemplateArgumentListInfo *ASTTemplArgList) {
5986 assert(ASTTemplArgList && "No ASTTemplArgList!")((ASTTemplArgList && "No ASTTemplArgList!") ? static_cast
<void> (0) : __assert_fail ("ASTTemplArgList && \"No ASTTemplArgList!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 5986, __PRETTY_FUNCTION__))
;
5987 AddSourceLocation(ASTTemplArgList->LAngleLoc);
5988 AddSourceLocation(ASTTemplArgList->RAngleLoc);
5989 Record->push_back(ASTTemplArgList->NumTemplateArgs);
5990 const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs();
5991 for (int i = 0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i)
5992 AddTemplateArgumentLoc(TemplArgs[i]);
5993}
5994
5995void ASTRecordWriter::AddUnresolvedSet(const ASTUnresolvedSet &Set) {
5996 Record->push_back(Set.size());
5997 for (ASTUnresolvedSet::const_iterator
5998 I = Set.begin(), E = Set.end(); I != E; ++I) {
5999 AddDeclRef(I.getDecl());
6000 Record->push_back(I.getAccess());
6001 }
6002}
6003
6004// FIXME: Move this out of the main ASTRecordWriter interface.
6005void ASTRecordWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base) {
6006 Record->push_back(Base.isVirtual());
6007 Record->push_back(Base.isBaseOfClass());
6008 Record->push_back(Base.getAccessSpecifierAsWritten());
6009 Record->push_back(Base.getInheritConstructors());
6010 AddTypeSourceInfo(Base.getTypeSourceInfo());
6011 AddSourceRange(Base.getSourceRange());
6012 AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
6013 : SourceLocation());
6014}
6015
6016static uint64_t EmitCXXBaseSpecifiers(ASTWriter &W,
6017 ArrayRef<CXXBaseSpecifier> Bases) {
6018 ASTWriter::RecordData Record;
6019 ASTRecordWriter Writer(W, Record);
6020 Writer.push_back(Bases.size());
6021
6022 for (auto &Base : Bases)
6023 Writer.AddCXXBaseSpecifier(Base);
6024
6025 return Writer.Emit(serialization::DECL_CXX_BASE_SPECIFIERS);
6026}
6027
6028// FIXME: Move this out of the main ASTRecordWriter interface.
6029void ASTRecordWriter::AddCXXBaseSpecifiers(ArrayRef<CXXBaseSpecifier> Bases) {
6030 AddOffset(EmitCXXBaseSpecifiers(*Writer, Bases));
6031}
6032
6033static uint64_t
6034EmitCXXCtorInitializers(ASTWriter &W,
6035 ArrayRef<CXXCtorInitializer *> CtorInits) {
6036 ASTWriter::RecordData Record;
6037 ASTRecordWriter Writer(W, Record);
6038 Writer.push_back(CtorInits.size());
6039
6040 for (auto *Init : CtorInits) {
6041 if (Init->isBaseInitializer()) {
6042 Writer.push_back(CTOR_INITIALIZER_BASE);
6043 Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
6044 Writer.push_back(Init->isBaseVirtual());
6045 } else if (Init->isDelegatingInitializer()) {
6046 Writer.push_back(CTOR_INITIALIZER_DELEGATING);
6047 Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
6048 } else if (Init->isMemberInitializer()){
6049 Writer.push_back(CTOR_INITIALIZER_MEMBER);
6050 Writer.AddDeclRef(Init->getMember());
6051 } else {
6052 Writer.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
6053 Writer.AddDeclRef(Init->getIndirectMember());
6054 }
6055
6056 Writer.AddSourceLocation(Init->getMemberLocation());
6057 Writer.AddStmt(Init->getInit());
6058 Writer.AddSourceLocation(Init->getLParenLoc());
6059 Writer.AddSourceLocation(Init->getRParenLoc());
6060 Writer.push_back(Init->isWritten());
6061 if (Init->isWritten())
6062 Writer.push_back(Init->getSourceOrder());
6063 }
6064
6065 return Writer.Emit(serialization::DECL_CXX_CTOR_INITIALIZERS);
6066}
6067
6068// FIXME: Move this out of the main ASTRecordWriter interface.
6069void ASTRecordWriter::AddCXXCtorInitializers(
6070 ArrayRef<CXXCtorInitializer *> CtorInits) {
6071 AddOffset(EmitCXXCtorInitializers(*Writer, CtorInits));
6072}
6073
6074void ASTRecordWriter::AddCXXDefinitionData(const CXXRecordDecl *D) {
6075 auto &Data = D->data();
6076 Record->push_back(Data.IsLambda);
6077 Record->push_back(Data.UserDeclaredConstructor);
6078 Record->push_back(Data.UserDeclaredSpecialMembers);
6079 Record->push_back(Data.Aggregate);
6080 Record->push_back(Data.PlainOldData);
6081 Record->push_back(Data.Empty);
6082 Record->push_back(Data.Polymorphic);
6083 Record->push_back(Data.Abstract);
6084 Record->push_back(Data.IsStandardLayout);
6085 Record->push_back(Data.IsCXX11StandardLayout);
6086 Record->push_back(Data.HasBasesWithFields);
6087 Record->push_back(Data.HasBasesWithNonStaticDataMembers);
6088 Record->push_back(Data.HasPrivateFields);
6089 Record->push_back(Data.HasProtectedFields);
6090 Record->push_back(Data.HasPublicFields);
6091 Record->push_back(Data.HasMutableFields);
6092 Record->push_back(Data.HasVariantMembers);
6093 Record->push_back(Data.HasOnlyCMembers);
6094 Record->push_back(Data.HasInClassInitializer);
6095 Record->push_back(Data.HasUninitializedReferenceMember);
6096 Record->push_back(Data.HasUninitializedFields);
6097 Record->push_back(Data.HasInheritedConstructor);
6098 Record->push_back(Data.HasInheritedAssignment);
6099 Record->push_back(Data.NeedOverloadResolutionForCopyConstructor);
6100 Record->push_back(Data.NeedOverloadResolutionForMoveConstructor);
6101 Record->push_back(Data.NeedOverloadResolutionForMoveAssignment);
6102 Record->push_back(Data.NeedOverloadResolutionForDestructor);
6103 Record->push_back(Data.DefaultedCopyConstructorIsDeleted);
6104 Record->push_back(Data.DefaultedMoveConstructorIsDeleted);
6105 Record->push_back(Data.DefaultedMoveAssignmentIsDeleted);
6106 Record->push_back(Data.DefaultedDestructorIsDeleted);
6107 Record->push_back(Data.HasTrivialSpecialMembers);
6108 Record->push_back(Data.HasTrivialSpecialMembersForCall);
6109 Record->push_back(Data.DeclaredNonTrivialSpecialMembers);
6110 Record->push_back(Data.DeclaredNonTrivialSpecialMembersForCall);
6111 Record->push_back(Data.HasIrrelevantDestructor);
6112 Record->push_back(Data.HasConstexprNonCopyMoveConstructor);
6113 Record->push_back(Data.HasDefaultedDefaultConstructor);
6114 Record->push_back(Data.DefaultedDefaultConstructorIsConstexpr);
6115 Record->push_back(Data.HasConstexprDefaultConstructor);
6116 Record->push_back(Data.HasNonLiteralTypeFieldsOrBases);
6117 Record->push_back(Data.ComputedVisibleConversions);
6118 Record->push_back(Data.UserProvidedDefaultConstructor);
6119 Record->push_back(Data.DeclaredSpecialMembers);
6120 Record->push_back(Data.ImplicitCopyConstructorCanHaveConstParamForVBase);
6121 Record->push_back(Data.ImplicitCopyConstructorCanHaveConstParamForNonVBase);
6122 Record->push_back(Data.ImplicitCopyAssignmentHasConstParam);
6123 Record->push_back(Data.HasDeclaredCopyConstructorWithConstParam);
6124 Record->push_back(Data.HasDeclaredCopyAssignmentWithConstParam);
6125
6126 // getODRHash will compute the ODRHash if it has not been previously computed.
6127 Record->push_back(D->getODRHash());
6128 bool ModulesDebugInfo = Writer->Context->getLangOpts().ModulesDebugInfo &&
6129 Writer->WritingModule && !D->isDependentType();
6130 Record->push_back(ModulesDebugInfo);
6131 if (ModulesDebugInfo)
6132 Writer->ModularCodegenDecls.push_back(Writer->GetDeclRef(D));
6133
6134 // IsLambda bit is already saved.
6135
6136 Record->push_back(Data.NumBases);
6137 if (Data.NumBases > 0)
6138 AddCXXBaseSpecifiers(Data.bases());
6139
6140 // FIXME: Make VBases lazily computed when needed to avoid storing them.
6141 Record->push_back(Data.NumVBases);
6142 if (Data.NumVBases > 0)
6143 AddCXXBaseSpecifiers(Data.vbases());
6144
6145 AddUnresolvedSet(Data.Conversions.get(*Writer->Context));
6146 AddUnresolvedSet(Data.VisibleConversions.get(*Writer->Context));
6147 // Data.Definition is the owning decl, no need to write it.
6148 AddDeclRef(D->getFirstFriend());
6149
6150 // Add lambda-specific data.
6151 if (Data.IsLambda) {
6152 auto &Lambda = D->getLambdaData();
6153 Record->push_back(Lambda.Dependent);
6154 Record->push_back(Lambda.IsGenericLambda);
6155 Record->push_back(Lambda.CaptureDefault);
6156 Record->push_back(Lambda.NumCaptures);
6157 Record->push_back(Lambda.NumExplicitCaptures);
6158 Record->push_back(Lambda.ManglingNumber);
6159 AddDeclRef(D->getLambdaContextDecl());
6160 AddTypeSourceInfo(Lambda.MethodTyInfo);
6161 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
6162 const LambdaCapture &Capture = Lambda.Captures[I];
6163 AddSourceLocation(Capture.getLocation());
6164 Record->push_back(Capture.isImplicit());
6165 Record->push_back(Capture.getCaptureKind());
6166 switch (Capture.getCaptureKind()) {
6167 case LCK_StarThis:
6168 case LCK_This:
6169 case LCK_VLAType:
6170 break;
6171 case LCK_ByCopy:
6172 case LCK_ByRef:
6173 VarDecl *Var =
6174 Capture.capturesVariable() ? Capture.getCapturedVar() : nullptr;
6175 AddDeclRef(Var);
6176 AddSourceLocation(Capture.isPackExpansion() ? Capture.getEllipsisLoc()
6177 : SourceLocation());
6178 break;
6179 }
6180 }
6181 }
6182}
6183
6184void ASTWriter::ReaderInitialized(ASTReader *Reader) {
6185 assert(Reader && "Cannot remove chain")((Reader && "Cannot remove chain") ? static_cast<void
> (0) : __assert_fail ("Reader && \"Cannot remove chain\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 6185, __PRETTY_FUNCTION__))
;
6186 assert((!Chain || Chain == Reader) && "Cannot replace chain")(((!Chain || Chain == Reader) && "Cannot replace chain"
) ? static_cast<void> (0) : __assert_fail ("(!Chain || Chain == Reader) && \"Cannot replace chain\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 6186, __PRETTY_FUNCTION__))
;
6187 assert(FirstDeclID == NextDeclID &&((FirstDeclID == NextDeclID && FirstTypeID == NextTypeID
&& FirstIdentID == NextIdentID && FirstMacroID
== NextMacroID && FirstSubmoduleID == NextSubmoduleID
&& FirstSelectorID == NextSelectorID && "Setting chain after writing has started."
) ? static_cast<void> (0) : __assert_fail ("FirstDeclID == NextDeclID && FirstTypeID == NextTypeID && FirstIdentID == NextIdentID && FirstMacroID == NextMacroID && FirstSubmoduleID == NextSubmoduleID && FirstSelectorID == NextSelectorID && \"Setting chain after writing has started.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 6193, __PRETTY_FUNCTION__))
6188 FirstTypeID == NextTypeID &&((FirstDeclID == NextDeclID && FirstTypeID == NextTypeID
&& FirstIdentID == NextIdentID && FirstMacroID
== NextMacroID && FirstSubmoduleID == NextSubmoduleID
&& FirstSelectorID == NextSelectorID && "Setting chain after writing has started."
) ? static_cast<void> (0) : __assert_fail ("FirstDeclID == NextDeclID && FirstTypeID == NextTypeID && FirstIdentID == NextIdentID && FirstMacroID == NextMacroID && FirstSubmoduleID == NextSubmoduleID && FirstSelectorID == NextSelectorID && \"Setting chain after writing has started.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 6193, __PRETTY_FUNCTION__))
6189 FirstIdentID == NextIdentID &&((FirstDeclID == NextDeclID && FirstTypeID == NextTypeID
&& FirstIdentID == NextIdentID && FirstMacroID
== NextMacroID && FirstSubmoduleID == NextSubmoduleID
&& FirstSelectorID == NextSelectorID && "Setting chain after writing has started."
) ? static_cast<void> (0) : __assert_fail ("FirstDeclID == NextDeclID && FirstTypeID == NextTypeID && FirstIdentID == NextIdentID && FirstMacroID == NextMacroID && FirstSubmoduleID == NextSubmoduleID && FirstSelectorID == NextSelectorID && \"Setting chain after writing has started.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 6193, __PRETTY_FUNCTION__))
6190 FirstMacroID == NextMacroID &&((FirstDeclID == NextDeclID && FirstTypeID == NextTypeID
&& FirstIdentID == NextIdentID && FirstMacroID
== NextMacroID && FirstSubmoduleID == NextSubmoduleID
&& FirstSelectorID == NextSelectorID && "Setting chain after writing has started."
) ? static_cast<void> (0) : __assert_fail ("FirstDeclID == NextDeclID && FirstTypeID == NextTypeID && FirstIdentID == NextIdentID && FirstMacroID == NextMacroID && FirstSubmoduleID == NextSubmoduleID && FirstSelectorID == NextSelectorID && \"Setting chain after writing has started.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 6193, __PRETTY_FUNCTION__))
6191 FirstSubmoduleID == NextSubmoduleID &&((FirstDeclID == NextDeclID && FirstTypeID == NextTypeID
&& FirstIdentID == NextIdentID && FirstMacroID
== NextMacroID && FirstSubmoduleID == NextSubmoduleID
&& FirstSelectorID == NextSelectorID && "Setting chain after writing has started."
) ? static_cast<void> (0) : __assert_fail ("FirstDeclID == NextDeclID && FirstTypeID == NextTypeID && FirstIdentID == NextIdentID && FirstMacroID == NextMacroID && FirstSubmoduleID == NextSubmoduleID && FirstSelectorID == NextSelectorID && \"Setting chain after writing has started.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 6193, __PRETTY_FUNCTION__))
6192 FirstSelectorID == NextSelectorID &&((FirstDeclID == NextDeclID && FirstTypeID == NextTypeID
&& FirstIdentID == NextIdentID && FirstMacroID
== NextMacroID && FirstSubmoduleID == NextSubmoduleID
&& FirstSelectorID == NextSelectorID && "Setting chain after writing has started."
) ? static_cast<void> (0) : __assert_fail ("FirstDeclID == NextDeclID && FirstTypeID == NextTypeID && FirstIdentID == NextIdentID && FirstMacroID == NextMacroID && FirstSubmoduleID == NextSubmoduleID && FirstSelectorID == NextSelectorID && \"Setting chain after writing has started.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 6193, __PRETTY_FUNCTION__))
6193 "Setting chain after writing has started.")((FirstDeclID == NextDeclID && FirstTypeID == NextTypeID
&& FirstIdentID == NextIdentID && FirstMacroID
== NextMacroID && FirstSubmoduleID == NextSubmoduleID
&& FirstSelectorID == NextSelectorID && "Setting chain after writing has started."
) ? static_cast<void> (0) : __assert_fail ("FirstDeclID == NextDeclID && FirstTypeID == NextTypeID && FirstIdentID == NextIdentID && FirstMacroID == NextMacroID && FirstSubmoduleID == NextSubmoduleID && FirstSelectorID == NextSelectorID && \"Setting chain after writing has started.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Serialization/ASTWriter.cpp"
, 6193, __PRETTY_FUNCTION__))
;
6194
6195 Chain = Reader;
6196
6197 // Note, this will get called multiple times, once one the reader starts up