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