1 //===--- ASTWriter.cpp - AST File Writer ----------------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the ASTWriter class, which writes AST files.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "clang/Serialization/ASTWriter.h"
15 #include "ASTCommon.h"
16 #include "clang/Sema/Sema.h"
17 #include "clang/Sema/IdentifierResolver.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclContextInternals.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/DeclFriend.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/Type.h"
26 #include "clang/AST/TypeLocVisitor.h"
27 #include "clang/Serialization/ASTReader.h"
28 #include "clang/Lex/MacroInfo.h"
29 #include "clang/Lex/PreprocessingRecord.h"
30 #include "clang/Lex/Preprocessor.h"
31 #include "clang/Lex/HeaderSearch.h"
32 #include "clang/Basic/FileManager.h"
33 #include "clang/Basic/FileSystemStatCache.h"
34 #include "clang/Basic/OnDiskHashTable.h"
35 #include "clang/Basic/SourceManager.h"
36 #include "clang/Basic/SourceManagerInternals.h"
37 #include "clang/Basic/TargetInfo.h"
38 #include "clang/Basic/Version.h"
39 #include "clang/Basic/VersionTuple.h"
40 #include "llvm/ADT/APFloat.h"
41 #include "llvm/ADT/APInt.h"
42 #include "llvm/ADT/StringExtras.h"
43 #include "llvm/Bitcode/BitstreamWriter.h"
44 #include "llvm/Support/FileSystem.h"
45 #include "llvm/Support/MemoryBuffer.h"
46 #include "llvm/Support/Path.h"
47 #include <algorithm>
48 #include <cstdio>
49 #include <string.h>
50 #include <utility>
51 using namespace clang;
52 using namespace clang::serialization;
53
54 template <typename T, typename Allocator>
data(const std::vector<T,Allocator> & v)55 static StringRef data(const std::vector<T, Allocator> &v) {
56 if (v.empty()) return StringRef();
57 return StringRef(reinterpret_cast<const char*>(&v[0]),
58 sizeof(T) * v.size());
59 }
60
61 template <typename T>
data(const SmallVectorImpl<T> & v)62 static StringRef data(const SmallVectorImpl<T> &v) {
63 return StringRef(reinterpret_cast<const char*>(v.data()),
64 sizeof(T) * v.size());
65 }
66
67 //===----------------------------------------------------------------------===//
68 // Type serialization
69 //===----------------------------------------------------------------------===//
70
71 namespace {
72 class ASTTypeWriter {
73 ASTWriter &Writer;
74 ASTWriter::RecordDataImpl &Record;
75
76 public:
77 /// \brief Type code that corresponds to the record generated.
78 TypeCode Code;
79
ASTTypeWriter(ASTWriter & Writer,ASTWriter::RecordDataImpl & Record)80 ASTTypeWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
81 : Writer(Writer), Record(Record), Code(TYPE_EXT_QUAL) { }
82
83 void VisitArrayType(const ArrayType *T);
84 void VisitFunctionType(const FunctionType *T);
85 void VisitTagType(const TagType *T);
86
87 #define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
88 #define ABSTRACT_TYPE(Class, Base)
89 #include "clang/AST/TypeNodes.def"
90 };
91 }
92
VisitBuiltinType(const BuiltinType * T)93 void ASTTypeWriter::VisitBuiltinType(const BuiltinType *T) {
94 llvm_unreachable("Built-in types are never serialized");
95 }
96
VisitComplexType(const ComplexType * T)97 void ASTTypeWriter::VisitComplexType(const ComplexType *T) {
98 Writer.AddTypeRef(T->getElementType(), Record);
99 Code = TYPE_COMPLEX;
100 }
101
VisitPointerType(const PointerType * T)102 void ASTTypeWriter::VisitPointerType(const PointerType *T) {
103 Writer.AddTypeRef(T->getPointeeType(), Record);
104 Code = TYPE_POINTER;
105 }
106
VisitBlockPointerType(const BlockPointerType * T)107 void ASTTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
108 Writer.AddTypeRef(T->getPointeeType(), Record);
109 Code = TYPE_BLOCK_POINTER;
110 }
111
VisitLValueReferenceType(const LValueReferenceType * T)112 void ASTTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
113 Writer.AddTypeRef(T->getPointeeTypeAsWritten(), Record);
114 Record.push_back(T->isSpelledAsLValue());
115 Code = TYPE_LVALUE_REFERENCE;
116 }
117
VisitRValueReferenceType(const RValueReferenceType * T)118 void ASTTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
119 Writer.AddTypeRef(T->getPointeeTypeAsWritten(), Record);
120 Code = TYPE_RVALUE_REFERENCE;
121 }
122
VisitMemberPointerType(const MemberPointerType * T)123 void ASTTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
124 Writer.AddTypeRef(T->getPointeeType(), Record);
125 Writer.AddTypeRef(QualType(T->getClass(), 0), Record);
126 Code = TYPE_MEMBER_POINTER;
127 }
128
VisitArrayType(const ArrayType * T)129 void ASTTypeWriter::VisitArrayType(const ArrayType *T) {
130 Writer.AddTypeRef(T->getElementType(), Record);
131 Record.push_back(T->getSizeModifier()); // FIXME: stable values
132 Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values
133 }
134
VisitConstantArrayType(const ConstantArrayType * T)135 void ASTTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
136 VisitArrayType(T);
137 Writer.AddAPInt(T->getSize(), Record);
138 Code = TYPE_CONSTANT_ARRAY;
139 }
140
VisitIncompleteArrayType(const IncompleteArrayType * T)141 void ASTTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
142 VisitArrayType(T);
143 Code = TYPE_INCOMPLETE_ARRAY;
144 }
145
VisitVariableArrayType(const VariableArrayType * T)146 void ASTTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
147 VisitArrayType(T);
148 Writer.AddSourceLocation(T->getLBracketLoc(), Record);
149 Writer.AddSourceLocation(T->getRBracketLoc(), Record);
150 Writer.AddStmt(T->getSizeExpr());
151 Code = TYPE_VARIABLE_ARRAY;
152 }
153
VisitVectorType(const VectorType * T)154 void ASTTypeWriter::VisitVectorType(const VectorType *T) {
155 Writer.AddTypeRef(T->getElementType(), Record);
156 Record.push_back(T->getNumElements());
157 Record.push_back(T->getVectorKind());
158 Code = TYPE_VECTOR;
159 }
160
VisitExtVectorType(const ExtVectorType * T)161 void ASTTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
162 VisitVectorType(T);
163 Code = TYPE_EXT_VECTOR;
164 }
165
VisitFunctionType(const FunctionType * T)166 void ASTTypeWriter::VisitFunctionType(const FunctionType *T) {
167 Writer.AddTypeRef(T->getResultType(), Record);
168 FunctionType::ExtInfo C = T->getExtInfo();
169 Record.push_back(C.getNoReturn());
170 Record.push_back(C.getHasRegParm());
171 Record.push_back(C.getRegParm());
172 // FIXME: need to stabilize encoding of calling convention...
173 Record.push_back(C.getCC());
174 Record.push_back(C.getProducesResult());
175 }
176
VisitFunctionNoProtoType(const FunctionNoProtoType * T)177 void ASTTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
178 VisitFunctionType(T);
179 Code = TYPE_FUNCTION_NO_PROTO;
180 }
181
VisitFunctionProtoType(const FunctionProtoType * T)182 void ASTTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
183 VisitFunctionType(T);
184 Record.push_back(T->getNumArgs());
185 for (unsigned I = 0, N = T->getNumArgs(); I != N; ++I)
186 Writer.AddTypeRef(T->getArgType(I), Record);
187 Record.push_back(T->isVariadic());
188 Record.push_back(T->hasTrailingReturn());
189 Record.push_back(T->getTypeQuals());
190 Record.push_back(static_cast<unsigned>(T->getRefQualifier()));
191 Record.push_back(T->getExceptionSpecType());
192 if (T->getExceptionSpecType() == EST_Dynamic) {
193 Record.push_back(T->getNumExceptions());
194 for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
195 Writer.AddTypeRef(T->getExceptionType(I), Record);
196 } else if (T->getExceptionSpecType() == EST_ComputedNoexcept) {
197 Writer.AddStmt(T->getNoexceptExpr());
198 } else if (T->getExceptionSpecType() == EST_Uninstantiated) {
199 Writer.AddDeclRef(T->getExceptionSpecDecl(), Record);
200 Writer.AddDeclRef(T->getExceptionSpecTemplate(), Record);
201 } else if (T->getExceptionSpecType() == EST_Unevaluated) {
202 Writer.AddDeclRef(T->getExceptionSpecDecl(), Record);
203 }
204 Code = TYPE_FUNCTION_PROTO;
205 }
206
VisitUnresolvedUsingType(const UnresolvedUsingType * T)207 void ASTTypeWriter::VisitUnresolvedUsingType(const UnresolvedUsingType *T) {
208 Writer.AddDeclRef(T->getDecl(), Record);
209 Code = TYPE_UNRESOLVED_USING;
210 }
211
VisitTypedefType(const TypedefType * T)212 void ASTTypeWriter::VisitTypedefType(const TypedefType *T) {
213 Writer.AddDeclRef(T->getDecl(), Record);
214 assert(!T->isCanonicalUnqualified() && "Invalid typedef ?");
215 Writer.AddTypeRef(T->getCanonicalTypeInternal(), Record);
216 Code = TYPE_TYPEDEF;
217 }
218
VisitTypeOfExprType(const TypeOfExprType * T)219 void ASTTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
220 Writer.AddStmt(T->getUnderlyingExpr());
221 Code = TYPE_TYPEOF_EXPR;
222 }
223
VisitTypeOfType(const TypeOfType * T)224 void ASTTypeWriter::VisitTypeOfType(const TypeOfType *T) {
225 Writer.AddTypeRef(T->getUnderlyingType(), Record);
226 Code = TYPE_TYPEOF;
227 }
228
VisitDecltypeType(const DecltypeType * T)229 void ASTTypeWriter::VisitDecltypeType(const DecltypeType *T) {
230 Writer.AddTypeRef(T->getUnderlyingType(), Record);
231 Writer.AddStmt(T->getUnderlyingExpr());
232 Code = TYPE_DECLTYPE;
233 }
234
VisitUnaryTransformType(const UnaryTransformType * T)235 void ASTTypeWriter::VisitUnaryTransformType(const UnaryTransformType *T) {
236 Writer.AddTypeRef(T->getBaseType(), Record);
237 Writer.AddTypeRef(T->getUnderlyingType(), Record);
238 Record.push_back(T->getUTTKind());
239 Code = TYPE_UNARY_TRANSFORM;
240 }
241
VisitAutoType(const AutoType * T)242 void ASTTypeWriter::VisitAutoType(const AutoType *T) {
243 Writer.AddTypeRef(T->getDeducedType(), Record);
244 Code = TYPE_AUTO;
245 }
246
VisitTagType(const TagType * T)247 void ASTTypeWriter::VisitTagType(const TagType *T) {
248 Record.push_back(T->isDependentType());
249 Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
250 assert(!T->isBeingDefined() &&
251 "Cannot serialize in the middle of a type definition");
252 }
253
VisitRecordType(const RecordType * T)254 void ASTTypeWriter::VisitRecordType(const RecordType *T) {
255 VisitTagType(T);
256 Code = TYPE_RECORD;
257 }
258
VisitEnumType(const EnumType * T)259 void ASTTypeWriter::VisitEnumType(const EnumType *T) {
260 VisitTagType(T);
261 Code = TYPE_ENUM;
262 }
263
VisitAttributedType(const AttributedType * T)264 void ASTTypeWriter::VisitAttributedType(const AttributedType *T) {
265 Writer.AddTypeRef(T->getModifiedType(), Record);
266 Writer.AddTypeRef(T->getEquivalentType(), Record);
267 Record.push_back(T->getAttrKind());
268 Code = TYPE_ATTRIBUTED;
269 }
270
271 void
VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType * T)272 ASTTypeWriter::VisitSubstTemplateTypeParmType(
273 const SubstTemplateTypeParmType *T) {
274 Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record);
275 Writer.AddTypeRef(T->getReplacementType(), Record);
276 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM;
277 }
278
279 void
VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType * T)280 ASTTypeWriter::VisitSubstTemplateTypeParmPackType(
281 const SubstTemplateTypeParmPackType *T) {
282 Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record);
283 Writer.AddTemplateArgument(T->getArgumentPack(), Record);
284 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK;
285 }
286
287 void
VisitTemplateSpecializationType(const TemplateSpecializationType * T)288 ASTTypeWriter::VisitTemplateSpecializationType(
289 const TemplateSpecializationType *T) {
290 Record.push_back(T->isDependentType());
291 Writer.AddTemplateName(T->getTemplateName(), Record);
292 Record.push_back(T->getNumArgs());
293 for (TemplateSpecializationType::iterator ArgI = T->begin(), ArgE = T->end();
294 ArgI != ArgE; ++ArgI)
295 Writer.AddTemplateArgument(*ArgI, Record);
296 Writer.AddTypeRef(T->isTypeAlias() ? T->getAliasedType() :
297 T->isCanonicalUnqualified() ? QualType()
298 : T->getCanonicalTypeInternal(),
299 Record);
300 Code = TYPE_TEMPLATE_SPECIALIZATION;
301 }
302
303 void
VisitDependentSizedArrayType(const DependentSizedArrayType * T)304 ASTTypeWriter::VisitDependentSizedArrayType(const DependentSizedArrayType *T) {
305 VisitArrayType(T);
306 Writer.AddStmt(T->getSizeExpr());
307 Writer.AddSourceRange(T->getBracketsRange(), Record);
308 Code = TYPE_DEPENDENT_SIZED_ARRAY;
309 }
310
311 void
VisitDependentSizedExtVectorType(const DependentSizedExtVectorType * T)312 ASTTypeWriter::VisitDependentSizedExtVectorType(
313 const DependentSizedExtVectorType *T) {
314 // FIXME: Serialize this type (C++ only)
315 llvm_unreachable("Cannot serialize dependent sized extended vector types");
316 }
317
318 void
VisitTemplateTypeParmType(const TemplateTypeParmType * T)319 ASTTypeWriter::VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
320 Record.push_back(T->getDepth());
321 Record.push_back(T->getIndex());
322 Record.push_back(T->isParameterPack());
323 Writer.AddDeclRef(T->getDecl(), Record);
324 Code = TYPE_TEMPLATE_TYPE_PARM;
325 }
326
327 void
VisitDependentNameType(const DependentNameType * T)328 ASTTypeWriter::VisitDependentNameType(const DependentNameType *T) {
329 Record.push_back(T->getKeyword());
330 Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
331 Writer.AddIdentifierRef(T->getIdentifier(), Record);
332 Writer.AddTypeRef(T->isCanonicalUnqualified() ? QualType()
333 : T->getCanonicalTypeInternal(),
334 Record);
335 Code = TYPE_DEPENDENT_NAME;
336 }
337
338 void
VisitDependentTemplateSpecializationType(const DependentTemplateSpecializationType * T)339 ASTTypeWriter::VisitDependentTemplateSpecializationType(
340 const DependentTemplateSpecializationType *T) {
341 Record.push_back(T->getKeyword());
342 Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
343 Writer.AddIdentifierRef(T->getIdentifier(), Record);
344 Record.push_back(T->getNumArgs());
345 for (DependentTemplateSpecializationType::iterator
346 I = T->begin(), E = T->end(); I != E; ++I)
347 Writer.AddTemplateArgument(*I, Record);
348 Code = TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION;
349 }
350
VisitPackExpansionType(const PackExpansionType * T)351 void ASTTypeWriter::VisitPackExpansionType(const PackExpansionType *T) {
352 Writer.AddTypeRef(T->getPattern(), Record);
353 if (llvm::Optional<unsigned> NumExpansions = T->getNumExpansions())
354 Record.push_back(*NumExpansions + 1);
355 else
356 Record.push_back(0);
357 Code = TYPE_PACK_EXPANSION;
358 }
359
VisitParenType(const ParenType * T)360 void ASTTypeWriter::VisitParenType(const ParenType *T) {
361 Writer.AddTypeRef(T->getInnerType(), Record);
362 Code = TYPE_PAREN;
363 }
364
VisitElaboratedType(const ElaboratedType * T)365 void ASTTypeWriter::VisitElaboratedType(const ElaboratedType *T) {
366 Record.push_back(T->getKeyword());
367 Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
368 Writer.AddTypeRef(T->getNamedType(), Record);
369 Code = TYPE_ELABORATED;
370 }
371
VisitInjectedClassNameType(const InjectedClassNameType * T)372 void ASTTypeWriter::VisitInjectedClassNameType(const InjectedClassNameType *T) {
373 Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
374 Writer.AddTypeRef(T->getInjectedSpecializationType(), Record);
375 Code = TYPE_INJECTED_CLASS_NAME;
376 }
377
VisitObjCInterfaceType(const ObjCInterfaceType * T)378 void ASTTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
379 Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
380 Code = TYPE_OBJC_INTERFACE;
381 }
382
VisitObjCObjectType(const ObjCObjectType * T)383 void ASTTypeWriter::VisitObjCObjectType(const ObjCObjectType *T) {
384 Writer.AddTypeRef(T->getBaseType(), Record);
385 Record.push_back(T->getNumProtocols());
386 for (ObjCObjectType::qual_iterator I = T->qual_begin(),
387 E = T->qual_end(); I != E; ++I)
388 Writer.AddDeclRef(*I, Record);
389 Code = TYPE_OBJC_OBJECT;
390 }
391
392 void
VisitObjCObjectPointerType(const ObjCObjectPointerType * T)393 ASTTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
394 Writer.AddTypeRef(T->getPointeeType(), Record);
395 Code = TYPE_OBJC_OBJECT_POINTER;
396 }
397
398 void
VisitAtomicType(const AtomicType * T)399 ASTTypeWriter::VisitAtomicType(const AtomicType *T) {
400 Writer.AddTypeRef(T->getValueType(), Record);
401 Code = TYPE_ATOMIC;
402 }
403
404 namespace {
405
406 class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
407 ASTWriter &Writer;
408 ASTWriter::RecordDataImpl &Record;
409
410 public:
TypeLocWriter(ASTWriter & Writer,ASTWriter::RecordDataImpl & Record)411 TypeLocWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
412 : Writer(Writer), Record(Record) { }
413
414 #define ABSTRACT_TYPELOC(CLASS, PARENT)
415 #define TYPELOC(CLASS, PARENT) \
416 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
417 #include "clang/AST/TypeLocNodes.def"
418
419 void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
420 void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
421 };
422
423 }
424
VisitQualifiedTypeLoc(QualifiedTypeLoc TL)425 void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
426 // nothing to do
427 }
VisitBuiltinTypeLoc(BuiltinTypeLoc TL)428 void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
429 Writer.AddSourceLocation(TL.getBuiltinLoc(), Record);
430 if (TL.needsExtraLocalData()) {
431 Record.push_back(TL.getWrittenTypeSpec());
432 Record.push_back(TL.getWrittenSignSpec());
433 Record.push_back(TL.getWrittenWidthSpec());
434 Record.push_back(TL.hasModeAttr());
435 }
436 }
VisitComplexTypeLoc(ComplexTypeLoc TL)437 void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
438 Writer.AddSourceLocation(TL.getNameLoc(), Record);
439 }
VisitPointerTypeLoc(PointerTypeLoc TL)440 void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
441 Writer.AddSourceLocation(TL.getStarLoc(), Record);
442 }
VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL)443 void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
444 Writer.AddSourceLocation(TL.getCaretLoc(), Record);
445 }
VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL)446 void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
447 Writer.AddSourceLocation(TL.getAmpLoc(), Record);
448 }
VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL)449 void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
450 Writer.AddSourceLocation(TL.getAmpAmpLoc(), Record);
451 }
VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL)452 void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
453 Writer.AddSourceLocation(TL.getStarLoc(), Record);
454 Writer.AddTypeSourceInfo(TL.getClassTInfo(), Record);
455 }
VisitArrayTypeLoc(ArrayTypeLoc TL)456 void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
457 Writer.AddSourceLocation(TL.getLBracketLoc(), Record);
458 Writer.AddSourceLocation(TL.getRBracketLoc(), Record);
459 Record.push_back(TL.getSizeExpr() ? 1 : 0);
460 if (TL.getSizeExpr())
461 Writer.AddStmt(TL.getSizeExpr());
462 }
VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL)463 void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
464 VisitArrayTypeLoc(TL);
465 }
VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL)466 void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
467 VisitArrayTypeLoc(TL);
468 }
VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL)469 void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
470 VisitArrayTypeLoc(TL);
471 }
VisitDependentSizedArrayTypeLoc(DependentSizedArrayTypeLoc TL)472 void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
473 DependentSizedArrayTypeLoc TL) {
474 VisitArrayTypeLoc(TL);
475 }
VisitDependentSizedExtVectorTypeLoc(DependentSizedExtVectorTypeLoc TL)476 void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
477 DependentSizedExtVectorTypeLoc TL) {
478 Writer.AddSourceLocation(TL.getNameLoc(), Record);
479 }
VisitVectorTypeLoc(VectorTypeLoc TL)480 void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
481 Writer.AddSourceLocation(TL.getNameLoc(), Record);
482 }
VisitExtVectorTypeLoc(ExtVectorTypeLoc TL)483 void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
484 Writer.AddSourceLocation(TL.getNameLoc(), Record);
485 }
VisitFunctionTypeLoc(FunctionTypeLoc TL)486 void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
487 Writer.AddSourceLocation(TL.getLocalRangeBegin(), Record);
488 Writer.AddSourceLocation(TL.getLocalRangeEnd(), Record);
489 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
490 Writer.AddDeclRef(TL.getArg(i), Record);
491 }
VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL)492 void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
493 VisitFunctionTypeLoc(TL);
494 }
VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL)495 void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
496 VisitFunctionTypeLoc(TL);
497 }
VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL)498 void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
499 Writer.AddSourceLocation(TL.getNameLoc(), Record);
500 }
VisitTypedefTypeLoc(TypedefTypeLoc TL)501 void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
502 Writer.AddSourceLocation(TL.getNameLoc(), Record);
503 }
VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL)504 void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
505 Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
506 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
507 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
508 }
VisitTypeOfTypeLoc(TypeOfTypeLoc TL)509 void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
510 Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
511 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
512 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
513 Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record);
514 }
VisitDecltypeTypeLoc(DecltypeTypeLoc TL)515 void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
516 Writer.AddSourceLocation(TL.getNameLoc(), Record);
517 }
VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL)518 void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
519 Writer.AddSourceLocation(TL.getKWLoc(), Record);
520 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
521 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
522 Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record);
523 }
VisitAutoTypeLoc(AutoTypeLoc TL)524 void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
525 Writer.AddSourceLocation(TL.getNameLoc(), Record);
526 }
VisitRecordTypeLoc(RecordTypeLoc TL)527 void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
528 Writer.AddSourceLocation(TL.getNameLoc(), Record);
529 }
VisitEnumTypeLoc(EnumTypeLoc TL)530 void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
531 Writer.AddSourceLocation(TL.getNameLoc(), Record);
532 }
VisitAttributedTypeLoc(AttributedTypeLoc TL)533 void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
534 Writer.AddSourceLocation(TL.getAttrNameLoc(), Record);
535 if (TL.hasAttrOperand()) {
536 SourceRange range = TL.getAttrOperandParensRange();
537 Writer.AddSourceLocation(range.getBegin(), Record);
538 Writer.AddSourceLocation(range.getEnd(), Record);
539 }
540 if (TL.hasAttrExprOperand()) {
541 Expr *operand = TL.getAttrExprOperand();
542 Record.push_back(operand ? 1 : 0);
543 if (operand) Writer.AddStmt(operand);
544 } else if (TL.hasAttrEnumOperand()) {
545 Writer.AddSourceLocation(TL.getAttrEnumOperandLoc(), Record);
546 }
547 }
VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL)548 void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
549 Writer.AddSourceLocation(TL.getNameLoc(), Record);
550 }
VisitSubstTemplateTypeParmTypeLoc(SubstTemplateTypeParmTypeLoc TL)551 void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
552 SubstTemplateTypeParmTypeLoc TL) {
553 Writer.AddSourceLocation(TL.getNameLoc(), Record);
554 }
VisitSubstTemplateTypeParmPackTypeLoc(SubstTemplateTypeParmPackTypeLoc TL)555 void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
556 SubstTemplateTypeParmPackTypeLoc TL) {
557 Writer.AddSourceLocation(TL.getNameLoc(), Record);
558 }
VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL)559 void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
560 TemplateSpecializationTypeLoc TL) {
561 Writer.AddSourceLocation(TL.getTemplateKeywordLoc(), Record);
562 Writer.AddSourceLocation(TL.getTemplateNameLoc(), Record);
563 Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
564 Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
565 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
566 Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
567 TL.getArgLoc(i).getLocInfo(), Record);
568 }
VisitParenTypeLoc(ParenTypeLoc TL)569 void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
570 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
571 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
572 }
VisitElaboratedTypeLoc(ElaboratedTypeLoc TL)573 void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
574 Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
575 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
576 }
VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL)577 void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
578 Writer.AddSourceLocation(TL.getNameLoc(), Record);
579 }
VisitDependentNameTypeLoc(DependentNameTypeLoc TL)580 void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
581 Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
582 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
583 Writer.AddSourceLocation(TL.getNameLoc(), Record);
584 }
VisitDependentTemplateSpecializationTypeLoc(DependentTemplateSpecializationTypeLoc TL)585 void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
586 DependentTemplateSpecializationTypeLoc TL) {
587 Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
588 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
589 Writer.AddSourceLocation(TL.getTemplateKeywordLoc(), Record);
590 Writer.AddSourceLocation(TL.getTemplateNameLoc(), Record);
591 Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
592 Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
593 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
594 Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
595 TL.getArgLoc(I).getLocInfo(), Record);
596 }
VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL)597 void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
598 Writer.AddSourceLocation(TL.getEllipsisLoc(), Record);
599 }
VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL)600 void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
601 Writer.AddSourceLocation(TL.getNameLoc(), Record);
602 }
VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL)603 void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
604 Record.push_back(TL.hasBaseTypeAsWritten());
605 Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
606 Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
607 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
608 Writer.AddSourceLocation(TL.getProtocolLoc(i), Record);
609 }
VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL)610 void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
611 Writer.AddSourceLocation(TL.getStarLoc(), Record);
612 }
VisitAtomicTypeLoc(AtomicTypeLoc TL)613 void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
614 Writer.AddSourceLocation(TL.getKWLoc(), Record);
615 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
616 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
617 }
618
619 //===----------------------------------------------------------------------===//
620 // ASTWriter Implementation
621 //===----------------------------------------------------------------------===//
622
EmitBlockID(unsigned ID,const char * Name,llvm::BitstreamWriter & Stream,ASTWriter::RecordDataImpl & Record)623 static void EmitBlockID(unsigned ID, const char *Name,
624 llvm::BitstreamWriter &Stream,
625 ASTWriter::RecordDataImpl &Record) {
626 Record.clear();
627 Record.push_back(ID);
628 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
629
630 // Emit the block name if present.
631 if (Name == 0 || Name[0] == 0) return;
632 Record.clear();
633 while (*Name)
634 Record.push_back(*Name++);
635 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
636 }
637
EmitRecordID(unsigned ID,const char * Name,llvm::BitstreamWriter & Stream,ASTWriter::RecordDataImpl & Record)638 static void EmitRecordID(unsigned ID, const char *Name,
639 llvm::BitstreamWriter &Stream,
640 ASTWriter::RecordDataImpl &Record) {
641 Record.clear();
642 Record.push_back(ID);
643 while (*Name)
644 Record.push_back(*Name++);
645 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
646 }
647
AddStmtsExprs(llvm::BitstreamWriter & Stream,ASTWriter::RecordDataImpl & Record)648 static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
649 ASTWriter::RecordDataImpl &Record) {
650 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
651 RECORD(STMT_STOP);
652 RECORD(STMT_NULL_PTR);
653 RECORD(STMT_NULL);
654 RECORD(STMT_COMPOUND);
655 RECORD(STMT_CASE);
656 RECORD(STMT_DEFAULT);
657 RECORD(STMT_LABEL);
658 RECORD(STMT_ATTRIBUTED);
659 RECORD(STMT_IF);
660 RECORD(STMT_SWITCH);
661 RECORD(STMT_WHILE);
662 RECORD(STMT_DO);
663 RECORD(STMT_FOR);
664 RECORD(STMT_GOTO);
665 RECORD(STMT_INDIRECT_GOTO);
666 RECORD(STMT_CONTINUE);
667 RECORD(STMT_BREAK);
668 RECORD(STMT_RETURN);
669 RECORD(STMT_DECL);
670 RECORD(STMT_GCCASM);
671 RECORD(STMT_MSASM);
672 RECORD(EXPR_PREDEFINED);
673 RECORD(EXPR_DECL_REF);
674 RECORD(EXPR_INTEGER_LITERAL);
675 RECORD(EXPR_FLOATING_LITERAL);
676 RECORD(EXPR_IMAGINARY_LITERAL);
677 RECORD(EXPR_STRING_LITERAL);
678 RECORD(EXPR_CHARACTER_LITERAL);
679 RECORD(EXPR_PAREN);
680 RECORD(EXPR_UNARY_OPERATOR);
681 RECORD(EXPR_SIZEOF_ALIGN_OF);
682 RECORD(EXPR_ARRAY_SUBSCRIPT);
683 RECORD(EXPR_CALL);
684 RECORD(EXPR_MEMBER);
685 RECORD(EXPR_BINARY_OPERATOR);
686 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
687 RECORD(EXPR_CONDITIONAL_OPERATOR);
688 RECORD(EXPR_IMPLICIT_CAST);
689 RECORD(EXPR_CSTYLE_CAST);
690 RECORD(EXPR_COMPOUND_LITERAL);
691 RECORD(EXPR_EXT_VECTOR_ELEMENT);
692 RECORD(EXPR_INIT_LIST);
693 RECORD(EXPR_DESIGNATED_INIT);
694 RECORD(EXPR_IMPLICIT_VALUE_INIT);
695 RECORD(EXPR_VA_ARG);
696 RECORD(EXPR_ADDR_LABEL);
697 RECORD(EXPR_STMT);
698 RECORD(EXPR_CHOOSE);
699 RECORD(EXPR_GNU_NULL);
700 RECORD(EXPR_SHUFFLE_VECTOR);
701 RECORD(EXPR_BLOCK);
702 RECORD(EXPR_GENERIC_SELECTION);
703 RECORD(EXPR_OBJC_STRING_LITERAL);
704 RECORD(EXPR_OBJC_BOXED_EXPRESSION);
705 RECORD(EXPR_OBJC_ARRAY_LITERAL);
706 RECORD(EXPR_OBJC_DICTIONARY_LITERAL);
707 RECORD(EXPR_OBJC_ENCODE);
708 RECORD(EXPR_OBJC_SELECTOR_EXPR);
709 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
710 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
711 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
712 RECORD(EXPR_OBJC_KVC_REF_EXPR);
713 RECORD(EXPR_OBJC_MESSAGE_EXPR);
714 RECORD(STMT_OBJC_FOR_COLLECTION);
715 RECORD(STMT_OBJC_CATCH);
716 RECORD(STMT_OBJC_FINALLY);
717 RECORD(STMT_OBJC_AT_TRY);
718 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
719 RECORD(STMT_OBJC_AT_THROW);
720 RECORD(EXPR_OBJC_BOOL_LITERAL);
721 RECORD(EXPR_CXX_OPERATOR_CALL);
722 RECORD(EXPR_CXX_CONSTRUCT);
723 RECORD(EXPR_CXX_STATIC_CAST);
724 RECORD(EXPR_CXX_DYNAMIC_CAST);
725 RECORD(EXPR_CXX_REINTERPRET_CAST);
726 RECORD(EXPR_CXX_CONST_CAST);
727 RECORD(EXPR_CXX_FUNCTIONAL_CAST);
728 RECORD(EXPR_USER_DEFINED_LITERAL);
729 RECORD(EXPR_CXX_BOOL_LITERAL);
730 RECORD(EXPR_CXX_NULL_PTR_LITERAL);
731 RECORD(EXPR_CXX_TYPEID_EXPR);
732 RECORD(EXPR_CXX_TYPEID_TYPE);
733 RECORD(EXPR_CXX_UUIDOF_EXPR);
734 RECORD(EXPR_CXX_UUIDOF_TYPE);
735 RECORD(EXPR_CXX_THIS);
736 RECORD(EXPR_CXX_THROW);
737 RECORD(EXPR_CXX_DEFAULT_ARG);
738 RECORD(EXPR_CXX_BIND_TEMPORARY);
739 RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
740 RECORD(EXPR_CXX_NEW);
741 RECORD(EXPR_CXX_DELETE);
742 RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
743 RECORD(EXPR_EXPR_WITH_CLEANUPS);
744 RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
745 RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
746 RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
747 RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
748 RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
749 RECORD(EXPR_CXX_UNARY_TYPE_TRAIT);
750 RECORD(EXPR_CXX_NOEXCEPT);
751 RECORD(EXPR_OPAQUE_VALUE);
752 RECORD(EXPR_BINARY_TYPE_TRAIT);
753 RECORD(EXPR_PACK_EXPANSION);
754 RECORD(EXPR_SIZEOF_PACK);
755 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
756 RECORD(EXPR_CUDA_KERNEL_CALL);
757 #undef RECORD
758 }
759
WriteBlockInfoBlock()760 void ASTWriter::WriteBlockInfoBlock() {
761 RecordData Record;
762 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
763
764 #define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
765 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
766
767 // AST Top-Level Block.
768 BLOCK(AST_BLOCK);
769 RECORD(ORIGINAL_FILE_NAME);
770 RECORD(ORIGINAL_FILE_ID);
771 RECORD(TYPE_OFFSET);
772 RECORD(DECL_OFFSET);
773 RECORD(LANGUAGE_OPTIONS);
774 RECORD(METADATA);
775 RECORD(IDENTIFIER_OFFSET);
776 RECORD(IDENTIFIER_TABLE);
777 RECORD(EXTERNAL_DEFINITIONS);
778 RECORD(SPECIAL_TYPES);
779 RECORD(STATISTICS);
780 RECORD(TENTATIVE_DEFINITIONS);
781 RECORD(UNUSED_FILESCOPED_DECLS);
782 RECORD(LOCALLY_SCOPED_EXTERNAL_DECLS);
783 RECORD(SELECTOR_OFFSETS);
784 RECORD(METHOD_POOL);
785 RECORD(PP_COUNTER_VALUE);
786 RECORD(SOURCE_LOCATION_OFFSETS);
787 RECORD(SOURCE_LOCATION_PRELOADS);
788 RECORD(STAT_CACHE);
789 RECORD(EXT_VECTOR_DECLS);
790 RECORD(VERSION_CONTROL_BRANCH_REVISION);
791 RECORD(PPD_ENTITIES_OFFSETS);
792 RECORD(IMPORTS);
793 RECORD(REFERENCED_SELECTOR_POOL);
794 RECORD(TU_UPDATE_LEXICAL);
795 RECORD(LOCAL_REDECLARATIONS_MAP);
796 RECORD(SEMA_DECL_REFS);
797 RECORD(WEAK_UNDECLARED_IDENTIFIERS);
798 RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
799 RECORD(DECL_REPLACEMENTS);
800 RECORD(UPDATE_VISIBLE);
801 RECORD(DECL_UPDATE_OFFSETS);
802 RECORD(DECL_UPDATES);
803 RECORD(CXX_BASE_SPECIFIER_OFFSETS);
804 RECORD(DIAG_PRAGMA_MAPPINGS);
805 RECORD(CUDA_SPECIAL_DECL_REFS);
806 RECORD(HEADER_SEARCH_TABLE);
807 RECORD(ORIGINAL_PCH_DIR);
808 RECORD(FP_PRAGMA_OPTIONS);
809 RECORD(OPENCL_EXTENSIONS);
810 RECORD(DELEGATING_CTORS);
811 RECORD(FILE_SOURCE_LOCATION_OFFSETS);
812 RECORD(KNOWN_NAMESPACES);
813 RECORD(MODULE_OFFSET_MAP);
814 RECORD(SOURCE_MANAGER_LINE_TABLE);
815 RECORD(OBJC_CATEGORIES_MAP);
816 RECORD(FILE_SORTED_DECLS);
817 RECORD(IMPORTED_MODULES);
818 RECORD(MERGED_DECLARATIONS);
819 RECORD(LOCAL_REDECLARATIONS);
820 RECORD(OBJC_CATEGORIES);
821
822 // SourceManager Block.
823 BLOCK(SOURCE_MANAGER_BLOCK);
824 RECORD(SM_SLOC_FILE_ENTRY);
825 RECORD(SM_SLOC_BUFFER_ENTRY);
826 RECORD(SM_SLOC_BUFFER_BLOB);
827 RECORD(SM_SLOC_EXPANSION_ENTRY);
828
829 // Preprocessor Block.
830 BLOCK(PREPROCESSOR_BLOCK);
831 RECORD(PP_MACRO_OBJECT_LIKE);
832 RECORD(PP_MACRO_FUNCTION_LIKE);
833 RECORD(PP_TOKEN);
834
835 // Decls and Types block.
836 BLOCK(DECLTYPES_BLOCK);
837 RECORD(TYPE_EXT_QUAL);
838 RECORD(TYPE_COMPLEX);
839 RECORD(TYPE_POINTER);
840 RECORD(TYPE_BLOCK_POINTER);
841 RECORD(TYPE_LVALUE_REFERENCE);
842 RECORD(TYPE_RVALUE_REFERENCE);
843 RECORD(TYPE_MEMBER_POINTER);
844 RECORD(TYPE_CONSTANT_ARRAY);
845 RECORD(TYPE_INCOMPLETE_ARRAY);
846 RECORD(TYPE_VARIABLE_ARRAY);
847 RECORD(TYPE_VECTOR);
848 RECORD(TYPE_EXT_VECTOR);
849 RECORD(TYPE_FUNCTION_PROTO);
850 RECORD(TYPE_FUNCTION_NO_PROTO);
851 RECORD(TYPE_TYPEDEF);
852 RECORD(TYPE_TYPEOF_EXPR);
853 RECORD(TYPE_TYPEOF);
854 RECORD(TYPE_RECORD);
855 RECORD(TYPE_ENUM);
856 RECORD(TYPE_OBJC_INTERFACE);
857 RECORD(TYPE_OBJC_OBJECT);
858 RECORD(TYPE_OBJC_OBJECT_POINTER);
859 RECORD(TYPE_DECLTYPE);
860 RECORD(TYPE_ELABORATED);
861 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
862 RECORD(TYPE_UNRESOLVED_USING);
863 RECORD(TYPE_INJECTED_CLASS_NAME);
864 RECORD(TYPE_OBJC_OBJECT);
865 RECORD(TYPE_TEMPLATE_TYPE_PARM);
866 RECORD(TYPE_TEMPLATE_SPECIALIZATION);
867 RECORD(TYPE_DEPENDENT_NAME);
868 RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
869 RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
870 RECORD(TYPE_PAREN);
871 RECORD(TYPE_PACK_EXPANSION);
872 RECORD(TYPE_ATTRIBUTED);
873 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
874 RECORD(TYPE_ATOMIC);
875 RECORD(DECL_TYPEDEF);
876 RECORD(DECL_ENUM);
877 RECORD(DECL_RECORD);
878 RECORD(DECL_ENUM_CONSTANT);
879 RECORD(DECL_FUNCTION);
880 RECORD(DECL_OBJC_METHOD);
881 RECORD(DECL_OBJC_INTERFACE);
882 RECORD(DECL_OBJC_PROTOCOL);
883 RECORD(DECL_OBJC_IVAR);
884 RECORD(DECL_OBJC_AT_DEFS_FIELD);
885 RECORD(DECL_OBJC_CATEGORY);
886 RECORD(DECL_OBJC_CATEGORY_IMPL);
887 RECORD(DECL_OBJC_IMPLEMENTATION);
888 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
889 RECORD(DECL_OBJC_PROPERTY);
890 RECORD(DECL_OBJC_PROPERTY_IMPL);
891 RECORD(DECL_FIELD);
892 RECORD(DECL_VAR);
893 RECORD(DECL_IMPLICIT_PARAM);
894 RECORD(DECL_PARM_VAR);
895 RECORD(DECL_FILE_SCOPE_ASM);
896 RECORD(DECL_BLOCK);
897 RECORD(DECL_CONTEXT_LEXICAL);
898 RECORD(DECL_CONTEXT_VISIBLE);
899 RECORD(DECL_NAMESPACE);
900 RECORD(DECL_NAMESPACE_ALIAS);
901 RECORD(DECL_USING);
902 RECORD(DECL_USING_SHADOW);
903 RECORD(DECL_USING_DIRECTIVE);
904 RECORD(DECL_UNRESOLVED_USING_VALUE);
905 RECORD(DECL_UNRESOLVED_USING_TYPENAME);
906 RECORD(DECL_LINKAGE_SPEC);
907 RECORD(DECL_CXX_RECORD);
908 RECORD(DECL_CXX_METHOD);
909 RECORD(DECL_CXX_CONSTRUCTOR);
910 RECORD(DECL_CXX_DESTRUCTOR);
911 RECORD(DECL_CXX_CONVERSION);
912 RECORD(DECL_ACCESS_SPEC);
913 RECORD(DECL_FRIEND);
914 RECORD(DECL_FRIEND_TEMPLATE);
915 RECORD(DECL_CLASS_TEMPLATE);
916 RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
917 RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
918 RECORD(DECL_FUNCTION_TEMPLATE);
919 RECORD(DECL_TEMPLATE_TYPE_PARM);
920 RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
921 RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
922 RECORD(DECL_STATIC_ASSERT);
923 RECORD(DECL_CXX_BASE_SPECIFIERS);
924 RECORD(DECL_INDIRECTFIELD);
925 RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
926
927 // Statements and Exprs can occur in the Decls and Types block.
928 AddStmtsExprs(Stream, Record);
929
930 BLOCK(PREPROCESSOR_DETAIL_BLOCK);
931 RECORD(PPD_MACRO_EXPANSION);
932 RECORD(PPD_MACRO_DEFINITION);
933 RECORD(PPD_INCLUSION_DIRECTIVE);
934
935 #undef RECORD
936 #undef BLOCK
937 Stream.ExitBlock();
938 }
939
940 /// \brief Adjusts the given filename to only write out the portion of the
941 /// filename that is not part of the system root directory.
942 ///
943 /// \param Filename the file name to adjust.
944 ///
945 /// \param isysroot When non-NULL, the PCH file is a relocatable PCH file and
946 /// the returned filename will be adjusted by this system root.
947 ///
948 /// \returns either the original filename (if it needs no adjustment) or the
949 /// adjusted filename (which points into the @p Filename parameter).
950 static const char *
adjustFilenameForRelocatablePCH(const char * Filename,StringRef isysroot)951 adjustFilenameForRelocatablePCH(const char *Filename, StringRef isysroot) {
952 assert(Filename && "No file name to adjust?");
953
954 if (isysroot.empty())
955 return Filename;
956
957 // Verify that the filename and the system root have the same prefix.
958 unsigned Pos = 0;
959 for (; Filename[Pos] && Pos < isysroot.size(); ++Pos)
960 if (Filename[Pos] != isysroot[Pos])
961 return Filename; // Prefixes don't match.
962
963 // We hit the end of the filename before we hit the end of the system root.
964 if (!Filename[Pos])
965 return Filename;
966
967 // If the file name has a '/' at the current position, skip over the '/'.
968 // We distinguish sysroot-based includes from absolute includes by the
969 // absence of '/' at the beginning of sysroot-based includes.
970 if (Filename[Pos] == '/')
971 ++Pos;
972
973 return Filename + Pos;
974 }
975
976 /// \brief Write the AST metadata (e.g., i686-apple-darwin9).
WriteMetadata(ASTContext & Context,StringRef isysroot,const std::string & OutputFile)977 void ASTWriter::WriteMetadata(ASTContext &Context, StringRef isysroot,
978 const std::string &OutputFile) {
979 using namespace llvm;
980
981 // Metadata
982 const TargetInfo &Target = Context.getTargetInfo();
983 BitCodeAbbrev *MetaAbbrev = new BitCodeAbbrev();
984 MetaAbbrev->Add(BitCodeAbbrevOp(METADATA));
985 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // AST major
986 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // AST minor
987 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang major
988 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang minor
989 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
990 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Has errors
991 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Target triple
992 unsigned MetaAbbrevCode = Stream.EmitAbbrev(MetaAbbrev);
993
994 RecordData Record;
995 Record.push_back(METADATA);
996 Record.push_back(VERSION_MAJOR);
997 Record.push_back(VERSION_MINOR);
998 Record.push_back(CLANG_VERSION_MAJOR);
999 Record.push_back(CLANG_VERSION_MINOR);
1000 Record.push_back(!isysroot.empty());
1001 Record.push_back(ASTHasCompilerErrors);
1002 const std::string &Triple = Target.getTriple().getTriple();
1003 Stream.EmitRecordWithBlob(MetaAbbrevCode, Record, Triple);
1004
1005 if (Chain) {
1006 serialization::ModuleManager &Mgr = Chain->getModuleManager();
1007 llvm::SmallVector<char, 128> ModulePaths;
1008 Record.clear();
1009
1010 for (ModuleManager::ModuleIterator M = Mgr.begin(), MEnd = Mgr.end();
1011 M != MEnd; ++M) {
1012 // Skip modules that weren't directly imported.
1013 if (!(*M)->isDirectlyImported())
1014 continue;
1015
1016 Record.push_back((unsigned)(*M)->Kind); // FIXME: Stable encoding
1017 // FIXME: Write import location, once it matters.
1018 // FIXME: This writes the absolute path for AST files we depend on.
1019 const std::string &FileName = (*M)->FileName;
1020 Record.push_back(FileName.size());
1021 Record.append(FileName.begin(), FileName.end());
1022 }
1023 Stream.EmitRecord(IMPORTS, Record);
1024 }
1025
1026 // Original file name and file ID
1027 SourceManager &SM = Context.getSourceManager();
1028 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1029 BitCodeAbbrev *FileAbbrev = new BitCodeAbbrev();
1030 FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE_NAME));
1031 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1032 unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
1033
1034 SmallString<128> MainFilePath(MainFile->getName());
1035
1036 llvm::sys::fs::make_absolute(MainFilePath);
1037
1038 const char *MainFileNameStr = MainFilePath.c_str();
1039 MainFileNameStr = adjustFilenameForRelocatablePCH(MainFileNameStr,
1040 isysroot);
1041 RecordData Record;
1042 Record.push_back(ORIGINAL_FILE_NAME);
1043 Stream.EmitRecordWithBlob(FileAbbrevCode, Record, MainFileNameStr);
1044
1045 Record.clear();
1046 Record.push_back(SM.getMainFileID().getOpaqueValue());
1047 Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
1048 }
1049
1050 // Original PCH directory
1051 if (!OutputFile.empty() && OutputFile != "-") {
1052 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1053 Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR));
1054 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1055 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
1056
1057 SmallString<128> OutputPath(OutputFile);
1058
1059 llvm::sys::fs::make_absolute(OutputPath);
1060 StringRef origDir = llvm::sys::path::parent_path(OutputPath);
1061
1062 RecordData Record;
1063 Record.push_back(ORIGINAL_PCH_DIR);
1064 Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir);
1065 }
1066
1067 // Repository branch/version information.
1068 BitCodeAbbrev *RepoAbbrev = new BitCodeAbbrev();
1069 RepoAbbrev->Add(BitCodeAbbrevOp(VERSION_CONTROL_BRANCH_REVISION));
1070 RepoAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
1071 unsigned RepoAbbrevCode = Stream.EmitAbbrev(RepoAbbrev);
1072 Record.clear();
1073 Record.push_back(VERSION_CONTROL_BRANCH_REVISION);
1074 Stream.EmitRecordWithBlob(RepoAbbrevCode, Record,
1075 getClangFullRepositoryVersion());
1076 }
1077
1078 /// \brief Write the LangOptions structure.
WriteLanguageOptions(const LangOptions & LangOpts)1079 void ASTWriter::WriteLanguageOptions(const LangOptions &LangOpts) {
1080 RecordData Record;
1081 #define LANGOPT(Name, Bits, Default, Description) \
1082 Record.push_back(LangOpts.Name);
1083 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
1084 Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
1085 #include "clang/Basic/LangOptions.def"
1086
1087 Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind());
1088 AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record);
1089
1090 Record.push_back(LangOpts.CurrentModule.size());
1091 Record.append(LangOpts.CurrentModule.begin(), LangOpts.CurrentModule.end());
1092 Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1093 }
1094
1095 //===----------------------------------------------------------------------===//
1096 // stat cache Serialization
1097 //===----------------------------------------------------------------------===//
1098
1099 namespace {
1100 // Trait used for the on-disk hash table of stat cache results.
1101 class ASTStatCacheTrait {
1102 public:
1103 typedef const char * key_type;
1104 typedef key_type key_type_ref;
1105
1106 typedef struct stat data_type;
1107 typedef const data_type &data_type_ref;
1108
ComputeHash(const char * path)1109 static unsigned ComputeHash(const char *path) {
1110 return llvm::HashString(path);
1111 }
1112
1113 std::pair<unsigned,unsigned>
EmitKeyDataLength(raw_ostream & Out,const char * path,data_type_ref Data)1114 EmitKeyDataLength(raw_ostream& Out, const char *path,
1115 data_type_ref Data) {
1116 unsigned StrLen = strlen(path);
1117 clang::io::Emit16(Out, StrLen);
1118 unsigned DataLen = 4 + 4 + 2 + 8 + 8;
1119 clang::io::Emit8(Out, DataLen);
1120 return std::make_pair(StrLen + 1, DataLen);
1121 }
1122
EmitKey(raw_ostream & Out,const char * path,unsigned KeyLen)1123 void EmitKey(raw_ostream& Out, const char *path, unsigned KeyLen) {
1124 Out.write(path, KeyLen);
1125 }
1126
EmitData(raw_ostream & Out,key_type_ref,data_type_ref Data,unsigned DataLen)1127 void EmitData(raw_ostream &Out, key_type_ref,
1128 data_type_ref Data, unsigned DataLen) {
1129 using namespace clang::io;
1130 uint64_t Start = Out.tell(); (void)Start;
1131
1132 Emit32(Out, (uint32_t) Data.st_ino);
1133 Emit32(Out, (uint32_t) Data.st_dev);
1134 Emit16(Out, (uint16_t) Data.st_mode);
1135 Emit64(Out, (uint64_t) Data.st_mtime);
1136 Emit64(Out, (uint64_t) Data.st_size);
1137
1138 assert(Out.tell() - Start == DataLen && "Wrong data length");
1139 }
1140 };
1141 } // end anonymous namespace
1142
1143 /// \brief Write the stat() system call cache to the AST file.
WriteStatCache(MemorizeStatCalls & StatCalls)1144 void ASTWriter::WriteStatCache(MemorizeStatCalls &StatCalls) {
1145 // Build the on-disk hash table containing information about every
1146 // stat() call.
1147 OnDiskChainedHashTableGenerator<ASTStatCacheTrait> Generator;
1148 unsigned NumStatEntries = 0;
1149 for (MemorizeStatCalls::iterator Stat = StatCalls.begin(),
1150 StatEnd = StatCalls.end();
1151 Stat != StatEnd; ++Stat, ++NumStatEntries) {
1152 StringRef Filename = Stat->first();
1153 Generator.insert(Filename.data(), Stat->second);
1154 }
1155
1156 // Create the on-disk hash table in a buffer.
1157 SmallString<4096> StatCacheData;
1158 uint32_t BucketOffset;
1159 {
1160 llvm::raw_svector_ostream Out(StatCacheData);
1161 // Make sure that no bucket is at offset 0
1162 clang::io::Emit32(Out, 0);
1163 BucketOffset = Generator.Emit(Out);
1164 }
1165
1166 // Create a blob abbreviation
1167 using namespace llvm;
1168 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1169 Abbrev->Add(BitCodeAbbrevOp(STAT_CACHE));
1170 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1171 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1172 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1173 unsigned StatCacheAbbrev = Stream.EmitAbbrev(Abbrev);
1174
1175 // Write the stat cache
1176 RecordData Record;
1177 Record.push_back(STAT_CACHE);
1178 Record.push_back(BucketOffset);
1179 Record.push_back(NumStatEntries);
1180 Stream.EmitRecordWithBlob(StatCacheAbbrev, Record, StatCacheData.str());
1181 }
1182
1183 //===----------------------------------------------------------------------===//
1184 // Source Manager Serialization
1185 //===----------------------------------------------------------------------===//
1186
1187 /// \brief Create an abbreviation for the SLocEntry that refers to a
1188 /// file.
CreateSLocFileAbbrev(llvm::BitstreamWriter & Stream)1189 static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
1190 using namespace llvm;
1191 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1192 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
1193 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1194 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1195 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1196 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1197 // FileEntry fields.
1198 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1199 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
1200 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // BufferOverridden
1201 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
1202 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
1203 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
1204 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1205 return Stream.EmitAbbrev(Abbrev);
1206 }
1207
1208 /// \brief Create an abbreviation for the SLocEntry that refers to a
1209 /// buffer.
CreateSLocBufferAbbrev(llvm::BitstreamWriter & Stream)1210 static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
1211 using namespace llvm;
1212 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1213 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
1214 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1215 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1216 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1217 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1218 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
1219 return Stream.EmitAbbrev(Abbrev);
1220 }
1221
1222 /// \brief Create an abbreviation for the SLocEntry that refers to a
1223 /// buffer's blob.
CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter & Stream)1224 static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
1225 using namespace llvm;
1226 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1227 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_BLOB));
1228 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
1229 return Stream.EmitAbbrev(Abbrev);
1230 }
1231
1232 /// \brief Create an abbreviation for the SLocEntry that refers to a macro
1233 /// expansion.
CreateSLocExpansionAbbrev(llvm::BitstreamWriter & Stream)1234 static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
1235 using namespace llvm;
1236 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1237 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
1238 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1239 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1240 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
1241 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
1242 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
1243 return Stream.EmitAbbrev(Abbrev);
1244 }
1245
1246 namespace {
1247 // Trait used for the on-disk hash table of header search information.
1248 class HeaderFileInfoTrait {
1249 ASTWriter &Writer;
1250
1251 // Keep track of the framework names we've used during serialization.
1252 SmallVector<char, 128> FrameworkStringData;
1253 llvm::StringMap<unsigned> FrameworkNameOffset;
1254
1255 public:
HeaderFileInfoTrait(ASTWriter & Writer)1256 HeaderFileInfoTrait(ASTWriter &Writer)
1257 : Writer(Writer) { }
1258
1259 typedef const char *key_type;
1260 typedef key_type key_type_ref;
1261
1262 typedef HeaderFileInfo data_type;
1263 typedef const data_type &data_type_ref;
1264
ComputeHash(const char * path)1265 static unsigned ComputeHash(const char *path) {
1266 // The hash is based only on the filename portion of the key, so that the
1267 // reader can match based on filenames when symlinking or excess path
1268 // elements ("foo/../", "../") change the form of the name. However,
1269 // complete path is still the key.
1270 return llvm::HashString(llvm::sys::path::filename(path));
1271 }
1272
1273 std::pair<unsigned,unsigned>
EmitKeyDataLength(raw_ostream & Out,const char * path,data_type_ref Data)1274 EmitKeyDataLength(raw_ostream& Out, const char *path,
1275 data_type_ref Data) {
1276 unsigned StrLen = strlen(path);
1277 clang::io::Emit16(Out, StrLen);
1278 unsigned DataLen = 1 + 2 + 4 + 4;
1279 clang::io::Emit8(Out, DataLen);
1280 return std::make_pair(StrLen + 1, DataLen);
1281 }
1282
EmitKey(raw_ostream & Out,const char * path,unsigned KeyLen)1283 void EmitKey(raw_ostream& Out, const char *path, unsigned KeyLen) {
1284 Out.write(path, KeyLen);
1285 }
1286
EmitData(raw_ostream & Out,key_type_ref,data_type_ref Data,unsigned DataLen)1287 void EmitData(raw_ostream &Out, key_type_ref,
1288 data_type_ref Data, unsigned DataLen) {
1289 using namespace clang::io;
1290 uint64_t Start = Out.tell(); (void)Start;
1291
1292 unsigned char Flags = (Data.isImport << 5)
1293 | (Data.isPragmaOnce << 4)
1294 | (Data.DirInfo << 2)
1295 | (Data.Resolved << 1)
1296 | Data.IndexHeaderMapHeader;
1297 Emit8(Out, (uint8_t)Flags);
1298 Emit16(Out, (uint16_t) Data.NumIncludes);
1299
1300 if (!Data.ControllingMacro)
1301 Emit32(Out, (uint32_t)Data.ControllingMacroID);
1302 else
1303 Emit32(Out, (uint32_t)Writer.getIdentifierRef(Data.ControllingMacro));
1304
1305 unsigned Offset = 0;
1306 if (!Data.Framework.empty()) {
1307 // If this header refers into a framework, save the framework name.
1308 llvm::StringMap<unsigned>::iterator Pos
1309 = FrameworkNameOffset.find(Data.Framework);
1310 if (Pos == FrameworkNameOffset.end()) {
1311 Offset = FrameworkStringData.size() + 1;
1312 FrameworkStringData.append(Data.Framework.begin(),
1313 Data.Framework.end());
1314 FrameworkStringData.push_back(0);
1315
1316 FrameworkNameOffset[Data.Framework] = Offset;
1317 } else
1318 Offset = Pos->second;
1319 }
1320 Emit32(Out, Offset);
1321
1322 assert(Out.tell() - Start == DataLen && "Wrong data length");
1323 }
1324
strings_begin() const1325 const char *strings_begin() const { return FrameworkStringData.begin(); }
strings_end() const1326 const char *strings_end() const { return FrameworkStringData.end(); }
1327 };
1328 } // end anonymous namespace
1329
1330 /// \brief Write the header search block for the list of files that
1331 ///
1332 /// \param HS The header search structure to save.
WriteHeaderSearch(const HeaderSearch & HS,StringRef isysroot)1333 void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS, StringRef isysroot) {
1334 SmallVector<const FileEntry *, 16> FilesByUID;
1335 HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
1336
1337 if (FilesByUID.size() > HS.header_file_size())
1338 FilesByUID.resize(HS.header_file_size());
1339
1340 HeaderFileInfoTrait GeneratorTrait(*this);
1341 OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
1342 SmallVector<const char *, 4> SavedStrings;
1343 unsigned NumHeaderSearchEntries = 0;
1344 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
1345 const FileEntry *File = FilesByUID[UID];
1346 if (!File)
1347 continue;
1348
1349 // Use HeaderSearch's getFileInfo to make sure we get the HeaderFileInfo
1350 // from the external source if it was not provided already.
1351 const HeaderFileInfo &HFI = HS.getFileInfo(File);
1352 if (HFI.External && Chain)
1353 continue;
1354
1355 // Turn the file name into an absolute path, if it isn't already.
1356 const char *Filename = File->getName();
1357 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
1358
1359 // If we performed any translation on the file name at all, we need to
1360 // save this string, since the generator will refer to it later.
1361 if (Filename != File->getName()) {
1362 Filename = strdup(Filename);
1363 SavedStrings.push_back(Filename);
1364 }
1365
1366 Generator.insert(Filename, HFI, GeneratorTrait);
1367 ++NumHeaderSearchEntries;
1368 }
1369
1370 // Create the on-disk hash table in a buffer.
1371 SmallString<4096> TableData;
1372 uint32_t BucketOffset;
1373 {
1374 llvm::raw_svector_ostream Out(TableData);
1375 // Make sure that no bucket is at offset 0
1376 clang::io::Emit32(Out, 0);
1377 BucketOffset = Generator.Emit(Out, GeneratorTrait);
1378 }
1379
1380 // Create a blob abbreviation
1381 using namespace llvm;
1382 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1383 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
1384 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1385 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1386 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1387 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1388 unsigned TableAbbrev = Stream.EmitAbbrev(Abbrev);
1389
1390 // Write the header search table
1391 RecordData Record;
1392 Record.push_back(HEADER_SEARCH_TABLE);
1393 Record.push_back(BucketOffset);
1394 Record.push_back(NumHeaderSearchEntries);
1395 Record.push_back(TableData.size());
1396 TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end());
1397 Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData.str());
1398
1399 // Free all of the strings we had to duplicate.
1400 for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
1401 free((void*)SavedStrings[I]);
1402 }
1403
1404 /// \brief Writes the block containing the serialized form of the
1405 /// source manager.
1406 ///
1407 /// TODO: We should probably use an on-disk hash table (stored in a
1408 /// blob), indexed based on the file name, so that we only create
1409 /// entries for files that we actually need. In the common case (no
1410 /// errors), we probably won't have to create file entries for any of
1411 /// the files in the AST.
WriteSourceManagerBlock(SourceManager & SourceMgr,const Preprocessor & PP,StringRef isysroot)1412 void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
1413 const Preprocessor &PP,
1414 StringRef isysroot) {
1415 RecordData Record;
1416
1417 // Enter the source manager block.
1418 Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 3);
1419
1420 // Abbreviations for the various kinds of source-location entries.
1421 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
1422 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
1423 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
1424 unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
1425
1426 // Write out the source location entry table. We skip the first
1427 // entry, which is always the same dummy entry.
1428 std::vector<uint32_t> SLocEntryOffsets;
1429 // Write out the offsets of only source location file entries.
1430 // We will go through them in ASTReader::validateFileEntries().
1431 std::vector<uint32_t> SLocFileEntryOffsets;
1432 RecordData PreloadSLocs;
1433 SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
1434 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
1435 I != N; ++I) {
1436 // Get this source location entry.
1437 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
1438
1439 // Record the offset of this source-location entry.
1440 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
1441
1442 // Figure out which record code to use.
1443 unsigned Code;
1444 if (SLoc->isFile()) {
1445 const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
1446 if (Cache->OrigEntry) {
1447 Code = SM_SLOC_FILE_ENTRY;
1448 SLocFileEntryOffsets.push_back(Stream.GetCurrentBitNo());
1449 } else
1450 Code = SM_SLOC_BUFFER_ENTRY;
1451 } else
1452 Code = SM_SLOC_EXPANSION_ENTRY;
1453 Record.clear();
1454 Record.push_back(Code);
1455
1456 // Starting offset of this entry within this module, so skip the dummy.
1457 Record.push_back(SLoc->getOffset() - 2);
1458 if (SLoc->isFile()) {
1459 const SrcMgr::FileInfo &File = SLoc->getFile();
1460 Record.push_back(File.getIncludeLoc().getRawEncoding());
1461 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
1462 Record.push_back(File.hasLineDirectives());
1463
1464 const SrcMgr::ContentCache *Content = File.getContentCache();
1465 if (Content->OrigEntry) {
1466 assert(Content->OrigEntry == Content->ContentsEntry &&
1467 "Writing to AST an overridden file is not supported");
1468
1469 // The source location entry is a file. The blob associated
1470 // with this entry is the file name.
1471
1472 // Emit size/modification time for this file.
1473 Record.push_back(Content->OrigEntry->getSize());
1474 Record.push_back(Content->OrigEntry->getModificationTime());
1475 Record.push_back(Content->BufferOverridden);
1476 Record.push_back(File.NumCreatedFIDs);
1477
1478 FileDeclIDsTy::iterator FDI = FileDeclIDs.find(SLoc);
1479 if (FDI != FileDeclIDs.end()) {
1480 Record.push_back(FDI->second->FirstDeclIndex);
1481 Record.push_back(FDI->second->DeclIDs.size());
1482 } else {
1483 Record.push_back(0);
1484 Record.push_back(0);
1485 }
1486
1487 // Turn the file name into an absolute path, if it isn't already.
1488 const char *Filename = Content->OrigEntry->getName();
1489 SmallString<128> FilePath(Filename);
1490
1491 // Ask the file manager to fixup the relative path for us. This will
1492 // honor the working directory.
1493 SourceMgr.getFileManager().FixupRelativePath(FilePath);
1494
1495 // FIXME: This call to make_absolute shouldn't be necessary, the
1496 // call to FixupRelativePath should always return an absolute path.
1497 llvm::sys::fs::make_absolute(FilePath);
1498 Filename = FilePath.c_str();
1499
1500 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
1501 Stream.EmitRecordWithBlob(SLocFileAbbrv, Record, Filename);
1502
1503 if (Content->BufferOverridden) {
1504 Record.clear();
1505 Record.push_back(SM_SLOC_BUFFER_BLOB);
1506 const llvm::MemoryBuffer *Buffer
1507 = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
1508 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
1509 StringRef(Buffer->getBufferStart(),
1510 Buffer->getBufferSize() + 1));
1511 }
1512 } else {
1513 // The source location entry is a buffer. The blob associated
1514 // with this entry contains the contents of the buffer.
1515
1516 // We add one to the size so that we capture the trailing NULL
1517 // that is required by llvm::MemoryBuffer::getMemBuffer (on
1518 // the reader side).
1519 const llvm::MemoryBuffer *Buffer
1520 = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
1521 const char *Name = Buffer->getBufferIdentifier();
1522 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
1523 StringRef(Name, strlen(Name) + 1));
1524 Record.clear();
1525 Record.push_back(SM_SLOC_BUFFER_BLOB);
1526 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
1527 StringRef(Buffer->getBufferStart(),
1528 Buffer->getBufferSize() + 1));
1529
1530 if (strcmp(Name, "<built-in>") == 0) {
1531 PreloadSLocs.push_back(SLocEntryOffsets.size());
1532 }
1533 }
1534 } else {
1535 // The source location entry is a macro expansion.
1536 const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
1537 Record.push_back(Expansion.getSpellingLoc().getRawEncoding());
1538 Record.push_back(Expansion.getExpansionLocStart().getRawEncoding());
1539 Record.push_back(Expansion.isMacroArgExpansion() ? 0
1540 : Expansion.getExpansionLocEnd().getRawEncoding());
1541
1542 // Compute the token length for this macro expansion.
1543 unsigned NextOffset = SourceMgr.getNextLocalOffset();
1544 if (I + 1 != N)
1545 NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
1546 Record.push_back(NextOffset - SLoc->getOffset() - 1);
1547 Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
1548 }
1549 }
1550
1551 Stream.ExitBlock();
1552
1553 if (SLocEntryOffsets.empty())
1554 return;
1555
1556 // Write the source-location offsets table into the AST block. This
1557 // table is used for lazily loading source-location information.
1558 using namespace llvm;
1559 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1560 Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
1561 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
1562 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
1563 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
1564 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
1565
1566 Record.clear();
1567 Record.push_back(SOURCE_LOCATION_OFFSETS);
1568 Record.push_back(SLocEntryOffsets.size());
1569 Record.push_back(SourceMgr.getNextLocalOffset() - 1); // skip dummy
1570 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record, data(SLocEntryOffsets));
1571
1572 Abbrev = new BitCodeAbbrev();
1573 Abbrev->Add(BitCodeAbbrevOp(FILE_SOURCE_LOCATION_OFFSETS));
1574 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
1575 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
1576 unsigned SLocFileOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
1577
1578 Record.clear();
1579 Record.push_back(FILE_SOURCE_LOCATION_OFFSETS);
1580 Record.push_back(SLocFileEntryOffsets.size());
1581 Stream.EmitRecordWithBlob(SLocFileOffsetsAbbrev, Record,
1582 data(SLocFileEntryOffsets));
1583
1584 // Write the source location entry preloads array, telling the AST
1585 // reader which source locations entries it should load eagerly.
1586 Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
1587
1588 // Write the line table. It depends on remapping working, so it must come
1589 // after the source location offsets.
1590 if (SourceMgr.hasLineTable()) {
1591 LineTableInfo &LineTable = SourceMgr.getLineTable();
1592
1593 Record.clear();
1594 // Emit the file names
1595 Record.push_back(LineTable.getNumFilenames());
1596 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
1597 // Emit the file name
1598 const char *Filename = LineTable.getFilename(I);
1599 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
1600 unsigned FilenameLen = Filename? strlen(Filename) : 0;
1601 Record.push_back(FilenameLen);
1602 if (FilenameLen)
1603 Record.insert(Record.end(), Filename, Filename + FilenameLen);
1604 }
1605
1606 // Emit the line entries
1607 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
1608 L != LEnd; ++L) {
1609 // Only emit entries for local files.
1610 if (L->first.ID < 0)
1611 continue;
1612
1613 // Emit the file ID
1614 Record.push_back(L->first.ID);
1615
1616 // Emit the line entries
1617 Record.push_back(L->second.size());
1618 for (std::vector<LineEntry>::iterator LE = L->second.begin(),
1619 LEEnd = L->second.end();
1620 LE != LEEnd; ++LE) {
1621 Record.push_back(LE->FileOffset);
1622 Record.push_back(LE->LineNo);
1623 Record.push_back(LE->FilenameID);
1624 Record.push_back((unsigned)LE->FileKind);
1625 Record.push_back(LE->IncludeOffset);
1626 }
1627 }
1628 Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
1629 }
1630 }
1631
1632 //===----------------------------------------------------------------------===//
1633 // Preprocessor Serialization
1634 //===----------------------------------------------------------------------===//
1635
compareMacroDefinitions(const void * XPtr,const void * YPtr)1636 static int compareMacroDefinitions(const void *XPtr, const void *YPtr) {
1637 const std::pair<const IdentifierInfo *, MacroInfo *> &X =
1638 *(const std::pair<const IdentifierInfo *, MacroInfo *>*)XPtr;
1639 const std::pair<const IdentifierInfo *, MacroInfo *> &Y =
1640 *(const std::pair<const IdentifierInfo *, MacroInfo *>*)YPtr;
1641 return X.first->getName().compare(Y.first->getName());
1642 }
1643
1644 /// \brief Writes the block containing the serialized form of the
1645 /// preprocessor.
1646 ///
WritePreprocessor(const Preprocessor & PP,bool IsModule)1647 void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
1648 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
1649 if (PPRec)
1650 WritePreprocessorDetail(*PPRec);
1651
1652 RecordData Record;
1653
1654 // If the preprocessor __COUNTER__ value has been bumped, remember it.
1655 if (PP.getCounterValue() != 0) {
1656 Record.push_back(PP.getCounterValue());
1657 Stream.EmitRecord(PP_COUNTER_VALUE, Record);
1658 Record.clear();
1659 }
1660
1661 // Enter the preprocessor block.
1662 Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
1663
1664 // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
1665 // FIXME: use diagnostics subsystem for localization etc.
1666 if (PP.SawDateOrTime())
1667 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
1668
1669
1670 // Loop over all the macro definitions that are live at the end of the file,
1671 // emitting each to the PP section.
1672
1673 // Construct the list of macro definitions that need to be serialized.
1674 SmallVector<std::pair<const IdentifierInfo *, MacroInfo *>, 2>
1675 MacrosToEmit;
1676 llvm::SmallPtrSet<const IdentifierInfo*, 4> MacroDefinitionsSeen;
1677 for (Preprocessor::macro_iterator I = PP.macro_begin(Chain == 0),
1678 E = PP.macro_end(Chain == 0);
1679 I != E; ++I) {
1680 // FIXME: We'll need to store macro history in PCH.
1681 if (I->first->hasMacroDefinition()) {
1682 if (!IsModule || I->second->isPublic()) {
1683 MacroDefinitionsSeen.insert(I->first);
1684 MacrosToEmit.push_back(std::make_pair(I->first, I->second));
1685 }
1686 }
1687 }
1688
1689 // Sort the set of macro definitions that need to be serialized by the
1690 // name of the macro, to provide a stable ordering.
1691 llvm::array_pod_sort(MacrosToEmit.begin(), MacrosToEmit.end(),
1692 &compareMacroDefinitions);
1693
1694 // Resolve any identifiers that defined macros at the time they were
1695 // deserialized, adding them to the list of macros to emit (if appropriate).
1696 for (unsigned I = 0, N = DeserializedMacroNames.size(); I != N; ++I) {
1697 IdentifierInfo *Name
1698 = const_cast<IdentifierInfo *>(DeserializedMacroNames[I]);
1699 if (Name->hasMacroDefinition() && MacroDefinitionsSeen.insert(Name))
1700 MacrosToEmit.push_back(std::make_pair(Name, PP.getMacroInfo(Name)));
1701 }
1702
1703 for (unsigned I = 0, N = MacrosToEmit.size(); I != N; ++I) {
1704 const IdentifierInfo *Name = MacrosToEmit[I].first;
1705 MacroInfo *MI = MacrosToEmit[I].second;
1706 if (!MI)
1707 continue;
1708
1709 // Don't emit builtin macros like __LINE__ to the AST file unless they have
1710 // been redefined by the header (in which case they are not isBuiltinMacro).
1711 // Also skip macros from a AST file if we're chaining.
1712
1713 // FIXME: There is a (probably minor) optimization we could do here, if
1714 // the macro comes from the original PCH but the identifier comes from a
1715 // chained PCH, by storing the offset into the original PCH rather than
1716 // writing the macro definition a second time.
1717 if (MI->isBuiltinMacro() ||
1718 (Chain &&
1719 Name->isFromAST() && !Name->hasChangedSinceDeserialization() &&
1720 MI->isFromAST() && !MI->hasChangedAfterLoad()))
1721 continue;
1722
1723 AddIdentifierRef(Name, Record);
1724 MacroOffsets[Name] = Stream.GetCurrentBitNo();
1725 Record.push_back(MI->getDefinitionLoc().getRawEncoding());
1726 Record.push_back(MI->isUsed());
1727 Record.push_back(MI->isPublic());
1728 AddSourceLocation(MI->getVisibilityLocation(), Record);
1729 unsigned Code;
1730 if (MI->isObjectLike()) {
1731 Code = PP_MACRO_OBJECT_LIKE;
1732 } else {
1733 Code = PP_MACRO_FUNCTION_LIKE;
1734
1735 Record.push_back(MI->isC99Varargs());
1736 Record.push_back(MI->isGNUVarargs());
1737 Record.push_back(MI->getNumArgs());
1738 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
1739 I != E; ++I)
1740 AddIdentifierRef(*I, Record);
1741 }
1742
1743 // If we have a detailed preprocessing record, record the macro definition
1744 // ID that corresponds to this macro.
1745 if (PPRec)
1746 Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
1747
1748 Stream.EmitRecord(Code, Record);
1749 Record.clear();
1750
1751 // Emit the tokens array.
1752 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
1753 // Note that we know that the preprocessor does not have any annotation
1754 // tokens in it because they are created by the parser, and thus can't be
1755 // in a macro definition.
1756 const Token &Tok = MI->getReplacementToken(TokNo);
1757
1758 Record.push_back(Tok.getLocation().getRawEncoding());
1759 Record.push_back(Tok.getLength());
1760
1761 // FIXME: When reading literal tokens, reconstruct the literal pointer if
1762 // it is needed.
1763 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
1764 // FIXME: Should translate token kind to a stable encoding.
1765 Record.push_back(Tok.getKind());
1766 // FIXME: Should translate token flags to a stable encoding.
1767 Record.push_back(Tok.getFlags());
1768
1769 Stream.EmitRecord(PP_TOKEN, Record);
1770 Record.clear();
1771 }
1772 ++NumMacros;
1773 }
1774 Stream.ExitBlock();
1775 }
1776
WritePreprocessorDetail(PreprocessingRecord & PPRec)1777 void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) {
1778 if (PPRec.local_begin() == PPRec.local_end())
1779 return;
1780
1781 SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
1782
1783 // Enter the preprocessor block.
1784 Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
1785
1786 // If the preprocessor has a preprocessing record, emit it.
1787 unsigned NumPreprocessingRecords = 0;
1788 using namespace llvm;
1789
1790 // Set up the abbreviation for
1791 unsigned InclusionAbbrev = 0;
1792 {
1793 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1794 Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
1795 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
1796 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
1797 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
1798 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1799 InclusionAbbrev = Stream.EmitAbbrev(Abbrev);
1800 }
1801
1802 unsigned FirstPreprocessorEntityID
1803 = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0)
1804 + NUM_PREDEF_PP_ENTITY_IDS;
1805 unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
1806 RecordData Record;
1807 for (PreprocessingRecord::iterator E = PPRec.local_begin(),
1808 EEnd = PPRec.local_end();
1809 E != EEnd;
1810 (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
1811 Record.clear();
1812
1813 PreprocessedEntityOffsets.push_back(PPEntityOffset((*E)->getSourceRange(),
1814 Stream.GetCurrentBitNo()));
1815
1816 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
1817 // Record this macro definition's ID.
1818 MacroDefinitions[MD] = NextPreprocessorEntityID;
1819
1820 AddIdentifierRef(MD->getName(), Record);
1821 Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
1822 continue;
1823 }
1824
1825 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(*E)) {
1826 Record.push_back(ME->isBuiltinMacro());
1827 if (ME->isBuiltinMacro())
1828 AddIdentifierRef(ME->getName(), Record);
1829 else
1830 Record.push_back(MacroDefinitions[ME->getDefinition()]);
1831 Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
1832 continue;
1833 }
1834
1835 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
1836 Record.push_back(PPD_INCLUSION_DIRECTIVE);
1837 Record.push_back(ID->getFileName().size());
1838 Record.push_back(ID->wasInQuotes());
1839 Record.push_back(static_cast<unsigned>(ID->getKind()));
1840 SmallString<64> Buffer;
1841 Buffer += ID->getFileName();
1842 // Check that the FileEntry is not null because it was not resolved and
1843 // we create a PCH even with compiler errors.
1844 if (ID->getFile())
1845 Buffer += ID->getFile()->getName();
1846 Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
1847 continue;
1848 }
1849
1850 llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
1851 }
1852 Stream.ExitBlock();
1853
1854 // Write the offsets table for the preprocessing record.
1855 if (NumPreprocessingRecords > 0) {
1856 assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords);
1857
1858 // Write the offsets table for identifier IDs.
1859 using namespace llvm;
1860 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1861 Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
1862 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
1863 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1864 unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1865
1866 Record.clear();
1867 Record.push_back(PPD_ENTITIES_OFFSETS);
1868 Record.push_back(FirstPreprocessorEntityID - NUM_PREDEF_PP_ENTITY_IDS);
1869 Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
1870 data(PreprocessedEntityOffsets));
1871 }
1872 }
1873
getSubmoduleID(Module * Mod)1874 unsigned ASTWriter::getSubmoduleID(Module *Mod) {
1875 llvm::DenseMap<Module *, unsigned>::iterator Known = SubmoduleIDs.find(Mod);
1876 if (Known != SubmoduleIDs.end())
1877 return Known->second;
1878
1879 return SubmoduleIDs[Mod] = NextSubmoduleID++;
1880 }
1881
1882 /// \brief Compute the number of modules within the given tree (including the
1883 /// given module).
getNumberOfModules(Module * Mod)1884 static unsigned getNumberOfModules(Module *Mod) {
1885 unsigned ChildModules = 0;
1886 for (Module::submodule_iterator Sub = Mod->submodule_begin(),
1887 SubEnd = Mod->submodule_end();
1888 Sub != SubEnd; ++Sub)
1889 ChildModules += getNumberOfModules(*Sub);
1890
1891 return ChildModules + 1;
1892 }
1893
WriteSubmodules(Module * WritingModule)1894 void ASTWriter::WriteSubmodules(Module *WritingModule) {
1895 // Determine the dependencies of our module and each of it's submodules.
1896 // FIXME: This feels like it belongs somewhere else, but there are no
1897 // other consumers of this information.
1898 SourceManager &SrcMgr = PP->getSourceManager();
1899 ModuleMap &ModMap = PP->getHeaderSearchInfo().getModuleMap();
1900 for (ASTContext::import_iterator I = Context->local_import_begin(),
1901 IEnd = Context->local_import_end();
1902 I != IEnd; ++I) {
1903 if (Module *ImportedFrom
1904 = ModMap.inferModuleFromLocation(FullSourceLoc(I->getLocation(),
1905 SrcMgr))) {
1906 ImportedFrom->Imports.push_back(I->getImportedModule());
1907 }
1908 }
1909
1910 // Enter the submodule description block.
1911 Stream.EnterSubblock(SUBMODULE_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE);
1912
1913 // Write the abbreviations needed for the submodules block.
1914 using namespace llvm;
1915 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1916 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
1917 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
1918 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
1919 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
1920 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
1921 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem
1922 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules...
1923 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
1924 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
1925 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
1926 unsigned DefinitionAbbrev = Stream.EmitAbbrev(Abbrev);
1927
1928 Abbrev = new BitCodeAbbrev();
1929 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
1930 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
1931 unsigned UmbrellaAbbrev = Stream.EmitAbbrev(Abbrev);
1932
1933 Abbrev = new BitCodeAbbrev();
1934 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
1935 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
1936 unsigned HeaderAbbrev = Stream.EmitAbbrev(Abbrev);
1937
1938 Abbrev = new BitCodeAbbrev();
1939 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
1940 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
1941 unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(Abbrev);
1942
1943 Abbrev = new BitCodeAbbrev();
1944 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES));
1945 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Feature
1946 unsigned RequiresAbbrev = Stream.EmitAbbrev(Abbrev);
1947
1948 // Write the submodule metadata block.
1949 RecordData Record;
1950 Record.push_back(getNumberOfModules(WritingModule));
1951 Record.push_back(FirstSubmoduleID - NUM_PREDEF_SUBMODULE_IDS);
1952 Stream.EmitRecord(SUBMODULE_METADATA, Record);
1953
1954 // Write all of the submodules.
1955 std::queue<Module *> Q;
1956 Q.push(WritingModule);
1957 while (!Q.empty()) {
1958 Module *Mod = Q.front();
1959 Q.pop();
1960 unsigned ID = getSubmoduleID(Mod);
1961
1962 // Emit the definition of the block.
1963 Record.clear();
1964 Record.push_back(SUBMODULE_DEFINITION);
1965 Record.push_back(ID);
1966 if (Mod->Parent) {
1967 assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?");
1968 Record.push_back(SubmoduleIDs[Mod->Parent]);
1969 } else {
1970 Record.push_back(0);
1971 }
1972 Record.push_back(Mod->IsFramework);
1973 Record.push_back(Mod->IsExplicit);
1974 Record.push_back(Mod->IsSystem);
1975 Record.push_back(Mod->InferSubmodules);
1976 Record.push_back(Mod->InferExplicitSubmodules);
1977 Record.push_back(Mod->InferExportWildcard);
1978 Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
1979
1980 // Emit the requirements.
1981 for (unsigned I = 0, N = Mod->Requires.size(); I != N; ++I) {
1982 Record.clear();
1983 Record.push_back(SUBMODULE_REQUIRES);
1984 Stream.EmitRecordWithBlob(RequiresAbbrev, Record,
1985 Mod->Requires[I].data(),
1986 Mod->Requires[I].size());
1987 }
1988
1989 // Emit the umbrella header, if there is one.
1990 if (const FileEntry *UmbrellaHeader = Mod->getUmbrellaHeader()) {
1991 Record.clear();
1992 Record.push_back(SUBMODULE_UMBRELLA_HEADER);
1993 Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
1994 UmbrellaHeader->getName());
1995 } else if (const DirectoryEntry *UmbrellaDir = Mod->getUmbrellaDir()) {
1996 Record.clear();
1997 Record.push_back(SUBMODULE_UMBRELLA_DIR);
1998 Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,
1999 UmbrellaDir->getName());
2000 }
2001
2002 // Emit the headers.
2003 for (unsigned I = 0, N = Mod->Headers.size(); I != N; ++I) {
2004 Record.clear();
2005 Record.push_back(SUBMODULE_HEADER);
2006 Stream.EmitRecordWithBlob(HeaderAbbrev, Record,
2007 Mod->Headers[I]->getName());
2008 }
2009
2010 // Emit the imports.
2011 if (!Mod->Imports.empty()) {
2012 Record.clear();
2013 for (unsigned I = 0, N = Mod->Imports.size(); I != N; ++I) {
2014 unsigned ImportedID = getSubmoduleID(Mod->Imports[I]);
2015 assert(ImportedID && "Unknown submodule!");
2016 Record.push_back(ImportedID);
2017 }
2018 Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
2019 }
2020
2021 // Emit the exports.
2022 if (!Mod->Exports.empty()) {
2023 Record.clear();
2024 for (unsigned I = 0, N = Mod->Exports.size(); I != N; ++I) {
2025 if (Module *Exported = Mod->Exports[I].getPointer()) {
2026 unsigned ExportedID = SubmoduleIDs[Exported];
2027 assert(ExportedID > 0 && "Unknown submodule ID?");
2028 Record.push_back(ExportedID);
2029 } else {
2030 Record.push_back(0);
2031 }
2032
2033 Record.push_back(Mod->Exports[I].getInt());
2034 }
2035 Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
2036 }
2037
2038 // Queue up the submodules of this module.
2039 for (Module::submodule_iterator Sub = Mod->submodule_begin(),
2040 SubEnd = Mod->submodule_end();
2041 Sub != SubEnd; ++Sub)
2042 Q.push(*Sub);
2043 }
2044
2045 Stream.ExitBlock();
2046
2047 assert((NextSubmoduleID - FirstSubmoduleID
2048 == getNumberOfModules(WritingModule)) && "Wrong # of submodules");
2049 }
2050
2051 serialization::SubmoduleID
inferSubmoduleIDFromLocation(SourceLocation Loc)2052 ASTWriter::inferSubmoduleIDFromLocation(SourceLocation Loc) {
2053 if (Loc.isInvalid() || !WritingModule)
2054 return 0; // No submodule
2055
2056 // Find the module that owns this location.
2057 ModuleMap &ModMap = PP->getHeaderSearchInfo().getModuleMap();
2058 Module *OwningMod
2059 = ModMap.inferModuleFromLocation(FullSourceLoc(Loc,PP->getSourceManager()));
2060 if (!OwningMod)
2061 return 0;
2062
2063 // Check whether this submodule is part of our own module.
2064 if (WritingModule != OwningMod && !OwningMod->isSubModuleOf(WritingModule))
2065 return 0;
2066
2067 return getSubmoduleID(OwningMod);
2068 }
2069
WritePragmaDiagnosticMappings(const DiagnosticsEngine & Diag)2070 void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag) {
2071 RecordData Record;
2072 for (DiagnosticsEngine::DiagStatePointsTy::const_iterator
2073 I = Diag.DiagStatePoints.begin(), E = Diag.DiagStatePoints.end();
2074 I != E; ++I) {
2075 const DiagnosticsEngine::DiagStatePoint &point = *I;
2076 if (point.Loc.isInvalid())
2077 continue;
2078
2079 Record.push_back(point.Loc.getRawEncoding());
2080 for (DiagnosticsEngine::DiagState::const_iterator
2081 I = point.State->begin(), E = point.State->end(); I != E; ++I) {
2082 if (I->second.isPragma()) {
2083 Record.push_back(I->first);
2084 Record.push_back(I->second.getMapping());
2085 }
2086 }
2087 Record.push_back(-1); // mark the end of the diag/map pairs for this
2088 // location.
2089 }
2090
2091 if (!Record.empty())
2092 Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
2093 }
2094
WriteCXXBaseSpecifiersOffsets()2095 void ASTWriter::WriteCXXBaseSpecifiersOffsets() {
2096 if (CXXBaseSpecifiersOffsets.empty())
2097 return;
2098
2099 RecordData Record;
2100
2101 // Create a blob abbreviation for the C++ base specifiers offsets.
2102 using namespace llvm;
2103
2104 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2105 Abbrev->Add(BitCodeAbbrevOp(CXX_BASE_SPECIFIER_OFFSETS));
2106 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
2107 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2108 unsigned BaseSpecifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2109
2110 // Write the base specifier offsets table.
2111 Record.clear();
2112 Record.push_back(CXX_BASE_SPECIFIER_OFFSETS);
2113 Record.push_back(CXXBaseSpecifiersOffsets.size());
2114 Stream.EmitRecordWithBlob(BaseSpecifierOffsetAbbrev, Record,
2115 data(CXXBaseSpecifiersOffsets));
2116 }
2117
2118 //===----------------------------------------------------------------------===//
2119 // Type Serialization
2120 //===----------------------------------------------------------------------===//
2121
2122 /// \brief Write the representation of a type to the AST stream.
WriteType(QualType T)2123 void ASTWriter::WriteType(QualType T) {
2124 TypeIdx &Idx = TypeIdxs[T];
2125 if (Idx.getIndex() == 0) // we haven't seen this type before.
2126 Idx = TypeIdx(NextTypeID++);
2127
2128 assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
2129
2130 // Record the offset for this type.
2131 unsigned Index = Idx.getIndex() - FirstTypeID;
2132 if (TypeOffsets.size() == Index)
2133 TypeOffsets.push_back(Stream.GetCurrentBitNo());
2134 else if (TypeOffsets.size() < Index) {
2135 TypeOffsets.resize(Index + 1);
2136 TypeOffsets[Index] = Stream.GetCurrentBitNo();
2137 }
2138
2139 RecordData Record;
2140
2141 // Emit the type's representation.
2142 ASTTypeWriter W(*this, Record);
2143
2144 if (T.hasLocalNonFastQualifiers()) {
2145 Qualifiers Qs = T.getLocalQualifiers();
2146 AddTypeRef(T.getLocalUnqualifiedType(), Record);
2147 Record.push_back(Qs.getAsOpaqueValue());
2148 W.Code = TYPE_EXT_QUAL;
2149 } else {
2150 switch (T->getTypeClass()) {
2151 // For all of the concrete, non-dependent types, call the
2152 // appropriate visitor function.
2153 #define TYPE(Class, Base) \
2154 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
2155 #define ABSTRACT_TYPE(Class, Base)
2156 #include "clang/AST/TypeNodes.def"
2157 }
2158 }
2159
2160 // Emit the serialized record.
2161 Stream.EmitRecord(W.Code, Record);
2162
2163 // Flush any expressions that were written as part of this type.
2164 FlushStmts();
2165 }
2166
2167 //===----------------------------------------------------------------------===//
2168 // Declaration Serialization
2169 //===----------------------------------------------------------------------===//
2170
2171 /// \brief Write the block containing all of the declaration IDs
2172 /// lexically declared within the given DeclContext.
2173 ///
2174 /// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
2175 /// bistream, or 0 if no block was written.
WriteDeclContextLexicalBlock(ASTContext & Context,DeclContext * DC)2176 uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
2177 DeclContext *DC) {
2178 if (DC->decls_empty())
2179 return 0;
2180
2181 uint64_t Offset = Stream.GetCurrentBitNo();
2182 RecordData Record;
2183 Record.push_back(DECL_CONTEXT_LEXICAL);
2184 SmallVector<KindDeclIDPair, 64> Decls;
2185 for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end();
2186 D != DEnd; ++D)
2187 Decls.push_back(std::make_pair((*D)->getKind(), GetDeclRef(*D)));
2188
2189 ++NumLexicalDeclContexts;
2190 Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record, data(Decls));
2191 return Offset;
2192 }
2193
WriteTypeDeclOffsets()2194 void ASTWriter::WriteTypeDeclOffsets() {
2195 using namespace llvm;
2196 RecordData Record;
2197
2198 // Write the type offsets array
2199 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2200 Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
2201 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
2202 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index
2203 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
2204 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2205 Record.clear();
2206 Record.push_back(TYPE_OFFSET);
2207 Record.push_back(TypeOffsets.size());
2208 Record.push_back(FirstTypeID - NUM_PREDEF_TYPE_IDS);
2209 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, data(TypeOffsets));
2210
2211 // Write the declaration offsets array
2212 Abbrev = new BitCodeAbbrev();
2213 Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
2214 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
2215 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID
2216 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
2217 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2218 Record.clear();
2219 Record.push_back(DECL_OFFSET);
2220 Record.push_back(DeclOffsets.size());
2221 Record.push_back(FirstDeclID - NUM_PREDEF_DECL_IDS);
2222 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, data(DeclOffsets));
2223 }
2224
WriteFileDeclIDsMap()2225 void ASTWriter::WriteFileDeclIDsMap() {
2226 using namespace llvm;
2227 RecordData Record;
2228
2229 // Join the vectors of DeclIDs from all files.
2230 SmallVector<DeclID, 256> FileSortedIDs;
2231 for (FileDeclIDsTy::iterator
2232 FI = FileDeclIDs.begin(), FE = FileDeclIDs.end(); FI != FE; ++FI) {
2233 DeclIDInFileInfo &Info = *FI->second;
2234 Info.FirstDeclIndex = FileSortedIDs.size();
2235 for (LocDeclIDsTy::iterator
2236 DI = Info.DeclIDs.begin(), DE = Info.DeclIDs.end(); DI != DE; ++DI)
2237 FileSortedIDs.push_back(DI->second);
2238 }
2239
2240 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2241 Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
2242 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2243 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
2244 Record.push_back(FILE_SORTED_DECLS);
2245 Stream.EmitRecordWithBlob(AbbrevCode, Record, data(FileSortedIDs));
2246 }
2247
WriteComments()2248 void ASTWriter::WriteComments() {
2249 Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
2250 ArrayRef<RawComment *> RawComments = Context->Comments.getComments();
2251 RecordData Record;
2252 for (ArrayRef<RawComment *>::iterator I = RawComments.begin(),
2253 E = RawComments.end();
2254 I != E; ++I) {
2255 Record.clear();
2256 AddSourceRange((*I)->getSourceRange(), Record);
2257 Record.push_back((*I)->getKind());
2258 Record.push_back((*I)->isTrailingComment());
2259 Record.push_back((*I)->isAlmostTrailingComment());
2260 Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
2261 }
2262 Stream.ExitBlock();
2263 }
2264
2265 //===----------------------------------------------------------------------===//
2266 // Global Method Pool and Selector Serialization
2267 //===----------------------------------------------------------------------===//
2268
2269 namespace {
2270 // Trait used for the on-disk hash table used in the method pool.
2271 class ASTMethodPoolTrait {
2272 ASTWriter &Writer;
2273
2274 public:
2275 typedef Selector key_type;
2276 typedef key_type key_type_ref;
2277
2278 struct data_type {
2279 SelectorID ID;
2280 ObjCMethodList Instance, Factory;
2281 };
2282 typedef const data_type& data_type_ref;
2283
ASTMethodPoolTrait(ASTWriter & Writer)2284 explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) { }
2285
ComputeHash(Selector Sel)2286 static unsigned ComputeHash(Selector Sel) {
2287 return serialization::ComputeHash(Sel);
2288 }
2289
2290 std::pair<unsigned,unsigned>
EmitKeyDataLength(raw_ostream & Out,Selector Sel,data_type_ref Methods)2291 EmitKeyDataLength(raw_ostream& Out, Selector Sel,
2292 data_type_ref Methods) {
2293 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
2294 clang::io::Emit16(Out, KeyLen);
2295 unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
2296 for (const ObjCMethodList *Method = &Methods.Instance; Method;
2297 Method = Method->Next)
2298 if (Method->Method)
2299 DataLen += 4;
2300 for (const ObjCMethodList *Method = &Methods.Factory; Method;
2301 Method = Method->Next)
2302 if (Method->Method)
2303 DataLen += 4;
2304 clang::io::Emit16(Out, DataLen);
2305 return std::make_pair(KeyLen, DataLen);
2306 }
2307
EmitKey(raw_ostream & Out,Selector Sel,unsigned)2308 void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
2309 uint64_t Start = Out.tell();
2310 assert((Start >> 32) == 0 && "Selector key offset too large");
2311 Writer.SetSelectorOffset(Sel, Start);
2312 unsigned N = Sel.getNumArgs();
2313 clang::io::Emit16(Out, N);
2314 if (N == 0)
2315 N = 1;
2316 for (unsigned I = 0; I != N; ++I)
2317 clang::io::Emit32(Out,
2318 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
2319 }
2320
EmitData(raw_ostream & Out,key_type_ref,data_type_ref Methods,unsigned DataLen)2321 void EmitData(raw_ostream& Out, key_type_ref,
2322 data_type_ref Methods, unsigned DataLen) {
2323 uint64_t Start = Out.tell(); (void)Start;
2324 clang::io::Emit32(Out, Methods.ID);
2325 unsigned NumInstanceMethods = 0;
2326 for (const ObjCMethodList *Method = &Methods.Instance; Method;
2327 Method = Method->Next)
2328 if (Method->Method)
2329 ++NumInstanceMethods;
2330
2331 unsigned NumFactoryMethods = 0;
2332 for (const ObjCMethodList *Method = &Methods.Factory; Method;
2333 Method = Method->Next)
2334 if (Method->Method)
2335 ++NumFactoryMethods;
2336
2337 clang::io::Emit16(Out, NumInstanceMethods);
2338 clang::io::Emit16(Out, NumFactoryMethods);
2339 for (const ObjCMethodList *Method = &Methods.Instance; Method;
2340 Method = Method->Next)
2341 if (Method->Method)
2342 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
2343 for (const ObjCMethodList *Method = &Methods.Factory; Method;
2344 Method = Method->Next)
2345 if (Method->Method)
2346 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
2347
2348 assert(Out.tell() - Start == DataLen && "Data length is wrong");
2349 }
2350 };
2351 } // end anonymous namespace
2352
2353 /// \brief Write ObjC data: selectors and the method pool.
2354 ///
2355 /// The method pool contains both instance and factory methods, stored
2356 /// in an on-disk hash table indexed by the selector. The hash table also
2357 /// contains an empty entry for every other selector known to Sema.
WriteSelectors(Sema & SemaRef)2358 void ASTWriter::WriteSelectors(Sema &SemaRef) {
2359 using namespace llvm;
2360
2361 // Do we have to do anything at all?
2362 if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
2363 return;
2364 unsigned NumTableEntries = 0;
2365 // Create and write out the blob that contains selectors and the method pool.
2366 {
2367 OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
2368 ASTMethodPoolTrait Trait(*this);
2369
2370 // Create the on-disk hash table representation. We walk through every
2371 // selector we've seen and look it up in the method pool.
2372 SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
2373 for (llvm::DenseMap<Selector, SelectorID>::iterator
2374 I = SelectorIDs.begin(), E = SelectorIDs.end();
2375 I != E; ++I) {
2376 Selector S = I->first;
2377 Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
2378 ASTMethodPoolTrait::data_type Data = {
2379 I->second,
2380 ObjCMethodList(),
2381 ObjCMethodList()
2382 };
2383 if (F != SemaRef.MethodPool.end()) {
2384 Data.Instance = F->second.first;
2385 Data.Factory = F->second.second;
2386 }
2387 // Only write this selector if it's not in an existing AST or something
2388 // changed.
2389 if (Chain && I->second < FirstSelectorID) {
2390 // Selector already exists. Did it change?
2391 bool changed = false;
2392 for (ObjCMethodList *M = &Data.Instance; !changed && M && M->Method;
2393 M = M->Next) {
2394 if (!M->Method->isFromASTFile())
2395 changed = true;
2396 }
2397 for (ObjCMethodList *M = &Data.Factory; !changed && M && M->Method;
2398 M = M->Next) {
2399 if (!M->Method->isFromASTFile())
2400 changed = true;
2401 }
2402 if (!changed)
2403 continue;
2404 } else if (Data.Instance.Method || Data.Factory.Method) {
2405 // A new method pool entry.
2406 ++NumTableEntries;
2407 }
2408 Generator.insert(S, Data, Trait);
2409 }
2410
2411 // Create the on-disk hash table in a buffer.
2412 SmallString<4096> MethodPool;
2413 uint32_t BucketOffset;
2414 {
2415 ASTMethodPoolTrait Trait(*this);
2416 llvm::raw_svector_ostream Out(MethodPool);
2417 // Make sure that no bucket is at offset 0
2418 clang::io::Emit32(Out, 0);
2419 BucketOffset = Generator.Emit(Out, Trait);
2420 }
2421
2422 // Create a blob abbreviation
2423 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2424 Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
2425 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2426 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2427 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2428 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
2429
2430 // Write the method pool
2431 RecordData Record;
2432 Record.push_back(METHOD_POOL);
2433 Record.push_back(BucketOffset);
2434 Record.push_back(NumTableEntries);
2435 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool.str());
2436
2437 // Create a blob abbreviation for the selector table offsets.
2438 Abbrev = new BitCodeAbbrev();
2439 Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
2440 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
2441 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
2442 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2443 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2444
2445 // Write the selector offsets table.
2446 Record.clear();
2447 Record.push_back(SELECTOR_OFFSETS);
2448 Record.push_back(SelectorOffsets.size());
2449 Record.push_back(FirstSelectorID - NUM_PREDEF_SELECTOR_IDS);
2450 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
2451 data(SelectorOffsets));
2452 }
2453 }
2454
2455 /// \brief Write the selectors referenced in @selector expression into AST file.
WriteReferencedSelectorsPool(Sema & SemaRef)2456 void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
2457 using namespace llvm;
2458 if (SemaRef.ReferencedSelectors.empty())
2459 return;
2460
2461 RecordData Record;
2462
2463 // Note: this writes out all references even for a dependent AST. But it is
2464 // very tricky to fix, and given that @selector shouldn't really appear in
2465 // headers, probably not worth it. It's not a correctness issue.
2466 for (DenseMap<Selector, SourceLocation>::iterator S =
2467 SemaRef.ReferencedSelectors.begin(),
2468 E = SemaRef.ReferencedSelectors.end(); S != E; ++S) {
2469 Selector Sel = (*S).first;
2470 SourceLocation Loc = (*S).second;
2471 AddSelectorRef(Sel, Record);
2472 AddSourceLocation(Loc, Record);
2473 }
2474 Stream.EmitRecord(REFERENCED_SELECTOR_POOL, Record);
2475 }
2476
2477 //===----------------------------------------------------------------------===//
2478 // Identifier Table Serialization
2479 //===----------------------------------------------------------------------===//
2480
2481 namespace {
2482 class ASTIdentifierTableTrait {
2483 ASTWriter &Writer;
2484 Preprocessor &PP;
2485 IdentifierResolver &IdResolver;
2486 bool IsModule;
2487
2488 /// \brief Determines whether this is an "interesting" identifier
2489 /// that needs a full IdentifierInfo structure written into the hash
2490 /// table.
isInterestingIdentifier(IdentifierInfo * II,MacroInfo * & Macro)2491 bool isInterestingIdentifier(IdentifierInfo *II, MacroInfo *&Macro) {
2492 if (II->isPoisoned() ||
2493 II->isExtensionToken() ||
2494 II->getObjCOrBuiltinID() ||
2495 II->hasRevertedTokenIDToIdentifier() ||
2496 II->getFETokenInfo<void>())
2497 return true;
2498
2499 return hasMacroDefinition(II, Macro);
2500 }
2501
hasMacroDefinition(IdentifierInfo * II,MacroInfo * & Macro)2502 bool hasMacroDefinition(IdentifierInfo *II, MacroInfo *&Macro) {
2503 if (!II->hasMacroDefinition())
2504 return false;
2505
2506 if (Macro || (Macro = PP.getMacroInfo(II)))
2507 return !Macro->isBuiltinMacro() && (!IsModule || Macro->isPublic());
2508
2509 return false;
2510 }
2511
2512 public:
2513 typedef IdentifierInfo* key_type;
2514 typedef key_type key_type_ref;
2515
2516 typedef IdentID data_type;
2517 typedef data_type data_type_ref;
2518
ASTIdentifierTableTrait(ASTWriter & Writer,Preprocessor & PP,IdentifierResolver & IdResolver,bool IsModule)2519 ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
2520 IdentifierResolver &IdResolver, bool IsModule)
2521 : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule) { }
2522
ComputeHash(const IdentifierInfo * II)2523 static unsigned ComputeHash(const IdentifierInfo* II) {
2524 return llvm::HashString(II->getName());
2525 }
2526
2527 std::pair<unsigned,unsigned>
EmitKeyDataLength(raw_ostream & Out,IdentifierInfo * II,IdentID ID)2528 EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
2529 unsigned KeyLen = II->getLength() + 1;
2530 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
2531 MacroInfo *Macro = 0;
2532 if (isInterestingIdentifier(II, Macro)) {
2533 DataLen += 2; // 2 bytes for builtin ID, flags
2534 if (hasMacroDefinition(II, Macro))
2535 DataLen += 8;
2536
2537 for (IdentifierResolver::iterator D = IdResolver.begin(II),
2538 DEnd = IdResolver.end();
2539 D != DEnd; ++D)
2540 DataLen += sizeof(DeclID);
2541 }
2542 clang::io::Emit16(Out, DataLen);
2543 // We emit the key length after the data length so that every
2544 // string is preceded by a 16-bit length. This matches the PTH
2545 // format for storing identifiers.
2546 clang::io::Emit16(Out, KeyLen);
2547 return std::make_pair(KeyLen, DataLen);
2548 }
2549
EmitKey(raw_ostream & Out,const IdentifierInfo * II,unsigned KeyLen)2550 void EmitKey(raw_ostream& Out, const IdentifierInfo* II,
2551 unsigned KeyLen) {
2552 // Record the location of the key data. This is used when generating
2553 // the mapping from persistent IDs to strings.
2554 Writer.SetIdentifierOffset(II, Out.tell());
2555 Out.write(II->getNameStart(), KeyLen);
2556 }
2557
EmitData(raw_ostream & Out,IdentifierInfo * II,IdentID ID,unsigned)2558 void EmitData(raw_ostream& Out, IdentifierInfo* II,
2559 IdentID ID, unsigned) {
2560 MacroInfo *Macro = 0;
2561 if (!isInterestingIdentifier(II, Macro)) {
2562 clang::io::Emit32(Out, ID << 1);
2563 return;
2564 }
2565
2566 clang::io::Emit32(Out, (ID << 1) | 0x01);
2567 uint32_t Bits = 0;
2568 bool HasMacroDefinition = hasMacroDefinition(II, Macro);
2569 Bits = (uint32_t)II->getObjCOrBuiltinID();
2570 assert((Bits & 0x7ff) == Bits && "ObjCOrBuiltinID too big for ASTReader.");
2571 Bits = (Bits << 1) | unsigned(HasMacroDefinition);
2572 Bits = (Bits << 1) | unsigned(II->isExtensionToken());
2573 Bits = (Bits << 1) | unsigned(II->isPoisoned());
2574 Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
2575 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
2576 clang::io::Emit16(Out, Bits);
2577
2578 if (HasMacroDefinition) {
2579 clang::io::Emit32(Out, Writer.getMacroOffset(II));
2580 clang::io::Emit32(Out,
2581 Writer.inferSubmoduleIDFromLocation(Macro->getDefinitionLoc()));
2582 }
2583
2584 // Emit the declaration IDs in reverse order, because the
2585 // IdentifierResolver provides the declarations as they would be
2586 // visible (e.g., the function "stat" would come before the struct
2587 // "stat"), but the ASTReader adds declarations to the end of the list
2588 // (so we need to see the struct "status" before the function "status").
2589 // Only emit declarations that aren't from a chained PCH, though.
2590 SmallVector<Decl *, 16> Decls(IdResolver.begin(II),
2591 IdResolver.end());
2592 for (SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(),
2593 DEnd = Decls.rend();
2594 D != DEnd; ++D)
2595 clang::io::Emit32(Out, Writer.getDeclID(*D));
2596 }
2597 };
2598 } // end anonymous namespace
2599
2600 /// \brief Write the identifier table into the AST file.
2601 ///
2602 /// The identifier table consists of a blob containing string data
2603 /// (the actual identifiers themselves) and a separate "offsets" index
2604 /// that maps identifier IDs to locations within the blob.
WriteIdentifierTable(Preprocessor & PP,IdentifierResolver & IdResolver,bool IsModule)2605 void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
2606 IdentifierResolver &IdResolver,
2607 bool IsModule) {
2608 using namespace llvm;
2609
2610 // Create and write out the blob that contains the identifier
2611 // strings.
2612 {
2613 OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
2614 ASTIdentifierTableTrait Trait(*this, PP, IdResolver, IsModule);
2615
2616 // Look for any identifiers that were named while processing the
2617 // headers, but are otherwise not needed. We add these to the hash
2618 // table to enable checking of the predefines buffer in the case
2619 // where the user adds new macro definitions when building the AST
2620 // file.
2621 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
2622 IDEnd = PP.getIdentifierTable().end();
2623 ID != IDEnd; ++ID)
2624 getIdentifierRef(ID->second);
2625
2626 // Create the on-disk hash table representation. We only store offsets
2627 // for identifiers that appear here for the first time.
2628 IdentifierOffsets.resize(NextIdentID - FirstIdentID);
2629 for (llvm::DenseMap<const IdentifierInfo *, IdentID>::iterator
2630 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
2631 ID != IDEnd; ++ID) {
2632 assert(ID->first && "NULL identifier in identifier table");
2633 if (!Chain || !ID->first->isFromAST() ||
2634 ID->first->hasChangedSinceDeserialization())
2635 Generator.insert(const_cast<IdentifierInfo *>(ID->first), ID->second,
2636 Trait);
2637 }
2638
2639 // Create the on-disk hash table in a buffer.
2640 SmallString<4096> IdentifierTable;
2641 uint32_t BucketOffset;
2642 {
2643 ASTIdentifierTableTrait Trait(*this, PP, IdResolver, IsModule);
2644 llvm::raw_svector_ostream Out(IdentifierTable);
2645 // Make sure that no bucket is at offset 0
2646 clang::io::Emit32(Out, 0);
2647 BucketOffset = Generator.Emit(Out, Trait);
2648 }
2649
2650 // Create a blob abbreviation
2651 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2652 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
2653 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2654 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2655 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
2656
2657 // Write the identifier table
2658 RecordData Record;
2659 Record.push_back(IDENTIFIER_TABLE);
2660 Record.push_back(BucketOffset);
2661 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable.str());
2662 }
2663
2664 // Write the offsets table for identifier IDs.
2665 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2666 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
2667 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
2668 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
2669 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2670 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2671
2672 RecordData Record;
2673 Record.push_back(IDENTIFIER_OFFSET);
2674 Record.push_back(IdentifierOffsets.size());
2675 Record.push_back(FirstIdentID - NUM_PREDEF_IDENT_IDS);
2676 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
2677 data(IdentifierOffsets));
2678 }
2679
2680 //===----------------------------------------------------------------------===//
2681 // DeclContext's Name Lookup Table Serialization
2682 //===----------------------------------------------------------------------===//
2683
2684 namespace {
2685 // Trait used for the on-disk hash table used in the method pool.
2686 class ASTDeclContextNameLookupTrait {
2687 ASTWriter &Writer;
2688
2689 public:
2690 typedef DeclarationName key_type;
2691 typedef key_type key_type_ref;
2692
2693 typedef DeclContext::lookup_result data_type;
2694 typedef const data_type& data_type_ref;
2695
ASTDeclContextNameLookupTrait(ASTWriter & Writer)2696 explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) { }
2697
ComputeHash(DeclarationName Name)2698 unsigned ComputeHash(DeclarationName Name) {
2699 llvm::FoldingSetNodeID ID;
2700 ID.AddInteger(Name.getNameKind());
2701
2702 switch (Name.getNameKind()) {
2703 case DeclarationName::Identifier:
2704 ID.AddString(Name.getAsIdentifierInfo()->getName());
2705 break;
2706 case DeclarationName::ObjCZeroArgSelector:
2707 case DeclarationName::ObjCOneArgSelector:
2708 case DeclarationName::ObjCMultiArgSelector:
2709 ID.AddInteger(serialization::ComputeHash(Name.getObjCSelector()));
2710 break;
2711 case DeclarationName::CXXConstructorName:
2712 case DeclarationName::CXXDestructorName:
2713 case DeclarationName::CXXConversionFunctionName:
2714 break;
2715 case DeclarationName::CXXOperatorName:
2716 ID.AddInteger(Name.getCXXOverloadedOperator());
2717 break;
2718 case DeclarationName::CXXLiteralOperatorName:
2719 ID.AddString(Name.getCXXLiteralIdentifier()->getName());
2720 case DeclarationName::CXXUsingDirective:
2721 break;
2722 }
2723
2724 return ID.ComputeHash();
2725 }
2726
2727 std::pair<unsigned,unsigned>
EmitKeyDataLength(raw_ostream & Out,DeclarationName Name,data_type_ref Lookup)2728 EmitKeyDataLength(raw_ostream& Out, DeclarationName Name,
2729 data_type_ref Lookup) {
2730 unsigned KeyLen = 1;
2731 switch (Name.getNameKind()) {
2732 case DeclarationName::Identifier:
2733 case DeclarationName::ObjCZeroArgSelector:
2734 case DeclarationName::ObjCOneArgSelector:
2735 case DeclarationName::ObjCMultiArgSelector:
2736 case DeclarationName::CXXLiteralOperatorName:
2737 KeyLen += 4;
2738 break;
2739 case DeclarationName::CXXOperatorName:
2740 KeyLen += 1;
2741 break;
2742 case DeclarationName::CXXConstructorName:
2743 case DeclarationName::CXXDestructorName:
2744 case DeclarationName::CXXConversionFunctionName:
2745 case DeclarationName::CXXUsingDirective:
2746 break;
2747 }
2748 clang::io::Emit16(Out, KeyLen);
2749
2750 // 2 bytes for num of decls and 4 for each DeclID.
2751 unsigned DataLen = 2 + 4 * (Lookup.second - Lookup.first);
2752 clang::io::Emit16(Out, DataLen);
2753
2754 return std::make_pair(KeyLen, DataLen);
2755 }
2756
EmitKey(raw_ostream & Out,DeclarationName Name,unsigned)2757 void EmitKey(raw_ostream& Out, DeclarationName Name, unsigned) {
2758 using namespace clang::io;
2759
2760 assert(Name.getNameKind() < 0x100 && "Invalid name kind ?");
2761 Emit8(Out, Name.getNameKind());
2762 switch (Name.getNameKind()) {
2763 case DeclarationName::Identifier:
2764 Emit32(Out, Writer.getIdentifierRef(Name.getAsIdentifierInfo()));
2765 break;
2766 case DeclarationName::ObjCZeroArgSelector:
2767 case DeclarationName::ObjCOneArgSelector:
2768 case DeclarationName::ObjCMultiArgSelector:
2769 Emit32(Out, Writer.getSelectorRef(Name.getObjCSelector()));
2770 break;
2771 case DeclarationName::CXXOperatorName:
2772 assert(Name.getCXXOverloadedOperator() < 0x100 && "Invalid operator ?");
2773 Emit8(Out, Name.getCXXOverloadedOperator());
2774 break;
2775 case DeclarationName::CXXLiteralOperatorName:
2776 Emit32(Out, Writer.getIdentifierRef(Name.getCXXLiteralIdentifier()));
2777 break;
2778 case DeclarationName::CXXConstructorName:
2779 case DeclarationName::CXXDestructorName:
2780 case DeclarationName::CXXConversionFunctionName:
2781 case DeclarationName::CXXUsingDirective:
2782 break;
2783 }
2784 }
2785
EmitData(raw_ostream & Out,key_type_ref,data_type Lookup,unsigned DataLen)2786 void EmitData(raw_ostream& Out, key_type_ref,
2787 data_type Lookup, unsigned DataLen) {
2788 uint64_t Start = Out.tell(); (void)Start;
2789 clang::io::Emit16(Out, Lookup.second - Lookup.first);
2790 for (; Lookup.first != Lookup.second; ++Lookup.first)
2791 clang::io::Emit32(Out, Writer.GetDeclRef(*Lookup.first));
2792
2793 assert(Out.tell() - Start == DataLen && "Data length is wrong");
2794 }
2795 };
2796 } // end anonymous namespace
2797
2798 /// \brief Write the block containing all of the declaration IDs
2799 /// visible from the given DeclContext.
2800 ///
2801 /// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
2802 /// bitstream, or 0 if no block was written.
WriteDeclContextVisibleBlock(ASTContext & Context,DeclContext * DC)2803 uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
2804 DeclContext *DC) {
2805 if (DC->getPrimaryContext() != DC)
2806 return 0;
2807
2808 // Since there is no name lookup into functions or methods, don't bother to
2809 // build a visible-declarations table for these entities.
2810 if (DC->isFunctionOrMethod())
2811 return 0;
2812
2813 // If not in C++, we perform name lookup for the translation unit via the
2814 // IdentifierInfo chains, don't bother to build a visible-declarations table.
2815 // FIXME: In C++ we need the visible declarations in order to "see" the
2816 // friend declarations, is there a way to do this without writing the table ?
2817 if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
2818 return 0;
2819
2820 // Serialize the contents of the mapping used for lookup. Note that,
2821 // although we have two very different code paths, the serialized
2822 // representation is the same for both cases: a declaration name,
2823 // followed by a size, followed by references to the visible
2824 // declarations that have that name.
2825 uint64_t Offset = Stream.GetCurrentBitNo();
2826 StoredDeclsMap *Map = DC->buildLookup();
2827 if (!Map || Map->empty())
2828 return 0;
2829
2830 OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait> Generator;
2831 ASTDeclContextNameLookupTrait Trait(*this);
2832
2833 // Create the on-disk hash table representation.
2834 DeclarationName ConversionName;
2835 llvm::SmallVector<NamedDecl *, 4> ConversionDecls;
2836 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
2837 D != DEnd; ++D) {
2838 DeclarationName Name = D->first;
2839 DeclContext::lookup_result Result = D->second.getLookupResult();
2840 if (Result.first != Result.second) {
2841 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2842 // Hash all conversion function names to the same name. The actual
2843 // type information in conversion function name is not used in the
2844 // key (since such type information is not stable across different
2845 // modules), so the intended effect is to coalesce all of the conversion
2846 // functions under a single key.
2847 if (!ConversionName)
2848 ConversionName = Name;
2849 ConversionDecls.append(Result.first, Result.second);
2850 continue;
2851 }
2852
2853 Generator.insert(Name, Result, Trait);
2854 }
2855 }
2856
2857 // Add the conversion functions
2858 if (!ConversionDecls.empty()) {
2859 Generator.insert(ConversionName,
2860 DeclContext::lookup_result(ConversionDecls.begin(),
2861 ConversionDecls.end()),
2862 Trait);
2863 }
2864
2865 // Create the on-disk hash table in a buffer.
2866 SmallString<4096> LookupTable;
2867 uint32_t BucketOffset;
2868 {
2869 llvm::raw_svector_ostream Out(LookupTable);
2870 // Make sure that no bucket is at offset 0
2871 clang::io::Emit32(Out, 0);
2872 BucketOffset = Generator.Emit(Out, Trait);
2873 }
2874
2875 // Write the lookup table
2876 RecordData Record;
2877 Record.push_back(DECL_CONTEXT_VISIBLE);
2878 Record.push_back(BucketOffset);
2879 Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
2880 LookupTable.str());
2881
2882 Stream.EmitRecord(DECL_CONTEXT_VISIBLE, Record);
2883 ++NumVisibleDeclContexts;
2884 return Offset;
2885 }
2886
2887 /// \brief Write an UPDATE_VISIBLE block for the given context.
2888 ///
2889 /// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
2890 /// DeclContext in a dependent AST file. As such, they only exist for the TU
2891 /// (in C++), for namespaces, and for classes with forward-declared unscoped
2892 /// enumeration members (in C++11).
WriteDeclContextVisibleUpdate(const DeclContext * DC)2893 void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
2894 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
2895 if (!Map || Map->empty())
2896 return;
2897
2898 OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait> Generator;
2899 ASTDeclContextNameLookupTrait Trait(*this);
2900
2901 // Create the hash table.
2902 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
2903 D != DEnd; ++D) {
2904 DeclarationName Name = D->first;
2905 DeclContext::lookup_result Result = D->second.getLookupResult();
2906 // For any name that appears in this table, the results are complete, i.e.
2907 // they overwrite results from previous PCHs. Merging is always a mess.
2908 if (Result.first != Result.second)
2909 Generator.insert(Name, Result, Trait);
2910 }
2911
2912 // Create the on-disk hash table in a buffer.
2913 SmallString<4096> LookupTable;
2914 uint32_t BucketOffset;
2915 {
2916 llvm::raw_svector_ostream Out(LookupTable);
2917 // Make sure that no bucket is at offset 0
2918 clang::io::Emit32(Out, 0);
2919 BucketOffset = Generator.Emit(Out, Trait);
2920 }
2921
2922 // Write the lookup table
2923 RecordData Record;
2924 Record.push_back(UPDATE_VISIBLE);
2925 Record.push_back(getDeclID(cast<Decl>(DC)));
2926 Record.push_back(BucketOffset);
2927 Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable.str());
2928 }
2929
2930 /// \brief Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
WriteFPPragmaOptions(const FPOptions & Opts)2931 void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) {
2932 RecordData Record;
2933 Record.push_back(Opts.fp_contract);
2934 Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
2935 }
2936
2937 /// \brief Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
WriteOpenCLExtensions(Sema & SemaRef)2938 void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
2939 if (!SemaRef.Context.getLangOpts().OpenCL)
2940 return;
2941
2942 const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
2943 RecordData Record;
2944 #define OPENCLEXT(nm) Record.push_back(Opts.nm);
2945 #include "clang/Basic/OpenCLExtensions.def"
2946 Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
2947 }
2948
WriteRedeclarations()2949 void ASTWriter::WriteRedeclarations() {
2950 RecordData LocalRedeclChains;
2951 SmallVector<serialization::LocalRedeclarationsInfo, 2> LocalRedeclsMap;
2952
2953 for (unsigned I = 0, N = Redeclarations.size(); I != N; ++I) {
2954 Decl *First = Redeclarations[I];
2955 assert(First->getPreviousDecl() == 0 && "Not the first declaration?");
2956
2957 Decl *MostRecent = First->getMostRecentDecl();
2958
2959 // If we only have a single declaration, there is no point in storing
2960 // a redeclaration chain.
2961 if (First == MostRecent)
2962 continue;
2963
2964 unsigned Offset = LocalRedeclChains.size();
2965 unsigned Size = 0;
2966 LocalRedeclChains.push_back(0); // Placeholder for the size.
2967
2968 // Collect the set of local redeclarations of this declaration.
2969 for (Decl *Prev = MostRecent; Prev != First;
2970 Prev = Prev->getPreviousDecl()) {
2971 if (!Prev->isFromASTFile()) {
2972 AddDeclRef(Prev, LocalRedeclChains);
2973 ++Size;
2974 }
2975 }
2976 LocalRedeclChains[Offset] = Size;
2977
2978 // Reverse the set of local redeclarations, so that we store them in
2979 // order (since we found them in reverse order).
2980 std::reverse(LocalRedeclChains.end() - Size, LocalRedeclChains.end());
2981
2982 // Add the mapping from the first ID to the set of local declarations.
2983 LocalRedeclarationsInfo Info = { getDeclID(First), Offset };
2984 LocalRedeclsMap.push_back(Info);
2985
2986 assert(N == Redeclarations.size() &&
2987 "Deserialized a declaration we shouldn't have");
2988 }
2989
2990 if (LocalRedeclChains.empty())
2991 return;
2992
2993 // Sort the local redeclarations map by the first declaration ID,
2994 // since the reader will be performing binary searches on this information.
2995 llvm::array_pod_sort(LocalRedeclsMap.begin(), LocalRedeclsMap.end());
2996
2997 // Emit the local redeclarations map.
2998 using namespace llvm;
2999 llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
3000 Abbrev->Add(BitCodeAbbrevOp(LOCAL_REDECLARATIONS_MAP));
3001 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
3002 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3003 unsigned AbbrevID = Stream.EmitAbbrev(Abbrev);
3004
3005 RecordData Record;
3006 Record.push_back(LOCAL_REDECLARATIONS_MAP);
3007 Record.push_back(LocalRedeclsMap.size());
3008 Stream.EmitRecordWithBlob(AbbrevID, Record,
3009 reinterpret_cast<char*>(LocalRedeclsMap.data()),
3010 LocalRedeclsMap.size() * sizeof(LocalRedeclarationsInfo));
3011
3012 // Emit the redeclaration chains.
3013 Stream.EmitRecord(LOCAL_REDECLARATIONS, LocalRedeclChains);
3014 }
3015
WriteObjCCategories()3016 void ASTWriter::WriteObjCCategories() {
3017 llvm::SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
3018 RecordData Categories;
3019
3020 for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
3021 unsigned Size = 0;
3022 unsigned StartIndex = Categories.size();
3023
3024 ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
3025
3026 // Allocate space for the size.
3027 Categories.push_back(0);
3028
3029 // Add the categories.
3030 for (ObjCCategoryDecl *Cat = Class->getCategoryList();
3031 Cat; Cat = Cat->getNextClassCategory(), ++Size) {
3032 assert(getDeclID(Cat) != 0 && "Bogus category");
3033 AddDeclRef(Cat, Categories);
3034 }
3035
3036 // Update the size.
3037 Categories[StartIndex] = Size;
3038
3039 // Record this interface -> category map.
3040 ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
3041 CategoriesMap.push_back(CatInfo);
3042 }
3043
3044 // Sort the categories map by the definition ID, since the reader will be
3045 // performing binary searches on this information.
3046 llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
3047
3048 // Emit the categories map.
3049 using namespace llvm;
3050 llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
3051 Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
3052 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
3053 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3054 unsigned AbbrevID = Stream.EmitAbbrev(Abbrev);
3055
3056 RecordData Record;
3057 Record.push_back(OBJC_CATEGORIES_MAP);
3058 Record.push_back(CategoriesMap.size());
3059 Stream.EmitRecordWithBlob(AbbrevID, Record,
3060 reinterpret_cast<char*>(CategoriesMap.data()),
3061 CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
3062
3063 // Emit the category lists.
3064 Stream.EmitRecord(OBJC_CATEGORIES, Categories);
3065 }
3066
WriteMergedDecls()3067 void ASTWriter::WriteMergedDecls() {
3068 if (!Chain || Chain->MergedDecls.empty())
3069 return;
3070
3071 RecordData Record;
3072 for (ASTReader::MergedDeclsMap::iterator I = Chain->MergedDecls.begin(),
3073 IEnd = Chain->MergedDecls.end();
3074 I != IEnd; ++I) {
3075 DeclID CanonID = I->first->isFromASTFile()? I->first->getGlobalID()
3076 : getDeclID(I->first);
3077 assert(CanonID && "Merged declaration not known?");
3078
3079 Record.push_back(CanonID);
3080 Record.push_back(I->second.size());
3081 Record.append(I->second.begin(), I->second.end());
3082 }
3083 Stream.EmitRecord(MERGED_DECLARATIONS, Record);
3084 }
3085
3086 //===----------------------------------------------------------------------===//
3087 // General Serialization Routines
3088 //===----------------------------------------------------------------------===//
3089
3090 /// \brief Write a record containing the given attributes.
WriteAttributes(ArrayRef<const Attr * > Attrs,RecordDataImpl & Record)3091 void ASTWriter::WriteAttributes(ArrayRef<const Attr*> Attrs,
3092 RecordDataImpl &Record) {
3093 Record.push_back(Attrs.size());
3094 for (ArrayRef<const Attr *>::iterator i = Attrs.begin(),
3095 e = Attrs.end(); i != e; ++i){
3096 const Attr *A = *i;
3097 Record.push_back(A->getKind()); // FIXME: stable encoding, target attrs
3098 AddSourceRange(A->getRange(), Record);
3099
3100 #include "clang/Serialization/AttrPCHWrite.inc"
3101
3102 }
3103 }
3104
AddString(StringRef Str,RecordDataImpl & Record)3105 void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
3106 Record.push_back(Str.size());
3107 Record.insert(Record.end(), Str.begin(), Str.end());
3108 }
3109
AddVersionTuple(const VersionTuple & Version,RecordDataImpl & Record)3110 void ASTWriter::AddVersionTuple(const VersionTuple &Version,
3111 RecordDataImpl &Record) {
3112 Record.push_back(Version.getMajor());
3113 if (llvm::Optional<unsigned> Minor = Version.getMinor())
3114 Record.push_back(*Minor + 1);
3115 else
3116 Record.push_back(0);
3117 if (llvm::Optional<unsigned> Subminor = Version.getSubminor())
3118 Record.push_back(*Subminor + 1);
3119 else
3120 Record.push_back(0);
3121 }
3122
3123 /// \brief Note that the identifier II occurs at the given offset
3124 /// within the identifier table.
SetIdentifierOffset(const IdentifierInfo * II,uint32_t Offset)3125 void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
3126 IdentID ID = IdentifierIDs[II];
3127 // Only store offsets new to this AST file. Other identifier names are looked
3128 // up earlier in the chain and thus don't need an offset.
3129 if (ID >= FirstIdentID)
3130 IdentifierOffsets[ID - FirstIdentID] = Offset;
3131 }
3132
3133 /// \brief Note that the selector Sel occurs at the given offset
3134 /// within the method pool/selector table.
SetSelectorOffset(Selector Sel,uint32_t Offset)3135 void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
3136 unsigned ID = SelectorIDs[Sel];
3137 assert(ID && "Unknown selector");
3138 // Don't record offsets for selectors that are also available in a different
3139 // file.
3140 if (ID < FirstSelectorID)
3141 return;
3142 SelectorOffsets[ID - FirstSelectorID] = Offset;
3143 }
3144
ASTWriter(llvm::BitstreamWriter & Stream)3145 ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream)
3146 : Stream(Stream), Context(0), PP(0), Chain(0), WritingModule(0),
3147 WritingAST(false), DoneWritingDeclsAndTypes(false),
3148 ASTHasCompilerErrors(false),
3149 FirstDeclID(NUM_PREDEF_DECL_IDS), NextDeclID(FirstDeclID),
3150 FirstTypeID(NUM_PREDEF_TYPE_IDS), NextTypeID(FirstTypeID),
3151 FirstIdentID(NUM_PREDEF_IDENT_IDS), NextIdentID(FirstIdentID),
3152 FirstSubmoduleID(NUM_PREDEF_SUBMODULE_IDS),
3153 NextSubmoduleID(FirstSubmoduleID),
3154 FirstSelectorID(NUM_PREDEF_SELECTOR_IDS), NextSelectorID(FirstSelectorID),
3155 CollectedStmts(&StmtsToEmit),
3156 NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0),
3157 NumVisibleDeclContexts(0),
3158 NextCXXBaseSpecifiersID(1),
3159 DeclParmVarAbbrev(0), DeclContextLexicalAbbrev(0),
3160 DeclContextVisibleLookupAbbrev(0), UpdateVisibleAbbrev(0),
3161 DeclRefExprAbbrev(0), CharacterLiteralAbbrev(0),
3162 DeclRecordAbbrev(0), IntegerLiteralAbbrev(0),
3163 DeclTypedefAbbrev(0),
3164 DeclVarAbbrev(0), DeclFieldAbbrev(0),
3165 DeclEnumAbbrev(0), DeclObjCIvarAbbrev(0)
3166 {
3167 }
3168
~ASTWriter()3169 ASTWriter::~ASTWriter() {
3170 for (FileDeclIDsTy::iterator
3171 I = FileDeclIDs.begin(), E = FileDeclIDs.end(); I != E; ++I)
3172 delete I->second;
3173 }
3174
WriteAST(Sema & SemaRef,MemorizeStatCalls * StatCalls,const std::string & OutputFile,Module * WritingModule,StringRef isysroot,bool hasErrors)3175 void ASTWriter::WriteAST(Sema &SemaRef, MemorizeStatCalls *StatCalls,
3176 const std::string &OutputFile,
3177 Module *WritingModule, StringRef isysroot,
3178 bool hasErrors) {
3179 WritingAST = true;
3180
3181 ASTHasCompilerErrors = hasErrors;
3182
3183 // Emit the file header.
3184 Stream.Emit((unsigned)'C', 8);
3185 Stream.Emit((unsigned)'P', 8);
3186 Stream.Emit((unsigned)'C', 8);
3187 Stream.Emit((unsigned)'H', 8);
3188
3189 WriteBlockInfoBlock();
3190
3191 Context = &SemaRef.Context;
3192 PP = &SemaRef.PP;
3193 this->WritingModule = WritingModule;
3194 WriteASTCore(SemaRef, StatCalls, isysroot, OutputFile, WritingModule);
3195 Context = 0;
3196 PP = 0;
3197 this->WritingModule = 0;
3198
3199 WritingAST = false;
3200 }
3201
3202 template<typename Vector>
AddLazyVectorDecls(ASTWriter & Writer,Vector & Vec,ASTWriter::RecordData & Record)3203 static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
3204 ASTWriter::RecordData &Record) {
3205 for (typename Vector::iterator I = Vec.begin(0, true), E = Vec.end();
3206 I != E; ++I) {
3207 Writer.AddDeclRef(*I, Record);
3208 }
3209 }
3210
WriteASTCore(Sema & SemaRef,MemorizeStatCalls * StatCalls,StringRef isysroot,const std::string & OutputFile,Module * WritingModule)3211 void ASTWriter::WriteASTCore(Sema &SemaRef, MemorizeStatCalls *StatCalls,
3212 StringRef isysroot,
3213 const std::string &OutputFile,
3214 Module *WritingModule) {
3215 using namespace llvm;
3216
3217 // Make sure that the AST reader knows to finalize itself.
3218 if (Chain)
3219 Chain->finalizeForWriting();
3220
3221 ASTContext &Context = SemaRef.Context;
3222 Preprocessor &PP = SemaRef.PP;
3223
3224 // Set up predefined declaration IDs.
3225 DeclIDs[Context.getTranslationUnitDecl()] = PREDEF_DECL_TRANSLATION_UNIT_ID;
3226 if (Context.ObjCIdDecl)
3227 DeclIDs[Context.ObjCIdDecl] = PREDEF_DECL_OBJC_ID_ID;
3228 if (Context.ObjCSelDecl)
3229 DeclIDs[Context.ObjCSelDecl] = PREDEF_DECL_OBJC_SEL_ID;
3230 if (Context.ObjCClassDecl)
3231 DeclIDs[Context.ObjCClassDecl] = PREDEF_DECL_OBJC_CLASS_ID;
3232 if (Context.ObjCProtocolClassDecl)
3233 DeclIDs[Context.ObjCProtocolClassDecl] = PREDEF_DECL_OBJC_PROTOCOL_ID;
3234 if (Context.Int128Decl)
3235 DeclIDs[Context.Int128Decl] = PREDEF_DECL_INT_128_ID;
3236 if (Context.UInt128Decl)
3237 DeclIDs[Context.UInt128Decl] = PREDEF_DECL_UNSIGNED_INT_128_ID;
3238 if (Context.ObjCInstanceTypeDecl)
3239 DeclIDs[Context.ObjCInstanceTypeDecl] = PREDEF_DECL_OBJC_INSTANCETYPE_ID;
3240 if (Context.BuiltinVaListDecl)
3241 DeclIDs[Context.getBuiltinVaListDecl()] = PREDEF_DECL_BUILTIN_VA_LIST_ID;
3242
3243 if (!Chain) {
3244 // Make sure that we emit IdentifierInfos (and any attached
3245 // declarations) for builtins. We don't need to do this when we're
3246 // emitting chained PCH files, because all of the builtins will be
3247 // in the original PCH file.
3248 // FIXME: Modules won't like this at all.
3249 IdentifierTable &Table = PP.getIdentifierTable();
3250 SmallVector<const char *, 32> BuiltinNames;
3251 Context.BuiltinInfo.GetBuiltinNames(BuiltinNames,
3252 Context.getLangOpts().NoBuiltin);
3253 for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I)
3254 getIdentifierRef(&Table.get(BuiltinNames[I]));
3255 }
3256
3257 // If there are any out-of-date identifiers, bring them up to date.
3258 if (ExternalPreprocessorSource *ExtSource = PP.getExternalSource()) {
3259 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
3260 IDEnd = PP.getIdentifierTable().end();
3261 ID != IDEnd; ++ID)
3262 if (ID->second->isOutOfDate())
3263 ExtSource->updateOutOfDateIdentifier(*ID->second);
3264 }
3265
3266 // Build a record containing all of the tentative definitions in this file, in
3267 // TentativeDefinitions order. Generally, this record will be empty for
3268 // headers.
3269 RecordData TentativeDefinitions;
3270 AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
3271
3272 // Build a record containing all of the file scoped decls in this file.
3273 RecordData UnusedFileScopedDecls;
3274 AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls,
3275 UnusedFileScopedDecls);
3276
3277 // Build a record containing all of the delegating constructors we still need
3278 // to resolve.
3279 RecordData DelegatingCtorDecls;
3280 AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
3281
3282 // Write the set of weak, undeclared identifiers. We always write the
3283 // entire table, since later PCH files in a PCH chain are only interested in
3284 // the results at the end of the chain.
3285 RecordData WeakUndeclaredIdentifiers;
3286 if (!SemaRef.WeakUndeclaredIdentifiers.empty()) {
3287 for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator
3288 I = SemaRef.WeakUndeclaredIdentifiers.begin(),
3289 E = SemaRef.WeakUndeclaredIdentifiers.end(); I != E; ++I) {
3290 AddIdentifierRef(I->first, WeakUndeclaredIdentifiers);
3291 AddIdentifierRef(I->second.getAlias(), WeakUndeclaredIdentifiers);
3292 AddSourceLocation(I->second.getLocation(), WeakUndeclaredIdentifiers);
3293 WeakUndeclaredIdentifiers.push_back(I->second.getUsed());
3294 }
3295 }
3296
3297 // Build a record containing all of the locally-scoped external
3298 // declarations in this header file. Generally, this record will be
3299 // empty.
3300 RecordData LocallyScopedExternalDecls;
3301 // FIXME: This is filling in the AST file in densemap order which is
3302 // nondeterminstic!
3303 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
3304 TD = SemaRef.LocallyScopedExternalDecls.begin(),
3305 TDEnd = SemaRef.LocallyScopedExternalDecls.end();
3306 TD != TDEnd; ++TD) {
3307 if (!TD->second->isFromASTFile())
3308 AddDeclRef(TD->second, LocallyScopedExternalDecls);
3309 }
3310
3311 // Build a record containing all of the ext_vector declarations.
3312 RecordData ExtVectorDecls;
3313 AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
3314
3315 // Build a record containing all of the VTable uses information.
3316 RecordData VTableUses;
3317 if (!SemaRef.VTableUses.empty()) {
3318 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
3319 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
3320 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
3321 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
3322 }
3323 }
3324
3325 // Build a record containing all of dynamic classes declarations.
3326 RecordData DynamicClasses;
3327 AddLazyVectorDecls(*this, SemaRef.DynamicClasses, DynamicClasses);
3328
3329 // Build a record containing all of pending implicit instantiations.
3330 RecordData PendingInstantiations;
3331 for (std::deque<Sema::PendingImplicitInstantiation>::iterator
3332 I = SemaRef.PendingInstantiations.begin(),
3333 N = SemaRef.PendingInstantiations.end(); I != N; ++I) {
3334 AddDeclRef(I->first, PendingInstantiations);
3335 AddSourceLocation(I->second, PendingInstantiations);
3336 }
3337 assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
3338 "There are local ones at end of translation unit!");
3339
3340 // Build a record containing some declaration references.
3341 RecordData SemaDeclRefs;
3342 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc) {
3343 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
3344 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
3345 }
3346
3347 RecordData CUDASpecialDeclRefs;
3348 if (Context.getcudaConfigureCallDecl()) {
3349 AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
3350 }
3351
3352 // Build a record containing all of the known namespaces.
3353 RecordData KnownNamespaces;
3354 for (llvm::DenseMap<NamespaceDecl*, bool>::iterator
3355 I = SemaRef.KnownNamespaces.begin(),
3356 IEnd = SemaRef.KnownNamespaces.end();
3357 I != IEnd; ++I) {
3358 if (!I->second)
3359 AddDeclRef(I->first, KnownNamespaces);
3360 }
3361
3362 // Write the remaining AST contents.
3363 RecordData Record;
3364 Stream.EnterSubblock(AST_BLOCK_ID, 5);
3365 WriteMetadata(Context, isysroot, OutputFile);
3366 WriteLanguageOptions(Context.getLangOpts());
3367 if (StatCalls && isysroot.empty())
3368 WriteStatCache(*StatCalls);
3369
3370 // Create a lexical update block containing all of the declarations in the
3371 // translation unit that do not come from other AST files.
3372 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
3373 SmallVector<KindDeclIDPair, 64> NewGlobalDecls;
3374 for (DeclContext::decl_iterator I = TU->noload_decls_begin(),
3375 E = TU->noload_decls_end();
3376 I != E; ++I) {
3377 if (!(*I)->isFromASTFile())
3378 NewGlobalDecls.push_back(std::make_pair((*I)->getKind(), GetDeclRef(*I)));
3379 }
3380
3381 llvm::BitCodeAbbrev *Abv = new llvm::BitCodeAbbrev();
3382 Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
3383 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
3384 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(Abv);
3385 Record.clear();
3386 Record.push_back(TU_UPDATE_LEXICAL);
3387 Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
3388 data(NewGlobalDecls));
3389
3390 // And a visible updates block for the translation unit.
3391 Abv = new llvm::BitCodeAbbrev();
3392 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
3393 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
3394 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Fixed, 32));
3395 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
3396 UpdateVisibleAbbrev = Stream.EmitAbbrev(Abv);
3397 WriteDeclContextVisibleUpdate(TU);
3398
3399 // If the translation unit has an anonymous namespace, and we don't already
3400 // have an update block for it, write it as an update block.
3401 if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
3402 ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
3403 if (Record.empty()) {
3404 Record.push_back(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE);
3405 Record.push_back(reinterpret_cast<uint64_t>(NS));
3406 }
3407 }
3408
3409 // Make sure visible decls, added to DeclContexts previously loaded from
3410 // an AST file, are registered for serialization.
3411 for (SmallVector<const Decl *, 16>::iterator
3412 I = UpdatingVisibleDecls.begin(),
3413 E = UpdatingVisibleDecls.end(); I != E; ++I) {
3414 GetDeclRef(*I);
3415 }
3416
3417 // Resolve any declaration pointers within the declaration updates block.
3418 ResolveDeclUpdatesBlocks();
3419
3420 // Form the record of special types.
3421 RecordData SpecialTypes;
3422 AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
3423 AddTypeRef(Context.getFILEType(), SpecialTypes);
3424 AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
3425 AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
3426 AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
3427 AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
3428 AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
3429 AddTypeRef(Context.getucontext_tType(), SpecialTypes);
3430
3431 // Keep writing types and declarations until all types and
3432 // declarations have been written.
3433 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE);
3434 WriteDeclsBlockAbbrevs();
3435 for (DeclsToRewriteTy::iterator I = DeclsToRewrite.begin(),
3436 E = DeclsToRewrite.end();
3437 I != E; ++I)
3438 DeclTypesToEmit.push(const_cast<Decl*>(*I));
3439 while (!DeclTypesToEmit.empty()) {
3440 DeclOrType DOT = DeclTypesToEmit.front();
3441 DeclTypesToEmit.pop();
3442 if (DOT.isType())
3443 WriteType(DOT.getType());
3444 else
3445 WriteDecl(Context, DOT.getDecl());
3446 }
3447 Stream.ExitBlock();
3448
3449 DoneWritingDeclsAndTypes = true;
3450
3451 WriteFileDeclIDsMap();
3452 WriteSourceManagerBlock(Context.getSourceManager(), PP, isysroot);
3453 WriteComments();
3454
3455 if (Chain) {
3456 // Write the mapping information describing our module dependencies and how
3457 // each of those modules were mapped into our own offset/ID space, so that
3458 // the reader can build the appropriate mapping to its own offset/ID space.
3459 // The map consists solely of a blob with the following format:
3460 // *(module-name-len:i16 module-name:len*i8
3461 // source-location-offset:i32
3462 // identifier-id:i32
3463 // preprocessed-entity-id:i32
3464 // macro-definition-id:i32
3465 // submodule-id:i32
3466 // selector-id:i32
3467 // declaration-id:i32
3468 // c++-base-specifiers-id:i32
3469 // type-id:i32)
3470 //
3471 llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
3472 Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
3473 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3474 unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(Abbrev);
3475 SmallString<2048> Buffer;
3476 {
3477 llvm::raw_svector_ostream Out(Buffer);
3478 for (ModuleManager::ModuleConstIterator M = Chain->ModuleMgr.begin(),
3479 MEnd = Chain->ModuleMgr.end();
3480 M != MEnd; ++M) {
3481 StringRef FileName = (*M)->FileName;
3482 io::Emit16(Out, FileName.size());
3483 Out.write(FileName.data(), FileName.size());
3484 io::Emit32(Out, (*M)->SLocEntryBaseOffset);
3485 io::Emit32(Out, (*M)->BaseIdentifierID);
3486 io::Emit32(Out, (*M)->BasePreprocessedEntityID);
3487 io::Emit32(Out, (*M)->BaseSubmoduleID);
3488 io::Emit32(Out, (*M)->BaseSelectorID);
3489 io::Emit32(Out, (*M)->BaseDeclID);
3490 io::Emit32(Out, (*M)->BaseTypeIndex);
3491 }
3492 }
3493 Record.clear();
3494 Record.push_back(MODULE_OFFSET_MAP);
3495 Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
3496 Buffer.data(), Buffer.size());
3497 }
3498 WritePreprocessor(PP, WritingModule != 0);
3499 WriteHeaderSearch(PP.getHeaderSearchInfo(), isysroot);
3500 WriteSelectors(SemaRef);
3501 WriteReferencedSelectorsPool(SemaRef);
3502 WriteIdentifierTable(PP, SemaRef.IdResolver, WritingModule != 0);
3503 WriteFPPragmaOptions(SemaRef.getFPOptions());
3504 WriteOpenCLExtensions(SemaRef);
3505
3506 WriteTypeDeclOffsets();
3507 WritePragmaDiagnosticMappings(Context.getDiagnostics());
3508
3509 WriteCXXBaseSpecifiersOffsets();
3510
3511 // If we're emitting a module, write out the submodule information.
3512 if (WritingModule)
3513 WriteSubmodules(WritingModule);
3514
3515 Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
3516
3517 // Write the record containing external, unnamed definitions.
3518 if (!ExternalDefinitions.empty())
3519 Stream.EmitRecord(EXTERNAL_DEFINITIONS, ExternalDefinitions);
3520
3521 // Write the record containing tentative definitions.
3522 if (!TentativeDefinitions.empty())
3523 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
3524
3525 // Write the record containing unused file scoped decls.
3526 if (!UnusedFileScopedDecls.empty())
3527 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
3528
3529 // Write the record containing weak undeclared identifiers.
3530 if (!WeakUndeclaredIdentifiers.empty())
3531 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
3532 WeakUndeclaredIdentifiers);
3533
3534 // Write the record containing locally-scoped external definitions.
3535 if (!LocallyScopedExternalDecls.empty())
3536 Stream.EmitRecord(LOCALLY_SCOPED_EXTERNAL_DECLS,
3537 LocallyScopedExternalDecls);
3538
3539 // Write the record containing ext_vector type names.
3540 if (!ExtVectorDecls.empty())
3541 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
3542
3543 // Write the record containing VTable uses information.
3544 if (!VTableUses.empty())
3545 Stream.EmitRecord(VTABLE_USES, VTableUses);
3546
3547 // Write the record containing dynamic classes declarations.
3548 if (!DynamicClasses.empty())
3549 Stream.EmitRecord(DYNAMIC_CLASSES, DynamicClasses);
3550
3551 // Write the record containing pending implicit instantiations.
3552 if (!PendingInstantiations.empty())
3553 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
3554
3555 // Write the record containing declaration references of Sema.
3556 if (!SemaDeclRefs.empty())
3557 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
3558
3559 // Write the record containing CUDA-specific declaration references.
3560 if (!CUDASpecialDeclRefs.empty())
3561 Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
3562
3563 // Write the delegating constructors.
3564 if (!DelegatingCtorDecls.empty())
3565 Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
3566
3567 // Write the known namespaces.
3568 if (!KnownNamespaces.empty())
3569 Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
3570
3571 // Write the visible updates to DeclContexts.
3572 for (llvm::SmallPtrSet<const DeclContext *, 16>::iterator
3573 I = UpdatedDeclContexts.begin(),
3574 E = UpdatedDeclContexts.end();
3575 I != E; ++I)
3576 WriteDeclContextVisibleUpdate(*I);
3577
3578 if (!WritingModule) {
3579 // Write the submodules that were imported, if any.
3580 RecordData ImportedModules;
3581 for (ASTContext::import_iterator I = Context.local_import_begin(),
3582 IEnd = Context.local_import_end();
3583 I != IEnd; ++I) {
3584 assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end());
3585 ImportedModules.push_back(SubmoduleIDs[I->getImportedModule()]);
3586 }
3587 if (!ImportedModules.empty()) {
3588 // Sort module IDs.
3589 llvm::array_pod_sort(ImportedModules.begin(), ImportedModules.end());
3590
3591 // Unique module IDs.
3592 ImportedModules.erase(std::unique(ImportedModules.begin(),
3593 ImportedModules.end()),
3594 ImportedModules.end());
3595
3596 Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
3597 }
3598 }
3599
3600 WriteDeclUpdatesBlocks();
3601 WriteDeclReplacementsBlock();
3602 WriteMergedDecls();
3603 WriteRedeclarations();
3604 WriteObjCCategories();
3605
3606 // Some simple statistics
3607 Record.clear();
3608 Record.push_back(NumStatements);
3609 Record.push_back(NumMacros);
3610 Record.push_back(NumLexicalDeclContexts);
3611 Record.push_back(NumVisibleDeclContexts);
3612 Stream.EmitRecord(STATISTICS, Record);
3613 Stream.ExitBlock();
3614 }
3615
3616 /// \brief Go through the declaration update blocks and resolve declaration
3617 /// pointers into declaration IDs.
ResolveDeclUpdatesBlocks()3618 void ASTWriter::ResolveDeclUpdatesBlocks() {
3619 for (DeclUpdateMap::iterator
3620 I = DeclUpdates.begin(), E = DeclUpdates.end(); I != E; ++I) {
3621 const Decl *D = I->first;
3622 UpdateRecord &URec = I->second;
3623
3624 if (isRewritten(D))
3625 continue; // The decl will be written completely
3626
3627 unsigned Idx = 0, N = URec.size();
3628 while (Idx < N) {
3629 switch ((DeclUpdateKind)URec[Idx++]) {
3630 case UPD_CXX_ADDED_IMPLICIT_MEMBER:
3631 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
3632 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE:
3633 URec[Idx] = GetDeclRef(reinterpret_cast<Decl *>(URec[Idx]));
3634 ++Idx;
3635 break;
3636
3637 case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER:
3638 ++Idx;
3639 break;
3640 }
3641 }
3642 }
3643 }
3644
WriteDeclUpdatesBlocks()3645 void ASTWriter::WriteDeclUpdatesBlocks() {
3646 if (DeclUpdates.empty())
3647 return;
3648
3649 RecordData OffsetsRecord;
3650 Stream.EnterSubblock(DECL_UPDATES_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE);
3651 for (DeclUpdateMap::iterator
3652 I = DeclUpdates.begin(), E = DeclUpdates.end(); I != E; ++I) {
3653 const Decl *D = I->first;
3654 UpdateRecord &URec = I->second;
3655
3656 if (isRewritten(D))
3657 continue; // The decl will be written completely,no need to store updates.
3658
3659 uint64_t Offset = Stream.GetCurrentBitNo();
3660 Stream.EmitRecord(DECL_UPDATES, URec);
3661
3662 OffsetsRecord.push_back(GetDeclRef(D));
3663 OffsetsRecord.push_back(Offset);
3664 }
3665 Stream.ExitBlock();
3666 Stream.EmitRecord(DECL_UPDATE_OFFSETS, OffsetsRecord);
3667 }
3668
WriteDeclReplacementsBlock()3669 void ASTWriter::WriteDeclReplacementsBlock() {
3670 if (ReplacedDecls.empty())
3671 return;
3672
3673 RecordData Record;
3674 for (SmallVector<ReplacedDeclInfo, 16>::iterator
3675 I = ReplacedDecls.begin(), E = ReplacedDecls.end(); I != E; ++I) {
3676 Record.push_back(I->ID);
3677 Record.push_back(I->Offset);
3678 Record.push_back(I->Loc);
3679 }
3680 Stream.EmitRecord(DECL_REPLACEMENTS, Record);
3681 }
3682
AddSourceLocation(SourceLocation Loc,RecordDataImpl & Record)3683 void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
3684 Record.push_back(Loc.getRawEncoding());
3685 }
3686
AddSourceRange(SourceRange Range,RecordDataImpl & Record)3687 void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
3688 AddSourceLocation(Range.getBegin(), Record);
3689 AddSourceLocation(Range.getEnd(), Record);
3690 }
3691
AddAPInt(const llvm::APInt & Value,RecordDataImpl & Record)3692 void ASTWriter::AddAPInt(const llvm::APInt &Value, RecordDataImpl &Record) {
3693 Record.push_back(Value.getBitWidth());
3694 const uint64_t *Words = Value.getRawData();
3695 Record.append(Words, Words + Value.getNumWords());
3696 }
3697
AddAPSInt(const llvm::APSInt & Value,RecordDataImpl & Record)3698 void ASTWriter::AddAPSInt(const llvm::APSInt &Value, RecordDataImpl &Record) {
3699 Record.push_back(Value.isUnsigned());
3700 AddAPInt(Value, Record);
3701 }
3702
AddAPFloat(const llvm::APFloat & Value,RecordDataImpl & Record)3703 void ASTWriter::AddAPFloat(const llvm::APFloat &Value, RecordDataImpl &Record) {
3704 AddAPInt(Value.bitcastToAPInt(), Record);
3705 }
3706
AddIdentifierRef(const IdentifierInfo * II,RecordDataImpl & Record)3707 void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
3708 Record.push_back(getIdentifierRef(II));
3709 }
3710
getIdentifierRef(const IdentifierInfo * II)3711 IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
3712 if (II == 0)
3713 return 0;
3714
3715 IdentID &ID = IdentifierIDs[II];
3716 if (ID == 0)
3717 ID = NextIdentID++;
3718 return ID;
3719 }
3720
AddSelectorRef(const Selector SelRef,RecordDataImpl & Record)3721 void ASTWriter::AddSelectorRef(const Selector SelRef, RecordDataImpl &Record) {
3722 Record.push_back(getSelectorRef(SelRef));
3723 }
3724
getSelectorRef(Selector Sel)3725 SelectorID ASTWriter::getSelectorRef(Selector Sel) {
3726 if (Sel.getAsOpaquePtr() == 0) {
3727 return 0;
3728 }
3729
3730 SelectorID &SID = SelectorIDs[Sel];
3731 if (SID == 0 && Chain) {
3732 // This might trigger a ReadSelector callback, which will set the ID for
3733 // this selector.
3734 Chain->LoadSelector(Sel);
3735 }
3736 if (SID == 0) {
3737 SID = NextSelectorID++;
3738 }
3739 return SID;
3740 }
3741
AddCXXTemporary(const CXXTemporary * Temp,RecordDataImpl & Record)3742 void ASTWriter::AddCXXTemporary(const CXXTemporary *Temp, RecordDataImpl &Record) {
3743 AddDeclRef(Temp->getDestructor(), Record);
3744 }
3745
AddCXXBaseSpecifiersRef(CXXBaseSpecifier const * Bases,CXXBaseSpecifier const * BasesEnd,RecordDataImpl & Record)3746 void ASTWriter::AddCXXBaseSpecifiersRef(CXXBaseSpecifier const *Bases,
3747 CXXBaseSpecifier const *BasesEnd,
3748 RecordDataImpl &Record) {
3749 assert(Bases != BasesEnd && "Empty base-specifier sets are not recorded");
3750 CXXBaseSpecifiersToWrite.push_back(
3751 QueuedCXXBaseSpecifiers(NextCXXBaseSpecifiersID,
3752 Bases, BasesEnd));
3753 Record.push_back(NextCXXBaseSpecifiersID++);
3754 }
3755
AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,const TemplateArgumentLocInfo & Arg,RecordDataImpl & Record)3756 void ASTWriter::AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
3757 const TemplateArgumentLocInfo &Arg,
3758 RecordDataImpl &Record) {
3759 switch (Kind) {
3760 case TemplateArgument::Expression:
3761 AddStmt(Arg.getAsExpr());
3762 break;
3763 case TemplateArgument::Type:
3764 AddTypeSourceInfo(Arg.getAsTypeSourceInfo(), Record);
3765 break;
3766 case TemplateArgument::Template:
3767 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record);
3768 AddSourceLocation(Arg.getTemplateNameLoc(), Record);
3769 break;
3770 case TemplateArgument::TemplateExpansion:
3771 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record);
3772 AddSourceLocation(Arg.getTemplateNameLoc(), Record);
3773 AddSourceLocation(Arg.getTemplateEllipsisLoc(), Record);
3774 break;
3775 case TemplateArgument::Null:
3776 case TemplateArgument::Integral:
3777 case TemplateArgument::Declaration:
3778 case TemplateArgument::Pack:
3779 break;
3780 }
3781 }
3782
AddTemplateArgumentLoc(const TemplateArgumentLoc & Arg,RecordDataImpl & Record)3783 void ASTWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg,
3784 RecordDataImpl &Record) {
3785 AddTemplateArgument(Arg.getArgument(), Record);
3786
3787 if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
3788 bool InfoHasSameExpr
3789 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
3790 Record.push_back(InfoHasSameExpr);
3791 if (InfoHasSameExpr)
3792 return; // Avoid storing the same expr twice.
3793 }
3794 AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo(),
3795 Record);
3796 }
3797
AddTypeSourceInfo(TypeSourceInfo * TInfo,RecordDataImpl & Record)3798 void ASTWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo,
3799 RecordDataImpl &Record) {
3800 if (TInfo == 0) {
3801 AddTypeRef(QualType(), Record);
3802 return;
3803 }
3804
3805 AddTypeLoc(TInfo->getTypeLoc(), Record);
3806 }
3807
AddTypeLoc(TypeLoc TL,RecordDataImpl & Record)3808 void ASTWriter::AddTypeLoc(TypeLoc TL, RecordDataImpl &Record) {
3809 AddTypeRef(TL.getType(), Record);
3810
3811 TypeLocWriter TLW(*this, Record);
3812 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
3813 TLW.Visit(TL);
3814 }
3815
AddTypeRef(QualType T,RecordDataImpl & Record)3816 void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
3817 Record.push_back(GetOrCreateTypeID(T));
3818 }
3819
GetOrCreateTypeID(QualType T)3820 TypeID ASTWriter::GetOrCreateTypeID( QualType T) {
3821 return MakeTypeID(*Context, T,
3822 std::bind1st(std::mem_fun(&ASTWriter::GetOrCreateTypeIdx), this));
3823 }
3824
getTypeID(QualType T) const3825 TypeID ASTWriter::getTypeID(QualType T) const {
3826 return MakeTypeID(*Context, T,
3827 std::bind1st(std::mem_fun(&ASTWriter::getTypeIdx), this));
3828 }
3829
GetOrCreateTypeIdx(QualType T)3830 TypeIdx ASTWriter::GetOrCreateTypeIdx(QualType T) {
3831 if (T.isNull())
3832 return TypeIdx();
3833 assert(!T.getLocalFastQualifiers());
3834
3835 TypeIdx &Idx = TypeIdxs[T];
3836 if (Idx.getIndex() == 0) {
3837 if (DoneWritingDeclsAndTypes) {
3838 assert(0 && "New type seen after serializing all the types to emit!");
3839 return TypeIdx();
3840 }
3841
3842 // We haven't seen this type before. Assign it a new ID and put it
3843 // into the queue of types to emit.
3844 Idx = TypeIdx(NextTypeID++);
3845 DeclTypesToEmit.push(T);
3846 }
3847 return Idx;
3848 }
3849
getTypeIdx(QualType T) const3850 TypeIdx ASTWriter::getTypeIdx(QualType T) const {
3851 if (T.isNull())
3852 return TypeIdx();
3853 assert(!T.getLocalFastQualifiers());
3854
3855 TypeIdxMap::const_iterator I = TypeIdxs.find(T);
3856 assert(I != TypeIdxs.end() && "Type not emitted!");
3857 return I->second;
3858 }
3859
AddDeclRef(const Decl * D,RecordDataImpl & Record)3860 void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
3861 Record.push_back(GetDeclRef(D));
3862 }
3863
GetDeclRef(const Decl * D)3864 DeclID ASTWriter::GetDeclRef(const Decl *D) {
3865 assert(WritingAST && "Cannot request a declaration ID before AST writing");
3866
3867 if (D == 0) {
3868 return 0;
3869 }
3870
3871 // If D comes from an AST file, its declaration ID is already known and
3872 // fixed.
3873 if (D->isFromASTFile())
3874 return D->getGlobalID();
3875
3876 assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
3877 DeclID &ID = DeclIDs[D];
3878 if (ID == 0) {
3879 if (DoneWritingDeclsAndTypes) {
3880 assert(0 && "New decl seen after serializing all the decls to emit!");
3881 return 0;
3882 }
3883
3884 // We haven't seen this declaration before. Give it a new ID and
3885 // enqueue it in the list of declarations to emit.
3886 ID = NextDeclID++;
3887 DeclTypesToEmit.push(const_cast<Decl *>(D));
3888 }
3889
3890 return ID;
3891 }
3892
getDeclID(const Decl * D)3893 DeclID ASTWriter::getDeclID(const Decl *D) {
3894 if (D == 0)
3895 return 0;
3896
3897 // If D comes from an AST file, its declaration ID is already known and
3898 // fixed.
3899 if (D->isFromASTFile())
3900 return D->getGlobalID();
3901
3902 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
3903 return DeclIDs[D];
3904 }
3905
compLocDecl(std::pair<unsigned,serialization::DeclID> L,std::pair<unsigned,serialization::DeclID> R)3906 static inline bool compLocDecl(std::pair<unsigned, serialization::DeclID> L,
3907 std::pair<unsigned, serialization::DeclID> R) {
3908 return L.first < R.first;
3909 }
3910
associateDeclWithFile(const Decl * D,DeclID ID)3911 void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) {
3912 assert(ID);
3913 assert(D);
3914
3915 SourceLocation Loc = D->getLocation();
3916 if (Loc.isInvalid())
3917 return;
3918
3919 // We only keep track of the file-level declarations of each file.
3920 if (!D->getLexicalDeclContext()->isFileContext())
3921 return;
3922 // FIXME: ParmVarDecls that are part of a function type of a parameter of
3923 // a function/objc method, should not have TU as lexical context.
3924 if (isa<ParmVarDecl>(D))
3925 return;
3926
3927 SourceManager &SM = Context->getSourceManager();
3928 SourceLocation FileLoc = SM.getFileLoc(Loc);
3929 assert(SM.isLocalSourceLocation(FileLoc));
3930 FileID FID;
3931 unsigned Offset;
3932 llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
3933 if (FID.isInvalid())
3934 return;
3935 const SrcMgr::SLocEntry *Entry = &SM.getSLocEntry(FID);
3936 assert(Entry->isFile());
3937
3938 DeclIDInFileInfo *&Info = FileDeclIDs[Entry];
3939 if (!Info)
3940 Info = new DeclIDInFileInfo();
3941
3942 std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID);
3943 LocDeclIDsTy &Decls = Info->DeclIDs;
3944
3945 if (Decls.empty() || Decls.back().first <= Offset) {
3946 Decls.push_back(LocDecl);
3947 return;
3948 }
3949
3950 LocDeclIDsTy::iterator
3951 I = std::upper_bound(Decls.begin(), Decls.end(), LocDecl, compLocDecl);
3952
3953 Decls.insert(I, LocDecl);
3954 }
3955
AddDeclarationName(DeclarationName Name,RecordDataImpl & Record)3956 void ASTWriter::AddDeclarationName(DeclarationName Name, RecordDataImpl &Record) {
3957 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
3958 Record.push_back(Name.getNameKind());
3959 switch (Name.getNameKind()) {
3960 case DeclarationName::Identifier:
3961 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
3962 break;
3963
3964 case DeclarationName::ObjCZeroArgSelector:
3965 case DeclarationName::ObjCOneArgSelector:
3966 case DeclarationName::ObjCMultiArgSelector:
3967 AddSelectorRef(Name.getObjCSelector(), Record);
3968 break;
3969
3970 case DeclarationName::CXXConstructorName:
3971 case DeclarationName::CXXDestructorName:
3972 case DeclarationName::CXXConversionFunctionName:
3973 AddTypeRef(Name.getCXXNameType(), Record);
3974 break;
3975
3976 case DeclarationName::CXXOperatorName:
3977 Record.push_back(Name.getCXXOverloadedOperator());
3978 break;
3979
3980 case DeclarationName::CXXLiteralOperatorName:
3981 AddIdentifierRef(Name.getCXXLiteralIdentifier(), Record);
3982 break;
3983
3984 case DeclarationName::CXXUsingDirective:
3985 // No extra data to emit
3986 break;
3987 }
3988 }
3989
AddDeclarationNameLoc(const DeclarationNameLoc & DNLoc,DeclarationName Name,RecordDataImpl & Record)3990 void ASTWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
3991 DeclarationName Name, RecordDataImpl &Record) {
3992 switch (Name.getNameKind()) {
3993 case DeclarationName::CXXConstructorName:
3994 case DeclarationName::CXXDestructorName:
3995 case DeclarationName::CXXConversionFunctionName:
3996 AddTypeSourceInfo(DNLoc.NamedType.TInfo, Record);
3997 break;
3998
3999 case DeclarationName::CXXOperatorName:
4000 AddSourceLocation(
4001 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.BeginOpNameLoc),
4002 Record);
4003 AddSourceLocation(
4004 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc),
4005 Record);
4006 break;
4007
4008 case DeclarationName::CXXLiteralOperatorName:
4009 AddSourceLocation(
4010 SourceLocation::getFromRawEncoding(DNLoc.CXXLiteralOperatorName.OpNameLoc),
4011 Record);
4012 break;
4013
4014 case DeclarationName::Identifier:
4015 case DeclarationName::ObjCZeroArgSelector:
4016 case DeclarationName::ObjCOneArgSelector:
4017 case DeclarationName::ObjCMultiArgSelector:
4018 case DeclarationName::CXXUsingDirective:
4019 break;
4020 }
4021 }
4022
AddDeclarationNameInfo(const DeclarationNameInfo & NameInfo,RecordDataImpl & Record)4023 void ASTWriter::AddDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
4024 RecordDataImpl &Record) {
4025 AddDeclarationName(NameInfo.getName(), Record);
4026 AddSourceLocation(NameInfo.getLoc(), Record);
4027 AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName(), Record);
4028 }
4029
AddQualifierInfo(const QualifierInfo & Info,RecordDataImpl & Record)4030 void ASTWriter::AddQualifierInfo(const QualifierInfo &Info,
4031 RecordDataImpl &Record) {
4032 AddNestedNameSpecifierLoc(Info.QualifierLoc, Record);
4033 Record.push_back(Info.NumTemplParamLists);
4034 for (unsigned i=0, e=Info.NumTemplParamLists; i != e; ++i)
4035 AddTemplateParameterList(Info.TemplParamLists[i], Record);
4036 }
4037
AddNestedNameSpecifier(NestedNameSpecifier * NNS,RecordDataImpl & Record)4038 void ASTWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS,
4039 RecordDataImpl &Record) {
4040 // Nested name specifiers usually aren't too long. I think that 8 would
4041 // typically accommodate the vast majority.
4042 SmallVector<NestedNameSpecifier *, 8> NestedNames;
4043
4044 // Push each of the NNS's onto a stack for serialization in reverse order.
4045 while (NNS) {
4046 NestedNames.push_back(NNS);
4047 NNS = NNS->getPrefix();
4048 }
4049
4050 Record.push_back(NestedNames.size());
4051 while(!NestedNames.empty()) {
4052 NNS = NestedNames.pop_back_val();
4053 NestedNameSpecifier::SpecifierKind Kind = NNS->getKind();
4054 Record.push_back(Kind);
4055 switch (Kind) {
4056 case NestedNameSpecifier::Identifier:
4057 AddIdentifierRef(NNS->getAsIdentifier(), Record);
4058 break;
4059
4060 case NestedNameSpecifier::Namespace:
4061 AddDeclRef(NNS->getAsNamespace(), Record);
4062 break;
4063
4064 case NestedNameSpecifier::NamespaceAlias:
4065 AddDeclRef(NNS->getAsNamespaceAlias(), Record);
4066 break;
4067
4068 case NestedNameSpecifier::TypeSpec:
4069 case NestedNameSpecifier::TypeSpecWithTemplate:
4070 AddTypeRef(QualType(NNS->getAsType(), 0), Record);
4071 Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
4072 break;
4073
4074 case NestedNameSpecifier::Global:
4075 // Don't need to write an associated value.
4076 break;
4077 }
4078 }
4079 }
4080
AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,RecordDataImpl & Record)4081 void ASTWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
4082 RecordDataImpl &Record) {
4083 // Nested name specifiers usually aren't too long. I think that 8 would
4084 // typically accommodate the vast majority.
4085 SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
4086
4087 // Push each of the nested-name-specifiers's onto a stack for
4088 // serialization in reverse order.
4089 while (NNS) {
4090 NestedNames.push_back(NNS);
4091 NNS = NNS.getPrefix();
4092 }
4093
4094 Record.push_back(NestedNames.size());
4095 while(!NestedNames.empty()) {
4096 NNS = NestedNames.pop_back_val();
4097 NestedNameSpecifier::SpecifierKind Kind
4098 = NNS.getNestedNameSpecifier()->getKind();
4099 Record.push_back(Kind);
4100 switch (Kind) {
4101 case NestedNameSpecifier::Identifier:
4102 AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier(), Record);
4103 AddSourceRange(NNS.getLocalSourceRange(), Record);
4104 break;
4105
4106 case NestedNameSpecifier::Namespace:
4107 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace(), Record);
4108 AddSourceRange(NNS.getLocalSourceRange(), Record);
4109 break;
4110
4111 case NestedNameSpecifier::NamespaceAlias:
4112 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias(), Record);
4113 AddSourceRange(NNS.getLocalSourceRange(), Record);
4114 break;
4115
4116 case NestedNameSpecifier::TypeSpec:
4117 case NestedNameSpecifier::TypeSpecWithTemplate:
4118 Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
4119 AddTypeLoc(NNS.getTypeLoc(), Record);
4120 AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record);
4121 break;
4122
4123 case NestedNameSpecifier::Global:
4124 AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record);
4125 break;
4126 }
4127 }
4128 }
4129
AddTemplateName(TemplateName Name,RecordDataImpl & Record)4130 void ASTWriter::AddTemplateName(TemplateName Name, RecordDataImpl &Record) {
4131 TemplateName::NameKind Kind = Name.getKind();
4132 Record.push_back(Kind);
4133 switch (Kind) {
4134 case TemplateName::Template:
4135 AddDeclRef(Name.getAsTemplateDecl(), Record);
4136 break;
4137
4138 case TemplateName::OverloadedTemplate: {
4139 OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate();
4140 Record.push_back(OvT->size());
4141 for (OverloadedTemplateStorage::iterator I = OvT->begin(), E = OvT->end();
4142 I != E; ++I)
4143 AddDeclRef(*I, Record);
4144 break;
4145 }
4146
4147 case TemplateName::QualifiedTemplate: {
4148 QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName();
4149 AddNestedNameSpecifier(QualT->getQualifier(), Record);
4150 Record.push_back(QualT->hasTemplateKeyword());
4151 AddDeclRef(QualT->getTemplateDecl(), Record);
4152 break;
4153 }
4154
4155 case TemplateName::DependentTemplate: {
4156 DependentTemplateName *DepT = Name.getAsDependentTemplateName();
4157 AddNestedNameSpecifier(DepT->getQualifier(), Record);
4158 Record.push_back(DepT->isIdentifier());
4159 if (DepT->isIdentifier())
4160 AddIdentifierRef(DepT->getIdentifier(), Record);
4161 else
4162 Record.push_back(DepT->getOperator());
4163 break;
4164 }
4165
4166 case TemplateName::SubstTemplateTemplateParm: {
4167 SubstTemplateTemplateParmStorage *subst
4168 = Name.getAsSubstTemplateTemplateParm();
4169 AddDeclRef(subst->getParameter(), Record);
4170 AddTemplateName(subst->getReplacement(), Record);
4171 break;
4172 }
4173
4174 case TemplateName::SubstTemplateTemplateParmPack: {
4175 SubstTemplateTemplateParmPackStorage *SubstPack
4176 = Name.getAsSubstTemplateTemplateParmPack();
4177 AddDeclRef(SubstPack->getParameterPack(), Record);
4178 AddTemplateArgument(SubstPack->getArgumentPack(), Record);
4179 break;
4180 }
4181 }
4182 }
4183
AddTemplateArgument(const TemplateArgument & Arg,RecordDataImpl & Record)4184 void ASTWriter::AddTemplateArgument(const TemplateArgument &Arg,
4185 RecordDataImpl &Record) {
4186 Record.push_back(Arg.getKind());
4187 switch (Arg.getKind()) {
4188 case TemplateArgument::Null:
4189 break;
4190 case TemplateArgument::Type:
4191 AddTypeRef(Arg.getAsType(), Record);
4192 break;
4193 case TemplateArgument::Declaration:
4194 AddDeclRef(Arg.getAsDecl(), Record);
4195 break;
4196 case TemplateArgument::Integral:
4197 AddAPSInt(Arg.getAsIntegral(), Record);
4198 AddTypeRef(Arg.getIntegralType(), Record);
4199 break;
4200 case TemplateArgument::Template:
4201 AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record);
4202 break;
4203 case TemplateArgument::TemplateExpansion:
4204 AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record);
4205 if (llvm::Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions())
4206 Record.push_back(*NumExpansions + 1);
4207 else
4208 Record.push_back(0);
4209 break;
4210 case TemplateArgument::Expression:
4211 AddStmt(Arg.getAsExpr());
4212 break;
4213 case TemplateArgument::Pack:
4214 Record.push_back(Arg.pack_size());
4215 for (TemplateArgument::pack_iterator I=Arg.pack_begin(), E=Arg.pack_end();
4216 I != E; ++I)
4217 AddTemplateArgument(*I, Record);
4218 break;
4219 }
4220 }
4221
4222 void
AddTemplateParameterList(const TemplateParameterList * TemplateParams,RecordDataImpl & Record)4223 ASTWriter::AddTemplateParameterList(const TemplateParameterList *TemplateParams,
4224 RecordDataImpl &Record) {
4225 assert(TemplateParams && "No TemplateParams!");
4226 AddSourceLocation(TemplateParams->getTemplateLoc(), Record);
4227 AddSourceLocation(TemplateParams->getLAngleLoc(), Record);
4228 AddSourceLocation(TemplateParams->getRAngleLoc(), Record);
4229 Record.push_back(TemplateParams->size());
4230 for (TemplateParameterList::const_iterator
4231 P = TemplateParams->begin(), PEnd = TemplateParams->end();
4232 P != PEnd; ++P)
4233 AddDeclRef(*P, Record);
4234 }
4235
4236 /// \brief Emit a template argument list.
4237 void
AddTemplateArgumentList(const TemplateArgumentList * TemplateArgs,RecordDataImpl & Record)4238 ASTWriter::AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs,
4239 RecordDataImpl &Record) {
4240 assert(TemplateArgs && "No TemplateArgs!");
4241 Record.push_back(TemplateArgs->size());
4242 for (int i=0, e = TemplateArgs->size(); i != e; ++i)
4243 AddTemplateArgument(TemplateArgs->get(i), Record);
4244 }
4245
4246
4247 void
AddUnresolvedSet(const UnresolvedSetImpl & Set,RecordDataImpl & Record)4248 ASTWriter::AddUnresolvedSet(const UnresolvedSetImpl &Set, RecordDataImpl &Record) {
4249 Record.push_back(Set.size());
4250 for (UnresolvedSetImpl::const_iterator
4251 I = Set.begin(), E = Set.end(); I != E; ++I) {
4252 AddDeclRef(I.getDecl(), Record);
4253 Record.push_back(I.getAccess());
4254 }
4255 }
4256
AddCXXBaseSpecifier(const CXXBaseSpecifier & Base,RecordDataImpl & Record)4257 void ASTWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base,
4258 RecordDataImpl &Record) {
4259 Record.push_back(Base.isVirtual());
4260 Record.push_back(Base.isBaseOfClass());
4261 Record.push_back(Base.getAccessSpecifierAsWritten());
4262 Record.push_back(Base.getInheritConstructors());
4263 AddTypeSourceInfo(Base.getTypeSourceInfo(), Record);
4264 AddSourceRange(Base.getSourceRange(), Record);
4265 AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
4266 : SourceLocation(),
4267 Record);
4268 }
4269
FlushCXXBaseSpecifiers()4270 void ASTWriter::FlushCXXBaseSpecifiers() {
4271 RecordData Record;
4272 for (unsigned I = 0, N = CXXBaseSpecifiersToWrite.size(); I != N; ++I) {
4273 Record.clear();
4274
4275 // Record the offset of this base-specifier set.
4276 unsigned Index = CXXBaseSpecifiersToWrite[I].ID - 1;
4277 if (Index == CXXBaseSpecifiersOffsets.size())
4278 CXXBaseSpecifiersOffsets.push_back(Stream.GetCurrentBitNo());
4279 else {
4280 if (Index > CXXBaseSpecifiersOffsets.size())
4281 CXXBaseSpecifiersOffsets.resize(Index + 1);
4282 CXXBaseSpecifiersOffsets[Index] = Stream.GetCurrentBitNo();
4283 }
4284
4285 const CXXBaseSpecifier *B = CXXBaseSpecifiersToWrite[I].Bases,
4286 *BEnd = CXXBaseSpecifiersToWrite[I].BasesEnd;
4287 Record.push_back(BEnd - B);
4288 for (; B != BEnd; ++B)
4289 AddCXXBaseSpecifier(*B, Record);
4290 Stream.EmitRecord(serialization::DECL_CXX_BASE_SPECIFIERS, Record);
4291
4292 // Flush any expressions that were written as part of the base specifiers.
4293 FlushStmts();
4294 }
4295
4296 CXXBaseSpecifiersToWrite.clear();
4297 }
4298
AddCXXCtorInitializers(const CXXCtorInitializer * const * CtorInitializers,unsigned NumCtorInitializers,RecordDataImpl & Record)4299 void ASTWriter::AddCXXCtorInitializers(
4300 const CXXCtorInitializer * const *CtorInitializers,
4301 unsigned NumCtorInitializers,
4302 RecordDataImpl &Record) {
4303 Record.push_back(NumCtorInitializers);
4304 for (unsigned i=0; i != NumCtorInitializers; ++i) {
4305 const CXXCtorInitializer *Init = CtorInitializers[i];
4306
4307 if (Init->isBaseInitializer()) {
4308 Record.push_back(CTOR_INITIALIZER_BASE);
4309 AddTypeSourceInfo(Init->getTypeSourceInfo(), Record);
4310 Record.push_back(Init->isBaseVirtual());
4311 } else if (Init->isDelegatingInitializer()) {
4312 Record.push_back(CTOR_INITIALIZER_DELEGATING);
4313 AddTypeSourceInfo(Init->getTypeSourceInfo(), Record);
4314 } else if (Init->isMemberInitializer()){
4315 Record.push_back(CTOR_INITIALIZER_MEMBER);
4316 AddDeclRef(Init->getMember(), Record);
4317 } else {
4318 Record.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
4319 AddDeclRef(Init->getIndirectMember(), Record);
4320 }
4321
4322 AddSourceLocation(Init->getMemberLocation(), Record);
4323 AddStmt(Init->getInit());
4324 AddSourceLocation(Init->getLParenLoc(), Record);
4325 AddSourceLocation(Init->getRParenLoc(), Record);
4326 Record.push_back(Init->isWritten());
4327 if (Init->isWritten()) {
4328 Record.push_back(Init->getSourceOrder());
4329 } else {
4330 Record.push_back(Init->getNumArrayIndices());
4331 for (unsigned i=0, e=Init->getNumArrayIndices(); i != e; ++i)
4332 AddDeclRef(Init->getArrayIndex(i), Record);
4333 }
4334 }
4335 }
4336
AddCXXDefinitionData(const CXXRecordDecl * D,RecordDataImpl & Record)4337 void ASTWriter::AddCXXDefinitionData(const CXXRecordDecl *D, RecordDataImpl &Record) {
4338 assert(D->DefinitionData);
4339 struct CXXRecordDecl::DefinitionData &Data = *D->DefinitionData;
4340 Record.push_back(Data.IsLambda);
4341 Record.push_back(Data.UserDeclaredConstructor);
4342 Record.push_back(Data.UserDeclaredCopyConstructor);
4343 Record.push_back(Data.UserDeclaredMoveConstructor);
4344 Record.push_back(Data.UserDeclaredCopyAssignment);
4345 Record.push_back(Data.UserDeclaredMoveAssignment);
4346 Record.push_back(Data.UserDeclaredDestructor);
4347 Record.push_back(Data.Aggregate);
4348 Record.push_back(Data.PlainOldData);
4349 Record.push_back(Data.Empty);
4350 Record.push_back(Data.Polymorphic);
4351 Record.push_back(Data.Abstract);
4352 Record.push_back(Data.IsStandardLayout);
4353 Record.push_back(Data.HasNoNonEmptyBases);
4354 Record.push_back(Data.HasPrivateFields);
4355 Record.push_back(Data.HasProtectedFields);
4356 Record.push_back(Data.HasPublicFields);
4357 Record.push_back(Data.HasMutableFields);
4358 Record.push_back(Data.HasOnlyCMembers);
4359 Record.push_back(Data.HasInClassInitializer);
4360 Record.push_back(Data.HasTrivialDefaultConstructor);
4361 Record.push_back(Data.HasConstexprNonCopyMoveConstructor);
4362 Record.push_back(Data.DefaultedDefaultConstructorIsConstexpr);
4363 Record.push_back(Data.HasConstexprDefaultConstructor);
4364 Record.push_back(Data.HasTrivialCopyConstructor);
4365 Record.push_back(Data.HasTrivialMoveConstructor);
4366 Record.push_back(Data.HasTrivialCopyAssignment);
4367 Record.push_back(Data.HasTrivialMoveAssignment);
4368 Record.push_back(Data.HasTrivialDestructor);
4369 Record.push_back(Data.HasIrrelevantDestructor);
4370 Record.push_back(Data.HasNonLiteralTypeFieldsOrBases);
4371 Record.push_back(Data.ComputedVisibleConversions);
4372 Record.push_back(Data.UserProvidedDefaultConstructor);
4373 Record.push_back(Data.DeclaredDefaultConstructor);
4374 Record.push_back(Data.DeclaredCopyConstructor);
4375 Record.push_back(Data.DeclaredMoveConstructor);
4376 Record.push_back(Data.DeclaredCopyAssignment);
4377 Record.push_back(Data.DeclaredMoveAssignment);
4378 Record.push_back(Data.DeclaredDestructor);
4379 Record.push_back(Data.FailedImplicitMoveConstructor);
4380 Record.push_back(Data.FailedImplicitMoveAssignment);
4381 // IsLambda bit is already saved.
4382
4383 Record.push_back(Data.NumBases);
4384 if (Data.NumBases > 0)
4385 AddCXXBaseSpecifiersRef(Data.getBases(), Data.getBases() + Data.NumBases,
4386 Record);
4387
4388 // FIXME: Make VBases lazily computed when needed to avoid storing them.
4389 Record.push_back(Data.NumVBases);
4390 if (Data.NumVBases > 0)
4391 AddCXXBaseSpecifiersRef(Data.getVBases(), Data.getVBases() + Data.NumVBases,
4392 Record);
4393
4394 AddUnresolvedSet(Data.Conversions, Record);
4395 AddUnresolvedSet(Data.VisibleConversions, Record);
4396 // Data.Definition is the owning decl, no need to write it.
4397 AddDeclRef(Data.FirstFriend, Record);
4398
4399 // Add lambda-specific data.
4400 if (Data.IsLambda) {
4401 CXXRecordDecl::LambdaDefinitionData &Lambda = D->getLambdaData();
4402 Record.push_back(Lambda.Dependent);
4403 Record.push_back(Lambda.NumCaptures);
4404 Record.push_back(Lambda.NumExplicitCaptures);
4405 Record.push_back(Lambda.ManglingNumber);
4406 AddDeclRef(Lambda.ContextDecl, Record);
4407 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
4408 LambdaExpr::Capture &Capture = Lambda.Captures[I];
4409 AddSourceLocation(Capture.getLocation(), Record);
4410 Record.push_back(Capture.isImplicit());
4411 Record.push_back(Capture.getCaptureKind()); // FIXME: stable!
4412 VarDecl *Var = Capture.capturesVariable()? Capture.getCapturedVar() : 0;
4413 AddDeclRef(Var, Record);
4414 AddSourceLocation(Capture.isPackExpansion()? Capture.getEllipsisLoc()
4415 : SourceLocation(),
4416 Record);
4417 }
4418 }
4419 }
4420
ReaderInitialized(ASTReader * Reader)4421 void ASTWriter::ReaderInitialized(ASTReader *Reader) {
4422 assert(Reader && "Cannot remove chain");
4423 assert((!Chain || Chain == Reader) && "Cannot replace chain");
4424 assert(FirstDeclID == NextDeclID &&
4425 FirstTypeID == NextTypeID &&
4426 FirstIdentID == NextIdentID &&
4427 FirstSubmoduleID == NextSubmoduleID &&
4428 FirstSelectorID == NextSelectorID &&
4429 "Setting chain after writing has started.");
4430
4431 Chain = Reader;
4432
4433 FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls();
4434 FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes();
4435 FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers();
4436 FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
4437 FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
4438 NextDeclID = FirstDeclID;
4439 NextTypeID = FirstTypeID;
4440 NextIdentID = FirstIdentID;
4441 NextSelectorID = FirstSelectorID;
4442 NextSubmoduleID = FirstSubmoduleID;
4443 }
4444
IdentifierRead(IdentID ID,IdentifierInfo * II)4445 void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
4446 IdentifierIDs[II] = ID;
4447 if (II->hasMacroDefinition())
4448 DeserializedMacroNames.push_back(II);
4449 }
4450
TypeRead(TypeIdx Idx,QualType T)4451 void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
4452 // Always take the highest-numbered type index. This copes with an interesting
4453 // case for chained AST writing where we schedule writing the type and then,
4454 // later, deserialize the type from another AST. In this case, we want to
4455 // keep the higher-numbered entry so that we can properly write it out to
4456 // the AST file.
4457 TypeIdx &StoredIdx = TypeIdxs[T];
4458 if (Idx.getIndex() >= StoredIdx.getIndex())
4459 StoredIdx = Idx;
4460 }
4461
SelectorRead(SelectorID ID,Selector S)4462 void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
4463 SelectorIDs[S] = ID;
4464 }
4465
MacroDefinitionRead(serialization::PreprocessedEntityID ID,MacroDefinition * MD)4466 void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
4467 MacroDefinition *MD) {
4468 assert(MacroDefinitions.find(MD) == MacroDefinitions.end());
4469 MacroDefinitions[MD] = ID;
4470 }
4471
MacroVisible(IdentifierInfo * II)4472 void ASTWriter::MacroVisible(IdentifierInfo *II) {
4473 DeserializedMacroNames.push_back(II);
4474 }
4475
ModuleRead(serialization::SubmoduleID ID,Module * Mod)4476 void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
4477 assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end());
4478 SubmoduleIDs[Mod] = ID;
4479 }
4480
CompletedTagDefinition(const TagDecl * D)4481 void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
4482 assert(D->isCompleteDefinition());
4483 assert(!WritingAST && "Already writing the AST!");
4484 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
4485 // We are interested when a PCH decl is modified.
4486 if (RD->isFromASTFile()) {
4487 // A forward reference was mutated into a definition. Rewrite it.
4488 // FIXME: This happens during template instantiation, should we
4489 // have created a new definition decl instead ?
4490 RewriteDecl(RD);
4491 }
4492 }
4493 }
AddedVisibleDecl(const DeclContext * DC,const Decl * D)4494 void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
4495 assert(!WritingAST && "Already writing the AST!");
4496
4497 // TU and namespaces are handled elsewhere.
4498 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC))
4499 return;
4500
4501 if (!(!D->isFromASTFile() && cast<Decl>(DC)->isFromASTFile()))
4502 return; // Not a source decl added to a DeclContext from PCH.
4503
4504 AddUpdatedDeclContext(DC);
4505 UpdatingVisibleDecls.push_back(D);
4506 }
4507
AddedCXXImplicitMember(const CXXRecordDecl * RD,const Decl * D)4508 void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
4509 assert(!WritingAST && "Already writing the AST!");
4510 assert(D->isImplicit());
4511 if (!(!D->isFromASTFile() && RD->isFromASTFile()))
4512 return; // Not a source member added to a class from PCH.
4513 if (!isa<CXXMethodDecl>(D))
4514 return; // We are interested in lazily declared implicit methods.
4515
4516 // A decl coming from PCH was modified.
4517 assert(RD->isCompleteDefinition());
4518 UpdateRecord &Record = DeclUpdates[RD];
4519 Record.push_back(UPD_CXX_ADDED_IMPLICIT_MEMBER);
4520 Record.push_back(reinterpret_cast<uint64_t>(D));
4521 }
4522
AddedCXXTemplateSpecialization(const ClassTemplateDecl * TD,const ClassTemplateSpecializationDecl * D)4523 void ASTWriter::AddedCXXTemplateSpecialization(const ClassTemplateDecl *TD,
4524 const ClassTemplateSpecializationDecl *D) {
4525 // The specializations set is kept in the canonical template.
4526 assert(!WritingAST && "Already writing the AST!");
4527 TD = TD->getCanonicalDecl();
4528 if (!(!D->isFromASTFile() && TD->isFromASTFile()))
4529 return; // Not a source specialization added to a template from PCH.
4530
4531 UpdateRecord &Record = DeclUpdates[TD];
4532 Record.push_back(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION);
4533 Record.push_back(reinterpret_cast<uint64_t>(D));
4534 }
4535
AddedCXXTemplateSpecialization(const FunctionTemplateDecl * TD,const FunctionDecl * D)4536 void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
4537 const FunctionDecl *D) {
4538 // The specializations set is kept in the canonical template.
4539 assert(!WritingAST && "Already writing the AST!");
4540 TD = TD->getCanonicalDecl();
4541 if (!(!D->isFromASTFile() && TD->isFromASTFile()))
4542 return; // Not a source specialization added to a template from PCH.
4543
4544 UpdateRecord &Record = DeclUpdates[TD];
4545 Record.push_back(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION);
4546 Record.push_back(reinterpret_cast<uint64_t>(D));
4547 }
4548
CompletedImplicitDefinition(const FunctionDecl * D)4549 void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
4550 assert(!WritingAST && "Already writing the AST!");
4551 if (!D->isFromASTFile())
4552 return; // Declaration not imported from PCH.
4553
4554 // Implicit decl from a PCH was defined.
4555 // FIXME: Should implicit definition be a separate FunctionDecl?
4556 RewriteDecl(D);
4557 }
4558
StaticDataMemberInstantiated(const VarDecl * D)4559 void ASTWriter::StaticDataMemberInstantiated(const VarDecl *D) {
4560 assert(!WritingAST && "Already writing the AST!");
4561 if (!D->isFromASTFile())
4562 return;
4563
4564 // Since the actual instantiation is delayed, this really means that we need
4565 // to update the instantiation location.
4566 UpdateRecord &Record = DeclUpdates[D];
4567 Record.push_back(UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER);
4568 AddSourceLocation(
4569 D->getMemberSpecializationInfo()->getPointOfInstantiation(), Record);
4570 }
4571
AddedObjCCategoryToInterface(const ObjCCategoryDecl * CatD,const ObjCInterfaceDecl * IFD)4572 void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
4573 const ObjCInterfaceDecl *IFD) {
4574 assert(!WritingAST && "Already writing the AST!");
4575 if (!IFD->isFromASTFile())
4576 return; // Declaration not imported from PCH.
4577
4578 assert(IFD->getDefinition() && "Category on a class without a definition?");
4579 ObjCClassesWithCategories.insert(
4580 const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
4581 }
4582
4583
AddedObjCPropertyInClassExtension(const ObjCPropertyDecl * Prop,const ObjCPropertyDecl * OrigProp,const ObjCCategoryDecl * ClassExt)4584 void ASTWriter::AddedObjCPropertyInClassExtension(const ObjCPropertyDecl *Prop,
4585 const ObjCPropertyDecl *OrigProp,
4586 const ObjCCategoryDecl *ClassExt) {
4587 const ObjCInterfaceDecl *D = ClassExt->getClassInterface();
4588 if (!D)
4589 return;
4590
4591 assert(!WritingAST && "Already writing the AST!");
4592 if (!D->isFromASTFile())
4593 return; // Declaration not imported from PCH.
4594
4595 RewriteDecl(D);
4596 }
4597