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