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