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