blob: 8a3b9d5163ffad5dc7f567a9a561fc5af849de5a [file] [log] [blame]
Sebastian Redld6522cf2010-08-18 23:56:31 +00001//===--- ASTWriter.cpp - AST File Writer ----------------------------------===//
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Sebastian Redl55c0ad52010-08-18 23:56:21 +000010// This file defines the ASTWriter class, which writes AST files.
Douglas Gregoref84c4b2009-04-09 22:27:44 +000011//
12//===----------------------------------------------------------------------===//
13
Sebastian Redl1914c6f2010-08-18 23:56:37 +000014#include "clang/Serialization/ASTWriter.h"
Argyrios Kyrtzidis4bd97102010-08-20 16:03:52 +000015#include "ASTCommon.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000016#include "clang/AST/ASTContext.h"
17#include "clang/AST/Decl.h"
18#include "clang/AST/DeclContextInternals.h"
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +000019#include "clang/AST/DeclFriend.h"
Richard Smith961eae52014-03-25 01:14:22 +000020#include "clang/AST/DeclLookups.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/AST/DeclTemplate.h"
Douglas Gregorfeb84b02009-04-14 21:18:50 +000022#include "clang/AST/Expr.h"
John McCallbfd822c2010-08-24 07:32:53 +000023#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000024#include "clang/AST/Type.h"
John McCall8f115c62009-10-16 21:56:05 +000025#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000026#include "clang/Basic/DiagnosticOptions.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000027#include "clang/Basic/FileManager.h"
Chris Lattner226efd32010-11-23 19:19:34 +000028#include "clang/Basic/FileSystemStatCache.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000029#include "clang/Basic/SourceManager.h"
Douglas Gregor4c7626e2009-04-13 16:31:14 +000030#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregorbfbde532009-04-10 21:16:55 +000031#include "clang/Basic/TargetInfo.h"
Douglas Gregorcb177f12012-10-16 23:40:58 +000032#include "clang/Basic/TargetOptions.h"
Douglas Gregor7b71e632009-04-27 22:23:34 +000033#include "clang/Basic/Version.h"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000034#include "clang/Basic/VersionTuple.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000035#include "clang/Lex/HeaderSearch.h"
36#include "clang/Lex/HeaderSearchOptions.h"
37#include "clang/Lex/MacroInfo.h"
38#include "clang/Lex/PreprocessingRecord.h"
39#include "clang/Lex/Preprocessor.h"
40#include "clang/Lex/PreprocessorOptions.h"
41#include "clang/Sema/IdentifierResolver.h"
42#include "clang/Sema/Sema.h"
43#include "clang/Serialization/ASTReader.h"
Douglas Gregore0a3a512009-04-14 21:55:33 +000044#include "llvm/ADT/APFloat.h"
45#include "llvm/ADT/APInt.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000046#include "llvm/ADT/Hashing.h"
Daniel Dunbarf8502d52009-10-17 23:52:28 +000047#include "llvm/ADT/StringExtras.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000048#include "llvm/Bitcode/BitstreamWriter.h"
Justin Bognere1c147c2014-03-28 22:03:19 +000049#include "llvm/Support/EndianStream.h"
Michael J. Spencer740857f2010-12-21 16:45:57 +000050#include "llvm/Support/FileSystem.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000051#include "llvm/Support/MemoryBuffer.h"
Justin Bognerbb094f02014-04-18 19:57:06 +000052#include "llvm/Support/OnDiskHashTable.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000053#include "llvm/Support/Path.h"
Ben Langmuir487ea142014-10-23 18:05:36 +000054#include "llvm/Support/Process.h"
Douglas Gregor925296b2011-07-19 16:10:42 +000055#include <algorithm>
Chris Lattner225dd6c2009-04-11 18:40:46 +000056#include <cstdio>
Douglas Gregor09b69892011-02-10 17:09:37 +000057#include <string.h>
Douglas Gregor925296b2011-07-19 16:10:42 +000058#include <utility>
Douglas Gregoref84c4b2009-04-09 22:27:44 +000059using namespace clang;
Sebastian Redl539c5062010-08-18 23:57:32 +000060using namespace clang::serialization;
Douglas Gregoref84c4b2009-04-09 22:27:44 +000061
Sebastian Redl3df5a082010-07-30 17:03:48 +000062template <typename T, typename Allocator>
Chris Lattner0e62c1c2011-07-23 10:55:15 +000063static StringRef data(const std::vector<T, Allocator> &v) {
64 if (v.empty()) return StringRef();
65 return StringRef(reinterpret_cast<const char*>(&v[0]),
Benjamin Kramerd47a12a2011-04-24 17:44:50 +000066 sizeof(T) * v.size());
Sebastian Redl3df5a082010-07-30 17:03:48 +000067}
Benjamin Kramerd47a12a2011-04-24 17:44:50 +000068
69template <typename T>
Chris Lattner0e62c1c2011-07-23 10:55:15 +000070static StringRef data(const SmallVectorImpl<T> &v) {
71 return StringRef(reinterpret_cast<const char*>(v.data()),
Benjamin Kramerd47a12a2011-04-24 17:44:50 +000072 sizeof(T) * v.size());
Sebastian Redl3df5a082010-07-30 17:03:48 +000073}
74
Douglas Gregoref84c4b2009-04-09 22:27:44 +000075//===----------------------------------------------------------------------===//
76// Type serialization
77//===----------------------------------------------------------------------===//
Chris Lattner7099dbc2009-04-27 06:16:06 +000078
Douglas Gregoref84c4b2009-04-09 22:27:44 +000079namespace {
Sebastian Redl42a0f6a2010-08-18 23:56:27 +000080 class ASTTypeWriter {
Sebastian Redl55c0ad52010-08-18 23:56:21 +000081 ASTWriter &Writer;
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +000082 ASTWriter::RecordDataImpl &Record;
Douglas Gregoref84c4b2009-04-09 22:27:44 +000083
84 public:
85 /// \brief Type code that corresponds to the record generated.
Sebastian Redl539c5062010-08-18 23:57:32 +000086 TypeCode Code;
Richard Smith01b2cb42014-07-26 06:37:51 +000087 /// \brief Abbreviation to use for the record, if any.
88 unsigned AbbrevToUse;
Douglas Gregoref84c4b2009-04-09 22:27:44 +000089
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +000090 ASTTypeWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
Sebastian Redl539c5062010-08-18 23:57:32 +000091 : Writer(Writer), Record(Record), Code(TYPE_EXT_QUAL) { }
Douglas Gregoref84c4b2009-04-09 22:27:44 +000092
93 void VisitArrayType(const ArrayType *T);
94 void VisitFunctionType(const FunctionType *T);
95 void VisitTagType(const TagType *T);
96
97#define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
98#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref84c4b2009-04-09 22:27:44 +000099#include "clang/AST/TypeNodes.def"
100 };
101}
102
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000103void ASTTypeWriter::VisitBuiltinType(const BuiltinType *T) {
David Blaikie83d382b2011-09-23 05:06:16 +0000104 llvm_unreachable("Built-in types are never serialized");
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000105}
106
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000107void ASTTypeWriter::VisitComplexType(const ComplexType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000108 Writer.AddTypeRef(T->getElementType(), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000109 Code = TYPE_COMPLEX;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000110}
111
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000112void ASTTypeWriter::VisitPointerType(const PointerType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000113 Writer.AddTypeRef(T->getPointeeType(), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000114 Code = TYPE_POINTER;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000115}
116
Reid Kleckner8a365022013-06-24 17:51:48 +0000117void ASTTypeWriter::VisitDecayedType(const DecayedType *T) {
118 Writer.AddTypeRef(T->getOriginalType(), Record);
119 Code = TYPE_DECAYED;
120}
121
Reid Kleckner0503a872013-12-05 01:23:43 +0000122void ASTTypeWriter::VisitAdjustedType(const AdjustedType *T) {
123 Writer.AddTypeRef(T->getOriginalType(), Record);
124 Writer.AddTypeRef(T->getAdjustedType(), Record);
125 Code = TYPE_ADJUSTED;
126}
127
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000128void ASTTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
Mike Stump11289f42009-09-09 15:08:12 +0000129 Writer.AddTypeRef(T->getPointeeType(), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000130 Code = TYPE_BLOCK_POINTER;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000131}
132
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000133void ASTTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
Richard Smith0f538462011-04-12 10:38:03 +0000134 Writer.AddTypeRef(T->getPointeeTypeAsWritten(), Record);
135 Record.push_back(T->isSpelledAsLValue());
Sebastian Redl539c5062010-08-18 23:57:32 +0000136 Code = TYPE_LVALUE_REFERENCE;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000137}
138
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000139void ASTTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
Richard Smith0f538462011-04-12 10:38:03 +0000140 Writer.AddTypeRef(T->getPointeeTypeAsWritten(), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000141 Code = TYPE_RVALUE_REFERENCE;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000142}
143
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000144void ASTTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
Mike Stump11289f42009-09-09 15:08:12 +0000145 Writer.AddTypeRef(T->getPointeeType(), Record);
146 Writer.AddTypeRef(QualType(T->getClass(), 0), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000147 Code = TYPE_MEMBER_POINTER;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000148}
149
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000150void ASTTypeWriter::VisitArrayType(const ArrayType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000151 Writer.AddTypeRef(T->getElementType(), Record);
152 Record.push_back(T->getSizeModifier()); // FIXME: stable values
John McCall8ccfcb52009-09-24 19:53:00 +0000153 Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000154}
155
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000156void ASTTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000157 VisitArrayType(T);
158 Writer.AddAPInt(T->getSize(), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000159 Code = TYPE_CONSTANT_ARRAY;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000160}
161
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000162void ASTTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000163 VisitArrayType(T);
Sebastian Redl539c5062010-08-18 23:57:32 +0000164 Code = TYPE_INCOMPLETE_ARRAY;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000165}
166
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000167void ASTTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000168 VisitArrayType(T);
Douglas Gregor04318252009-07-06 15:59:29 +0000169 Writer.AddSourceLocation(T->getLBracketLoc(), Record);
170 Writer.AddSourceLocation(T->getRBracketLoc(), Record);
Douglas Gregor8f45df52009-04-16 22:23:12 +0000171 Writer.AddStmt(T->getSizeExpr());
Sebastian Redl539c5062010-08-18 23:57:32 +0000172 Code = TYPE_VARIABLE_ARRAY;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000173}
174
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000175void ASTTypeWriter::VisitVectorType(const VectorType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000176 Writer.AddTypeRef(T->getElementType(), Record);
177 Record.push_back(T->getNumElements());
Bob Wilsonaeb56442010-11-10 21:56:12 +0000178 Record.push_back(T->getVectorKind());
Sebastian Redl539c5062010-08-18 23:57:32 +0000179 Code = TYPE_VECTOR;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000180}
181
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000182void ASTTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000183 VisitVectorType(T);
Sebastian Redl539c5062010-08-18 23:57:32 +0000184 Code = TYPE_EXT_VECTOR;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000185}
186
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000187void ASTTypeWriter::VisitFunctionType(const FunctionType *T) {
Alp Toker314cc812014-01-25 16:55:45 +0000188 Writer.AddTypeRef(T->getReturnType(), Record);
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000189 FunctionType::ExtInfo C = T->getExtInfo();
190 Record.push_back(C.getNoReturn());
Eli Friedmanc5b20b52011-04-09 08:18:08 +0000191 Record.push_back(C.getHasRegParm());
Rafael Espindola49b85ab2010-03-30 22:15:11 +0000192 Record.push_back(C.getRegParm());
Douglas Gregor8c940862010-01-18 17:14:39 +0000193 // FIXME: need to stabilize encoding of calling convention...
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000194 Record.push_back(C.getCC());
John McCall31168b02011-06-15 23:02:42 +0000195 Record.push_back(C.getProducesResult());
Richard Smith01b2cb42014-07-26 06:37:51 +0000196
197 if (C.getHasRegParm() || C.getRegParm() || C.getProducesResult())
198 AbbrevToUse = 0;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000199}
200
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000201void ASTTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000202 VisitFunctionType(T);
Sebastian Redl539c5062010-08-18 23:57:32 +0000203 Code = TYPE_FUNCTION_NO_PROTO;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000204}
205
Richard Smith564417a2014-03-20 21:47:22 +0000206static void addExceptionSpec(ASTWriter &Writer, const FunctionProtoType *T,
207 ASTWriter::RecordDataImpl &Record) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000208 Record.push_back(T->getExceptionSpecType());
209 if (T->getExceptionSpecType() == EST_Dynamic) {
210 Record.push_back(T->getNumExceptions());
211 for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
212 Writer.AddTypeRef(T->getExceptionType(I), Record);
213 } else if (T->getExceptionSpecType() == EST_ComputedNoexcept) {
214 Writer.AddStmt(T->getNoexceptExpr());
Richard Smith8b987a92012-04-21 17:47:47 +0000215 } else if (T->getExceptionSpecType() == EST_Uninstantiated) {
216 Writer.AddDeclRef(T->getExceptionSpecDecl(), Record);
217 Writer.AddDeclRef(T->getExceptionSpecTemplate(), Record);
Richard Smithd3b5c9082012-07-27 04:22:15 +0000218 } else if (T->getExceptionSpecType() == EST_Unevaluated) {
219 Writer.AddDeclRef(T->getExceptionSpecDecl(), Record);
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000220 }
Richard Smith564417a2014-03-20 21:47:22 +0000221}
222
223void ASTTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
224 VisitFunctionType(T);
Richard Smith01b2cb42014-07-26 06:37:51 +0000225
Richard Smith564417a2014-03-20 21:47:22 +0000226 Record.push_back(T->isVariadic());
227 Record.push_back(T->hasTrailingReturn());
228 Record.push_back(T->getTypeQuals());
229 Record.push_back(static_cast<unsigned>(T->getRefQualifier()));
230 addExceptionSpec(Writer, T, Record);
Richard Smith01b2cb42014-07-26 06:37:51 +0000231
232 Record.push_back(T->getNumParams());
233 for (unsigned I = 0, N = T->getNumParams(); I != N; ++I)
234 Writer.AddTypeRef(T->getParamType(I), Record);
235
236 if (T->isVariadic() || T->hasTrailingReturn() || T->getTypeQuals() ||
237 T->getRefQualifier() || T->getExceptionSpecType() != EST_None)
238 AbbrevToUse = 0;
239
Sebastian Redl539c5062010-08-18 23:57:32 +0000240 Code = TYPE_FUNCTION_PROTO;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000241}
242
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000243void ASTTypeWriter::VisitUnresolvedUsingType(const UnresolvedUsingType *T) {
John McCallb96ec562009-12-04 22:46:56 +0000244 Writer.AddDeclRef(T->getDecl(), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000245 Code = TYPE_UNRESOLVED_USING;
John McCallb96ec562009-12-04 22:46:56 +0000246}
John McCallb96ec562009-12-04 22:46:56 +0000247
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000248void ASTTypeWriter::VisitTypedefType(const TypedefType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000249 Writer.AddDeclRef(T->getDecl(), Record);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +0000250 assert(!T->isCanonicalUnqualified() && "Invalid typedef ?");
251 Writer.AddTypeRef(T->getCanonicalTypeInternal(), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000252 Code = TYPE_TYPEDEF;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000253}
254
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000255void ASTTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
Douglas Gregor8f45df52009-04-16 22:23:12 +0000256 Writer.AddStmt(T->getUnderlyingExpr());
Sebastian Redl539c5062010-08-18 23:57:32 +0000257 Code = TYPE_TYPEOF_EXPR;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000258}
259
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000260void ASTTypeWriter::VisitTypeOfType(const TypeOfType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000261 Writer.AddTypeRef(T->getUnderlyingType(), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000262 Code = TYPE_TYPEOF;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000263}
264
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000265void ASTTypeWriter::VisitDecltypeType(const DecltypeType *T) {
Douglas Gregor81495f32012-02-12 18:42:33 +0000266 Writer.AddTypeRef(T->getUnderlyingType(), Record);
Anders Carlsson81df7b82009-06-24 19:06:50 +0000267 Writer.AddStmt(T->getUnderlyingExpr());
Sebastian Redl539c5062010-08-18 23:57:32 +0000268 Code = TYPE_DECLTYPE;
Anders Carlsson81df7b82009-06-24 19:06:50 +0000269}
270
Alexis Hunte852b102011-05-24 22:41:36 +0000271void ASTTypeWriter::VisitUnaryTransformType(const UnaryTransformType *T) {
272 Writer.AddTypeRef(T->getBaseType(), Record);
273 Writer.AddTypeRef(T->getUnderlyingType(), Record);
274 Record.push_back(T->getUTTKind());
275 Code = TYPE_UNARY_TRANSFORM;
276}
277
Richard Smith30482bc2011-02-20 03:19:35 +0000278void ASTTypeWriter::VisitAutoType(const AutoType *T) {
279 Writer.AddTypeRef(T->getDeducedType(), Record);
Richard Smith74aeef52013-04-26 16:15:35 +0000280 Record.push_back(T->isDecltypeAuto());
Richard Smith27d807c2013-04-30 13:56:41 +0000281 if (T->getDeducedType().isNull())
282 Record.push_back(T->isDependentType());
Richard Smith30482bc2011-02-20 03:19:35 +0000283 Code = TYPE_AUTO;
284}
285
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000286void ASTTypeWriter::VisitTagType(const TagType *T) {
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +0000287 Record.push_back(T->isDependentType());
Douglas Gregorf3bccd72012-01-17 19:21:53 +0000288 Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
Mike Stump11289f42009-09-09 15:08:12 +0000289 assert(!T->isBeingDefined() &&
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000290 "Cannot serialize in the middle of a type definition");
291}
292
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000293void ASTTypeWriter::VisitRecordType(const RecordType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000294 VisitTagType(T);
Sebastian Redl539c5062010-08-18 23:57:32 +0000295 Code = TYPE_RECORD;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000296}
297
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000298void ASTTypeWriter::VisitEnumType(const EnumType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000299 VisitTagType(T);
Sebastian Redl539c5062010-08-18 23:57:32 +0000300 Code = TYPE_ENUM;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000301}
302
John McCall81904512011-01-06 01:58:22 +0000303void ASTTypeWriter::VisitAttributedType(const AttributedType *T) {
304 Writer.AddTypeRef(T->getModifiedType(), Record);
305 Writer.AddTypeRef(T->getEquivalentType(), Record);
306 Record.push_back(T->getAttrKind());
307 Code = TYPE_ATTRIBUTED;
308}
309
Mike Stump11289f42009-09-09 15:08:12 +0000310void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000311ASTTypeWriter::VisitSubstTemplateTypeParmType(
John McCallcebee162009-10-18 09:09:24 +0000312 const SubstTemplateTypeParmType *T) {
313 Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record);
314 Writer.AddTypeRef(T->getReplacementType(), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000315 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM;
John McCallcebee162009-10-18 09:09:24 +0000316}
317
318void
Douglas Gregorada4b792011-01-14 02:55:32 +0000319ASTTypeWriter::VisitSubstTemplateTypeParmPackType(
320 const SubstTemplateTypeParmPackType *T) {
321 Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record);
322 Writer.AddTemplateArgument(T->getArgumentPack(), Record);
323 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK;
324}
325
326void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000327ASTTypeWriter::VisitTemplateSpecializationType(
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000328 const TemplateSpecializationType *T) {
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +0000329 Record.push_back(T->isDependentType());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000330 Writer.AddTemplateName(T->getTemplateName(), Record);
331 Record.push_back(T->getNumArgs());
332 for (TemplateSpecializationType::iterator ArgI = T->begin(), ArgE = T->end();
333 ArgI != ArgE; ++ArgI)
334 Writer.AddTemplateArgument(*ArgI, Record);
Richard Smith3f1b5d02011-05-05 21:57:07 +0000335 Writer.AddTypeRef(T->isTypeAlias() ? T->getAliasedType() :
336 T->isCanonicalUnqualified() ? QualType()
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +0000337 : T->getCanonicalTypeInternal(),
338 Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000339 Code = TYPE_TEMPLATE_SPECIALIZATION;
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000340}
341
342void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000343ASTTypeWriter::VisitDependentSizedArrayType(const DependentSizedArrayType *T) {
Argyrios Kyrtzidis4a57bd02010-06-30 08:49:25 +0000344 VisitArrayType(T);
345 Writer.AddStmt(T->getSizeExpr());
346 Writer.AddSourceRange(T->getBracketsRange(), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000347 Code = TYPE_DEPENDENT_SIZED_ARRAY;
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000348}
349
350void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000351ASTTypeWriter::VisitDependentSizedExtVectorType(
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000352 const DependentSizedExtVectorType *T) {
353 // FIXME: Serialize this type (C++ only)
David Blaikie83d382b2011-09-23 05:06:16 +0000354 llvm_unreachable("Cannot serialize dependent sized extended vector types");
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000355}
356
357void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000358ASTTypeWriter::VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000359 Record.push_back(T->getDepth());
360 Record.push_back(T->getIndex());
361 Record.push_back(T->isParameterPack());
Chandler Carruth08836322011-05-01 00:51:33 +0000362 Writer.AddDeclRef(T->getDecl(), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000363 Code = TYPE_TEMPLATE_TYPE_PARM;
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000364}
365
366void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000367ASTTypeWriter::VisitDependentNameType(const DependentNameType *T) {
Argyrios Kyrtzidisbfcacee2010-06-24 08:57:31 +0000368 Record.push_back(T->getKeyword());
369 Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
370 Writer.AddIdentifierRef(T->getIdentifier(), Record);
Argyrios Kyrtzidise9290952010-07-02 11:55:24 +0000371 Writer.AddTypeRef(T->isCanonicalUnqualified() ? QualType()
372 : T->getCanonicalTypeInternal(),
373 Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000374 Code = TYPE_DEPENDENT_NAME;
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000375}
376
377void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000378ASTTypeWriter::VisitDependentTemplateSpecializationType(
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000379 const DependentTemplateSpecializationType *T) {
Argyrios Kyrtzidisf0f7a792010-06-25 16:24:58 +0000380 Record.push_back(T->getKeyword());
381 Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
382 Writer.AddIdentifierRef(T->getIdentifier(), Record);
383 Record.push_back(T->getNumArgs());
384 for (DependentTemplateSpecializationType::iterator
385 I = T->begin(), E = T->end(); I != E; ++I)
386 Writer.AddTemplateArgument(*I, Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000387 Code = TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000388}
389
Douglas Gregord2fa7662010-12-20 02:24:11 +0000390void ASTTypeWriter::VisitPackExpansionType(const PackExpansionType *T) {
391 Writer.AddTypeRef(T->getPattern(), Record);
David Blaikie05785d12013-02-20 22:23:23 +0000392 if (Optional<unsigned> NumExpansions = T->getNumExpansions())
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000393 Record.push_back(*NumExpansions + 1);
394 else
395 Record.push_back(0);
Douglas Gregord2fa7662010-12-20 02:24:11 +0000396 Code = TYPE_PACK_EXPANSION;
397}
398
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000399void ASTTypeWriter::VisitParenType(const ParenType *T) {
400 Writer.AddTypeRef(T->getInnerType(), Record);
401 Code = TYPE_PAREN;
402}
403
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000404void ASTTypeWriter::VisitElaboratedType(const ElaboratedType *T) {
Abramo Bagnara6150c882010-05-11 21:36:43 +0000405 Record.push_back(T->getKeyword());
Argyrios Kyrtzidisf0f7a792010-06-25 16:24:58 +0000406 Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
407 Writer.AddTypeRef(T->getNamedType(), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000408 Code = TYPE_ELABORATED;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000409}
410
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000411void ASTTypeWriter::VisitInjectedClassNameType(const InjectedClassNameType *T) {
Douglas Gregor9f218892012-03-26 15:52:37 +0000412 Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
John McCall2408e322010-04-27 00:57:59 +0000413 Writer.AddTypeRef(T->getInjectedSpecializationType(), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000414 Code = TYPE_INJECTED_CLASS_NAME;
John McCalle78aac42010-03-10 03:28:59 +0000415}
416
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000417void ASTTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
Douglas Gregorf3bccd72012-01-17 19:21:53 +0000418 Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000419 Code = TYPE_OBJC_INTERFACE;
John McCall8b07ec22010-05-15 11:32:37 +0000420}
421
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000422void ASTTypeWriter::VisitObjCObjectType(const ObjCObjectType *T) {
John McCall8b07ec22010-05-15 11:32:37 +0000423 Writer.AddTypeRef(T->getBaseType(), Record);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000424 Record.push_back(T->getNumProtocols());
Aaron Ballman1683f7b2014-03-17 15:55:30 +0000425 for (const auto *I : T->quals())
426 Writer.AddDeclRef(I, Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000427 Code = TYPE_OBJC_OBJECT;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000428}
429
Steve Narofffb4330f2009-06-17 22:40:22 +0000430void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000431ASTTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
Mike Stump11289f42009-09-09 15:08:12 +0000432 Writer.AddTypeRef(T->getPointeeType(), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000433 Code = TYPE_OBJC_OBJECT_POINTER;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000434}
435
Eli Friedman0dfb8892011-10-06 23:00:33 +0000436void
437ASTTypeWriter::VisitAtomicType(const AtomicType *T) {
438 Writer.AddTypeRef(T->getValueType(), Record);
439 Code = TYPE_ATOMIC;
440}
441
John McCall8f115c62009-10-16 21:56:05 +0000442namespace {
443
444class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
Sebastian Redl55c0ad52010-08-18 23:56:21 +0000445 ASTWriter &Writer;
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000446 ASTWriter::RecordDataImpl &Record;
John McCall8f115c62009-10-16 21:56:05 +0000447
448public:
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000449 TypeLocWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
John McCall8f115c62009-10-16 21:56:05 +0000450 : Writer(Writer), Record(Record) { }
451
John McCall17001972009-10-18 01:05:36 +0000452#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCall8f115c62009-10-16 21:56:05 +0000453#define TYPELOC(CLASS, PARENT) \
John McCall17001972009-10-18 01:05:36 +0000454 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCall8f115c62009-10-16 21:56:05 +0000455#include "clang/AST/TypeLocNodes.def"
456
John McCall17001972009-10-18 01:05:36 +0000457 void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
458 void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
John McCall8f115c62009-10-16 21:56:05 +0000459};
460
461}
462
John McCall17001972009-10-18 01:05:36 +0000463void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
464 // nothing to do
John McCall8f115c62009-10-16 21:56:05 +0000465}
John McCall17001972009-10-18 01:05:36 +0000466void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Douglas Gregorc9b7a592010-01-18 18:04:31 +0000467 Writer.AddSourceLocation(TL.getBuiltinLoc(), Record);
468 if (TL.needsExtraLocalData()) {
469 Record.push_back(TL.getWrittenTypeSpec());
470 Record.push_back(TL.getWrittenSignSpec());
471 Record.push_back(TL.getWrittenWidthSpec());
472 Record.push_back(TL.hasModeAttr());
473 }
John McCall8f115c62009-10-16 21:56:05 +0000474}
John McCall17001972009-10-18 01:05:36 +0000475void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
476 Writer.AddSourceLocation(TL.getNameLoc(), Record);
John McCall8f115c62009-10-16 21:56:05 +0000477}
John McCall17001972009-10-18 01:05:36 +0000478void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
479 Writer.AddSourceLocation(TL.getStarLoc(), Record);
John McCall8f115c62009-10-16 21:56:05 +0000480}
Reid Kleckner8a365022013-06-24 17:51:48 +0000481void TypeLocWriter::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
482 // nothing to do
483}
Reid Kleckner0503a872013-12-05 01:23:43 +0000484void TypeLocWriter::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
485 // nothing to do
486}
John McCall17001972009-10-18 01:05:36 +0000487void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
488 Writer.AddSourceLocation(TL.getCaretLoc(), Record);
John McCall8f115c62009-10-16 21:56:05 +0000489}
John McCall17001972009-10-18 01:05:36 +0000490void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
491 Writer.AddSourceLocation(TL.getAmpLoc(), Record);
John McCall8f115c62009-10-16 21:56:05 +0000492}
John McCall17001972009-10-18 01:05:36 +0000493void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
494 Writer.AddSourceLocation(TL.getAmpAmpLoc(), Record);
John McCall8f115c62009-10-16 21:56:05 +0000495}
John McCall17001972009-10-18 01:05:36 +0000496void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
497 Writer.AddSourceLocation(TL.getStarLoc(), Record);
Abramo Bagnara509357842011-03-05 14:42:21 +0000498 Writer.AddTypeSourceInfo(TL.getClassTInfo(), Record);
John McCall8f115c62009-10-16 21:56:05 +0000499}
John McCall17001972009-10-18 01:05:36 +0000500void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
501 Writer.AddSourceLocation(TL.getLBracketLoc(), Record);
502 Writer.AddSourceLocation(TL.getRBracketLoc(), Record);
503 Record.push_back(TL.getSizeExpr() ? 1 : 0);
504 if (TL.getSizeExpr())
505 Writer.AddStmt(TL.getSizeExpr());
John McCall8f115c62009-10-16 21:56:05 +0000506}
John McCall17001972009-10-18 01:05:36 +0000507void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
508 VisitArrayTypeLoc(TL);
509}
510void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
511 VisitArrayTypeLoc(TL);
512}
513void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
514 VisitArrayTypeLoc(TL);
515}
516void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
517 DependentSizedArrayTypeLoc TL) {
518 VisitArrayTypeLoc(TL);
519}
520void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
521 DependentSizedExtVectorTypeLoc TL) {
522 Writer.AddSourceLocation(TL.getNameLoc(), Record);
523}
524void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
525 Writer.AddSourceLocation(TL.getNameLoc(), Record);
526}
527void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
528 Writer.AddSourceLocation(TL.getNameLoc(), Record);
529}
530void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +0000531 Writer.AddSourceLocation(TL.getLocalRangeBegin(), Record);
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +0000532 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
533 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +0000534 Writer.AddSourceLocation(TL.getLocalRangeEnd(), Record);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +0000535 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i)
536 Writer.AddDeclRef(TL.getParam(i), Record);
John McCall17001972009-10-18 01:05:36 +0000537}
538void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
539 VisitFunctionTypeLoc(TL);
540}
541void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
542 VisitFunctionTypeLoc(TL);
543}
John McCallb96ec562009-12-04 22:46:56 +0000544void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
545 Writer.AddSourceLocation(TL.getNameLoc(), Record);
546}
John McCall17001972009-10-18 01:05:36 +0000547void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
548 Writer.AddSourceLocation(TL.getNameLoc(), Record);
549}
550void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
John McCalle8595032010-01-13 20:03:27 +0000551 Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
552 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
553 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
John McCall17001972009-10-18 01:05:36 +0000554}
555void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
John McCalle8595032010-01-13 20:03:27 +0000556 Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
557 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
558 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
559 Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record);
John McCall17001972009-10-18 01:05:36 +0000560}
561void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
562 Writer.AddSourceLocation(TL.getNameLoc(), Record);
563}
Alexis Hunte852b102011-05-24 22:41:36 +0000564void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
565 Writer.AddSourceLocation(TL.getKWLoc(), Record);
566 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
567 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
568 Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record);
569}
Richard Smith30482bc2011-02-20 03:19:35 +0000570void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
571 Writer.AddSourceLocation(TL.getNameLoc(), Record);
572}
John McCall17001972009-10-18 01:05:36 +0000573void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
574 Writer.AddSourceLocation(TL.getNameLoc(), Record);
575}
576void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
577 Writer.AddSourceLocation(TL.getNameLoc(), Record);
578}
John McCall81904512011-01-06 01:58:22 +0000579void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
580 Writer.AddSourceLocation(TL.getAttrNameLoc(), Record);
581 if (TL.hasAttrOperand()) {
582 SourceRange range = TL.getAttrOperandParensRange();
583 Writer.AddSourceLocation(range.getBegin(), Record);
584 Writer.AddSourceLocation(range.getEnd(), Record);
585 }
586 if (TL.hasAttrExprOperand()) {
587 Expr *operand = TL.getAttrExprOperand();
588 Record.push_back(operand ? 1 : 0);
589 if (operand) Writer.AddStmt(operand);
590 } else if (TL.hasAttrEnumOperand()) {
591 Writer.AddSourceLocation(TL.getAttrEnumOperandLoc(), Record);
592 }
593}
John McCall17001972009-10-18 01:05:36 +0000594void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
595 Writer.AddSourceLocation(TL.getNameLoc(), Record);
596}
John McCallcebee162009-10-18 09:09:24 +0000597void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
598 SubstTemplateTypeParmTypeLoc TL) {
599 Writer.AddSourceLocation(TL.getNameLoc(), Record);
600}
Douglas Gregorada4b792011-01-14 02:55:32 +0000601void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
602 SubstTemplateTypeParmPackTypeLoc TL) {
603 Writer.AddSourceLocation(TL.getNameLoc(), Record);
604}
John McCall17001972009-10-18 01:05:36 +0000605void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
606 TemplateSpecializationTypeLoc TL) {
Abramo Bagnara48c05be2012-02-06 14:41:24 +0000607 Writer.AddSourceLocation(TL.getTemplateKeywordLoc(), Record);
John McCall0ad16662009-10-29 08:12:44 +0000608 Writer.AddSourceLocation(TL.getTemplateNameLoc(), Record);
609 Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
610 Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
611 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +0000612 Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
613 TL.getArgLoc(i).getLocInfo(), Record);
John McCall17001972009-10-18 01:05:36 +0000614}
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000615void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
616 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
617 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
618}
Abramo Bagnara6150c882010-05-11 21:36:43 +0000619void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
Abramo Bagnara9033e2b2012-02-06 19:09:27 +0000620 Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
Douglas Gregor844cb502011-03-01 18:12:44 +0000621 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
John McCall17001972009-10-18 01:05:36 +0000622}
John McCalle78aac42010-03-10 03:28:59 +0000623void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
624 Writer.AddSourceLocation(TL.getNameLoc(), Record);
625}
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +0000626void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Abramo Bagnara9033e2b2012-02-06 19:09:27 +0000627 Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +0000628 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
John McCall17001972009-10-18 01:05:36 +0000629 Writer.AddSourceLocation(TL.getNameLoc(), Record);
630}
John McCallc392f372010-06-11 00:33:02 +0000631void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
632 DependentTemplateSpecializationTypeLoc TL) {
Abramo Bagnara48c05be2012-02-06 14:41:24 +0000633 Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
Douglas Gregora7a795b2011-03-01 20:11:18 +0000634 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
Abramo Bagnarae0a70b22012-02-06 22:45:07 +0000635 Writer.AddSourceLocation(TL.getTemplateKeywordLoc(), Record);
Abramo Bagnara48c05be2012-02-06 14:41:24 +0000636 Writer.AddSourceLocation(TL.getTemplateNameLoc(), Record);
John McCallc392f372010-06-11 00:33:02 +0000637 Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
638 Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
639 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +0000640 Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
641 TL.getArgLoc(I).getLocInfo(), Record);
John McCallc392f372010-06-11 00:33:02 +0000642}
Douglas Gregord2fa7662010-12-20 02:24:11 +0000643void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
644 Writer.AddSourceLocation(TL.getEllipsisLoc(), Record);
645}
John McCall17001972009-10-18 01:05:36 +0000646void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
647 Writer.AddSourceLocation(TL.getNameLoc(), Record);
John McCall8b07ec22010-05-15 11:32:37 +0000648}
649void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
650 Record.push_back(TL.hasBaseTypeAsWritten());
John McCall17001972009-10-18 01:05:36 +0000651 Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
652 Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
653 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
654 Writer.AddSourceLocation(TL.getProtocolLoc(i), Record);
John McCall8f115c62009-10-16 21:56:05 +0000655}
John McCallfc93cf92009-10-22 22:37:11 +0000656void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
657 Writer.AddSourceLocation(TL.getStarLoc(), Record);
John McCallfc93cf92009-10-22 22:37:11 +0000658}
Eli Friedman0dfb8892011-10-06 23:00:33 +0000659void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
660 Writer.AddSourceLocation(TL.getKWLoc(), Record);
661 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
662 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
663}
John McCall8f115c62009-10-16 21:56:05 +0000664
Richard Smith01b2cb42014-07-26 06:37:51 +0000665void ASTWriter::WriteTypeAbbrevs() {
666 using namespace llvm;
667
668 BitCodeAbbrev *Abv;
669
670 // Abbreviation for TYPE_EXT_QUAL
671 Abv = new BitCodeAbbrev();
672 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_EXT_QUAL));
673 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
674 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3)); // Quals
675 TypeExtQualAbbrev = Stream.EmitAbbrev(Abv);
676
677 // Abbreviation for TYPE_FUNCTION_PROTO
678 Abv = new BitCodeAbbrev();
679 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_FUNCTION_PROTO));
680 // FunctionType
681 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ReturnType
682 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // NoReturn
683 Abv->Add(BitCodeAbbrevOp(0)); // HasRegParm
684 Abv->Add(BitCodeAbbrevOp(0)); // RegParm
685 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // CC
686 Abv->Add(BitCodeAbbrevOp(0)); // ProducesResult
687 // FunctionProtoType
688 Abv->Add(BitCodeAbbrevOp(0)); // IsVariadic
689 Abv->Add(BitCodeAbbrevOp(0)); // HasTrailingReturn
690 Abv->Add(BitCodeAbbrevOp(0)); // TypeQuals
691 Abv->Add(BitCodeAbbrevOp(0)); // RefQualifier
692 Abv->Add(BitCodeAbbrevOp(EST_None)); // ExceptionSpec
693 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // NumParams
694 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
695 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Params
696 TypeFunctionProtoAbbrev = Stream.EmitAbbrev(Abv);
697}
698
Chris Lattner19cea4e2009-04-22 05:57:30 +0000699//===----------------------------------------------------------------------===//
Sebastian Redl55c0ad52010-08-18 23:56:21 +0000700// ASTWriter Implementation
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000701//===----------------------------------------------------------------------===//
702
Chris Lattner28fa4e62009-04-26 22:26:21 +0000703static void EmitBlockID(unsigned ID, const char *Name,
704 llvm::BitstreamWriter &Stream,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000705 ASTWriter::RecordDataImpl &Record) {
Chris Lattner28fa4e62009-04-26 22:26:21 +0000706 Record.clear();
707 Record.push_back(ID);
708 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
709
710 // Emit the block name if present.
Craig Toppera13603a2014-05-22 05:54:18 +0000711 if (!Name || Name[0] == 0)
712 return;
Chris Lattner28fa4e62009-04-26 22:26:21 +0000713 Record.clear();
714 while (*Name)
715 Record.push_back(*Name++);
716 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
717}
718
719static void EmitRecordID(unsigned ID, const char *Name,
720 llvm::BitstreamWriter &Stream,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000721 ASTWriter::RecordDataImpl &Record) {
Chris Lattner28fa4e62009-04-26 22:26:21 +0000722 Record.clear();
723 Record.push_back(ID);
724 while (*Name)
725 Record.push_back(*Name++);
726 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000727}
728
729static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000730 ASTWriter::RecordDataImpl &Record) {
Sebastian Redl539c5062010-08-18 23:57:32 +0000731#define RECORD(X) EmitRecordID(X, #X, Stream, Record)
Chris Lattnerccac3a62009-04-27 00:49:53 +0000732 RECORD(STMT_STOP);
733 RECORD(STMT_NULL_PTR);
Richard Smith01b2cb42014-07-26 06:37:51 +0000734 RECORD(STMT_REF_PTR);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000735 RECORD(STMT_NULL);
736 RECORD(STMT_COMPOUND);
737 RECORD(STMT_CASE);
738 RECORD(STMT_DEFAULT);
739 RECORD(STMT_LABEL);
Richard Smithc202b282012-04-14 00:33:13 +0000740 RECORD(STMT_ATTRIBUTED);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000741 RECORD(STMT_IF);
742 RECORD(STMT_SWITCH);
743 RECORD(STMT_WHILE);
744 RECORD(STMT_DO);
745 RECORD(STMT_FOR);
746 RECORD(STMT_GOTO);
747 RECORD(STMT_INDIRECT_GOTO);
748 RECORD(STMT_CONTINUE);
749 RECORD(STMT_BREAK);
750 RECORD(STMT_RETURN);
751 RECORD(STMT_DECL);
Chad Rosierde70e0e2012-08-25 00:11:56 +0000752 RECORD(STMT_GCCASM);
Chad Rosiere30d4992012-08-24 23:51:02 +0000753 RECORD(STMT_MSASM);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000754 RECORD(EXPR_PREDEFINED);
755 RECORD(EXPR_DECL_REF);
756 RECORD(EXPR_INTEGER_LITERAL);
757 RECORD(EXPR_FLOATING_LITERAL);
758 RECORD(EXPR_IMAGINARY_LITERAL);
759 RECORD(EXPR_STRING_LITERAL);
760 RECORD(EXPR_CHARACTER_LITERAL);
761 RECORD(EXPR_PAREN);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000762 RECORD(EXPR_PAREN_LIST);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000763 RECORD(EXPR_UNARY_OPERATOR);
764 RECORD(EXPR_SIZEOF_ALIGN_OF);
765 RECORD(EXPR_ARRAY_SUBSCRIPT);
766 RECORD(EXPR_CALL);
767 RECORD(EXPR_MEMBER);
768 RECORD(EXPR_BINARY_OPERATOR);
769 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
770 RECORD(EXPR_CONDITIONAL_OPERATOR);
771 RECORD(EXPR_IMPLICIT_CAST);
772 RECORD(EXPR_CSTYLE_CAST);
773 RECORD(EXPR_COMPOUND_LITERAL);
774 RECORD(EXPR_EXT_VECTOR_ELEMENT);
775 RECORD(EXPR_INIT_LIST);
776 RECORD(EXPR_DESIGNATED_INIT);
777 RECORD(EXPR_IMPLICIT_VALUE_INIT);
778 RECORD(EXPR_VA_ARG);
779 RECORD(EXPR_ADDR_LABEL);
780 RECORD(EXPR_STMT);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000781 RECORD(EXPR_CHOOSE);
782 RECORD(EXPR_GNU_NULL);
783 RECORD(EXPR_SHUFFLE_VECTOR);
784 RECORD(EXPR_BLOCK);
Peter Collingbourne91147592011-04-15 00:35:48 +0000785 RECORD(EXPR_GENERIC_SELECTION);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000786 RECORD(EXPR_OBJC_STRING_LITERAL);
Patrick Beard0caa3942012-04-19 00:25:12 +0000787 RECORD(EXPR_OBJC_BOXED_EXPRESSION);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000788 RECORD(EXPR_OBJC_ARRAY_LITERAL);
789 RECORD(EXPR_OBJC_DICTIONARY_LITERAL);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000790 RECORD(EXPR_OBJC_ENCODE);
791 RECORD(EXPR_OBJC_SELECTOR_EXPR);
792 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
793 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
794 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
795 RECORD(EXPR_OBJC_KVC_REF_EXPR);
796 RECORD(EXPR_OBJC_MESSAGE_EXPR);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000797 RECORD(STMT_OBJC_FOR_COLLECTION);
798 RECORD(STMT_OBJC_CATCH);
799 RECORD(STMT_OBJC_FINALLY);
800 RECORD(STMT_OBJC_AT_TRY);
801 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
802 RECORD(STMT_OBJC_AT_THROW);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000803 RECORD(EXPR_OBJC_BOOL_LITERAL);
Richard Smith01b2cb42014-07-26 06:37:51 +0000804 RECORD(STMT_CXX_CATCH);
805 RECORD(STMT_CXX_TRY);
806 RECORD(STMT_CXX_FOR_RANGE);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000807 RECORD(EXPR_CXX_OPERATOR_CALL);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000808 RECORD(EXPR_CXX_MEMBER_CALL);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000809 RECORD(EXPR_CXX_CONSTRUCT);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000810 RECORD(EXPR_CXX_TEMPORARY_OBJECT);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000811 RECORD(EXPR_CXX_STATIC_CAST);
812 RECORD(EXPR_CXX_DYNAMIC_CAST);
813 RECORD(EXPR_CXX_REINTERPRET_CAST);
814 RECORD(EXPR_CXX_CONST_CAST);
815 RECORD(EXPR_CXX_FUNCTIONAL_CAST);
Richard Smithc67fdd42012-03-07 08:35:16 +0000816 RECORD(EXPR_USER_DEFINED_LITERAL);
Richard Smithcc1b96d2013-06-12 22:31:48 +0000817 RECORD(EXPR_CXX_STD_INITIALIZER_LIST);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000818 RECORD(EXPR_CXX_BOOL_LITERAL);
819 RECORD(EXPR_CXX_NULL_PTR_LITERAL);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000820 RECORD(EXPR_CXX_TYPEID_EXPR);
821 RECORD(EXPR_CXX_TYPEID_TYPE);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000822 RECORD(EXPR_CXX_THIS);
823 RECORD(EXPR_CXX_THROW);
824 RECORD(EXPR_CXX_DEFAULT_ARG);
Richard Smith01b2cb42014-07-26 06:37:51 +0000825 RECORD(EXPR_CXX_DEFAULT_INIT);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000826 RECORD(EXPR_CXX_BIND_TEMPORARY);
827 RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
828 RECORD(EXPR_CXX_NEW);
829 RECORD(EXPR_CXX_DELETE);
830 RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
831 RECORD(EXPR_EXPR_WITH_CLEANUPS);
832 RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
833 RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
834 RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
835 RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
836 RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
Richard Smith01b2cb42014-07-26 06:37:51 +0000837 RECORD(EXPR_CXX_EXPRESSION_TRAIT);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000838 RECORD(EXPR_CXX_NOEXCEPT);
839 RECORD(EXPR_OPAQUE_VALUE);
Richard Smith01b2cb42014-07-26 06:37:51 +0000840 RECORD(EXPR_BINARY_CONDITIONAL_OPERATOR);
841 RECORD(EXPR_TYPE_TRAIT);
842 RECORD(EXPR_ARRAY_TYPE_TRAIT);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000843 RECORD(EXPR_PACK_EXPANSION);
844 RECORD(EXPR_SIZEOF_PACK);
Richard Smith01b2cb42014-07-26 06:37:51 +0000845 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000846 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
Richard Smith01b2cb42014-07-26 06:37:51 +0000847 RECORD(EXPR_FUNCTION_PARM_PACK);
848 RECORD(EXPR_MATERIALIZE_TEMPORARY);
Peter Collingbourne41f85462011-02-09 21:07:24 +0000849 RECORD(EXPR_CUDA_KERNEL_CALL);
Richard Smith01b2cb42014-07-26 06:37:51 +0000850 RECORD(EXPR_CXX_UUIDOF_EXPR);
851 RECORD(EXPR_CXX_UUIDOF_TYPE);
852 RECORD(EXPR_LAMBDA);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000853#undef RECORD
Chris Lattner28fa4e62009-04-26 22:26:21 +0000854}
Mike Stump11289f42009-09-09 15:08:12 +0000855
Sebastian Redl55c0ad52010-08-18 23:56:21 +0000856void ASTWriter::WriteBlockInfoBlock() {
Chris Lattner28fa4e62009-04-26 22:26:21 +0000857 RecordData Record;
858 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
Mike Stump11289f42009-09-09 15:08:12 +0000859
Sebastian Redl539c5062010-08-18 23:57:32 +0000860#define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
861#define RECORD(X) EmitRecordID(X, #X, Stream, Record)
Mike Stump11289f42009-09-09 15:08:12 +0000862
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000863 // Control Block.
864 BLOCK(CONTROL_BLOCK);
865 RECORD(METADATA);
Ben Langmuir487ea142014-10-23 18:05:36 +0000866 RECORD(SIGNATURE);
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000867 RECORD(MODULE_NAME);
868 RECORD(MODULE_MAP_FILE);
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000869 RECORD(IMPORTS);
Richard Smith7f330cd2015-03-18 01:42:29 +0000870 RECORD(KNOWN_MODULE_FILES);
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000871 RECORD(LANGUAGE_OPTIONS);
872 RECORD(TARGET_OPTIONS);
Douglas Gregorfad10d82012-10-18 18:36:53 +0000873 RECORD(ORIGINAL_FILE);
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000874 RECORD(ORIGINAL_PCH_DIR);
Argyrios Kyrtzidis52595242012-11-15 18:57:27 +0000875 RECORD(ORIGINAL_FILE_ID);
Douglas Gregor3120d2c2012-10-22 18:42:04 +0000876 RECORD(INPUT_FILE_OFFSETS);
Douglas Gregor8263ffb2012-10-24 15:17:15 +0000877 RECORD(DIAGNOSTIC_OPTIONS);
Douglas Gregorc6317db2012-10-24 15:49:58 +0000878 RECORD(FILE_SYSTEM_OPTIONS);
Douglas Gregor2d302362012-10-24 16:50:34 +0000879 RECORD(HEADER_SEARCH_OPTIONS);
Douglas Gregorb6af6c22012-10-24 20:05:57 +0000880 RECORD(PREPROCESSOR_OPTIONS);
881
Douglas Gregor108cb222012-10-19 00:45:00 +0000882 BLOCK(INPUT_FILES_BLOCK);
883 RECORD(INPUT_FILE);
884
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000885 // AST Top-Level Block.
886 BLOCK(AST_BLOCK);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000887 RECORD(TYPE_OFFSET);
888 RECORD(DECL_OFFSET);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000889 RECORD(IDENTIFIER_OFFSET);
890 RECORD(IDENTIFIER_TABLE);
Ben Langmuir332aafe2014-01-31 01:06:56 +0000891 RECORD(EAGERLY_DESERIALIZED_DECLS);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000892 RECORD(SPECIAL_TYPES);
893 RECORD(STATISTICS);
894 RECORD(TENTATIVE_DEFINITIONS);
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +0000895 RECORD(UNUSED_FILESCOPED_DECLS);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000896 RECORD(SELECTOR_OFFSETS);
897 RECORD(METHOD_POOL);
898 RECORD(PP_COUNTER_VALUE);
Douglas Gregor258ae542009-04-27 06:38:32 +0000899 RECORD(SOURCE_LOCATION_OFFSETS);
900 RECORD(SOURCE_LOCATION_PRELOADS);
Douglas Gregor61cac2b2009-04-27 20:06:05 +0000901 RECORD(EXT_VECTOR_DECLS);
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +0000902 RECORD(PPD_ENTITIES_OFFSETS);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +0000903 RECORD(REFERENCED_SELECTOR_POOL);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000904 RECORD(TU_UPDATE_LEXICAL);
Douglas Gregor358cd442012-01-15 16:58:34 +0000905 RECORD(LOCAL_REDECLARATIONS_MAP);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000906 RECORD(SEMA_DECL_REFS);
907 RECORD(WEAK_UNDECLARED_IDENTIFIERS);
908 RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
909 RECORD(DECL_REPLACEMENTS);
910 RECORD(UPDATE_VISIBLE);
911 RECORD(DECL_UPDATE_OFFSETS);
912 RECORD(DECL_UPDATES);
913 RECORD(CXX_BASE_SPECIFIER_OFFSETS);
914 RECORD(DIAG_PRAGMA_MAPPINGS);
Peter Collingbourne5df20e02011-02-15 19:46:30 +0000915 RECORD(CUDA_SPECIAL_DECL_REFS);
Douglas Gregor09b69892011-02-10 17:09:37 +0000916 RECORD(HEADER_SEARCH_TABLE);
Peter Collingbourne5df20e02011-02-15 19:46:30 +0000917 RECORD(FP_PRAGMA_OPTIONS);
918 RECORD(OPENCL_EXTENSIONS);
Alexis Hunt27a761d2011-05-04 23:29:54 +0000919 RECORD(DELEGATING_CTORS);
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000920 RECORD(KNOWN_NAMESPACES);
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +0000921 RECORD(UNDEFINED_BUT_USED);
Douglas Gregor78d0b572011-08-04 16:39:39 +0000922 RECORD(MODULE_OFFSET_MAP);
923 RECORD(SOURCE_MANAGER_LINE_TABLE);
Douglas Gregor404cdde2012-01-27 01:47:08 +0000924 RECORD(OBJC_CATEGORIES_MAP);
Douglas Gregor66e4add2011-12-19 21:09:25 +0000925 RECORD(FILE_SORTED_DECLS);
926 RECORD(IMPORTED_MODULES);
Douglas Gregor358cd442012-01-15 16:58:34 +0000927 RECORD(LOCAL_REDECLARATIONS);
Douglas Gregor404cdde2012-01-27 01:47:08 +0000928 RECORD(OBJC_CATEGORIES);
Douglas Gregorcb28f9d2012-10-09 23:05:51 +0000929 RECORD(MACRO_OFFSET);
Richard Smithe40f2ba2013-08-07 21:41:30 +0000930 RECORD(LATE_PARSED_TEMPLATE);
Dario Domizioli13a0a382014-05-23 12:13:25 +0000931 RECORD(OPTIMIZE_PRAGMA_OPTIONS);
Douglas Gregor358cd442012-01-15 16:58:34 +0000932
Chris Lattner28fa4e62009-04-26 22:26:21 +0000933 // SourceManager Block.
Chris Lattner64031982009-04-27 00:40:25 +0000934 BLOCK(SOURCE_MANAGER_BLOCK);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000935 RECORD(SM_SLOC_FILE_ENTRY);
936 RECORD(SM_SLOC_BUFFER_ENTRY);
937 RECORD(SM_SLOC_BUFFER_BLOB);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +0000938 RECORD(SM_SLOC_EXPANSION_ENTRY);
Mike Stump11289f42009-09-09 15:08:12 +0000939
Chris Lattner28fa4e62009-04-26 22:26:21 +0000940 // Preprocessor Block.
Chris Lattner64031982009-04-27 00:40:25 +0000941 BLOCK(PREPROCESSOR_BLOCK);
Richard Smithec216502015-02-13 19:48:37 +0000942 RECORD(PP_MACRO_DIRECTIVE_HISTORY);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000943 RECORD(PP_MACRO_FUNCTION_LIKE);
Richard Smithd7329392015-04-21 21:46:32 +0000944 RECORD(PP_MACRO_OBJECT_LIKE);
945 RECORD(PP_MODULE_MACRO);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000946 RECORD(PP_TOKEN);
Richard Smithec216502015-02-13 19:48:37 +0000947
Douglas Gregor12bfa382009-10-17 00:13:19 +0000948 // Decls and Types block.
949 BLOCK(DECLTYPES_BLOCK);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000950 RECORD(TYPE_EXT_QUAL);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000951 RECORD(TYPE_COMPLEX);
952 RECORD(TYPE_POINTER);
953 RECORD(TYPE_BLOCK_POINTER);
954 RECORD(TYPE_LVALUE_REFERENCE);
955 RECORD(TYPE_RVALUE_REFERENCE);
956 RECORD(TYPE_MEMBER_POINTER);
957 RECORD(TYPE_CONSTANT_ARRAY);
958 RECORD(TYPE_INCOMPLETE_ARRAY);
959 RECORD(TYPE_VARIABLE_ARRAY);
960 RECORD(TYPE_VECTOR);
961 RECORD(TYPE_EXT_VECTOR);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000962 RECORD(TYPE_FUNCTION_NO_PROTO);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000963 RECORD(TYPE_FUNCTION_PROTO);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000964 RECORD(TYPE_TYPEDEF);
965 RECORD(TYPE_TYPEOF_EXPR);
966 RECORD(TYPE_TYPEOF);
967 RECORD(TYPE_RECORD);
968 RECORD(TYPE_ENUM);
969 RECORD(TYPE_OBJC_INTERFACE);
Steve Narofffb4330f2009-06-17 22:40:22 +0000970 RECORD(TYPE_OBJC_OBJECT_POINTER);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000971 RECORD(TYPE_DECLTYPE);
972 RECORD(TYPE_ELABORATED);
973 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
974 RECORD(TYPE_UNRESOLVED_USING);
975 RECORD(TYPE_INJECTED_CLASS_NAME);
976 RECORD(TYPE_OBJC_OBJECT);
977 RECORD(TYPE_TEMPLATE_TYPE_PARM);
978 RECORD(TYPE_TEMPLATE_SPECIALIZATION);
979 RECORD(TYPE_DEPENDENT_NAME);
980 RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
981 RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
982 RECORD(TYPE_PAREN);
983 RECORD(TYPE_PACK_EXPANSION);
984 RECORD(TYPE_ATTRIBUTED);
985 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000986 RECORD(TYPE_AUTO);
987 RECORD(TYPE_UNARY_TRANSFORM);
Eli Friedman0dfb8892011-10-06 23:00:33 +0000988 RECORD(TYPE_ATOMIC);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000989 RECORD(TYPE_DECAYED);
990 RECORD(TYPE_ADJUSTED);
Chris Lattnerdb397b62009-04-26 22:32:16 +0000991 RECORD(DECL_TYPEDEF);
Richard Smith01b2cb42014-07-26 06:37:51 +0000992 RECORD(DECL_TYPEALIAS);
Chris Lattnerdb397b62009-04-26 22:32:16 +0000993 RECORD(DECL_ENUM);
994 RECORD(DECL_RECORD);
995 RECORD(DECL_ENUM_CONSTANT);
996 RECORD(DECL_FUNCTION);
997 RECORD(DECL_OBJC_METHOD);
998 RECORD(DECL_OBJC_INTERFACE);
999 RECORD(DECL_OBJC_PROTOCOL);
1000 RECORD(DECL_OBJC_IVAR);
1001 RECORD(DECL_OBJC_AT_DEFS_FIELD);
Chris Lattnerdb397b62009-04-26 22:32:16 +00001002 RECORD(DECL_OBJC_CATEGORY);
1003 RECORD(DECL_OBJC_CATEGORY_IMPL);
1004 RECORD(DECL_OBJC_IMPLEMENTATION);
1005 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
1006 RECORD(DECL_OBJC_PROPERTY);
1007 RECORD(DECL_OBJC_PROPERTY_IMPL);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001008 RECORD(DECL_FIELD);
John McCall5e77d762013-04-16 07:28:30 +00001009 RECORD(DECL_MS_PROPERTY);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001010 RECORD(DECL_VAR);
Chris Lattnerdb397b62009-04-26 22:32:16 +00001011 RECORD(DECL_IMPLICIT_PARAM);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001012 RECORD(DECL_PARM_VAR);
Chris Lattnerdb397b62009-04-26 22:32:16 +00001013 RECORD(DECL_FILE_SCOPE_ASM);
1014 RECORD(DECL_BLOCK);
1015 RECORD(DECL_CONTEXT_LEXICAL);
1016 RECORD(DECL_CONTEXT_VISIBLE);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001017 RECORD(DECL_NAMESPACE);
1018 RECORD(DECL_NAMESPACE_ALIAS);
1019 RECORD(DECL_USING);
1020 RECORD(DECL_USING_SHADOW);
1021 RECORD(DECL_USING_DIRECTIVE);
1022 RECORD(DECL_UNRESOLVED_USING_VALUE);
1023 RECORD(DECL_UNRESOLVED_USING_TYPENAME);
1024 RECORD(DECL_LINKAGE_SPEC);
1025 RECORD(DECL_CXX_RECORD);
1026 RECORD(DECL_CXX_METHOD);
1027 RECORD(DECL_CXX_CONSTRUCTOR);
1028 RECORD(DECL_CXX_DESTRUCTOR);
1029 RECORD(DECL_CXX_CONVERSION);
1030 RECORD(DECL_ACCESS_SPEC);
1031 RECORD(DECL_FRIEND);
1032 RECORD(DECL_FRIEND_TEMPLATE);
1033 RECORD(DECL_CLASS_TEMPLATE);
1034 RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
1035 RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
Larisse Voufo39a1e502013-08-06 01:03:05 +00001036 RECORD(DECL_VAR_TEMPLATE);
1037 RECORD(DECL_VAR_TEMPLATE_SPECIALIZATION);
1038 RECORD(DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001039 RECORD(DECL_FUNCTION_TEMPLATE);
1040 RECORD(DECL_TEMPLATE_TYPE_PARM);
1041 RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
1042 RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
1043 RECORD(DECL_STATIC_ASSERT);
1044 RECORD(DECL_CXX_BASE_SPECIFIERS);
1045 RECORD(DECL_INDIRECTFIELD);
1046 RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
1047
Douglas Gregor03412ba2011-06-03 02:27:19 +00001048 // Statements and Exprs can occur in the Decls and Types block.
1049 AddStmtsExprs(Stream, Record);
1050
Douglas Gregor92a96f52011-02-08 21:58:10 +00001051 BLOCK(PREPROCESSOR_DETAIL_BLOCK);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001052 RECORD(PPD_MACRO_EXPANSION);
Douglas Gregor92a96f52011-02-08 21:58:10 +00001053 RECORD(PPD_MACRO_DEFINITION);
1054 RECORD(PPD_INCLUSION_DIRECTIVE);
1055
Chris Lattner28fa4e62009-04-26 22:26:21 +00001056#undef RECORD
1057#undef BLOCK
1058 Stream.ExitBlock();
1059}
1060
Richard Smith54cc3c22014-12-11 20:50:24 +00001061/// \brief Prepares a path for being written to an AST file by converting it
1062/// to an absolute path and removing nested './'s.
1063///
1064/// \return \c true if the path was changed.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001065static bool cleanPathForOutput(FileManager &FileMgr,
1066 SmallVectorImpl<char> &Path) {
Richard Smith54cc3c22014-12-11 20:50:24 +00001067 bool Changed = false;
1068
1069 if (!llvm::sys::path::is_absolute(StringRef(Path.data(), Path.size()))) {
1070 llvm::sys::fs::make_absolute(Path);
1071 Changed = true;
1072 }
1073
1074 return Changed | FileMgr.removeDotPaths(Path);
1075}
1076
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001077/// \brief Adjusts the given filename to only write out the portion of the
1078/// filename that is not part of the system root directory.
Mike Stump11289f42009-09-09 15:08:12 +00001079///
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001080/// \param Filename the file name to adjust.
1081///
Richard Smith7ed1bc92014-12-05 22:42:13 +00001082/// \param BaseDir When non-NULL, the PCH file is a relocatable AST file and
1083/// the returned filename will be adjusted by this root directory.
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001084///
1085/// \returns either the original filename (if it needs no adjustment) or the
1086/// adjusted filename (which points into the @p Filename parameter).
Mike Stump11289f42009-09-09 15:08:12 +00001087static const char *
Richard Smith7ed1bc92014-12-05 22:42:13 +00001088adjustFilenameForRelocatableAST(const char *Filename, StringRef BaseDir) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001089 assert(Filename && "No file name to adjust?");
Mike Stump11289f42009-09-09 15:08:12 +00001090
Richard Smith7ed1bc92014-12-05 22:42:13 +00001091 if (BaseDir.empty())
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001092 return Filename;
Mike Stump11289f42009-09-09 15:08:12 +00001093
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001094 // Verify that the filename and the system root have the same prefix.
1095 unsigned Pos = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001096 for (; Filename[Pos] && Pos < BaseDir.size(); ++Pos)
1097 if (Filename[Pos] != BaseDir[Pos])
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001098 return Filename; // Prefixes don't match.
Mike Stump11289f42009-09-09 15:08:12 +00001099
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001100 // We hit the end of the filename before we hit the end of the system root.
1101 if (!Filename[Pos])
1102 return Filename;
Mike Stump11289f42009-09-09 15:08:12 +00001103
Richard Smith7ed1bc92014-12-05 22:42:13 +00001104 // If there's not a path separator at the end of the base directory nor
1105 // immediately after it, then this isn't within the base directory.
1106 if (!llvm::sys::path::is_separator(Filename[Pos])) {
1107 if (!llvm::sys::path::is_separator(BaseDir.back()))
1108 return Filename;
1109 } else {
1110 // If the file name has a '/' at the current position, skip over the '/'.
1111 // We distinguish relative paths from absolute paths by the
1112 // absence of '/' at the beginning of relative paths.
1113 //
1114 // FIXME: This is wrong. We distinguish them by asking if the path is
1115 // absolute, which isn't the same thing. And there might be multiple '/'s
1116 // in a row. Use a better mechanism to indicate whether we have emitted an
1117 // absolute or relative path.
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001118 ++Pos;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001119 }
Mike Stump11289f42009-09-09 15:08:12 +00001120
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001121 return Filename + Pos;
1122}
Chris Lattner28fa4e62009-04-26 22:26:21 +00001123
Ben Langmuir487ea142014-10-23 18:05:36 +00001124static ASTFileSignature getSignature() {
1125 while (1) {
1126 if (ASTFileSignature S = llvm::sys::Process::GetRandomNumber())
1127 return S;
1128 // Rely on GetRandomNumber to eventually return non-zero...
1129 }
1130}
1131
Douglas Gregor112b9072012-10-18 05:31:06 +00001132/// \brief Write the control block.
Douglas Gregor2d302362012-10-24 16:50:34 +00001133void ASTWriter::WriteControlBlock(Preprocessor &PP, ASTContext &Context,
1134 StringRef isysroot,
Douglas Gregor112b9072012-10-18 05:31:06 +00001135 const std::string &OutputFile) {
Douglas Gregorbfbde532009-04-10 21:16:55 +00001136 using namespace llvm;
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001137 Stream.EnterSubblock(CONTROL_BLOCK_ID, 5);
1138 RecordData Record;
Douglas Gregor112b9072012-10-18 05:31:06 +00001139
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001140 // Metadata
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001141 BitCodeAbbrev *MetadataAbbrev = new BitCodeAbbrev();
1142 MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA));
1143 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major
1144 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor
1145 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj.
1146 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min.
1147 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
1148 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors
1149 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
1150 unsigned MetadataAbbrevCode = Stream.EmitAbbrev(MetadataAbbrev);
1151 Record.push_back(METADATA);
Sebastian Redl539c5062010-08-18 23:57:32 +00001152 Record.push_back(VERSION_MAJOR);
1153 Record.push_back(VERSION_MINOR);
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001154 Record.push_back(CLANG_VERSION_MAJOR);
1155 Record.push_back(CLANG_VERSION_MINOR);
Richard Smith7ed1bc92014-12-05 22:42:13 +00001156 assert((!WritingModule || isysroot.empty()) &&
1157 "writing module as a relocatable PCH?");
Douglas Gregorc567ba22011-07-22 16:35:34 +00001158 Record.push_back(!isysroot.empty());
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00001159 Record.push_back(ASTHasCompilerErrors);
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001160 Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record,
1161 getClangFullRepositoryVersion());
Douglas Gregor29cc6422011-08-17 21:07:30 +00001162
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001163 if (WritingModule) {
Chandler Carruth885e78c2015-03-24 21:18:10 +00001164 // For implicit modules we output a signature that we can use to ensure
1165 // duplicate module builds don't collide in the cache as their output order
1166 // is non-deterministic.
1167 // FIXME: Remove this when output is deterministic.
1168 if (Context.getLangOpts().ImplicitModules) {
1169 Record.clear();
1170 Record.push_back(getSignature());
1171 Stream.EmitRecord(SIGNATURE, Record);
1172 }
1173
Richard Smith7ed1bc92014-12-05 22:42:13 +00001174 // Module name
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001175 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1176 Abbrev->Add(BitCodeAbbrevOp(MODULE_NAME));
1177 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
1178 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
1179 RecordData Record;
1180 Record.push_back(MODULE_NAME);
1181 Stream.EmitRecordWithBlob(AbbrevCode, Record, WritingModule->Name);
1182 }
1183
Richard Smith7ed1bc92014-12-05 22:42:13 +00001184 if (WritingModule && WritingModule->Directory) {
1185 // Module directory.
1186 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1187 Abbrev->Add(BitCodeAbbrevOp(MODULE_DIRECTORY));
1188 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Directory
1189 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
1190 RecordData Record;
1191 Record.push_back(MODULE_DIRECTORY);
1192
1193 SmallString<128> BaseDir(WritingModule->Directory->getName());
Richard Smith54cc3c22014-12-11 20:50:24 +00001194 cleanPathForOutput(Context.getSourceManager().getFileManager(), BaseDir);
Richard Smith7ed1bc92014-12-05 22:42:13 +00001195 Stream.EmitRecordWithBlob(AbbrevCode, Record, BaseDir);
1196
1197 // Write out all other paths relative to the base directory if possible.
1198 BaseDirectory.assign(BaseDir.begin(), BaseDir.end());
1199 } else if (!isysroot.empty()) {
1200 // Write out paths relative to the sysroot if possible.
1201 BaseDirectory = isysroot;
1202 }
1203
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001204 // Module map file
1205 if (WritingModule) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001206 Record.clear();
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001207
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001208 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
1209
1210 // Primary module map file.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001211 AddPath(Map.getModuleMapFileForUniquing(WritingModule)->getName(), Record);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001212
1213 // Additional module map files.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001214 if (auto *AdditionalModMaps =
1215 Map.getAdditionalModuleMapFiles(WritingModule)) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001216 Record.push_back(AdditionalModMaps->size());
1217 for (const FileEntry *F : *AdditionalModMaps)
Richard Smith7ed1bc92014-12-05 22:42:13 +00001218 AddPath(F->getName(), Record);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001219 } else {
1220 Record.push_back(0);
1221 }
1222
1223 Stream.EmitRecord(MODULE_MAP_FILE, Record);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001224 }
1225
Douglas Gregor112b9072012-10-18 05:31:06 +00001226 // Imports
Douglas Gregor29cc6422011-08-17 21:07:30 +00001227 if (Chain) {
Douglas Gregor29cc6422011-08-17 21:07:30 +00001228 serialization::ModuleManager &Mgr = Chain->getModuleManager();
Douglas Gregor29cc6422011-08-17 21:07:30 +00001229 Record.clear();
Douglas Gregordf0c1512011-08-18 04:12:04 +00001230
Richard Smith7f330cd2015-03-18 01:42:29 +00001231 for (auto *M : Mgr) {
Douglas Gregordf0c1512011-08-18 04:12:04 +00001232 // Skip modules that weren't directly imported.
Richard Smith7f330cd2015-03-18 01:42:29 +00001233 if (!M->isDirectlyImported())
Douglas Gregordf0c1512011-08-18 04:12:04 +00001234 continue;
1235
Richard Smith7f330cd2015-03-18 01:42:29 +00001236 Record.push_back((unsigned)M->Kind); // FIXME: Stable encoding
1237 AddSourceLocation(M->ImportLoc, Record);
1238 Record.push_back(M->File->getSize());
1239 Record.push_back(M->File->getModificationTime());
1240 Record.push_back(M->Signature);
1241 AddPath(M->FileName, Record);
Douglas Gregordf0c1512011-08-18 04:12:04 +00001242 }
Douglas Gregor29cc6422011-08-17 21:07:30 +00001243 Stream.EmitRecord(IMPORTS, Record);
Richard Smith7f330cd2015-03-18 01:42:29 +00001244
1245 // Also emit a list of known module files that were not imported,
1246 // but are made available by this module.
1247 // FIXME: Should we also include a signature here?
1248 Record.clear();
1249 for (auto *E : Mgr.getAdditionalKnownModuleFiles())
1250 AddPath(E->getName(), Record);
1251 if (!Record.empty())
1252 Stream.EmitRecord(KNOWN_MODULE_FILES, Record);
Douglas Gregor29cc6422011-08-17 21:07:30 +00001253 }
Mike Stump11289f42009-09-09 15:08:12 +00001254
Douglas Gregor112b9072012-10-18 05:31:06 +00001255 // Language options.
1256 Record.clear();
1257 const LangOptions &LangOpts = Context.getLangOpts();
1258#define LANGOPT(Name, Bits, Default, Description) \
1259 Record.push_back(LangOpts.Name);
1260#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
1261 Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001262#include "clang/Basic/LangOptions.def"
1263#define SANITIZER(NAME, ID) \
1264 Record.push_back(LangOpts.Sanitize.has(SanitizerKind::ID));
Will Dietzf54319c2013-01-18 11:30:38 +00001265#include "clang/Basic/Sanitizers.def"
Douglas Gregor112b9072012-10-18 05:31:06 +00001266
1267 Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind());
1268 AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record);
1269
1270 Record.push_back(LangOpts.CurrentModule.size());
1271 Record.append(LangOpts.CurrentModule.begin(), LangOpts.CurrentModule.end());
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00001272
1273 // Comment options.
1274 Record.push_back(LangOpts.CommentOpts.BlockCommandNames.size());
1275 for (CommentOptions::BlockCommandNamesTy::const_iterator
1276 I = LangOpts.CommentOpts.BlockCommandNames.begin(),
1277 IEnd = LangOpts.CommentOpts.BlockCommandNames.end();
1278 I != IEnd; ++I) {
1279 AddString(*I, Record);
1280 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00001281 Record.push_back(LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00001282
Douglas Gregor112b9072012-10-18 05:31:06 +00001283 Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1284
Douglas Gregor4d3611c2012-10-18 17:58:09 +00001285 // Target options.
1286 Record.clear();
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001287 const TargetInfo &Target = Context.getTargetInfo();
1288 const TargetOptions &TargetOpts = Target.getTargetOpts();
Douglas Gregor4d3611c2012-10-18 17:58:09 +00001289 AddString(TargetOpts.Triple, Record);
1290 AddString(TargetOpts.CPU, Record);
1291 AddString(TargetOpts.ABI, Record);
Douglas Gregor4d3611c2012-10-18 17:58:09 +00001292 Record.push_back(TargetOpts.FeaturesAsWritten.size());
1293 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; ++I) {
1294 AddString(TargetOpts.FeaturesAsWritten[I], Record);
1295 }
1296 Record.push_back(TargetOpts.Features.size());
1297 for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; ++I) {
1298 AddString(TargetOpts.Features[I], Record);
1299 }
1300 Stream.EmitRecord(TARGET_OPTIONS, Record);
1301
Douglas Gregor8263ffb2012-10-24 15:17:15 +00001302 // Diagnostic options.
1303 Record.clear();
1304 const DiagnosticOptions &DiagOpts
1305 = Context.getDiagnostics().getDiagnosticOptions();
1306#define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name);
1307#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
1308 Record.push_back(static_cast<unsigned>(DiagOpts.get##Name()));
1309#include "clang/Basic/DiagnosticOptions.def"
1310 Record.push_back(DiagOpts.Warnings.size());
1311 for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; ++I)
1312 AddString(DiagOpts.Warnings[I], Record);
Richard Smith3be1cb22014-08-07 00:24:21 +00001313 Record.push_back(DiagOpts.Remarks.size());
1314 for (unsigned I = 0, N = DiagOpts.Remarks.size(); I != N; ++I)
1315 AddString(DiagOpts.Remarks[I], Record);
Douglas Gregor8263ffb2012-10-24 15:17:15 +00001316 // Note: we don't serialize the log or serialization file names, because they
1317 // are generally transient files and will almost always be overridden.
1318 Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record);
1319
Douglas Gregorc6317db2012-10-24 15:49:58 +00001320 // File system options.
1321 Record.clear();
1322 const FileSystemOptions &FSOpts
1323 = Context.getSourceManager().getFileManager().getFileSystemOptions();
1324 AddString(FSOpts.WorkingDir, Record);
1325 Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record);
1326
Douglas Gregor2d302362012-10-24 16:50:34 +00001327 // Header search options.
1328 Record.clear();
1329 const HeaderSearchOptions &HSOpts
1330 = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1331 AddString(HSOpts.Sysroot, Record);
1332
1333 // Include entries.
1334 Record.push_back(HSOpts.UserEntries.size());
1335 for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; ++I) {
1336 const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I];
1337 AddString(Entry.Path, Record);
1338 Record.push_back(static_cast<unsigned>(Entry.Group));
Douglas Gregor2d302362012-10-24 16:50:34 +00001339 Record.push_back(Entry.IsFramework);
1340 Record.push_back(Entry.IgnoreSysRoot);
Douglas Gregor2d302362012-10-24 16:50:34 +00001341 }
1342
1343 // System header prefixes.
1344 Record.push_back(HSOpts.SystemHeaderPrefixes.size());
1345 for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; ++I) {
1346 AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record);
1347 Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader);
1348 }
1349
1350 AddString(HSOpts.ResourceDir, Record);
1351 AddString(HSOpts.ModuleCachePath, Record);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00001352 AddString(HSOpts.ModuleUserBuildPath, Record);
Douglas Gregor2d302362012-10-24 16:50:34 +00001353 Record.push_back(HSOpts.DisableModuleHash);
1354 Record.push_back(HSOpts.UseBuiltinIncludes);
1355 Record.push_back(HSOpts.UseStandardSystemIncludes);
1356 Record.push_back(HSOpts.UseStandardCXXIncludes);
1357 Record.push_back(HSOpts.UseLibcxx);
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00001358 // Write out the specific module cache path that contains the module files.
1359 AddString(PP.getHeaderSearchInfo().getModuleCachePath(), Record);
Douglas Gregor2d302362012-10-24 16:50:34 +00001360 Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record);
1361
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001362 // Preprocessor options.
1363 Record.clear();
1364 const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts();
1365
1366 // Macro definitions.
1367 Record.push_back(PPOpts.Macros.size());
1368 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
1369 AddString(PPOpts.Macros[I].first, Record);
1370 Record.push_back(PPOpts.Macros[I].second);
1371 }
1372
1373 // Includes
1374 Record.push_back(PPOpts.Includes.size());
1375 for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I)
1376 AddString(PPOpts.Includes[I], Record);
1377
1378 // Macro includes
1379 Record.push_back(PPOpts.MacroIncludes.size());
1380 for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; ++I)
1381 AddString(PPOpts.MacroIncludes[I], Record);
1382
Douglas Gregorb6368752012-10-24 23:41:50 +00001383 Record.push_back(PPOpts.UsePredefines);
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00001384 // Detailed record is important since it is used for the module cache hash.
1385 Record.push_back(PPOpts.DetailedRecord);
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001386 AddString(PPOpts.ImplicitPCHInclude, Record);
1387 AddString(PPOpts.ImplicitPTHInclude, Record);
1388 Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary));
1389 Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record);
1390
Douglas Gregora3b20262011-05-06 21:43:30 +00001391 // Original file name and file ID
Douglas Gregor45fe0362009-05-12 01:31:05 +00001392 SourceManager &SM = Context.getSourceManager();
1393 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1394 BitCodeAbbrev *FileAbbrev = new BitCodeAbbrev();
Douglas Gregorfad10d82012-10-18 18:36:53 +00001395 FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE));
1396 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID
Douglas Gregor45fe0362009-05-12 01:31:05 +00001397 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1398 unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
1399
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001400 Record.clear();
Douglas Gregorfad10d82012-10-18 18:36:53 +00001401 Record.push_back(ORIGINAL_FILE);
Douglas Gregora3b20262011-05-06 21:43:30 +00001402 Record.push_back(SM.getMainFileID().getOpaqueValue());
Richard Smith7ed1bc92014-12-05 22:42:13 +00001403 EmitRecordWithPath(FileAbbrevCode, Record, MainFile->getName());
Douglas Gregor45fe0362009-05-12 01:31:05 +00001404 }
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00001405
Argyrios Kyrtzidis52595242012-11-15 18:57:27 +00001406 Record.clear();
1407 Record.push_back(SM.getMainFileID().getOpaqueValue());
1408 Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
1409
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001410 // Original PCH directory
1411 if (!OutputFile.empty() && OutputFile != "-") {
1412 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1413 Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR));
1414 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1415 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
1416
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001417 SmallString<128> OutputPath(OutputFile);
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001418
1419 llvm::sys::fs::make_absolute(OutputPath);
1420 StringRef origDir = llvm::sys::path::parent_path(OutputPath);
1421
1422 RecordData Record;
1423 Record.push_back(ORIGINAL_PCH_DIR);
1424 Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir);
1425 }
1426
Douglas Gregor49491f72013-03-15 22:15:07 +00001427 WriteInputFiles(Context.SourceMgr,
1428 PP.getHeaderSearchInfo().getHeaderSearchOpts(),
Douglas Gregora3dd9002013-07-22 20:48:33 +00001429 PP.getLangOpts().Modules);
Douglas Gregor72be3902012-10-19 00:38:02 +00001430 Stream.ExitBlock();
1431}
1432
Douglas Gregor49491f72013-03-15 22:15:07 +00001433namespace {
1434 /// \brief An input file.
1435 struct InputFileEntry {
1436 const FileEntry *File;
1437 bool IsSystemFile;
1438 bool BufferOverridden;
1439 };
1440}
1441
1442void ASTWriter::WriteInputFiles(SourceManager &SourceMgr,
1443 HeaderSearchOptions &HSOpts,
Douglas Gregora3dd9002013-07-22 20:48:33 +00001444 bool Modules) {
Douglas Gregor72be3902012-10-19 00:38:02 +00001445 using namespace llvm;
1446 Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4);
1447 RecordData Record;
1448
1449 // Create input-file abbreviation.
1450 BitCodeAbbrev *IFAbbrev = new BitCodeAbbrev();
1451 IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE));
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001452 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
Douglas Gregor72be3902012-10-19 00:38:02 +00001453 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1454 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001455 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden
Douglas Gregor72be3902012-10-19 00:38:02 +00001456 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1457 unsigned IFAbbrevCode = Stream.EmitAbbrev(IFAbbrev);
1458
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001459 // Get all ContentCache objects for files, sorted by whether the file is a
1460 // system one or not. System files go at the back, users files at the front.
Douglas Gregor49491f72013-03-15 22:15:07 +00001461 std::deque<InputFileEntry> SortedFiles;
Douglas Gregor72be3902012-10-19 00:38:02 +00001462 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) {
1463 // Get this source location entry.
1464 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
NAKAMURA Takumideca50f2012-10-19 01:53:57 +00001465 assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc);
Douglas Gregor72be3902012-10-19 00:38:02 +00001466
1467 // We only care about file entries that were not overridden.
1468 if (!SLoc->isFile())
1469 continue;
1470 const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001471 if (!Cache->OrigEntry)
Douglas Gregor72be3902012-10-19 00:38:02 +00001472 continue;
1473
Douglas Gregor49491f72013-03-15 22:15:07 +00001474 InputFileEntry Entry;
1475 Entry.File = Cache->OrigEntry;
1476 Entry.IsSystemFile = Cache->IsSystemFile;
1477 Entry.BufferOverridden = Cache->BufferOverridden;
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001478 if (Cache->IsSystemFile)
Douglas Gregor49491f72013-03-15 22:15:07 +00001479 SortedFiles.push_back(Entry);
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001480 else
Douglas Gregor49491f72013-03-15 22:15:07 +00001481 SortedFiles.push_front(Entry);
1482 }
1483
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001484 unsigned UserFilesNum = 0;
1485 // Write out all of the input files.
Richard Smithec216502015-02-13 19:48:37 +00001486 std::vector<uint64_t> InputFileOffsets;
Douglas Gregor49491f72013-03-15 22:15:07 +00001487 for (std::deque<InputFileEntry>::iterator
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001488 I = SortedFiles.begin(), E = SortedFiles.end(); I != E; ++I) {
Douglas Gregor49491f72013-03-15 22:15:07 +00001489 const InputFileEntry &Entry = *I;
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001490
Douglas Gregor49491f72013-03-15 22:15:07 +00001491 uint32_t &InputFileID = InputFileIDs[Entry.File];
Argyrios Kyrtzidise65856f2012-12-11 07:48:08 +00001492 if (InputFileID != 0)
1493 continue; // already recorded this file.
1494
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001495 // Record this entry's offset.
1496 InputFileOffsets.push_back(Stream.GetCurrentBitNo());
Argyrios Kyrtzidise65856f2012-12-11 07:48:08 +00001497
1498 InputFileID = InputFileOffsets.size();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001499
Douglas Gregor49491f72013-03-15 22:15:07 +00001500 if (!Entry.IsSystemFile)
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001501 ++UserFilesNum;
1502
Douglas Gregor72be3902012-10-19 00:38:02 +00001503 Record.clear();
1504 Record.push_back(INPUT_FILE);
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001505 Record.push_back(InputFileOffsets.size());
Douglas Gregor72be3902012-10-19 00:38:02 +00001506
1507 // Emit size/modification time for this file.
Douglas Gregor49491f72013-03-15 22:15:07 +00001508 Record.push_back(Entry.File->getSize());
1509 Record.push_back(Entry.File->getModificationTime());
Douglas Gregor72be3902012-10-19 00:38:02 +00001510
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001511 // Whether this file was overridden.
Douglas Gregor49491f72013-03-15 22:15:07 +00001512 Record.push_back(Entry.BufferOverridden);
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001513
Richard Smith7ed1bc92014-12-05 22:42:13 +00001514 EmitRecordWithPath(IFAbbrevCode, Record, Entry.File->getName());
1515 }
Douglas Gregor49491f72013-03-15 22:15:07 +00001516
Douglas Gregor112b9072012-10-18 05:31:06 +00001517 Stream.ExitBlock();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001518
1519 // Create input file offsets abbreviation.
1520 BitCodeAbbrev *OffsetsAbbrev = new BitCodeAbbrev();
1521 OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS));
1522 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001523 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system
1524 // input files
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001525 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Array
1526 unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(OffsetsAbbrev);
1527
1528 // Write input file offsets.
1529 Record.clear();
1530 Record.push_back(INPUT_FILE_OFFSETS);
1531 Record.push_back(InputFileOffsets.size());
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001532 Record.push_back(UserFilesNum);
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001533 Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, data(InputFileOffsets));
Douglas Gregor55abb232009-04-10 20:39:37 +00001534}
1535
Douglas Gregora7f71a92009-04-10 03:52:48 +00001536//===----------------------------------------------------------------------===//
1537// Source Manager Serialization
1538//===----------------------------------------------------------------------===//
1539
1540/// \brief Create an abbreviation for the SLocEntry that refers to a
1541/// file.
Douglas Gregor8f45df52009-04-16 22:23:12 +00001542static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001543 using namespace llvm;
1544 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00001545 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001546 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1547 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1548 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1549 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
Douglas Gregorb41ca8f2010-03-21 22:49:54 +00001550 // FileEntry fields.
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001551 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001552 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00001553 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
1554 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
Douglas Gregor8f45df52009-04-16 22:23:12 +00001555 return Stream.EmitAbbrev(Abbrev);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001556}
1557
1558/// \brief Create an abbreviation for the SLocEntry that refers to a
1559/// buffer.
Douglas Gregor8f45df52009-04-16 22:23:12 +00001560static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001561 using namespace llvm;
1562 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00001563 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001564 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1565 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1566 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1567 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1568 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
Douglas Gregor8f45df52009-04-16 22:23:12 +00001569 return Stream.EmitAbbrev(Abbrev);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001570}
1571
1572/// \brief Create an abbreviation for the SLocEntry that refers to a
1573/// buffer's blob.
Douglas Gregor8f45df52009-04-16 22:23:12 +00001574static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001575 using namespace llvm;
1576 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00001577 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_BLOB));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001578 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
Douglas Gregor8f45df52009-04-16 22:23:12 +00001579 return Stream.EmitAbbrev(Abbrev);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001580}
1581
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001582/// \brief Create an abbreviation for the SLocEntry that refers to a macro
1583/// expansion.
1584static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001585 using namespace llvm;
1586 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001587 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001588 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1589 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1590 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
1591 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
Douglas Gregor83243272009-04-15 18:05:10 +00001592 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
Douglas Gregor8f45df52009-04-16 22:23:12 +00001593 return Stream.EmitAbbrev(Abbrev);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001594}
1595
Douglas Gregor09b69892011-02-10 17:09:37 +00001596namespace {
1597 // Trait used for the on-disk hash table of header search information.
1598 class HeaderFileInfoTrait {
1599 ASTWriter &Writer;
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001600 const HeaderSearch &HS;
Douglas Gregor09b69892011-02-10 17:09:37 +00001601
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001602 // Keep track of the framework names we've used during serialization.
1603 SmallVector<char, 128> FrameworkStringData;
1604 llvm::StringMap<unsigned> FrameworkNameOffset;
1605
Douglas Gregor09b69892011-02-10 17:09:37 +00001606 public:
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001607 HeaderFileInfoTrait(ASTWriter &Writer, const HeaderSearch &HS)
1608 : Writer(Writer), HS(HS) { }
Douglas Gregor09b69892011-02-10 17:09:37 +00001609
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001610 struct key_type {
1611 const FileEntry *FE;
1612 const char *Filename;
1613 };
1614 typedef const key_type &key_type_ref;
Douglas Gregor09b69892011-02-10 17:09:37 +00001615
1616 typedef HeaderFileInfo data_type;
1617 typedef const data_type &data_type_ref;
Justin Bogner25463f12014-04-18 20:27:24 +00001618 typedef unsigned hash_value_type;
1619 typedef unsigned offset_type;
Douglas Gregor09b69892011-02-10 17:09:37 +00001620
Justin Bogner25463f12014-04-18 20:27:24 +00001621 static hash_value_type ComputeHash(key_type_ref key) {
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001622 // The hash is based only on size/time of the file, so that the reader can
1623 // match even when symlinking or excess path elements ("foo/../", "../")
1624 // change the form of the name. However, complete path is still the key.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001625 //
1626 // FIXME: Using the mtime here will cause problems for explicit module
1627 // imports.
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001628 return llvm::hash_combine(key.FE->getSize(),
1629 key.FE->getModificationTime());
Douglas Gregor09b69892011-02-10 17:09:37 +00001630 }
1631
1632 std::pair<unsigned,unsigned>
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001633 EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) {
Justin Bognere1c147c2014-03-28 22:03:19 +00001634 using namespace llvm::support;
1635 endian::Writer<little> Writer(Out);
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001636 unsigned KeyLen = strlen(key.Filename) + 1 + 8 + 8;
Justin Bognere1c147c2014-03-28 22:03:19 +00001637 Writer.write<uint16_t>(KeyLen);
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001638 unsigned DataLen = 1 + 2 + 4 + 4;
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001639 if (Data.isModuleHeader)
1640 DataLen += 4;
Justin Bognere1c147c2014-03-28 22:03:19 +00001641 Writer.write<uint8_t>(DataLen);
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001642 return std::make_pair(KeyLen, DataLen);
Douglas Gregor09b69892011-02-10 17:09:37 +00001643 }
1644
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001645 void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00001646 using namespace llvm::support;
1647 endian::Writer<little> LE(Out);
1648 LE.write<uint64_t>(key.FE->getSize());
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001649 KeyLen -= 8;
Justin Bognere1c147c2014-03-28 22:03:19 +00001650 LE.write<uint64_t>(key.FE->getModificationTime());
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001651 KeyLen -= 8;
1652 Out.write(key.Filename, KeyLen);
Douglas Gregor09b69892011-02-10 17:09:37 +00001653 }
1654
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001655 void EmitData(raw_ostream &Out, key_type_ref key,
Douglas Gregor09b69892011-02-10 17:09:37 +00001656 data_type_ref Data, unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00001657 using namespace llvm::support;
1658 endian::Writer<little> LE(Out);
Douglas Gregor09b69892011-02-10 17:09:37 +00001659 uint64_t Start = Out.tell(); (void)Start;
1660
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001661 unsigned char Flags = (Data.HeaderRole << 6)
1662 | (Data.isImport << 5)
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001663 | (Data.isPragmaOnce << 4)
1664 | (Data.DirInfo << 2)
1665 | (Data.Resolved << 1)
1666 | Data.IndexHeaderMapHeader;
Justin Bognere1c147c2014-03-28 22:03:19 +00001667 LE.write<uint8_t>(Flags);
1668 LE.write<uint16_t>(Data.NumIncludes);
Douglas Gregor09b69892011-02-10 17:09:37 +00001669
1670 if (!Data.ControllingMacro)
Justin Bognere1c147c2014-03-28 22:03:19 +00001671 LE.write<uint32_t>(Data.ControllingMacroID);
Douglas Gregor09b69892011-02-10 17:09:37 +00001672 else
Justin Bognere1c147c2014-03-28 22:03:19 +00001673 LE.write<uint32_t>(Writer.getIdentifierRef(Data.ControllingMacro));
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001674
1675 unsigned Offset = 0;
1676 if (!Data.Framework.empty()) {
1677 // If this header refers into a framework, save the framework name.
1678 llvm::StringMap<unsigned>::iterator Pos
1679 = FrameworkNameOffset.find(Data.Framework);
1680 if (Pos == FrameworkNameOffset.end()) {
1681 Offset = FrameworkStringData.size() + 1;
1682 FrameworkStringData.append(Data.Framework.begin(),
1683 Data.Framework.end());
1684 FrameworkStringData.push_back(0);
1685
1686 FrameworkNameOffset[Data.Framework] = Offset;
1687 } else
1688 Offset = Pos->second;
1689 }
Justin Bognere1c147c2014-03-28 22:03:19 +00001690 LE.write<uint32_t>(Offset);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001691
1692 if (Data.isModuleHeader) {
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001693 Module *Mod = HS.findModuleForHeader(key.FE).getModule();
Justin Bognere1c147c2014-03-28 22:03:19 +00001694 LE.write<uint32_t>(Writer.getExistingSubmoduleID(Mod));
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001695 }
1696
Douglas Gregor09b69892011-02-10 17:09:37 +00001697 assert(Out.tell() - Start == DataLen && "Wrong data length");
1698 }
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001699
1700 const char *strings_begin() const { return FrameworkStringData.begin(); }
1701 const char *strings_end() const { return FrameworkStringData.end(); }
Douglas Gregor09b69892011-02-10 17:09:37 +00001702 };
1703} // end anonymous namespace
1704
1705/// \brief Write the header search block for the list of files that
1706///
1707/// \param HS The header search structure to save.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001708void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001709 SmallVector<const FileEntry *, 16> FilesByUID;
Douglas Gregor09b69892011-02-10 17:09:37 +00001710 HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
1711
1712 if (FilesByUID.size() > HS.header_file_size())
1713 FilesByUID.resize(HS.header_file_size());
1714
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001715 HeaderFileInfoTrait GeneratorTrait(*this, HS);
Justin Bognerbb094f02014-04-18 19:57:06 +00001716 llvm::OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001717 SmallVector<const char *, 4> SavedStrings;
Douglas Gregor09b69892011-02-10 17:09:37 +00001718 unsigned NumHeaderSearchEntries = 0;
1719 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
1720 const FileEntry *File = FilesByUID[UID];
1721 if (!File)
1722 continue;
1723
Argyrios Kyrtzidisf5ab0342011-11-13 22:08:39 +00001724 // Use HeaderSearch's getFileInfo to make sure we get the HeaderFileInfo
1725 // from the external source if it was not provided already.
Ben Langmuird285c502014-03-13 16:46:36 +00001726 HeaderFileInfo HFI;
1727 if (!HS.tryGetFileInfo(File, HFI) ||
1728 (HFI.External && Chain) ||
1729 (HFI.isModuleHeader && !HFI.isCompilingModuleHeader))
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001730 continue;
Douglas Gregor09b69892011-02-10 17:09:37 +00001731
Richard Smith7ed1bc92014-12-05 22:42:13 +00001732 // Massage the file path into an appropriate form.
Douglas Gregor09b69892011-02-10 17:09:37 +00001733 const char *Filename = File->getName();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001734 SmallString<128> FilenameTmp(Filename);
1735 if (PreparePathForOutput(FilenameTmp)) {
1736 // If we performed any translation on the file name at all, we need to
1737 // save this string, since the generator will refer to it later.
1738 Filename = strdup(FilenameTmp.c_str());
Douglas Gregor09b69892011-02-10 17:09:37 +00001739 SavedStrings.push_back(Filename);
1740 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00001741
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001742 HeaderFileInfoTrait::key_type key = { File, Filename };
1743 Generator.insert(key, HFI, GeneratorTrait);
Douglas Gregor09b69892011-02-10 17:09:37 +00001744 ++NumHeaderSearchEntries;
1745 }
1746
1747 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001748 SmallString<4096> TableData;
Douglas Gregor09b69892011-02-10 17:09:37 +00001749 uint32_t BucketOffset;
1750 {
Justin Bognere1c147c2014-03-28 22:03:19 +00001751 using namespace llvm::support;
Douglas Gregor09b69892011-02-10 17:09:37 +00001752 llvm::raw_svector_ostream Out(TableData);
1753 // Make sure that no bucket is at offset 0
Justin Bognere1c147c2014-03-28 22:03:19 +00001754 endian::Writer<little>(Out).write<uint32_t>(0);
Douglas Gregor09b69892011-02-10 17:09:37 +00001755 BucketOffset = Generator.Emit(Out, GeneratorTrait);
1756 }
1757
1758 // Create a blob abbreviation
1759 using namespace llvm;
1760 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1761 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
1762 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1763 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001764 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor09b69892011-02-10 17:09:37 +00001765 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1766 unsigned TableAbbrev = Stream.EmitAbbrev(Abbrev);
1767
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001768 // Write the header search table
Douglas Gregor09b69892011-02-10 17:09:37 +00001769 RecordData Record;
1770 Record.push_back(HEADER_SEARCH_TABLE);
1771 Record.push_back(BucketOffset);
1772 Record.push_back(NumHeaderSearchEntries);
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001773 Record.push_back(TableData.size());
1774 TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end());
Yaron Keren92e1b622015-03-18 10:17:07 +00001775 Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData);
Douglas Gregor09b69892011-02-10 17:09:37 +00001776
1777 // Free all of the strings we had to duplicate.
1778 for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
David Greenebae0e352013-01-15 22:09:43 +00001779 free(const_cast<char *>(SavedStrings[I]));
Douglas Gregor09b69892011-02-10 17:09:37 +00001780}
1781
Douglas Gregora7f71a92009-04-10 03:52:48 +00001782/// \brief Writes the block containing the serialized form of the
1783/// source manager.
1784///
1785/// TODO: We should probably use an on-disk hash table (stored in a
1786/// blob), indexed based on the file name, so that we only create
1787/// entries for files that we actually need. In the common case (no
1788/// errors), we probably won't have to create file entries for any of
1789/// the files in the AST.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00001790void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001791 const Preprocessor &PP) {
Douglas Gregor258ae542009-04-27 06:38:32 +00001792 RecordData Record;
1793
Chris Lattner0910e3b2009-04-10 17:16:57 +00001794 // Enter the source manager block.
Sebastian Redl539c5062010-08-18 23:57:32 +00001795 Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 3);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001796
1797 // Abbreviations for the various kinds of source-location entries.
Chris Lattnerc4976c732009-04-27 19:03:22 +00001798 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
1799 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
1800 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001801 unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001802
Douglas Gregor258ae542009-04-27 06:38:32 +00001803 // Write out the source location entry table. We skip the first
1804 // entry, which is always the same dummy entry.
Chris Lattner12d61d32009-04-27 19:01:47 +00001805 std::vector<uint32_t> SLocEntryOffsets;
Douglas Gregor258ae542009-04-27 06:38:32 +00001806 RecordData PreloadSLocs;
Douglas Gregor925296b2011-07-19 16:10:42 +00001807 SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
1808 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
Sebastian Redl5c415f32010-07-22 17:01:13 +00001809 I != N; ++I) {
Douglas Gregor8655e882009-10-16 22:46:09 +00001810 // Get this source location entry.
Douglas Gregor925296b2011-07-19 16:10:42 +00001811 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00001812 FileID FID = FileID::get(I);
1813 assert(&SourceMgr.getSLocEntry(FID) == SLoc);
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00001814
Douglas Gregor258ae542009-04-27 06:38:32 +00001815 // Record the offset of this source-location entry.
1816 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
1817
1818 // Figure out which record code to use.
1819 unsigned Code;
1820 if (SLoc->isFile()) {
Douglas Gregor9dc32122011-11-16 20:05:18 +00001821 const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
1822 if (Cache->OrigEntry) {
Sebastian Redl539c5062010-08-18 23:57:32 +00001823 Code = SM_SLOC_FILE_ENTRY;
Argyrios Kyrtzidis92dd4662011-06-02 20:01:46 +00001824 } else
Sebastian Redl539c5062010-08-18 23:57:32 +00001825 Code = SM_SLOC_BUFFER_ENTRY;
Douglas Gregor258ae542009-04-27 06:38:32 +00001826 } else
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001827 Code = SM_SLOC_EXPANSION_ENTRY;
Douglas Gregor258ae542009-04-27 06:38:32 +00001828 Record.clear();
1829 Record.push_back(Code);
1830
Douglas Gregor925296b2011-07-19 16:10:42 +00001831 // Starting offset of this entry within this module, so skip the dummy.
1832 Record.push_back(SLoc->getOffset() - 2);
Douglas Gregor258ae542009-04-27 06:38:32 +00001833 if (SLoc->isFile()) {
1834 const SrcMgr::FileInfo &File = SLoc->getFile();
1835 Record.push_back(File.getIncludeLoc().getRawEncoding());
1836 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
1837 Record.push_back(File.hasLineDirectives());
1838
1839 const SrcMgr::ContentCache *Content = File.getContentCache();
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001840 if (Content->OrigEntry) {
1841 assert(Content->OrigEntry == Content->ContentsEntry &&
Douglas Gregor9dc32122011-11-16 20:05:18 +00001842 "Writing to AST an overridden file is not supported");
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001843
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001844 // The source location entry is a file. Emit input file ID.
1845 assert(InputFileIDs[Content->OrigEntry] != 0 && "Missed file entry");
1846 Record.push_back(InputFileIDs[Content->OrigEntry]);
Mike Stump11289f42009-09-09 15:08:12 +00001847
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001848 Record.push_back(File.NumCreatedFIDs);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00001849
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00001850 FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00001851 if (FDI != FileDeclIDs.end()) {
1852 Record.push_back(FDI->second->FirstDeclIndex);
1853 Record.push_back(FDI->second->DeclIDs.size());
1854 } else {
1855 Record.push_back(0);
1856 Record.push_back(0);
1857 }
Douglas Gregor9dc32122011-11-16 20:05:18 +00001858
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001859 Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record);
Douglas Gregor9dc32122011-11-16 20:05:18 +00001860
1861 if (Content->BufferOverridden) {
1862 Record.clear();
1863 Record.push_back(SM_SLOC_BUFFER_BLOB);
1864 const llvm::MemoryBuffer *Buffer
1865 = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
1866 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
1867 StringRef(Buffer->getBufferStart(),
1868 Buffer->getBufferSize() + 1));
1869 }
Douglas Gregor258ae542009-04-27 06:38:32 +00001870 } else {
1871 // The source location entry is a buffer. The blob associated
1872 // with this entry contains the contents of the buffer.
1873
1874 // We add one to the size so that we capture the trailing NULL
1875 // that is required by llvm::MemoryBuffer::getMemBuffer (on
1876 // the reader side).
Douglas Gregor874cc622010-03-16 00:35:39 +00001877 const llvm::MemoryBuffer *Buffer
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001878 = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
Douglas Gregor258ae542009-04-27 06:38:32 +00001879 const char *Name = Buffer->getBufferIdentifier();
Daniel Dunbar8100d012009-08-24 09:31:37 +00001880 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001881 StringRef(Name, strlen(Name) + 1));
Douglas Gregor258ae542009-04-27 06:38:32 +00001882 Record.clear();
Sebastian Redl539c5062010-08-18 23:57:32 +00001883 Record.push_back(SM_SLOC_BUFFER_BLOB);
Douglas Gregor258ae542009-04-27 06:38:32 +00001884 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001885 StringRef(Buffer->getBufferStart(),
Daniel Dunbar8100d012009-08-24 09:31:37 +00001886 Buffer->getBufferSize() + 1));
Douglas Gregor258ae542009-04-27 06:38:32 +00001887
Douglas Gregor925296b2011-07-19 16:10:42 +00001888 if (strcmp(Name, "<built-in>") == 0) {
1889 PreloadSLocs.push_back(SLocEntryOffsets.size());
1890 }
Douglas Gregor258ae542009-04-27 06:38:32 +00001891 }
1892 } else {
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001893 // The source location entry is a macro expansion.
Chandler Carruthee4c1d12011-07-26 04:56:51 +00001894 const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
Chandler Carruth73ee5d72011-07-26 04:41:47 +00001895 Record.push_back(Expansion.getSpellingLoc().getRawEncoding());
1896 Record.push_back(Expansion.getExpansionLocStart().getRawEncoding());
Argyrios Kyrtzidisa1d943a2011-08-17 00:31:14 +00001897 Record.push_back(Expansion.isMacroArgExpansion() ? 0
1898 : Expansion.getExpansionLocEnd().getRawEncoding());
Douglas Gregor258ae542009-04-27 06:38:32 +00001899
1900 // Compute the token length for this macro expansion.
Douglas Gregor925296b2011-07-19 16:10:42 +00001901 unsigned NextOffset = SourceMgr.getNextLocalOffset();
Douglas Gregor8655e882009-10-16 22:46:09 +00001902 if (I + 1 != N)
Douglas Gregor925296b2011-07-19 16:10:42 +00001903 NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
Douglas Gregor258ae542009-04-27 06:38:32 +00001904 Record.push_back(NextOffset - SLoc->getOffset() - 1);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001905 Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
Douglas Gregor258ae542009-04-27 06:38:32 +00001906 }
1907 }
1908
Douglas Gregor8f45df52009-04-16 22:23:12 +00001909 Stream.ExitBlock();
Douglas Gregor258ae542009-04-27 06:38:32 +00001910
1911 if (SLocEntryOffsets.empty())
1912 return;
1913
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00001914 // Write the source-location offsets table into the AST block. This
Douglas Gregor258ae542009-04-27 06:38:32 +00001915 // table is used for lazily loading source-location information.
1916 using namespace llvm;
1917 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00001918 Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
Douglas Gregor258ae542009-04-27 06:38:32 +00001919 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
Douglas Gregor925296b2011-07-19 16:10:42 +00001920 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
Douglas Gregor258ae542009-04-27 06:38:32 +00001921 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
1922 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
Mike Stump11289f42009-09-09 15:08:12 +00001923
Douglas Gregor258ae542009-04-27 06:38:32 +00001924 Record.clear();
Sebastian Redl539c5062010-08-18 23:57:32 +00001925 Record.push_back(SOURCE_LOCATION_OFFSETS);
Douglas Gregor258ae542009-04-27 06:38:32 +00001926 Record.push_back(SLocEntryOffsets.size());
Douglas Gregor925296b2011-07-19 16:10:42 +00001927 Record.push_back(SourceMgr.getNextLocalOffset() - 1); // skip dummy
Benjamin Kramerd47a12a2011-04-24 17:44:50 +00001928 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record, data(SLocEntryOffsets));
Douglas Gregor258ae542009-04-27 06:38:32 +00001929
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00001930 // Write the source location entry preloads array, telling the AST
Douglas Gregor258ae542009-04-27 06:38:32 +00001931 // reader which source locations entries it should load eagerly.
Sebastian Redl539c5062010-08-18 23:57:32 +00001932 Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
Douglas Gregor925296b2011-07-19 16:10:42 +00001933
1934 // Write the line table. It depends on remapping working, so it must come
1935 // after the source location offsets.
1936 if (SourceMgr.hasLineTable()) {
1937 LineTableInfo &LineTable = SourceMgr.getLineTable();
1938
1939 Record.clear();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001940 // Emit the file names.
Douglas Gregor925296b2011-07-19 16:10:42 +00001941 Record.push_back(LineTable.getNumFilenames());
Richard Smith7ed1bc92014-12-05 22:42:13 +00001942 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I)
1943 AddPath(LineTable.getFilename(I), Record);
Douglas Gregor925296b2011-07-19 16:10:42 +00001944
1945 // Emit the line entries
1946 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
1947 L != LEnd; ++L) {
1948 // Only emit entries for local files.
Douglas Gregor02c2dbf2012-06-08 16:40:28 +00001949 if (L->first.ID < 0)
Douglas Gregor925296b2011-07-19 16:10:42 +00001950 continue;
1951
1952 // Emit the file ID
Douglas Gregor02c2dbf2012-06-08 16:40:28 +00001953 Record.push_back(L->first.ID);
Douglas Gregor925296b2011-07-19 16:10:42 +00001954
1955 // Emit the line entries
1956 Record.push_back(L->second.size());
1957 for (std::vector<LineEntry>::iterator LE = L->second.begin(),
1958 LEEnd = L->second.end();
1959 LE != LEEnd; ++LE) {
1960 Record.push_back(LE->FileOffset);
1961 Record.push_back(LE->LineNo);
1962 Record.push_back(LE->FilenameID);
1963 Record.push_back((unsigned)LE->FileKind);
1964 Record.push_back(LE->IncludeOffset);
1965 }
1966 }
1967 Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
1968 }
Douglas Gregora7f71a92009-04-10 03:52:48 +00001969}
1970
Douglas Gregorc5046832009-04-27 18:38:38 +00001971//===----------------------------------------------------------------------===//
1972// Preprocessor Serialization
1973//===----------------------------------------------------------------------===//
1974
Argyrios Kyrtzidis0aef0f02013-03-15 22:43:10 +00001975static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule,
1976 const Preprocessor &PP) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001977 if (MacroInfo *MI = MD->getMacroInfo())
1978 if (MI->isBuiltinMacro())
1979 return true;
Argyrios Kyrtzidis0aef0f02013-03-15 22:43:10 +00001980
1981 if (IsModule) {
1982 SourceLocation Loc = MD->getLocation();
1983 if (Loc.isInvalid())
1984 return true;
1985 if (PP.getSourceManager().getFileID(Loc) == PP.getPredefinesFileID())
1986 return true;
1987 }
1988
1989 return false;
1990}
1991
Chris Lattnereeffaef2009-04-10 17:15:23 +00001992/// \brief Writes the block containing the serialized form of the
1993/// preprocessor.
1994///
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001995void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00001996 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
1997 if (PPRec)
1998 WritePreprocessorDetail(*PPRec);
1999
Chris Lattnerbaa52f42009-04-10 18:00:12 +00002000 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00002001 RecordData ModuleMacroRecord;
Chris Lattner0910e3b2009-04-10 17:16:57 +00002002
Chris Lattner0af3ba12009-04-13 01:29:17 +00002003 // If the preprocessor __COUNTER__ value has been bumped, remember it.
2004 if (PP.getCounterValue() != 0) {
2005 Record.push_back(PP.getCounterValue());
Sebastian Redl539c5062010-08-18 23:57:32 +00002006 Stream.EmitRecord(PP_COUNTER_VALUE, Record);
Chris Lattner0af3ba12009-04-13 01:29:17 +00002007 Record.clear();
Douglas Gregoreda6a892009-04-26 00:07:37 +00002008 }
2009
2010 // Enter the preprocessor block.
Douglas Gregor796d76a2010-10-20 22:00:55 +00002011 Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
Mike Stump11289f42009-09-09 15:08:12 +00002012
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002013 // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
Douglas Gregoreda6a892009-04-26 00:07:37 +00002014 // FIXME: use diagnostics subsystem for localization etc.
2015 if (PP.SawDateOrTime())
2016 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
Mike Stump11289f42009-09-09 15:08:12 +00002017
Douglas Gregor796d76a2010-10-20 22:00:55 +00002018
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002019 // Loop over all the macro directives that are live at the end of the file,
Chris Lattnerbaa52f42009-04-10 18:00:12 +00002020 // emitting each to the PP section.
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002021
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002022 // Construct the list of macro directives that need to be serialized.
Richard Smithcf97cf62015-04-19 01:34:23 +00002023 typedef std::pair<const IdentifierInfo *, MacroDirective *> MacroChain;
2024 SmallVector<MacroChain, 2> MacroDirectives;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002025 for (Preprocessor::macro_iterator
2026 I = PP.macro_begin(/*IncludeExternalMacros=*/false),
2027 E = PP.macro_end(/*IncludeExternalMacros=*/false);
Chris Lattnerbaa52f42009-04-10 18:00:12 +00002028 I != E; ++I) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00002029 MacroDirectives.push_back(std::make_pair(I->first, I->second.getLatest()));
Douglas Gregor2e5571d2011-02-10 18:20:09 +00002030 }
Alexander Kornienko1d26c022012-09-25 17:18:14 +00002031
Douglas Gregor2e5571d2011-02-10 18:20:09 +00002032 // Sort the set of macro definitions that need to be serialized by the
2033 // name of the macro, to provide a stable ordering.
Richard Smith9eb30932015-04-19 01:47:53 +00002034 int (*Cmp)(const MacroChain*, const MacroChain*) =
2035 [](const MacroChain *A, const MacroChain *B) -> int {
2036 return A->first->getName().compare(B->first->getName());
2037 };
2038 llvm::array_pod_sort(MacroDirectives.begin(), MacroDirectives.end(), Cmp);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002039
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002040 // Emit the macro directives as a list and associate the offset with the
2041 // identifier they belong to.
Richard Smithcf97cf62015-04-19 01:34:23 +00002042 for (auto &Chain : MacroDirectives) {
2043 const IdentifierInfo *Name = Chain.first;
2044 MacroDirective *MD = Chain.second;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002045
2046 // If the macro or identifier need no updates, don't write the macro history
2047 // for this one.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002048 // FIXME: Chain the macro history instead of re-writing it.
Richard Smith20e883e2015-04-29 23:20:19 +00002049 if (MD && MD->isFromPCH() &&
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002050 Name->isFromAST() && !Name->hasChangedSinceDeserialization())
2051 continue;
2052
Richard Smithd7329392015-04-21 21:46:32 +00002053 auto StartOffset = Stream.GetCurrentBitNo();
2054
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002055 // Emit the macro directives in reverse source order.
2056 for (; MD; MD = MD->getPrevious()) {
Richard Smithd7329392015-04-21 21:46:32 +00002057 // Once we hit an ignored macro, we're done: the rest of the chain
2058 // will all be ignored macros.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002059 if (shouldIgnoreMacro(MD, IsModule, PP))
Richard Smithd7329392015-04-21 21:46:32 +00002060 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002061
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002062 AddSourceLocation(MD->getLocation(), Record);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002063 Record.push_back(MD->getKind());
Richard Smithdaa69e02014-07-25 04:40:03 +00002064 if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) {
Richard Smith3981b172015-04-30 02:16:23 +00002065 Record.push_back(getMacroRef(DefMD->getInfo(), Name));
Richard Smith713369b2015-04-23 20:40:50 +00002066 } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002067 Record.push_back(VisMD->isPublic());
2068 }
Richard Smithb8b2ed62015-04-23 18:18:26 +00002069 }
Richard Smithd7329392015-04-21 21:46:32 +00002070
Richard Smithb8b2ed62015-04-23 18:18:26 +00002071 // Write out any exported module macros.
2072 if (IsModule) {
2073 auto Leafs = PP.getLeafModuleMacros(Name);
2074 SmallVector<ModuleMacro*, 8> Worklist(Leafs.begin(), Leafs.end());
2075 llvm::DenseMap<ModuleMacro*, unsigned> Visits;
2076 while (!Worklist.empty()) {
2077 auto *Macro = Worklist.pop_back_val();
Richard Smithd7329392015-04-21 21:46:32 +00002078
Richard Smithb8b2ed62015-04-23 18:18:26 +00002079 // Emit a record indicating this submodule exports this macro.
2080 ModuleMacroRecord.push_back(
2081 getSubmoduleID(Macro->getOwningModule()));
2082 ModuleMacroRecord.push_back(getMacroID(Macro->getMacroInfo()));
2083 for (auto *M : Macro->overrides())
2084 ModuleMacroRecord.push_back(getSubmoduleID(M->getOwningModule()));
Richard Smithd7329392015-04-21 21:46:32 +00002085
Richard Smithb8b2ed62015-04-23 18:18:26 +00002086 Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord);
2087 ModuleMacroRecord.clear();
Richard Smithd7329392015-04-21 21:46:32 +00002088
Richard Smithb8b2ed62015-04-23 18:18:26 +00002089 // Enqueue overridden macros once we've visited all their ancestors.
2090 for (auto *M : Macro->overrides())
2091 if (++Visits[M] == M->getNumOverridingMacros())
2092 Worklist.push_back(M);
Richard Smithd7329392015-04-21 21:46:32 +00002093 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002094 }
Richard Smithd7329392015-04-21 21:46:32 +00002095
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002096 if (Record.empty())
2097 continue;
2098
Richard Smithd7329392015-04-21 21:46:32 +00002099 IdentMacroDirectivesOffsetMap[Name] = StartOffset;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002100 Stream.EmitRecord(PP_MACRO_DIRECTIVE_HISTORY, Record);
2101 Record.clear();
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002102 }
Alexander Kornienko1d26c022012-09-25 17:18:14 +00002103
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002104 /// \brief Offsets of each of the macros into the bitstream, indexed by
2105 /// the local macro ID
2106 ///
2107 /// For each identifier that is associated with a macro, this map
2108 /// provides the offset into the bitstream where that macro is
2109 /// defined.
2110 std::vector<uint32_t> MacroOffsets;
2111
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002112 for (unsigned I = 0, N = MacroInfosToEmit.size(); I != N; ++I) {
2113 const IdentifierInfo *Name = MacroInfosToEmit[I].Name;
2114 MacroInfo *MI = MacroInfosToEmit[I].MI;
2115 MacroID ID = MacroInfosToEmit[I].ID;
Douglas Gregoreb114da2010-10-01 01:03:07 +00002116
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002117 if (ID < FirstMacroID) {
2118 assert(0 && "Loaded MacroInfo entered MacroInfosToEmit ?");
2119 continue;
Chris Lattner2199f5b2009-04-10 18:08:30 +00002120 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002121
2122 // Record the local offset of this macro.
2123 unsigned Index = ID - FirstMacroID;
2124 if (Index == MacroOffsets.size())
2125 MacroOffsets.push_back(Stream.GetCurrentBitNo());
2126 else {
2127 if (Index > MacroOffsets.size())
2128 MacroOffsets.resize(Index + 1);
2129
2130 MacroOffsets[Index] = Stream.GetCurrentBitNo();
2131 }
2132
2133 AddIdentifierRef(Name, Record);
2134 Record.push_back(inferSubmoduleIDFromLocation(MI->getDefinitionLoc()));
2135 AddSourceLocation(MI->getDefinitionLoc(), Record);
2136 AddSourceLocation(MI->getDefinitionEndLoc(), Record);
2137 Record.push_back(MI->isUsed());
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00002138 Record.push_back(MI->isUsedForHeaderGuard());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002139 unsigned Code;
2140 if (MI->isObjectLike()) {
2141 Code = PP_MACRO_OBJECT_LIKE;
2142 } else {
2143 Code = PP_MACRO_FUNCTION_LIKE;
2144
2145 Record.push_back(MI->isC99Varargs());
2146 Record.push_back(MI->isGNUVarargs());
2147 Record.push_back(MI->hasCommaPasting());
2148 Record.push_back(MI->getNumArgs());
2149 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
2150 I != E; ++I)
2151 AddIdentifierRef(*I, Record);
2152 }
2153
2154 // If we have a detailed preprocessing record, record the macro definition
2155 // ID that corresponds to this macro.
2156 if (PPRec)
2157 Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
2158
2159 Stream.EmitRecord(Code, Record);
2160 Record.clear();
2161
2162 // Emit the tokens array.
2163 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
2164 // Note that we know that the preprocessor does not have any annotation
2165 // tokens in it because they are created by the parser, and thus can't
2166 // be in a macro definition.
2167 const Token &Tok = MI->getReplacementToken(TokNo);
John McCallf413f5e2013-05-03 00:10:13 +00002168 AddToken(Tok, Record);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002169 Stream.EmitRecord(PP_TOKEN, Record);
2170 Record.clear();
2171 }
2172 ++NumMacros;
Chris Lattnerbaa52f42009-04-10 18:00:12 +00002173 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002174
Douglas Gregor92a96f52011-02-08 21:58:10 +00002175 Stream.ExitBlock();
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002176
2177 // Write the offsets table for macro IDs.
2178 using namespace llvm;
Richard Smith13090a22015-04-10 02:02:24 +00002179 auto *Abbrev = new BitCodeAbbrev();
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002180 Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET));
2181 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros
2182 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
2183 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2184
2185 unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2186 Record.clear();
2187 Record.push_back(MACRO_OFFSET);
2188 Record.push_back(MacroOffsets.size());
2189 Record.push_back(FirstMacroID - NUM_PREDEF_MACRO_IDS);
2190 Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record,
2191 data(MacroOffsets));
Douglas Gregor92a96f52011-02-08 21:58:10 +00002192}
2193
2194void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) {
Argyrios Kyrtzidis7f448362011-09-19 20:40:42 +00002195 if (PPRec.local_begin() == PPRec.local_end())
Douglas Gregor92a96f52011-02-08 21:58:10 +00002196 return;
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002197
Argyrios Kyrtzidis64f63812011-09-19 20:40:25 +00002198 SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002199
Douglas Gregor92a96f52011-02-08 21:58:10 +00002200 // Enter the preprocessor block.
2201 Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002202
Douglas Gregoraae92242010-03-19 21:51:54 +00002203 // If the preprocessor has a preprocessing record, emit it.
2204 unsigned NumPreprocessingRecords = 0;
Douglas Gregor92a96f52011-02-08 21:58:10 +00002205 using namespace llvm;
2206
2207 // Set up the abbreviation for
2208 unsigned InclusionAbbrev = 0;
2209 {
2210 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2211 Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
Douglas Gregor92a96f52011-02-08 21:58:10 +00002212 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
2213 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
2214 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
Argyrios Kyrtzidisf590e092012-10-02 16:10:46 +00002215 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module
Douglas Gregor92a96f52011-02-08 21:58:10 +00002216 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2217 InclusionAbbrev = Stream.EmitAbbrev(Abbrev);
2218 }
2219
Douglas Gregor2f555fc2011-08-04 18:56:47 +00002220 unsigned FirstPreprocessorEntityID
2221 = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0)
2222 + NUM_PREDEF_PP_ENTITY_IDS;
2223 unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
Douglas Gregor92a96f52011-02-08 21:58:10 +00002224 RecordData Record;
Argyrios Kyrtzidis7f448362011-09-19 20:40:42 +00002225 for (PreprocessingRecord::iterator E = PPRec.local_begin(),
2226 EEnd = PPRec.local_end();
Douglas Gregor0d4b4312011-08-04 17:06:18 +00002227 E != EEnd;
2228 (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
Douglas Gregor92a96f52011-02-08 21:58:10 +00002229 Record.clear();
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002230
Argyrios Kyrtzidis64f63812011-09-19 20:40:25 +00002231 PreprocessedEntityOffsets.push_back(PPEntityOffset((*E)->getSourceRange(),
2232 Stream.GetCurrentBitNo()));
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002233
Douglas Gregor92a96f52011-02-08 21:58:10 +00002234 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002235 // Record this macro definition's ID.
2236 MacroDefinitions[MD] = NextPreprocessorEntityID;
Douglas Gregor92a96f52011-02-08 21:58:10 +00002237
Douglas Gregor92a96f52011-02-08 21:58:10 +00002238 AddIdentifierRef(MD->getName(), Record);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002239 Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
2240 continue;
Douglas Gregoraae92242010-03-19 21:51:54 +00002241 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002242
Chandler Carrutha88a22182011-07-14 08:20:46 +00002243 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(*E)) {
Argyrios Kyrtzidis80f78b92011-09-08 17:18:41 +00002244 Record.push_back(ME->isBuiltinMacro());
2245 if (ME->isBuiltinMacro())
2246 AddIdentifierRef(ME->getName(), Record);
2247 else
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002248 Record.push_back(MacroDefinitions[ME->getDefinition()]);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00002249 Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002250 continue;
2251 }
2252
2253 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
2254 Record.push_back(PPD_INCLUSION_DIRECTIVE);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002255 Record.push_back(ID->getFileName().size());
2256 Record.push_back(ID->wasInQuotes());
2257 Record.push_back(static_cast<unsigned>(ID->getKind()));
Argyrios Kyrtzidisf590e092012-10-02 16:10:46 +00002258 Record.push_back(ID->importedModule());
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002259 SmallString<64> Buffer;
Douglas Gregor92a96f52011-02-08 21:58:10 +00002260 Buffer += ID->getFileName();
Argyrios Kyrtzidis8dbcfc32012-03-08 01:08:28 +00002261 // Check that the FileEntry is not null because it was not resolved and
2262 // we create a PCH even with compiler errors.
2263 if (ID->getFile())
2264 Buffer += ID->getFile()->getName();
Douglas Gregor92a96f52011-02-08 21:58:10 +00002265 Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
2266 continue;
2267 }
2268
2269 llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
2270 }
Douglas Gregor8f45df52009-04-16 22:23:12 +00002271 Stream.ExitBlock();
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002272
Douglas Gregoraae92242010-03-19 21:51:54 +00002273 // Write the offsets table for the preprocessing record.
2274 if (NumPreprocessingRecords > 0) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002275 assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords);
2276
Douglas Gregoraae92242010-03-19 21:51:54 +00002277 // Write the offsets table for identifier IDs.
2278 using namespace llvm;
2279 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002280 Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
Douglas Gregor2f555fc2011-08-04 18:56:47 +00002281 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
Douglas Gregoraae92242010-03-19 21:51:54 +00002282 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002283 unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002284
Douglas Gregoraae92242010-03-19 21:51:54 +00002285 Record.clear();
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002286 Record.push_back(PPD_ENTITIES_OFFSETS);
Douglas Gregor2f555fc2011-08-04 18:56:47 +00002287 Record.push_back(FirstPreprocessorEntityID - NUM_PREDEF_PP_ENTITY_IDS);
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002288 Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
2289 data(PreprocessedEntityOffsets));
Douglas Gregoraae92242010-03-19 21:51:54 +00002290 }
Chris Lattnereeffaef2009-04-10 17:15:23 +00002291}
2292
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002293unsigned ASTWriter::getSubmoduleID(Module *Mod) {
2294 llvm::DenseMap<Module *, unsigned>::iterator Known = SubmoduleIDs.find(Mod);
2295 if (Known != SubmoduleIDs.end())
2296 return Known->second;
2297
2298 return SubmoduleIDs[Mod] = NextSubmoduleID++;
2299}
2300
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00002301unsigned ASTWriter::getExistingSubmoduleID(Module *Mod) const {
2302 if (!Mod)
2303 return 0;
2304
2305 llvm::DenseMap<Module *, unsigned>::const_iterator
2306 Known = SubmoduleIDs.find(Mod);
2307 if (Known != SubmoduleIDs.end())
2308 return Known->second;
2309
2310 return 0;
2311}
2312
Douglas Gregor253eefe2011-12-01 00:59:36 +00002313/// \brief Compute the number of modules within the given tree (including the
2314/// given module).
2315static unsigned getNumberOfModules(Module *Mod) {
2316 unsigned ChildModules = 0;
Douglas Gregoreb90e832012-01-04 23:32:19 +00002317 for (Module::submodule_iterator Sub = Mod->submodule_begin(),
2318 SubEnd = Mod->submodule_end();
Douglas Gregor253eefe2011-12-01 00:59:36 +00002319 Sub != SubEnd; ++Sub)
Douglas Gregoreb90e832012-01-04 23:32:19 +00002320 ChildModules += getNumberOfModules(*Sub);
Douglas Gregor253eefe2011-12-01 00:59:36 +00002321
2322 return ChildModules + 1;
2323}
2324
Douglas Gregorde3ef502011-11-30 23:21:26 +00002325void ASTWriter::WriteSubmodules(Module *WritingModule) {
Douglas Gregor69021972011-11-30 17:33:56 +00002326 // Enter the submodule description block.
Richard Smith202210b2014-10-24 20:23:01 +00002327 Stream.EnterSubblock(SUBMODULE_BLOCK_ID, /*bits for abbreviations*/5);
Douglas Gregor69021972011-11-30 17:33:56 +00002328
2329 // Write the abbreviations needed for the submodules block.
2330 using namespace llvm;
2331 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2332 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002333 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
Douglas Gregor69021972011-11-30 17:33:56 +00002334 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
2335 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2336 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
Richard Smith9bca2982014-03-08 00:03:56 +00002337 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem
2338 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExternC
Douglas Gregora686e1b2012-01-27 19:52:33 +00002339 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules...
Douglas Gregor73441092011-12-05 22:27:44 +00002340 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
Douglas Gregor73441092011-12-05 22:27:44 +00002341 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002342 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ConfigMacrosExh...
Douglas Gregor69021972011-11-30 17:33:56 +00002343 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2344 unsigned DefinitionAbbrev = Stream.EmitAbbrev(Abbrev);
2345
2346 Abbrev = new BitCodeAbbrev();
Douglas Gregor524e33e2011-12-08 19:11:24 +00002347 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
Douglas Gregor69021972011-11-30 17:33:56 +00002348 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2349 unsigned UmbrellaAbbrev = Stream.EmitAbbrev(Abbrev);
2350
2351 Abbrev = new BitCodeAbbrev();
2352 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
2353 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2354 unsigned HeaderAbbrev = Stream.EmitAbbrev(Abbrev);
Douglas Gregor524e33e2011-12-08 19:11:24 +00002355
2356 Abbrev = new BitCodeAbbrev();
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +00002357 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TOPHEADER));
2358 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2359 unsigned TopHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2360
2361 Abbrev = new BitCodeAbbrev();
Douglas Gregor524e33e2011-12-08 19:11:24 +00002362 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
2363 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2364 unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(Abbrev);
2365
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002366 Abbrev = new BitCodeAbbrev();
2367 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES));
Richard Smitha3feee22013-10-28 22:18:19 +00002368 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // State
2369 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Feature
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002370 unsigned RequiresAbbrev = Stream.EmitAbbrev(Abbrev);
2371
Douglas Gregor59527662012-10-15 06:28:11 +00002372 Abbrev = new BitCodeAbbrev();
2373 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXCLUDED_HEADER));
2374 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2375 unsigned ExcludedHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2376
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002377 Abbrev = new BitCodeAbbrev();
Richard Smith306d8922014-10-22 23:50:56 +00002378 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TEXTUAL_HEADER));
2379 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2380 unsigned TextualHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2381
2382 Abbrev = new BitCodeAbbrev();
Lawrence Crowlb53e5482013-06-20 21:14:14 +00002383 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_HEADER));
2384 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2385 unsigned PrivateHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2386
2387 Abbrev = new BitCodeAbbrev();
Richard Smith202210b2014-10-24 20:23:01 +00002388 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_TEXTUAL_HEADER));
2389 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2390 unsigned PrivateTextualHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2391
2392 Abbrev = new BitCodeAbbrev();
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002393 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_LINK_LIBRARY));
2394 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2395 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2396 unsigned LinkLibraryAbbrev = Stream.EmitAbbrev(Abbrev);
2397
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002398 Abbrev = new BitCodeAbbrev();
2399 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFIG_MACRO));
2400 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
2401 unsigned ConfigMacroAbbrev = Stream.EmitAbbrev(Abbrev);
2402
Douglas Gregorfb912652013-03-20 21:10:35 +00002403 Abbrev = new BitCodeAbbrev();
2404 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFLICT));
2405 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Other module
2406 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Message
2407 unsigned ConflictAbbrev = Stream.EmitAbbrev(Abbrev);
2408
Douglas Gregor253eefe2011-12-01 00:59:36 +00002409 // Write the submodule metadata block.
2410 RecordData Record;
2411 Record.push_back(getNumberOfModules(WritingModule));
2412 Record.push_back(FirstSubmoduleID - NUM_PREDEF_SUBMODULE_IDS);
2413 Stream.EmitRecord(SUBMODULE_METADATA, Record);
2414
Douglas Gregor69021972011-11-30 17:33:56 +00002415 // Write all of the submodules.
Douglas Gregorde3ef502011-11-30 23:21:26 +00002416 std::queue<Module *> Q;
Douglas Gregor69021972011-11-30 17:33:56 +00002417 Q.push(WritingModule);
Douglas Gregor69021972011-11-30 17:33:56 +00002418 while (!Q.empty()) {
Douglas Gregorde3ef502011-11-30 23:21:26 +00002419 Module *Mod = Q.front();
Douglas Gregor69021972011-11-30 17:33:56 +00002420 Q.pop();
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002421 unsigned ID = getSubmoduleID(Mod);
Douglas Gregor69021972011-11-30 17:33:56 +00002422
2423 // Emit the definition of the block.
2424 Record.clear();
2425 Record.push_back(SUBMODULE_DEFINITION);
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002426 Record.push_back(ID);
Douglas Gregor69021972011-11-30 17:33:56 +00002427 if (Mod->Parent) {
2428 assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?");
2429 Record.push_back(SubmoduleIDs[Mod->Parent]);
2430 } else {
2431 Record.push_back(0);
2432 }
2433 Record.push_back(Mod->IsFramework);
2434 Record.push_back(Mod->IsExplicit);
Douglas Gregora686e1b2012-01-27 19:52:33 +00002435 Record.push_back(Mod->IsSystem);
Richard Smith9bca2982014-03-08 00:03:56 +00002436 Record.push_back(Mod->IsExternC);
Douglas Gregor73441092011-12-05 22:27:44 +00002437 Record.push_back(Mod->InferSubmodules);
2438 Record.push_back(Mod->InferExplicitSubmodules);
2439 Record.push_back(Mod->InferExportWildcard);
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002440 Record.push_back(Mod->ConfigMacrosExhaustive);
Douglas Gregor69021972011-11-30 17:33:56 +00002441 Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
2442
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002443 // Emit the requirements.
Richard Smitha3feee22013-10-28 22:18:19 +00002444 for (unsigned I = 0, N = Mod->Requirements.size(); I != N; ++I) {
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002445 Record.clear();
2446 Record.push_back(SUBMODULE_REQUIRES);
Richard Smitha3feee22013-10-28 22:18:19 +00002447 Record.push_back(Mod->Requirements[I].second);
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002448 Stream.EmitRecordWithBlob(RequiresAbbrev, Record,
Richard Smitha3feee22013-10-28 22:18:19 +00002449 Mod->Requirements[I].first);
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002450 }
2451
Douglas Gregor69021972011-11-30 17:33:56 +00002452 // Emit the umbrella header, if there is one.
Douglas Gregor73141fa2011-12-08 17:39:04 +00002453 if (const FileEntry *UmbrellaHeader = Mod->getUmbrellaHeader()) {
Douglas Gregor69021972011-11-30 17:33:56 +00002454 Record.clear();
Douglas Gregor524e33e2011-12-08 19:11:24 +00002455 Record.push_back(SUBMODULE_UMBRELLA_HEADER);
Douglas Gregor69021972011-11-30 17:33:56 +00002456 Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
Douglas Gregor73141fa2011-12-08 17:39:04 +00002457 UmbrellaHeader->getName());
Douglas Gregor524e33e2011-12-08 19:11:24 +00002458 } else if (const DirectoryEntry *UmbrellaDir = Mod->getUmbrellaDir()) {
2459 Record.clear();
2460 Record.push_back(SUBMODULE_UMBRELLA_DIR);
2461 Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,
2462 UmbrellaDir->getName());
Douglas Gregor69021972011-11-30 17:33:56 +00002463 }
Richard Smith306d8922014-10-22 23:50:56 +00002464
Douglas Gregor69021972011-11-30 17:33:56 +00002465 // Emit the headers.
Richard Smith202210b2014-10-24 20:23:01 +00002466 struct {
Richard Smith3c1a41a2014-12-02 00:08:08 +00002467 unsigned RecordKind;
Richard Smith202210b2014-10-24 20:23:01 +00002468 unsigned Abbrev;
Richard Smith3c1a41a2014-12-02 00:08:08 +00002469 Module::HeaderKind HeaderKind;
Richard Smith202210b2014-10-24 20:23:01 +00002470 } HeaderLists[] = {
Richard Smith3c1a41a2014-12-02 00:08:08 +00002471 {SUBMODULE_HEADER, HeaderAbbrev, Module::HK_Normal},
2472 {SUBMODULE_TEXTUAL_HEADER, TextualHeaderAbbrev, Module::HK_Textual},
2473 {SUBMODULE_PRIVATE_HEADER, PrivateHeaderAbbrev, Module::HK_Private},
Richard Smith202210b2014-10-24 20:23:01 +00002474 {SUBMODULE_PRIVATE_TEXTUAL_HEADER, PrivateTextualHeaderAbbrev,
Richard Smith3c1a41a2014-12-02 00:08:08 +00002475 Module::HK_PrivateTextual},
2476 {SUBMODULE_EXCLUDED_HEADER, ExcludedHeaderAbbrev, Module::HK_Excluded}
Richard Smith202210b2014-10-24 20:23:01 +00002477 };
2478 for (auto &HL : HeaderLists) {
Douglas Gregor69021972011-11-30 17:33:56 +00002479 Record.clear();
Richard Smith3c1a41a2014-12-02 00:08:08 +00002480 Record.push_back(HL.RecordKind);
2481 for (auto &H : Mod->Headers[HL.HeaderKind])
2482 Stream.EmitRecordWithBlob(HL.Abbrev, Record, H.NameAsWritten);
2483 }
2484
2485 // Emit the top headers.
2486 {
2487 auto TopHeaders = Mod->getTopHeaders(PP->getFileManager());
2488 Record.clear();
2489 Record.push_back(SUBMODULE_TOPHEADER);
2490 for (auto *H : TopHeaders)
2491 Stream.EmitRecordWithBlob(TopHeaderAbbrev, Record, H->getName());
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +00002492 }
Douglas Gregor0093b3c2011-12-05 16:33:54 +00002493
2494 // Emit the imports.
2495 if (!Mod->Imports.empty()) {
2496 Record.clear();
2497 for (unsigned I = 0, N = Mod->Imports.size(); I != N; ++I) {
Douglas Gregor18b58642011-12-12 23:17:57 +00002498 unsigned ImportedID = getSubmoduleID(Mod->Imports[I]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00002499 assert(ImportedID && "Unknown submodule!");
Douglas Gregor0093b3c2011-12-05 16:33:54 +00002500 Record.push_back(ImportedID);
2501 }
2502 Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
2503 }
2504
Douglas Gregor24bb9232011-12-02 18:58:38 +00002505 // Emit the exports.
2506 if (!Mod->Exports.empty()) {
2507 Record.clear();
2508 for (unsigned I = 0, N = Mod->Exports.size(); I != N; ++I) {
Douglas Gregor18b58642011-12-12 23:17:57 +00002509 if (Module *Exported = Mod->Exports[I].getPointer()) {
2510 unsigned ExportedID = SubmoduleIDs[Exported];
2511 assert(ExportedID > 0 && "Unknown submodule ID?");
2512 Record.push_back(ExportedID);
2513 } else {
2514 Record.push_back(0);
2515 }
2516
Douglas Gregor24bb9232011-12-02 18:58:38 +00002517 Record.push_back(Mod->Exports[I].getInt());
2518 }
2519 Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
2520 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002521
Daniel Jasperba7f2f72013-09-24 09:14:14 +00002522 //FIXME: How do we emit the 'use'd modules? They may not be submodules.
2523 // Might be unnecessary as use declarations are only used to build the
2524 // module itself.
2525
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002526 // Emit the link libraries.
2527 for (unsigned I = 0, N = Mod->LinkLibraries.size(); I != N; ++I) {
2528 Record.clear();
2529 Record.push_back(SUBMODULE_LINK_LIBRARY);
2530 Record.push_back(Mod->LinkLibraries[I].IsFramework);
2531 Stream.EmitRecordWithBlob(LinkLibraryAbbrev, Record,
2532 Mod->LinkLibraries[I].Library);
2533 }
2534
Douglas Gregorfb912652013-03-20 21:10:35 +00002535 // Emit the conflicts.
2536 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
2537 Record.clear();
2538 Record.push_back(SUBMODULE_CONFLICT);
2539 unsigned OtherID = getSubmoduleID(Mod->Conflicts[I].Other);
2540 assert(OtherID && "Unknown submodule!");
2541 Record.push_back(OtherID);
2542 Stream.EmitRecordWithBlob(ConflictAbbrev, Record,
2543 Mod->Conflicts[I].Message);
2544 }
2545
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002546 // Emit the configuration macros.
2547 for (unsigned I = 0, N = Mod->ConfigMacros.size(); I != N; ++I) {
2548 Record.clear();
2549 Record.push_back(SUBMODULE_CONFIG_MACRO);
2550 Stream.EmitRecordWithBlob(ConfigMacroAbbrev, Record,
2551 Mod->ConfigMacros[I]);
2552 }
2553
Douglas Gregor69021972011-11-30 17:33:56 +00002554 // Queue up the submodules of this module.
Douglas Gregoreb90e832012-01-04 23:32:19 +00002555 for (Module::submodule_iterator Sub = Mod->submodule_begin(),
2556 SubEnd = Mod->submodule_end();
Douglas Gregor69021972011-11-30 17:33:56 +00002557 Sub != SubEnd; ++Sub)
Douglas Gregoreb90e832012-01-04 23:32:19 +00002558 Q.push(*Sub);
Douglas Gregor69021972011-11-30 17:33:56 +00002559 }
2560
2561 Stream.ExitBlock();
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002562
2563 assert((NextSubmoduleID - FirstSubmoduleID
2564 == getNumberOfModules(WritingModule)) && "Wrong # of submodules");
Douglas Gregor69021972011-11-30 17:33:56 +00002565}
2566
Douglas Gregora28bcdd2011-12-01 02:07:58 +00002567serialization::SubmoduleID
2568ASTWriter::inferSubmoduleIDFromLocation(SourceLocation Loc) {
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002569 if (Loc.isInvalid() || !WritingModule)
Douglas Gregora28bcdd2011-12-01 02:07:58 +00002570 return 0; // No submodule
Douglas Gregor0093b3c2011-12-05 16:33:54 +00002571
2572 // Find the module that owns this location.
Douglas Gregora28bcdd2011-12-01 02:07:58 +00002573 ModuleMap &ModMap = PP->getHeaderSearchInfo().getModuleMap();
Douglas Gregor0093b3c2011-12-05 16:33:54 +00002574 Module *OwningMod
2575 = ModMap.inferModuleFromLocation(FullSourceLoc(Loc,PP->getSourceManager()));
Douglas Gregora28bcdd2011-12-01 02:07:58 +00002576 if (!OwningMod)
2577 return 0;
2578
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002579 // Check whether this submodule is part of our own module.
2580 if (WritingModule != OwningMod && !OwningMod->isSubModuleOf(WritingModule))
Douglas Gregora28bcdd2011-12-01 02:07:58 +00002581 return 0;
2582
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002583 return getSubmoduleID(OwningMod);
Douglas Gregora28bcdd2011-12-01 02:07:58 +00002584}
2585
Argyrios Kyrtzidis0f06b982013-03-27 17:17:23 +00002586void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
2587 bool isModule) {
2588 // Make sure set diagnostic pragmas don't affect the translation unit that
2589 // imports the module.
2590 // FIXME: Make diagnostic pragma sections work properly with modules.
2591 if (isModule)
2592 return;
2593
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002594 llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64>
2595 DiagStateIDMap;
2596 unsigned CurrID = 0;
2597 DiagStateIDMap[&Diag.DiagStates.front()] = ++CurrID; // the command-line one.
Argyrios Kyrtzidis452707c2010-11-05 22:10:18 +00002598 RecordData Record;
David Blaikie9c902b52011-09-25 23:23:43 +00002599 for (DiagnosticsEngine::DiagStatePointsTy::const_iterator
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +00002600 I = Diag.DiagStatePoints.begin(), E = Diag.DiagStatePoints.end();
2601 I != E; ++I) {
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002602 const DiagnosticsEngine::DiagStatePoint &point = *I;
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +00002603 if (point.Loc.isInvalid())
2604 continue;
2605
2606 Record.push_back(point.Loc.getRawEncoding());
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002607 unsigned &DiagStateID = DiagStateIDMap[point.State];
2608 Record.push_back(DiagStateID);
2609
2610 if (DiagStateID == 0) {
2611 DiagStateID = ++CurrID;
2612 for (DiagnosticsEngine::DiagState::const_iterator
2613 I = point.State->begin(), E = point.State->end(); I != E; ++I) {
2614 if (I->second.isPragma()) {
2615 Record.push_back(I->first);
Alp Toker46df1c02014-06-12 10:15:20 +00002616 Record.push_back((unsigned)I->second.getSeverity());
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002617 }
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +00002618 }
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002619 Record.push_back(-1); // mark the end of the diag/map pairs for this
2620 // location.
Argyrios Kyrtzidis452707c2010-11-05 22:10:18 +00002621 }
2622 }
2623
Argyrios Kyrtzidisb0ca9eb2010-11-05 22:20:49 +00002624 if (!Record.empty())
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +00002625 Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
Argyrios Kyrtzidis452707c2010-11-05 22:10:18 +00002626}
2627
Richard Smithc2bb8182015-03-24 06:36:48 +00002628void ASTWriter::WriteCXXCtorInitializersOffsets() {
2629 if (CXXCtorInitializersOffsets.empty())
2630 return;
2631
2632 RecordData Record;
2633
2634 // Create a blob abbreviation for the C++ ctor initializer offsets.
2635 using namespace llvm;
2636
2637 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2638 Abbrev->Add(BitCodeAbbrevOp(CXX_CTOR_INITIALIZERS_OFFSETS));
2639 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
2640 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2641 unsigned CtorInitializersOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2642
2643 // Write the base specifier offsets table.
2644 Record.clear();
2645 Record.push_back(CXX_CTOR_INITIALIZERS_OFFSETS);
2646 Record.push_back(CXXCtorInitializersOffsets.size());
2647 Stream.EmitRecordWithBlob(CtorInitializersOffsetAbbrev, Record,
2648 data(CXXCtorInitializersOffsets));
2649}
2650
Anders Carlsson9bb83e82011-03-06 18:41:18 +00002651void ASTWriter::WriteCXXBaseSpecifiersOffsets() {
2652 if (CXXBaseSpecifiersOffsets.empty())
2653 return;
2654
2655 RecordData Record;
2656
2657 // Create a blob abbreviation for the C++ base specifiers offsets.
2658 using namespace llvm;
2659
2660 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2661 Abbrev->Add(BitCodeAbbrevOp(CXX_BASE_SPECIFIER_OFFSETS));
2662 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
2663 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2664 unsigned BaseSpecifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2665
Douglas Gregorc27b2872011-08-04 00:01:48 +00002666 // Write the base specifier offsets table.
Anders Carlsson9bb83e82011-03-06 18:41:18 +00002667 Record.clear();
2668 Record.push_back(CXX_BASE_SPECIFIER_OFFSETS);
2669 Record.push_back(CXXBaseSpecifiersOffsets.size());
2670 Stream.EmitRecordWithBlob(BaseSpecifierOffsetAbbrev, Record,
Benjamin Kramerd47a12a2011-04-24 17:44:50 +00002671 data(CXXBaseSpecifiersOffsets));
Anders Carlsson9bb83e82011-03-06 18:41:18 +00002672}
2673
Douglas Gregorc5046832009-04-27 18:38:38 +00002674//===----------------------------------------------------------------------===//
2675// Type Serialization
2676//===----------------------------------------------------------------------===//
Chris Lattnereeffaef2009-04-10 17:15:23 +00002677
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002678/// \brief Write the representation of a type to the AST stream.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002679void ASTWriter::WriteType(QualType T) {
Argyrios Kyrtzidisa7fbbb02010-08-20 16:04:04 +00002680 TypeIdx &Idx = TypeIdxs[T];
Argyrios Kyrtzidisbb5c7eae2010-08-20 16:03:59 +00002681 if (Idx.getIndex() == 0) // we haven't seen this type before.
2682 Idx = TypeIdx(NextTypeID++);
Mike Stump11289f42009-09-09 15:08:12 +00002683
Douglas Gregor9b3932c2010-10-05 18:37:06 +00002684 assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
Douglas Gregordc72caa2010-10-04 18:21:45 +00002685
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002686 // Record the offset for this type.
Argyrios Kyrtzidisbb5c7eae2010-08-20 16:03:59 +00002687 unsigned Index = Idx.getIndex() - FirstTypeID;
Sebastian Redl66c5eef2010-07-27 00:17:23 +00002688 if (TypeOffsets.size() == Index)
Douglas Gregor8f45df52009-04-16 22:23:12 +00002689 TypeOffsets.push_back(Stream.GetCurrentBitNo());
Sebastian Redl66c5eef2010-07-27 00:17:23 +00002690 else if (TypeOffsets.size() < Index) {
2691 TypeOffsets.resize(Index + 1);
2692 TypeOffsets[Index] = Stream.GetCurrentBitNo();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002693 }
2694
2695 RecordData Record;
Mike Stump11289f42009-09-09 15:08:12 +00002696
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002697 // Emit the type's representation.
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002698 ASTTypeWriter W(*this, Record);
Richard Smith01b2cb42014-07-26 06:37:51 +00002699 W.AbbrevToUse = 0;
John McCall8ccfcb52009-09-24 19:53:00 +00002700
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002701 if (T.hasLocalNonFastQualifiers()) {
2702 Qualifiers Qs = T.getLocalQualifiers();
2703 AddTypeRef(T.getLocalUnqualifiedType(), Record);
John McCall8ccfcb52009-09-24 19:53:00 +00002704 Record.push_back(Qs.getAsOpaqueValue());
Sebastian Redl539c5062010-08-18 23:57:32 +00002705 W.Code = TYPE_EXT_QUAL;
Richard Smith01b2cb42014-07-26 06:37:51 +00002706 W.AbbrevToUse = TypeExtQualAbbrev;
John McCall8ccfcb52009-09-24 19:53:00 +00002707 } else {
2708 switch (T->getTypeClass()) {
2709 // For all of the concrete, non-dependent types, call the
2710 // appropriate visitor function.
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002711#define TYPE(Class, Base) \
Mike Stump281d6d72010-01-20 02:03:14 +00002712 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002713#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002714#include "clang/AST/TypeNodes.def"
John McCall8ccfcb52009-09-24 19:53:00 +00002715 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002716 }
2717
2718 // Emit the serialized record.
Richard Smith01b2cb42014-07-26 06:37:51 +00002719 Stream.EmitRecord(W.Code, Record, W.AbbrevToUse);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002720
2721 // Flush any expressions that were written as part of this type.
Douglas Gregor8f45df52009-04-16 22:23:12 +00002722 FlushStmts();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002723}
2724
Douglas Gregorc5046832009-04-27 18:38:38 +00002725//===----------------------------------------------------------------------===//
2726// Declaration Serialization
2727//===----------------------------------------------------------------------===//
2728
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002729/// \brief Write the block containing all of the declaration IDs
2730/// lexically declared within the given DeclContext.
2731///
2732/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
2733/// bistream, or 0 if no block was written.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002734uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002735 DeclContext *DC) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002736 if (DC->decls_empty())
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002737 return 0;
2738
Douglas Gregor8f45df52009-04-16 22:23:12 +00002739 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002740 RecordData Record;
Sebastian Redl539c5062010-08-18 23:57:32 +00002741 Record.push_back(DECL_CONTEXT_LEXICAL);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002742 SmallVector<KindDeclIDPair, 64> Decls;
Aaron Ballman629afae2014-03-07 19:56:05 +00002743 for (const auto *D : DC->decls())
2744 Decls.push_back(std::make_pair(D->getKind(), GetDeclRef(D)));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002745
Douglas Gregora57c3ab2009-04-22 22:34:57 +00002746 ++NumLexicalDeclContexts;
Benjamin Kramerd47a12a2011-04-24 17:44:50 +00002747 Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record, data(Decls));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002748 return Offset;
2749}
2750
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002751void ASTWriter::WriteTypeDeclOffsets() {
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002752 using namespace llvm;
2753 RecordData Record;
2754
2755 // Write the type offsets array
2756 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00002757 Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002758 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
Douglas Gregor5204bde2011-08-02 16:26:37 +00002759 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002760 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
2761 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2762 Record.clear();
Sebastian Redl539c5062010-08-18 23:57:32 +00002763 Record.push_back(TYPE_OFFSET);
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002764 Record.push_back(TypeOffsets.size());
Douglas Gregor5204bde2011-08-02 16:26:37 +00002765 Record.push_back(FirstTypeID - NUM_PREDEF_TYPE_IDS);
Benjamin Kramerd47a12a2011-04-24 17:44:50 +00002766 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, data(TypeOffsets));
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002767
2768 // Write the declaration offsets array
2769 Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00002770 Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002771 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
Douglas Gregorf7180622011-08-03 15:48:04 +00002772 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002773 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
2774 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2775 Record.clear();
Sebastian Redl539c5062010-08-18 23:57:32 +00002776 Record.push_back(DECL_OFFSET);
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002777 Record.push_back(DeclOffsets.size());
Douglas Gregor6f8912e2011-08-03 16:05:40 +00002778 Record.push_back(FirstDeclID - NUM_PREDEF_DECL_IDS);
Benjamin Kramerd47a12a2011-04-24 17:44:50 +00002779 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, data(DeclOffsets));
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002780}
2781
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002782void ASTWriter::WriteFileDeclIDsMap() {
2783 using namespace llvm;
2784 RecordData Record;
2785
Chandler Carruthb306d732015-03-27 00:31:20 +00002786 SmallVector<std::pair<FileID, DeclIDInFileInfo *>, 64> SortedFileDeclIDs(
2787 FileDeclIDs.begin(), FileDeclIDs.end());
2788 std::sort(SortedFileDeclIDs.begin(), SortedFileDeclIDs.end(),
2789 llvm::less_first());
2790
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002791 // Join the vectors of DeclIDs from all files.
Chandler Carruthb306d732015-03-27 00:31:20 +00002792 SmallVector<DeclID, 256> FileGroupedDeclIDs;
2793 for (auto &FileDeclEntry : SortedFileDeclIDs) {
2794 DeclIDInFileInfo &Info = *FileDeclEntry.second;
2795 Info.FirstDeclIndex = FileGroupedDeclIDs.size();
2796 for (auto &LocDeclEntry : Info.DeclIDs)
2797 FileGroupedDeclIDs.push_back(LocDeclEntry.second);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002798 }
2799
2800 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2801 Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002802 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002803 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2804 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
2805 Record.push_back(FILE_SORTED_DECLS);
Chandler Carruthb306d732015-03-27 00:31:20 +00002806 Record.push_back(FileGroupedDeclIDs.size());
2807 Stream.EmitRecordWithBlob(AbbrevCode, Record, data(FileGroupedDeclIDs));
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002808}
2809
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002810void ASTWriter::WriteComments() {
2811 Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +00002812 ArrayRef<RawComment *> RawComments = Context->Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002813 RecordData Record;
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +00002814 for (ArrayRef<RawComment *>::iterator I = RawComments.begin(),
2815 E = RawComments.end();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002816 I != E; ++I) {
2817 Record.clear();
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +00002818 AddSourceRange((*I)->getSourceRange(), Record);
2819 Record.push_back((*I)->getKind());
2820 Record.push_back((*I)->isTrailingComment());
2821 Record.push_back((*I)->isAlmostTrailingComment());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002822 Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
2823 }
2824 Stream.ExitBlock();
2825}
2826
Douglas Gregorc5046832009-04-27 18:38:38 +00002827//===----------------------------------------------------------------------===//
2828// Global Method Pool and Selector Serialization
2829//===----------------------------------------------------------------------===//
2830
Douglas Gregore84a9da2009-04-20 20:36:09 +00002831namespace {
Douglas Gregorc78d3462009-04-24 21:10:55 +00002832// Trait used for the on-disk hash table used in the method pool.
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002833class ASTMethodPoolTrait {
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002834 ASTWriter &Writer;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002835
2836public:
2837 typedef Selector key_type;
2838 typedef key_type key_type_ref;
Mike Stump11289f42009-09-09 15:08:12 +00002839
Sebastian Redl834bb972010-08-04 17:20:04 +00002840 struct data_type {
Sebastian Redl539c5062010-08-18 23:57:32 +00002841 SelectorID ID;
Sebastian Redl834bb972010-08-04 17:20:04 +00002842 ObjCMethodList Instance, Factory;
2843 };
Douglas Gregorc78d3462009-04-24 21:10:55 +00002844 typedef const data_type& data_type_ref;
2845
Justin Bogner25463f12014-04-18 20:27:24 +00002846 typedef unsigned hash_value_type;
2847 typedef unsigned offset_type;
2848
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002849 explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) { }
Mike Stump11289f42009-09-09 15:08:12 +00002850
Justin Bogner25463f12014-04-18 20:27:24 +00002851 static hash_value_type ComputeHash(Selector Sel) {
Argyrios Kyrtzidis4bd97102010-08-20 16:03:52 +00002852 return serialization::ComputeHash(Sel);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002853 }
Mike Stump11289f42009-09-09 15:08:12 +00002854
2855 std::pair<unsigned,unsigned>
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002856 EmitKeyDataLength(raw_ostream& Out, Selector Sel,
Douglas Gregorc78d3462009-04-24 21:10:55 +00002857 data_type_ref Methods) {
Justin Bognere1c147c2014-03-28 22:03:19 +00002858 using namespace llvm::support;
2859 endian::Writer<little> LE(Out);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002860 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
Justin Bognere1c147c2014-03-28 22:03:19 +00002861 LE.write<uint16_t>(KeyLen);
Sebastian Redl834bb972010-08-04 17:20:04 +00002862 unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
2863 for (const ObjCMethodList *Method = &Methods.Instance; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002864 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002865 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00002866 DataLen += 4;
Sebastian Redl834bb972010-08-04 17:20:04 +00002867 for (const ObjCMethodList *Method = &Methods.Factory; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002868 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002869 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00002870 DataLen += 4;
Justin Bognere1c147c2014-03-28 22:03:19 +00002871 LE.write<uint16_t>(DataLen);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002872 return std::make_pair(KeyLen, DataLen);
2873 }
Mike Stump11289f42009-09-09 15:08:12 +00002874
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002875 void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
Justin Bognere1c147c2014-03-28 22:03:19 +00002876 using namespace llvm::support;
2877 endian::Writer<little> LE(Out);
Mike Stump11289f42009-09-09 15:08:12 +00002878 uint64_t Start = Out.tell();
Douglas Gregor95c13f52009-04-25 17:48:32 +00002879 assert((Start >> 32) == 0 && "Selector key offset too large");
2880 Writer.SetSelectorOffset(Sel, Start);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002881 unsigned N = Sel.getNumArgs();
Justin Bognere1c147c2014-03-28 22:03:19 +00002882 LE.write<uint16_t>(N);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002883 if (N == 0)
2884 N = 1;
2885 for (unsigned I = 0; I != N; ++I)
Justin Bognere1c147c2014-03-28 22:03:19 +00002886 LE.write<uint32_t>(
2887 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
Douglas Gregorc78d3462009-04-24 21:10:55 +00002888 }
Mike Stump11289f42009-09-09 15:08:12 +00002889
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002890 void EmitData(raw_ostream& Out, key_type_ref,
Douglas Gregor4647cfa2009-04-24 21:49:02 +00002891 data_type_ref Methods, unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00002892 using namespace llvm::support;
2893 endian::Writer<little> LE(Out);
Douglas Gregor4647cfa2009-04-24 21:49:02 +00002894 uint64_t Start = Out.tell(); (void)Start;
Justin Bognere1c147c2014-03-28 22:03:19 +00002895 LE.write<uint32_t>(Methods.ID);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002896 unsigned NumInstanceMethods = 0;
Sebastian Redl834bb972010-08-04 17:20:04 +00002897 for (const ObjCMethodList *Method = &Methods.Instance; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002898 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002899 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00002900 ++NumInstanceMethods;
2901
2902 unsigned NumFactoryMethods = 0;
Sebastian Redl834bb972010-08-04 17:20:04 +00002903 for (const ObjCMethodList *Method = &Methods.Factory; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002904 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002905 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00002906 ++NumFactoryMethods;
2907
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002908 unsigned InstanceBits = Methods.Instance.getBits();
2909 assert(InstanceBits < 4);
Nico Weberff4b35e2014-12-27 22:14:15 +00002910 unsigned InstanceHasMoreThanOneDeclBit =
2911 Methods.Instance.hasMoreThanOneDecl();
2912 unsigned FullInstanceBits = (NumInstanceMethods << 3) |
2913 (InstanceHasMoreThanOneDeclBit << 2) |
2914 InstanceBits;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002915 unsigned FactoryBits = Methods.Factory.getBits();
2916 assert(FactoryBits < 4);
Nico Weberff4b35e2014-12-27 22:14:15 +00002917 unsigned FactoryHasMoreThanOneDeclBit =
2918 Methods.Factory.hasMoreThanOneDecl();
2919 unsigned FullFactoryBits = (NumFactoryMethods << 3) |
2920 (FactoryHasMoreThanOneDeclBit << 2) |
2921 FactoryBits;
2922 LE.write<uint16_t>(FullInstanceBits);
2923 LE.write<uint16_t>(FullFactoryBits);
Sebastian Redl834bb972010-08-04 17:20:04 +00002924 for (const ObjCMethodList *Method = &Methods.Instance; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002925 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002926 if (Method->getMethod())
2927 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
Sebastian Redl834bb972010-08-04 17:20:04 +00002928 for (const ObjCMethodList *Method = &Methods.Factory; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002929 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002930 if (Method->getMethod())
2931 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
Douglas Gregor4647cfa2009-04-24 21:49:02 +00002932
2933 assert(Out.tell() - Start == DataLen && "Data length is wrong");
Douglas Gregorc78d3462009-04-24 21:10:55 +00002934 }
2935};
2936} // end anonymous namespace
2937
Sebastian Redla19a67f2010-08-03 21:58:15 +00002938/// \brief Write ObjC data: selectors and the method pool.
Douglas Gregorc78d3462009-04-24 21:10:55 +00002939///
2940/// The method pool contains both instance and factory methods, stored
Sebastian Redla19a67f2010-08-03 21:58:15 +00002941/// in an on-disk hash table indexed by the selector. The hash table also
2942/// contains an empty entry for every other selector known to Sema.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002943void ASTWriter::WriteSelectors(Sema &SemaRef) {
Douglas Gregorc78d3462009-04-24 21:10:55 +00002944 using namespace llvm;
2945
Sebastian Redla19a67f2010-08-03 21:58:15 +00002946 // Do we have to do anything at all?
Sebastian Redl834bb972010-08-04 17:20:04 +00002947 if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
Sebastian Redla19a67f2010-08-03 21:58:15 +00002948 return;
Sebastian Redld95a56e2010-08-04 18:21:41 +00002949 unsigned NumTableEntries = 0;
Sebastian Redla19a67f2010-08-03 21:58:15 +00002950 // Create and write out the blob that contains selectors and the method pool.
Douglas Gregorc78d3462009-04-24 21:10:55 +00002951 {
Justin Bognerbb094f02014-04-18 19:57:06 +00002952 llvm::OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00002953 ASTMethodPoolTrait Trait(*this);
Mike Stump11289f42009-09-09 15:08:12 +00002954
Sebastian Redla19a67f2010-08-03 21:58:15 +00002955 // Create the on-disk hash table representation. We walk through every
2956 // selector we've seen and look it up in the method pool.
Sebastian Redld95a56e2010-08-04 18:21:41 +00002957 SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
Chandler Carruthacbbeb92015-03-27 00:47:43 +00002958 for (auto &SelectorAndID : SelectorIDs) {
2959 Selector S = SelectorAndID.first;
2960 SelectorID ID = SelectorAndID.second;
Sebastian Redla19a67f2010-08-03 21:58:15 +00002961 Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002962 ASTMethodPoolTrait::data_type Data = {
Chandler Carruthacbbeb92015-03-27 00:47:43 +00002963 ID,
Sebastian Redl834bb972010-08-04 17:20:04 +00002964 ObjCMethodList(),
2965 ObjCMethodList()
2966 };
2967 if (F != SemaRef.MethodPool.end()) {
2968 Data.Instance = F->second.first;
2969 Data.Factory = F->second.second;
2970 }
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002971 // Only write this selector if it's not in an existing AST or something
Sebastian Redld95a56e2010-08-04 18:21:41 +00002972 // changed.
Chandler Carruthacbbeb92015-03-27 00:47:43 +00002973 if (Chain && ID < FirstSelectorID) {
Sebastian Redld95a56e2010-08-04 18:21:41 +00002974 // Selector already exists. Did it change?
2975 bool changed = false;
Nico Weber2e0c8f72014-12-27 03:58:08 +00002976 for (ObjCMethodList *M = &Data.Instance;
2977 !changed && M && M->getMethod(); M = M->getNext()) {
2978 if (!M->getMethod()->isFromASTFile())
Sebastian Redld95a56e2010-08-04 18:21:41 +00002979 changed = true;
2980 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00002981 for (ObjCMethodList *M = &Data.Factory; !changed && M && M->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002982 M = M->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00002983 if (!M->getMethod()->isFromASTFile())
Sebastian Redld95a56e2010-08-04 18:21:41 +00002984 changed = true;
2985 }
2986 if (!changed)
2987 continue;
Nico Weber2e0c8f72014-12-27 03:58:08 +00002988 } else if (Data.Instance.getMethod() || Data.Factory.getMethod()) {
Sebastian Redl6e1a2a02010-08-04 21:22:45 +00002989 // A new method pool entry.
2990 ++NumTableEntries;
Sebastian Redld95a56e2010-08-04 18:21:41 +00002991 }
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00002992 Generator.insert(S, Data, Trait);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002993 }
2994
Douglas Gregorc78d3462009-04-24 21:10:55 +00002995 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002996 SmallString<4096> MethodPool;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002997 uint32_t BucketOffset;
2998 {
Justin Bognere1c147c2014-03-28 22:03:19 +00002999 using namespace llvm::support;
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003000 ASTMethodPoolTrait Trait(*this);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003001 llvm::raw_svector_ostream Out(MethodPool);
3002 // Make sure that no bucket is at offset 0
Justin Bognere1c147c2014-03-28 22:03:19 +00003003 endian::Writer<little>(Out).write<uint32_t>(0);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003004 BucketOffset = Generator.Emit(Out, Trait);
3005 }
3006
3007 // Create a blob abbreviation
3008 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00003009 Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
Douglas Gregorc78d3462009-04-24 21:10:55 +00003010 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor95c13f52009-04-25 17:48:32 +00003011 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorc78d3462009-04-24 21:10:55 +00003012 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3013 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
3014
Douglas Gregor95c13f52009-04-25 17:48:32 +00003015 // Write the method pool
Douglas Gregorc78d3462009-04-24 21:10:55 +00003016 RecordData Record;
Sebastian Redl539c5062010-08-18 23:57:32 +00003017 Record.push_back(METHOD_POOL);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003018 Record.push_back(BucketOffset);
Sebastian Redld95a56e2010-08-04 18:21:41 +00003019 Record.push_back(NumTableEntries);
Yaron Keren92e1b622015-03-18 10:17:07 +00003020 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool);
Douglas Gregor95c13f52009-04-25 17:48:32 +00003021
3022 // Create a blob abbreviation for the selector table offsets.
3023 Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00003024 Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
Douglas Gregord4c5ed02010-10-29 22:39:52 +00003025 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
Douglas Gregor8f364fb2011-08-03 23:28:44 +00003026 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
Douglas Gregor95c13f52009-04-25 17:48:32 +00003027 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3028 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
3029
3030 // Write the selector offsets table.
3031 Record.clear();
Sebastian Redl539c5062010-08-18 23:57:32 +00003032 Record.push_back(SELECTOR_OFFSETS);
Douglas Gregor95c13f52009-04-25 17:48:32 +00003033 Record.push_back(SelectorOffsets.size());
Douglas Gregor8f364fb2011-08-03 23:28:44 +00003034 Record.push_back(FirstSelectorID - NUM_PREDEF_SELECTOR_IDS);
Douglas Gregor95c13f52009-04-25 17:48:32 +00003035 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
Benjamin Kramerd47a12a2011-04-24 17:44:50 +00003036 data(SelectorOffsets));
Douglas Gregorc78d3462009-04-24 21:10:55 +00003037 }
3038}
3039
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003040/// \brief Write the selectors referenced in @selector expression into AST file.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00003041void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003042 using namespace llvm;
3043 if (SemaRef.ReferencedSelectors.empty())
3044 return;
Sebastian Redlada023c2010-08-04 20:40:17 +00003045
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003046 RecordData Record;
Sebastian Redlada023c2010-08-04 20:40:17 +00003047
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003048 // Note: this writes out all references even for a dependent AST. But it is
Sebastian Redl51c79d82010-08-04 22:21:29 +00003049 // very tricky to fix, and given that @selector shouldn't really appear in
3050 // headers, probably not worth it. It's not a correctness issue.
Chandler Carruth12c8f652015-03-27 00:55:05 +00003051 for (auto &SelectorAndLocation : SemaRef.ReferencedSelectors) {
3052 Selector Sel = SelectorAndLocation.first;
3053 SourceLocation Loc = SelectorAndLocation.second;
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003054 AddSelectorRef(Sel, Record);
3055 AddSourceLocation(Loc, Record);
3056 }
Sebastian Redl539c5062010-08-18 23:57:32 +00003057 Stream.EmitRecord(REFERENCED_SELECTOR_POOL, Record);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003058}
3059
Douglas Gregorc5046832009-04-27 18:38:38 +00003060//===----------------------------------------------------------------------===//
3061// Identifier Table Serialization
3062//===----------------------------------------------------------------------===//
3063
Richard Smithb3761912015-02-05 23:08:52 +00003064/// Determine the declaration that should be put into the name lookup table to
3065/// represent the given declaration in this module. This is usually D itself,
3066/// but if D was imported and merged into a local declaration, we want the most
3067/// recent local declaration instead. The chosen declaration will be the most
3068/// recent declaration in any module that imports this one.
3069static NamedDecl *getDeclForLocalLookup(const LangOptions &LangOpts,
3070 NamedDecl *D) {
3071 if (!LangOpts.Modules || !D->isFromASTFile())
3072 return D;
3073
3074 if (Decl *Redecl = D->getPreviousDecl()) {
3075 // For Redeclarable decls, a prior declaration might be local.
3076 for (; Redecl; Redecl = Redecl->getPreviousDecl()) {
3077 if (!Redecl->isFromASTFile())
3078 return cast<NamedDecl>(Redecl);
Richard Smithfe620d22015-03-05 23:24:12 +00003079 // If we find a decl from a (chained-)PCH stop since we won't find a
Richard Smithb3761912015-02-05 23:08:52 +00003080 // local one.
3081 if (D->getOwningModuleID() == 0)
3082 break;
3083 }
3084 } else if (Decl *First = D->getCanonicalDecl()) {
3085 // For Mergeable decls, the first decl might be local.
3086 if (!First->isFromASTFile())
3087 return cast<NamedDecl>(First);
3088 }
3089
3090 // All declarations are imported. Our most recent declaration will also be
3091 // the most recent one in anyone who imports us.
3092 return D;
3093}
3094
Douglas Gregorc78d3462009-04-24 21:10:55 +00003095namespace {
Richard Smithcf97cf62015-04-19 01:34:23 +00003096class ASTIdentifierTableTrait {
3097 ASTWriter &Writer;
3098 Preprocessor &PP;
3099 IdentifierResolver &IdResolver;
Richard Smithcf97cf62015-04-19 01:34:23 +00003100
3101 /// \brief Determines whether this is an "interesting" identifier that needs a
3102 /// full IdentifierInfo structure written into the hash table. Notably, this
3103 /// doesn't check whether the name has macros defined; use PublicMacroIterator
3104 /// to check that.
Richard Smithd7329392015-04-21 21:46:32 +00003105 bool isInterestingIdentifier(IdentifierInfo *II, uint64_t MacroOffset) {
3106 if (MacroOffset ||
3107 II->isPoisoned() ||
Richard Smithcf97cf62015-04-19 01:34:23 +00003108 II->isExtensionToken() ||
3109 II->getObjCOrBuiltinID() ||
3110 II->hasRevertedTokenIDToIdentifier() ||
3111 II->getFETokenInfo<void>())
3112 return true;
3113
3114 return false;
3115 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003116
Douglas Gregore84a9da2009-04-20 20:36:09 +00003117public:
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00003118 typedef IdentifierInfo* key_type;
Douglas Gregore84a9da2009-04-20 20:36:09 +00003119 typedef key_type key_type_ref;
Mike Stump11289f42009-09-09 15:08:12 +00003120
Sebastian Redl539c5062010-08-18 23:57:32 +00003121 typedef IdentID data_type;
Douglas Gregore84a9da2009-04-20 20:36:09 +00003122 typedef data_type data_type_ref;
Mike Stump11289f42009-09-09 15:08:12 +00003123
Justin Bogner25463f12014-04-18 20:27:24 +00003124 typedef unsigned hash_value_type;
3125 typedef unsigned offset_type;
3126
Richard Smithd7329392015-04-21 21:46:32 +00003127 ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
3128 IdentifierResolver &IdResolver)
3129 : Writer(Writer), PP(PP), IdResolver(IdResolver) {}
Douglas Gregore84a9da2009-04-20 20:36:09 +00003130
Justin Bogner25463f12014-04-18 20:27:24 +00003131 static hash_value_type ComputeHash(const IdentifierInfo* II) {
Daniel Dunbarf8502d52009-10-17 23:52:28 +00003132 return llvm::HashString(II->getName());
Douglas Gregore84a9da2009-04-20 20:36:09 +00003133 }
Mike Stump11289f42009-09-09 15:08:12 +00003134
3135 std::pair<unsigned,unsigned>
Douglas Gregor935bc7a22011-10-27 09:33:13 +00003136 EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003137 unsigned KeyLen = II->getLength() + 1;
Douglas Gregor1d583f22009-04-28 21:18:29 +00003138 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
Richard Smithd7329392015-04-21 21:46:32 +00003139 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3140 if (isInterestingIdentifier(II, MacroOffset)) {
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003141 DataLen += 2; // 2 bytes for builtin ID
3142 DataLen += 2; // 2 bytes for flags
Richard Smithd7329392015-04-21 21:46:32 +00003143 if (MacroOffset)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003144 DataLen += 4; // MacroDirectives offset.
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003145
Douglas Gregor935bc7a22011-10-27 09:33:13 +00003146 for (IdentifierResolver::iterator D = IdResolver.begin(II),
3147 DEnd = IdResolver.end();
Douglas Gregor1d583f22009-04-28 21:18:29 +00003148 D != DEnd; ++D)
Richard Smithdaa69e02014-07-25 04:40:03 +00003149 DataLen += 4;
Douglas Gregor1d583f22009-04-28 21:18:29 +00003150 }
Justin Bognere1c147c2014-03-28 22:03:19 +00003151 using namespace llvm::support;
3152 endian::Writer<little> LE(Out);
3153
Richard Smithdf8a8312015-03-13 04:05:01 +00003154 assert((uint16_t)DataLen == DataLen && (uint16_t)KeyLen == KeyLen);
Justin Bognere1c147c2014-03-28 22:03:19 +00003155 LE.write<uint16_t>(DataLen);
Douglas Gregorab4df582009-04-28 20:01:51 +00003156 // We emit the key length after the data length so that every
3157 // string is preceded by a 16-bit length. This matches the PTH
3158 // format for storing identifiers.
Justin Bognere1c147c2014-03-28 22:03:19 +00003159 LE.write<uint16_t>(KeyLen);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003160 return std::make_pair(KeyLen, DataLen);
3161 }
Mike Stump11289f42009-09-09 15:08:12 +00003162
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003163 void EmitKey(raw_ostream& Out, const IdentifierInfo* II,
Douglas Gregore84a9da2009-04-20 20:36:09 +00003164 unsigned KeyLen) {
3165 // Record the location of the key data. This is used when generating
3166 // the mapping from persistent IDs to strings.
3167 Writer.SetIdentifierOffset(II, Out.tell());
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003168 Out.write(II->getNameStart(), KeyLen);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003169 }
Mike Stump11289f42009-09-09 15:08:12 +00003170
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00003171 void EmitData(raw_ostream& Out, IdentifierInfo* II,
Sebastian Redl539c5062010-08-18 23:57:32 +00003172 IdentID ID, unsigned) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003173 using namespace llvm::support;
3174 endian::Writer<little> LE(Out);
Richard Smithcf97cf62015-04-19 01:34:23 +00003175
Richard Smithd7329392015-04-21 21:46:32 +00003176 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3177 if (!isInterestingIdentifier(II, MacroOffset)) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003178 LE.write<uint32_t>(ID << 1);
Douglas Gregor1d583f22009-04-28 21:18:29 +00003179 return;
3180 }
Douglas Gregorb9256522009-04-28 21:32:13 +00003181
Justin Bognere1c147c2014-03-28 22:03:19 +00003182 LE.write<uint32_t>((ID << 1) | 0x01);
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003183 uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID();
3184 assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader.");
Justin Bognere1c147c2014-03-28 22:03:19 +00003185 LE.write<uint16_t>(Bits);
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003186 Bits = 0;
Richard Smithd7329392015-04-21 21:46:32 +00003187 bool HadMacroDefinition = MacroOffset != 0;
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003188 Bits = (Bits << 1) | unsigned(HadMacroDefinition);
Daniel Dunbar91b640a2009-12-18 20:58:47 +00003189 Bits = (Bits << 1) | unsigned(II->isExtensionToken());
3190 Bits = (Bits << 1) | unsigned(II->isPoisoned());
Argyrios Kyrtzidis3084a612010-08-11 22:55:12 +00003191 Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
Daniel Dunbar91b640a2009-12-18 20:58:47 +00003192 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
Justin Bognere1c147c2014-03-28 22:03:19 +00003193 LE.write<uint16_t>(Bits);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003194
Richard Smithd7329392015-04-21 21:46:32 +00003195 if (HadMacroDefinition)
3196 LE.write<uint32_t>(MacroOffset);
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003197
Douglas Gregora868bbd2009-04-21 22:25:48 +00003198 // Emit the declaration IDs in reverse order, because the
3199 // IdentifierResolver provides the declarations as they would be
3200 // visible (e.g., the function "stat" would come before the struct
Richard Smithb3761912015-02-05 23:08:52 +00003201 // "stat"), but the ASTReader adds declarations to the end of the list
3202 // (so we need to see the struct "stat" before the function "stat").
Sebastian Redlff4a2952010-07-23 23:49:55 +00003203 // Only emit declarations that aren't from a chained PCH, though.
Richard Smithb3761912015-02-05 23:08:52 +00003204 SmallVector<NamedDecl *, 16> Decls(IdResolver.begin(II), IdResolver.end());
3205 for (SmallVectorImpl<NamedDecl *>::reverse_iterator D = Decls.rbegin(),
3206 DEnd = Decls.rend();
Douglas Gregore84a9da2009-04-20 20:36:09 +00003207 D != DEnd; ++D)
Richard Smithb3761912015-02-05 23:08:52 +00003208 LE.write<uint32_t>(
3209 Writer.getDeclID(getDeclForLocalLookup(PP.getLangOpts(), *D)));
Douglas Gregore84a9da2009-04-20 20:36:09 +00003210 }
3211};
3212} // end anonymous namespace
3213
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003214/// \brief Write the identifier table into the AST file.
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003215///
3216/// The identifier table consists of a blob containing string data
3217/// (the actual identifiers themselves) and a separate "offsets" index
3218/// that maps identifier IDs to locations within the blob.
Douglas Gregor935bc7a22011-10-27 09:33:13 +00003219void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
3220 IdentifierResolver &IdResolver,
3221 bool IsModule) {
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003222 using namespace llvm;
3223
3224 // Create and write out the blob that contains the identifier
3225 // strings.
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003226 {
Justin Bognerbb094f02014-04-18 19:57:06 +00003227 llvm::OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
Richard Smithd7329392015-04-21 21:46:32 +00003228 ASTIdentifierTableTrait Trait(*this, PP, IdResolver);
Mike Stump11289f42009-09-09 15:08:12 +00003229
Douglas Gregore6648fb2009-04-28 20:33:11 +00003230 // Look for any identifiers that were named while processing the
3231 // headers, but are otherwise not needed. We add these to the hash
3232 // table to enable checking of the predefines buffer in the case
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003233 // where the user adds new macro definitions when building the AST
Douglas Gregore6648fb2009-04-28 20:33:11 +00003234 // file.
Chandler Carruth8440c982015-03-26 23:54:15 +00003235 SmallVector<const IdentifierInfo *, 128> IIs;
Douglas Gregore6648fb2009-04-28 20:33:11 +00003236 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
3237 IDEnd = PP.getIdentifierTable().end();
3238 ID != IDEnd; ++ID)
Chandler Carruth8440c982015-03-26 23:54:15 +00003239 IIs.push_back(ID->second);
3240 // Sort the identifiers lexicographically before getting them references so
3241 // that their order is stable.
3242 std::sort(IIs.begin(), IIs.end(), llvm::less_ptr<IdentifierInfo>());
3243 for (const IdentifierInfo *II : IIs)
3244 getIdentifierRef(II);
Douglas Gregore6648fb2009-04-28 20:33:11 +00003245
Sebastian Redlff4a2952010-07-23 23:49:55 +00003246 // Create the on-disk hash table representation. We only store offsets
3247 // for identifiers that appear here for the first time.
3248 IdentifierOffsets.resize(NextIdentID - FirstIdentID);
Chandler Carruth885e78c2015-03-24 21:18:10 +00003249 for (auto IdentIDPair : IdentifierIDs) {
3250 IdentifierInfo *II = const_cast<IdentifierInfo *>(IdentIDPair.first);
3251 IdentID ID = IdentIDPair.second;
3252 assert(II && "NULL identifier in identifier table");
3253 if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization())
3254 Generator.insert(II, ID, Trait);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003255 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003256
Douglas Gregore84a9da2009-04-20 20:36:09 +00003257 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003258 SmallString<4096> IdentifierTable;
Douglas Gregora868bbd2009-04-21 22:25:48 +00003259 uint32_t BucketOffset;
Douglas Gregore84a9da2009-04-20 20:36:09 +00003260 {
Justin Bognere1c147c2014-03-28 22:03:19 +00003261 using namespace llvm::support;
Douglas Gregore84a9da2009-04-20 20:36:09 +00003262 llvm::raw_svector_ostream Out(IdentifierTable);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003263 // Make sure that no bucket is at offset 0
Justin Bognere1c147c2014-03-28 22:03:19 +00003264 endian::Writer<little>(Out).write<uint32_t>(0);
Douglas Gregora868bbd2009-04-21 22:25:48 +00003265 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003266 }
3267
3268 // Create a blob abbreviation
3269 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00003270 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
Douglas Gregora868bbd2009-04-21 22:25:48 +00003271 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregore84a9da2009-04-20 20:36:09 +00003272 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
Douglas Gregor8f45df52009-04-16 22:23:12 +00003273 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003274
3275 // Write the identifier table
3276 RecordData Record;
Sebastian Redl539c5062010-08-18 23:57:32 +00003277 Record.push_back(IDENTIFIER_TABLE);
Douglas Gregora868bbd2009-04-21 22:25:48 +00003278 Record.push_back(BucketOffset);
Yaron Keren92e1b622015-03-18 10:17:07 +00003279 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003280 }
3281
3282 // Write the offsets table for identifier IDs.
Douglas Gregor0e149972009-04-25 19:10:14 +00003283 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00003284 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
Douglas Gregor0e149972009-04-25 19:10:14 +00003285 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
Douglas Gregor1ab036c2011-08-03 21:49:18 +00003286 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
Douglas Gregor0e149972009-04-25 19:10:14 +00003287 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3288 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
3289
Douglas Gregor8d7edce2013-02-08 21:30:59 +00003290#ifndef NDEBUG
3291 for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I)
3292 assert(IdentifierOffsets[I] && "Missing identifier offset?");
3293#endif
3294
Douglas Gregor0e149972009-04-25 19:10:14 +00003295 RecordData Record;
Sebastian Redl539c5062010-08-18 23:57:32 +00003296 Record.push_back(IDENTIFIER_OFFSET);
Douglas Gregor0e149972009-04-25 19:10:14 +00003297 Record.push_back(IdentifierOffsets.size());
Douglas Gregor1ab036c2011-08-03 21:49:18 +00003298 Record.push_back(FirstIdentID - NUM_PREDEF_IDENT_IDS);
Douglas Gregor0e149972009-04-25 19:10:14 +00003299 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
Benjamin Kramerd47a12a2011-04-24 17:44:50 +00003300 data(IdentifierOffsets));
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003301}
3302
Douglas Gregorc5046832009-04-27 18:38:38 +00003303//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003304// DeclContext's Name Lookup Table Serialization
3305//===----------------------------------------------------------------------===//
3306
3307namespace {
3308// Trait used for the on-disk hash table used in the method pool.
3309class ASTDeclContextNameLookupTrait {
3310 ASTWriter &Writer;
3311
3312public:
3313 typedef DeclarationName key_type;
3314 typedef key_type key_type_ref;
3315
3316 typedef DeclContext::lookup_result data_type;
3317 typedef const data_type& data_type_ref;
3318
Justin Bogner25463f12014-04-18 20:27:24 +00003319 typedef unsigned hash_value_type;
3320 typedef unsigned offset_type;
3321
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003322 explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) { }
3323
Justin Bogner25463f12014-04-18 20:27:24 +00003324 hash_value_type ComputeHash(DeclarationName Name) {
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003325 llvm::FoldingSetNodeID ID;
3326 ID.AddInteger(Name.getNameKind());
3327
3328 switch (Name.getNameKind()) {
3329 case DeclarationName::Identifier:
3330 ID.AddString(Name.getAsIdentifierInfo()->getName());
3331 break;
3332 case DeclarationName::ObjCZeroArgSelector:
3333 case DeclarationName::ObjCOneArgSelector:
3334 case DeclarationName::ObjCMultiArgSelector:
3335 ID.AddInteger(serialization::ComputeHash(Name.getObjCSelector()));
3336 break;
3337 case DeclarationName::CXXConstructorName:
3338 case DeclarationName::CXXDestructorName:
3339 case DeclarationName::CXXConversionFunctionName:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003340 break;
3341 case DeclarationName::CXXOperatorName:
3342 ID.AddInteger(Name.getCXXOverloadedOperator());
3343 break;
3344 case DeclarationName::CXXLiteralOperatorName:
3345 ID.AddString(Name.getCXXLiteralIdentifier()->getName());
3346 case DeclarationName::CXXUsingDirective:
3347 break;
3348 }
3349
3350 return ID.ComputeHash();
3351 }
3352
3353 std::pair<unsigned,unsigned>
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003354 EmitKeyDataLength(raw_ostream& Out, DeclarationName Name,
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003355 data_type_ref Lookup) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003356 using namespace llvm::support;
3357 endian::Writer<little> LE(Out);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003358 unsigned KeyLen = 1;
3359 switch (Name.getNameKind()) {
3360 case DeclarationName::Identifier:
3361 case DeclarationName::ObjCZeroArgSelector:
3362 case DeclarationName::ObjCOneArgSelector:
3363 case DeclarationName::ObjCMultiArgSelector:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003364 case DeclarationName::CXXLiteralOperatorName:
3365 KeyLen += 4;
3366 break;
3367 case DeclarationName::CXXOperatorName:
3368 KeyLen += 1;
3369 break;
Douglas Gregor3b65ed02011-08-02 18:32:54 +00003370 case DeclarationName::CXXConstructorName:
3371 case DeclarationName::CXXDestructorName:
3372 case DeclarationName::CXXConversionFunctionName:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003373 case DeclarationName::CXXUsingDirective:
3374 break;
3375 }
Justin Bognere1c147c2014-03-28 22:03:19 +00003376 LE.write<uint16_t>(KeyLen);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003377
3378 // 2 bytes for num of decls and 4 for each DeclID.
David Blaikieff7d47a2012-12-19 00:45:41 +00003379 unsigned DataLen = 2 + 4 * Lookup.size();
Justin Bognere1c147c2014-03-28 22:03:19 +00003380 LE.write<uint16_t>(DataLen);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003381
3382 return std::make_pair(KeyLen, DataLen);
3383 }
3384
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003385 void EmitKey(raw_ostream& Out, DeclarationName Name, unsigned) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003386 using namespace llvm::support;
3387 endian::Writer<little> LE(Out);
3388 LE.write<uint8_t>(Name.getNameKind());
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003389 switch (Name.getNameKind()) {
3390 case DeclarationName::Identifier:
Justin Bognere1c147c2014-03-28 22:03:19 +00003391 LE.write<uint32_t>(Writer.getIdentifierRef(Name.getAsIdentifierInfo()));
Benjamin Kramer53750b12012-09-19 13:40:40 +00003392 return;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003393 case DeclarationName::ObjCZeroArgSelector:
3394 case DeclarationName::ObjCOneArgSelector:
3395 case DeclarationName::ObjCMultiArgSelector:
Justin Bognere1c147c2014-03-28 22:03:19 +00003396 LE.write<uint32_t>(Writer.getSelectorRef(Name.getObjCSelector()));
Benjamin Kramer53750b12012-09-19 13:40:40 +00003397 return;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003398 case DeclarationName::CXXOperatorName:
Benjamin Kramer53750b12012-09-19 13:40:40 +00003399 assert(Name.getCXXOverloadedOperator() < NUM_OVERLOADED_OPERATORS &&
3400 "Invalid operator?");
Justin Bognere1c147c2014-03-28 22:03:19 +00003401 LE.write<uint8_t>(Name.getCXXOverloadedOperator());
Benjamin Kramer53750b12012-09-19 13:40:40 +00003402 return;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003403 case DeclarationName::CXXLiteralOperatorName:
Justin Bognere1c147c2014-03-28 22:03:19 +00003404 LE.write<uint32_t>(Writer.getIdentifierRef(Name.getCXXLiteralIdentifier()));
Benjamin Kramer53750b12012-09-19 13:40:40 +00003405 return;
Douglas Gregor3b65ed02011-08-02 18:32:54 +00003406 case DeclarationName::CXXConstructorName:
3407 case DeclarationName::CXXDestructorName:
3408 case DeclarationName::CXXConversionFunctionName:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003409 case DeclarationName::CXXUsingDirective:
Benjamin Kramer53750b12012-09-19 13:40:40 +00003410 return;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003411 }
Benjamin Kramer53750b12012-09-19 13:40:40 +00003412
3413 llvm_unreachable("Invalid name kind?");
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003414 }
3415
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003416 void EmitData(raw_ostream& Out, key_type_ref,
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003417 data_type Lookup, unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003418 using namespace llvm::support;
3419 endian::Writer<little> LE(Out);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003420 uint64_t Start = Out.tell(); (void)Start;
Justin Bognere1c147c2014-03-28 22:03:19 +00003421 LE.write<uint16_t>(Lookup.size());
David Blaikieff7d47a2012-12-19 00:45:41 +00003422 for (DeclContext::lookup_iterator I = Lookup.begin(), E = Lookup.end();
3423 I != E; ++I)
Richard Smithb3761912015-02-05 23:08:52 +00003424 LE.write<uint32_t>(
3425 Writer.GetDeclRef(getDeclForLocalLookup(Writer.getLangOpts(), *I)));
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003426
3427 assert(Out.tell() - Start == DataLen && "Data length is wrong");
3428 }
3429};
3430} // end anonymous namespace
3431
Chandler Carruthe972c362015-03-26 03:11:40 +00003432bool ASTWriter::isLookupResultExternal(StoredDeclsList &Result,
3433 DeclContext *DC) {
3434 return Result.hasExternalDecls() && DC->NeedToReconcileExternalVisibleStorage;
3435}
3436
3437bool ASTWriter::isLookupResultEntirelyExternal(StoredDeclsList &Result,
3438 DeclContext *DC) {
3439 for (auto *D : Result.getLookupResult())
3440 if (!getDeclForLocalLookup(getLangOpts(), D)->isFromASTFile())
3441 return false;
3442
3443 return true;
3444}
3445
Richard Smithcd45dbc2014-04-19 03:48:30 +00003446uint32_t
Chandler Carruthe972c362015-03-26 03:11:40 +00003447ASTWriter::GenerateNameLookupTable(const DeclContext *ConstDC,
Richard Smithcd45dbc2014-04-19 03:48:30 +00003448 llvm::SmallVectorImpl<char> &LookupTable) {
Chandler Carruthe972c362015-03-26 03:11:40 +00003449 assert(!ConstDC->HasLazyLocalLexicalLookups &&
3450 !ConstDC->HasLazyExternalLexicalLookups &&
Richard Smith9e2341d2015-03-23 03:25:59 +00003451 "must call buildLookups first");
Richard Smithcd45dbc2014-04-19 03:48:30 +00003452
Chandler Carruthe972c362015-03-26 03:11:40 +00003453 // FIXME: We need to build the lookups table, which is logically const.
3454 DeclContext *DC = const_cast<DeclContext*>(ConstDC);
3455 assert(DC == DC->getPrimaryContext() && "only primary DC has lookup table");
3456
3457 // Create the on-disk hash table representation.
Richard Smithcd45dbc2014-04-19 03:48:30 +00003458 llvm::OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait>
3459 Generator;
3460 ASTDeclContextNameLookupTrait Trait(*this);
3461
Chandler Carruthe972c362015-03-26 03:11:40 +00003462 // The first step is to collect the declaration names which we need to
3463 // serialize into the name lookup table, and to collect them in a stable
3464 // order.
3465 SmallVector<DeclarationName, 16> Names;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003466
Chandler Carruthe972c362015-03-26 03:11:40 +00003467 // We also build up small sets of the constructor and conversion function
3468 // names which are visible.
3469 llvm::SmallSet<DeclarationName, 8> ConstructorNameSet, ConversionNameSet;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003470
Chandler Carruthe972c362015-03-26 03:11:40 +00003471 for (auto &Lookup : *DC->buildLookup()) {
3472 auto &Name = Lookup.first;
3473 auto &Result = Lookup.second;
3474
3475 // If there are no local declarations in our lookup result, we don't
3476 // need to write an entry for the name at all unless we're rewriting
3477 // the decl context. If we can't write out a lookup set without
3478 // performing more deserialization, just skip this entry.
3479 if (isLookupResultExternal(Result, DC) && !isRewritten(cast<Decl>(DC)) &&
3480 isLookupResultEntirelyExternal(Result, DC))
3481 continue;
3482
3483 // We also skip empty results. If any of the results could be external and
3484 // the currently available results are empty, then all of the results are
3485 // external and we skip it above. So the only way we get here with an empty
3486 // results is when no results could have been external *and* we have
3487 // external results.
3488 //
3489 // FIXME: While we might want to start emitting on-disk entries for negative
3490 // lookups into a decl context as an optimization, today we *have* to skip
3491 // them because there are names with empty lookup results in decl contexts
3492 // which we can't emit in any stable ordering: we lookup constructors and
3493 // conversion functions in the enclosing namespace scope creating empty
3494 // results for them. This in almost certainly a bug in Clang's name lookup,
3495 // but that is likely to be hard or impossible to fix and so we tolerate it
3496 // here by omitting lookups with empty results.
3497 if (Lookup.second.getLookupResult().empty())
3498 continue;
3499
3500 switch (Lookup.first.getNameKind()) {
3501 default:
3502 Names.push_back(Lookup.first);
3503 break;
3504
Richard Smithcd45dbc2014-04-19 03:48:30 +00003505 case DeclarationName::CXXConstructorName:
Chandler Carruthe972c362015-03-26 03:11:40 +00003506 assert(isa<CXXRecordDecl>(DC) &&
3507 "Cannot have a constructor name outside of a class!");
3508 ConstructorNameSet.insert(Name);
3509 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003510
3511 case DeclarationName::CXXConversionFunctionName:
Chandler Carruthe972c362015-03-26 03:11:40 +00003512 assert(isa<CXXRecordDecl>(DC) &&
3513 "Cannot have a conversion function name outside of a class!");
3514 ConversionNameSet.insert(Name);
Rafael Espindolac606b3e2015-03-25 04:43:15 +00003515 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003516 }
Chandler Carruth75c9f132015-03-25 00:34:51 +00003517 }
Chandler Carruth75c9f132015-03-25 00:34:51 +00003518
Chandler Carruthe972c362015-03-26 03:11:40 +00003519 // Sort the names into a stable order.
3520 std::sort(Names.begin(), Names.end());
3521
Chandler Carruthffbf7052015-03-26 22:27:09 +00003522 if (auto *D = dyn_cast<CXXRecordDecl>(DC)) {
Chandler Carruthe972c362015-03-26 03:11:40 +00003523 // We need to establish an ordering of constructor and conversion function
Chandler Carruthffbf7052015-03-26 22:27:09 +00003524 // names, and they don't have an intrinsic ordering.
Chandler Carruthe972c362015-03-26 03:11:40 +00003525
Chandler Carruthffbf7052015-03-26 22:27:09 +00003526 // First we try the easy case by forming the current context's constructor
3527 // name and adding that name first. This is a very useful optimization to
3528 // avoid walking the lexical declarations in many cases, and it also
3529 // handles the only case where a constructor name can come from some other
3530 // lexical context -- when that name is an implicit constructor merged from
3531 // another declaration in the redecl chain. Any non-implicit constructor or
3532 // conversion function which doesn't occur in all the lexical contexts
3533 // would be an ODR violation.
3534 auto ImplicitCtorName = Context->DeclarationNames.getCXXConstructorName(
3535 Context->getCanonicalType(Context->getRecordType(D)));
3536 if (ConstructorNameSet.erase(ImplicitCtorName))
3537 Names.push_back(ImplicitCtorName);
Chandler Carruthe972c362015-03-26 03:11:40 +00003538
Chandler Carruthffbf7052015-03-26 22:27:09 +00003539 // If we still have constructors or conversion functions, we walk all the
3540 // names in the decl and add the constructors and conversion functions
3541 // which are visible in the order they lexically occur within the context.
3542 if (!ConstructorNameSet.empty() || !ConversionNameSet.empty())
3543 for (Decl *ChildD : cast<CXXRecordDecl>(DC)->decls())
3544 if (auto *ChildND = dyn_cast<NamedDecl>(ChildD)) {
3545 auto Name = ChildND->getDeclName();
3546 switch (Name.getNameKind()) {
3547 default:
3548 continue;
3549
3550 case DeclarationName::CXXConstructorName:
3551 if (ConstructorNameSet.erase(Name))
3552 Names.push_back(Name);
3553 break;
3554
3555 case DeclarationName::CXXConversionFunctionName:
3556 if (ConversionNameSet.erase(Name))
3557 Names.push_back(Name);
3558 break;
3559 }
3560
3561 if (ConstructorNameSet.empty() && ConversionNameSet.empty())
3562 break;
Chandler Carruthe972c362015-03-26 03:11:40 +00003563 }
3564
Chandler Carruthe972c362015-03-26 03:11:40 +00003565 assert(ConstructorNameSet.empty() && "Failed to find all of the visible "
3566 "constructors by walking all the "
3567 "lexical members of the context.");
3568 assert(ConversionNameSet.empty() && "Failed to find all of the visible "
3569 "conversion functions by walking all "
3570 "the lexical members of the context.");
Richard Smith961eae52014-03-25 01:14:22 +00003571 }
3572
Chandler Carruthe972c362015-03-26 03:11:40 +00003573 // Next we need to do a lookup with each name into this decl context to fully
3574 // populate any results from external sources. We don't actually use the
3575 // results of these lookups because we only want to use the results after all
3576 // results have been loaded and the pointers into them will be stable.
3577 for (auto &Name : Names)
3578 DC->lookup(Name);
3579
3580 // Now we need to insert the results for each name into the hash table. For
3581 // constructor names and conversion function names, we actually need to merge
3582 // all of the results for them into one list of results each and insert
3583 // those.
3584 SmallVector<NamedDecl *, 8> ConstructorDecls;
3585 SmallVector<NamedDecl *, 8> ConversionDecls;
3586
3587 // Now loop over the names, either inserting them or appending for the two
3588 // special cases.
3589 for (auto &Name : Names) {
3590 DeclContext::lookup_result Result = DC->noload_lookup(Name);
3591
3592 switch (Name.getNameKind()) {
3593 default:
3594 Generator.insert(Name, Result, Trait);
3595 break;
3596
3597 case DeclarationName::CXXConstructorName:
3598 ConstructorDecls.append(Result.begin(), Result.end());
3599 break;
3600
3601 case DeclarationName::CXXConversionFunctionName:
3602 ConversionDecls.append(Result.begin(), Result.end());
3603 break;
3604 }
3605 }
3606
3607 // Handle our two special cases if we ended up having any. We arbitrarily use
3608 // the first declaration's name here because the name itself isn't part of
3609 // the key, only the kind of name is used.
3610 if (!ConstructorDecls.empty())
3611 Generator.insert(ConstructorDecls.front()->getDeclName(),
3612 DeclContext::lookup_result(ConstructorDecls), Trait);
3613 if (!ConversionDecls.empty())
3614 Generator.insert(ConversionDecls.front()->getDeclName(),
3615 DeclContext::lookup_result(ConversionDecls), Trait);
3616
Richard Smith961eae52014-03-25 01:14:22 +00003617 // Create the on-disk hash table in a buffer.
3618 llvm::raw_svector_ostream Out(LookupTable);
3619 // Make sure that no bucket is at offset 0
Justin Bognere1c147c2014-03-28 22:03:19 +00003620 using namespace llvm::support;
3621 endian::Writer<little>(Out).write<uint32_t>(0);
Richard Smith961eae52014-03-25 01:14:22 +00003622 return Generator.Emit(Out, Trait);
3623}
3624
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003625/// \brief Write the block containing all of the declaration IDs
3626/// visible from the given DeclContext.
3627///
3628/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
Sebastian Redla4071b42010-08-24 00:50:09 +00003629/// bitstream, or 0 if no block was written.
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003630uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
3631 DeclContext *DC) {
3632 if (DC->getPrimaryContext() != DC)
3633 return 0;
3634
Chandler Carruthe972c362015-03-26 03:11:40 +00003635 // Skip contexts which don't support name lookup.
3636 if (!DC->isLookupContext())
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003637 return 0;
3638
3639 // If not in C++, we perform name lookup for the translation unit via the
3640 // IdentifierInfo chains, don't bother to build a visible-declarations table.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003641 if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003642 return 0;
3643
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003644 // Serialize the contents of the mapping used for lookup. Note that,
3645 // although we have two very different code paths, the serialized
3646 // representation is the same for both cases: a declaration name,
3647 // followed by a size, followed by references to the visible
3648 // declarations that have that name.
3649 uint64_t Offset = Stream.GetCurrentBitNo();
Richard Smithf634c902012-03-16 06:12:59 +00003650 StoredDeclsMap *Map = DC->buildLookup();
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003651 if (!Map || Map->empty())
3652 return 0;
3653
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003654 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003655 SmallString<4096> LookupTable;
Richard Smith961eae52014-03-25 01:14:22 +00003656 uint32_t BucketOffset = GenerateNameLookupTable(DC, LookupTable);
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003657
3658 // Write the lookup table
3659 RecordData Record;
3660 Record.push_back(DECL_CONTEXT_VISIBLE);
3661 Record.push_back(BucketOffset);
3662 Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
Yaron Keren92e1b622015-03-18 10:17:07 +00003663 LookupTable);
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003664 ++NumVisibleDeclContexts;
3665 return Offset;
3666}
3667
Sebastian Redla4071b42010-08-24 00:50:09 +00003668/// \brief Write an UPDATE_VISIBLE block for the given context.
3669///
3670/// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
3671/// DeclContext in a dependent AST file. As such, they only exist for the TU
Richard Smithf634c902012-03-16 06:12:59 +00003672/// (in C++), for namespaces, and for classes with forward-declared unscoped
3673/// enumeration members (in C++11).
Sebastian Redla4071b42010-08-24 00:50:09 +00003674void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
Richard Smith961eae52014-03-25 01:14:22 +00003675 StoredDeclsMap *Map = DC->getLookupPtr();
Sebastian Redla4071b42010-08-24 00:50:09 +00003676 if (!Map || Map->empty())
3677 return;
3678
Sebastian Redla4071b42010-08-24 00:50:09 +00003679 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003680 SmallString<4096> LookupTable;
Richard Smith961eae52014-03-25 01:14:22 +00003681 uint32_t BucketOffset = GenerateNameLookupTable(DC, LookupTable);
Sebastian Redla4071b42010-08-24 00:50:09 +00003682
3683 // Write the lookup table
3684 RecordData Record;
3685 Record.push_back(UPDATE_VISIBLE);
3686 Record.push_back(getDeclID(cast<Decl>(DC)));
3687 Record.push_back(BucketOffset);
Yaron Keren92e1b622015-03-18 10:17:07 +00003688 Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable);
Sebastian Redla4071b42010-08-24 00:50:09 +00003689}
3690
Peter Collingbourne5df20e02011-02-15 19:46:30 +00003691/// \brief Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
3692void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) {
3693 RecordData Record;
3694 Record.push_back(Opts.fp_contract);
3695 Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
3696}
3697
3698/// \brief Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
3699void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003700 if (!SemaRef.Context.getLangOpts().OpenCL)
Peter Collingbourne5df20e02011-02-15 19:46:30 +00003701 return;
3702
3703 const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
3704 RecordData Record;
3705#define OPENCLEXT(nm) Record.push_back(Opts.nm);
3706#include "clang/Basic/OpenCLExtensions.def"
3707 Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
3708}
3709
Douglas Gregor358cd442012-01-15 16:58:34 +00003710void ASTWriter::WriteRedeclarations() {
3711 RecordData LocalRedeclChains;
3712 SmallVector<serialization::LocalRedeclarationsInfo, 2> LocalRedeclsMap;
3713
3714 for (unsigned I = 0, N = Redeclarations.size(); I != N; ++I) {
3715 Decl *First = Redeclarations[I];
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003716 assert(First->isFirstDecl() && "Not the first declaration?");
Douglas Gregor358cd442012-01-15 16:58:34 +00003717
3718 Decl *MostRecent = First->getMostRecentDecl();
3719
3720 // If we only have a single declaration, there is no point in storing
3721 // a redeclaration chain.
3722 if (First == MostRecent)
3723 continue;
3724
3725 unsigned Offset = LocalRedeclChains.size();
3726 unsigned Size = 0;
3727 LocalRedeclChains.push_back(0); // Placeholder for the size.
3728
3729 // Collect the set of local redeclarations of this declaration.
Douglas Gregor6168bd22013-02-18 15:53:43 +00003730 for (Decl *Prev = MostRecent; Prev != First;
Douglas Gregor358cd442012-01-15 16:58:34 +00003731 Prev = Prev->getPreviousDecl()) {
3732 if (!Prev->isFromASTFile()) {
3733 AddDeclRef(Prev, LocalRedeclChains);
3734 ++Size;
3735 }
3736 }
Douglas Gregor6168bd22013-02-18 15:53:43 +00003737
Douglas Gregor358cd442012-01-15 16:58:34 +00003738 LocalRedeclChains[Offset] = Size;
3739
3740 // Reverse the set of local redeclarations, so that we store them in
3741 // order (since we found them in reverse order).
3742 std::reverse(LocalRedeclChains.end() - Size, LocalRedeclChains.end());
3743
Douglas Gregor6168bd22013-02-18 15:53:43 +00003744 // Add the mapping from the first ID from the AST to the set of local
3745 // declarations.
Douglas Gregor358cd442012-01-15 16:58:34 +00003746 LocalRedeclarationsInfo Info = { getDeclID(First), Offset };
3747 LocalRedeclsMap.push_back(Info);
3748
3749 assert(N == Redeclarations.size() &&
3750 "Deserialized a declaration we shouldn't have");
3751 }
3752
3753 if (LocalRedeclChains.empty())
3754 return;
3755
3756 // Sort the local redeclarations map by the first declaration ID,
3757 // since the reader will be performing binary searches on this information.
3758 llvm::array_pod_sort(LocalRedeclsMap.begin(), LocalRedeclsMap.end());
3759
3760 // Emit the local redeclarations map.
3761 using namespace llvm;
3762 llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
3763 Abbrev->Add(BitCodeAbbrevOp(LOCAL_REDECLARATIONS_MAP));
3764 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
3765 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3766 unsigned AbbrevID = Stream.EmitAbbrev(Abbrev);
3767
3768 RecordData Record;
3769 Record.push_back(LOCAL_REDECLARATIONS_MAP);
3770 Record.push_back(LocalRedeclsMap.size());
3771 Stream.EmitRecordWithBlob(AbbrevID, Record,
3772 reinterpret_cast<char*>(LocalRedeclsMap.data()),
3773 LocalRedeclsMap.size() * sizeof(LocalRedeclarationsInfo));
3774
3775 // Emit the redeclaration chains.
3776 Stream.EmitRecord(LOCAL_REDECLARATIONS, LocalRedeclChains);
3777}
3778
Douglas Gregor404cdde2012-01-27 01:47:08 +00003779void ASTWriter::WriteObjCCategories() {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003780 SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
Douglas Gregor404cdde2012-01-27 01:47:08 +00003781 RecordData Categories;
3782
3783 for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
3784 unsigned Size = 0;
3785 unsigned StartIndex = Categories.size();
3786
3787 ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
3788
3789 // Allocate space for the size.
3790 Categories.push_back(0);
3791
3792 // Add the categories.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003793 for (ObjCInterfaceDecl::known_categories_iterator
3794 Cat = Class->known_categories_begin(),
3795 CatEnd = Class->known_categories_end();
3796 Cat != CatEnd; ++Cat, ++Size) {
3797 assert(getDeclID(*Cat) != 0 && "Bogus category");
3798 AddDeclRef(*Cat, Categories);
Douglas Gregor404cdde2012-01-27 01:47:08 +00003799 }
3800
3801 // Update the size.
3802 Categories[StartIndex] = Size;
3803
3804 // Record this interface -> category map.
3805 ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
3806 CategoriesMap.push_back(CatInfo);
3807 }
3808
3809 // Sort the categories map by the definition ID, since the reader will be
3810 // performing binary searches on this information.
3811 llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
3812
3813 // Emit the categories map.
3814 using namespace llvm;
3815 llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
3816 Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
3817 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
3818 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3819 unsigned AbbrevID = Stream.EmitAbbrev(Abbrev);
3820
3821 RecordData Record;
3822 Record.push_back(OBJC_CATEGORIES_MAP);
3823 Record.push_back(CategoriesMap.size());
3824 Stream.EmitRecordWithBlob(AbbrevID, Record,
3825 reinterpret_cast<char*>(CategoriesMap.data()),
3826 CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
3827
3828 // Emit the category lists.
3829 Stream.EmitRecord(OBJC_CATEGORIES, Categories);
3830}
3831
Richard Smithe40f2ba2013-08-07 21:41:30 +00003832void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) {
3833 Sema::LateParsedTemplateMapT &LPTMap = SemaRef.LateParsedTemplateMap;
3834
3835 if (LPTMap.empty())
3836 return;
3837
3838 RecordData Record;
Chandler Carruth52cee4d2015-03-26 09:08:15 +00003839 for (auto LPTMapEntry : LPTMap) {
3840 const FunctionDecl *FD = LPTMapEntry.first;
3841 LateParsedTemplate *LPT = LPTMapEntry.second;
3842 AddDeclRef(FD, Record);
Richard Smithe40f2ba2013-08-07 21:41:30 +00003843 AddDeclRef(LPT->D, Record);
3844 Record.push_back(LPT->Toks.size());
3845
3846 for (CachedTokens::iterator TokIt = LPT->Toks.begin(),
3847 TokEnd = LPT->Toks.end();
3848 TokIt != TokEnd; ++TokIt) {
3849 AddToken(*TokIt, Record);
3850 }
3851 }
3852 Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record);
3853}
3854
Dario Domizioli13a0a382014-05-23 12:13:25 +00003855/// \brief Write the state of 'pragma clang optimize' at the end of the module.
3856void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) {
3857 RecordData Record;
3858 SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation();
3859 AddSourceLocation(PragmaLoc, Record);
3860 Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record);
3861}
3862
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003863//===----------------------------------------------------------------------===//
Douglas Gregorc5046832009-04-27 18:38:38 +00003864// General Serialization Routines
3865//===----------------------------------------------------------------------===//
3866
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00003867/// \brief Write a record containing the given attributes.
Alexander Kornienko20f6fc62012-07-09 10:04:07 +00003868void ASTWriter::WriteAttributes(ArrayRef<const Attr*> Attrs,
3869 RecordDataImpl &Record) {
Argyrios Kyrtzidis9beef8e2010-10-18 19:20:11 +00003870 Record.push_back(Attrs.size());
Alexander Kornienko20f6fc62012-07-09 10:04:07 +00003871 for (ArrayRef<const Attr *>::iterator i = Attrs.begin(),
3872 e = Attrs.end(); i != e; ++i){
3873 const Attr *A = *i;
Alexis Huntdcfba7b2010-08-18 23:23:40 +00003874 Record.push_back(A->getKind()); // FIXME: stable encoding, target attrs
Argyrios Kyrtzidis309b4c42011-09-13 16:05:58 +00003875 AddSourceRange(A->getRange(), Record);
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00003876
Alexis Huntdcfba7b2010-08-18 23:23:40 +00003877#include "clang/Serialization/AttrPCHWrite.inc"
Daniel Dunbarfc6507e2010-05-27 02:25:39 +00003878
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00003879 }
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00003880}
3881
John McCallf413f5e2013-05-03 00:10:13 +00003882void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) {
3883 AddSourceLocation(Tok.getLocation(), Record);
3884 Record.push_back(Tok.getLength());
3885
3886 // FIXME: When reading literal tokens, reconstruct the literal pointer
3887 // if it is needed.
3888 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
3889 // FIXME: Should translate token kind to a stable encoding.
3890 Record.push_back(Tok.getKind());
3891 // FIXME: Should translate token flags to a stable encoding.
3892 Record.push_back(Tok.getFlags());
3893}
3894
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003895void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00003896 Record.push_back(Str.size());
3897 Record.insert(Record.end(), Str.begin(), Str.end());
3898}
3899
Richard Smith7ed1bc92014-12-05 22:42:13 +00003900bool ASTWriter::PreparePathForOutput(SmallVectorImpl<char> &Path) {
Richard Smith54cc3c22014-12-11 20:50:24 +00003901 assert(Context && "should have context when outputting path");
Richard Smith7ed1bc92014-12-05 22:42:13 +00003902
Richard Smith54cc3c22014-12-11 20:50:24 +00003903 bool Changed =
3904 cleanPathForOutput(Context->getSourceManager().getFileManager(), Path);
Richard Smith7ed1bc92014-12-05 22:42:13 +00003905
3906 // Remove a prefix to make the path relative, if relevant.
3907 const char *PathBegin = Path.data();
3908 const char *PathPtr =
3909 adjustFilenameForRelocatableAST(PathBegin, BaseDirectory);
3910 if (PathPtr != PathBegin) {
3911 Path.erase(Path.begin(), Path.begin() + (PathPtr - PathBegin));
3912 Changed = true;
3913 }
3914
3915 return Changed;
3916}
3917
3918void ASTWriter::AddPath(StringRef Path, RecordDataImpl &Record) {
3919 SmallString<128> FilePath(Path);
3920 PreparePathForOutput(FilePath);
3921 AddString(FilePath, Record);
3922}
3923
3924void ASTWriter::EmitRecordWithPath(unsigned Abbrev, RecordDataImpl &Record,
3925 StringRef Path) {
3926 SmallString<128> FilePath(Path);
3927 PreparePathForOutput(FilePath);
3928 Stream.EmitRecordWithBlob(Abbrev, Record, FilePath);
3929}
3930
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00003931void ASTWriter::AddVersionTuple(const VersionTuple &Version,
3932 RecordDataImpl &Record) {
3933 Record.push_back(Version.getMajor());
David Blaikie05785d12013-02-20 22:23:23 +00003934 if (Optional<unsigned> Minor = Version.getMinor())
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00003935 Record.push_back(*Minor + 1);
3936 else
3937 Record.push_back(0);
David Blaikie05785d12013-02-20 22:23:23 +00003938 if (Optional<unsigned> Subminor = Version.getSubminor())
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00003939 Record.push_back(*Subminor + 1);
3940 else
3941 Record.push_back(0);
3942}
3943
Douglas Gregore84a9da2009-04-20 20:36:09 +00003944/// \brief Note that the identifier II occurs at the given offset
3945/// within the identifier table.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00003946void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
Sebastian Redl539c5062010-08-18 23:57:32 +00003947 IdentID ID = IdentifierIDs[II];
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003948 // Only store offsets new to this AST file. Other identifier names are looked
Sebastian Redlff4a2952010-07-23 23:49:55 +00003949 // up earlier in the chain and thus don't need an offset.
3950 if (ID >= FirstIdentID)
3951 IdentifierOffsets[ID - FirstIdentID] = Offset;
Douglas Gregore84a9da2009-04-20 20:36:09 +00003952}
3953
Douglas Gregor95c13f52009-04-25 17:48:32 +00003954/// \brief Note that the selector Sel occurs at the given offset
3955/// within the method pool/selector table.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00003956void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
Douglas Gregor95c13f52009-04-25 17:48:32 +00003957 unsigned ID = SelectorIDs[Sel];
3958 assert(ID && "Unknown selector");
Sebastian Redld95a56e2010-08-04 18:21:41 +00003959 // Don't record offsets for selectors that are also available in a different
3960 // file.
3961 if (ID < FirstSelectorID)
3962 return;
3963 SelectorOffsets[ID - FirstSelectorID] = Offset;
Douglas Gregor95c13f52009-04-25 17:48:32 +00003964}
3965
Sebastian Redl55c0ad52010-08-18 23:56:21 +00003966ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream)
Richard Smith01b2cb42014-07-26 06:37:51 +00003967 : Stream(Stream), Context(nullptr), PP(nullptr), Chain(nullptr),
3968 WritingModule(nullptr), WritingAST(false),
3969 DoneWritingDeclsAndTypes(false), ASTHasCompilerErrors(false),
3970 FirstDeclID(NUM_PREDEF_DECL_IDS), NextDeclID(FirstDeclID),
3971 FirstTypeID(NUM_PREDEF_TYPE_IDS), NextTypeID(FirstTypeID),
3972 FirstIdentID(NUM_PREDEF_IDENT_IDS), NextIdentID(FirstIdentID),
3973 FirstMacroID(NUM_PREDEF_MACRO_IDS), NextMacroID(FirstMacroID),
3974 FirstSubmoduleID(NUM_PREDEF_SUBMODULE_IDS),
3975 NextSubmoduleID(FirstSubmoduleID),
3976 FirstSelectorID(NUM_PREDEF_SELECTOR_IDS), NextSelectorID(FirstSelectorID),
3977 CollectedStmts(&StmtsToEmit), NumStatements(0), NumMacros(0),
3978 NumLexicalDeclContexts(0), NumVisibleDeclContexts(0),
Richard Smithc2bb8182015-03-24 06:36:48 +00003979 NextCXXBaseSpecifiersID(1), NextCXXCtorInitializersID(1),
3980 TypeExtQualAbbrev(0),
Richard Smith01b2cb42014-07-26 06:37:51 +00003981 TypeFunctionProtoAbbrev(0), DeclParmVarAbbrev(0),
3982 DeclContextLexicalAbbrev(0), DeclContextVisibleLookupAbbrev(0),
Richard Smitha27c26e2014-07-27 04:19:32 +00003983 UpdateVisibleAbbrev(0), DeclRecordAbbrev(0), DeclTypedefAbbrev(0),
Richard Smith01b2cb42014-07-26 06:37:51 +00003984 DeclVarAbbrev(0), DeclFieldAbbrev(0), DeclEnumAbbrev(0),
Richard Smitha27c26e2014-07-27 04:19:32 +00003985 DeclObjCIvarAbbrev(0), DeclCXXMethodAbbrev(0), DeclRefExprAbbrev(0),
3986 CharacterLiteralAbbrev(0), IntegerLiteralAbbrev(0),
3987 ExprImplicitCastAbbrev(0) {}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003988
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00003989ASTWriter::~ASTWriter() {
Reid Kleckner588c9372014-02-19 23:44:52 +00003990 llvm::DeleteContainerSeconds(FileDeclIDs);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00003991}
3992
Richard Smithb3761912015-02-05 23:08:52 +00003993const LangOptions &ASTWriter::getLangOpts() const {
3994 assert(WritingAST && "can't determine lang opts when not writing AST");
3995 return Context->getLangOpts();
3996}
3997
Argyrios Kyrtzidisd7c16b22012-10-31 20:59:50 +00003998void ASTWriter::WriteAST(Sema &SemaRef,
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00003999 const std::string &OutputFile,
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00004000 Module *WritingModule, StringRef isysroot,
4001 bool hasErrors) {
Douglas Gregor2fd3d402011-09-17 00:05:03 +00004002 WritingAST = true;
4003
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00004004 ASTHasCompilerErrors = hasErrors;
4005
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004006 // Emit the file header.
Douglas Gregor8f45df52009-04-16 22:23:12 +00004007 Stream.Emit((unsigned)'C', 8);
4008 Stream.Emit((unsigned)'P', 8);
4009 Stream.Emit((unsigned)'C', 8);
4010 Stream.Emit((unsigned)'H', 8);
Mike Stump11289f42009-09-09 15:08:12 +00004011
Chris Lattner28fa4e62009-04-26 22:26:21 +00004012 WriteBlockInfoBlock();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004013
Douglas Gregoreda8e122011-08-09 15:13:55 +00004014 Context = &SemaRef.Context;
Douglas Gregora28bcdd2011-12-01 02:07:58 +00004015 PP = &SemaRef.PP;
Douglas Gregora89c5ac2011-12-06 01:10:29 +00004016 this->WritingModule = WritingModule;
Argyrios Kyrtzidisd7c16b22012-10-31 20:59:50 +00004017 WriteASTCore(SemaRef, isysroot, OutputFile, WritingModule);
Craig Toppera13603a2014-05-22 05:54:18 +00004018 Context = nullptr;
4019 PP = nullptr;
4020 this->WritingModule = nullptr;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004021 this->BaseDirectory.clear();
Craig Toppera13603a2014-05-22 05:54:18 +00004022
Douglas Gregor2fd3d402011-09-17 00:05:03 +00004023 WritingAST = false;
Sebastian Redl143413f2010-07-12 22:02:52 +00004024}
4025
Douglas Gregora94a1542011-07-27 21:45:57 +00004026template<typename Vector>
4027static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
4028 ASTWriter::RecordData &Record) {
Craig Toppera13603a2014-05-22 05:54:18 +00004029 for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
4030 I != E; ++I) {
Douglas Gregora94a1542011-07-27 21:45:57 +00004031 Writer.AddDeclRef(*I, Record);
4032 }
4033}
4034
Argyrios Kyrtzidisd7c16b22012-10-31 20:59:50 +00004035void ASTWriter::WriteASTCore(Sema &SemaRef,
Douglas Gregorc567ba22011-07-22 16:35:34 +00004036 StringRef isysroot,
Douglas Gregorf7a700fd2011-11-30 04:39:39 +00004037 const std::string &OutputFile,
Douglas Gregorde3ef502011-11-30 23:21:26 +00004038 Module *WritingModule) {
Sebastian Redl143413f2010-07-12 22:02:52 +00004039 using namespace llvm;
4040
Craig Toppera13603a2014-05-22 05:54:18 +00004041 bool isModule = WritingModule != nullptr;
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004042
Douglas Gregorcf68c582011-12-01 22:20:10 +00004043 // Make sure that the AST reader knows to finalize itself.
4044 if (Chain)
4045 Chain->finalizeForWriting();
4046
Sebastian Redl143413f2010-07-12 22:02:52 +00004047 ASTContext &Context = SemaRef.Context;
4048 Preprocessor &PP = SemaRef.PP;
4049
Douglas Gregordab42432011-08-12 00:15:20 +00004050 // Set up predefined declaration IDs.
4051 DeclIDs[Context.getTranslationUnitDecl()] = PREDEF_DECL_TRANSLATION_UNIT_ID;
Douglas Gregor3ea72692011-08-12 05:46:01 +00004052 if (Context.ObjCIdDecl)
4053 DeclIDs[Context.ObjCIdDecl] = PREDEF_DECL_OBJC_ID_ID;
Douglas Gregor52e02802011-08-12 06:17:30 +00004054 if (Context.ObjCSelDecl)
4055 DeclIDs[Context.ObjCSelDecl] = PREDEF_DECL_OBJC_SEL_ID;
Douglas Gregor0a586182011-08-12 05:59:41 +00004056 if (Context.ObjCClassDecl)
4057 DeclIDs[Context.ObjCClassDecl] = PREDEF_DECL_OBJC_CLASS_ID;
Douglas Gregord53ae832012-01-17 18:09:05 +00004058 if (Context.ObjCProtocolClassDecl)
4059 DeclIDs[Context.ObjCProtocolClassDecl] = PREDEF_DECL_OBJC_PROTOCOL_ID;
Douglas Gregor801c99d2011-08-12 06:49:56 +00004060 if (Context.Int128Decl)
4061 DeclIDs[Context.Int128Decl] = PREDEF_DECL_INT_128_ID;
4062 if (Context.UInt128Decl)
4063 DeclIDs[Context.UInt128Decl] = PREDEF_DECL_UNSIGNED_INT_128_ID;
Douglas Gregorbab8a962011-09-08 01:46:34 +00004064 if (Context.ObjCInstanceTypeDecl)
4065 DeclIDs[Context.ObjCInstanceTypeDecl] = PREDEF_DECL_OBJC_INSTANCETYPE_ID;
Meador Inge5d3fb222012-06-16 03:34:49 +00004066 if (Context.BuiltinVaListDecl)
4067 DeclIDs[Context.getBuiltinVaListDecl()] = PREDEF_DECL_BUILTIN_VA_LIST_ID;
Richard Smithf19e1272015-03-07 00:04:49 +00004068 if (Context.ExternCContext)
4069 DeclIDs[Context.ExternCContext] = PREDEF_DECL_EXTERN_C_CONTEXT_ID;
Meador Inge5d3fb222012-06-16 03:34:49 +00004070
Chris Lattner0c797362009-09-08 18:19:27 +00004071 // Build a record containing all of the tentative definitions in this file, in
Sebastian Redl35351a92010-01-31 22:27:38 +00004072 // TentativeDefinitions order. Generally, this record will be empty for
Chris Lattner0c797362009-09-08 18:19:27 +00004073 // headers.
Douglas Gregord4df8652009-04-22 22:02:47 +00004074 RecordData TentativeDefinitions;
Douglas Gregora94a1542011-07-27 21:45:57 +00004075 AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
Douglas Gregoreb08bd42011-07-27 20:58:46 +00004076
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00004077 // Build a record containing all of the file scoped decls in this file.
4078 RecordData UnusedFileScopedDecls;
Argyrios Kyrtzidis59852362013-03-14 04:45:00 +00004079 if (!isModule)
4080 AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls,
4081 UnusedFileScopedDecls);
Sebastian Redl08aca90252010-08-05 18:21:25 +00004082
Douglas Gregor851443c2011-08-12 01:39:19 +00004083 // Build a record containing all of the delegating constructors we still need
4084 // to resolve.
Alexis Hunt27a761d2011-05-04 23:29:54 +00004085 RecordData DelegatingCtorDecls;
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004086 if (!isModule)
4087 AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
Alexis Hunt27a761d2011-05-04 23:29:54 +00004088
Douglas Gregor851443c2011-08-12 01:39:19 +00004089 // Write the set of weak, undeclared identifiers. We always write the
4090 // entire table, since later PCH files in a PCH chain are only interested in
4091 // the results at the end of the chain.
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004092 RecordData WeakUndeclaredIdentifiers;
Chandler Carruthf85d9822015-03-26 08:32:49 +00004093 for (auto &WeakUndeclaredIdentifier : SemaRef.WeakUndeclaredIdentifiers) {
4094 IdentifierInfo *II = WeakUndeclaredIdentifier.first;
4095 WeakInfo &WI = WeakUndeclaredIdentifier.second;
4096 AddIdentifierRef(II, WeakUndeclaredIdentifiers);
4097 AddIdentifierRef(WI.getAlias(), WeakUndeclaredIdentifiers);
4098 AddSourceLocation(WI.getLocation(), WeakUndeclaredIdentifiers);
4099 WeakUndeclaredIdentifiers.push_back(WI.getUsed());
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004100 }
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00004101
Douglas Gregor61cac2b2009-04-27 20:06:05 +00004102 // Build a record containing all of the ext_vector declarations.
4103 RecordData ExtVectorDecls;
Douglas Gregorb7098a32011-07-28 00:39:29 +00004104 AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
Douglas Gregor61cac2b2009-04-27 20:06:05 +00004105
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004106 // Build a record containing all of the VTable uses information.
4107 RecordData VTableUses;
Argyrios Kyrtzidisedee67f2010-08-03 17:29:52 +00004108 if (!SemaRef.VTableUses.empty()) {
Argyrios Kyrtzidisedee67f2010-08-03 17:29:52 +00004109 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
4110 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
4111 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
4112 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
4113 }
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004114 }
4115
Nico Weber72889432014-09-06 01:25:55 +00004116 // Build a record containing all of the UnusedLocalTypedefNameCandidates.
4117 RecordData UnusedLocalTypedefNameCandidates;
4118 for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates)
4119 AddDeclRef(TD, UnusedLocalTypedefNameCandidates);
4120
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004121 // Build a record containing all of pending implicit instantiations.
Chandler Carruth54080172010-08-25 08:44:16 +00004122 RecordData PendingInstantiations;
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004123 for (std::deque<Sema::PendingImplicitInstantiation>::iterator
Chandler Carruth54080172010-08-25 08:44:16 +00004124 I = SemaRef.PendingInstantiations.begin(),
4125 N = SemaRef.PendingInstantiations.end(); I != N; ++I) {
4126 AddDeclRef(I->first, PendingInstantiations);
4127 AddSourceLocation(I->second, PendingInstantiations);
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004128 }
4129 assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
4130 "There are local ones at end of translation unit!");
4131
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004132 // Build a record containing some declaration references.
4133 RecordData SemaDeclRefs;
4134 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc) {
4135 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
4136 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
4137 }
4138
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00004139 RecordData CUDASpecialDeclRefs;
4140 if (Context.getcudaConfigureCallDecl()) {
4141 AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
4142 }
4143
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004144 // Build a record containing all of the known namespaces.
4145 RecordData KnownNamespaces;
Nick Lewycky8334af82013-01-26 00:35:08 +00004146 for (llvm::MapVector<NamespaceDecl*, bool>::iterator
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004147 I = SemaRef.KnownNamespaces.begin(),
4148 IEnd = SemaRef.KnownNamespaces.end();
4149 I != IEnd; ++I) {
4150 if (!I->second)
4151 AddDeclRef(I->first, KnownNamespaces);
4152 }
Douglas Gregor112b9072012-10-18 05:31:06 +00004153
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00004154 // Build a record of all used, undefined objects that require definitions.
4155 RecordData UndefinedButUsed;
Nick Lewyckyf0f56162013-01-31 03:23:57 +00004156
4157 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00004158 SemaRef.getUndefinedButUsed(Undefined);
Nick Lewyckyf0f56162013-01-31 03:23:57 +00004159 for (SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> >::iterator
4160 I = Undefined.begin(), E = Undefined.end(); I != E; ++I) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00004161 AddDeclRef(I->first, UndefinedButUsed);
4162 AddSourceLocation(I->second, UndefinedButUsed);
Nick Lewycky8334af82013-01-26 00:35:08 +00004163 }
4164
Douglas Gregor112b9072012-10-18 05:31:06 +00004165 // Write the control block
Douglas Gregor2d302362012-10-24 16:50:34 +00004166 WriteControlBlock(PP, Context, isysroot, OutputFile);
Douglas Gregor112b9072012-10-18 05:31:06 +00004167
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00004168 // Write the remaining AST contents.
Douglas Gregor652d82a2009-04-18 05:55:16 +00004169 RecordData Record;
Sebastian Redl539c5062010-08-18 23:57:32 +00004170 Stream.EnterSubblock(AST_BLOCK_ID, 5);
Douglas Gregor851443c2011-08-12 01:39:19 +00004171
Argyrios Kyrtzidis39605402012-12-13 21:38:23 +00004172 // This is so that older clang versions, before the introduction
4173 // of the control block, can read and reject the newer PCH format.
4174 Record.clear();
4175 Record.push_back(VERSION_MAJOR);
4176 Stream.EmitRecord(METADATA_OLD_FORMAT, Record);
4177
Douglas Gregor851443c2011-08-12 01:39:19 +00004178 // Create a lexical update block containing all of the declarations in the
4179 // translation unit that do not come from other AST files.
4180 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
4181 SmallVector<KindDeclIDPair, 64> NewGlobalDecls;
Aaron Ballman629afae2014-03-07 19:56:05 +00004182 for (const auto *I : TU->noload_decls()) {
4183 if (!I->isFromASTFile())
4184 NewGlobalDecls.push_back(std::make_pair(I->getKind(), GetDeclRef(I)));
Douglas Gregor851443c2011-08-12 01:39:19 +00004185 }
4186
4187 llvm::BitCodeAbbrev *Abv = new llvm::BitCodeAbbrev();
4188 Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
4189 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4190 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(Abv);
4191 Record.clear();
4192 Record.push_back(TU_UPDATE_LEXICAL);
4193 Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
4194 data(NewGlobalDecls));
4195
4196 // And a visible updates block for the translation unit.
4197 Abv = new llvm::BitCodeAbbrev();
4198 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
4199 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4200 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Fixed, 32));
4201 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4202 UpdateVisibleAbbrev = Stream.EmitAbbrev(Abv);
4203 WriteDeclContextVisibleUpdate(TU);
Richard Smithf19e1272015-03-07 00:04:49 +00004204
4205 // If we have any extern "C" names, write out a visible update for them.
4206 if (Context.ExternCContext)
4207 WriteDeclContextVisibleUpdate(Context.ExternCContext);
Douglas Gregor851443c2011-08-12 01:39:19 +00004208
4209 // If the translation unit has an anonymous namespace, and we don't already
4210 // have an update block for it, write it as an update block.
Richard Smith6ef42932014-03-20 21:02:00 +00004211 // FIXME: Why do we not do this if there's already an update block?
Douglas Gregor851443c2011-08-12 01:39:19 +00004212 if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
4213 ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
Richard Smith6ef42932014-03-20 21:02:00 +00004214 if (Record.empty())
Aaron Ballman4f45b712014-03-21 15:22:56 +00004215 Record.push_back(DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, NS));
Douglas Gregor851443c2011-08-12 01:39:19 +00004216 }
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004217
Richard Smith5652c0f2014-03-21 01:48:23 +00004218 // Add update records for all mangling numbers and static local numbers.
4219 // These aren't really update records, but this is a convenient way of
4220 // tagging this rare extra data onto the declarations.
4221 for (const auto &Number : Context.MangleNumbers)
4222 if (!Number.first->isFromASTFile())
Aaron Ballman4f45b712014-03-21 15:22:56 +00004223 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_MANGLING_NUMBER,
4224 Number.second));
Richard Smith5652c0f2014-03-21 01:48:23 +00004225 for (const auto &Number : Context.StaticLocalNumbers)
4226 if (!Number.first->isFromASTFile())
Aaron Ballman4f45b712014-03-21 15:22:56 +00004227 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_STATIC_LOCAL_NUMBER,
4228 Number.second));
Richard Smith5652c0f2014-03-21 01:48:23 +00004229
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004230 // Make sure visible decls, added to DeclContexts previously loaded from
4231 // an AST file, are registered for serialization.
Craig Topper2341c0d2013-07-04 03:08:24 +00004232 for (SmallVectorImpl<const Decl *>::iterator
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004233 I = UpdatingVisibleDecls.begin(),
4234 E = UpdatingVisibleDecls.end(); I != E; ++I) {
4235 GetDeclRef(*I);
4236 }
4237
Argyrios Kyrtzidisacfbbd72013-08-07 21:17:33 +00004238 // Make sure all decls associated with an identifier are registered for
4239 // serialization.
Chandler Carruth8440c982015-03-26 23:54:15 +00004240 llvm::SmallVector<const IdentifierInfo*, 256> IIs;
Argyrios Kyrtzidisacfbbd72013-08-07 21:17:33 +00004241 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
4242 IDEnd = PP.getIdentifierTable().end();
4243 ID != IDEnd; ++ID) {
4244 const IdentifierInfo *II = ID->second;
Richard Smith9ab4cce2015-03-11 00:00:51 +00004245 if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization())
Chandler Carruth8440c982015-03-26 23:54:15 +00004246 IIs.push_back(II);
Richard Smith9ab4cce2015-03-11 00:00:51 +00004247 }
Chandler Carruth8440c982015-03-26 23:54:15 +00004248 // Sort the identifiers to visit based on their name.
4249 std::sort(IIs.begin(), IIs.end(), llvm::less_ptr<IdentifierInfo>());
4250 for (const IdentifierInfo *II : IIs) {
Richard Smith9ab4cce2015-03-11 00:00:51 +00004251 for (IdentifierResolver::iterator D = SemaRef.IdResolver.begin(II),
4252 DEnd = SemaRef.IdResolver.end();
4253 D != DEnd; ++D) {
4254 GetDeclRef(*D);
Argyrios Kyrtzidisacfbbd72013-08-07 21:17:33 +00004255 }
4256 }
4257
Douglas Gregor5204bde2011-08-02 16:26:37 +00004258 // Form the record of special types.
4259 RecordData SpecialTypes;
Douglas Gregor5204bde2011-08-02 16:26:37 +00004260 AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
Douglas Gregor5204bde2011-08-02 16:26:37 +00004261 AddTypeRef(Context.getFILEType(), SpecialTypes);
4262 AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
4263 AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
4264 AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
4265 AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
Douglas Gregor5204bde2011-08-02 16:26:37 +00004266 AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00004267 AddTypeRef(Context.getucontext_tType(), SpecialTypes);
Douglas Gregora28bcdd2011-12-01 02:07:58 +00004268
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004269 if (Chain) {
4270 // Write the mapping information describing our module dependencies and how
4271 // each of those modules were mapped into our own offset/ID space, so that
4272 // the reader can build the appropriate mapping to its own offset/ID space.
4273 // The map consists solely of a blob with the following format:
4274 // *(module-name-len:i16 module-name:len*i8
4275 // source-location-offset:i32
4276 // identifier-id:i32
4277 // preprocessed-entity-id:i32
4278 // macro-definition-id:i32
Douglas Gregor253eefe2011-12-01 00:59:36 +00004279 // submodule-id:i32
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004280 // selector-id:i32
4281 // declaration-id:i32
4282 // c++-base-specifiers-id:i32
4283 // type-id:i32)
4284 //
4285 llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
4286 Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
4287 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4288 unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(Abbrev);
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004289 SmallString<2048> Buffer;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004290 {
4291 llvm::raw_svector_ostream Out(Buffer);
Ben Langmuir785180e2014-10-20 16:27:30 +00004292 for (ModuleFile *M : Chain->ModuleMgr) {
Justin Bognere1c147c2014-03-28 22:03:19 +00004293 using namespace llvm::support;
4294 endian::Writer<little> LE(Out);
Ben Langmuir785180e2014-10-20 16:27:30 +00004295 StringRef FileName = M->FileName;
Justin Bognere1c147c2014-03-28 22:03:19 +00004296 LE.write<uint16_t>(FileName.size());
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004297 Out.write(FileName.data(), FileName.size());
Ben Langmuirfe971d92014-08-16 04:54:18 +00004298
Ben Langmuir785180e2014-10-20 16:27:30 +00004299 // Note: if a base ID was uint max, it would not be possible to load
4300 // another module after it or have more than one entity inside it.
4301 uint32_t None = std::numeric_limits<uint32_t>::max();
4302
4303 auto writeBaseIDOrNone = [&](uint32_t BaseID, bool ShouldWrite) {
4304 assert(BaseID < std::numeric_limits<uint32_t>::max() && "base id too high");
4305 if (ShouldWrite)
4306 LE.write<uint32_t>(BaseID);
4307 else
4308 LE.write<uint32_t>(None);
4309 };
4310
Ben Langmuirfe971d92014-08-16 04:54:18 +00004311 // These values should be unique within a chain, since they will be read
4312 // as keys into ContinuousRangeMaps.
Ben Langmuir785180e2014-10-20 16:27:30 +00004313 writeBaseIDOrNone(M->SLocEntryBaseOffset, M->LocalNumSLocEntries);
4314 writeBaseIDOrNone(M->BaseIdentifierID, M->LocalNumIdentifiers);
4315 writeBaseIDOrNone(M->BaseMacroID, M->LocalNumMacros);
4316 writeBaseIDOrNone(M->BasePreprocessedEntityID,
4317 M->NumPreprocessedEntities);
4318 writeBaseIDOrNone(M->BaseSubmoduleID, M->LocalNumSubmodules);
4319 writeBaseIDOrNone(M->BaseSelectorID, M->LocalNumSelectors);
4320 writeBaseIDOrNone(M->BaseDeclID, M->LocalNumDecls);
4321 writeBaseIDOrNone(M->BaseTypeIndex, M->LocalNumTypes);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004322 }
4323 }
4324 Record.clear();
4325 Record.push_back(MODULE_OFFSET_MAP);
4326 Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
4327 Buffer.data(), Buffer.size());
4328 }
Richard Smithb9eab6d2014-03-20 19:44:17 +00004329
Richard Smithb9eab6d2014-03-20 19:44:17 +00004330 RecordData DeclUpdatesOffsetsRecord;
4331
Richard Smith59442b42014-03-20 20:07:19 +00004332 // Keep writing types, declarations, and declaration update records
4333 // until we've emitted all of them.
Richard Smith01b2cb42014-07-26 06:37:51 +00004334 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/5);
4335 WriteTypeAbbrevs();
4336 WriteDeclAbbrevs();
Richard Smithb9eab6d2014-03-20 19:44:17 +00004337 for (DeclsToRewriteTy::iterator I = DeclsToRewrite.begin(),
4338 E = DeclsToRewrite.end();
4339 I != E; ++I)
4340 DeclTypesToEmit.push(const_cast<Decl*>(*I));
Richard Smith59442b42014-03-20 20:07:19 +00004341 do {
4342 WriteDeclUpdatesBlocks(DeclUpdatesOffsetsRecord);
4343 while (!DeclTypesToEmit.empty()) {
4344 DeclOrType DOT = DeclTypesToEmit.front();
4345 DeclTypesToEmit.pop();
4346 if (DOT.isType())
4347 WriteType(DOT.getType());
4348 else
4349 WriteDecl(Context, DOT.getDecl());
4350 }
4351 } while (!DeclUpdates.empty());
Richard Smithb9eab6d2014-03-20 19:44:17 +00004352 Stream.ExitBlock();
4353
Richard Smithb9eab6d2014-03-20 19:44:17 +00004354 DoneWritingDeclsAndTypes = true;
4355
4356 // These things can only be done once we've written out decls and types.
4357 WriteTypeDeclOffsets();
Richard Smith5652c0f2014-03-21 01:48:23 +00004358 if (!DeclUpdatesOffsetsRecord.empty())
4359 Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord);
Richard Smithb9eab6d2014-03-20 19:44:17 +00004360 WriteCXXBaseSpecifiersOffsets();
Richard Smithc2bb8182015-03-24 06:36:48 +00004361 WriteCXXCtorInitializersOffsets();
Richard Smithb9eab6d2014-03-20 19:44:17 +00004362 WriteFileDeclIDsMap();
Richard Smith7ed1bc92014-12-05 22:42:13 +00004363 WriteSourceManagerBlock(Context.getSourceManager(), PP);
Richard Smithb9eab6d2014-03-20 19:44:17 +00004364
4365 WriteComments();
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004366 WritePreprocessor(PP, isModule);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004367 WriteHeaderSearch(PP.getHeaderSearchInfo());
Sebastian Redla19a67f2010-08-03 21:58:15 +00004368 WriteSelectors(SemaRef);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00004369 WriteReferencedSelectorsPool(SemaRef);
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004370 WriteIdentifierTable(PP, SemaRef.IdResolver, isModule);
Peter Collingbourne5df20e02011-02-15 19:46:30 +00004371 WriteFPPragmaOptions(SemaRef.getFPOptions());
4372 WriteOpenCLExtensions(SemaRef);
Argyrios Kyrtzidis0f06b982013-03-27 17:17:23 +00004373 WritePragmaDiagnosticMappings(Context.getDiagnostics(), isModule);
Douglas Gregor652d82a2009-04-18 05:55:16 +00004374
Douglas Gregora89c5ac2011-12-06 01:10:29 +00004375 // If we're emitting a module, write out the submodule information.
4376 if (WritingModule)
4377 WriteSubmodules(WritingModule);
4378
Douglas Gregor5204bde2011-08-02 16:26:37 +00004379 Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
4380
Douglas Gregord4df8652009-04-22 22:02:47 +00004381 // Write the record containing external, unnamed definitions.
Ben Langmuir332aafe2014-01-31 01:06:56 +00004382 if (!EagerlyDeserializedDecls.empty())
4383 Stream.EmitRecord(EAGERLY_DESERIALIZED_DECLS, EagerlyDeserializedDecls);
Douglas Gregord4df8652009-04-22 22:02:47 +00004384
4385 // Write the record containing tentative definitions.
4386 if (!TentativeDefinitions.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004387 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
Douglas Gregoracfc76c2009-04-22 22:18:58 +00004388
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00004389 // Write the record containing unused file scoped decls.
4390 if (!UnusedFileScopedDecls.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004391 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00004392
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004393 // Write the record containing weak undeclared identifiers.
4394 if (!WeakUndeclaredIdentifiers.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004395 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004396 WeakUndeclaredIdentifiers);
4397
Douglas Gregor61cac2b2009-04-27 20:06:05 +00004398 // Write the record containing ext_vector type names.
4399 if (!ExtVectorDecls.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004400 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
Mike Stump11289f42009-09-09 15:08:12 +00004401
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004402 // Write the record containing VTable uses information.
4403 if (!VTableUses.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004404 Stream.EmitRecord(VTABLE_USES, VTableUses);
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004405
Nico Weber72889432014-09-06 01:25:55 +00004406 // Write the record containing potentially unused local typedefs.
4407 if (!UnusedLocalTypedefNameCandidates.empty())
4408 Stream.EmitRecord(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES,
4409 UnusedLocalTypedefNameCandidates);
4410
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004411 // Write the record containing pending implicit instantiations.
Chandler Carruth54080172010-08-25 08:44:16 +00004412 if (!PendingInstantiations.empty())
4413 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004414
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004415 // Write the record containing declaration references of Sema.
4416 if (!SemaDeclRefs.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004417 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004418
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00004419 // Write the record containing CUDA-specific declaration references.
4420 if (!CUDASpecialDeclRefs.empty())
4421 Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
Alexis Hunt27a761d2011-05-04 23:29:54 +00004422
4423 // Write the delegating constructors.
4424 if (!DelegatingCtorDecls.empty())
4425 Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00004426
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004427 // Write the known namespaces.
4428 if (!KnownNamespaces.empty())
4429 Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
Nick Lewycky8334af82013-01-26 00:35:08 +00004430
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00004431 // Write the undefined internal functions and variables, and inline functions.
4432 if (!UndefinedButUsed.empty())
4433 Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004434
Douglas Gregor851443c2011-08-12 01:39:19 +00004435 // Write the visible updates to DeclContexts.
Richard Smithcd45dbc2014-04-19 03:48:30 +00004436 for (auto *DC : UpdatedDeclContexts)
4437 WriteDeclContextVisibleUpdate(DC);
Douglas Gregor851443c2011-08-12 01:39:19 +00004438
Douglas Gregor959bb062011-12-03 01:15:29 +00004439 if (!WritingModule) {
4440 // Write the submodules that were imported, if any.
Aaron Ballman4f45b712014-03-21 15:22:56 +00004441 struct ModuleInfo {
4442 uint64_t ID;
4443 Module *M;
4444 ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {}
4445 };
Richard Smith56be7542014-03-21 00:33:59 +00004446 llvm::SmallVector<ModuleInfo, 64> Imports;
Aaron Ballmanbbc31212014-03-14 20:59:21 +00004447 for (const auto *I : Context.local_imports()) {
Douglas Gregor959bb062011-12-03 01:15:29 +00004448 assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end());
Aaron Ballman4f45b712014-03-21 15:22:56 +00004449 Imports.push_back(ModuleInfo(SubmoduleIDs[I->getImportedModule()],
4450 I->getImportedModule()));
Douglas Gregor959bb062011-12-03 01:15:29 +00004451 }
Richard Smith56be7542014-03-21 00:33:59 +00004452
4453 if (!Imports.empty()) {
4454 auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) {
4455 return A.ID < B.ID;
4456 };
Ben Langmuir5f95c8f2014-09-08 20:36:26 +00004457 auto Eq = [](const ModuleInfo &A, const ModuleInfo &B) {
4458 return A.ID == B.ID;
4459 };
Richard Smith56be7542014-03-21 00:33:59 +00004460
4461 // Sort and deduplicate module IDs.
4462 std::sort(Imports.begin(), Imports.end(), Cmp);
Ben Langmuir5f95c8f2014-09-08 20:36:26 +00004463 Imports.erase(std::unique(Imports.begin(), Imports.end(), Eq),
Richard Smith56be7542014-03-21 00:33:59 +00004464 Imports.end());
4465
4466 RecordData ImportedModules;
4467 for (const auto &Import : Imports) {
4468 ImportedModules.push_back(Import.ID);
4469 // FIXME: If the module has macros imported then later has declarations
4470 // imported, this location won't be the right one as a location for the
4471 // declaration imports.
4472 AddSourceLocation(Import.M->MacroVisibilityLoc, ImportedModules);
4473 }
4474
Douglas Gregor959bb062011-12-03 01:15:29 +00004475 Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
4476 }
Douglas Gregor0a839132011-12-03 00:59:55 +00004477 }
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00004478
Douglas Gregor851443c2011-08-12 01:39:19 +00004479 WriteDeclReplacementsBlock();
Douglas Gregor358cd442012-01-15 16:58:34 +00004480 WriteRedeclarations();
Douglas Gregor404cdde2012-01-27 01:47:08 +00004481 WriteObjCCategories();
Richard Smithe40f2ba2013-08-07 21:41:30 +00004482 WriteLateParsedTemplates(SemaRef);
Dario Domizioli13a0a382014-05-23 12:13:25 +00004483 if(!WritingModule)
4484 WriteOptimizePragmaOptions(SemaRef);
Richard Smithe40f2ba2013-08-07 21:41:30 +00004485
Douglas Gregor08f01292009-04-17 22:13:46 +00004486 // Some simple statistics
Douglas Gregor652d82a2009-04-18 05:55:16 +00004487 Record.clear();
Douglas Gregor08f01292009-04-17 22:13:46 +00004488 Record.push_back(NumStatements);
Douglas Gregorc3366a52009-04-21 23:56:24 +00004489 Record.push_back(NumMacros);
Douglas Gregora57c3ab2009-04-22 22:34:57 +00004490 Record.push_back(NumLexicalDeclContexts);
4491 Record.push_back(NumVisibleDeclContexts);
Sebastian Redl539c5062010-08-18 23:57:32 +00004492 Stream.EmitRecord(STATISTICS, Record);
Douglas Gregor8f45df52009-04-16 22:23:12 +00004493 Stream.ExitBlock();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004494}
4495
Richard Smithb9eab6d2014-03-20 19:44:17 +00004496void ASTWriter::WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord) {
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00004497 if (DeclUpdates.empty())
4498 return;
4499
Richard Smith59442b42014-03-20 20:07:19 +00004500 DeclUpdateMap LocalUpdates;
4501 LocalUpdates.swap(DeclUpdates);
4502
Richard Smith6ef42932014-03-20 21:02:00 +00004503 for (auto &DeclUpdate : LocalUpdates) {
4504 const Decl *D = DeclUpdate.first;
Argyrios Kyrtzidisb97a4022011-11-12 21:07:46 +00004505 if (isRewritten(D))
Argyrios Kyrtzidis3ba70b82010-10-24 17:26:46 +00004506 continue; // The decl will be written completely,no need to store updates.
4507
Richard Smithd28ac5b2014-03-22 23:33:22 +00004508 bool HasUpdatedBody = false;
Richard Smith6ef42932014-03-20 21:02:00 +00004509 RecordData Record;
4510 for (auto &Update : DeclUpdate.second) {
4511 DeclUpdateKind Kind = (DeclUpdateKind)Update.getKind();
4512
4513 Record.push_back(Kind);
4514 switch (Kind) {
4515 case UPD_CXX_ADDED_IMPLICIT_MEMBER:
4516 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
4517 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE:
Richard Smithcd45dbc2014-04-19 03:48:30 +00004518 assert(Update.getDecl() && "no decl to add?");
Richard Smith6ef42932014-03-20 21:02:00 +00004519 Record.push_back(GetDeclRef(Update.getDecl()));
4520 break;
4521
Richard Smith4d235792014-08-07 18:53:08 +00004522 case UPD_CXX_ADDED_FUNCTION_DEFINITION:
Richard Smithd28ac5b2014-03-22 23:33:22 +00004523 // An updated body is emitted last, so that the reader doesn't need
4524 // to skip over the lazy body to reach statements for other records.
4525 Record.pop_back();
4526 HasUpdatedBody = true;
4527 break;
4528
Richard Smith4d235792014-08-07 18:53:08 +00004529 case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER:
4530 AddSourceLocation(Update.getLoc(), Record);
4531 break;
4532
Richard Smithcd45dbc2014-04-19 03:48:30 +00004533 case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
4534 auto *RD = cast<CXXRecordDecl>(D);
Chandler Carruth8a3d24d2015-03-26 04:27:10 +00004535 UpdatedDeclContexts.insert(RD->getPrimaryContext());
Richard Smithcd45dbc2014-04-19 03:48:30 +00004536 AddCXXDefinitionData(RD, Record);
4537 Record.push_back(WriteDeclContextLexicalBlock(
4538 *Context, const_cast<CXXRecordDecl *>(RD)));
4539
4540 // This state is sometimes updated by template instantiation, when we
4541 // switch from the specialization referring to the template declaration
4542 // to it referring to the template definition.
4543 if (auto *MSInfo = RD->getMemberSpecializationInfo()) {
4544 Record.push_back(MSInfo->getTemplateSpecializationKind());
4545 AddSourceLocation(MSInfo->getPointOfInstantiation(), Record);
4546 } else {
4547 auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
4548 Record.push_back(Spec->getTemplateSpecializationKind());
4549 AddSourceLocation(Spec->getPointOfInstantiation(), Record);
Richard Smithdf352052014-05-22 20:59:29 +00004550
4551 // The instantiation might have been resolved to a partial
4552 // specialization. If so, record which one.
4553 auto From = Spec->getInstantiatedFrom();
4554 if (auto PartialSpec =
4555 From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) {
4556 Record.push_back(true);
4557 AddDeclRef(PartialSpec, Record);
4558 AddTemplateArgumentList(&Spec->getTemplateInstantiationArgs(),
4559 Record);
4560 } else {
4561 Record.push_back(false);
4562 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00004563 }
4564 Record.push_back(RD->getTagKind());
4565 AddSourceLocation(RD->getLocation(), Record);
4566 AddSourceLocation(RD->getLocStart(), Record);
4567 AddSourceLocation(RD->getRBraceLoc(), Record);
4568
4569 // Instantiation may change attributes; write them all out afresh.
4570 Record.push_back(D->hasAttrs());
4571 if (Record.back())
Craig Topper8c2a2a02014-08-30 16:55:39 +00004572 WriteAttributes(llvm::makeArrayRef(D->getAttrs().begin(),
4573 D->getAttrs().size()), Record);
Richard Smithcd45dbc2014-04-19 03:48:30 +00004574
4575 // FIXME: Ensure we don't get here for explicit instantiations.
4576 break;
4577 }
4578
Richard Smithf8134002015-03-10 01:41:22 +00004579 case UPD_CXX_RESOLVED_DTOR_DELETE:
4580 AddDeclRef(Update.getDecl(), Record);
4581 break;
4582
Richard Smith564417a2014-03-20 21:47:22 +00004583 case UPD_CXX_RESOLVED_EXCEPTION_SPEC:
4584 addExceptionSpec(
4585 *this,
4586 cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>(),
4587 Record);
4588 break;
4589
Richard Smith6ef42932014-03-20 21:02:00 +00004590 case UPD_CXX_DEDUCED_RETURN_TYPE:
4591 Record.push_back(GetOrCreateTypeID(Update.getType()));
4592 break;
4593
4594 case UPD_DECL_MARKED_USED:
4595 break;
Richard Smith5652c0f2014-03-21 01:48:23 +00004596
4597 case UPD_MANGLING_NUMBER:
4598 case UPD_STATIC_LOCAL_NUMBER:
4599 Record.push_back(Update.getNumber());
4600 break;
Richard Smith65ebb4a2015-03-26 04:09:53 +00004601
Alexey Bataev97720002014-11-11 04:05:39 +00004602 case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
4603 AddSourceRange(D->getAttr<OMPThreadPrivateDeclAttr>()->getRange(),
4604 Record);
4605 break;
Richard Smith65ebb4a2015-03-26 04:09:53 +00004606
4607 case UPD_DECL_EXPORTED:
4608 Record.push_back(inferSubmoduleIDFromLocation(Update.getLoc()));
4609 break;
Richard Smith6ef42932014-03-20 21:02:00 +00004610 }
4611 }
4612
Richard Smithd28ac5b2014-03-22 23:33:22 +00004613 if (HasUpdatedBody) {
4614 const FunctionDecl *Def = cast<FunctionDecl>(D);
Richard Smith4d235792014-08-07 18:53:08 +00004615 Record.push_back(UPD_CXX_ADDED_FUNCTION_DEFINITION);
Richard Smithd28ac5b2014-03-22 23:33:22 +00004616 Record.push_back(Def->isInlined());
4617 AddSourceLocation(Def->getInnerLocStart(), Record);
4618 AddFunctionDefinition(Def, Record);
4619 }
4620
Richard Smithcd45dbc2014-04-19 03:48:30 +00004621 OffsetsRecord.push_back(GetDeclRef(D));
4622 OffsetsRecord.push_back(Stream.GetCurrentBitNo());
4623
Richard Smith6ef42932014-03-20 21:02:00 +00004624 Stream.EmitRecord(DECL_UPDATES, Record);
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00004625
Richard Smithc2bb8182015-03-24 06:36:48 +00004626 FlushPendingAfterDecl();
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00004627 }
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00004628}
4629
Argyrios Kyrtzidis97bfda92010-10-24 17:26:43 +00004630void ASTWriter::WriteDeclReplacementsBlock() {
Sebastian Redle7c1fe62010-08-13 00:28:03 +00004631 if (ReplacedDecls.empty())
4632 return;
4633
4634 RecordData Record;
Craig Topper2341c0d2013-07-04 03:08:24 +00004635 for (SmallVectorImpl<ReplacedDeclInfo>::iterator
4636 I = ReplacedDecls.begin(), E = ReplacedDecls.end(); I != E; ++I) {
Argyrios Kyrtzidis6fb60032011-10-31 07:20:15 +00004637 Record.push_back(I->ID);
4638 Record.push_back(I->Offset);
4639 Record.push_back(I->Loc);
Sebastian Redle7c1fe62010-08-13 00:28:03 +00004640 }
Sebastian Redl539c5062010-08-18 23:57:32 +00004641 Stream.EmitRecord(DECL_REPLACEMENTS, Record);
Sebastian Redle7c1fe62010-08-13 00:28:03 +00004642}
4643
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004644void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004645 Record.push_back(Loc.getRawEncoding());
4646}
4647
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004648void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
Chris Lattnerca025db2010-05-07 21:43:38 +00004649 AddSourceLocation(Range.getBegin(), Record);
4650 AddSourceLocation(Range.getEnd(), Record);
4651}
4652
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004653void ASTWriter::AddAPInt(const llvm::APInt &Value, RecordDataImpl &Record) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004654 Record.push_back(Value.getBitWidth());
Benjamin Kramer25f9ea62010-09-06 23:43:28 +00004655 const uint64_t *Words = Value.getRawData();
4656 Record.append(Words, Words + Value.getNumWords());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004657}
4658
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004659void ASTWriter::AddAPSInt(const llvm::APSInt &Value, RecordDataImpl &Record) {
Douglas Gregor1daeb692009-04-13 18:14:40 +00004660 Record.push_back(Value.isUnsigned());
4661 AddAPInt(Value, Record);
4662}
4663
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004664void ASTWriter::AddAPFloat(const llvm::APFloat &Value, RecordDataImpl &Record) {
Douglas Gregore0a3a512009-04-14 21:55:33 +00004665 AddAPInt(Value.bitcastToAPInt(), Record);
4666}
4667
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004668void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
Douglas Gregor4621c6a2009-04-22 18:49:13 +00004669 Record.push_back(getIdentifierRef(II));
4670}
4671
Sebastian Redl539c5062010-08-18 23:57:32 +00004672IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
Craig Toppera13603a2014-05-22 05:54:18 +00004673 if (!II)
Douglas Gregor4621c6a2009-04-22 18:49:13 +00004674 return 0;
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00004675
Sebastian Redl539c5062010-08-18 23:57:32 +00004676 IdentID &ID = IdentifierIDs[II];
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00004677 if (ID == 0)
Sebastian Redlff4a2952010-07-23 23:49:55 +00004678 ID = NextIdentID++;
Douglas Gregor4621c6a2009-04-22 18:49:13 +00004679 return ID;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004680}
4681
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00004682MacroID ASTWriter::getMacroRef(MacroInfo *MI, const IdentifierInfo *Name) {
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00004683 // Don't emit builtin macros like __LINE__ to the AST file unless they
4684 // have been redefined by the header (in which case they are not
4685 // isBuiltinMacro).
Craig Toppera13603a2014-05-22 05:54:18 +00004686 if (!MI || MI->isBuiltinMacro())
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00004687 return 0;
4688
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00004689 MacroID &ID = MacroIDs[MI];
4690 if (ID == 0) {
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00004691 ID = NextMacroID++;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00004692 MacroInfoToEmitData Info = { Name, MI, ID };
4693 MacroInfosToEmit.push_back(Info);
4694 }
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00004695 return ID;
4696}
4697
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00004698MacroID ASTWriter::getMacroID(MacroInfo *MI) {
Craig Toppera13603a2014-05-22 05:54:18 +00004699 if (!MI || MI->isBuiltinMacro())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00004700 return 0;
4701
4702 assert(MacroIDs.find(MI) != MacroIDs.end() && "Macro not emitted!");
4703 return MacroIDs[MI];
4704}
4705
4706uint64_t ASTWriter::getMacroDirectivesOffset(const IdentifierInfo *Name) {
Richard Smithd7329392015-04-21 21:46:32 +00004707 return IdentMacroDirectivesOffsetMap.lookup(Name);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00004708}
4709
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004710void ASTWriter::AddSelectorRef(const Selector SelRef, RecordDataImpl &Record) {
Sebastian Redl834bb972010-08-04 17:20:04 +00004711 Record.push_back(getSelectorRef(SelRef));
4712}
4713
Sebastian Redl539c5062010-08-18 23:57:32 +00004714SelectorID ASTWriter::getSelectorRef(Selector Sel) {
Craig Toppera13603a2014-05-22 05:54:18 +00004715 if (Sel.getAsOpaquePtr() == nullptr) {
Sebastian Redl834bb972010-08-04 17:20:04 +00004716 return 0;
Steve Naroff2ddea052009-04-23 10:39:46 +00004717 }
4718
Douglas Gregor8d7edce2013-02-08 21:30:59 +00004719 SelectorID SID = SelectorIDs[Sel];
Sebastian Redld95a56e2010-08-04 18:21:41 +00004720 if (SID == 0 && Chain) {
4721 // This might trigger a ReadSelector callback, which will set the ID for
4722 // this selector.
4723 Chain->LoadSelector(Sel);
Douglas Gregor8d7edce2013-02-08 21:30:59 +00004724 SID = SelectorIDs[Sel];
Sebastian Redld95a56e2010-08-04 18:21:41 +00004725 }
Steve Naroff2ddea052009-04-23 10:39:46 +00004726 if (SID == 0) {
Sebastian Redld95a56e2010-08-04 18:21:41 +00004727 SID = NextSelectorID++;
Douglas Gregor8d7edce2013-02-08 21:30:59 +00004728 SelectorIDs[Sel] = SID;
Steve Naroff2ddea052009-04-23 10:39:46 +00004729 }
Sebastian Redl834bb972010-08-04 17:20:04 +00004730 return SID;
Steve Naroff2ddea052009-04-23 10:39:46 +00004731}
4732
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004733void ASTWriter::AddCXXTemporary(const CXXTemporary *Temp, RecordDataImpl &Record) {
Chris Lattnercba86142010-05-10 00:25:06 +00004734 AddDeclRef(Temp->getDestructor(), Record);
4735}
4736
Richard Smithc2bb8182015-03-24 06:36:48 +00004737void ASTWriter::AddCXXCtorInitializersRef(ArrayRef<CXXCtorInitializer *> Inits,
4738 RecordDataImpl &Record) {
4739 assert(!Inits.empty() && "Empty ctor initializer sets are not recorded");
4740 CXXCtorInitializersToWrite.push_back(
4741 QueuedCXXCtorInitializers(NextCXXCtorInitializersID, Inits));
4742 Record.push_back(NextCXXCtorInitializersID++);
4743}
4744
Douglas Gregord4c5ed02010-10-29 22:39:52 +00004745void ASTWriter::AddCXXBaseSpecifiersRef(CXXBaseSpecifier const *Bases,
Richard Smithc2bb8182015-03-24 06:36:48 +00004746 CXXBaseSpecifier const *BasesEnd,
Douglas Gregord4c5ed02010-10-29 22:39:52 +00004747 RecordDataImpl &Record) {
4748 assert(Bases != BasesEnd && "Empty base-specifier sets are not recorded");
4749 CXXBaseSpecifiersToWrite.push_back(
4750 QueuedCXXBaseSpecifiers(NextCXXBaseSpecifiersID,
4751 Bases, BasesEnd));
4752 Record.push_back(NextCXXBaseSpecifiersID++);
4753}
4754
Sebastian Redl55c0ad52010-08-18 23:56:21 +00004755void ASTWriter::AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00004756 const TemplateArgumentLocInfo &Arg,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004757 RecordDataImpl &Record) {
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00004758 switch (Kind) {
John McCall0ad16662009-10-29 08:12:44 +00004759 case TemplateArgument::Expression:
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00004760 AddStmt(Arg.getAsExpr());
John McCall0ad16662009-10-29 08:12:44 +00004761 break;
4762 case TemplateArgument::Type:
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00004763 AddTypeSourceInfo(Arg.getAsTypeSourceInfo(), Record);
John McCall0ad16662009-10-29 08:12:44 +00004764 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004765 case TemplateArgument::Template:
Douglas Gregor9d802122011-03-02 17:09:35 +00004766 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record);
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00004767 AddSourceLocation(Arg.getTemplateNameLoc(), Record);
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004768 break;
4769 case TemplateArgument::TemplateExpansion:
Douglas Gregor9d802122011-03-02 17:09:35 +00004770 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record);
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004771 AddSourceLocation(Arg.getTemplateNameLoc(), Record);
Douglas Gregoreb29d182011-01-05 17:40:24 +00004772 AddSourceLocation(Arg.getTemplateEllipsisLoc(), Record);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004773 break;
John McCall0ad16662009-10-29 08:12:44 +00004774 case TemplateArgument::Null:
4775 case TemplateArgument::Integral:
4776 case TemplateArgument::Declaration:
Eli Friedmanb826a002012-09-26 02:36:12 +00004777 case TemplateArgument::NullPtr:
John McCall0ad16662009-10-29 08:12:44 +00004778 case TemplateArgument::Pack:
Eli Friedmanb826a002012-09-26 02:36:12 +00004779 // FIXME: Is this right?
John McCall0ad16662009-10-29 08:12:44 +00004780 break;
4781 }
4782}
4783
Sebastian Redl55c0ad52010-08-18 23:56:21 +00004784void ASTWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004785 RecordDataImpl &Record) {
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00004786 AddTemplateArgument(Arg.getArgument(), Record);
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00004787
4788 if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
4789 bool InfoHasSameExpr
4790 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
4791 Record.push_back(InfoHasSameExpr);
4792 if (InfoHasSameExpr)
4793 return; // Avoid storing the same expr twice.
4794 }
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00004795 AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo(),
4796 Record);
4797}
4798
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004799void ASTWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo,
4800 RecordDataImpl &Record) {
Craig Toppera13603a2014-05-22 05:54:18 +00004801 if (!TInfo) {
John McCall8f115c62009-10-16 21:56:05 +00004802 AddTypeRef(QualType(), Record);
4803 return;
4804 }
4805
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004806 AddTypeLoc(TInfo->getTypeLoc(), Record);
4807}
4808
4809void ASTWriter::AddTypeLoc(TypeLoc TL, RecordDataImpl &Record) {
4810 AddTypeRef(TL.getType(), Record);
4811
John McCall8f115c62009-10-16 21:56:05 +00004812 TypeLocWriter TLW(*this, Record);
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004813 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00004814 TLW.Visit(TL);
John McCall8f115c62009-10-16 21:56:05 +00004815}
4816
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004817void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
Argyrios Kyrtzidis9ab44ea2010-08-20 16:04:14 +00004818 Record.push_back(GetOrCreateTypeID(T));
4819}
4820
Richard Smith2095ffe2015-03-16 20:11:03 +00004821TypeID ASTWriter::GetOrCreateTypeID(QualType T) {
Richard Smith1fa5d642013-05-11 05:45:24 +00004822 assert(Context);
Richard Smith2095ffe2015-03-16 20:11:03 +00004823 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
4824 if (T.isNull())
4825 return TypeIdx();
4826 assert(!T.getLocalFastQualifiers());
4827
4828 TypeIdx &Idx = TypeIdxs[T];
4829 if (Idx.getIndex() == 0) {
4830 if (DoneWritingDeclsAndTypes) {
4831 assert(0 && "New type seen after serializing all the types to emit!");
4832 return TypeIdx();
4833 }
4834
4835 // We haven't seen this type before. Assign it a new ID and put it
4836 // into the queue of types to emit.
4837 Idx = TypeIdx(NextTypeID++);
4838 DeclTypesToEmit.push(T);
4839 }
4840 return Idx;
4841 });
Argyrios Kyrtzidis082e4612010-08-20 16:04:20 +00004842}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004843
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00004844TypeID ASTWriter::getTypeID(QualType T) const {
Richard Smith1fa5d642013-05-11 05:45:24 +00004845 assert(Context);
Richard Smith2095ffe2015-03-16 20:11:03 +00004846 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
4847 if (T.isNull())
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004848 return TypeIdx();
Richard Smith2095ffe2015-03-16 20:11:03 +00004849 assert(!T.getLocalFastQualifiers());
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004850
Richard Smith2095ffe2015-03-16 20:11:03 +00004851 TypeIdxMap::const_iterator I = TypeIdxs.find(T);
4852 assert(I != TypeIdxs.end() && "Type not emitted!");
4853 return I->second;
4854 });
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004855}
4856
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00004857void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
Sebastian Redl66c5eef2010-07-27 00:17:23 +00004858 Record.push_back(GetDeclRef(D));
4859}
4860
Sebastian Redl539c5062010-08-18 23:57:32 +00004861DeclID ASTWriter::GetDeclRef(const Decl *D) {
Douglas Gregor2fd3d402011-09-17 00:05:03 +00004862 assert(WritingAST && "Cannot request a declaration ID before AST writing");
Craig Toppera13603a2014-05-22 05:54:18 +00004863
4864 if (!D) {
Sebastian Redl66c5eef2010-07-27 00:17:23 +00004865 return 0;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004866 }
Douglas Gregorb3163e52012-01-05 22:33:30 +00004867
4868 // If D comes from an AST file, its declaration ID is already known and
4869 // fixed.
4870 if (D->isFromASTFile())
4871 return D->getGlobalID();
4872
Douglas Gregor9b3932c2010-10-05 18:37:06 +00004873 assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
Sebastian Redl539c5062010-08-18 23:57:32 +00004874 DeclID &ID = DeclIDs[D];
Mike Stump11289f42009-09-09 15:08:12 +00004875 if (ID == 0) {
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004876 if (DoneWritingDeclsAndTypes) {
4877 assert(0 && "New decl seen after serializing all the decls to emit!");
4878 return 0;
4879 }
4880
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004881 // We haven't seen this declaration before. Give it a new ID and
4882 // enqueue it in the list of declarations to emit.
Sebastian Redlff4a2952010-07-23 23:49:55 +00004883 ID = NextDeclID++;
Douglas Gregor12bfa382009-10-17 00:13:19 +00004884 DeclTypesToEmit.push(const_cast<Decl *>(D));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004885 }
4886
Sebastian Redl66c5eef2010-07-27 00:17:23 +00004887 return ID;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004888}
4889
Sebastian Redl539c5062010-08-18 23:57:32 +00004890DeclID ASTWriter::getDeclID(const Decl *D) {
Craig Toppera13603a2014-05-22 05:54:18 +00004891 if (!D)
Douglas Gregore84a9da2009-04-20 20:36:09 +00004892 return 0;
4893
Douglas Gregorb3163e52012-01-05 22:33:30 +00004894 // If D comes from an AST file, its declaration ID is already known and
4895 // fixed.
4896 if (D->isFromASTFile())
4897 return D->getGlobalID();
4898
Douglas Gregore84a9da2009-04-20 20:36:09 +00004899 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
4900 return DeclIDs[D];
4901}
4902
Argyrios Kyrtzidisdf53da82011-10-28 23:57:43 +00004903void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) {
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004904 assert(ID);
Argyrios Kyrtzidisdf53da82011-10-28 23:57:43 +00004905 assert(D);
4906
4907 SourceLocation Loc = D->getLocation();
4908 if (Loc.isInvalid())
4909 return;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004910
4911 // We only keep track of the file-level declarations of each file.
4912 if (!D->getLexicalDeclContext()->isFileContext())
4913 return;
Argyrios Kyrtzidise1bc99e2012-02-24 19:45:46 +00004914 // FIXME: ParmVarDecls that are part of a function type of a parameter of
4915 // a function/objc method, should not have TU as lexical context.
Argyrios Kyrtzidisffe055a82012-02-24 01:12:38 +00004916 if (isa<ParmVarDecl>(D))
4917 return;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004918
4919 SourceManager &SM = Context->getSourceManager();
Argyrios Kyrtzidisdf53da82011-10-28 23:57:43 +00004920 SourceLocation FileLoc = SM.getFileLoc(Loc);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004921 assert(SM.isLocalSourceLocation(FileLoc));
Argyrios Kyrtzidis7362e9b2011-10-28 23:57:47 +00004922 FileID FID;
4923 unsigned Offset;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00004924 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004925 if (FID.isInvalid())
4926 return;
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00004927 assert(SM.getSLocEntry(FID).isFile());
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004928
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00004929 DeclIDInFileInfo *&Info = FileDeclIDs[FID];
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004930 if (!Info)
4931 Info = new DeclIDInFileInfo();
4932
Argyrios Kyrtzidis7362e9b2011-10-28 23:57:47 +00004933 std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004934 LocDeclIDsTy &Decls = Info->DeclIDs;
4935
Argyrios Kyrtzidis7362e9b2011-10-28 23:57:47 +00004936 if (Decls.empty() || Decls.back().first <= Offset) {
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004937 Decls.push_back(LocDecl);
4938 return;
4939 }
4940
Benjamin Kramer45025c02013-08-24 13:22:59 +00004941 LocDeclIDsTy::iterator I =
4942 std::upper_bound(Decls.begin(), Decls.end(), LocDecl, llvm::less_first());
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004943
4944 Decls.insert(I, LocDecl);
4945}
4946
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004947void ASTWriter::AddDeclarationName(DeclarationName Name, RecordDataImpl &Record) {
Chris Lattner258172e2009-04-27 07:35:58 +00004948 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004949 Record.push_back(Name.getNameKind());
4950 switch (Name.getNameKind()) {
4951 case DeclarationName::Identifier:
4952 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
4953 break;
4954
4955 case DeclarationName::ObjCZeroArgSelector:
4956 case DeclarationName::ObjCOneArgSelector:
4957 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff2ddea052009-04-23 10:39:46 +00004958 AddSelectorRef(Name.getObjCSelector(), Record);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004959 break;
4960
4961 case DeclarationName::CXXConstructorName:
4962 case DeclarationName::CXXDestructorName:
4963 case DeclarationName::CXXConversionFunctionName:
4964 AddTypeRef(Name.getCXXNameType(), Record);
4965 break;
4966
4967 case DeclarationName::CXXOperatorName:
4968 Record.push_back(Name.getCXXOverloadedOperator());
4969 break;
4970
Alexis Hunt3d221f22009-11-29 07:34:05 +00004971 case DeclarationName::CXXLiteralOperatorName:
4972 AddIdentifierRef(Name.getCXXLiteralIdentifier(), Record);
4973 break;
4974
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004975 case DeclarationName::CXXUsingDirective:
4976 // No extra data to emit
4977 break;
4978 }
4979}
Chris Lattnerca025db2010-05-07 21:43:38 +00004980
Richard Smithd08aeb62014-08-28 01:33:39 +00004981unsigned ASTWriter::getAnonymousDeclarationNumber(const NamedDecl *D) {
4982 assert(needsAnonymousDeclarationNumber(D) &&
4983 "expected an anonymous declaration");
4984
4985 // Number the anonymous declarations within this context, if we've not
4986 // already done so.
4987 auto It = AnonymousDeclarationNumbers.find(D);
4988 if (It == AnonymousDeclarationNumbers.end()) {
Richard Smith2b560572015-02-07 03:11:11 +00004989 auto *DC = D->getLexicalDeclContext();
4990 numberAnonymousDeclsWithin(DC, [&](const NamedDecl *ND, unsigned Number) {
4991 AnonymousDeclarationNumbers[ND] = Number;
4992 });
Richard Smithd08aeb62014-08-28 01:33:39 +00004993
4994 It = AnonymousDeclarationNumbers.find(D);
4995 assert(It != AnonymousDeclarationNumbers.end() &&
4996 "declaration not found within its lexical context");
4997 }
4998
4999 return It->second;
5000}
5001
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005002void ASTWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005003 DeclarationName Name, RecordDataImpl &Record) {
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005004 switch (Name.getNameKind()) {
5005 case DeclarationName::CXXConstructorName:
5006 case DeclarationName::CXXDestructorName:
5007 case DeclarationName::CXXConversionFunctionName:
5008 AddTypeSourceInfo(DNLoc.NamedType.TInfo, Record);
5009 break;
5010
5011 case DeclarationName::CXXOperatorName:
5012 AddSourceLocation(
5013 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.BeginOpNameLoc),
5014 Record);
5015 AddSourceLocation(
5016 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc),
5017 Record);
5018 break;
5019
5020 case DeclarationName::CXXLiteralOperatorName:
5021 AddSourceLocation(
5022 SourceLocation::getFromRawEncoding(DNLoc.CXXLiteralOperatorName.OpNameLoc),
5023 Record);
5024 break;
5025
5026 case DeclarationName::Identifier:
5027 case DeclarationName::ObjCZeroArgSelector:
5028 case DeclarationName::ObjCOneArgSelector:
5029 case DeclarationName::ObjCMultiArgSelector:
5030 case DeclarationName::CXXUsingDirective:
5031 break;
5032 }
5033}
5034
5035void ASTWriter::AddDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005036 RecordDataImpl &Record) {
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005037 AddDeclarationName(NameInfo.getName(), Record);
5038 AddSourceLocation(NameInfo.getLoc(), Record);
5039 AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName(), Record);
5040}
5041
5042void ASTWriter::AddQualifierInfo(const QualifierInfo &Info,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005043 RecordDataImpl &Record) {
Douglas Gregor14454802011-02-25 02:25:35 +00005044 AddNestedNameSpecifierLoc(Info.QualifierLoc, Record);
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005045 Record.push_back(Info.NumTemplParamLists);
5046 for (unsigned i=0, e=Info.NumTemplParamLists; i != e; ++i)
5047 AddTemplateParameterList(Info.TemplParamLists[i], Record);
5048}
5049
Sebastian Redl55c0ad52010-08-18 23:56:21 +00005050void ASTWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005051 RecordDataImpl &Record) {
Chris Lattnerca025db2010-05-07 21:43:38 +00005052 // Nested name specifiers usually aren't too long. I think that 8 would
Chris Lattner57540c52011-04-15 05:22:18 +00005053 // typically accommodate the vast majority.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005054 SmallVector<NestedNameSpecifier *, 8> NestedNames;
Chris Lattnerca025db2010-05-07 21:43:38 +00005055
5056 // Push each of the NNS's onto a stack for serialization in reverse order.
5057 while (NNS) {
5058 NestedNames.push_back(NNS);
5059 NNS = NNS->getPrefix();
5060 }
5061
5062 Record.push_back(NestedNames.size());
5063 while(!NestedNames.empty()) {
5064 NNS = NestedNames.pop_back_val();
5065 NestedNameSpecifier::SpecifierKind Kind = NNS->getKind();
5066 Record.push_back(Kind);
5067 switch (Kind) {
5068 case NestedNameSpecifier::Identifier:
5069 AddIdentifierRef(NNS->getAsIdentifier(), Record);
5070 break;
5071
5072 case NestedNameSpecifier::Namespace:
5073 AddDeclRef(NNS->getAsNamespace(), Record);
5074 break;
5075
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005076 case NestedNameSpecifier::NamespaceAlias:
5077 AddDeclRef(NNS->getAsNamespaceAlias(), Record);
5078 break;
5079
Chris Lattnerca025db2010-05-07 21:43:38 +00005080 case NestedNameSpecifier::TypeSpec:
5081 case NestedNameSpecifier::TypeSpecWithTemplate:
5082 AddTypeRef(QualType(NNS->getAsType(), 0), Record);
5083 Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5084 break;
5085
5086 case NestedNameSpecifier::Global:
5087 // Don't need to write an associated value.
5088 break;
Nikola Smiljanic67860242014-09-26 00:28:20 +00005089
5090 case NestedNameSpecifier::Super:
5091 AddDeclRef(NNS->getAsRecordDecl(), Record);
5092 break;
Chris Lattnerca025db2010-05-07 21:43:38 +00005093 }
5094 }
5095}
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005096
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005097void ASTWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
5098 RecordDataImpl &Record) {
5099 // Nested name specifiers usually aren't too long. I think that 8 would
Chris Lattner57540c52011-04-15 05:22:18 +00005100 // typically accommodate the vast majority.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005101 SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005102
5103 // Push each of the nested-name-specifiers's onto a stack for
5104 // serialization in reverse order.
5105 while (NNS) {
5106 NestedNames.push_back(NNS);
5107 NNS = NNS.getPrefix();
5108 }
5109
5110 Record.push_back(NestedNames.size());
5111 while(!NestedNames.empty()) {
5112 NNS = NestedNames.pop_back_val();
5113 NestedNameSpecifier::SpecifierKind Kind
5114 = NNS.getNestedNameSpecifier()->getKind();
5115 Record.push_back(Kind);
5116 switch (Kind) {
5117 case NestedNameSpecifier::Identifier:
5118 AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier(), Record);
5119 AddSourceRange(NNS.getLocalSourceRange(), Record);
5120 break;
5121
5122 case NestedNameSpecifier::Namespace:
5123 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace(), Record);
5124 AddSourceRange(NNS.getLocalSourceRange(), Record);
5125 break;
5126
5127 case NestedNameSpecifier::NamespaceAlias:
5128 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias(), Record);
5129 AddSourceRange(NNS.getLocalSourceRange(), Record);
5130 break;
5131
5132 case NestedNameSpecifier::TypeSpec:
5133 case NestedNameSpecifier::TypeSpecWithTemplate:
5134 Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5135 AddTypeLoc(NNS.getTypeLoc(), Record);
5136 AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record);
5137 break;
5138
5139 case NestedNameSpecifier::Global:
5140 AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record);
5141 break;
Nikola Smiljanic67860242014-09-26 00:28:20 +00005142
5143 case NestedNameSpecifier::Super:
5144 AddDeclRef(NNS.getNestedNameSpecifier()->getAsRecordDecl(), Record);
5145 AddSourceRange(NNS.getLocalSourceRange(), Record);
5146 break;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005147 }
5148 }
5149}
5150
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005151void ASTWriter::AddTemplateName(TemplateName Name, RecordDataImpl &Record) {
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005152 TemplateName::NameKind Kind = Name.getKind();
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005153 Record.push_back(Kind);
5154 switch (Kind) {
5155 case TemplateName::Template:
5156 AddDeclRef(Name.getAsTemplateDecl(), Record);
5157 break;
5158
5159 case TemplateName::OverloadedTemplate: {
5160 OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate();
5161 Record.push_back(OvT->size());
5162 for (OverloadedTemplateStorage::iterator I = OvT->begin(), E = OvT->end();
5163 I != E; ++I)
5164 AddDeclRef(*I, Record);
5165 break;
5166 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005167
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005168 case TemplateName::QualifiedTemplate: {
5169 QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName();
5170 AddNestedNameSpecifier(QualT->getQualifier(), Record);
5171 Record.push_back(QualT->hasTemplateKeyword());
5172 AddDeclRef(QualT->getTemplateDecl(), Record);
5173 break;
5174 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005175
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005176 case TemplateName::DependentTemplate: {
5177 DependentTemplateName *DepT = Name.getAsDependentTemplateName();
5178 AddNestedNameSpecifier(DepT->getQualifier(), Record);
5179 Record.push_back(DepT->isIdentifier());
5180 if (DepT->isIdentifier())
5181 AddIdentifierRef(DepT->getIdentifier(), Record);
5182 else
5183 Record.push_back(DepT->getOperator());
5184 break;
5185 }
John McCalld9dfe3a2011-06-30 08:33:18 +00005186
5187 case TemplateName::SubstTemplateTemplateParm: {
5188 SubstTemplateTemplateParmStorage *subst
5189 = Name.getAsSubstTemplateTemplateParm();
5190 AddDeclRef(subst->getParameter(), Record);
5191 AddTemplateName(subst->getReplacement(), Record);
5192 break;
5193 }
Douglas Gregor5590be02011-01-15 06:45:20 +00005194
5195 case TemplateName::SubstTemplateTemplateParmPack: {
5196 SubstTemplateTemplateParmPackStorage *SubstPack
5197 = Name.getAsSubstTemplateTemplateParmPack();
5198 AddDeclRef(SubstPack->getParameterPack(), Record);
5199 AddTemplateArgument(SubstPack->getArgumentPack(), Record);
5200 break;
5201 }
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005202 }
5203}
5204
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005205void ASTWriter::AddTemplateArgument(const TemplateArgument &Arg,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005206 RecordDataImpl &Record) {
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005207 Record.push_back(Arg.getKind());
5208 switch (Arg.getKind()) {
5209 case TemplateArgument::Null:
5210 break;
5211 case TemplateArgument::Type:
5212 AddTypeRef(Arg.getAsType(), Record);
5213 break;
5214 case TemplateArgument::Declaration:
5215 AddDeclRef(Arg.getAsDecl(), Record);
David Blaikie952a9b12014-10-17 18:00:12 +00005216 AddTypeRef(Arg.getParamTypeForDecl(), Record);
Eli Friedmanb826a002012-09-26 02:36:12 +00005217 break;
5218 case TemplateArgument::NullPtr:
5219 AddTypeRef(Arg.getNullPtrType(), Record);
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005220 break;
5221 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005222 AddAPSInt(Arg.getAsIntegral(), Record);
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005223 AddTypeRef(Arg.getIntegralType(), Record);
5224 break;
5225 case TemplateArgument::Template:
Douglas Gregore1d60df2011-01-14 23:41:42 +00005226 AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record);
5227 break;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005228 case TemplateArgument::TemplateExpansion:
5229 AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record);
David Blaikie05785d12013-02-20 22:23:23 +00005230 if (Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions())
Douglas Gregore1d60df2011-01-14 23:41:42 +00005231 Record.push_back(*NumExpansions + 1);
5232 else
5233 Record.push_back(0);
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005234 break;
5235 case TemplateArgument::Expression:
5236 AddStmt(Arg.getAsExpr());
5237 break;
5238 case TemplateArgument::Pack:
5239 Record.push_back(Arg.pack_size());
Aaron Ballman2a89e852014-07-15 21:32:31 +00005240 for (const auto &P : Arg.pack_elements())
5241 AddTemplateArgument(P, Record);
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005242 break;
5243 }
5244}
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005245
5246void
Sebastian Redl55c0ad52010-08-18 23:56:21 +00005247ASTWriter::AddTemplateParameterList(const TemplateParameterList *TemplateParams,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005248 RecordDataImpl &Record) {
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005249 assert(TemplateParams && "No TemplateParams!");
5250 AddSourceLocation(TemplateParams->getTemplateLoc(), Record);
5251 AddSourceLocation(TemplateParams->getLAngleLoc(), Record);
5252 AddSourceLocation(TemplateParams->getRAngleLoc(), Record);
5253 Record.push_back(TemplateParams->size());
5254 for (TemplateParameterList::const_iterator
5255 P = TemplateParams->begin(), PEnd = TemplateParams->end();
5256 P != PEnd; ++P)
5257 AddDeclRef(*P, Record);
5258}
5259
5260/// \brief Emit a template argument list.
5261void
Sebastian Redl55c0ad52010-08-18 23:56:21 +00005262ASTWriter::AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005263 RecordDataImpl &Record) {
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005264 assert(TemplateArgs && "No TemplateArgs!");
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005265 Record.push_back(TemplateArgs->size());
5266 for (int i=0, e = TemplateArgs->size(); i != e; ++i)
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005267 AddTemplateArgument(TemplateArgs->get(i), Record);
5268}
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005269
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005270void
5271ASTWriter::AddASTTemplateArgumentListInfo
5272(const ASTTemplateArgumentListInfo *ASTTemplArgList, RecordDataImpl &Record) {
5273 assert(ASTTemplArgList && "No ASTTemplArgList!");
5274 AddSourceLocation(ASTTemplArgList->LAngleLoc, Record);
5275 AddSourceLocation(ASTTemplArgList->RAngleLoc, Record);
5276 Record.push_back(ASTTemplArgList->NumTemplateArgs);
5277 const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs();
5278 for (int i=0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i)
5279 AddTemplateArgumentLoc(TemplArgs[i], Record);
5280}
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005281
5282void
Argyrios Kyrtzidis0f05fb92012-11-28 03:56:16 +00005283ASTWriter::AddUnresolvedSet(const ASTUnresolvedSet &Set, RecordDataImpl &Record) {
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005284 Record.push_back(Set.size());
Argyrios Kyrtzidis0f05fb92012-11-28 03:56:16 +00005285 for (ASTUnresolvedSet::const_iterator
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005286 I = Set.begin(), E = Set.end(); I != E; ++I) {
5287 AddDeclRef(I.getDecl(), Record);
5288 Record.push_back(I.getAccess());
5289 }
5290}
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00005291
Sebastian Redl55c0ad52010-08-18 23:56:21 +00005292void ASTWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005293 RecordDataImpl &Record) {
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00005294 Record.push_back(Base.isVirtual());
5295 Record.push_back(Base.isBaseOfClass());
5296 Record.push_back(Base.getAccessSpecifierAsWritten());
Sebastian Redl08905022011-02-05 19:23:19 +00005297 Record.push_back(Base.getInheritConstructors());
Nick Lewycky19b9f952010-07-26 16:56:01 +00005298 AddTypeSourceInfo(Base.getTypeSourceInfo(), Record);
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00005299 AddSourceRange(Base.getSourceRange(), Record);
Douglas Gregor752a5952011-01-03 22:36:02 +00005300 AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
5301 : SourceLocation(),
5302 Record);
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00005303}
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00005304
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005305void ASTWriter::FlushCXXBaseSpecifiers() {
5306 RecordData Record;
Richard Smithc2bb8182015-03-24 06:36:48 +00005307 unsigned N = CXXBaseSpecifiersToWrite.size();
5308 for (unsigned I = 0; I != N; ++I) {
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005309 Record.clear();
5310
5311 // Record the offset of this base-specifier set.
Douglas Gregorc27b2872011-08-04 00:01:48 +00005312 unsigned Index = CXXBaseSpecifiersToWrite[I].ID - 1;
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005313 if (Index == CXXBaseSpecifiersOffsets.size())
5314 CXXBaseSpecifiersOffsets.push_back(Stream.GetCurrentBitNo());
5315 else {
5316 if (Index > CXXBaseSpecifiersOffsets.size())
5317 CXXBaseSpecifiersOffsets.resize(Index + 1);
5318 CXXBaseSpecifiersOffsets[Index] = Stream.GetCurrentBitNo();
5319 }
5320
5321 const CXXBaseSpecifier *B = CXXBaseSpecifiersToWrite[I].Bases,
5322 *BEnd = CXXBaseSpecifiersToWrite[I].BasesEnd;
5323 Record.push_back(BEnd - B);
5324 for (; B != BEnd; ++B)
5325 AddCXXBaseSpecifier(*B, Record);
5326 Stream.EmitRecord(serialization::DECL_CXX_BASE_SPECIFIERS, Record);
Douglas Gregord5853042010-10-30 04:28:16 +00005327
5328 // Flush any expressions that were written as part of the base specifiers.
5329 FlushStmts();
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005330 }
5331
Richard Smithc2bb8182015-03-24 06:36:48 +00005332 assert(N == CXXBaseSpecifiersToWrite.size() &&
5333 "added more base specifiers while writing base specifiers");
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005334 CXXBaseSpecifiersToWrite.clear();
5335}
5336
Alexis Hunt1d792652011-01-08 20:30:50 +00005337void ASTWriter::AddCXXCtorInitializers(
5338 const CXXCtorInitializer * const *CtorInitializers,
5339 unsigned NumCtorInitializers,
5340 RecordDataImpl &Record) {
5341 Record.push_back(NumCtorInitializers);
5342 for (unsigned i=0; i != NumCtorInitializers; ++i) {
5343 const CXXCtorInitializer *Init = CtorInitializers[i];
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005344
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005345 if (Init->isBaseInitializer()) {
Alexis Hunt37a477f2011-05-04 01:19:08 +00005346 Record.push_back(CTOR_INITIALIZER_BASE);
Douglas Gregord73f3dd2011-11-01 01:16:03 +00005347 AddTypeSourceInfo(Init->getTypeSourceInfo(), Record);
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005348 Record.push_back(Init->isBaseVirtual());
Alexis Hunt37a477f2011-05-04 01:19:08 +00005349 } else if (Init->isDelegatingInitializer()) {
5350 Record.push_back(CTOR_INITIALIZER_DELEGATING);
Douglas Gregord73f3dd2011-11-01 01:16:03 +00005351 AddTypeSourceInfo(Init->getTypeSourceInfo(), Record);
Alexis Hunt37a477f2011-05-04 01:19:08 +00005352 } else if (Init->isMemberInitializer()){
5353 Record.push_back(CTOR_INITIALIZER_MEMBER);
5354 AddDeclRef(Init->getMember(), Record);
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005355 } else {
Alexis Hunt37a477f2011-05-04 01:19:08 +00005356 Record.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
5357 AddDeclRef(Init->getIndirectMember(), Record);
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005358 }
Francois Pichetd583da02010-12-04 09:14:42 +00005359
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005360 AddSourceLocation(Init->getMemberLocation(), Record);
5361 AddStmt(Init->getInit());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005362 AddSourceLocation(Init->getLParenLoc(), Record);
5363 AddSourceLocation(Init->getRParenLoc(), Record);
5364 Record.push_back(Init->isWritten());
5365 if (Init->isWritten()) {
5366 Record.push_back(Init->getSourceOrder());
5367 } else {
5368 Record.push_back(Init->getNumArrayIndices());
5369 for (unsigned i=0, e=Init->getNumArrayIndices(); i != e; ++i)
5370 AddDeclRef(Init->getArrayIndex(i), Record);
5371 }
5372 }
5373}
5374
Richard Smithc2bb8182015-03-24 06:36:48 +00005375void ASTWriter::FlushCXXCtorInitializers() {
5376 RecordData Record;
5377
5378 unsigned N = CXXCtorInitializersToWrite.size();
Daniel Jasperc77b0a12015-03-24 08:06:38 +00005379 (void)N; // Silence unused warning in non-assert builds.
Richard Smithc2bb8182015-03-24 06:36:48 +00005380 for (auto &Init : CXXCtorInitializersToWrite) {
5381 Record.clear();
5382
5383 // Record the offset of this mem-initializer list.
5384 unsigned Index = Init.ID - 1;
5385 if (Index == CXXCtorInitializersOffsets.size())
5386 CXXCtorInitializersOffsets.push_back(Stream.GetCurrentBitNo());
5387 else {
5388 if (Index > CXXCtorInitializersOffsets.size())
5389 CXXCtorInitializersOffsets.resize(Index + 1);
5390 CXXCtorInitializersOffsets[Index] = Stream.GetCurrentBitNo();
5391 }
5392
5393 AddCXXCtorInitializers(Init.Inits.data(), Init.Inits.size(), Record);
5394 Stream.EmitRecord(serialization::DECL_CXX_CTOR_INITIALIZERS, Record);
5395
5396 // Flush any expressions that were written as part of the initializers.
5397 FlushStmts();
5398 }
5399
5400 assert(N == CXXCtorInitializersToWrite.size() &&
5401 "added more ctor initializers while writing ctor initializers");
5402 CXXCtorInitializersToWrite.clear();
5403}
5404
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005405void ASTWriter::AddCXXDefinitionData(const CXXRecordDecl *D, RecordDataImpl &Record) {
Richard Smith053f6c62014-05-16 23:01:30 +00005406 auto &Data = D->data();
Douglas Gregor99ae8062012-02-14 17:54:36 +00005407 Record.push_back(Data.IsLambda);
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005408 Record.push_back(Data.UserDeclaredConstructor);
Richard Smith328aae52012-11-30 05:11:39 +00005409 Record.push_back(Data.UserDeclaredSpecialMembers);
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005410 Record.push_back(Data.Aggregate);
5411 Record.push_back(Data.PlainOldData);
5412 Record.push_back(Data.Empty);
5413 Record.push_back(Data.Polymorphic);
5414 Record.push_back(Data.Abstract);
Chandler Carruth583edf82011-04-30 10:07:30 +00005415 Record.push_back(Data.IsStandardLayout);
Chandler Carruthb1963742011-04-30 09:17:45 +00005416 Record.push_back(Data.HasNoNonEmptyBases);
5417 Record.push_back(Data.HasPrivateFields);
5418 Record.push_back(Data.HasProtectedFields);
5419 Record.push_back(Data.HasPublicFields);
Douglas Gregor61226d32011-05-13 01:05:07 +00005420 Record.push_back(Data.HasMutableFields);
Richard Smithab44d5b2013-12-10 08:25:00 +00005421 Record.push_back(Data.HasVariantMembers);
Richard Smith561fb152012-02-25 07:33:38 +00005422 Record.push_back(Data.HasOnlyCMembers);
Richard Smithe2648ba2012-05-07 01:07:30 +00005423 Record.push_back(Data.HasInClassInitializer);
Richard Smith593f9932012-12-08 02:01:17 +00005424 Record.push_back(Data.HasUninitializedReferenceMember);
Richard Smith6b02d462012-12-08 08:32:28 +00005425 Record.push_back(Data.NeedOverloadResolutionForMoveConstructor);
5426 Record.push_back(Data.NeedOverloadResolutionForMoveAssignment);
5427 Record.push_back(Data.NeedOverloadResolutionForDestructor);
5428 Record.push_back(Data.DefaultedMoveConstructorIsDeleted);
5429 Record.push_back(Data.DefaultedMoveAssignmentIsDeleted);
5430 Record.push_back(Data.DefaultedDestructorIsDeleted);
Richard Smith328aae52012-11-30 05:11:39 +00005431 Record.push_back(Data.HasTrivialSpecialMembers);
Richard Smithb45a6f72014-04-17 20:33:01 +00005432 Record.push_back(Data.DeclaredNonTrivialSpecialMembers);
Richard Smith328aae52012-11-30 05:11:39 +00005433 Record.push_back(Data.HasIrrelevantDestructor);
Richard Smith111af8d2011-08-10 18:11:37 +00005434 Record.push_back(Data.HasConstexprNonCopyMoveConstructor);
Richard Smith561fb152012-02-25 07:33:38 +00005435 Record.push_back(Data.DefaultedDefaultConstructorIsConstexpr);
Richard Smith561fb152012-02-25 07:33:38 +00005436 Record.push_back(Data.HasConstexprDefaultConstructor);
Chandler Carruthe71d0622011-04-24 02:49:34 +00005437 Record.push_back(Data.HasNonLiteralTypeFieldsOrBases);
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005438 Record.push_back(Data.ComputedVisibleConversions);
Alexis Huntea6f0322011-05-11 22:34:38 +00005439 Record.push_back(Data.UserProvidedDefaultConstructor);
Richard Smith328aae52012-11-30 05:11:39 +00005440 Record.push_back(Data.DeclaredSpecialMembers);
Richard Smith1c33fe82012-11-28 06:23:12 +00005441 Record.push_back(Data.ImplicitCopyConstructorHasConstParam);
5442 Record.push_back(Data.ImplicitCopyAssignmentHasConstParam);
5443 Record.push_back(Data.HasDeclaredCopyConstructorWithConstParam);
5444 Record.push_back(Data.HasDeclaredCopyAssignmentWithConstParam);
Richard Smith561fb152012-02-25 07:33:38 +00005445 // IsLambda bit is already saved.
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005446
5447 Record.push_back(Data.NumBases);
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005448 if (Data.NumBases > 0)
5449 AddCXXBaseSpecifiersRef(Data.getBases(), Data.getBases() + Data.NumBases,
5450 Record);
5451
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005452 // FIXME: Make VBases lazily computed when needed to avoid storing them.
5453 Record.push_back(Data.NumVBases);
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005454 if (Data.NumVBases > 0)
5455 AddCXXBaseSpecifiersRef(Data.getVBases(), Data.getVBases() + Data.NumVBases,
5456 Record);
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005457
Richard Smitha4ba74c2013-08-30 04:46:40 +00005458 AddUnresolvedSet(Data.Conversions.get(*Context), Record);
5459 AddUnresolvedSet(Data.VisibleConversions.get(*Context), Record);
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005460 // Data.Definition is the owning decl, no need to write it.
Richard Smith68ad0e72013-06-26 02:41:25 +00005461 AddDeclRef(D->getFirstFriend(), Record);
Douglas Gregor99ae8062012-02-14 17:54:36 +00005462
5463 // Add lambda-specific data.
5464 if (Data.IsLambda) {
Richard Smith053f6c62014-05-16 23:01:30 +00005465 auto &Lambda = D->getLambdaData();
Douglas Gregor680e9e02012-02-21 19:11:17 +00005466 Record.push_back(Lambda.Dependent);
Faisal Valic1a6dc42013-10-23 16:10:50 +00005467 Record.push_back(Lambda.IsGenericLambda);
5468 Record.push_back(Lambda.CaptureDefault);
Douglas Gregor99ae8062012-02-14 17:54:36 +00005469 Record.push_back(Lambda.NumCaptures);
5470 Record.push_back(Lambda.NumExplicitCaptures);
Douglas Gregor63798542012-02-20 19:44:39 +00005471 Record.push_back(Lambda.ManglingNumber);
Douglas Gregor7fcbd902012-02-21 00:37:24 +00005472 AddDeclRef(Lambda.ContextDecl, Record);
Eli Friedmand564afb2012-09-19 01:18:11 +00005473 AddTypeSourceInfo(Lambda.MethodTyInfo, Record);
Douglas Gregor99ae8062012-02-14 17:54:36 +00005474 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
Benjamin Kramerf3ca26982014-05-10 16:31:55 +00005475 const LambdaCapture &Capture = Lambda.Captures[I];
Douglas Gregor99ae8062012-02-14 17:54:36 +00005476 AddSourceLocation(Capture.getLocation(), Record);
5477 Record.push_back(Capture.isImplicit());
Richard Smithba71c082013-05-16 06:20:58 +00005478 Record.push_back(Capture.getCaptureKind());
5479 switch (Capture.getCaptureKind()) {
5480 case LCK_This:
Alexey Bataev39c81e22014-08-28 04:28:19 +00005481 case LCK_VLAType:
Richard Smithba71c082013-05-16 06:20:58 +00005482 break;
5483 case LCK_ByCopy:
Richard Smithbb13c9a2013-09-28 04:02:39 +00005484 case LCK_ByRef:
Richard Smithba71c082013-05-16 06:20:58 +00005485 VarDecl *Var =
Craig Toppera13603a2014-05-22 05:54:18 +00005486 Capture.capturesVariable() ? Capture.getCapturedVar() : nullptr;
Richard Smithba71c082013-05-16 06:20:58 +00005487 AddDeclRef(Var, Record);
5488 AddSourceLocation(Capture.isPackExpansion() ? Capture.getEllipsisLoc()
5489 : SourceLocation(),
5490 Record);
5491 break;
5492 }
Douglas Gregor99ae8062012-02-14 17:54:36 +00005493 }
5494 }
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005495}
5496
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005497void ASTWriter::ReaderInitialized(ASTReader *Reader) {
Sebastian Redl07a89a82010-07-30 00:29:29 +00005498 assert(Reader && "Cannot remove chain");
Douglas Gregordf0c1512011-08-18 04:12:04 +00005499 assert((!Chain || Chain == Reader) && "Cannot replace chain");
Sebastian Redl07a89a82010-07-30 00:29:29 +00005500 assert(FirstDeclID == NextDeclID &&
5501 FirstTypeID == NextTypeID &&
5502 FirstIdentID == NextIdentID &&
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005503 FirstMacroID == NextMacroID &&
Douglas Gregor253eefe2011-12-01 00:59:36 +00005504 FirstSubmoduleID == NextSubmoduleID &&
Sebastian Redld95a56e2010-08-04 18:21:41 +00005505 FirstSelectorID == NextSelectorID &&
Sebastian Redl07a89a82010-07-30 00:29:29 +00005506 "Setting chain after writing has started.");
Douglas Gregor925296b2011-07-19 16:10:42 +00005507
Sebastian Redl07a89a82010-07-30 00:29:29 +00005508 Chain = Reader;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005509
Richard Smith7f330cd2015-03-18 01:42:29 +00005510 // Note, this will get called multiple times, once one the reader starts up
5511 // and again each time it's done reading a PCH or module.
Douglas Gregordf0c1512011-08-18 04:12:04 +00005512 FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls();
5513 FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes();
5514 FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers();
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005515 FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros();
Douglas Gregor253eefe2011-12-01 00:59:36 +00005516 FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
Douglas Gregordf0c1512011-08-18 04:12:04 +00005517 FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005518 NextDeclID = FirstDeclID;
5519 NextTypeID = FirstTypeID;
5520 NextIdentID = FirstIdentID;
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005521 NextMacroID = FirstMacroID;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005522 NextSelectorID = FirstSelectorID;
Douglas Gregor253eefe2011-12-01 00:59:36 +00005523 NextSubmoduleID = FirstSubmoduleID;
Sebastian Redl07a89a82010-07-30 00:29:29 +00005524}
5525
Sebastian Redl539c5062010-08-18 23:57:32 +00005526void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005527 // Always keep the highest ID. See \p TypeRead() for more information.
5528 IdentID &StoredID = IdentifierIDs[II];
5529 if (ID > StoredID)
5530 StoredID = ID;
Sebastian Redlff4a2952010-07-23 23:49:55 +00005531}
5532
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005533void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) {
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005534 // Always keep the highest ID. See \p TypeRead() for more information.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005535 MacroID &StoredID = MacroIDs[MI];
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005536 if (ID > StoredID)
5537 StoredID = ID;
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005538}
5539
Argyrios Kyrtzidisbb5c7eae2010-08-20 16:03:59 +00005540void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
Douglas Gregor9b3932c2010-10-05 18:37:06 +00005541 // Always take the highest-numbered type index. This copes with an interesting
5542 // case for chained AST writing where we schedule writing the type and then,
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005543 // later, deserialize the type from another AST. In this case, we want to
Douglas Gregor9b3932c2010-10-05 18:37:06 +00005544 // keep the higher-numbered entry so that we can properly write it out to
5545 // the AST file.
5546 TypeIdx &StoredIdx = TypeIdxs[T];
5547 if (Idx.getIndex() >= StoredIdx.getIndex())
5548 StoredIdx = Idx;
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00005549}
5550
Sebastian Redl539c5062010-08-18 23:57:32 +00005551void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005552 // Always keep the highest ID. See \p TypeRead() for more information.
5553 SelectorID &StoredID = SelectorIDs[S];
5554 if (ID > StoredID)
5555 StoredID = ID;
Sebastian Redl834bb972010-08-04 17:20:04 +00005556}
Douglas Gregor91096292010-10-02 19:29:26 +00005557
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00005558void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
Douglas Gregor91096292010-10-02 19:29:26 +00005559 MacroDefinition *MD) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00005560 assert(MacroDefinitions.find(MD) == MacroDefinitions.end());
Douglas Gregor91096292010-10-02 19:29:26 +00005561 MacroDefinitions[MD] = ID;
5562}
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005563
Douglas Gregore37a85a2011-12-02 17:30:13 +00005564void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
5565 assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end());
5566 SubmoduleIDs[Mod] = ID;
5567}
5568
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005569void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
John McCallf937c022011-10-07 06:10:15 +00005570 assert(D->isCompleteDefinition());
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005571 assert(!WritingAST && "Already writing the AST!");
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005572 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
5573 // We are interested when a PCH decl is modified.
Douglas Gregorb3722e22011-09-09 23:01:35 +00005574 if (RD->isFromASTFile()) {
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005575 // A forward reference was mutated into a definition. Rewrite it.
5576 // FIXME: This happens during template instantiation, should we
5577 // have created a new definition decl instead ?
Richard Smithcd45dbc2014-04-19 03:48:30 +00005578 assert(isTemplateInstantiation(RD->getTemplateSpecializationKind()) &&
5579 "completed a tag from another module but not by instantiation?");
5580 DeclUpdates[RD].push_back(
5581 DeclUpdate(UPD_CXX_INSTANTIATED_CLASS_DEFINITION));
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005582 }
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005583 }
5584}
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005585
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00005586void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
5587 // TU and namespaces are handled elsewhere.
5588 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC))
5589 return;
5590
Douglas Gregorb3722e22011-09-09 23:01:35 +00005591 if (!(!D->isFromASTFile() && cast<Decl>(DC)->isFromASTFile()))
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00005592 return; // Not a source decl added to a DeclContext from PCH.
5593
Douglas Gregor9f782892013-01-21 15:25:38 +00005594 assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!");
Richard Smithe9a8bc32014-09-30 00:45:29 +00005595 assert(!WritingAST && "Already writing the AST!");
Chandler Carruth8a3d24d2015-03-26 04:27:10 +00005596 UpdatedDeclContexts.insert(DC);
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00005597 UpdatingVisibleDecls.push_back(D);
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00005598}
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005599
5600void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
5601 assert(D->isImplicit());
Douglas Gregorb3722e22011-09-09 23:01:35 +00005602 if (!(!D->isFromASTFile() && RD->isFromASTFile()))
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005603 return; // Not a source member added to a class from PCH.
5604 if (!isa<CXXMethodDecl>(D))
5605 return; // We are interested in lazily declared implicit methods.
5606
5607 // A decl coming from PCH was modified.
John McCallf937c022011-10-07 06:10:15 +00005608 assert(RD->isCompleteDefinition());
Richard Smithe9a8bc32014-09-30 00:45:29 +00005609 assert(!WritingAST && "Already writing the AST!");
Aaron Ballman4f45b712014-03-21 15:22:56 +00005610 DeclUpdates[RD].push_back(DeclUpdate(UPD_CXX_ADDED_IMPLICIT_MEMBER, D));
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005611}
Argyrios Kyrtzidis402dbbb2010-10-28 07:38:42 +00005612
5613void ASTWriter::AddedCXXTemplateSpecialization(const ClassTemplateDecl *TD,
5614 const ClassTemplateSpecializationDecl *D) {
Argyrios Kyrtzidisef80a012010-10-28 07:38:47 +00005615 // The specializations set is kept in the canonical template.
5616 TD = TD->getCanonicalDecl();
Douglas Gregorb3722e22011-09-09 23:01:35 +00005617 if (!(!D->isFromASTFile() && TD->isFromASTFile()))
Argyrios Kyrtzidis402dbbb2010-10-28 07:38:42 +00005618 return; // Not a source specialization added to a template from PCH.
5619
Richard Smithe9a8bc32014-09-30 00:45:29 +00005620 assert(!WritingAST && "Already writing the AST!");
Aaron Ballman4f45b712014-03-21 15:22:56 +00005621 DeclUpdates[TD].push_back(DeclUpdate(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION,
5622 D));
Argyrios Kyrtzidis402dbbb2010-10-28 07:38:42 +00005623}
Douglas Gregorf88e35b2010-11-30 06:16:57 +00005624
Larisse Voufo39a1e502013-08-06 01:03:05 +00005625void ASTWriter::AddedCXXTemplateSpecialization(
5626 const VarTemplateDecl *TD, const VarTemplateSpecializationDecl *D) {
5627 // The specializations set is kept in the canonical template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00005628 TD = TD->getCanonicalDecl();
5629 if (!(!D->isFromASTFile() && TD->isFromASTFile()))
5630 return; // Not a source specialization added to a template from PCH.
5631
Richard Smithe9a8bc32014-09-30 00:45:29 +00005632 assert(!WritingAST && "Already writing the AST!");
Aaron Ballman4f45b712014-03-21 15:22:56 +00005633 DeclUpdates[TD].push_back(DeclUpdate(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION,
5634 D));
Larisse Voufo39a1e502013-08-06 01:03:05 +00005635}
5636
Sebastian Redl9ab988f2011-04-14 14:07:59 +00005637void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
5638 const FunctionDecl *D) {
5639 // The specializations set is kept in the canonical template.
5640 TD = TD->getCanonicalDecl();
Douglas Gregorb3722e22011-09-09 23:01:35 +00005641 if (!(!D->isFromASTFile() && TD->isFromASTFile()))
Sebastian Redl9ab988f2011-04-14 14:07:59 +00005642 return; // Not a source specialization added to a template from PCH.
5643
Richard Smithe9a8bc32014-09-30 00:45:29 +00005644 assert(!WritingAST && "Already writing the AST!");
Aaron Ballman4f45b712014-03-21 15:22:56 +00005645 DeclUpdates[TD].push_back(DeclUpdate(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION,
5646 D));
Sebastian Redl9ab988f2011-04-14 14:07:59 +00005647}
5648
Richard Smith564417a2014-03-20 21:47:22 +00005649void ASTWriter::ResolvedExceptionSpec(const FunctionDecl *FD) {
Richard Smith9e2341d2015-03-23 03:25:59 +00005650 assert(!DoneWritingDeclsAndTypes && "Already done writing updates!");
5651 if (!Chain) return;
5652 Chain->forEachFormerlyCanonicalImportedDecl(FD, [&](const Decl *D) {
5653 // If we don't already know the exception specification for this redecl
5654 // chain, add an update record for it.
5655 if (isUnresolvedExceptionSpec(cast<FunctionDecl>(D)
5656 ->getType()
5657 ->castAs<FunctionProtoType>()
5658 ->getExceptionSpecType()))
5659 DeclUpdates[D].push_back(UPD_CXX_RESOLVED_EXCEPTION_SPEC);
5660 });
Richard Smith564417a2014-03-20 21:47:22 +00005661}
5662
Richard Smith1fa5d642013-05-11 05:45:24 +00005663void ASTWriter::DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) {
5664 assert(!WritingAST && "Already writing the AST!");
Richard Smith9e2341d2015-03-23 03:25:59 +00005665 if (!Chain) return;
5666 Chain->forEachFormerlyCanonicalImportedDecl(FD, [&](const Decl *D) {
5667 DeclUpdates[D].push_back(
5668 DeclUpdate(UPD_CXX_DEDUCED_RETURN_TYPE, ReturnType));
5669 });
Richard Smith1fa5d642013-05-11 05:45:24 +00005670}
5671
Richard Smithf8134002015-03-10 01:41:22 +00005672void ASTWriter::ResolvedOperatorDelete(const CXXDestructorDecl *DD,
5673 const FunctionDecl *Delete) {
5674 assert(!WritingAST && "Already writing the AST!");
5675 assert(Delete && "Not given an operator delete");
Richard Smith9e2341d2015-03-23 03:25:59 +00005676 if (!Chain) return;
5677 Chain->forEachFormerlyCanonicalImportedDecl(DD, [&](const Decl *D) {
5678 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_RESOLVED_DTOR_DELETE, Delete));
5679 });
Richard Smithf8134002015-03-10 01:41:22 +00005680}
5681
Sebastian Redlab238a72011-04-24 16:28:06 +00005682void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005683 assert(!WritingAST && "Already writing the AST!");
Douglas Gregorb3722e22011-09-09 23:01:35 +00005684 if (!D->isFromASTFile())
Sebastian Redlab238a72011-04-24 16:28:06 +00005685 return; // Declaration not imported from PCH.
5686
Richard Smith4d235792014-08-07 18:53:08 +00005687 // Implicit function decl from a PCH was defined.
5688 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
Sebastian Redlab238a72011-04-24 16:28:06 +00005689}
5690
Richard Smithd28ac5b2014-03-22 23:33:22 +00005691void ASTWriter::FunctionDefinitionInstantiated(const FunctionDecl *D) {
5692 assert(!WritingAST && "Already writing the AST!");
5693 if (!D->isFromASTFile())
5694 return;
5695
Richard Smith9e2341d2015-03-23 03:25:59 +00005696 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
Richard Smithd28ac5b2014-03-22 23:33:22 +00005697}
5698
Sebastian Redl2ac2c722011-04-29 08:19:30 +00005699void ASTWriter::StaticDataMemberInstantiated(const VarDecl *D) {
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005700 assert(!WritingAST && "Already writing the AST!");
Douglas Gregorb3722e22011-09-09 23:01:35 +00005701 if (!D->isFromASTFile())
Sebastian Redl2ac2c722011-04-29 08:19:30 +00005702 return;
5703
5704 // Since the actual instantiation is delayed, this really means that we need
5705 // to update the instantiation location.
Richard Smith6ef42932014-03-20 21:02:00 +00005706 DeclUpdates[D].push_back(
Aaron Ballman4f45b712014-03-21 15:22:56 +00005707 DeclUpdate(UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER,
5708 D->getMemberSpecializationInfo()->getPointOfInstantiation()));
Sebastian Redl2ac2c722011-04-29 08:19:30 +00005709}
5710
Argyrios Kyrtzidis7d847c92011-09-01 00:58:55 +00005711void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
5712 const ObjCInterfaceDecl *IFD) {
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005713 assert(!WritingAST && "Already writing the AST!");
Douglas Gregorb3722e22011-09-09 23:01:35 +00005714 if (!IFD->isFromASTFile())
Argyrios Kyrtzidis7d847c92011-09-01 00:58:55 +00005715 return; // Declaration not imported from PCH.
Douglas Gregor404cdde2012-01-27 01:47:08 +00005716
5717 assert(IFD->getDefinition() && "Category on a class without a definition?");
5718 ObjCClassesWithCategories.insert(
5719 const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
Argyrios Kyrtzidis7d847c92011-09-01 00:58:55 +00005720}
Argyrios Kyrtzidisb97a4022011-11-12 21:07:46 +00005721
Argyrios Kyrtzidis0ca3a8b2011-11-12 21:07:52 +00005722
Argyrios Kyrtzidis846e61a2011-11-14 04:52:29 +00005723void ASTWriter::AddedObjCPropertyInClassExtension(const ObjCPropertyDecl *Prop,
5724 const ObjCPropertyDecl *OrigProp,
5725 const ObjCCategoryDecl *ClassExt) {
5726 const ObjCInterfaceDecl *D = ClassExt->getClassInterface();
5727 if (!D)
5728 return;
5729
5730 assert(!WritingAST && "Already writing the AST!");
5731 if (!D->isFromASTFile())
5732 return; // Declaration not imported from PCH.
5733
5734 RewriteDecl(D);
5735}
Eli Friedman276dd182013-09-05 00:02:25 +00005736
5737void ASTWriter::DeclarationMarkedUsed(const Decl *D) {
5738 assert(!WritingAST && "Already writing the AST!");
5739 if (!D->isFromASTFile())
5740 return;
5741
Aaron Ballman4f45b712014-03-21 15:22:56 +00005742 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_USED));
Eli Friedman276dd182013-09-05 00:02:25 +00005743}
Alexey Bataev97720002014-11-11 04:05:39 +00005744
5745void ASTWriter::DeclarationMarkedOpenMPThreadPrivate(const Decl *D) {
5746 assert(!WritingAST && "Already writing the AST!");
5747 if (!D->isFromASTFile())
5748 return;
5749
5750 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_THREADPRIVATE));
5751}
Richard Smith65ebb4a2015-03-26 04:09:53 +00005752
5753void ASTWriter::RedefinedHiddenDefinition(const NamedDecl *D,
5754 SourceLocation Loc) {
5755 assert(!WritingAST && "Already writing the AST!");
5756 assert(D->isHidden() && "expected a hidden declaration");
5757 assert(D->isFromASTFile() && "hidden decl not from AST file");
5758 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_EXPORTED, Loc));
5759}