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