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