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