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